Skip to content

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

feat(agents): link the flows that still use an agent when you try to delete or move it (#16010)

Hazem Adelb1243b11747c
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index eb86aa87f02..e02811a6df7 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.187.0",
+ "version": "0.187.1",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/ee/agent/agent.ts b/packages/core/shared/src/lib/ee/agent/agent.ts
index 528f63a930c..cc8bfb55b99 100644
--- a/packages/core/shared/src/lib/ee/agent/agent.ts
+++ b/packages/core/shared/src/lib/ee/agent/agent.ts
@@ -72,6 +72,7 @@ const Agent = z.object({
const AgentUsage = z.object({
total: z.number().int().nonnegative(),
names: z.array(z.string()),
+ flows: z.array(z.object({ id: z.string(), displayName: z.string() })),
})
const AgentWithUsage = Agent.extend({
diff --git a/packages/server/api/src/app/ee/agent/agent-controller.ts b/packages/server/api/src/app/ee/agent/agent-controller.ts
index 5af6a4f3bfa..8093a5c9250 100644
--- a/packages/server/api/src/app/ee/agent/agent-controller.ts
+++ b/packages/server/api/src/app/ee/agent/agent-controller.ts
@@ -9,7 +9,7 @@ import { securityAccess } from '../../core/security/authorization/fastify-securi
import { applicationEvents } from '../../helper/application-events'
import { securityHelper } from '../../helper/security-helper'
import { AgentEntity } from './agent-entity'
-import { agentAudit, agentRedaction, agentService } from './agent-service'
+import { AGENT_USAGE_LIST_LIMIT, agentAudit, agentRedaction, agentService } from './agent-service'
export const agentController: FastifyPluginAsyncZod = async (app) => {
app.post('/', CreateAgentRoute, async (request, reply) => {
@@ -50,7 +50,7 @@ export const agentController: FastifyPluginAsyncZod = async (app) => {
if (request.query.includeUsage !== true) {
return redacted
}
- const publishedFlowsUsingAgent = await agentService(request.log).publishedFlowsUsing({ agent, projectId: request.projectId, userId })
+ const publishedFlowsUsingAgent = await agentService(request.log).publishedFlowsUsing({ agent, projectId: request.projectId, userId, nameLimit: AGENT_USAGE_LIST_LIMIT })
return { ...redacted, publishedFlowsUsingAgent }
})
diff --git a/packages/server/api/src/app/ee/agent/agent-service.ts b/packages/server/api/src/app/ee/agent/agent-service.ts
index e710c428ff2..1beb39b4a4d 100644
--- a/packages/server/api/src/app/ee/agent/agent-service.ts
+++ b/packages/server/api/src/app/ee/agent/agent-service.ts
@@ -229,11 +229,10 @@ export const agentService = (log: FastifyBaseLogger) => ({
})
},
- async publishedFlowsUsing({ agent, projectId, userId }: { agent: Agent, projectId: ProjectId, userId: UserId }): Promise<PublishedFlowsUsingAgent> {
+ async publishedFlowsUsing({ agent, projectId, userId, nameLimit = MAX_NAMED_FLOWS_IN_USE }: { agent: Agent, projectId: ProjectId, userId: UserId, nameLimit?: number }): Promise<PublishedFlowsUsingAgent> {
const checker = await resolvePermissionChecker({ userId, projectId, log })
const mayReadFlows = isNil(checker.check(Permission.READ_FLOW, '__name_flows_using_agent'))
- const usage = await publishedFlowsUsingAgent({ projectId, agentExternalId: agent.externalId, nameLimit: mayReadFlows ? MAX_NAMED_FLOWS_IN_USE : 0 })
- return { total: usage.total, names: usage.names }
+ return publishedFlowsUsingAgent({ projectId, agentExternalId: agent.externalId, nameLimit: mayReadFlows ? nameLimit : 0 })
},
async movePreview({ id, projectId, userId, targetProjectId, platformId }: MoveParams & { id: string }): Promise<AgentMovePreview> {
@@ -241,7 +240,7 @@ export const agentService = (log: FastifyBaseLogger) => ({
await assertMayDestroy({ agent, projectId, userId, log })
const target = await readableProjectOrThrow({ platformId, userId, targetProjectId, log })
const [flowsInUse, mayCreateAgentsThere] = await Promise.all([
- this.publishedFlowsUsing({ agent, projectId, userId }),
+ this.publishedFlowsUsing({ agent, projectId, userId, nameLimit: AGENT_USAGE_LIST_LIMIT }),
mayWriteAgentsIn({ projectId: target.id, userId, log }),
])
if (!mayCreateAgentsThere) {
@@ -376,13 +375,13 @@ function refuseBecauseFlowsUseIt({ agent, flowsInUse }: {
})
}
-function describeFlowsInUse({ total, names }: PublishedFlowsUsingAgent): string {
+function describeFlowsInUse({ total, flows }: PublishedFlowsUsingAgent): string {
const counted = total === 1 ? '1 published flow' : `${total} published flows`
- if (names.length === 0) {
+ if (flows.length === 0) {
return `This agent is running in ${counted}. Remove it from them first.`
}
- const listed = names.join(', ')
- const tail = total > names.length ? `, and ${total - names.length} more` : ''
+ const listed = flows.map((flow) => flow.displayName).join(', ')
+ const tail = total > flows.length ? `, and ${total - flows.length} more` : ''
return `This agent is running in ${counted} (${listed}${tail}). Remove it from them first.`
}
@@ -755,3 +754,5 @@ type AssertShareParams = {
userId: UserId
log: FastifyBaseLogger
}
+
+export const AGENT_USAGE_LIST_LIMIT = 100
diff --git a/packages/server/api/src/app/flows/flow-version/flow-version.service.ts b/packages/server/api/src/app/flows/flow-version/flow-version.service.ts
index 227e56d3315..64097452170 100644
--- a/packages/server/api/src/app/flows/flow-version/flow-version.service.ts
+++ b/packages/server/api/src/app/flows/flow-version/flow-version.service.ts
@@ -28,12 +28,13 @@ export const publishedFlowsUsingAgent = async ({ projectId, agentExternalId, nam
const [total, named] = await Promise.all([
referencing().getCount(),
referencing()
- .select('flow_version."displayName"', 'displayName')
+ .select('flow_version_flow.id', 'id')
+ .addSelect('flow_version."displayName"', 'displayName')
.orderBy('flow_version."displayName"', 'ASC')
.limit(nameLimit)
- .getRawMany<{ displayName: string }>(),
+ .getRawMany<{ id: string, displayName: string }>(),
])
- return { total, names: named.map((row) => row.displayName) }
+ return { total, names: named.map((flow) => flow.displayName), flows: named }
}
export const flowVersionService = (log: FastifyBaseLogger) => ({
@@ -434,4 +435,5 @@ type ApplyOperationParams = {
export type PublishedFlowsUsingAgent = {
total: number
names: string[]
+ flows: { id: string, displayName: string }[]
}
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.ts
index 2ee4a8caee1..9b82616d8aa 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
@@ -36,7 +36,7 @@ async function createAgent(ctx: TestContext, overrides: Record<string, unknown>
return response.json()
}
-async function publishFlowRunningAgent({ projectId, externalId, displayName, publish = true }: { projectId: string, externalId: string, displayName: string, publish?: boolean }): Promise<void> {
+async function publishFlowRunningAgent({ projectId, externalId, displayName, publish = true }: { projectId: string, externalId: string, displayName: string, publish?: boolean }): Promise<string> {
const flow = createMockFlow({ projectId, status: FlowStatus.ENABLED })
await db.save('flow', flow)
const version = createMockFlowVersion({
@@ -49,6 +49,7 @@ async function publishFlowRunningAgent({ projectId, externalId, displayName, pub
if (publish) {
await db.update('flow', flow.id, { publishedVersionId: version.id })
}
+ return flow.id
}
beforeAll(async () => {
@@ -136,12 +137,12 @@ describe('agent crud', () => {
it('tells you which published flows use an agent before you try to delete it', async () => {
const ctx = await context()
const agent = await createAgent(ctx)
- await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly digest' })
+ const flowId = await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly digest' })
const withUsage = (await ctx.get(`/v1/agents/${agent.id}`, { includeUsage: 'true' })).json()
const withoutUsage = (await ctx.get(`/v1/agents/${agent.id}`)).json()
- expect(withUsage.publishedFlowsUsingAgent).toStrictEqual({ total: 1, names: ['Nightly digest'] })
+ expect(withUsage.publishedFlowsUsingAgent).toStrictEqual({ total: 1, names: ['Nightly digest'], flows: [{ id: flowId, displayName: 'Nightly digest' }] })
expect(withoutUsage.publishedFlowsUsingAgent).toBeUndefined()
})
@@ -151,7 +152,7 @@ describe('agent crud', () => {
const response = await ctx.get(`/v1/agents/${agent.id}`, { includeUsage: 'true' })
- expect(response.json().publishedFlowsUsingAgent).toStrictEqual({ total: 0, names: [] })
+ expect(response.json().publishedFlowsUsingAgent).toStrictEqual({ total: 0, names: [], flows: [] })
})
it('refuses an editor who did not create the agent, because deleting takes other people\'s conversations with it', async () => {
@@ -211,6 +212,19 @@ describe('agent crud', () => {
expect(message).not.toContain('Flow D')
})
+ it('lists every flow that uses an agent for the delete dialog, so each one can be opened from it', async () => {
+ const ctx = await context()
+ const agent = await createAgent(ctx)
+ for (const name of ['Flow A', 'Flow B', 'Flow C', 'Flow D', 'Flow E']) {
+ await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: name })
+ }
+
+ const usage = (await ctx.get(`/v1/agents/${agent.id}`, { includeUsage: 'true' })).json().publishedFlowsUsingAgent
+
+ expect(usage.total).toBe(5)
+ expect(usage.flows.map((flow: { displayName: string }) => flow.displayName)).toStrictEqual(['Flow A', 'Flow B', 'Flow C', 'Flow D', 'Flow E'])
+ })
+
it('counts the flows instead of naming them for a caller who cannot read flows', async () => {
const owner = await context()
const role = createMockProjectRole({
@@ -771,13 +785,13 @@ describe('moving an agent to another project', () => {
const ctx = await context()
const agent = await createAgent(ctx)
const target = await secondProjectOf(ctx)
- await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly sweep' })
+ const flowId = await publishFlowRunningAgent({ projectId: ctx.project.id, externalId: agent.externalId, displayName: 'Nightly sweep' })
const preview = await ctx.get(`/v1/agents/${agent.id}/move-preview`, { projectId: target.id })
expect(preview.statusCode).toBe(StatusCodes.OK)
expect(preview.json().blockedByPublishedFlows.total).toBe(1)
- expect(preview.json().blockedByPublishedFlows.names).toStrictEqual(['Nightly sweep'])
+ expect(preview.json().blockedByPublishedFlows.flows).toStrictEqual([{ id: flowId, displayName: 'Nightly sweep' }])
expect(preview.json().mayCreateAgentsThere).toBe(true)
expect(preview.json().toolsThatStopWorking).toStrictEqual([])
expect(preview.json().membersLosingAccess).toBe(0)
diff --git a/packages/web/src/features/agents/delete-agent-dialog.tsx b/packages/web/src/features/agents/delete-agent-dialog.tsx
index e5f5b717581..6108154dc22 100644
--- a/packages/web/src/features/agents/delete-agent-dialog.tsx
+++ b/packages/web/src/features/agents/delete-agent-dialog.tsx
@@ -1,5 +1,7 @@
+import { AgentUsage } from '@activepieces/shared';
import { useQueryClient } from '@tanstack/react-query';
import { t } from 'i18next';
+import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
@@ -31,7 +33,11 @@ export const DeleteAgentDialog = ({
message={t(
'Its instructions, its tools, and every conversation held with it are deleted for good. Any draft flow step using it will break.',
)}
- warning={stillInUse ? describeUsage(usage) : undefined}
+ warning={
+ stillInUse && usage !== undefined && withUsage !== undefined ? (
+ <FlowsUsingAgent usage={usage} projectId={withUsage.projectId} />
+ ) : undefined
+ }
confirmDisabled={stillInUse}
entityName={agent.displayName}
buttonText={t('Delete')}
@@ -56,26 +62,49 @@ export const DeleteAgentDialog = ({
);
};
-export function describeUsage(usage?: {
- total: number;
- names: string[];
-}): string {
+export function FlowsUsingAgent({
+ usage,
+ projectId,
+}: {
+ usage: AgentUsage;
+ projectId: string;
+}) {
+ if (usage.flows.length === 0) {
+ return <>{describeUsage(usage)}</>;
+ }
+ const unnamed = usage.total - usage.flows.length;
+ return (
+ <div className="flex flex-col gap-1">
+ <span>{t('agentStillUsedUnnamed', { count: usage.total })}</span>
+ <ul className="max-h-40 list-disc overflow-y-auto pl-4">
+ {usage.flows.map((flow) => (
+ <li key={flow.id}>
+ <Link
+ to={`/projects/${projectId}/flows/${flow.id}`}
+ className="font-medium underline underline-offset-2"
+ >
+ {flow.displayName}
+ </Link>
+ </li>
+ ))}
+ </ul>
+ {unnamed > 0 && <span>{t('and {count} more', { count: unnamed })}</span>}
+ </div>
+ );
+}
+
+export function describeUsage(usage?: AgentUsage): string {
if (usage === undefined) {
return '';
}
- if (usage.names.length === 0) {
+ const names = usage.flows.map((flow) => flow.displayName).join(', ');
+ if (usage.flows.length === 0) {
return t('agentStillUsedUnnamed', { count: usage.total });
}
- if (usage.total > usage.names.length) {
- return t('agentStillUsedPartlyNamed', {
- count: usage.total,
- flows: usage.names.join(', '),
- });
+ if (usage.total > usage.flows.length) {
+ return t('agentStillUsedPartlyNamed', { count: usage.total, flows: names });
}
- return t('agentStillUsedNamed', {
- count: usage.total,
- flows: usage.names.join(', '),
- });
+ return t('agentStillUsedNamed', { count: usage.total, flows: names });
}
type DeleteAgentDialogProps = {
diff --git a/packages/web/src/features/agents/move-agent-dialog.tsx b/packages/web/src/features/agents/move-agent-dialog.tsx
index c814024c2d3..b0164bdc30d 100644
--- a/packages/web/src/features/agents/move-agent-dialog.tsx
+++ b/packages/web/src/features/agents/move-agent-dialog.tsx
@@ -15,7 +15,7 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
-import { describeUsage } from '@/features/agents/delete-agent-dialog';
+import { FlowsUsingAgent } from '@/features/agents/delete-agent-dialog';
import {
agentsMutations,
agentsQueries,
@@ -94,7 +94,12 @@ export const MoveAgentDialog = ({
</DialogHeader>
{blockedByFlows && (
<MoveAlert variant="destructive">
- {describeUsage(preview?.blockedByPublishedFlows)}
+ {preview !== undefined && (
+ <FlowsUsingAgent
+ usage={preview.blockedByPublishedFlows}
+ projectId={agent.projectId}
+ />
+ )}
</MoveAlert>
)}
<SearchableSelect
diff --git a/packages/web/test/features/agents/flows-using-agent.test.tsx b/packages/web/test/features/agents/flows-using-agent.test.tsx
new file mode 100644
index 00000000000..3e9d5438751
--- /dev/null
+++ b/packages/web/test/features/agents/flows-using-agent.test.tsx
@@ -0,0 +1,49 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { describe, expect, it, vi } from 'vitest';
+
+import { FlowsUsingAgent } from '@/features/agents/delete-agent-dialog';
+
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+
+describe('FlowsUsingAgent', () => {
+ it('links each flow in the agent’s own project', () => {
+ renderUsage({
+ total: 2,
+ names: ['Lead triage', 'Weekly report'],
+ flows: [
+ { id: 'flow-1', displayName: 'Lead triage' },
+ { id: 'flow-2', displayName: 'Weekly report' },
+ ],
+ });
+
+ expect(
+ screen.getByRole('link', { name: 'Lead triage' }).getAttribute('href'),
+ ).toBe('/projects/agent-project/flows/flow-1');
+ expect(
+ screen.getByRole('link', { name: 'Weekly report' }).getAttribute('href'),
+ ).toBe('/projects/agent-project/flows/flow-2');
+ });
+
+ it('shows only the count to someone who cannot read flows', () => {
+ renderUsage({ total: 3, names: [], flows: [] });
+
+ expect(screen.queryAllByRole('link')).toHaveLength(0);
+ expect(screen.getByText('agentStillUsedUnnamed')).toBeTruthy();
+ });
+});
+
+function renderUsage(usage: {
+ total: number;
+ names: string[];
+ flows: { id: string; displayName: string }[];
+}) {
+ return render(
+ <MemoryRouter initialEntries={['/projects/current-project/agents']}>
+ <FlowsUsingAgent usage={usage} projectId="agent-project" />
+ </MemoryRouter>,
+ );
+}