mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
fix(agents): set agents up again when their environment driver changes (#23449)
This commit is contained in:
1 parent
725a9e36b6
commit
5a956b724b
11 files changed
+200
-30
No files matched your search
+26
-6
@@ -198,10 +198,16 @@ plugins are selected for all agents, including a sandbox provider that declares
|
|||||||
`requiresAgent: true`.
|
`requiresAgent: true`.
|
||||||
|
|
||||||
When an agent moves to such an environment, the host adds the plugin at the next
|
When an agent moves to such an environment, the host adds the plugin at the next
|
||||||
`preparing` or `resuming` step. Moving a `ready` agent to an environment that
|
`preparing` or `resuming` step. The plugin prepares the agent for the
|
||||||
needs a new plugin automatically pauses execution, waits for the host and
|
environment's driver: each request carries `environmentDriverKey`, and nothing
|
||||||
existing plugins to stop, resumes with the new plugin, and verifies the saved
|
else about the environment. So an agent needs setup again when it moves to an
|
||||||
configuration before admitting work. The change and pause request commit
|
environment whose plugin has not prepared it, or whose plugin prepared it for
|
||||||
|
another driver. A move between two environments with the same plugin and driver
|
||||||
|
needs no setup. A move back to the plugin's environment from an environment that
|
||||||
|
the plugin does not serve also runs setup again. Moving a `ready` agent to an
|
||||||
|
environment that needs setup automatically pauses execution, waits for the host
|
||||||
|
and existing plugins to stop, resumes with the plugin set up for the new
|
||||||
|
driver, and verifies the saved configuration before admitting work. The change and pause request commit
|
||||||
together; retries and server restarts retain the pending operation. Manual,
|
together; retries and server restarts retain the pending operation. Manual,
|
||||||
budget, and company holds still prevent automatic resume. An agent in
|
budget, and company holds still prevent automatic resume. An agent in
|
||||||
`verifying` returns to `preparing`. An agent that moves away keeps the selection until it is terminated,
|
`verifying` returns to `preparing`. An agent that moves away keeps the selection until it is terminated,
|
||||||
@@ -215,8 +221,22 @@ before the change; an unauthorized request cannot save the environment or pause
|
|||||||
the agent.
|
the agent.
|
||||||
|
|
||||||
Saving an environment or the instance default that gives such a plugin to `ready`
|
Saving an environment or the instance default that gives such a plugin to `ready`
|
||||||
or `verifying` agents without that selection returns a conflict. Pause those agents,
|
or `verifying` agents without that selection returns a conflict. The same applies
|
||||||
save the change, and then resume them.
|
when the change keeps the plugin but changes its driver; then every `ready` or
|
||||||
|
`verifying` agent on the environment needs setup. Pause those agents, save the
|
||||||
|
change, and then resume them.
|
||||||
|
|
||||||
|
This save check trusts a selection when the old environment uses another plugin
|
||||||
|
or none. An agent keeps its selection after it leaves the plugin's environment.
|
||||||
|
So an agent that was set up for one driver, then moved to an environment that
|
||||||
|
the plugin does not serve, can follow a later environment or instance default
|
||||||
|
save to another driver of the same plugin without setup. Its next lease on the
|
||||||
|
new driver can fail. Pausing and resuming the agent runs setup for the new
|
||||||
|
driver.
|
||||||
|
|
||||||
|
A connection test on such an environment runs only for the environment that the
|
||||||
|
agent has saved. A test of another plugin or driver, before the agent is saved
|
||||||
|
with it, returns the `environment_agent_unsaved` warning without a lease.
|
||||||
|
|
||||||
Each request contains these fields:
|
Each request contains these fields:
|
||||||
|
|
||||||
|
|||||||
@@ -155,8 +155,8 @@ Saved OpenCode agents keep their runner and runtime policies.
|
|||||||
Plugin environment drivers can declare `requiresAgent: true` when their leases
|
Plugin environment drivers can declare `requiresAgent: true` when their leases
|
||||||
need an agent-owned resource. The host selects that plugin's lifecycle work only for
|
need an agent-owned resource. The host selects that plugin's lifecycle work only for
|
||||||
agents on that environment. See [Required plugin work](./AGENT-LIFECYCLE.md#required-plugin-work).
|
agents on that environment. See [Required plugin work](./AGENT-LIFECYCLE.md#required-plugin-work).
|
||||||
Moving a ready agent to an environment that needs a new plugin automatically
|
Moving a ready agent to an environment that needs a new plugin, or another
|
||||||
pauses execution, waits for stop completion, starts the required resources, and
|
driver of the same plugin, automatically pauses execution, waits for stop completion, starts the required resources, and
|
||||||
verifies the saved configuration before allowing work. Existing pause holds
|
verifies the saved configuration before allowing work. Existing pause holds
|
||||||
still apply; the user does not need to pause or resume the agent for this move.
|
still apply; the user does not need to pause or resume the agent for this move.
|
||||||
Setup saves the draft and environment, runs its
|
Setup saves the draft and environment, runs its
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vites
|
|||||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||||
import { configureAgentLifecycle, createAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
|
import { configureAgentLifecycle, createAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
|
||||||
import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js";
|
import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js";
|
||||||
|
import { agentEnvironmentTestService } from "../../../services/agent-environment-test.js";
|
||||||
import { agentService as agentConfiguration } from "../../../services/agents.js";
|
import { agentService as agentConfiguration } from "../../../services/agents.js";
|
||||||
import { assertAgentsReadyForEnvironmentChange } from "../../../services/plugin-environment-driver.js";
|
import { assertAgentsReadyForEnvironmentChange } from "../../../services/plugin-environment-driver.js";
|
||||||
import { createLifecycleStore } from "../adapters/postgres.js";
|
import { createLifecycleStore } from "../adapters/postgres.js";
|
||||||
@@ -22,6 +23,8 @@ const support = await getEmbeddedPostgresTestSupport();
|
|||||||
let boundPluginId: string;
|
let boundPluginId: string;
|
||||||
let boundEnvironmentId: string;
|
let boundEnvironmentId: string;
|
||||||
let otherEnvironmentId: string;
|
let otherEnvironmentId: string;
|
||||||
|
let siblingEnvironmentId: string;
|
||||||
|
let twinEnvironmentId: string;
|
||||||
const workers: ReturnType<typeof configureAgentLifecycle>[] = [];
|
const workers: ReturnType<typeof configureAgentLifecycle>[] = [];
|
||||||
const call = vi.fn(async (_id, _method, input) => ({ operationId: input.operationId, version: input.version, status: "complete" }));
|
const call = vi.fn(async (_id, _method, input) => ({ operationId: input.operationId, version: input.version, status: "complete" }));
|
||||||
|
|
||||||
@@ -33,13 +36,17 @@ const support = await getEmbeddedPostgresTestSupport();
|
|||||||
await db.delete(plugins);
|
await db.delete(plugins);
|
||||||
await db.update(instanceSettings).set({ defaultEnvironmentId: null });
|
await db.update(instanceSettings).set({ defaultEnvironmentId: null });
|
||||||
companyId = randomUUID(); boundPluginId = randomUUID(); boundEnvironmentId = randomUUID(); otherEnvironmentId = randomUUID();
|
companyId = randomUUID(); boundPluginId = randomUUID(); boundEnvironmentId = randomUUID(); otherEnvironmentId = randomUUID();
|
||||||
|
siblingEnvironmentId = randomUUID(); twinEnvironmentId = randomUUID();
|
||||||
await db.insert(companies).values({ id: companyId, name: "Environment plugins", issuePrefix: `E${companyId.slice(0, 7)}` });
|
await db.insert(companies).values({ id: companyId, name: "Environment plugins", issuePrefix: `E${companyId.slice(0, 7)}` });
|
||||||
await db.insert(plugins).values({ id: boundPluginId, pluginKey: boundPluginId, packageName: "bound", version: "1.0.0", status: "ready",
|
await db.insert(plugins).values({ id: boundPluginId, pluginKey: boundPluginId, packageName: "bound", version: "1.0.0", status: "ready",
|
||||||
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
|
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
|
||||||
environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true }] } as never });
|
environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true },
|
||||||
|
{ driverKey: "isolated", requiresAgent: true, supportsTasks: true }] } as never });
|
||||||
await db.insert(environments).values([
|
await db.insert(environments).values([
|
||||||
{ id: boundEnvironmentId, name: `Bound ${boundEnvironmentId}`, driver: "plugin", status: "active", config: { pluginKey: boundPluginId, driverKey: "tasks", driverConfig: {} } },
|
{ id: boundEnvironmentId, name: `Bound ${boundEnvironmentId}`, driver: "plugin", status: "active", config: { pluginKey: boundPluginId, driverKey: "tasks", driverConfig: {} } },
|
||||||
{ id: otherEnvironmentId, name: `Other ${otherEnvironmentId}`, driver: "sandbox", status: "active", config: { provider: "fixture" } },
|
{ id: otherEnvironmentId, name: `Other ${otherEnvironmentId}`, driver: "sandbox", status: "active", config: { provider: "fixture" } },
|
||||||
|
{ id: siblingEnvironmentId, name: `Sibling ${siblingEnvironmentId}`, driver: "plugin", status: "active", config: { pluginKey: boundPluginId, driverKey: "isolated", driverConfig: {} } },
|
||||||
|
{ id: twinEnvironmentId, name: `Twin ${twinEnvironmentId}`, driver: "plugin", status: "active", config: { pluginKey: boundPluginId, driverKey: "tasks", driverConfig: {} } },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -244,6 +251,64 @@ const support = await getEmbeddedPostgresTestSupport();
|
|||||||
expect((await current(id)).lifecycleError).toBeTruthy();
|
expect((await current(id)).lifecycleError).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("automatically re-prepares a ready agent that moves to another driver of the same plugin", async () => {
|
||||||
|
const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
||||||
|
const saved = await agentConfiguration(db).update(id, { defaultEnvironmentId: siblingEnvironmentId });
|
||||||
|
expect(saved).toMatchObject({ defaultEnvironmentId: siblingEnvironmentId, lifecycleState: "pausing", status: "paused" });
|
||||||
|
await worker().process(id);
|
||||||
|
expect(call.mock.calls.map(args => [args[2].phase, args[2].environmentDriverKey])).toEqual([
|
||||||
|
["pausing", "isolated"], ["resuming", "isolated"], ["verifying", "isolated"]]);
|
||||||
|
expect(await current(id)).toMatchObject({ lifecycleState: "ready", status: "idle", lifecycleRequiredPluginIds: [boundPluginId] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns a verifying agent to preparing when it moves to another driver of the same plugin", async () => {
|
||||||
|
const id = await agent(boundEnvironmentId, { lifecycleState: "verifying", status: "paused", lifecycleRequiredPluginIds: [boundPluginId],
|
||||||
|
lifecycleOperation: { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0 } });
|
||||||
|
await agentConfiguration(db).update(id, { defaultEnvironmentId: siblingEnvironmentId });
|
||||||
|
expect((await current(id)).lifecycleState).toBe("preparing");
|
||||||
|
await worker().process(id);
|
||||||
|
expect(call.mock.calls.map(args => [args[2].phase, args[2].environmentDriverKey])).toContainEqual(["preparing", "isolated"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("re-prepares an agent that returns to the plugin's environment through an environment it does not serve", async () => {
|
||||||
|
const id = await agent(otherEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
||||||
|
expect(await agentConfiguration(db).update(id, { defaultEnvironmentId: siblingEnvironmentId })).toMatchObject({ lifecycleState: "pausing" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a ready agent ready when it moves between environments with the same driver", async () => {
|
||||||
|
const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
||||||
|
const before = await current(id);
|
||||||
|
await agentConfiguration(db).update(id, { defaultEnvironmentId: twinEnvironmentId });
|
||||||
|
expect(await current(id)).toMatchObject({ defaultEnvironmentId: twinEnvironmentId, lifecycleState: "ready",
|
||||||
|
lifecycleVersion: before.lifecycleVersion });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses an environment change that moves active agents to another driver of the same plugin", async () => {
|
||||||
|
const bound = { driver: "plugin", config: { pluginKey: boundPluginId, driverKey: "tasks" } };
|
||||||
|
const sibling = { driver: "plugin", config: { pluginKey: boundPluginId, driverKey: "isolated" } };
|
||||||
|
const users = { environmentId: boundEnvironmentId, inheritsDefault: false };
|
||||||
|
const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
||||||
|
await expect(assertAgentsReadyForEnvironmentChange(db, bound, sibling, users)).rejects.toThrow("need setup first");
|
||||||
|
await expect(assertAgentsReadyForEnvironmentChange(db, bound, bound, users)).resolves.toBeUndefined();
|
||||||
|
await db.update(agents).set({ lifecycleState: "paused", status: "paused" }).where(eq(agents.id, id));
|
||||||
|
await expect(assertAgentsReadyForEnvironmentChange(db, bound, sibling, users)).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tests an agent's connection only on the environment driver its plugin set it up for", async () => {
|
||||||
|
const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
||||||
|
const lease = vi.fn(async () => { throw new Error("Sandbox agent session storage is unavailable"); });
|
||||||
|
const setup = agentEnvironmentTestService(db, { call: lease, isRunning: () => true } as never);
|
||||||
|
const test = (environmentId: string) => setup.resolveAdapterTestExecutionContext({ companyId, agentId: id, environmentId, adapterType: "process" });
|
||||||
|
expect((await test(siblingEnvironmentId)).fallbackChecks).toMatchObject([{ code: "environment_agent_unsaved", level: "warn" }]);
|
||||||
|
expect(lease).not.toHaveBeenCalled();
|
||||||
|
expect((await test(twinEnvironmentId)).fallbackChecks).toMatchObject([{ code: "environment_lease_acquire_failed",
|
||||||
|
detail: expect.stringContaining("session storage is unavailable"), hint: expect.stringContaining("Pausing and resuming the agent") }]);
|
||||||
|
for (const lifecycleState of ["pausing", "resuming"] as const) {
|
||||||
|
await db.update(agents).set({ lifecycleState, status: "paused" }).where(eq(agents.id, id));
|
||||||
|
expect((await test(boundEnvironmentId)).fallbackChecks).toMatchObject([{ code: "environment_agent_preparing" }]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("lets a ready agent move when the plugin is selected, and keeps the selection when it leaves", async () => {
|
it("lets a ready agent move when the plugin is selected, and keeps the selection when it leaves", async () => {
|
||||||
const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] });
|
||||||
await agentConfiguration(db).update(id, { defaultEnvironmentId: otherEnvironmentId });
|
await agentConfiguration(db).update(id, { defaultEnvironmentId: otherEnvironmentId });
|
||||||
|
|||||||
@@ -26,12 +26,12 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects
|
|||||||
assertConfigurationFields(patch);
|
assertConfigurationFields(patch);
|
||||||
const changed = ["adapterType", "adapterConfig", "runtimeConfig", "defaultEnvironmentId"].some(key =>
|
const changed = ["adapterType", "adapterConfig", "runtimeConfig", "defaultEnvironmentId"].some(key =>
|
||||||
Object.prototype.hasOwnProperty.call(patch, key) && !jsonEqual(patch[key as keyof typeof patch], current[key as keyof typeof current]));
|
Object.prototype.hasOwnProperty.call(patch, key) && !jsonEqual(patch[key as keyof typeof patch], current[key as keyof typeof current]));
|
||||||
const needsNewPlugin = ["ready", "verifying"].includes(current.lifecycleState)
|
const needsEnvironmentSetup = ["ready", "verifying"].includes(current.lifecycleState)
|
||||||
&& Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId")
|
&& Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId")
|
||||||
&& patch.defaultEnvironmentId !== current.defaultEnvironmentId
|
&& patch.defaultEnvironmentId !== current.defaultEnvironmentId
|
||||||
&& await effects.environmentRequiresNewPlugin(tx, patch.defaultEnvironmentId, current.lifecycleRequiredPluginIds);
|
&& await effects.environmentChangeRequiresSetup(tx, current.defaultEnvironmentId, patch.defaultEnvironmentId, current.lifecycleRequiredPluginIds);
|
||||||
const pauseForEnvironment = needsNewPlugin && current.lifecycleState === "ready";
|
const pauseForEnvironment = needsEnvironmentSetup && current.lifecycleState === "ready";
|
||||||
const prepareEnvironment = needsNewPlugin && !current.lifecycleHolds.includes("setup");
|
const prepareEnvironment = needsEnvironmentSetup && !current.lifecycleHolds.includes("setup");
|
||||||
const prepareSetup = changed && current.lifecycleHolds.length === 1 && current.lifecycleHolds[0] === "setup"
|
const prepareSetup = changed && current.lifecycleHolds.length === 1 && current.lifecycleHolds[0] === "setup"
|
||||||
&& ["paused", "preparing", "verifying"].includes(current.lifecycleState)
|
&& ["paused", "preparing", "verifying"].includes(current.lifecycleState)
|
||||||
&& await effects.setupRequiresPreparation(tx, current.companyId,
|
&& await effects.setupRequiresPreparation(tx, current.companyId,
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ import type { ActivityPublication } from "../../../types/activity-publication.js
|
|||||||
export interface LifecycleEffects {
|
export interface LifecycleEffects {
|
||||||
setupRequiresPreparation(db: Db, companyId: string, environmentId: string | null | undefined,
|
setupRequiresPreparation(db: Db, companyId: string, environmentId: string | null | undefined,
|
||||||
profile: Pick<CreateAgentData, "adapterType" | "adapterConfig">): Promise<boolean>;
|
profile: Pick<CreateAgentData, "adapterType" | "adapterConfig">): Promise<boolean>;
|
||||||
environmentRequiresNewPlugin(db: Db, environmentId: string | null | undefined, selectedPluginIds: string[] | null): Promise<boolean>;
|
environmentChangeRequiresSetup(db: Db, beforeEnvironmentId: string | null | undefined, afterEnvironmentId: string | null | undefined,
|
||||||
|
selectedPluginIds: string[] | null): Promise<boolean>;
|
||||||
notifyWork(db: Db): Promise<void>;
|
notifyWork(db: Db): Promise<void>;
|
||||||
/** The calling controller process, stamped on a lifecycle lease so restart recovery can settle a dead holder. */
|
/** The calling controller process, stamped on a lifecycle lease so restart recovery can settle a dead holder. */
|
||||||
leaseHolder?(): Record<string, unknown> | null;
|
leaseHolder?(): Record<string, unknown> | null;
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import { validateAiApiKey } from "./ai-api-key-test.js";
|
|||||||
import { probeCopilotExecutionTarget } from "./copilot-connection-probe.js";
|
import { probeCopilotExecutionTarget } from "./copilot-connection-probe.js";
|
||||||
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
||||||
import { assertEnvironmentSelectionForCompany } from "./environment-selection.js";
|
import { assertEnvironmentSelectionForCompany } from "./environment-selection.js";
|
||||||
import { pluginEnvironmentRequiresAgent } from "./plugin-environment-driver.js";
|
import { agentSetupTarget, pluginEnvironmentRequiresAgent, sameAgentSetupTarget } from "./plugin-environment-driver.js";
|
||||||
const asRecord = (value: unknown): Record<string, unknown> | null => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
const asRecord = (value: unknown): Record<string, unknown> | null => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||||
function finishManagedConnectionTest(adapterType: string, context: AdapterEnvironmentTestContext, result: AdapterEnvironmentTestResult): AdapterEnvironmentTestResult {
|
function finishManagedConnectionTest(adapterType: string, context: AdapterEnvironmentTestContext, result: AdapterEnvironmentTestResult): AdapterEnvironmentTestResult {
|
||||||
const target = context.executionTarget;
|
const target = context.executionTarget;
|
||||||
@@ -231,9 +231,10 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
|
|||||||
// agent lease) and archive it on release instead of deleting it, so the
|
// agent lease) and archive it on release instead of deleting it, so the
|
||||||
// operator can inspect the exact sandbox from the provider dashboard while
|
// operator can inspect the exact sandbox from the provider dashboard while
|
||||||
// provider-side expiry reaps it later.
|
// provider-side expiry reaps it later.
|
||||||
if (environment.driver === "plugin" && await pluginEnvironmentRequiresAgent(db, environment)) {
|
const requiresAgentSetup = environment.driver === "plugin" && await pluginEnvironmentRequiresAgent(db, environment);
|
||||||
|
if (requiresAgentSetup) {
|
||||||
const [agent] = input.agentId ? await db.select({ state: agents.lifecycleState, pauseReason: agents.pauseReason,
|
const [agent] = input.agentId ? await db.select({ state: agents.lifecycleState, pauseReason: agents.pauseReason,
|
||||||
requiresApproval: companies.requireBoardApprovalForNewAgents }).from(agents)
|
environmentId: agents.defaultEnvironmentId, requiresApproval: companies.requireBoardApprovalForNewAgents }).from(agents)
|
||||||
.innerJoin(companies, eq(companies.id, agents.companyId))
|
.innerJoin(companies, eq(companies.id, agents.companyId))
|
||||||
.where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId))) : [];
|
.where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId))) : [];
|
||||||
if (agent?.state === "paused" && agent.pauseReason === "setup" && agent.requiresApproval) return {
|
if (agent?.state === "paused" && agent.pauseReason === "setup" && agent.requiresApproval) return {
|
||||||
@@ -242,13 +243,21 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
|
|||||||
message: "The selected account will be verified on the agent computer after hire approval.",
|
message: "The selected account will be verified on the agent computer after hire approval.",
|
||||||
}], release: noopRelease,
|
}], release: noopRelease,
|
||||||
};
|
};
|
||||||
if (!agent || ["paused", "preparing"].includes(agent.state)) return {
|
if (!agent || ["paused", "preparing", "pausing", "resuming"].includes(agent.state)) return {
|
||||||
executionTarget: null, environmentName: environment.name, fallbackChecks: [{
|
executionTarget: null, environmentName: environment.name, fallbackChecks: [{
|
||||||
code: !input.agentId ? "environment_agent_required" : "environment_agent_preparing", level: "warn",
|
code: !input.agentId ? "environment_agent_required" : "environment_agent_preparing", level: "warn",
|
||||||
message: !input.agentId ? "This environment needs a saved agent before its connection can be tested."
|
message: !input.agentId ? "This environment needs a saved agent before its connection can be tested."
|
||||||
: "The agent computer is being prepared. Test the connection when preparation finishes.",
|
: "The agent computer is being prepared. Test the connection when preparation finishes.",
|
||||||
}], release: noopRelease,
|
}], release: noopRelease,
|
||||||
};
|
};
|
||||||
|
const savedEnvironmentId = agent.environmentId ?? (await instanceSettings.get()).defaultEnvironmentId;
|
||||||
|
const savedEnvironment = savedEnvironmentId ? await environmentsSvc.getById(savedEnvironmentId) : null;
|
||||||
|
if (!sameAgentSetupTarget(await agentSetupTarget(db, savedEnvironment), await agentSetupTarget(db, environment))) return {
|
||||||
|
executionTarget: null, environmentName: environment.name, fallbackChecks: [{
|
||||||
|
code: "environment_agent_unsaved", level: "warn",
|
||||||
|
message: `Save the agent with "${environment.name}" first. The agent is set up for an environment when it is saved, then its connection can be tested.`,
|
||||||
|
}], release: noopRelease,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
const testEnvironment = environment.driver === "sandbox"
|
const testEnvironment = environment.driver === "sandbox"
|
||||||
? {
|
? {
|
||||||
@@ -294,7 +303,9 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
|
|||||||
level: "error",
|
level: "error",
|
||||||
message: `Could not acquire a lease for environment "${environment.name}".`,
|
message: `Could not acquire a lease for environment "${environment.name}".`,
|
||||||
detail: err instanceof Error ? err.message : String(err),
|
detail: err instanceof Error ? err.message : String(err),
|
||||||
hint: "Check the environment's provider credentials and quota.",
|
hint: requiresAgentSetup
|
||||||
|
? "Check the detail above. Pausing and resuming the agent runs its environment setup again."
|
||||||
|
: "Check the environment's provider credentials and quota.",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
release: noopRelease,
|
release: noopRelease,
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ import { applyAgentPolicyHoldsInTransaction } from "../modules/agent-lifecycle/i
|
|||||||
import { trackIdleWork } from "./task-admission.js";
|
import { trackIdleWork } from "./task-admission.js";
|
||||||
import { environmentService } from "./environments.js";
|
import { environmentService } from "./environments.js";
|
||||||
import { instanceSettingsService } from "./instance-settings.js";
|
import { instanceSettingsService } from "./instance-settings.js";
|
||||||
import { pluginEnvironmentRequiresAgent, pluginForAgentEnvironment } from "./plugin-environment-driver.js";
|
import { environmentChangeRequiresAgentSetup, pluginEnvironmentRequiresAgent } from "./plugin-environment-driver.js";
|
||||||
import { isProviderApiSetupDraft } from "./native-runtime/provider-api-placement.js";
|
import { isProviderApiSetupDraft } from "./native-runtime/provider-api-placement.js";
|
||||||
|
|
||||||
export { scheduleAgentLifecycle, processAgentLifecycle } from "../modules/agent-lifecycle/index.js";
|
export { scheduleAgentLifecycle, processAgentLifecycle } from "../modules/agent-lifecycle/index.js";
|
||||||
@@ -47,11 +47,13 @@ export function createAgentLifecycleEffects(_hooks: BudgetServiceHooks = {}): li
|
|||||||
if (bound.length && !bound.includes(companyId)) throw new lifecycle.AgentLifecycleConflict("The environment belongs to another company");
|
if (bound.length && !bound.includes(companyId)) throw new lifecycle.AgentLifecycleConflict("The environment belongs to another company");
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
async environmentRequiresNewPlugin(db, environmentId, selectedPluginIds) {
|
async environmentChangeRequiresSetup(db, beforeEnvironmentId, afterEnvironmentId, selectedPluginIds) {
|
||||||
const id = environmentId ?? (await instanceSettingsService(db).get()).defaultEnvironmentId;
|
const instanceDefault = async () => (await instanceSettingsService(db).get()).defaultEnvironmentId;
|
||||||
const environment = id ? await environmentService(db).getById(id) : null;
|
const resolve = async (id: string | null | undefined) => {
|
||||||
const plugin = environment ? await pluginForAgentEnvironment(db, environment) : null;
|
const resolved = id ?? await instanceDefault();
|
||||||
return plugin !== null && !selectedPluginIds?.includes(plugin.id);
|
return resolved ? await environmentService(db).getById(resolved) : null;
|
||||||
|
};
|
||||||
|
return environmentChangeRequiresAgentSetup(db, await resolve(beforeEnvironmentId), await resolve(afterEnvironmentId), selectedPluginIds);
|
||||||
},
|
},
|
||||||
notifyWork: tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle),
|
notifyWork: tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle),
|
||||||
leaseHolder: () => currentControllerProcessStamp(),
|
leaseHolder: () => currentControllerProcessStamp(),
|
||||||
|
|||||||
@@ -59,17 +59,37 @@ export async function pluginForAgentEnvironment(db: Db, environment: AgentEnviro
|
|||||||
return plugin && pluginServesAgentEnvironment(plugin, environment) ? plugin : null;
|
return plugin && pluginServesAgentEnvironment(plugin, environment) ? plugin : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function agentSetupTarget(db: Db, environment: AgentEnvironmentRef | null | undefined) {
|
||||||
|
const plugin = environment ? await pluginForAgentEnvironment(db, environment) : null;
|
||||||
|
return plugin ? { pluginId: plugin.id, driverKey: environment!.config?.driverKey } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sameAgentSetupTarget(a: { pluginId: string; driverKey: unknown } | null, b: { pluginId: string; driverKey: unknown } | null) {
|
||||||
|
return a !== null && b !== null && a.pluginId === b.pluginId && a.driverKey === b.driverKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function environmentChangeRequiresAgentSetup(db: Db, before: AgentEnvironmentRef | null | undefined,
|
||||||
|
after: AgentEnvironmentRef | null | undefined, selectedPluginIds: string[] | null) {
|
||||||
|
const target = await agentSetupTarget(db, after);
|
||||||
|
if (!target) return false;
|
||||||
|
if (!selectedPluginIds?.includes(target.pluginId)) return true;
|
||||||
|
return !sameAgentSetupTarget(await agentSetupTarget(db, before), target);
|
||||||
|
}
|
||||||
|
|
||||||
/** Whether a saved environment change would give active agents a plugin that has not prepared them. */
|
/** Whether a saved environment change would give active agents a plugin that has not prepared them. */
|
||||||
export async function agentsNeedSetupForEnvironmentChange(db: Db, before: AgentEnvironmentRef | null | undefined,
|
export async function agentsNeedSetupForEnvironmentChange(db: Db, before: AgentEnvironmentRef | null | undefined,
|
||||||
after: AgentEnvironmentRef | null | undefined, users: { environmentId?: string; inheritsDefault: boolean }) {
|
after: AgentEnvironmentRef | null | undefined, users: { environmentId?: string; inheritsDefault: boolean }) {
|
||||||
const plugin = after ? await pluginForAgentEnvironment(db, after) : null;
|
const target = await agentSetupTarget(db, after);
|
||||||
if (!plugin || (before && (await pluginForAgentEnvironment(db, before))?.id === plugin.id)) return false;
|
if (!target) return false;
|
||||||
|
const previous = await agentSetupTarget(db, before);
|
||||||
|
if (sameAgentSetupTarget(previous, target)) return false;
|
||||||
const usesEnvironment = or(users.environmentId ? eq(agents.defaultEnvironmentId, users.environmentId) : undefined,
|
const usesEnvironment = or(users.environmentId ? eq(agents.defaultEnvironmentId, users.environmentId) : undefined,
|
||||||
users.inheritsDefault ? isNull(agents.defaultEnvironmentId) : undefined);
|
users.inheritsDefault ? isNull(agents.defaultEnvironmentId) : undefined);
|
||||||
if (!usesEnvironment) return false;
|
if (!usesEnvironment) return false;
|
||||||
|
const unprepared = previous?.pluginId === target.pluginId ? undefined
|
||||||
|
: sql`not coalesce(${agents.lifecycleRequiredPluginIds}, '[]'::jsonb) @> ${JSON.stringify([target.pluginId])}::jsonb`;
|
||||||
const [waiting] = await db.select({ id: agents.id }).from(agents).where(and(usesEnvironment,
|
const [waiting] = await db.select({ id: agents.id }).from(agents).where(and(usesEnvironment,
|
||||||
inArray(agents.lifecycleState, ["ready", "verifying"]),
|
inArray(agents.lifecycleState, ["ready", "verifying"]), unprepared)).limit(1);
|
||||||
sql`not coalesce(${agents.lifecycleRequiredPluginIds}, '[]'::jsonb) @> ${JSON.stringify([plugin.id])}::jsonb`)).limit(1);
|
|
||||||
return Boolean(waiting);
|
return Boolean(waiting);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { ApiError } from "../api/client";
|
|||||||
import { CodexLocalConfigFields } from "../adapters/codex-local/config-fields";
|
import { CodexLocalConfigFields } from "../adapters/codex-local/config-fields";
|
||||||
import type { AdapterConfigFieldsProps } from "../adapters/types";
|
import type { AdapterConfigFieldsProps } from "../adapters/types";
|
||||||
import { createAppQueryClient } from "../lib/query-client";
|
import { createAppQueryClient } from "../lib/query-client";
|
||||||
|
import { queryKeys } from "../lib/queryKeys";
|
||||||
import type { ConnectivityStore } from "../lib/connectivity";
|
import type { ConnectivityStore } from "../lib/connectivity";
|
||||||
|
|
||||||
const mockAgentsApi = vi.hoisted(() => ({
|
const mockAgentsApi = vi.hoisted(() => ({
|
||||||
@@ -340,6 +341,42 @@ describe("AgentConfigForm session replay masking", () => {
|
|||||||
expect(isBlockedFromReplay("WXYZ-1234", document.body)).toBe(true);
|
expect(isBlockedFromReplay("WXYZ-1234", document.body)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("holds the connection test while the agent is set up for its saved environment", async () => {
|
||||||
|
const container = document.createElement("div");
|
||||||
|
document.body.appendChild(container);
|
||||||
|
const root = createRoot(container);
|
||||||
|
roots.push(root);
|
||||||
|
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||||
|
const agent = makeAgent({ defaultEnvironmentId: "sandbox-1", status: "paused", lifecycleState: "resuming" });
|
||||||
|
mockAgentsApi.get.mockResolvedValue(agent);
|
||||||
|
await act(async () => {
|
||||||
|
root.render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ToastProvider>
|
||||||
|
<TooltipProvider>
|
||||||
|
<AgentConfigForm mode="edit" agent={agent} onSave={vi.fn()} hidePromptTemplate showAdapterTypeField={false}
|
||||||
|
showAdapterTestEnvironmentButton compactTestFeedback />
|
||||||
|
</TooltipProvider>
|
||||||
|
</ToastProvider>
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
const testButton = () => container.querySelector<HTMLButtonElement>('section[aria-label="Runtime test"] button');
|
||||||
|
expect(container.querySelector('section[aria-label="Runtime test"] h3')?.textContent).toBe("Test your agent");
|
||||||
|
expect(testButton()).toMatchObject({ disabled: true, textContent: "Run test" });
|
||||||
|
expect(testButton()?.querySelector("svg.animate-spin")).toBeNull();
|
||||||
|
await act(async () => { testButton()?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
|
||||||
|
expect(mockAgentsApi.testEnvironment).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
queryClient.setQueryData([...queryKeys.agents.detail(agent.id), "lifecycle", agent.companyId],
|
||||||
|
{ ...agent, status: "idle", lifecycleState: "ready" });
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
expect(testButton()).toMatchObject({ disabled: false, textContent: "Run test" });
|
||||||
|
});
|
||||||
|
|
||||||
it("offers Google Antigravity in the Harness dropdown, displays its logo, exposes Daytona and Unikraft environments, and saves native ACPX config", async () => {
|
it("offers Google Antigravity in the Harness dropdown, displays its logo, exposes Daytona and Unikraft environments, and saves native ACPX config", async () => {
|
||||||
mockEnvironmentsApi.list.mockResolvedValue([
|
mockEnvironmentsApi.list.mockResolvedValue([
|
||||||
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
makeEnvironment({ id: "local-1", name: "Local", driver: "local" }),
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { aiConnectionBindingSchema, aiRuntimeConnectionBindingSchema, isAiConnec
|
|||||||
import { testAgentSetup } from "@/lib/test-agent-setup";
|
import { testAgentSetup } from "@/lib/test-agent-setup";
|
||||||
import { setupEfforts } from "../lib/agent-setup-fields";
|
import { setupEfforts } from "../lib/agent-setup-fields";
|
||||||
import { RuntimeTestCard } from "./RuntimeTestCard";
|
import { RuntimeTestCard } from "./RuntimeTestCard";
|
||||||
|
import { agentSetupInProgress, useAgentLifecycleStatus } from "./AgentLifecycleStatus";
|
||||||
import { useState, useEffect, useRef, useMemo, useCallback, Children, isValidElement, type ReactNode } from "react";
|
import { useState, useEffect, useRef, useMemo, useCallback, Children, isValidElement, type ReactNode } from "react";
|
||||||
import type { AdapterConfigSection } from "../adapters/types";
|
import type { AdapterConfigSection } from "../adapters/types";
|
||||||
import { useConfigSchema } from "../adapters/schema-config-fields";
|
import { useConfigSchema } from "../adapters/schema-config-fields";
|
||||||
@@ -1456,9 +1457,12 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
|||||||
});
|
});
|
||||||
const [testActionPending, setTestActionPending] = useState(false);
|
const [testActionPending, setTestActionPending] = useState(false);
|
||||||
const [testActionError, setTestActionError] = useState<string | null>(null);
|
const [testActionError, setTestActionError] = useState<string | null>(null);
|
||||||
|
const lifecycle = useAgentLifecycleStatus(props.mode === "edit" ? props.agent : undefined);
|
||||||
|
const agentSettingUp = props.mode === "edit"
|
||||||
|
&& agentSetupInProgress(lifecycle.data?.lifecycleState ?? props.agent.lifecycleState);
|
||||||
const testActionLabel = "Test";
|
const testActionLabel = "Test";
|
||||||
const isSavePending = !isCreate && Boolean(props.isSaving);
|
const isSavePending = !isCreate && Boolean(props.isSaving);
|
||||||
const testEnvironmentDisabled = testActionPending || isSavePending || !selectedCompanyId;
|
const testEnvironmentDisabled = testActionPending || isSavePending || agentSettingUp || !selectedCompanyId;
|
||||||
|
|
||||||
// Drop a stale Test result when the adapter type or the effective environment
|
// Drop a stale Test result when the adapter type or the effective environment
|
||||||
// changes. A held result would keep the login affordance visible for a target
|
// changes. A held result would keep the login affordance visible for a target
|
||||||
@@ -1468,6 +1472,12 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
|||||||
const resetTestEnvironmentRef = useRef(testEnvironment.reset);
|
const resetTestEnvironmentRef = useRef(testEnvironment.reset);
|
||||||
resetTestEnvironmentRef.current = testEnvironment.reset;
|
resetTestEnvironmentRef.current = testEnvironment.reset;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!agentSettingUp) return;
|
||||||
|
resetTestEnvironmentRef.current();
|
||||||
|
setTestActionError(null);
|
||||||
|
}, [agentSettingUp]);
|
||||||
|
|
||||||
// Clear a stale Claude login claim when the adapter type or the effective
|
// Clear a stale Claude login claim when the adapter type or the effective
|
||||||
// environment changes. A login binds `CLAUDE_CODE_OAUTH_TOKEN` to one specific
|
// environment changes. A login binds `CLAUDE_CODE_OAUTH_TOKEN` to one specific
|
||||||
// environment. After the environment changes, the held claim and the fixed
|
// environment. After the environment changes, the held claim and the fixed
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ function pendingPhase(state?: AgentLifecycleState) {
|
|||||||
return state && state in phases ? phases[state as keyof typeof phases] : undefined;
|
return state && state in phases ? phases[state as keyof typeof phases] : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function agentSetupInProgress(state?: AgentLifecycleState) {
|
||||||
|
return state === "preparing" || state === "pausing" || state === "resuming";
|
||||||
|
}
|
||||||
|
|
||||||
export function agentLifecycleRefetchInterval(state?: AgentLifecycleState) {
|
export function agentLifecycleRefetchInterval(state?: AgentLifecycleState) {
|
||||||
return pendingPhase(state) ? 2_000 : 30_000;
|
return pendingPhase(state) ? 2_000 : 30_000;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user