feat(plugins): honor harness login driver preferences (#23425)

## Thinking Path

> - People use Paperclip to manage agents and the accounts they use.
> - A harness can sign in on an environment supplied by a plugin.
> - Some plugins offer several environments with different login
requirements.
> - Today the task environment also determines where sign-in runs.
> - This change lets the plugin declare its preferred login drivers.
> - A company can use a temporary environment for sign-in and keep
running tasks on its chosen computer.

## Linked Issues or Issue Description

**Subsystem affected**

Plugin manifests, login target selection, and the harness sign-in UI.

**Current behavior**

A plugin with several environments cannot direct sign-in to a preferred
driver. Selecting an agent computer for tasks can require an agent even
when a temporary environment is available for login.

**Proposed behavior**

Allow the manifest to declare an ordered list of login drivers. Select
the first eligible environment for the company and harness before
starting a login.

**Reason and benefit**

A plugin can offer agentless sign-in first and keep an agent-targeted
computer as a fallback. The choice applies only to sign-in.

**Additional context**

This builds on the agentless login capability in #23392.

## What Changed

- Validate ordered login driver keys in the manifest and expose the
eligible environments to the company.
- Use the same selection rule for device login, setup-token login,
onboarding, agent configuration, and AI Connections.
- Bind the session and lease to the selected environment. Existing agent
eligibility checks apply when the target needs an agent.

## Verification

- Server and UI typechecks passed. Focused Vitest runs covered shared
manifest validation, driver order, the company access boundary, lease
checks, both HTTP login flows, and the UI helpers.
- The public SDK source input registry was regenerated. The registry
change requires broad CI coverage under `pnpm verify`.
- Regression tests cover skipping an environment without an eligible
computer, using a newly prepared draft computer, and holding the
selected host across capability and readiness updates during sign-in.
The UI typecheck and all 16 focused login tests passed on the final
commit.
- No external provider credentials were used.

## Risks

A plugin that opts in must declare at least one usable driver for the
user's harness and company. If none qualifies, the start fails before
acquisition. Manifests that omit the field keep their existing routing.
There is no database migration.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex (GPT-6), with local code inspection, TypeScript checks, and
test execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-12-01 16:58:28 -08:00
1 parent f0ee1b40f0
commit 550d8fc576
21 files changed
+475 -146

No files matched your search

+10
View File
@@ -644,6 +644,16 @@ declare `supportsAgentlessLogin: true`. Core can then acquire a
connection. The driver scopes the login and its cleanup to that allocation.
`requiresAgent` continues to govern ordinary agent provisioning.
A plugin can set an ordered `loginDriverPreference` array on its manifest.
Use distinct keys of its own login-capable environment drivers. Starting a login
on that plugin selects an active environment available to the company whose
running driver supports the harness. Within one driver the requested environment
wins, then environment ID breaks ties. Agentless drivers use no agent disk.
Core skips computer targets without an eligible agent for the caller. An empty
selection fails before login starts. Lease acquisition, credential readback,
and cleanup use the selected environment; a provider failure never starts a
second login. Task and workspace routing continue to use the task environment.
## Login allocations on an existing computer
A login-capable environment driver can host authorization on a saved agent's
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import {
adapterSupportsRemoteManagedEnvironments,
preferredLoginEnvironmentId,
pluginLoginChoices,
environmentLoginRequiresAgent,
environmentSupportsLoginPty,
getEnvironmentCapabilities,
@@ -132,3 +134,35 @@ it("offers the declared adapters for a plugin login that needs no agent", () =>
expect(environmentSupportsLoginPty(environment, capabilities, "codex_local")).toBe(true);
expect(environmentSupportsLoginPty(environment, capabilities, "claude_local")).toBe(false);
});
it("chooses a login environment by plugin, adapter and driver order, preserving a same-driver choice", () => {
const env = { id: "b", driver: "plugin", config: {}, pluginDriver: { pluginKey: "example", driverKey: "temporary" } };
const target = (environmentId: string, driverKey: string) => ({ environmentId, driverKey, loginAdapters: ["codex_local"] });
const targets = { example: [target("a", "temporary"), target("b", "temporary"), target("c", "computer")] };
expect(preferredLoginEnvironmentId(env, "codex_local", targets)).toBe("b");
expect(preferredLoginEnvironmentId({ ...env, id: "c" }, "codex_local", targets)).toBe("a");
expect(preferredLoginEnvironmentId(env, "claude_local", targets)).toBeNull();
expect(preferredLoginEnvironmentId(env, "codex_local", {})).toBe("b");
});
it("indexes the first usable driver for automatic or direct computer login in one catalog pass", () => {
let adapterReads = 0;
const targets = Array.from({ length: 2000 }, (_, i) => ({
environmentId: String(i), driverKey: i < 1000 ? "computers" : "sandboxes",
...(i < 1000 ? { automaticComputerAvailable: false } : {}),
get loginAdapters() { adapterReads++; return ["claude_local"]; },
}));
const automatic = pluginLoginChoices(targets, "claude_local");
expect(automatic.size).toBe(1000);
expect(automatic.has("1000")).toBe(true);
expect(adapterReads).toBeLessThanOrEqual(targets.length);
expect([...pluginLoginChoices(targets, "claude_local", { ownEnvironmentId: "47", allowAutomatic: false })]).toEqual(["47"]);
expect(pluginLoginChoices(targets, "claude_local", { allowAutomatic: false })).toEqual(automatic);
});
it("offers a newly prepared draft computer even when the company capability snapshot predates its hire", () => {
const draft = { id: "draft-env", driver: "plugin", config: { pluginKey: "example" } };
const targets = { example: [{ environmentId: draft.id, driverKey: "computers", automaticComputerAvailable: false, loginAdapters: ["codex_local"] }] };
expect(preferredLoginEnvironmentId(draft, "codex_local", targets)).toBeNull();
expect(preferredLoginEnvironmentId(draft, "codex_local", targets, { ownEnvironmentId: draft.id })).toBe(draft.id);
});
+48 -5
View File
@@ -1,5 +1,6 @@
import { adapterLoginCommandKey } from "./adapter-login.js";
import type { AgentAdapterType, EnvironmentDriver } from "./constants.js";
import type { SandboxEnvironmentProvider } from "./types/environment.js";
import type { Environment, SandboxEnvironmentProvider } from "./types/environment.js";
import type {
JsonSchema,
PluginEnvironmentTemplateConfigBinding,
@@ -58,7 +59,17 @@ export interface EnvironmentProviderCapability {
configSchema?: JsonSchema;
}
export interface PluginLoginTarget {
environmentId: string;
/** Present only for computer targets. Direct sign-in can instead use the agent's own environment. */
automaticComputerAvailable?: boolean;
driverKey: string;
loginAdapters: string[];
}
export interface EnvironmentCapabilities {
/** Company-visible login environments in manifest preference order, keyed by plugin. */
pluginLoginTargets?: Record<string, PluginLoginTarget[]>;
/** Namespaced plugin driver keys that can host a login on a saved agent. */
loginPtyDrivers?: Record<string, { supportsLoginPty: boolean; supportsAgentlessLogin?: boolean; loginAdapters: string[] }>;
adapters: AdapterEnvironmentSupport[];
@@ -203,18 +214,50 @@ export function getEnvironmentCapabilities(
};
}
export function environmentLoginRequiresAgent(environment: { driver: string; config?: Record<string, unknown> | null } | null | undefined, capabilities?: EnvironmentCapabilities | null): boolean {
type LoginComputerChoice = { ownEnvironmentId?: string | null; allowAutomatic?: boolean };
/** Eligible environments of the first usable driver, indexed for environment pickers. */
export function pluginLoginChoices(targets: PluginLoginTarget[], adapter: string, computer?: LoginComputerChoice): Set<string> {
const choices = new Set<string>();
let driver: string | undefined;
for (const target of targets) {
if (driver && target.driverKey !== driver) break;
if (!target.loginAdapters.includes(adapter)) continue;
if (target.automaticComputerAvailable !== undefined &&
target.environmentId !== computer?.ownEnvironmentId && (computer?.allowAutomatic === false || !target.automaticComputerAvailable)) continue;
driver = target.driverKey;
choices.add(target.environmentId);
}
return choices;
}
/** Resolve only the login transport. Keep the selected environment on ties within one driver. */
export function preferredLoginEnvironmentId(
environment: { id: string; driver: string; config: Record<string, unknown> } & Pick<Environment, "pluginDriver"> | null | undefined,
adapter: string, preferences?: EnvironmentCapabilities["pluginLoginTargets"], computer?: LoginComputerChoice,
): string | null {
if (!environment) return null;
if (environment.driver !== "plugin" || !adapterLoginCommandKey(adapter)) return environment.id;
const key = (environment.pluginDriver ?? environment.config)?.pluginKey;
const targets = typeof key === "string" ? preferences?.[key] : undefined;
if (!Array.isArray(targets)) return environment.id;
const choices = pluginLoginChoices(targets, adapter, computer);
return choices.has(environment.id) ? environment.id : choices.values().next().value ?? null;
}
export function environmentLoginRequiresAgent(environment: { driver: string; config?: Record<string, unknown> | null; pluginDriver?: Environment["pluginDriver"] } | null | undefined, capabilities?: EnvironmentCapabilities | null): boolean {
if (environment?.driver !== "plugin") return false;
const config = environment.config;
const config = environment.pluginDriver ?? environment.config;
return capabilities?.loginPtyDrivers?.[`${config?.pluginKey}:${config?.driverKey}`]?.supportsAgentlessLogin !== true;
}
/** Shared presentation rule for both temporary sandboxes and existing computers. */
export function environmentSupportsLoginPty(environment: { driver: string; config: Record<string, unknown> } | null | undefined, capabilities: EnvironmentCapabilities | null | undefined, adapterType?: string): boolean {
export function environmentSupportsLoginPty(environment: { driver: string; config: Record<string, unknown>; pluginDriver?: Environment["pluginDriver"] } | null | undefined, capabilities: EnvironmentCapabilities | null | undefined, adapterType?: string): boolean {
if (!environment || !capabilities) return false;
if (environment.driver === "sandbox") return typeof environment.config.provider === "string" && capabilities.sandboxProviders[environment.config.provider]?.supportsLoginPty === true;
if (environment.driver === "plugin") {
const driver = capabilities.loginPtyDrivers?.[`${environment.config.pluginKey}:${environment.config.driverKey}`];
const config = environment.pluginDriver ?? environment.config;
const driver = capabilities.loginPtyDrivers?.[`${config.pluginKey}:${config.driverKey}`];
return driver?.supportsLoginPty === true
&& (adapterType === undefined ? driver.loginAdapters.length > 0 : driver.loginAdapters.includes(adapterType));
}
+3
View File
@@ -2857,6 +2857,9 @@ export {
getEnvironmentCapabilities,
environmentSupportsLoginPty,
environmentLoginRequiresAgent,
preferredLoginEnvironmentId,
pluginLoginChoices,
type PluginLoginTarget,
getAdapterEnvironmentSupport,
isEnvironmentDriverSupportedForAdapter,
isSandboxProviderSupportedForAdapter,
+2
View File
@@ -772,6 +772,8 @@ export interface PaperclipPluginManifestV1 {
apiRoutes?: PluginApiRouteDeclaration[];
/** Environment drivers this plugin contributes. Requires `environment.drivers.register` capability. */
environmentDrivers?: PluginEnvironmentDriverDeclaration[];
/** Ordered environment drivers for new harness logins started on this plugin. */
loginDriverPreference?: string[];
/** Suggested company-scoped agents this plugin can provision and resolve by stable key. */
agents?: PluginManagedAgentDeclaration[];
/** Suggested company-scoped projects this plugin can provision and resolve by stable key. */
@@ -26,6 +26,16 @@ function buildSandboxProviderManifest(driver: Record<string, unknown>) {
};
}
it("validates ordered login drivers against the same manifest", () => {
const manifest = buildSandboxProviderManifest({ kind: "environment_driver", supportsTasks: true, supportsLoginPty: true, creationOperationVersion: 1 });
const key = manifest.environmentDrivers[0]!.driverKey;
expect(pluginManifestV1Schema.safeParse({ ...manifest, loginDriverPreference: [key] }).success).toBe(true);
for (const preference of [[], [key, key], ["undeclared"]]) {
expect(pluginManifestV1Schema.safeParse({ ...manifest, loginDriverPreference: preference }).success).toBe(false);
}
expect(pluginManifestV1Schema.safeParse({ ...buildSandboxProviderManifest({}), loginDriverPreference: [key] }).success).toBe(false);
});
describe("plugin capability constants", () => {
it("exposes each capability once", () => {
expect(new Set(PLUGIN_CAPABILITIES).size).toBe(PLUGIN_CAPABILITIES.length);
+9
View File
@@ -849,6 +849,7 @@ export const pluginManifestV1Schema = z.object({
database: pluginDatabaseDeclarationSchema.optional(),
apiRoutes: z.array(pluginApiRouteDeclarationSchema).optional(),
environmentDrivers: z.array(pluginEnvironmentDriverDeclarationSchema).optional(),
loginDriverPreference: z.array(z.string()).min(1).max(64).optional(),
agents: z.array(pluginManagedAgentDeclarationSchema).optional(),
projects: z.array(pluginManagedProjectDeclarationSchema).optional(),
routines: z.array(pluginManagedRoutineDeclarationSchema).optional(),
@@ -1203,6 +1204,14 @@ export const pluginManifestV1Schema = z.object({
}
}
if (manifest.loginDriverPreference) {
const keys = new Set(manifest.environmentDrivers?.filter(driver => driver.kind === "environment_driver" && driver.supportsLoginPty).map(driver => driver.driverKey));
if (new Set(manifest.loginDriverPreference).size !== manifest.loginDriverPreference.length ||
manifest.loginDriverPreference.some(key => !keys.has(key))) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["loginDriverPreference"], message: "Login preferences must name distinct login-capable environment drivers declared by this plugin" });
}
}
// environment driver keys must be unique within the plugin
if (manifest.environmentDrivers) {
const driverKeys = manifest.environmentDrivers.map((d) => d.driverKey);
@@ -1,7 +1,7 @@
import type { Request, Response } from "express";
import type { z } from "zod";
type LoginTarget = { agentId: string | undefined; environment: { driver: string } };
type LoginTarget = { agentId: string | undefined; environment: { id: string; driver: string } };
/**
* The result of the shared adapter login start-route spine. The spine returns it
+9 -7
View File
@@ -1581,8 +1581,9 @@ export function agentRoutes(
companyId: string,
environmentId: string,
options: { requireSetupTokenLoginProvider?: boolean; agentId?: string; adapterType?: string; selectComputer?: boolean },
start?: { workerManager?: PluginWorkerManager },
) {
const target = await resolveLoginEnvironmentTarget(db, { companyId, environmentId, ...options });
const target = await resolveLoginEnvironmentTarget(db, { companyId, environmentId, ...options }, start);
// Gate the Claude setup-token login on the provider capability. Only a
// sandbox provider that advertises the setup-token login capability
// implements the setup-token pseudo-terminal methods. The setup-token start
@@ -1591,7 +1592,7 @@ export function agentRoutes(
// reconciliation that rebinds the environment to an unsupported provider
// still fails closed before the lease and the pseudo-terminal.
if (options.requireSetupTokenLoginProvider) {
await assertSetupTokenLoginProviderCapability(environmentId);
await assertSetupTokenLoginProviderCapability(target.environment.id);
}
return target;
}
@@ -3824,8 +3825,8 @@ export function agentRoutes(
// runtime state before the provider lease.
const target = await resolveSandboxLoginTarget(companyId, data.environmentId, {
agentId: data.agentId, adapterType: data.adapterType, selectComputer: Boolean(data.aiConnection),
});
await assertDeviceLoginProviderCapability(data.environmentId, data.adapterType);
}, { workerManager: options.pluginWorkerManager });
await assertDeviceLoginProviderCapability(target.environment.id, data.adapterType);
return target;
},
});
@@ -3842,7 +3843,7 @@ export function agentRoutes(
try {
result = await adapterLoginService.start({
companyId,
environmentId: data.environmentId,
environmentId: target.environment.id,
agentId: target.agentId,
environmentDriver: target.environment.driver,
adapterType: type,
@@ -7059,11 +7060,12 @@ export function agentRoutes(
agentId: data.agentId,
adapterType: data.adapterType,
selectComputer: Boolean(data.aiConnection),
}),
}, { workerManager: options.pluginWorkerManager }),
});
if (!resolved) return;
const { ownerUserId, data, target } = resolved;
const { environmentId, adapterType } = data;
const { adapterType } = data;
const environmentId = target.environment.id;
if (req.actor.type === "agent" && !data.aiConnection) throw forbidden("Agent logins must save a managed AI account");
if (data.aiConnection) {
await assertAiConnectionCreateAccess(db, req, companyId, data.aiConnection);
+12 -5
View File
@@ -60,6 +60,7 @@ import {
assertAgentsReadyForEnvironmentChange,
} from "../services/plugin-environment-driver.js";
import { getConfiguredSecretProvider } from "../secrets/configured-provider.js";
import { listPluginLoginTargets } from "../services/login-environment.js";
import { assertBoard, assertBoardOrgAccess, boardAccessRequired, getActorInfo } from "./authz.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { environmentService } from "../services/environments.js";
@@ -401,7 +402,7 @@ export function environmentRoutes(
assertBoardOrgAccess(req);
}
function assertCustomImageCompanyAccess(req: Request, companyId: string) {
function assertEnvironmentCompanyAccess(req: Request, companyId: string) {
assertBoard(req);
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
const allowedCompanies = req.actor.companyIds ?? [];
@@ -522,7 +523,7 @@ export function environmentRoutes(
? req.query.companyId.trim()
: null;
if (queryCompanyId) {
assertCustomImageCompanyAccess(req, queryCompanyId);
assertEnvironmentCompanyAccess(req, queryCompanyId);
return queryCompanyId;
}
if (req.actor.type === "board" && req.actor.companyIds?.length === 1) {
@@ -531,7 +532,7 @@ export function environmentRoutes(
const companyIds = await instanceSettings.listCompanyIds();
if (companyIds.length === 1 && companyIds[0]) {
const companyId = companyIds[0];
assertCustomImageCompanyAccess(req, companyId);
assertEnvironmentCompanyAccess(req, companyId);
return companyId;
}
throw unprocessable("companyId query parameter is required for environment customImage setup.");
@@ -543,7 +544,7 @@ export function environmentRoutes(
): Promise<string> {
const metadataCompanyId = readCustomImageSetupSessionCompanyId(session);
if (metadataCompanyId) {
assertCustomImageCompanyAccess(req, metadataCompanyId);
assertEnvironmentCompanyAccess(req, metadataCompanyId);
return metadataCompanyId;
}
return await resolveCustomImageCompanyId(req);
@@ -820,7 +821,13 @@ export function environmentRoutes(
])),
},
);
res.json({ ...capabilities, loginPtyDrivers: Object.fromEntries(loginDrivers.map(driver => [
let pluginLoginTargets;
if (loginDrivers.some(driver => driver.loginDriverPreference)) {
const companyId = req.params.companyId as string;
assertEnvironmentCompanyAccess(req, companyId);
pluginLoginTargets = await listPluginLoginTargets(db, companyId, loginDrivers);
}
res.json({ ...capabilities, ...(pluginLoginTargets && { pluginLoginTargets }), loginPtyDrivers: Object.fromEntries(loginDrivers.map(driver => [
`${driver.pluginKey}:${driver.driverKey}`, {
supportsLoginPty: driver.supportsLoginPty === true,
loginAdapters: driver.loginAdapters,
+44 -3
View File
@@ -3,15 +3,21 @@ import { eq } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, companies, createDb, environmentLeases, environments, type Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { assertLoginEnvironmentTarget, resolveLoginEnvironmentTarget } from "./login-environment.js";
const fixtures = vi.hoisted(() => ({ environment: { id: "environment", driver: "plugin" }, instanceDefault: "environment", companies: ["company"], agent: { id: "agent", companyId: "company", adapterType: "paperclip_runner", lifecycleState: "verifying", defaultEnvironmentId: "environment" } as Record<string, unknown> | undefined }));
vi.mock("./environments.js", () => ({ environmentService: () => ({ getById: async () => fixtures.environment, listBoundCompanyIds: async () => fixtures.companies }) }));
const { list, getById, listBoundCompanyIds } = vi.hoisted(() => ({ list: vi.fn(), getById: vi.fn(), listBoundCompanyIds: vi.fn() }));
vi.mock("./environments.js", () => ({ environmentService: () => ({ list, getById, listBoundCompanyIds }) }));
vi.mock("./instance-settings.js", () => ({ instanceSettingsService: () => ({ get: async () => ({ defaultEnvironmentId: fixtures.instanceDefault }) }) }));
vi.mock("./environment-selection.js", () => ({ assertEnvironmentSelectionForCompany: vi.fn(async () => {}) }));
const { getByKey } = vi.hoisted(() => ({ getByKey: vi.fn() }));
vi.mock("./plugin-registry.js", () => ({ pluginRegistryService: () => ({ getByKey }) }));
const db = { select: () => ({ from: () => ({ where: () => ({ limit: async () => fixtures.agent ? [fixtures.agent] : [] }) }) }) } as unknown as Db;
beforeEach(() => { fixtures.instanceDefault = "environment"; fixtures.environment = { id: "environment", driver: "plugin" }; fixtures.companies = ["company"]; fixtures.agent = { id: "agent", companyId: "company", adapterType: "paperclip_runner", lifecycleState: "verifying", defaultEnvironmentId: "environment" }; });
const db = { selectDistinctOn: () => ({ from: () => ({ where: () => ({ orderBy: async () => [] }) }) }), select: () => ({ from: () => ({ where: () => ({ limit: async () => fixtures.agent ? [fixtures.agent] : [], orderBy: async () => [] }) }) }) } as unknown as Db;
beforeEach(() => {
getById.mockImplementation(async () => fixtures.environment);
listBoundCompanyIds.mockImplementation(async () => fixtures.companies);
getByKey.mockReset();
fixtures.instanceDefault = "environment"; fixtures.environment = { id: "environment", driver: "plugin" }; fixtures.companies = ["company"]; fixtures.agent = { id: "agent", companyId: "company", adapterType: "paperclip_runner", lifecycleState: "verifying", defaultEnvironmentId: "environment" }; });
describe("login environment transport target", () => {
it("acquires an opted-in plugin login without selecting an agent", async () => {
Object.assign(fixtures.environment, { config: { pluginKey: "computers", driverKey: "temporary" } });
@@ -25,6 +31,41 @@ describe("login environment transport target", () => {
Object.assign(fixtures.environment, { config: { pluginKey: "computers", driverKey: "persistent" } });
await expect(assertLoginEnvironmentTarget(db, input)).rejects.toMatchObject({ status: 400 });
});
it("selects the first company-visible login driver and pins the lease check to that environment", async () => {
const keys = ["first", "second", "computer"];
const rows = keys.map(key => ({ id: key, status: "active", driver: "plugin", config: { pluginKey: "example", driverKey: key } }));
const methods = ["environmentAcquireLease", "environmentInspectLease", "environmentReleaseLease", "loginPtyOpen",
"loginPtyInput", "loginPtyStop", "loginPtyClose", "loginPtyReadCredential"];
const start = { workerManager: { isRunning: () => true, getWorker: () => ({ supportedMethods: methods }) } as unknown as PluginWorkerManager };
getByKey.mockResolvedValue({ id: "plugin", pluginKey: "example", status: "ready", manifestJson: {
loginDriverPreference: keys, environmentDrivers: keys.map(driverKey => ({
driverKey, kind: "environment_driver", creationOperationVersion: 1, supportsLoginPty: true, supportsAgentlessLogin: driverKey !== "computer",
})),
} });
list.mockResolvedValue([...rows].reverse());
getById.mockImplementation(async id => rows.find(row => row.id === id));
fixtures.agent!.defaultEnvironmentId = "computer";
const request = { companyId: "company", environmentId: "computer", agentId: "agent", adapterType: "codex_local" };
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toMatchObject({ environment: rows[0], agentId: undefined });
expect(list).toHaveBeenCalledWith({ driver: "plugin", status: "active" });
listBoundCompanyIds.mockImplementation(async id => id === "first" ? ["another-company"] : []);
const second = await resolveLoginEnvironmentTarget(db, request, start);
expect(second).toEqual({ environment: rows[1], agentId: undefined });
listBoundCompanyIds.mockResolvedValue([]);
await expect(assertLoginEnvironmentTarget(db, { ...request, environmentId: second.environment.id, agentId: undefined })).resolves.toEqual(rows[1]);
list.mockResolvedValue([rows[2]]);
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toMatchObject({ environment: rows[2], agentId: "agent" });
await expect(resolveLoginEnvironmentTarget(db, { ...request, agentId: undefined }, start)).rejects.toMatchObject({ status: 400 });
list.mockResolvedValue([...rows]);
keys.unshift(keys.pop()!);
await expect(resolveLoginEnvironmentTarget(db, { ...request, agentId: undefined, selectComputer: true }, start))
.resolves.toEqual({ environment: rows[0], agentId: undefined });
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toEqual({ environment: rows[2], agentId: "agent" });
fixtures.agent!.lifecycleState = "preparing";
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toEqual({ environment: rows[0], agentId: undefined });
methods.pop();
await expect(resolveLoginEnvironmentTarget(db, request, start)).rejects.toMatchObject({ status: 400 });
});
it("permits a verifying saved agent on its own computer", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).resolves.toEqual(fixtures.environment); });
it("leaves which adapters a computer signs in to its driver's declared support", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent", adapterType: "grok_local" })).resolves.toEqual(fixtures.environment); });
it("rejects an adapter that has no Paperclip sign-in", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent", adapterType: "copilot_runtime" })).rejects.toMatchObject({ status: 400 }); });
+116 -39
View File
@@ -1,11 +1,53 @@
import { agents, environmentLeases, type Db } from "@paperclipai/db";
import { adapterLoginCommandKey } from "@paperclipai/shared";
import { and, asc, eq, isNull, notExists, notInArray, or, sql } from "drizzle-orm";
import { adapterLoginCommandKey, type PluginLoginTarget } from "@paperclipai/shared";
import { and, asc, eq, notExists, notInArray, or, sql } from "drizzle-orm";
import { badRequest, forbidden, notFound } from "../errors.js";
import { assertEnvironmentSelectionForCompany } from "./environment-selection.js";
import { environmentService } from "./environments.js";
import { pluginRegistryService } from "./plugin-registry.js";
import { instanceSettingsService } from "./instance-settings.js";
import { pluginDriverLoginAdapters, type ReadyPluginEnvironmentDriver } from "./plugin-environment-driver.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
type LoginDriver = Pick<ReadyPluginEnvironmentDriver, "pluginKey" | "driverKey" | "loginAdapters" | "loginDriverPreference" | "supportsAgentlessLogin">;
/** The same company-scoped catalog is used to present and to start a login. */
export async function listPluginLoginTargets(db: Db, companyId: string, drivers: LoginDriver[], includeComputerAvailability = true) {
const preferences = new Map(drivers.flatMap(driver =>
driver.loginDriverPreference ? [[driver.pluginKey, driver.loginDriverPreference] as const] : []));
if (!preferences.size) return {};
const environments = environmentService(db);
const rows = await environments.list({ status: "active", driver: "plugin" });
rows.sort((a, b) => a.id.localeCompare(b.id));
const visible = await Promise.all(rows.filter(row => {
const { pluginKey, driverKey } = row.config;
return typeof pluginKey === "string" && typeof driverKey === "string" && preferences.get(pluginKey)?.includes(driverKey);
}).map(async row => {
const companies = await environments.listBoundCompanyIds(row.id);
return !companies.length || companies.includes(companyId) ? row : null;
}));
const targets: Record<string, PluginLoginTarget[]> = Object.create(null);
let computers: Awaited<ReturnType<typeof availableLoginComputers>> | undefined;
for (const [pluginKey, preference] of preferences) {
const ordered: PluginLoginTarget[] = [];
for (const driverKey of preference) {
const driver = drivers.find(item => item.pluginKey === pluginKey && item.driverKey === driverKey);
if (!driver?.loginAdapters.length) continue;
for (const row of visible) {
if (row && row.config.pluginKey === pluginKey && row.config.driverKey === driverKey) {
const target: PluginLoginTarget = { environmentId: row.id, driverKey, loginAdapters: driver.loginAdapters };
if (!driver.supportsAgentlessLogin && includeComputerAvailability) {
computers ??= await availableLoginComputers(db, companyId);
target.automaticComputerAvailable = computers.has(row.id);
}
ordered.push(target);
}
}
}
targets[pluginKey] = ordered;
}
return targets;
}
type LoginEnvironmentTarget = { companyId: string; environmentId: string; agentId?: string; adapterType?: string };
@@ -17,6 +59,7 @@ export async function assertLoginEnvironmentTarget(db: Db, input: LoginEnvironme
export async function resolveLoginEnvironmentTarget(
db: Db,
input: LoginEnvironmentTarget & { selectComputer?: boolean },
start?: { workerManager?: PluginWorkerManager },
) {
const environments = environmentService(db);
await assertEnvironmentSelectionForCompany(environments, input.companyId, input.environmentId, {
@@ -31,45 +74,79 @@ export async function resolveLoginEnvironmentTarget(
return { environment, agentId: undefined };
}
if (input.adapterType && !adapterLoginCommandKey(input.adapterType)) throw badRequest("This provider login is not supported on agent computers.", { code: "login_adapter_unsupported" });
if (!input.agentId) {
const config = environment.config;
if (typeof config?.pluginKey === "string" && typeof config.driverKey === "string") {
const plugin = await pluginRegistryService(db).getByKey(config.pluginKey);
const driver = plugin?.manifestJson.environmentDrivers?.find(item => item.driverKey === config.driverKey);
if (plugin?.status === "ready" && driver?.kind !== "sandbox_provider" && driver?.supportsLoginPty && driver.supportsAgentlessLogin) {
return { environment, agentId: undefined };
const config = environment.config;
const plugin = typeof config?.pluginKey === "string" && (start || !input.agentId)
? await pluginRegistryService(db).getByKey(config.pluginKey) : null;
const preference = plugin?.manifestJson.loginDriverPreference;
if (start && plugin && preference) {
const methods = plugin.status === "ready" && start.workerManager?.isRunning(plugin.id)
? start.workerManager.getWorker(plugin.id)?.supportedMethods ?? [] : [];
const drivers = (plugin.manifestJson.environmentDrivers ?? []).map(driver => ({
pluginKey: plugin.pluginKey, driverKey: driver.driverKey, loginDriverPreference: preference,
loginAdapters: pluginDriverLoginAdapters(driver, methods), supportsAgentlessLogin: driver.supportsAgentlessLogin,
}));
const targets = (await listPluginLoginTargets(db, input.companyId, drivers, false))[plugin.pluginKey] ?? [];
const eligible = targets.filter(target => target.loginAdapters.includes(input.adapterType ?? ""));
// Within a driver, try the requested environment before its siblings.
const ownIndex = eligible.findIndex(target => target.environmentId === environment.id);
if (ownIndex >= 0) {
const own = eligible[ownIndex]!;
eligible.splice(ownIndex, 1);
const firstSibling = eligible.findIndex(target => target.driverKey === own.driverKey);
eligible.splice(firstSibling < 0 ? ownIndex : firstSibling, 0, own);
}
let computers = input.agentId ? await availableLoginComputers(db, input.companyId, input.agentId) : undefined;
for (const candidate of eligible) {
const agentless = drivers.find(driver => driver.driverKey === candidate.driverKey)?.supportsAgentlessLogin;
let agentId: string | undefined;
if (!agentless) {
if (!input.agentId && !input.selectComputer) continue;
computers ??= await availableLoginComputers(db, input.companyId);
agentId = computers.get(candidate.environmentId);
if (!agentId) continue;
}
const selected = await environments.getById(candidate.environmentId);
if (selected?.status === "active" && selected.config.pluginKey === plugin.pluginKey && selected.config.driverKey === candidate.driverKey) {
return { environment: selected, agentId };
}
}
if (!input.selectComputer) throw badRequest("Select an agent computer for sign-in.", { code: "login_agent_required" });
const settings = await instanceSettingsService(db).get();
const matchesEnvironment = eq(agents.defaultEnvironmentId, environment.id);
const activeLogin = db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, input.companyId),
eq(environmentLeases.environmentId, environment.id),
eq(environmentLeases.status, "active"),
sql`${environmentLeases.metadata}->>'purpose' = 'login'`,
sql`${environmentLeases.metadata}->>'agentId' = ${agents.id}::text`,
));
const [agent] = await db.select({ id: agents.id }).from(agents).where(and(
eq(agents.companyId, input.companyId),
eq(agents.adapterType, "paperclip_runner"),
notExists(activeLogin),
settings.defaultEnvironmentId === environment.id
? or(matchesEnvironment, isNull(agents.defaultEnvironmentId))
: matchesEnvironment,
or(
and(eq(agents.lifecycleState, "ready"), notInArray(agents.status, ["paused", "terminated", "pending_approval"])),
and(eq(agents.lifecycleState, "verifying"), notInArray(agents.status, ["terminated", "pending_approval"])),
),
)).orderBy(asc(agents.lifecycleState), asc(agents.id)).limit(1);
if (!agent) throw badRequest("No agent computer is available for sign-in.", { code: "login_agent_unavailable" });
return { environment, agentId: agent.id };
throw badRequest("No eligible login environment is available.", { code: "login_environment_unavailable" });
}
const [agent] = await db.select().from(agents).where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId))).limit(1);
if (!agent || agent.companyId !== input.companyId) throw notFound("Agent not found");
const inherited = agent.defaultEnvironmentId ?? (await instanceSettingsService(db).get()).defaultEnvironmentId;
if (inherited !== environment.id || agent.adapterType !== "paperclip_runner" || !["ready", "verifying"].includes(agent.lifecycleState)) {
throw badRequest("The selected agent computer is not available for sign-in.", { code: "login_agent_unavailable" });
const driver = plugin?.manifestJson.environmentDrivers?.find(item => item.driverKey === environment.config.driverKey);
if (!input.agentId && plugin?.status === "ready" && driver?.kind !== "sandbox_provider" && driver?.supportsLoginPty && driver.supportsAgentlessLogin) {
return { environment, agentId: undefined };
}
return { environment, agentId: agent.id };
if (!input.agentId && !input.selectComputer) throw badRequest("Select an agent computer for sign-in.", { code: "login_agent_required" });
const computers = await availableLoginComputers(db, input.companyId, input.agentId);
const agentId = computers.get(environment.id);
if (!agentId) throw badRequest("No agent computer is available for sign-in.", { code: "login_agent_unavailable" });
return { environment, agentId };
}
/** First usable computer per environment, or the caller's exact computer when supplied. */
async function availableLoginComputers(db: Db, companyId: string, agentId?: string): Promise<Map<string, string>> {
if (agentId) {
const [agent] = await db.select().from(agents).where(and(eq(agents.id, agentId), eq(agents.companyId, companyId))).limit(1);
if (!agent || agent.companyId !== companyId) throw notFound("Agent not found");
if (agent.adapterType !== "paperclip_runner" || !["ready", "verifying"].includes(agent.lifecycleState)) return new Map();
const environmentId = agent.defaultEnvironmentId ?? (await instanceSettingsService(db).get()).defaultEnvironmentId;
return environmentId ? new Map([[environmentId, agent.id]]) : new Map();
}
const settings = await instanceSettingsService(db).get();
const effective = sql<string>`coalesce(${agents.defaultEnvironmentId}, ${settings.defaultEnvironmentId}::uuid)`;
const activeLogin = db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, companyId), eq(environmentLeases.environmentId, effective),
eq(environmentLeases.status, "active"), sql`${environmentLeases.metadata}->>'purpose' = 'login'`,
sql`${environmentLeases.metadata}->>'agentId' = ${agents.id}::text`,
));
// Sort once so the first agent for each environment is deterministic, including agents that inherit the instance default.
const key = sql`"login_environment_id"`;
const rows = await db.selectDistinctOn([key], { environmentId: effective.as("login_environment_id"), id: agents.id }).from(agents).where(and(
eq(agents.companyId, companyId), eq(agents.adapterType, "paperclip_runner"), notExists(activeLogin),
or(
and(eq(agents.lifecycleState, "ready"), notInArray(agents.status, ["paused", "terminated", "pending_approval"])),
and(eq(agents.lifecycleState, "verifying"), notInArray(agents.status, ["terminated", "pending_approval"])),
),
)).orderBy(key, asc(agents.lifecycleState), asc(agents.id));
return new Map(rows.filter(row => row.environmentId).map(row => [row.environmentId, row.id]));
}
@@ -212,6 +212,7 @@ export interface ReadyPluginEnvironmentDriver {
supportedAdapters?: string[];
loginAdapters: string[];
supportsAgentlessLogin?: boolean;
loginDriverPreference?: string[];
supportsInteractiveSetup?: PluginEnvironmentDriverDeclaration["supportsInteractiveSetup"];
interactiveSetupConnectionTypes?: PluginEnvironmentDriverDeclaration["interactiveSetupConnectionTypes"];
supportsTemplateCapture?: PluginEnvironmentDriverDeclaration["supportsTemplateCapture"];
@@ -473,6 +474,7 @@ export async function listReadyPluginEnvironmentDrivers(input: {
supportsTemplateDelete: driver.supportsTemplateDelete,
supportsLoginPty: driver.kind === "environment_driver" ? pluginSupportsLoginPty(driver, [...workerMethods]) : sandboxProviderSupportsLoginPty(driver),
...(driver.supportsAgentlessLogin ? { supportsAgentlessLogin: true } : {}),
...(plugin.manifestJson.loginDriverPreference ? { loginDriverPreference: plugin.manifestJson.loginDriverPreference } : {}),
...supportedAdapterFields(plugin.pluginKey, driver, [...workerMethods]),
})),
);
@@ -253,8 +253,8 @@
"packages/shared/src/env-file.ts": "ee15f8dfa6610d3fd1eea3ca0846cc2c583f9070",
"packages/shared/src/environment-custom-images.test.ts": "80d00f3581f13a782480700296b1295d8159ddae",
"packages/shared/src/environment-custom-images.ts": "a81814b7f99e5c8871f50ffcf9dd93dc435dee27",
"packages/shared/src/environment-support.test.ts": "eed931ef7535cd4aae1dc12d640149976634b057",
"packages/shared/src/environment-support.ts": "6bef8200e293fa734e7779456bde5774bab4bdf0",
"packages/shared/src/environment-support.test.ts": "664d6cdc670672f15e120c972d1e6d5514d1aeed",
"packages/shared/src/environment-support.ts": "af4c24d4bf242ce4919745cc419f93f04c6d3143",
"packages/shared/src/execution-workspace-guards.ts": "5428546ab16ef5cb4d23edd914d0a15a83a94668",
"packages/shared/src/external-agent-guidance.ts": "d815fc60b170717f0fdcff61bc30c8a1289f7fcc",
"packages/shared/src/external-objects-server.ts": "f323ba3e5e0b1a2ad415bdb5e0ca99bf9d449821",
@@ -290,7 +290,7 @@
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
"packages/shared/src/index.ts": "ecc9ea3b705c264939c941e673f21c2dbbcd1b7f",
"packages/shared/src/index.ts": "dab61eb638290a2e8bdcb0f4598bf5eeaa697396",
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
@@ -466,7 +466,7 @@
"packages/shared/src/types/issue.ts": "1a01870cfda97510486c20425fabe7ac553460ac",
"packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec",
"packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358",
"packages/shared/src/types/plugin.ts": "ec78e2ec76b61eca20f7250237042c9ac70d5376",
"packages/shared/src/types/plugin.ts": "8745a3dd3043baa4a132df6dd223da18e68e7797",
"packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c",
"packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e",
"packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8",
@@ -552,8 +552,8 @@
"packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830",
"packages/shared/src/validators/onboarding-seed.ts": "de302a8400d4199053f379d9ed853522a3ac6d32",
"packages/shared/src/validators/partial.ts": "fa60ec7481fc14175365e9e500c814b159f1ab53",
"packages/shared/src/validators/plugin.test.ts": "0a028e978f6706b3b23039e30ea04d7d8bccb1e2",
"packages/shared/src/validators/plugin.ts": "424177f7a174e00622acfc0abe1726a7a0768bbb",
"packages/shared/src/validators/plugin.test.ts": "4e281c0ceec0d3404b6b60f2c96ccb558600455a",
"packages/shared/src/validators/plugin.ts": "10f4f8ecdee02eeb9f9c11556efeea79cd64bc60",
"packages/shared/src/validators/project.ts": "6ea168f5faf3161e6004ea47274f60634c77b219",
"packages/shared/src/validators/provider-trace.ts": "b38b6200a2e51513f5dca0f8b008f2fe68175e82",
"packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd",
+14 -11
View File
@@ -1,4 +1,4 @@
import { environmentLoginRequiresAgent, environmentSupportsLoginPty } from "@paperclipai/shared";
import { preferredLoginEnvironmentId, environmentLoginRequiresAgent, environmentSupportsLoginPty } from "@paperclipai/shared";
import {
normalizeSubmittedBrowserCode,
validateSubmittedBrowserCode,
@@ -1518,13 +1518,16 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
// advertises the login pseudo-terminal capability. Read the capability for the
// effective environment provider. The form reads the adapter login capability,
// not the adapter name: every adapter login gates on this provider capability.
const providerSupportsLoginPty = environmentSupportsLoginPty(effectiveLoginEnvironment, environmentCapabilities, isRunnerHarness ? harnessType : adapterType);
const loginRequiresAgent = environmentLoginRequiresAgent(effectiveLoginEnvironment, environmentCapabilities);
const loginEnvironmentId = preferredLoginEnvironmentId(effectiveLoginEnvironment, isRunnerHarness ? harnessType : adapterType, environmentCapabilities?.pluginLoginTargets,
{ ownEnvironmentId: !isCreate && (props.agent.lifecycleState === "ready" || props.agent.lifecycleState === "verifying") ? savedLoginEnvironmentId : null, allowAutomatic: false });
const loginEnvironment = environments.find(env => env.id === loginEnvironmentId);
const providerSupportsLoginPty = environmentSupportsLoginPty(loginEnvironment, environmentCapabilities, isRunnerHarness ? harnessType : adapterType);
const loginRequiresAgent = environmentLoginRequiresAgent(loginEnvironment, environmentCapabilities);
const showAdapterLogin =
(isCreate || !currentAiConnection) &&
adapterSupportsSandboxLogin &&
!(isCreate && loginRequiresAgent) &&
Boolean(effectiveLoginEnvironmentId) &&
(!loginRequiresAgent || (!isCreate && savedLoginEnvironmentId === loginEnvironmentId)) &&
Boolean(loginEnvironmentId) &&
Boolean(selectedCompanyId) &&
Boolean(authMissingCheck) &&
providerSupportsLoginPty;
@@ -1593,8 +1596,8 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
// `showAdapterLogin` already requires a selected company and a non-empty
// environment id, so both are present here.
login:
showAdapterLogin && selectedCompanyId && effectiveLoginEnvironmentId
? { companyId: selectedCompanyId, adapterType: isRunnerHarness ? harnessType : adapterType, environmentId: effectiveLoginEnvironmentId }
showAdapterLogin && selectedCompanyId && loginEnvironmentId
? { companyId: selectedCompanyId, adapterType: isRunnerHarness ? harnessType : adapterType, environmentId: loginEnvironmentId }
: null,
});
return () => {
@@ -1608,7 +1611,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
showAdapterLogin,
selectedCompanyId,
adapterType,
effectiveLoginEnvironmentId,
loginEnvironmentId,
]);
// Current model for display
@@ -2201,11 +2204,11 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
{showInlineAdapterTestEnvironmentFeedback && showAdapterLogin && (
<AdapterLoginPanel
requiresAgent={loginRequiresAgent}
agentId={!isCreate && loginRequiresAgent ? props.agent.id : undefined}
key={`${adapterType}:${effectiveLoginEnvironmentId}`}
agentId={!isCreate && loginRequiresAgent && savedLoginEnvironmentId === loginEnvironmentId ? props.agent.id : undefined}
key={`${adapterType}:${loginEnvironmentId}`}
companyId={selectedCompanyId!}
adapterType={isRunnerHarness ? harnessType : adapterType}
environmentId={effectiveLoginEnvironmentId!}
environmentId={loginEnvironmentId!}
onStored={isCreate ? handleClaudeLoginStored : handleClaudeLoginStoredEdit}
onApplyStored={
isCreate ? handleApplyStoredClaudeLogin : handleApplyStoredClaudeLoginEdit
+59 -40
View File
@@ -8,7 +8,7 @@ import { needsClaudeSetupQualification, qualifyClaudeSetup } from "../lib/qualif
import { blocksAgentCreate, runOnboardingConnectionTest } from "../lib/onboarding-connection-test";
import { normalizeApiKeyInput } from "../lib/onboarding-login-helpers";
import { OnboardingApiKeyField } from "./onboarding/OnboardingApiKeyField";
import { agentComputerAwaitsHire, agentComputerHostsLogin, useAgentComputerLogin } from "../lib/agent-computer-login";
import { agentComputerAwaitsHire, agentComputerHostsLogin, useAgentComputerLogin, useLoginAttemptHost } from "../lib/agent-computer-login";
import { agentHarnessType, agentRunner } from "@paperclipai/shared";
import { adaptersApi, type AdapterInfo } from "../api/adapters";
import { healthApi } from "@/api/health";
@@ -47,7 +47,7 @@ import type {
Environment,
InstanceSettings,
} from "@paperclipai/shared";
import { AGENT_ROLES, AGENT_ROLE_LABELS, ADAPTER_AUTH_MISSING_CHECK_CODE, environmentLoginRequiresAgent, environmentSupportsLoginPty, resolveCloudTrialModel } from "@paperclipai/shared";
import { AGENT_ROLES, AGENT_ROLE_LABELS, ADAPTER_AUTH_MISSING_CHECK_CODE, preferredLoginEnvironmentId, environmentLoginRequiresAgent, environmentSupportsLoginPty, resolveCloudTrialModel } from "@paperclipai/shared";
import { AdapterLoginPanel, ModelDropdown } from "./AgentConfigForm";
import {
CONNECT_SOURCE_NAMES,
@@ -1238,8 +1238,38 @@ function OnboardingWizardInner({
effectiveOnboardingOpen &&
step === 4,
});
const loginProviderSupportsPty = environmentSupportsLoginPty(
resolvedLoginEnvironment,
// A newly prepared draft can host its own login before the cached company availability includes it.
const ownLoginCandidate = environmentLoginRequiresAgent(resolvedLoginEnvironment, loginEnvironmentCapabilities) &&
environmentSupportsLoginPty(resolvedLoginEnvironment, loginEnvironmentCapabilities, adapterType) &&
preferredLoginEnvironmentId(resolvedLoginEnvironment, adapterType, loginEnvironmentCapabilities?.pluginLoginTargets,
{ ownEnvironmentId: resolvedLoginEnvironmentId, allowAutomatic: false }) === resolvedLoginEnvironmentId;
const agentSettledOnChoice = (agent: Pick<Agent, "adapterType" | "adapterConfig">) =>
agentHarnessType(agent.adapterType, agent.adapterConfig) === adapterType
&& (!model.trim() || agent.adapterConfig?.model === model.trim());
const loginAgentId = createdAgentId ?? setupAgentId;
const loginAgentQuery = useQuery({
queryKey: queryKeys.agents.detail(loginAgentId ?? "none"),
queryFn: () => agentsApi.get(loginAgentId!, createdCompanyId!),
enabled: ownLoginCandidate && Boolean(loginAgentId) && credentialMode !== "api"
&& effectiveOnboardingOpen && step === 4,
refetchInterval: (query) => {
const agent = query.state.data;
if (query.state.status === "error") return false;
const instanceDefault = instanceSettingsForLogin?.defaultEnvironmentId ?? null;
return agent && (agent.lifecycleError || (agentSettledOnChoice(agent)
&& (agentComputerHostsLogin(agent, resolvedLoginEnvironmentId, instanceDefault)
|| agentComputerAwaitsHire(agent, resolvedLoginEnvironmentId, instanceDefault)))) ? false : 500;
},
});
const loginAgent = loginAgentQuery.data?.id === loginAgentId ? loginAgentQuery.data : null;
const loginAgentSettled = Boolean(loginAgent && agentSettledOnChoice(loginAgent));
const ownLoginComputerReady = loginAgent && loginAgentSettled &&
agentComputerHostsLogin(loginAgent, resolvedLoginEnvironmentId, instanceSettingsForLogin?.defaultEnvironmentId ?? null);
const candidateHostId = preferredLoginEnvironmentId(resolvedLoginEnvironment, adapterType, loginEnvironmentCapabilities?.pluginLoginTargets,
{ ownEnvironmentId: ownLoginComputerReady ? resolvedLoginEnvironmentId : null });
const loginHost = loginEnvironmentList.find(env => env.id === candidateHostId);
const candidateSupportsPty = environmentSupportsLoginPty(
loginHost,
loginEnvironmentCapabilities,
adapterType,
);
@@ -1277,43 +1307,32 @@ function OnboardingWizardInner({
return () => { connectAttemptRef.current++; };
}, [effectiveOnboardingOpen, createdCompanyId, adapterType, credentialMode, step]);
const canShowAdapterLogin = Boolean(
adapterCaps.login != null &&
resolvedLoginEnvironmentId &&
createdCompanyId &&
loginProviderSupportsPty,
);
const loginRequiresAgent = canShowAdapterLogin && environmentLoginRequiresAgent(resolvedLoginEnvironment, loginEnvironmentCapabilities);
const agentSettledOnChoice = (agent: Pick<Agent, "adapterType" | "adapterConfig">) =>
agentHarnessType(agent.adapterType, agent.adapterConfig) === adapterType
&& (!model.trim() || agent.adapterConfig?.model === model.trim());
const loginAgentId = createdAgentId ?? setupAgentId;
const loginAgentQuery = useQuery({
queryKey: queryKeys.agents.detail(loginAgentId ?? "none"),
queryFn: () => agentsApi.get(loginAgentId!, createdCompanyId!),
enabled: loginRequiresAgent && Boolean(loginAgentId) && credentialMode !== "api"
&& effectiveOnboardingOpen && step === 4,
refetchInterval: (query) => {
const agent = query.state.data;
if (query.state.status === "error") return false;
const instanceDefault = instanceSettingsForLogin?.defaultEnvironmentId ?? null;
return agent && (agent.lifecycleError || (agentSettledOnChoice(agent)
&& (agentComputerHostsLogin(agent, resolvedLoginEnvironmentId, instanceDefault)
|| agentComputerAwaitsHire(agent, resolvedLoginEnvironmentId, instanceDefault)))) ? false : 500;
},
});
const loginAgent = loginAgentQuery.data?.id === loginAgentId ? loginAgentQuery.data : null;
const loginAgentSettled = Boolean(loginAgent && agentSettledOnChoice(loginAgent));
const candidateRequiresAgent = environmentLoginRequiresAgent(loginHost, loginEnvironmentCapabilities);
const loginComputer = useAgentComputerLogin({
required: loginRequiresAgent,
required: candidateRequiresAgent && candidateHostId === resolvedLoginEnvironmentId,
agent: loginAgent,
environmentId: resolvedLoginEnvironmentId,
environmentId: candidateHostId,
instanceDefaultEnvironmentId: instanceSettingsForLogin?.defaultEnvironmentId ?? null,
settled: loginAgentSettled,
holdKey: adapterType,
});
const loginComputerReady = loginComputer.ready;
const loginOnOwnComputer = loginRequiresAgent && loginComputer.ownComputer;
const inLoginStep = effectiveOnboardingOpen && step === 4 && credentialMode !== "api" && connectPhase !== "idle";
const host = useLoginAttemptHost(
JSON.stringify([createdCompanyId, adapterType, model, runner, resolvedLoginEnvironmentId]),
inLoginStep,
connectPhase !== "collapsing" && !connectPhase.startsWith("unwind"),
{
environmentId: candidateHostId,
requiresAgent: candidateRequiresAgent,
ready: loginComputer.ready,
canLogin: candidateSupportsPty,
agentId: loginComputer.ownComputer ? loginAgentId ?? undefined : undefined,
},
);
const loginHostId = host.environmentId;
const loginComputerReady = host.ready;
const loginRequiresAgent = host.requiresAgent;
const canShowAdapterLogin = Boolean(adapterCaps.login && createdCompanyId && loginHostId && host.canLogin);
const loginComputerReadFailed = loginRequiresAgent && !loginComputerReady && loginAgentQuery.isError;
const loginComputerError = !loginRequiresAgent || loginComputerReady ? null
: loginComputerReadFailed ? "Could not check your agent's computer." : loginAgent?.lifecycleError ?? null;
@@ -1371,7 +1390,7 @@ function OnboardingWizardInner({
const managedSubscriptionIntent: AiConnectionLoginIntent | undefined = managedSubscriptionProvider
? { provider: managedSubscriptionProvider, method: "subscription", name: `My ${CONNECT_SOURCE_NAMES[adapterType] ?? managedProvider} subscription`, ownership: "personal", agentIds: [], allAgents: true }
: undefined;
const loginTarget = { environmentId: resolvedLoginEnvironmentId ?? "", aiConnection: managedSubscriptionIntent };
const loginTarget = { environmentId: loginHostId ?? "", aiConnection: managedSubscriptionIntent };
const dismissedLoginResumes = useRef(new Set<string>());
const loginResumeKey = JSON.stringify([createdCompanyId, adapterType]);
const activeLoginSessionQuery = useQuery({
@@ -3782,7 +3801,7 @@ function OnboardingWizardInner({
) : connectStepNeedsLogin &&
loginComputerReady &&
createdCompanyId &&
resolvedLoginEnvironmentId ? (
loginHostId ? (
/* The same panel the agent configuration form shows after
a test — see AdapterLoginPanel in AgentConfigForm.tsx —
in the connect step's chrome. It owns the session; the
@@ -3791,12 +3810,12 @@ function OnboardingWizardInner({
No "Use saved login" control: the hire step already
applies a stored login on its own. */
<AdapterLoginPanel
key={`${adapterType}:${resolvedLoginEnvironmentId}:${loginOnOwnComputer ? loginAgentId : ""}`}
key={`${adapterType}:${loginHostId}:${host.agentId ?? ""}`}
companyId={createdCompanyId}
adapterType={adapterType}
environmentId={resolvedLoginEnvironmentId}
environmentId={loginHostId}
requiresAgent={loginRequiresAgent}
agentId={loginOnOwnComputer ? loginAgentId ?? undefined : undefined}
agentId={host.agentId}
chrome="onboarding"
aiConnection={managedSubscriptionIntent}
autoStart
@@ -1,5 +1,5 @@
import { AI_CONNECTION_CAPABILITIES, adapterLoginCommandKey, environmentLoginRequiresAgent, environmentSupportsLoginPty } from "@paperclipai/shared";
import { useState, type ReactNode } from "react";
import { AI_CONNECTION_CAPABILITIES, adapterLoginCommandKey, pluginLoginChoices, environmentLoginRequiresAgent, environmentSupportsLoginPty } from "@paperclipai/shared";
import { useMemo, 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";
@@ -83,16 +83,31 @@ function SubscriptionConnectionStep({ defaultAccountDialog, onOtherModels, advan
}
const subscriptionAdapter = AI_CONNECTION_CAPABILITIES[provider].methods.subscription?.adapters[0];
const loginAdapter = subscriptionAdapter && adapterLoginCommandKey(subscriptionAdapter) ? subscriptionAdapter : undefined;
const loginEnvironments = (envs.data ?? []).filter((env) =>
env.status === "active" && (env.driver === "local" || (loginAdapter !== undefined && environmentSupportsLoginPty(env, caps.data, loginAdapter))),
);
// Signing in may use a different environment from later agent execution.
// Prefer a supported login environment without changing any agent routing.
if (!forced.forced && !suppliedEnvironmentId && !chosenEnvironment &&
!loginEnvironments.some((env) => env.id === environmentId)) {
environmentId = loginEnvironments[0]?.id ?? null;
const { catalog, choices, loginEnvironments } = useMemo(() => {
const rows = envs.data ?? [];
const catalog = new Map(rows.map(env => [env.id, env]));
const choices = new Map(Object.entries(caps.data?.pluginLoginTargets ?? {}).map(([plugin, targets]) =>
[plugin, pluginLoginChoices(targets, loginAdapter ?? "",
{ ownEnvironmentId: loginAgentId ? suppliedEnvironmentId ?? settings.data?.defaultEnvironmentId : null })]));
const loginEnvironments = rows.filter(env => {
if (env.status !== "active") return false;
if (env.driver === "local") return true;
const key = env.driver === "plugin" && (env.pluginDriver ?? env.config).pluginKey;
const preferred = typeof key === "string" ? choices.get(key) : undefined;
return Boolean(loginAdapter && (!preferred || preferred.has(env.id)) && environmentSupportsLoginPty(env, caps.data, loginAdapter));
});
return { catalog, choices, loginEnvironments };
}, [envs.data, caps.data, loginAdapter, loginAgentId, suppliedEnvironmentId, settings.data?.defaultEnvironmentId]);
const requestedEnvironment = catalog.get(environmentId ?? "");
const key = requestedEnvironment?.driver === "plugin" && (requestedEnvironment.pluginDriver ?? requestedEnvironment.config).pluginKey;
const preferred = loginAdapter && typeof key === "string" ? choices.get(key) : undefined;
let environment = preferred && !preferred.has(environmentId ?? "")
? catalog.get(preferred.values().next().value ?? "") : requestedEnvironment;
if (!forced.forced && !suppliedEnvironmentId && !chosenEnvironment && environment?.id === requestedEnvironment?.id &&
!loginEnvironments.some(env => env.id === environmentId)) {
environment = loginEnvironments[0];
}
const environment = envs.data?.find((env) => env.id === environmentId);
environmentId = environment?.id ?? null;
const canLogin = loginAdapter !== undefined && environmentSupportsLoginPty(environment, caps.data, loginAdapter);
const loading = [envs, caps, settings, experimental, general].some((query) => query.isPending) || (provider === "google" && health.isPending) || views.some((view) => view.kind === "reconnecting");
const loadError = views.find((view) => view.kind === "error");
@@ -108,13 +123,13 @@ function SubscriptionConnectionStep({ defaultAccountDialog, onOtherModels, advan
{loadError ? <QueryErrorState size="inline" error={loadError.error} action="prepare sign-in" onRetry={loadError.retry} retrying={loadError.isFetching} />
: environmentError && !loading ? <p role="alert" className="text-sm text-destructive">{environmentError}</p> : null}
{loading && !dialogFields ? <p role="status" className="text-sm text-muted-foreground">Preparing sign-in…</p> : <AgentProviderConnection
key={environmentId ?? "local"}
key={JSON.stringify([companyId, provider, connectionId, requestedEnvironment?.id])}
companyId={companyId}
adapterType={provider === "google" ? "antigravity_runtime" : provider === "anthropic" ? "claude_local" : provider === "xai" ? "grok_local" : "codex_local"}
environmentId={environmentId}
canLogin={!loading && canLogin}
requiresAgent={environmentLoginRequiresAgent(environment, caps.data)}
agentId={environmentId === (suppliedEnvironmentId ?? settings.data?.defaultEnvironmentId) ? loginAgentId : undefined}
agentId={environmentLoginRequiresAgent(environment, caps.data) && environmentId === (suppliedEnvironmentId ?? settings.data?.defaultEnvironmentId) ? loginAgentId : undefined}
localEnvironment={!loading && environment?.driver === "local"}
onBack={onCancel}
onConnected={() => {}}
@@ -1,3 +1,4 @@
import { useLoginAttemptHost } from "../../lib/agent-computer-login";
import { healthApi } from "@/api/health";
import { aiConnectionsApi } from "@/api/ai-connections";
import { useLocalAiLogin } from "../ai-connections/useLocalAiLogin";
@@ -43,11 +44,11 @@ export type ProviderConnection = {
export function AgentProviderConnection({
companyId,
adapterType,
environmentId,
canLogin,
requiresAgent = false,
agentId,
loginHostPending = false,
environmentId: candidateId,
canLogin: candidateCanLogin,
requiresAgent: candidateRequiresAgent = false,
agentId: candidateAgentId,
loginHostPending: candidatePending = false,
localEnvironment = false,
onConnected,
onDraftChanged,
@@ -131,8 +132,6 @@ export function AgentProviderConnection({
// Connections already selected the provider before showing this step.
const [opened, setOpened] = useState(Boolean(advancedConnection || managedAccount));
const [loginRequested, setLoginRequested] = useState(false);
const automaticComputer = requiresAgent && !agentId;
const awaitingLoginRequest = automaticComputer && !loginRequested;
const [authorizationUrl, setAuthorizationUrl] = useState<string | null>(null);
const [loginPhase, setLoginPhase] = useState<"preparing" | "ready" | "waiting" | "connecting">("preparing");
const phaseBeforeSubmit = useRef<"ready" | "waiting">("ready");
@@ -177,6 +176,17 @@ export function AgentProviderConnection({
(savedKeys.subscriptions.length > 0 || (adapterType === "claude_local" && !savedSubscription && storedLogin.data))
? "subscription" : savedKeys.options.length ? "api" : "subscription"
);
const host = useLoginAttemptHost(
JSON.stringify([companyId, adapterType]),
opened && !advanced && method === "subscription" && !storedConnection,
!savedKeys.loading && !savedSubscription && !storedLogin.data && !managedAccount?.preparingEnvironment &&
(!candidateRequiresAgent || Boolean(candidateAgentId) || loginRequested),
{ environmentId: candidateId, canLogin: candidateCanLogin, requiresAgent: candidateRequiresAgent, agentId: candidateAgentId, ready: !candidatePending },
);
const { environmentId, canLogin, requiresAgent, agentId } = host;
const loginHostPending = !host.ready;
const automaticComputer = requiresAgent && !agentId;
const awaitingLoginRequest = automaticComputer && !loginRequested;
const authMethod = method === "api" ? "api_key" : "subscription";
// Reconnect preserves an account's method. Choosing another method creates
// an account for the same provider; the task host selects it after sign-in.
+13 -8
View File
@@ -30,10 +30,10 @@ import type {
Agent,
EnvBinding,
} from "@paperclipai/shared";
import { ADAPTER_AUTH_MISSING_CHECK_CODE, environmentLoginRequiresAgent, environmentSupportsLoginPty, isAgentStatusInvokable, paperclipRunnerCreationLifecycle, paperclipRunnerProfileForHarness } from "@paperclipai/shared";
import { ADAPTER_AUTH_MISSING_CHECK_CODE, preferredLoginEnvironmentId, environmentLoginRequiresAgent, environmentSupportsLoginPty, isAgentStatusInvokable, paperclipRunnerCreationLifecycle, paperclipRunnerProfileForHarness } from "@paperclipai/shared";
import { useNavigate, useSearchParams } from "@/lib/router";
import { agentsApi } from "@/api/agents";
import { useAgentComputerLogin } from "@/lib/agent-computer-login";
import { agentComputerHostsLogin, useAgentComputerLogin } from "@/lib/agent-computer-login";
import { ApiError } from "@/api/client";
import { adaptersApi } from "@/api/adapters";
import { environmentsApi } from "@/api/environments";
@@ -371,12 +371,17 @@ function Setup({
&& transition.environmentId === environmentId && transition.runner === defaultRunner) return;
resetTest();
}, [companyId, environmentId, runner === "auto" ? defaultRunner : undefined]);
const loginOnComputer = environmentLoginRequiresAgent(environment, caps.data);
const canLogin = environmentSupportsLoginPty(environment, caps.data, connectionAdapter ?? adapterType);
const ownLoginComputerReady = created && !environmentSaving &&
agentComputerHostsLogin(created, environmentId, settings.data?.defaultEnvironmentId ?? null);
const loginHostId = preferredLoginEnvironmentId(environment, connectionAdapter ?? adapterType, caps.data?.pluginLoginTargets,
{ ownEnvironmentId: ownLoginComputerReady ? environmentId : null });
const loginHost = envs.data?.find(env => env.id === loginHostId);
const loginOnComputer = environmentLoginRequiresAgent(loginHost, caps.data);
const canLogin = environmentSupportsLoginPty(loginHost, caps.data, connectionAdapter ?? adapterType);
const loginComputer = useAgentComputerLogin({
required: loginOnComputer,
required: loginOnComputer && loginHostId === environmentId,
agent: created,
environmentId,
environmentId: loginHostId,
instanceDefaultEnvironmentId: settings.data?.defaultEnvironmentId ?? null,
settled: !environmentSaving,
holdKey: connectionAdapter ?? adapterType,
@@ -1072,10 +1077,10 @@ function Setup({
/>
</div>
{connectionSettingsReady ? <fieldset disabled={!ready} className="contents"><AgentProviderConnection
key={environmentId ?? "local"}
key={JSON.stringify([companyId, connectionAdapter, environmentId])}
companyId={companyId}
adapterType={connectionAdapter}
environmentId={environmentId}
environmentId={loginHostId}
canLogin={canLogin}
requiresAgent={loginOnComputer}
agentId={loginOnComputer && loginComputer.ownComputer ? created?.id : undefined}
+24 -1
View File
@@ -2,7 +2,7 @@
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { useAgentComputerLogin } from "./agent-computer-login";
import { useAgentComputerLogin, useLoginAttemptHost } from "./agent-computer-login";
const computer = "11111111-1111-4111-8111-111111111111";
type Agent = Parameters<typeof useAgentComputerLogin>[0]["agent"];
@@ -70,3 +70,26 @@ describe("useAgentComputerLogin", () => {
expect(login).toEqual({ ready: true, ownComputer: false });
});
});
it("keeps an admitted sign-in on the same host until the attempt closes or the user changes source", () => {
const fallback = { environmentId: "other", ready: true, canLogin: true, requiresAgent: true };
const own = { ...fallback, environmentId: computer, agentId: "draft" };
type Host = ReturnType<typeof useLoginAttemptHost>;
function Attempt({ target, scope, active, admit }: { target: Host; scope: string; active: boolean; admit: boolean }) {
const host = useLoginAttemptHost(scope, active, admit, target);
return <span>{JSON.stringify(host)}</span>;
}
function choose(target: Host, active = true, admit = true, scope = "first") {
flushSync(() => root.render(<Attempt target={target} scope={scope} active={active} admit={admit} />));
return JSON.parse(host.textContent!);
}
expect(choose(own, true, false)).toEqual(own);
expect(choose(fallback)).toEqual(fallback);
expect(choose(own)).toEqual(fallback);
expect(choose({ ...own, ready: false, canLogin: false })).toEqual(fallback);
expect(choose(own, false)).toEqual(own);
expect(choose(own)).toEqual(own);
expect(choose(fallback)).toEqual(own);
expect(choose(fallback, true, true, "second")).toEqual(fallback);
});
+14
View File
@@ -51,3 +51,17 @@ export function useAgentComputerLogin(input: {
if (agent && settled && agentComputerAwaitsHire(agent, environmentId, instanceDefaultEnvironmentId)) return { ready: true, ownComputer: false };
return { ready: false, ownComputer: false };
}
type LoginHost = { environmentId: string | null; requiresAgent: boolean; agentId?: string; ready: boolean; canLogin: boolean };
/** Keep the admitted PTY target through this attempt, even if the draft or capability query updates. */
export function useLoginAttemptHost(scope: string, active: boolean, admit: boolean, candidate: LoginHost): LoginHost {
const [attempt, setAttempt] = useState<{ scope: string; host: LoginHost } | null>(null);
if (active && attempt?.scope === scope) return attempt.host;
if (active && admit && candidate.ready && candidate.canLogin && candidate.environmentId) {
setAttempt({ scope, host: candidate });
} else if (attempt) {
setAttempt(null);
}
return candidate;
}