diff --git a/doc/AGENT-LIFECYCLE.md b/doc/AGENT-LIFECYCLE.md index a28181b1420..0fd53948c33 100644 --- a/doc/AGENT-LIFECYCLE.md +++ b/doc/AGENT-LIFECYCLE.md @@ -139,9 +139,19 @@ The application supplies the worker driver at startup. `updateConfiguration` owns the transaction for an ordinary configuration update. The module locks the agent. The configuration service validates and prepares the patch. The module saves it and invalidates an old verification result when -execution configuration changes during setup. The service then updates dependent +execution configuration changes during verification. A change to instructions +alone keeps the verification. The service then updates dependent records and saves the configuration revision in the same transaction. +A change to the harness, model, credentials, or instructions does not restart +`preparing`. Preparation restarts only when the agent moves to an environment +that needs setup. There is no separate invalidation operation for callers. +A prepared setup draft waits in `verifying` with no background work. Edits keep +it prepared. If an edit means that the draft no longer needs preparation, the +draft pauses. When the draft becomes a hire on the same environment driver, a +prepared draft goes directly to verification. A draft that is still `preparing` +keeps its operation, and the hire verifies after that operation completes. A +hire that needs setup for another environment starts `preparing` again. Configuration writes reject caller-supplied lifecycle fields. For `updateAndTransition`, lifecycle owns the transaction and calls the same configuration operation. Both changes commit together. @@ -222,9 +232,10 @@ the agent. Saving an environment or the instance default that gives such a plugin to `ready` or `verifying` agents without that selection returns a conflict. The same applies -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. +when the change keeps the plugin but changes its driver; then every `ready`, +`preparing`, or `verifying` agent on the environment needs setup. A preparation +in progress belongs to the previous driver. 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. diff --git a/server/src/__tests__/dot-oauth-onboarding.test.ts b/server/src/__tests__/dot-oauth-onboarding.test.ts index 653f8d9e65d..c7c95d76e0d 100644 --- a/server/src/__tests__/dot-oauth-onboarding.test.ts +++ b/server/src/__tests__/dot-oauth-onboarding.test.ts @@ -45,7 +45,7 @@ describe("Dot onboarding with an operator-issued pairing capability", () => { } it("invalidates setup when a broker pairing is applied or revoked", async () => { - const f = await fixture(undefined, "preparing"); + const f = await fixture(undefined, "verifying"); const consent = await f.oauth.consent(f.id, { type: "board", source: "session", userId: f.userId }, { decision: "approve", companyId: f.company.id, allowWrites: false }); const tokens = await f.oauth.token({ grant_type: "authorization_code", client_id: f.client.client_id, diff --git a/server/src/lib/agent-records.ts b/server/src/lib/agent-records.ts index 8af5d18be73..b09bdf56ede 100644 --- a/server/src/lib/agent-records.ts +++ b/server/src/lib/agent-records.ts @@ -125,6 +125,22 @@ export function jsonEqual(left: unknown, right: unknown): boolean { return canonicalJson(left) === canonicalJson(right); } +const INSTRUCTION_CONFIGURATION_KEYS = [ + "instructionsBundleMode", + "instructionsRootPath", + "instructionsEntryFile", + "instructionsFilePath", + "agentsMdPath", + "promptTemplate", + "bootstrapPromptTemplate", +]; + +export function adapterConfigWithoutInstructions(adapterConfig: unknown) { + return adapterConfig && typeof adapterConfig === "object" && !Array.isArray(adapterConfig) + ? Object.fromEntries(Object.entries(adapterConfig).filter(([key]) => !INSTRUCTION_CONFIGURATION_KEYS.includes(key))) + : adapterConfig; +} + export function buildConfigSnapshot( row: Pick, ): AgentConfigSnapshot { diff --git a/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts b/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts index 85867e91d70..f27a97a3528 100644 --- a/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts @@ -289,6 +289,8 @@ const support = await getEmbeddedPostgresTestSupport(); 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 db.update(agents).set({ lifecycleState: "preparing", status: "paused" }).where(eq(agents.id, id)); + 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(); diff --git a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts index 638f77aa416..c03a63a7421 100644 --- a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts @@ -1030,6 +1030,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu it("fences verification when the saved configuration changes", async () => { const lifecycle = createAgentLifecycle(db); const store = createLifecycleStore(db); const agent = await hire(); + await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, agent.id)); const claimed = (await store.claim(agent.id, "configuration-test", new Date()))!; await store.setRequiredPlugins(claimed, "configuration-test", []); await agentConfiguration(db).update(agent.id, { adapterConfig: { command: "echo" } }); @@ -1040,6 +1041,10 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu it("invalidates only changed execution configuration during setup", async () => { const lifecycle = createAgentLifecycle(db); const agent = await hire(); + const preparing = await current(agent.id); + await lifecycle.updateConfiguration(agent.id, { adapterConfig: { command: "true" } }); + expect(await current(agent.id)).toMatchObject({ lifecycleVersion: preparing.lifecycleVersion, lifecycleOperation: preparing.lifecycleOperation }); + await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, agent.id)); const before = await current(agent.id); await lifecycle.updateConfiguration(agent.id, { name: "Profile only" }); await lifecycle.updateConfiguration(agent.id, { adapterConfig: before.adapterConfig }); @@ -1111,6 +1116,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu it("rolls back configuration and verification invalidation in the binding transaction", async () => { const agent = await hire(); + await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, agent.id)); const before = await current(agent.id); await expect(updateAgentConfigurationInTransaction(db, agent.id, { name: "Uncommitted" })) .rejects.toThrow("requires a database transaction"); diff --git a/server/src/modules/agent-lifecycle/__tests__/setup.test.ts b/server/src/modules/agent-lifecycle/__tests__/setup.test.ts index 8c4ded0a840..33825517736 100644 --- a/server/src/modules/agent-lifecycle/__tests__/setup.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/setup.test.ts @@ -3,7 +3,7 @@ import express from "express"; import request from "supertest"; import { eq } from "drizzle-orm"; import { agents, companies, companyMemberships, principalPermissionGrants, environments, plugins, createDb, type Db } from "@paperclipai/db"; -import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; import { createAgentLifecycle, configureAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js"; import { agentService as agentConfiguration } from "../../../services/agents.js"; @@ -20,7 +20,9 @@ const support = await getEmbeddedPostgresTestSupport(); let db: Db; let companyId: string; const workers: ReturnType[] = []; + const releases: (() => void)[] = []; beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-agent-setup-"); db = createDb(database.connectionString); }, 90_000); + afterEach(() => { for (const release of releases.splice(0)) release(); }); afterAll(async () => { for (const work of workers) await work.stop(); await database?.cleanup(); }); beforeEach(async () => { for (const work of workers) await work.stop(); @@ -57,18 +59,31 @@ const support = await getEmbeddedPostgresTestSupport(); await expect(lifecycle.requestHire(companyId, { id, name: "Early agent" }, { setupAgentId: id })).rejects.toThrow("no longer available"); }); - it("prepares agent-dependent drafts, stays idle until finish, and invalidates changed environments", async () => { + async function agentEnvironment(hold?: () => Promise) { const pluginId = randomUUID(), environmentId = randomUUID(); await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "agent-environment-test", version: "1.0.0", status: "ready", manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"], - environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true }] } as never }); - await db.insert(environments).values({ id: environmentId, name: "Agent-owned test computer", driver: "plugin", status: "active", - config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } }); - const call = vi.fn(async (_id, _method, input) => ({ operationId: input.operationId, version: input.version, status: "complete" })); + environmentDrivers: ["tasks", "desktop"].map(driverKey => ({ driverKey, requiresAgent: true, supportsTasks: true })) } as never }); + const environment = async (id: string, driverKey: string) => { + await db.insert(environments).values({ id, name: `Agent-owned ${id}`, driver: "plugin", status: "active", + config: { pluginKey: pluginId, driverKey, driverConfig: {} } }); + return id; + }; + await environment(environmentId, "tasks"); + const call = vi.fn(async (_id, _method, input) => { + if (input.phase === "preparing") await hold?.(); + return { operationId: input.operationId, version: input.version, status: "complete" }; + }); + const runHost = vi.fn(async () => "complete"); const driver = createLifecycleDriver(db, { call } as never); - const runHost = vi.fn(async () => "complete" as const); - const work = configureAgentLifecycle(db, { ...driver, requiredPluginIds: async () => [pluginId], runHost }); + const work = configureAgentLifecycle(db, { ...driver, runHost }); workers.push(work); + const phases = () => call.mock.calls.map(([, , request]) => request.phase); + return { pluginId, environmentId, environment, call, runHost, work, phases }; + } + + it("prepares agent-dependent drafts, stays idle until finish, and invalidates changed environments", async () => { + const { environmentId, call, runHost, work } = await agentEnvironment(); const lifecycle = createAgentLifecycle(db); const id = randomUUID(); const input = { id, name: "Early computer", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }; @@ -130,6 +145,92 @@ const support = await getEmbeddedPostgresTestSupport(); expect(runHost).not.toHaveBeenCalled(); }); + it("keeps a prepared draft prepared while its harness, model, sign-in and instructions change", async () => { + const { environmentId, environment, work, phases } = await agentEnvironment(); + const lifecycle = createAgentLifecycle(db); + const id = randomUUID(); + await lifecycle.requestHire(companyId, { id, name: "Prepared", adapterType: "paperclip_runner", + adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }, { setupOnly: true, runnerResolved: true }); + await work.process(id); + const prepared = await current(id); + expect(prepared.lifecycleState).toBe("verifying"); + await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "claude", model: "changed", env: { TOKEN: { type: "plain", value: "saved" } } } }); + await lifecycle.updateConfiguration(id, { runtimeConfig: { heartbeat: { enabled: false } } }); + await lifecycle.updateConfiguration(id, { defaultEnvironmentId: await environment(randomUUID(), "tasks") }); + await work.process(id); + expect(await current(id)).toMatchObject({ lifecycleState: "verifying", lifecycleVersion: prepared.lifecycleVersion, + lifecycleOperation: { id: prepared.lifecycleOperation!.id } }); + expect(phases()).toEqual(["preparing"]); + await lifecycle.updateConfiguration(id, { defaultEnvironmentId: await environment(randomUUID(), "desktop") }); + expect((await current(id)).lifecycleState).toBe("preparing"); + await work.process(id); + expect(phases()).toEqual(["preparing", "preparing"]); + expect((await current(id)).lifecycleState).toBe("verifying"); + }); + + it("verifies a prepared draft at hire without preparing it again", async () => { + const { environmentId, environment, work, phases } = await agentEnvironment(); + const lifecycle = createAgentLifecycle(db); + const hire = async (finalEnvironmentId: string) => { + const id = randomUUID(); + const input = { id, name: "Hired", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }; + await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true }); + await work.process(id); + const prepared = await current(id); + await lifecycle.requestHire(companyId, { ...input, adapterConfig: { provider: "claude", model: "chosen" }, status: "idle", + defaultEnvironmentId: finalEnvironmentId }, { setupAgentId: id, runnerResolved: true, responsibleUserId: "owner" }); + return { prepared, hired: await current(id) }; + }; + const same = await hire(environmentId); + expect(same.hired).toMatchObject({ lifecycleState: "verifying", lifecycleHolds: [], lifecycleOperation: { responsibleUserId: "owner" } }); + expect(same.hired.lifecycleVersion).toBeGreaterThan(same.prepared.lifecycleVersion); + expect(same.hired.lifecycleOperation!.id).not.toBe(same.prepared.lifecycleOperation!.id); + await work.process(same.hired.id); + expect((await current(same.hired.id)).lifecycleState).toBe("ready"); + expect(phases()).toEqual(["preparing", "verifying"]); + expect((await hire(await environment(randomUUID(), "desktop"))).hired.lifecycleState).toBe("preparing"); + }); + + it("joins the preparation in progress when a draft is edited and hired", async () => { + let entered!: () => void, release!: () => void; + const started = new Promise(resolve => { entered = resolve; }); + const held = new Promise(resolve => { release = resolve; }); + const { environmentId, work, phases } = await agentEnvironment(() => { entered(); return held; }); + releases.push(release); + const lifecycle = createAgentLifecycle(db); + const id = randomUUID(); + const input = { id, name: "Joined", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }; + await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true }); + const processing = work.process(id); + await started; + const preparing = await current(id); + await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "claude" } }); + await lifecycle.requestHire(companyId, { ...input, adapterConfig: { provider: "claude" }, status: "idle" }, + { setupAgentId: id, runnerResolved: true, responsibleUserId: "owner" }); + expect(await current(id)).toMatchObject({ lifecycleState: "preparing", lifecycleHolds: [], lifecycleVersion: preparing.lifecycleVersion, + lifecycleOperation: { id: preparing.lifecycleOperation!.id, leaseOwner: preparing.lifecycleOperation!.leaseOwner, responsibleUserId: "owner" } }); + release(); + await processing; + expect(await current(id)).toMatchObject({ lifecycleState: "ready", lifecycleHolds: [], lifecycleOperation: { responsibleUserId: "owner" } }); + expect(phases()).toEqual(["preparing", "verifying"]); + }); + + it("keeps a running verification when only instructions change", async () => { + const { environmentId, work } = await agentEnvironment(); + const lifecycle = createAgentLifecycle(db); + const id = randomUUID(); + await lifecycle.requestHire(companyId, { id, name: "Verified", adapterType: "paperclip_runner", + adapterConfig: { provider: "codex", promptTemplate: "Old" }, defaultEnvironmentId: environmentId, status: "idle" }, { runnerResolved: true }); + await db.update(agents).set({ lifecycleState: "verifying" }).where(eq(agents.id, id)); + const verifying = await current(id); + await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", instructionsBundleMode: "managed", + instructionsRootPath: "/managed", instructionsEntryFile: "AGENTS.md", instructionsFilePath: "/managed/AGENTS.md" } }); + expect(await current(id)).toMatchObject({ lifecycleVersion: verifying.lifecycleVersion, + adapterConfig: { instructionsFilePath: "/managed/AGENTS.md" }, lifecycleOperation: { id: verifying.lifecycleOperation!.id } }); + await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", model: "changed" } }); + expect((await current(id)).lifecycleVersion).toBe(verifying.lifecycleVersion + 1); + }); + it("lets only the setup creator configure and retry a stopping draft with creation permission", async () => { await db.insert(companyMemberships).values(["setup-owner", "setup-other"].map(principalId => ({ companyId, principalType: "user", principalId, membershipRole: "member" }))); diff --git a/server/src/modules/agent-lifecycle/adapters/configuration.ts b/server/src/modules/agent-lifecycle/adapters/configuration.ts index 5a4554de98f..788341b1165 100644 --- a/server/src/modules/agent-lifecycle/adapters/configuration.ts +++ b/server/src/modules/agent-lifecycle/adapters/configuration.ts @@ -4,7 +4,7 @@ import { agentConfigurationRevision } from "../../../lib/agent-configuration-rev import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { agents, type Db } from "@paperclipai/db"; -import { agentRecordQueries, AGENT_CONFIGURATION_FIELDS, jsonEqual, type AgentConfigurationPatch, type UpdateAgentOptions } from "../../../lib/agent-records.js"; +import { agentRecordQueries, adapterConfigWithoutInstructions, AGENT_CONFIGURATION_FIELDS, jsonEqual, type AgentConfigurationPatch, type UpdateAgentOptions } from "../../../lib/agent-records.js"; import type { ActivityPublication } from "../../../types/activity-publication.js"; import { AgentLifecycleConflict, canConfigureAgentConnection } from "../domain/policy.js"; import type { LifecycleEffects } from "./effects.js"; @@ -24,21 +24,29 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects } const patch = await effects.prepareConfiguration(tx, current, data, options); assertConfigurationFields(patch); - 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])); - const needsEnvironmentSetup = ["ready", "verifying"].includes(current.lifecycleState) - && Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId") - && patch.defaultEnvironmentId !== current.defaultEnvironmentId + const patched = (key: K) => + Object.prototype.hasOwnProperty.call(patch, key) && !jsonEqual(patch[key], current[key]); + const environmentChanged = patched("defaultEnvironmentId"); + const changed = environmentChanged || patched("adapterType") || patched("adapterConfig") || patched("runtimeConfig"); + const executionChanged = environmentChanged || patched("adapterType") || patched("runtimeConfig") || patched("adapterConfig") + && !jsonEqual(adapterConfigWithoutInstructions(patch.adapterConfig), adapterConfigWithoutInstructions(current.adapterConfig)); + const settingUp = current.lifecycleHolds.includes("setup"); + const needsEnvironmentSetup = environmentChanged && ["ready", "preparing", "verifying"].includes(current.lifecycleState) && await effects.environmentChangeRequiresSetup(tx, current.defaultEnvironmentId, patch.defaultEnvironmentId, current.lifecycleRequiredPluginIds); const pauseForEnvironment = needsEnvironmentSetup && current.lifecycleState === "ready"; - const prepareEnvironment = needsEnvironmentSetup && !current.lifecycleHolds.includes("setup"); - const prepareSetup = changed && current.lifecycleHolds.length === 1 && current.lifecycleHolds[0] === "setup" - && ["paused", "preparing", "verifying"].includes(current.lifecycleState) + const draft = changed && current.lifecycleHolds.length === 1 && settingUp + && ["paused", "preparing", "verifying"].includes(current.lifecycleState); + const draftNeedsPreparation = draft && await effects.setupRequiresPreparation(tx, current.companyId, Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId") ? patch.defaultEnvironmentId : current.defaultEnvironmentId, { adapterType: patch.adapterType ?? current.adapterType, adapterConfig: Object.prototype.hasOwnProperty.call(patch, "adapterConfig") ? patch.adapterConfig : current.adapterConfig }); - const invalidate = changed && (["preparing", "verifying", "resuming"].includes(current.lifecycleState) || prepareSetup || pauseForEnvironment); + const prepareSetup = draftNeedsPreparation && (current.lifecycleState === "paused" || needsEnvironmentSetup); + const stopSetup = draft && !draftNeedsPreparation && current.lifecycleState !== "paused"; + const prepareEnvironment = needsEnvironmentSetup && !settingUp && !pauseForEnvironment; + const reverify = executionChanged && !settingUp && current.lifecycleState === "verifying"; + const invalidate = prepareSetup || stopSetup || prepareEnvironment || pauseForEnvironment || reverify + || changed && current.lifecycleState === "resuming"; if(prepareSetup&&!canConfigureAgentConnection(current))await effects.beforeConnectionEligibilityRestore?.(tx,current.companyId,current.id); if (pauseForEnvironment) await effects.beforeStatusChange(tx, current.companyId, id, current.status, "paused"); if (invalidate) await effects.notifyWork(tx); @@ -46,8 +54,7 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects lifecycleVersion: current.lifecycleVersion + 1, lifecycleError: null, ...(prepareSetup || prepareEnvironment ? { lifecycleState: "preparing" as const } : {}), ...(pauseForEnvironment ? { lifecycleState: "pausing" as const, status: "paused", pausedAt: new Date() } : {}), - ...(!prepareSetup && current.lifecycleHolds.includes("setup") && ["preparing", "verifying"].includes(current.lifecycleState) - ? { lifecycleState: "pausing" as const } : {}), + ...(stopSetup ? { lifecycleState: "pausing" as const } : {}), lifecycleOperation: { ...current.lifecycleOperation!, id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, leaseOwner: undefined, leaseUntil: undefined, leaseHolder: undefined, retryAt: undefined, retryRequired: undefined, verificationFailures: undefined, diff --git a/server/src/modules/agent-lifecycle/adapters/records.ts b/server/src/modules/agent-lifecycle/adapters/records.ts index 082716afd83..67034243342 100644 --- a/server/src/modules/agent-lifecycle/adapters/records.ts +++ b/server/src/modules/agent-lifecycle/adapters/records.ts @@ -38,20 +38,30 @@ export function agentRecords(db: Db, effects: LifecycleEffects) { const companyHolds = company?.status === "paused" ? ["company_paused"] : company?.status === "archived" ? ["company_archived"] : []; const holds = [...(status === "paused" ? [pauseReason ?? "manual"] : []), ...companyHolds]; const prepareSetup = options?.setupOnly && !companyHolds.length && await effects.setupRequiresPreparation(txDb, companyId, prepared.defaultEnvironmentId, prepared); + const keepsPreparation = setup !== undefined && status !== "pending_approval" && status !== "terminated" && !holds.length + && (setup.lifecycleState === "preparing" || setup.lifecycleState === "verifying") + && !await effects.environmentChangeRequiresSetup(txDb, setup.defaultEnvironmentId, + prepared.defaultEnvironmentId === undefined ? setup.defaultEnvironmentId : prepared.defaultEnvironmentId, setup.lifecycleRequiredPluginIds); + const joinsPreparation = keepsPreparation && setup.lifecycleState === "preparing" && setup.lifecycleOperation !== null; const lifecycleState = status === "pending_approval" ? "pending_approval" : status === "terminated" ? "terminated" - : prepareSetup ? "preparing" : status === "paused" ? "paused" : companyHolds.length ? "pausing" : "preparing"; - if (lifecycleState === "preparing" || lifecycleState === "pausing") await effects.notifyWork(tx); + : prepareSetup ? "preparing" : status === "paused" ? "paused" : companyHolds.length ? "pausing" + : keepsPreparation && setup.lifecycleState === "verifying" ? "verifying" : "preparing"; + if (lifecycleState === "preparing" || lifecycleState === "verifying" || lifecycleState === "pausing") await effects.notifyWork(tx); const createdStatus=status === "pending_approval" ? "pending_approval" : status === "terminated" ? "terminated" : "paused"; + const responsibleUserId = options?.responsibleUserId ?? options?.createdByUserId; const values: typeof agents.$inferInsert = { ...prepared, ...(setup ? { permissions: preserveAgentInteractionPermissions(setup.permissions, prepared.permissions) } : {}), createdByUserId: setup?.createdByUserId ?? options?.createdByUserId ?? null, lifecycleState, - lifecycleVersion: setup ? setup.lifecycleVersion + 1 : 1, + lifecycleVersion: !setup ? 1 : joinsPreparation ? setup.lifecycleVersion : setup.lifecycleVersion + 1, lifecycleHolds: holds, + lifecycleError: null, pauseReason: holds[0] ?? null, pausedAt: holds.length ? new Date() : null, - lifecycleOperation: { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, resumeState: "preparing" as const, responsibleUserId: options?.responsibleUserId ?? options?.createdByUserId }, + lifecycleOperation: joinsPreparation + ? { ...setup.lifecycleOperation!, retryAt: undefined, responsibleUserId } + : { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, resumeState: "preparing" as const, responsibleUserId }, status: createdStatus, companyId, }; diff --git a/server/src/services/plugin-environment-driver.ts b/server/src/services/plugin-environment-driver.ts index b12965e0372..e478c696278 100644 --- a/server/src/services/plugin-environment-driver.ts +++ b/server/src/services/plugin-environment-driver.ts @@ -86,10 +86,11 @@ export async function agentsNeedSetupForEnvironmentChange(db: Db, before: AgentE const usesEnvironment = or(users.environmentId ? eq(agents.defaultEnvironmentId, users.environmentId) : undefined, users.inheritsDefault ? isNull(agents.defaultEnvironmentId) : undefined); if (!usesEnvironment) return false; - const unprepared = previous?.pluginId === target.pluginId ? undefined + const changesDriver = previous?.pluginId === target.pluginId; + const unprepared = changesDriver ? 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, - inArray(agents.lifecycleState, ["ready", "verifying"]), unprepared)).limit(1); + inArray(agents.lifecycleState, changesDriver ? ["ready", "preparing", "verifying"] : ["ready", "verifying"]), unprepared)).limit(1); return Boolean(waiting); }