diff --git a/doc/AGENT-LIFECYCLE.md b/doc/AGENT-LIFECYCLE.md index 8da664e1a35..a28181b1420 100644 --- a/doc/AGENT-LIFECYCLE.md +++ b/doc/AGENT-LIFECYCLE.md @@ -198,10 +198,16 @@ plugins are selected for all agents, including a sandbox provider that declares `requiresAgent: true`. 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 -needs a new plugin automatically pauses execution, waits for the host and -existing plugins to stop, resumes with the new plugin, and verifies the saved -configuration before admitting work. The change and pause request commit +`preparing` or `resuming` step. The plugin prepares the agent for the +environment's driver: each request carries `environmentDriverKey`, and nothing +else about the environment. So an agent needs setup again when it moves to an +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, 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, @@ -215,8 +221,22 @@ before the change; an unauthorized request cannot save the environment or pause 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. Pause those agents, -save the change, and then resume them. +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. + +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: diff --git a/doc/runner-internals.md b/doc/runner-internals.md index 9bf3116f7e2..9fa381b7353 100644 --- a/doc/runner-internals.md +++ b/doc/runner-internals.md @@ -155,8 +155,8 @@ Saved OpenCode agents keep their runner and runtime policies. 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 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 -pauses execution, waits for stop completion, starts the required resources, and +Moving a ready agent to an environment that needs a new plugin, or another +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 still apply; the user does not need to pause or resume the agent for this move. Setup saves the draft and environment, runs its 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 96a87845273..85867e91d70 100644 --- a/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts @@ -9,6 +9,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vites import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; import { configureAgentLifecycle, createAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.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 { assertAgentsReadyForEnvironmentChange } from "../../../services/plugin-environment-driver.js"; import { createLifecycleStore } from "../adapters/postgres.js"; @@ -22,6 +23,8 @@ const support = await getEmbeddedPostgresTestSupport(); let boundPluginId: string; let boundEnvironmentId: string; let otherEnvironmentId: string; + let siblingEnvironmentId: string; + let twinEnvironmentId: string; const workers: ReturnType[] = []; 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.update(instanceSettings).set({ defaultEnvironmentId: null }); 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(plugins).values({ id: boundPluginId, pluginKey: boundPluginId, packageName: "bound", 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 }); + environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true }, + { driverKey: "isolated", requiresAgent: true, supportsTasks: true }] } as never }); await db.insert(environments).values([ { 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: 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(); }); + 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 () => { const id = await agent(boundEnvironmentId, { lifecycleRequiredPluginIds: [boundPluginId] }); await agentConfiguration(db).update(id, { defaultEnvironmentId: otherEnvironmentId }); diff --git a/server/src/modules/agent-lifecycle/adapters/configuration.ts b/server/src/modules/agent-lifecycle/adapters/configuration.ts index de618971dea..5a4554de98f 100644 --- a/server/src/modules/agent-lifecycle/adapters/configuration.ts +++ b/server/src/modules/agent-lifecycle/adapters/configuration.ts @@ -26,12 +26,12 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects 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 needsNewPlugin = ["ready", "verifying"].includes(current.lifecycleState) + const needsEnvironmentSetup = ["ready", "verifying"].includes(current.lifecycleState) && Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId") && patch.defaultEnvironmentId !== current.defaultEnvironmentId - && await effects.environmentRequiresNewPlugin(tx, patch.defaultEnvironmentId, current.lifecycleRequiredPluginIds); - const pauseForEnvironment = needsNewPlugin && current.lifecycleState === "ready"; - const prepareEnvironment = needsNewPlugin && !current.lifecycleHolds.includes("setup"); + && 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) && await effects.setupRequiresPreparation(tx, current.companyId, diff --git a/server/src/modules/agent-lifecycle/adapters/effects.ts b/server/src/modules/agent-lifecycle/adapters/effects.ts index 486e17ea5f4..657ce360d8e 100644 --- a/server/src/modules/agent-lifecycle/adapters/effects.ts +++ b/server/src/modules/agent-lifecycle/adapters/effects.ts @@ -8,7 +8,8 @@ import type { ActivityPublication } from "../../../types/activity-publication.js export interface LifecycleEffects { setupRequiresPreparation(db: Db, companyId: string, environmentId: string | null | undefined, profile: Pick): Promise; - environmentRequiresNewPlugin(db: Db, environmentId: string | null | undefined, selectedPluginIds: string[] | null): Promise; + environmentChangeRequiresSetup(db: Db, beforeEnvironmentId: string | null | undefined, afterEnvironmentId: string | null | undefined, + selectedPluginIds: string[] | null): Promise; notifyWork(db: Db): Promise; /** The calling controller process, stamped on a lifecycle lease so restart recovery can settle a dead holder. */ leaseHolder?(): Record | null; diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.ts index 9ddf1b2a6ff..9a1f8859add 100644 --- a/server/src/services/agent-environment-test.ts +++ b/server/src/services/agent-environment-test.ts @@ -24,7 +24,7 @@ import { validateAiApiKey } from "./ai-api-key-test.js"; import { probeCopilotExecutionTarget } from "./copilot-connection-probe.js"; import type { PluginWorkerManager } from "./plugin-worker-manager.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 | null => value && typeof value === "object" && !Array.isArray(value) ? value as Record : null; function finishManagedConnectionTest(adapterType: string, context: AdapterEnvironmentTestContext, result: AdapterEnvironmentTestResult): AdapterEnvironmentTestResult { 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 // operator can inspect the exact sandbox from the provider dashboard while // 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, - requiresApproval: companies.requireBoardApprovalForNewAgents }).from(agents) + environmentId: agents.defaultEnvironmentId, requiresApproval: companies.requireBoardApprovalForNewAgents }).from(agents) .innerJoin(companies, eq(companies.id, agents.companyId)) .where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId))) : []; 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.", }], 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: [{ 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." : "The agent computer is being prepared. Test the connection when preparation finishes.", }], 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" ? { @@ -294,7 +303,9 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin level: "error", message: `Could not acquire a lease for environment "${environment.name}".`, 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, diff --git a/server/src/services/agent-lifecycle.ts b/server/src/services/agent-lifecycle.ts index 1f4cb399ab2..1b198ac62a4 100644 --- a/server/src/services/agent-lifecycle.ts +++ b/server/src/services/agent-lifecycle.ts @@ -28,7 +28,7 @@ import { applyAgentPolicyHoldsInTransaction } from "../modules/agent-lifecycle/i import { trackIdleWork } from "./task-admission.js"; import { environmentService } from "./environments.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"; 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"); return true; }, - async environmentRequiresNewPlugin(db, environmentId, selectedPluginIds) { - const id = environmentId ?? (await instanceSettingsService(db).get()).defaultEnvironmentId; - const environment = id ? await environmentService(db).getById(id) : null; - const plugin = environment ? await pluginForAgentEnvironment(db, environment) : null; - return plugin !== null && !selectedPluginIds?.includes(plugin.id); + async environmentChangeRequiresSetup(db, beforeEnvironmentId, afterEnvironmentId, selectedPluginIds) { + const instanceDefault = async () => (await instanceSettingsService(db).get()).defaultEnvironmentId; + const resolve = async (id: string | null | undefined) => { + const resolved = id ?? await instanceDefault(); + 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), leaseHolder: () => currentControllerProcessStamp(), diff --git a/server/src/services/plugin-environment-driver.ts b/server/src/services/plugin-environment-driver.ts index 14f03c53b14..b12965e0372 100644 --- a/server/src/services/plugin-environment-driver.ts +++ b/server/src/services/plugin-environment-driver.ts @@ -59,17 +59,37 @@ export async function pluginForAgentEnvironment(db: Db, environment: AgentEnviro 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. */ export async function agentsNeedSetupForEnvironmentChange(db: Db, before: AgentEnvironmentRef | null | undefined, after: AgentEnvironmentRef | null | undefined, users: { environmentId?: string; inheritsDefault: boolean }) { - const plugin = after ? await pluginForAgentEnvironment(db, after) : null; - if (!plugin || (before && (await pluginForAgentEnvironment(db, before))?.id === plugin.id)) return false; + const target = await agentSetupTarget(db, after); + 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, users.inheritsDefault ? isNull(agents.defaultEnvironmentId) : undefined); 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, - inArray(agents.lifecycleState, ["ready", "verifying"]), - sql`not coalesce(${agents.lifecycleRequiredPluginIds}, '[]'::jsonb) @> ${JSON.stringify([plugin.id])}::jsonb`)).limit(1); + inArray(agents.lifecycleState, ["ready", "verifying"]), unprepared)).limit(1); return Boolean(waiting); } diff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsx index d5a2931be4e..78af8708765 100644 --- a/ui/src/components/AgentConfigForm.render.test.tsx +++ b/ui/src/components/AgentConfigForm.render.test.tsx @@ -14,6 +14,7 @@ import { ApiError } from "../api/client"; import { CodexLocalConfigFields } from "../adapters/codex-local/config-fields"; import type { AdapterConfigFieldsProps } from "../adapters/types"; import { createAppQueryClient } from "../lib/query-client"; +import { queryKeys } from "../lib/queryKeys"; import type { ConnectivityStore } from "../lib/connectivity"; const mockAgentsApi = vi.hoisted(() => ({ @@ -340,6 +341,42 @@ describe("AgentConfigForm session replay masking", () => { 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( + + + + + + + , + ); + }); + await flushReact(); + const testButton = () => container.querySelector('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 () => { mockEnvironmentsApi.list.mockResolvedValue([ makeEnvironment({ id: "local-1", name: "Local", driver: "local" }), diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index edbaf708eae..5fbede7cdbe 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -19,6 +19,7 @@ import { aiConnectionBindingSchema, aiRuntimeConnectionBindingSchema, isAiConnec import { testAgentSetup } from "@/lib/test-agent-setup"; import { setupEfforts } from "../lib/agent-setup-fields"; import { RuntimeTestCard } from "./RuntimeTestCard"; +import { agentSetupInProgress, useAgentLifecycleStatus } from "./AgentLifecycleStatus"; import { useState, useEffect, useRef, useMemo, useCallback, Children, isValidElement, type ReactNode } from "react"; import type { AdapterConfigSection } from "../adapters/types"; import { useConfigSchema } from "../adapters/schema-config-fields"; @@ -1456,9 +1457,12 @@ export function AgentConfigForm(props: AgentConfigFormProps) { }); const [testActionPending, setTestActionPending] = useState(false); const [testActionError, setTestActionError] = useState(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 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 // 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); 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 // environment changes. A login binds `CLAUDE_CODE_OAUTH_TOKEN` to one specific // environment. After the environment changes, the held claim and the fixed diff --git a/ui/src/components/AgentLifecycleStatus.tsx b/ui/src/components/AgentLifecycleStatus.tsx index 51c87c63e4e..64c39aab0ce 100644 --- a/ui/src/components/AgentLifecycleStatus.tsx +++ b/ui/src/components/AgentLifecycleStatus.tsx @@ -25,6 +25,10 @@ function pendingPhase(state?: AgentLifecycleState) { 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) { return pendingPhase(state) ? 2_000 : 30_000; }