AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(agents): deleting an agent while a flow that uses it is being published no longer breaks that flow (#15932)
Hazem Adel57bc8988ea3f
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.mdindex 1bd7ebe3813..f3942579d85 100644--- a/brain/knowledge/ai-intelligence/ai-agents.md+++ b/brain/knowledge/ai-intelligence/ai-agents.md@@ -31,6 +31,7 @@ Three things follow. `run_agent` has two modes: pointed at a saved agent (`agent### Gotchas+- **Deleting an agent locks its row before it checks for published flows.** `agentService.delete` takes `FOR UPDATE` on the row (`lockedAgentInProjectOrThrow`) and only then runs the `NOT EXISTS` delete as a fresh statement. Publishing takes `FOR SHARE` in `assertAgentsResolveInProject`. A bare `DELETE ... WHERE NOT EXISTS` is not enough: if it blocks on a publisher's `FOR SHARE`, it wakes with the snapshot it started with and deletes an agent the publish just linked. The integration tests run on PGlite, one connection, so the race cannot be reproduced there; the tests assert the lock modes are requested instead.- **A managed agent row or Run Agent step stores a tier id (`smart`) from ENG-754 on; nothing converts the rows saved before.** `AIModelSelector` (`web/src/features/agents/ai-model/`) lists the published flow tiers by id for the managed provider and never calls `/models` for it; a blank picker pre-fills the published `flow.defaultTierId` once the tiers query settles (it used to take the first tier, Fast), and `withDefaultModel` (`agent-service.ts`) seeds the same default tier id on create. Own-key providers still store concrete ids: `resolveNamedModelId` passes their name through verbatim, so a tier id there would reach the provider as a model name. An older row keeps its concrete id: it runs that model (slash rule), shows the raw id in the picker, and does not follow a re-point until the ENG-753 migration.- **A flow-surface run takes its thinking budget from the tier it names, not the default tier.** `resolveRunTier` (`agent-model-resolution.ts`) builds `config.tier` for FLOW_STEP and AGENT runs: a managed tier id gives that tier's `thinkingBudget`, `id` and `modelId`; a concrete id, an own-key model, a tier the file dropped, or no model at all gives the flow default, as every flow-surface run did before ENG-754. So a Heavy agent thinks at Heavy's budget and reports `premium` in `chat.tier`, while a Heavy row saved as `anthropic/claude-opus-4.8` still thinks at Expert's until it is migrated.- **A chat turn's data lives in jsonb, so recording something per turn needs no migration.** `agent_conversation.messages` is a `jsonb` column and each entry is a `PersistedAgentMessageSchema`, which already carries optional per-turn fields (`thinkingDurationMs`, `feedback`). Adding another optional one is a zod field plus a `@activepieces/shared` patch bump — no column, no migration, no rollback flag. The conversation row itself only has `modelName`, which is why "record it on the conversation" is usually the wrong instinct: a user can switch tier mid-conversation, so anything that describes one turn belongs on the message, not the row.diff --git a/packages/server/api/src/app/ee/agent/agent-service.ts b/packages/server/api/src/app/ee/agent/agent-service.tsindex 1beb39b4a4d..da6769b20ed 100644--- a/packages/server/api/src/app/ee/agent/agent-service.ts+++ b/packages/server/api/src/app/ee/agent/agent-service.ts@@ -302,14 +302,17 @@ export const agentService = (log: FastifyBaseLogger) => ({const agent = await this.getOneOrThrow({ id, projectId, userId })await assertMayRemoveFromProject({ agent, projectId, userId, log })const blocking = publishedFlowVersionsUsingAgent({ projectId, agentExternalId: agent.externalId, alias: 'blocking_version' })- const deleted = await agentRepo()- .createQueryBuilder()- .delete()- .where('"id" = :id AND "projectId" = :projectId', { id, projectId })- .andWhere(`NOT EXISTS (${blocking.getQuery()})`)- .setParameters(blocking.getParameters())- .returning('id')- .execute()+ const deleted = await transaction(async (entityManager) => {+ await lockedAgentInProjectOrThrow({ entityManager, id, projectId })+ return entityManager.getRepository(AgentEntity)+ .createQueryBuilder()+ .delete()+ .where('"id" = :id AND "projectId" = :projectId', { id, projectId })+ .andWhere(`NOT EXISTS (${blocking.getQuery()})`)+ .setParameters(blocking.getParameters())+ .returning('id')+ .execute()+ })const deletedRows: unknown[] = deleted.raw ?? []if (deletedRows.length === 0) {diff --git a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts b/packages/server/api/test/integration/ee/agent/agent-controller.test.tsindex 9b82616d8aa..73bcc68493f 100644--- a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts+++ b/packages/server/api/test/integration/ee/agent/agent-controller.test.ts@@ -1,7 +1,8 @@import { AIProviderName, apId, Permission, RoleType } from '@activepieces/core-utils'-import { AgentIcon, AgentRunSource, AgentToolType, AgentVisibility, ColorName, DefaultProjectRole, FlowStatus, FlowVersionState, KnowledgeBaseSourceType } from '@activepieces/shared'+import { AgentIcon, AgentPieceProps, AgentRunSource, AgentToolType, AgentVisibility, AI_PIECE_NAME, ColorName, DefaultProjectRole, FlowActionType, FlowStatus, FlowTriggerType, FlowVersionState, KnowledgeBaseSourceType } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'+import { SelectQueryBuilder } from 'typeorm'import { agentConversationService } from '../../../../src/app/ee/agent/agent-conversation-service'import { db } from '../../../helpers/db'import { createMockFlow, createMockFlowVersion, createMockFolder, createMockProject, createMockProjectRole, mockAndSaveAIProvider } from '../../../helpers/mocks'@@ -198,6 +199,36 @@ describe('agent crud', () => {expect((await ctx.get(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.OK)})+ it('locks the agent row FOR UPDATE when deleting, so a publish holding it FOR SHARE cannot slip a reference past the guard', async () => {+ const ctx = await context()+ const agent = await createAgent(ctx)+ const setLock = vi.spyOn(SelectQueryBuilder.prototype, 'setLock')++ expect((await ctx.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.NO_CONTENT)++ expect(setLock.mock.calls.map(([mode]) => mode)).toContain('pessimistic_write')+ setLock.mockRestore()+ })++ it('locks the agent row FOR SHARE when a flow that uses it is published, so a delete waits for the publish', async () => {+ const ctx = await context()+ const agent = await createAgent(ctx)+ await db.update('agent', agent.id, { published: agent.draft })+ const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.DISABLED })+ await db.save('flow', flow)+ const version = createMockFlowVersion({ flowId: flow.id, updatedBy: ctx.user.id, state: FlowVersionState.DRAFT, agentIds: [agent.externalId], trigger: triggerRunningAgent(agent.externalId) })+ await db.save('flow_version', version)+ const setLock = vi.spyOn(SelectQueryBuilder.prototype, 'setLock')++ const published = await ctx.post(`/v1/flows/${flow.id}`, { type: 'LOCK_AND_PUBLISH', request: { status: FlowStatus.DISABLED } })++ expect(published.statusCode).toBe(StatusCodes.OK)+ expect(setLock.mock.calls.map(([mode]) => mode)).toContain('pessimistic_read')+ const publishedVersion = await db.findOneByOrFail('flow_version', { id: version.id }) as { agentIds: string[] }+ expect(publishedVersion.agentIds).toStrictEqual([agent.externalId])+ setLock.mockRestore()+ })+it('names three flows and stops counting, so the refusal cannot grow without bound', async () => {const ctx = await context()const agent = await createAgent(ctx)@@ -1024,3 +1055,29 @@ describe('agent feature gate', () => {expect((await ctx.delete(`/v1/agents/${agent.id}`)).statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)})})++function triggerRunningAgent(agentExternalId: string) {+ return {+ type: FlowTriggerType.EMPTY,+ name: 'trigger',+ settings: {},+ valid: false,+ displayName: 'Select Trigger',+ lastUpdatedDate: new Date().toISOString(),+ nextAction: {+ type: FlowActionType.PIECE,+ name: 'step_1',+ displayName: 'Run Agent',+ skip: false,+ valid: true,+ lastUpdatedDate: new Date().toISOString(),+ settings: {+ pieceName: AI_PIECE_NAME,+ pieceVersion: '0.1.0',+ actionName: 'run_agent',+ input: { [AgentPieceProps.AGENT_ID]: agentExternalId },+ propertySettings: {},+ },+ },+ } as const+}