diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index eed8fd66287..83536c4a913 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -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 diff --git a/packages/shared/src/environment-support.test.ts b/packages/shared/src/environment-support.test.ts index eed931ef753..664d6cdc670 100644 --- a/packages/shared/src/environment-support.test.ts +++ b/packages/shared/src/environment-support.test.ts @@ -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); +}); diff --git a/packages/shared/src/environment-support.ts b/packages/shared/src/environment-support.ts index 6bef8200e29..af4c24d4bf2 100644 --- a/packages/shared/src/environment-support.ts +++ b/packages/shared/src/environment-support.ts @@ -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; /** Namespaced plugin driver keys that can host a login on a saved agent. */ loginPtyDrivers?: Record; adapters: AdapterEnvironmentSupport[]; @@ -203,18 +214,50 @@ export function getEnvironmentCapabilities( }; } -export function environmentLoginRequiresAgent(environment: { driver: string; config?: Record | 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 { + const choices = new Set(); + 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 } & Pick | 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 | 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 } | null | undefined, capabilities: EnvironmentCapabilities | null | undefined, adapterType?: string): boolean { +export function environmentSupportsLoginPty(environment: { driver: string; config: Record; 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)); } diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index ecc9ea3b705..dab61eb6382 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2857,6 +2857,9 @@ export { getEnvironmentCapabilities, environmentSupportsLoginPty, environmentLoginRequiresAgent, + preferredLoginEnvironmentId, + pluginLoginChoices, + type PluginLoginTarget, getAdapterEnvironmentSupport, isEnvironmentDriverSupportedForAdapter, isSandboxProviderSupportedForAdapter, diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts index ec78e2ec76b..8745a3dd304 100644 --- a/packages/shared/src/types/plugin.ts +++ b/packages/shared/src/types/plugin.ts @@ -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. */ diff --git a/packages/shared/src/validators/plugin.test.ts b/packages/shared/src/validators/plugin.test.ts index 0a028e978f6..4e281c0ceec 100644 --- a/packages/shared/src/validators/plugin.test.ts +++ b/packages/shared/src/validators/plugin.test.ts @@ -26,6 +26,16 @@ function buildSandboxProviderManifest(driver: Record) { }; } +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); diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.ts index 424177f7a17..10f4f8ecdee 100644 --- a/packages/shared/src/validators/plugin.ts +++ b/packages/shared/src/validators/plugin.ts @@ -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); diff --git a/server/src/routes/adapter-login-route-spine.ts b/server/src/routes/adapter-login-route-spine.ts index 35653083a59..29c4fe20ce9 100644 --- a/server/src/routes/adapter-login-route-spine.ts +++ b/server/src/routes/adapter-login-route-spine.ts @@ -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 diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 4ce8aa10db1..9c25e9fd240 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -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); diff --git a/server/src/routes/environments.ts b/server/src/routes/environments.ts index d49b4ea9875..b43486c040d 100644 --- a/server/src/routes/environments.ts +++ b/server/src/routes/environments.ts @@ -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 { 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, diff --git a/server/src/services/login-environment.test.ts b/server/src/services/login-environment.test.ts index 8ebb4468fe7..bf6908cbc4a 100644 --- a/server/src/services/login-environment.test.ts +++ b/server/src/services/login-environment.test.ts @@ -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 | 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 }); }); diff --git a/server/src/services/login-environment.ts b/server/src/services/login-environment.ts index e5707435630..f58ebddf348 100644 --- a/server/src/services/login-environment.ts +++ b/server/src/services/login-environment.ts @@ -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; + +/** 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 = Object.create(null); + let computers: Awaited> | 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> { + 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`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])); } diff --git a/server/src/services/plugin-environment-driver.ts b/server/src/services/plugin-environment-driver.ts index f8cf61befd0..14f03c53b14 100644 --- a/server/src/services/plugin-environment-driver.ts +++ b/server/src/services/plugin-environment-driver.ts @@ -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]), })), ); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 14481823ac0..0d9733fbc09 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -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", diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index 1687352fc81..edbaf708eae 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -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 && ( ) => + 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) => - 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()); 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. */ - 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 ? : environmentError && !loading ?

{environmentError}

: null} {loading && !dialogFields ?

Preparing sign-in…

: {}} diff --git a/ui/src/components/new-agent/AgentProviderConnection.tsx b/ui/src/components/new-agent/AgentProviderConnection.tsx index 1f2777f9f2f..08f8bc523bf 100644 --- a/ui/src/components/new-agent/AgentProviderConnection.tsx +++ b/ui/src/components/new-agent/AgentProviderConnection.tsx @@ -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(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. diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsx index 949bc13982a..9eb84722774 100644 --- a/ui/src/components/new-agent/NewAgentSetup.tsx +++ b/ui/src/components/new-agent/NewAgentSetup.tsx @@ -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({ /> {connectionSettingsReady ?
[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; + function Attempt({ target, scope, active, admit }: { target: Host; scope: string; active: boolean; admit: boolean }) { + const host = useLoginAttemptHost(scope, active, admit, target); + return {JSON.stringify(host)}; + } + function choose(target: Host, active = true, admit = true, scope = "first") { + flushSync(() => root.render()); + 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); +}); diff --git a/ui/src/lib/agent-computer-login.ts b/ui/src/lib/agent-computer-login.ts index d24dfd0880c..aacc6d01409 100644 --- a/ui/src/lib/agent-computer-login.ts +++ b/ui/src/lib/agent-computer-login.ts @@ -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; +}