Files
PaperClipAI/server/src/services/login-environment.test.ts
T
Nicky LeachandPaperclip 550d8fc576 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>
2026-12-01 16:58:28 -08:00

132 lines
12 KiB
TypeScript

import { randomUUID } from "node:crypto";
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 }));
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 = { 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" } });
getByKey.mockResolvedValue({ status: "ready", manifestJson: { environmentDrivers: [
{ kind: "environment_driver", driverKey: "temporary", supportsLoginPty: true, supportsAgentlessLogin: true },
] } });
fixtures.agent = undefined;
const input = { companyId: "company", environmentId: "environment", adapterType: "codex_local" };
await expect(resolveLoginEnvironmentTarget(db, { ...input, selectComputer: true })).resolves.toEqual({ environment: fixtures.environment, agentId: undefined });
await expect(assertLoginEnvironmentTarget(db, input)).resolves.toEqual(fixtures.environment);
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 }); });
it("requires a saved target for existing-computer login", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment" })).rejects.toMatchObject({ status: 400 }); });
it("rejects a foreign company environment", async () => { fixtures.companies = ["another-company"]; await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).rejects.toMatchObject({ status: 403 }); });
it("does not expose a foreign or missing agent", async () => { fixtures.agent!.companyId = "another-company"; await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).rejects.toMatchObject({ status: 404 }); });
it.each([{ defaultEnvironmentId: "another-environment" }, { lifecycleState: "pending" }, { adapterType: "codex_local" }])("rejects unavailable target binding %j", async change => { Object.assign(fixtures.agent!, change); await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).rejects.toMatchObject({ status: 400 }); });
it("supports the inherited environment", async () => { fixtures.agent!.defaultEnvironmentId = null; await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).resolves.toEqual(fixtures.environment); });
it("retains agentless temporary sandbox login", async () => { fixtures.environment.driver = "sandbox"; await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment" })).resolves.toEqual(fixtures.environment); });
});
const postgres = await getEmbeddedPostgresTestSupport();
(postgres.supported ? describe : describe.skip)("automatic login computer selection", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-login-target-"); }, 90_000);
afterAll(async () => { await database?.cleanup(); });
it("prefers a ready computer in the chosen company and effective environment", async () => {
const db = createDb(database.connectionString);
const companyId = randomUUID();
const otherCompanyId = randomUUID();
const environmentId = randomUUID();
const otherEnvironmentId = randomUUID();
const readyId = randomUUID();
const verifyingId = randomUUID();
fixtures.environment = { id: environmentId, driver: "plugin" };
fixtures.instanceDefault = environmentId;
fixtures.companies = [companyId];
await db.insert(companies).values([
{ id: companyId, name: "Login company", issuePrefix: "LOGIN" },
{ id: otherCompanyId, name: "Other company", issuePrefix: "OTHER" },
]);
await db.insert(environments).values([
{ id: environmentId, name: "Computers", driver: "plugin" },
{ id: otherEnvironmentId, name: "Other computers", driver: "plugin" },
]);
const agent = { companyId, name: "Computer", adapterType: "paperclip_runner", defaultEnvironmentId: environmentId } as const;
await db.insert(agents).values([
{ ...agent, id: readyId, defaultEnvironmentId: null, lifecycleState: "ready" },
{ ...agent, id: verifyingId, lifecycleState: "verifying", status: "paused" },
{ ...agent, companyId: otherCompanyId },
{ ...agent, defaultEnvironmentId: otherEnvironmentId },
{ ...agent, status: "paused" },
{ ...agent, status: "pending_approval", lifecycleState: "verifying" },
{ ...agent, adapterType: "codex_local" },
]);
const request = { companyId, environmentId, adapterType: "codex_local", selectComputer: true };
await expect(resolveLoginEnvironmentTarget(db, request)).resolves.toMatchObject({ agentId: readyId });
await expect(resolveLoginEnvironmentTarget(db, { ...request, agentId: verifyingId })).resolves.toMatchObject({ agentId: verifyingId });
const [loginLease] = await db.insert(environmentLeases).values({
companyId, environmentId, metadata: { purpose: "login", agentId: readyId },
}).returning({ id: environmentLeases.id });
await expect(resolveLoginEnvironmentTarget(db, request)).resolves.toMatchObject({ agentId: verifyingId });
await db.update(environmentLeases).set({ status: "released" }).where(eq(environmentLeases.id, loginLease.id));
await expect(resolveLoginEnvironmentTarget(db, request)).resolves.toMatchObject({ agentId: readyId });
fixtures.instanceDefault = otherEnvironmentId;
await expect(resolveLoginEnvironmentTarget(db, request)).resolves.toMatchObject({ agentId: verifyingId });
await db.delete(agents).where(eq(agents.id, verifyingId));
await expect(resolveLoginEnvironmentTarget(db, request)).rejects.toMatchObject({
status: 400, message: "No agent computer is available for sign-in.",
});
});
});