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): see and organize your agents on the Automations page, next to flows and tables (#15994)

Hazem Adel4f4ef21300a2
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index 8ac923d67ee..ec2b81cd1c1 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -101,7 +101,8 @@ Paths verified 2026-07-17. An earlier version pointed at `packages/core/shared/s
- **`knowledge_base_chunk` is created by a migration that records itself as run even when pgvector is absent.** A database that gains pgvector later never gets the table, because the migration is already marked complete. Deleting its row from `migrations` replays it safely, since the DDL is `CREATE TABLE IF NOT EXISTS`.
- **Embeddings are stored at a fixed 768 dimensions, and most models do not return that.** `text-embedding-3-small` answers 1536, and the `dimensions` provider option is namespaced under `openai`, so the OpenRouter and managed paths never see it. `aiUtils.toStorageEmbedding` truncates and re-normalises instead, which is what the option does server-side and works whatever the provider returns. This only holds for Matryoshka-trained models — adding a model that is not one will truncate badly and silently.
-- **Saving a saved agent publishes it.** `POST /v1/agents/:id` sets `goLive: true` unless the body says otherwise, so an ordinary save copies the draft over the published snapshot. There is no separate publish step in the UI, deliberately: two versions with no history means nobody can say which one a linked flow runs. The consequence is easy to trip over in tests and callers — anything that needs `draft` to differ from `published` has to write the row directly (`db.update('agent', id, { draft })`) or pass `goLive: false`, which is what the Test tab uses to stage a change it can run without shipping it. A test that edited the draft through the API to prove "a flow runs the published copy" was quietly moving the copy it was asserting about, and it only started failing when the save-publishes change merged from another branch.
+- **Saving a saved agent publishes it.** `POST /v1/agents/:id` sets `goLive: true` unless the body says otherwise, so an ordinary save copies the draft over the published snapshot. There is no separate publish step in the UI, deliberately: two versions with no history means nobody can say which one a linked flow runs. The consequence is easy to trip over in tests and callers — anything that needs `draft` to differ from `published` has to write the row directly (`db.update('agent', id, { draft })`) or pass `goLive: false`, which is what the Test tab uses to stage a change it can run without shipping it. A test that edited the draft through the API to prove "a flow runs the published copy" was quietly moving the copy it was asserting about, and it only started failing when the save-publishes change merged from another branch. The Automations page hits the same trap: renaming an agent or filing it into a folder is a save, so those calls pass `goLive: false`; without it, moving an agent into a folder silently ships its staged draft.
+- **Agent folder counts are computed in the browser, not in `folder.service` list.** `agent.folderId` exists, but `FolderDto` only counts flows and tables. The Automations page adds agents from the visibility-filtered `/v1/agents` list. A server-side `COUNT(*)` would count `RESTRICTED` agents the viewer can't see, so the count would disagree with the rows shown.
- **`ap_add_agent_tools` will save a tool with no connection pinned.** `connectionExternalId` is optional, so a tool the AI adds without one carries no `predefinedInput.auth` for good. The visible symptom is a connection picker card on *every* conversation with that agent, which reads as the card being broken or the credential expiring — it is neither. The agent has nothing to use, so it asks, and the answer only ever lands on the run (`__store_selected_connection` writes a map the agent tool set does not read), so the next conversation asks again. Fixing the card is the wrong end: pin a connection when the tool is created, and write a chosen or repaired one back into `draft.tools` via `editDraftTools`. The same gap shows up one turn apart inside a single conversation: `selectedConnectionByPiece` is rebuilt empty per run in `execute-agent-run.ts`, and the picker's only skip check reads `piecesTheAuthorGaveAnAccount`, which is built empty unless `source === AgentRunSource.AGENT`. So on the chat surface the card re-asked for an account the user had picked ninety seconds earlier. The durable copy was already being written; nothing read it back. The picker now asks the server for it through `__get_selected_connection` and seeds the in-memory map from the answer, which fixes auth injection across turns too. Scope that skip to `ap_show_connection_picker` and nothing else: `ap_show_connection_required` is the reconnect card (`status: 'error'`), so refusing it because a selection exists would make a broken connection unrepairable, which is the one case the prompt insists must always be fixable inline. The picker takes `switchAccount` for when the user wants a different account. Leave the older `accountAlreadyChosenFor` refusal alone while you are in there: it fires only when a saved agent runs on a connection its author pinned, and it deliberately blocks both switching and reconnecting, because the card offers "use a different account" and the person chatting with someone else's agent should not be able to repoint that credential. Compose the two guards at the call site rather than nesting one inside the other, or a reviewer reads the pre-existing rule as part of the new one.
- **An agent asked to change itself will send back the entire system prompt as its new brief.** `ap_update_agent` replaces the instructions rather than patching them, so the note tells the agent to read its current brief first. On an agent run that brief is the *top* of the system prompt and every run note is appended under it, and the model reads "your current instructions above" as the whole message: a 183 character brief came back as 3,156, carrying the capabilities note, the connection guidance and the self-edit note itself, which would then be appended again on the next run and grow every turn. `agentSurfaceNotes.stripRunNotes` cuts the payload at the first run-note heading and both write paths go through it. It needs a heading on its own line and two of them present, because a hand-written brief may legitimately contain one of those strings and truncating it silently is worse than the pollution.
- **The taint flag must be set where the tool's `execute` is built, not where the group is assembled.** `TaintState` is one mutable object per job, and the two readers are the action-preview gate and the refusal to change a saved agent after a read. Three paths reached the model without marking, each because it joined the tool set past the policy: the provider's native web search, the flow step's MCP tools (merged in `run(stepMcpToolSet)`), and the conversation MCP set (through `agentMcpClient.withToolTimeouts`). Set it in `withToolTimeouts` and the configured-tool factories, before awaiting, so a same-batch call cannot slip through. Provider search never reaches the chat model directly: plugin search has no tool call at all, and native Anthropic/Google search has no `execute`, so neither can be wrapped. Without a Tavily key, `ap_web_search` runs the provider's own search in a sub-call on the fast model (`createProviderSearchTools`) and taints like any other tool. See decision 000041. **But marking every MCP tool was too wide, and it broke agent building outright.** `ap_list_connections` and `ap_research_pieces` are MCP-served and return only the platform's own catalog, yet they tainted, so `ap_add_agent_tool` refused the write its own description had just told the model to prepare ("Look them up first"). Following the instructions correctly was what broke it. `agentToolPhases.taintsTurn` now exempts a short catalog-only list (`ap_research_pieces`, `ap_search_actions`, `ap_search_triggers`, `ap_list_connections`) and unknown names still taint, so a new tool is never silently exempt. It lives in `tool-phases.ts` beside `BUILD_ONLY_TOOL_NAMES` and `CHAT_HIDDEN_TOOL_NAMES` because it classifies the same name space; a near-twin already exists server-side as `PLATFORM_LEVEL_TOOL_NAMES` in the MCP registry, differing only by `+ap_list_connections` and `-ap_get_piece_props`. Keep anything that can reach a third party off the list however metadata-ish it looks: `ap_get_piece_props` and `ap_resolve_property_*` run a piece's dynamic-props function against its API when given `auth`, and `ap_list_ai_models` can fetch a provider's model list over the network. The two layers are not symmetric, and it matters which way you reconcile them. The server's Redis flag is set by three RPCs only, so it is blind to MCP and web reads: `ap_find_records`, `ap_list_runs` and every `mcp__connector__*` call never reach `markTurnAsHavingRead`. The worker is the only mark for those and has to stay wider, so the server is the tighter list for **catalog** tools, not the model to copy wholesale, and narrowing the worker to match it would reopen the hole. A server-owned mark is reachable in principle, contrary to what this note used to claim: the agent's MCP server is the API (`${frontendUrl}/mcp/platform`) and the worker already sends `x-ap-conversation-id` on every MCP request, so marking in the MCP tool-call handler would work given a `runId` alongside it. Nobody has done it, but do not cite impossibility as the reason to keep both copies.
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index 1216b083c87..eb86aa87f02 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.186.0",
+ "version": "0.187.0",
"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 d2976547b33..528f63a930c 100644
--- a/packages/core/shared/src/lib/ee/agent/agent.ts
+++ b/packages/core/shared/src/lib/ee/agent/agent.ts
@@ -1,4 +1,5 @@
import { AgentOutputField, AgentTool } from '@activepieces/core-execution'
+import { AgentToolType } from '@activepieces/core-piece-types'
import { AIProviderName, ApId, BaseModelSchema, Nullable } from '@activepieces/core-utils'
import { z } from 'zod'
import { formErrors } from '../../form-errors'
@@ -57,6 +58,7 @@ const Agent = z.object({
projectId: ApId,
ownerId: ApId,
externalId: z.string(),
+ folderId: Nullable(ApId),
displayName: z.string(),
description: Nullable(z.string()),
icon: z.enum(AgentIcon),
@@ -80,6 +82,7 @@ const AgentSummary = Agent.omit({ draft: true, published: true }).extend({
isPublished: z.boolean(),
toolCount: z.number(),
toolPieceNames: z.array(z.string()),
+ toolTypes: z.array(z.enum(AgentToolType)),
projectDisplayName: z.string(),
projectIsPrivate: z.boolean(),
})
@@ -92,6 +95,7 @@ const CreateAgentRequest = z.object({
color: z.enum(ColorName),
visibility: z.enum(AgentVisibility).optional(),
sharedWithUserIds: z.array(ApId).max(MAX_AGENT_SHARED_MEMBERS).optional(),
+ folderId: Nullable(ApId),
draft: AgentConfig,
})
diff --git a/packages/server/api/src/app/database/migration/postgres/1858000000000-AddAgentFolderId.ts b/packages/server/api/src/app/database/migration/postgres/1858000000000-AddAgentFolderId.ts
new file mode 100644
index 00000000000..cc225531f54
--- /dev/null
+++ b/packages/server/api/src/app/database/migration/postgres/1858000000000-AddAgentFolderId.ts
@@ -0,0 +1,29 @@
+import { QueryRunner } from 'typeorm'
+import { Migration } from '../../migration'
+
+export class AddAgentFolderId1858000000000 implements Migration {
+ name = 'AddAgentFolderId1858000000000'
+ breaking = false
+ release = '0.92.0'
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`
+ ALTER TABLE "agent"
+ ADD COLUMN IF NOT EXISTS "folderId" character varying(21)
+ `)
+ await queryRunner.query(`
+ CREATE INDEX IF NOT EXISTS "idx_agent_folder_id" ON "agent" ("folderId")
+ `)
+ await queryRunner.query(`
+ ALTER TABLE "agent"
+ ADD CONSTRAINT "fk_agent_folder_id"
+ FOREIGN KEY ("folderId") REFERENCES "folder"("id") ON DELETE SET NULL
+ `)
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TABLE "agent" DROP CONSTRAINT IF EXISTS "fk_agent_folder_id"')
+ await queryRunner.query('DROP INDEX IF EXISTS "idx_agent_folder_id"')
+ await queryRunner.query('ALTER TABLE "agent" DROP COLUMN IF EXISTS "folderId"')
+ }
+}
diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.ts
index ef4639141ad..127bcff6cd9 100644
--- a/packages/server/api/src/app/database/postgres-connection.ts
+++ b/packages/server/api/src/app/database/postgres-connection.ts
@@ -446,6 +446,7 @@ import { UniqueProjectRoleNamePerPlatform1852000000000 } from './migration/postg
import { FlowExternalIdUniqueIgnoresDeleting1855000000000 } from './migration/postgres/1855000000000-FlowExternalIdUniqueIgnoresDeleting'
import { AddFlowTombstoneIndex1856000000000 } from './migration/postgres/1856000000000-AddFlowTombstoneIndex'
import { AddWaitpointDeadLetteredAt1857000000000 } from './migration/postgres/1857000000000-AddWaitpointDeadLetteredAt'
+import { AddAgentFolderId1858000000000 } from './migration/postgres/1858000000000-AddAgentFolderId'
const getSslConfig = (): boolean | TlsOptions => {
const useSsl = system.get(AppSystemProp.POSTGRES_USE_SSL)
@@ -907,6 +908,7 @@ export const getMigrations = (): (new () => Migration)[] => {
FlowExternalIdUniqueIgnoresDeleting1855000000000,
AddFlowTombstoneIndex1856000000000,
AddWaitpointDeadLetteredAt1857000000000,
+ AddAgentFolderId1858000000000,
]
return migrations
}
diff --git a/packages/server/api/src/app/ee/agent/agent-entity.ts b/packages/server/api/src/app/ee/agent/agent-entity.ts
index 258fbd8035d..374506f398c 100644
--- a/packages/server/api/src/app/ee/agent/agent-entity.ts
+++ b/packages/server/api/src/app/ee/agent/agent-entity.ts
@@ -1,10 +1,11 @@
-import { Agent, Project, User } from '@activepieces/shared'
+import { Agent, Folder, Project, User } from '@activepieces/shared'
import { EntitySchema } from 'typeorm'
import { ApIdSchema, BaseColumnSchemaPart } from '../../database/database-common'
export type AgentWithRelations = Agent & {
owner: User
project: Project
+ folder?: Folder
}
export const AgentEntity = new EntitySchema<AgentWithRelations>({
@@ -19,6 +20,10 @@ export const AgentEntity = new EntitySchema<AgentWithRelations>({
...ApIdSchema,
nullable: false,
},
+ folderId: {
+ ...ApIdSchema,
+ nullable: true,
+ },
externalId: {
type: String,
nullable: false,
@@ -68,6 +73,10 @@ export const AgentEntity = new EntitySchema<AgentWithRelations>({
columns: ['projectId', 'externalId'],
unique: true,
},
+ {
+ name: 'idx_agent_folder_id',
+ columns: ['folderId'],
+ },
],
relations: {
owner: {
@@ -88,5 +97,15 @@ export const AgentEntity = new EntitySchema<AgentWithRelations>({
foreignKeyConstraintName: 'fk_agent_project_id',
},
},
+ folder: {
+ type: 'many-to-one',
+ target: 'folder',
+ onDelete: 'SET NULL',
+ nullable: true,
+ joinColumn: {
+ name: 'folderId',
+ foreignKeyConstraintName: 'fk_agent_folder_id',
+ },
+ },
},
})
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 5845ef9bbb3..e710c428ff2 100644
--- a/packages/server/api/src/app/ee/agent/agent-service.ts
+++ b/packages/server/api/src/app/ee/agent/agent-service.ts
@@ -8,7 +8,7 @@ import { appConnectionService } from '../../app-connection/app-connection-servic
import { repoFactory } from '../../core/db/repo-factory'
import { transaction } from '../../core/db/transaction'
import { publishHooksFactory } from '../../flows/flow/flow-publish-hooks'
-import { flowService } from '../../flows/flow/flow.service'
+import { flowService, getFolderIdFromRequest } from '../../flows/flow/flow.service'
import { PublishedFlowsUsingAgent, publishedFlowsUsingAgent, publishedFlowVersionsUsingAgent } from '../../flows/flow-version/flow-version.service'
import { buildPaginator } from '../../helper/pagination/build-paginator'
import { paginationHelper } from '../../helper/pagination/pagination-utils'
@@ -43,6 +43,7 @@ export const agentService = (log: FastifyBaseLogger) => ({
externalId: apId(),
displayName: request.displayName,
description: request.description ?? null,
+ folderId: await getFolderIdFromRequest({ projectId, folderId: request.folderId ?? undefined, folderName: undefined, log }),
icon: request.icon,
color: request.color,
visibility,
@@ -119,6 +120,7 @@ export const agentService = (log: FastifyBaseLogger) => ({
log,
})
const draft = isNil(request.draft) ? agent.draft : sanitizeObjectForPostgresql(request.draft)
+ await getFolderIdFromRequest({ projectId, folderId: request.folderId ?? undefined, folderName: undefined, log })
const goingLive = goLive && agentUtils.isPublishable(draft)
const published = goingLive ? draft : agent.published
if (goingLive) {
@@ -279,7 +281,7 @@ export const agentService = (log: FastifyBaseLogger) => ({
const blocking = publishedFlowVersionsUsingAgent({ projectId, agentExternalId: agent.externalId, alias: 'blocking_version' })
const moved = await repo.createQueryBuilder()
.update()
- .set({ projectId: target.id, sharedWithUserIds })
+ .set({ projectId: target.id, sharedWithUserIds, folderId: null })
.where('"id" = :id AND "projectId" = :projectId', { id, projectId })
.andWhere(`NOT EXISTS (${blocking.getQuery()})`)
.setParameters(blocking.getParameters())
@@ -637,6 +639,7 @@ function toSummary(agent: Agent, project?: Project): AgentSummary {
projectIsPrivate: project?.type === ProjectType.PERSONAL,
toolCount: agent.draft.tools.length,
toolPieceNames: agent.draft.tools.flatMap((tool) => tool.type === AgentToolType.PIECE ? [tool.pieceMetadata.pieceName] : []),
+ toolTypes: agent.draft.tools.map((tool) => tool.type),
}
}
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 2033c56d76a..2ee4a8caee1 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,11 +1,10 @@
import { AIProviderName, apId, Permission, RoleType } from '@activepieces/core-utils'
-import { AgentIcon, AgentRunSource, AgentToolType, KnowledgeBaseSourceType, AgentVisibility, ColorName, DefaultProjectRole, FlowStatus, FlowVersionState } from '@activepieces/shared'
+import { AgentIcon, AgentRunSource, AgentToolType, AgentVisibility, ColorName, DefaultProjectRole, FlowStatus, FlowVersionState, KnowledgeBaseSourceType } from '@activepieces/shared'
import { FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
import { agentConversationService } from '../../../../src/app/ee/agent/agent-conversation-service'
-import { agentService } from '../../../../src/app/ee/agent/agent-service'
import { db } from '../../../helpers/db'
-import { createMockFlow, createMockFlowVersion, createMockProject, createMockProjectRole, mockAndSaveAIProvider } from '../../../helpers/mocks'
+import { createMockFlow, createMockFlowVersion, createMockFolder, createMockProject, createMockProjectRole, mockAndSaveAIProvider } from '../../../helpers/mocks'
import { createMemberContext, createTestContext, TestContext } from '../../../helpers/test-context'
import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
@@ -591,6 +590,7 @@ describe('agent project isolation', () => {
expect(listed.toolCount).toBe(0)
expect(listed.toolPieceNames).toStrictEqual([])
+ expect(listed.toolTypes).toStrictEqual([])
expect(listed.draft).toBeUndefined()
expect(listed.published).toBeUndefined()
})
@@ -890,6 +890,83 @@ describe('moving an agent to another project', () => {
})
})
+describe('agent folders', () => {
+ const folderIn = async (projectId: string) => {
+ const folder = createMockFolder({ projectId })
+ await db.save('folder', folder)
+ return folder
+ }
+
+ it('files an agent into a folder, moves it between folders, and back to the root', async () => {
+ const ctx = await context()
+ const first = await folderIn(ctx.project.id)
+ const second = await folderIn(ctx.project.id)
+
+ const agent = await createAgent(ctx, { folderId: first.id })
+ expect(agent.folderId).toBe(first.id)
+
+ const moved = await ctx.post(`/v1/agents/${agent.id}`, { folderId: second.id })
+ expect(moved.json().folderId).toBe(second.id)
+
+ const renamed = await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Still filed' })
+ expect(renamed.json().folderId).toBe(second.id)
+
+ const unfiled = await ctx.post(`/v1/agents/${agent.id}`, { folderId: null })
+ expect(unfiled.json().folderId).toBeNull()
+
+ const listed = (await ctx.get('/v1/agents', { projectId: ctx.project.id })).json()
+ expect(listed.data[0].folderId).toBeNull()
+ })
+
+ it('files an unpublished agent without publishing it', async () => {
+ const ctx = await context()
+ const folder = await folderIn(ctx.project.id)
+ const agent = await createAgent(ctx)
+ await ctx.post(`/v1/agents/${agent.id}/unpublish`)
+
+ const filed = await ctx.post(`/v1/agents/${agent.id}`, { folderId: folder.id, goLive: false })
+
+ expect(filed.json().folderId).toBe(folder.id)
+ expect(filed.json().published).toBeNull()
+ })
+
+ it('refuses a folder from another project, on create and on update', async () => {
+ const ctx = await context()
+ const stranger = await context()
+ const foreign = await folderIn(stranger.project.id)
+ const agent = await createAgent(ctx)
+
+ expect((await ctx.post('/v1/agents', agentBody(ctx.project.id, { folderId: foreign.id }))).statusCode).toBe(StatusCodes.NOT_FOUND)
+ expect((await ctx.post(`/v1/agents/${agent.id}`, { folderId: foreign.id })).statusCode).toBe(StatusCodes.NOT_FOUND)
+ expect((await ctx.get(`/v1/agents/${agent.id}`)).json().folderId).toBeNull()
+ })
+
+ it('keeps the agent at the root when its folder is deleted', async () => {
+ const ctx = await context()
+ const folder = await folderIn(ctx.project.id)
+ const agent = await createAgent(ctx, { folderId: folder.id })
+
+ expect((await ctx.delete(`/v1/folders/${folder.id}`)).statusCode).toBe(StatusCodes.OK)
+
+ const after = await ctx.get(`/v1/agents/${agent.id}`)
+ expect(after.statusCode).toBe(StatusCodes.OK)
+ expect(after.json().folderId).toBeNull()
+ })
+
+ it('drops the folder when the agent moves to another project, since the folder stays behind', async () => {
+ const ctx = await context()
+ const folder = await folderIn(ctx.project.id)
+ const agent = await createAgent(ctx, { folderId: folder.id })
+ const target = createMockProject({ ownerId: ctx.user.id, platformId: ctx.platform.id })
+ await db.save('project', target)
+
+ const moved = await ctx.post(`/v1/agents/${agent.id}/move`, { projectId: target.id })
+
+ expect(moved.statusCode).toBe(StatusCodes.OK)
+ expect(moved.json().folderId).toBeNull()
+ })
+})
+
describe('agent permissions', () => {
it('lets a viewer read an agent but never create or change one', async () => {
const owner = await context()
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index c03c90d1cad..6805172cdaf 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -889,6 +889,9 @@
"projects": "projects",
"users": "users",
"New Table": "New Table",
+ "New Agent": "New Agent",
+ "Build an Agent": "Build an Agent",
+ "Delegate tasks to AI": "Delegate tasks to AI",
"Response stopped": "Response stopped",
"Retry": "Retry",
"Ask, build, or run a task...": "Ask, build, or run a task...",
@@ -2085,6 +2088,7 @@
"All templates": "All templates",
"Search flows...": "Search flows...",
"Search flows and tables...": "Search flows and tables...",
+ "Search flows, tables and agents...": "Search flows, tables and agents...",
"Import Flow": "Import Flow",
"Import Table": "Import Table",
"Create New": "Create New",
@@ -2130,6 +2134,8 @@
"Failed to move items": "Failed to move items",
"Renamed successfully": "Renamed successfully",
"Failed to rename item": "Failed to rename item",
+ "Failed to create agent": "Failed to create agent",
+ "{name} cannot be deleted. {usage}": "{name} cannot be deleted. {usage}",
"Flow duplicated successfully": "Flow duplicated successfully",
"Failed to duplicate flow": "Failed to duplicate flow",
"Moved successfully": "Moved successfully",
diff --git a/packages/web/src/app/routes/agents/id/index.tsx b/packages/web/src/app/routes/agents/id/index.tsx
index 28bf11bbe4e..5de6f05d5fe 100644
--- a/packages/web/src/app/routes/agents/id/index.tsx
+++ b/packages/web/src/app/routes/agents/id/index.tsx
@@ -86,7 +86,8 @@ const AgentEditorSkeleton = () => (
const AgentEditorContent = () => {
const navigate = useNavigate();
const { agentId } = useParams<{ agentId: string }>();
- const { pathname } = useLocation();
+ const { pathname, state: locationState } = useLocation();
+ const [backTo] = useState(() => backDestination(locationState));
const agentsAvailable = useAgentsAvailable();
const [openPanel, setOpenPanel] = useState<OpenPanel>();
const [configureMounted, setConfigureMounted] = useState(false);
@@ -192,8 +193,8 @@ const AgentEditorContent = () => {
>
<button
type="button"
- aria-label={t('Back to agents')}
- onClick={() => navigate('/agents')}
+ aria-label={t('Back')}
+ onClick={() => navigate(backTo)}
className="flex size-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<ChevronLeft size={16} />
@@ -290,6 +291,18 @@ const AgentEditorContent = () => {
);
};
+function backDestination(state: unknown): string {
+ if (
+ typeof state === 'object' &&
+ state !== null &&
+ 'backTo' in state &&
+ typeof state.backTo === 'string'
+ ) {
+ return state.backTo;
+ }
+ return '/agents';
+}
+
const AgentEditorPage = () => {
const agentsAvailable = useAgentsAvailable();
return (
diff --git a/packages/web/src/app/routes/agents/index.tsx b/packages/web/src/app/routes/agents/index.tsx
index 3aa0c949322..3c0f2079929 100644
--- a/packages/web/src/app/routes/agents/index.tsx
+++ b/packages/web/src/app/routes/agents/index.tsx
@@ -1,9 +1,6 @@
import {
- AgentIcon,
AgentListSort,
AgentSummary,
- ColorName,
- DEFAULT_AGENT_MAX_STEPS,
PROJECT_COLOR_PALETTE,
} from '@activepieces/shared';
import { t } from 'i18next';
@@ -48,6 +45,7 @@ import {
agentsQueries,
useAgentsAvailable,
} from '@/features/agents/hooks/agents-hooks';
+import { blankAgentUtils } from '@/features/agents/lib/blank-agent';
import { NewBlankAgentButton } from '@/features/agents/new-blank-agent-button';
import { getProjectName, projectCollectionUtils } from '@/features/projects';
import { platformHooks } from '@/hooks/platform-hooks';
@@ -180,19 +178,7 @@ const AgentsPageContent = () => {
if (createAgent.isPending) {
return;
}
- createAgent.mutate({
- projectId,
- displayName: t('New agent'),
- description: null,
- icon: AgentIcon.BOT,
- color: ColorName.PURPLE,
- draft: {
- instructions: '',
- maxSteps: DEFAULT_AGENT_MAX_STEPS,
- tools: [],
- structuredOutput: [],
- },
- });
+ createAgent.mutate(blankAgentUtils.request({ projectId }));
};
const projectDotColorFor = (agent: AgentSummary) =>
diff --git a/packages/web/src/app/routes/automations/index.tsx b/packages/web/src/app/routes/automations/index.tsx
index bc4d27054bc..e9c64833f33 100644
--- a/packages/web/src/app/routes/automations/index.tsx
+++ b/packages/web/src/app/routes/automations/index.tsx
@@ -2,7 +2,12 @@ import { Permission } from '@activepieces/core-utils';
import { UncategorizedFolderId } from '@activepieces/shared';
import { t } from 'i18next';
import { useCallback } from 'react';
-import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
+import {
+ useLocation,
+ useNavigate,
+ useParams,
+ useSearchParams,
+} from 'react-router-dom';
import { recordAccess } from '@/app/components/global-search/access-history';
import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';
@@ -23,7 +28,8 @@ import { useAutomationsFilters } from '@/features/automations/hooks/use-automati
import { useAutomationsMutations } from '@/features/automations/hooks/use-automations-mutations';
import {
useAutomationsSelection,
- hasMovableOrExportableItems,
+ hasExportableItems,
+ hasMovableItems,
} from '@/features/automations/hooks/use-automations-selection';
import { usePinnedItems } from '@/features/automations/hooks/use-pinned-items';
import { AutomationsSort, TreeItem } from '@/features/automations/lib/types';
@@ -47,6 +53,7 @@ export const AutomationsPage = () => {
const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
const [, setSearchParams] = useSearchParams();
const navigate = useNavigate();
+ const location = useLocation();
const { embedState } = useEmbedding();
const { data: allProjects = [] } = projectCollectionUtils.useAll();
@@ -59,6 +66,7 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
const userHasPermissionToWriteFlow = checkAccess(Permission.WRITE_FLOW);
const userHasPermissionToWriteTable = checkAccess(Permission.WRITE_TABLE);
const userHasPermissionToWriteFolder = checkAccess(Permission.WRITE_FOLDER);
+ const userHasPermissionToWriteAgent = checkAccess(Permission.WRITE_AGENT);
const {
searchInput,
@@ -87,6 +95,8 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
folders,
rootFlows,
rootTables,
+ agents,
+ agentsVisible,
isLoading,
isError,
expandedFolders,
@@ -227,6 +237,15 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
} else {
navigate(href);
}
+ } else if (item.type === 'agent') {
+ const href = `/projects/${projectId}/agents/${item.id}`;
+ if (ctrlKey) {
+ window.open(href, '_blank');
+ } else {
+ navigate(href, {
+ state: { backTo: `${location.pathname}${location.search}` },
+ });
+ }
}
},
[
@@ -236,6 +255,8 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
currentProjectName,
clearSelection,
expandedFolders,
+ projectId,
+ location,
],
);
@@ -248,6 +269,9 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
case 'table':
mutations.createTable(t('New Table'), folderId);
break;
+ case 'agent':
+ mutations.createAgent(folderId);
+ break;
case 'import-flow':
expandFolderIfCollapsed(folderId);
dialogs.setImportTargetFolderId(folderId);
@@ -279,7 +303,10 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
};
const hasAnyItems =
- rootFlows.length > 0 || rootTables.length > 0 || folders.length > 0;
+ rootFlows.length > 0 ||
+ rootTables.length > 0 ||
+ agents.length > 0 ||
+ folders.length > 0;
const isSortTruncated =
sort !== 'default' &&
(rootFlows.length >= ROOT_ITEMS_LIMIT ||
@@ -291,7 +318,15 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
treeItems.length === 0 && filtersActive && !isLoading && !isErrorState;
if (isEmptyState) {
- return <AutomationsEmptyState onRefresh={() => invalidateAll()} />;
+ return (
+ <AutomationsEmptyState
+ onRefresh={() => invalidateAll()}
+ agentsVisible={agentsVisible}
+ userHasPermissionToWriteAgent={userHasPermissionToWriteAgent}
+ isCreatingAgent={mutations.isCreatingAgent}
+ onCreateAgent={() => mutations.createAgent()}
+ />
+ );
}
return (
@@ -316,8 +351,11 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
userHasPermissionToWriteFlow={userHasPermissionToWriteFlow}
userHasPermissionToWriteTable={userHasPermissionToWriteTable}
userHasPermissionToWriteFolder={userHasPermissionToWriteFolder}
+ userHasPermissionToWriteAgent={userHasPermissionToWriteAgent}
+ agentsVisible={agentsVisible}
onCreateFlow={() => mutations.createFlow()}
onCreateTable={() => mutations.createTable(t('New Table'))}
+ onCreateAgent={() => mutations.createAgent()}
onCreateFolder={() => dialogs.setIsFolderDialogOpen(true)}
onImportFlow={() => {
dialogs.setImportTargetFolderId(undefined);
@@ -331,6 +369,7 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
hasActiveFilters={filtersActive}
isCreatingFlow={mutations.isCreateFlowPending}
isCreatingTable={mutations.isCreatingTable}
+ isCreatingAgent={mutations.isCreatingAgent}
/>
{isErrorState ? (
@@ -365,8 +404,11 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
onCreateInFolder={handleCreateInFolder}
userHasPermissionToWriteFlow={userHasPermissionToWriteFlow}
userHasPermissionToWriteTable={userHasPermissionToWriteTable}
+ userHasPermissionToWriteAgent={userHasPermissionToWriteAgent}
+ agentsVisible={agentsVisible}
isCreatingFlow={mutations.isCreateFlowPending}
isCreatingTable={mutations.isCreatingTable}
+ isCreatingAgent={mutations.isCreatingAgent}
isMoving={mutations.isMoving}
isDuplicating={mutations.isDuplicating}
onLoadMoreInFolder={loadMoreInFolder}
@@ -400,7 +442,8 @@ const AutomationsPageContent = ({ projectId }: { projectId: string }) => {
isDeleting={mutations.isDeleting}
isMoving={mutations.isMoving}
isExporting={mutations.isExporting}
- hasMovableOrExportableItems={hasMovableOrExportableItems(selectedItems)}
+ hasMovableItems={hasMovableItems(selectedItems)}
+ hasExportableItems={hasExportableItems(selectedItems)}
onMoveClick={() => dialogs.setMoveToDialogOpen(true)}
onDeleteClick={() => mutations.handleBulkDelete(selectedItems)}
onExportClick={() => mutations.handleBulkExport(selectedItems)}
diff --git a/packages/web/src/features/agents/agent-card.tsx b/packages/web/src/features/agents/agent-card.tsx
index fb6f68a5245..5ec6a1e5831 100644
--- a/packages/web/src/features/agents/agent-card.tsx
+++ b/packages/web/src/features/agents/agent-card.tsx
@@ -81,6 +81,7 @@ export const AgentCard = ({
<AgentToolStack
toolCount={agent.toolCount}
toolPieceNames={agent.toolPieceNames}
+ toolTypes={agent.toolTypes}
/>
<div className="ms-auto">
{(agent.projectIsPrivate ||
diff --git a/packages/web/src/features/agents/agent-table.tsx b/packages/web/src/features/agents/agent-table.tsx
index 9b30c98a4f1..43b3aa1420c 100644
--- a/packages/web/src/features/agents/agent-table.tsx
+++ b/packages/web/src/features/agents/agent-table.tsx
@@ -77,6 +77,7 @@ export const AgentTable = ({
<AgentToolStack
toolCount={agent.toolCount}
toolPieceNames={agent.toolPieceNames}
+ toolTypes={agent.toolTypes}
/>
</TableCell>
<TableCell>
diff --git a/packages/web/src/features/agents/agent-tool-stack.tsx b/packages/web/src/features/agents/agent-tool-stack.tsx
index 6df998db128..542196499a1 100644
--- a/packages/web/src/features/agents/agent-tool-stack.tsx
+++ b/packages/web/src/features/agents/agent-tool-stack.tsx
@@ -1,6 +1,13 @@
+import { unique } from '@activepieces/core-utils';
+import { AgentToolType } from '@activepieces/shared';
import { t } from 'i18next';
-import { Unplug } from 'lucide-react';
+import { BookOpen, LucideIcon, Server, Unplug, Workflow } from 'lucide-react';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
import { PieceIcon } from '@/features/pieces/components/piece-icon';
import { piecesHooks } from '@/features/pieces/hooks/pieces-hooks';
@@ -9,14 +16,16 @@ const MAX_VISIBLE = 3;
type AgentToolStackProps = {
toolCount: number;
toolPieceNames: string[];
+ toolTypes?: AgentToolType[];
};
export const AgentToolStack = ({
toolCount,
toolPieceNames,
+ toolTypes = [],
}: AgentToolStackProps) => {
const { summaries } = piecesHooks.usePieceSummariesByNames({
- names: toolPieceNames,
+ names: unique(toolPieceNames),
});
if (toolCount === 0) {
@@ -28,12 +37,10 @@ export const AgentToolStack = ({
);
}
- const visible = summaries.slice(0, MAX_VISIBLE);
- const remaining = toolCount - visible.length;
-
- return (
- <div className="flex shrink-0 items-center gap-[5px]">
- {visible.map((metadata) => (
+ const tiles = [
+ ...summaries.map((metadata) => ({
+ tools: toolPieceNames.filter((name) => name === metadata.name).length,
+ element: (
<PieceIcon
key={metadata.name}
logoUrl={metadata.logoUrl}
@@ -42,7 +49,39 @@ export const AgentToolStack = ({
size="tile"
border={true}
/>
- ))}
+ ),
+ })),
+ ...NON_PIECE_TOOL_KINDS.flatMap(({ type, icon: Icon, label }) => {
+ const count = toolTypes.filter((toolType) => toolType === type).length;
+ if (count === 0) {
+ return [];
+ }
+ return [
+ {
+ tools: count,
+ element: (
+ <Tooltip key={type}>
+ <TooltipTrigger asChild>
+ <span className="flex size-6.5 items-center justify-center rounded-md border bg-background text-muted-foreground">
+ <Icon size={14} />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {count > 1 ? `${t(label)} · ${count}` : t(label)}
+ </TooltipContent>
+ </Tooltip>
+ ),
+ },
+ ];
+ }),
+ ];
+ const visible = tiles.slice(0, MAX_VISIBLE);
+ const remaining =
+ toolCount - visible.reduce((shown, tile) => shown + tile.tools, 0);
+
+ return (
+ <div className="flex shrink-0 items-center gap-[5px]">
+ {visible.map((tile) => tile.element)}
{remaining > 0 && (
<span className="flex size-[26px] items-center justify-center rounded-[7px] bg-[#F0F0F2] text-xs leading-none font-semibold text-[#8A8A8F]">
+{remaining}
@@ -51,3 +90,17 @@ export const AgentToolStack = ({
</div>
);
};
+
+const NON_PIECE_TOOL_KINDS: {
+ type: AgentToolType;
+ icon: LucideIcon;
+ label: string;
+}[] = [
+ {
+ type: AgentToolType.KNOWLEDGE_BASE,
+ icon: BookOpen,
+ label: 'Knowledge Base',
+ },
+ { type: AgentToolType.FLOW, icon: Workflow, label: 'Flows' },
+ { type: AgentToolType.MCP, icon: Server, label: 'MCP Servers' },
+];
diff --git a/packages/web/src/features/agents/lib/blank-agent.ts b/packages/web/src/features/agents/lib/blank-agent.ts
new file mode 100644
index 00000000000..f604372631e
--- /dev/null
+++ b/packages/web/src/features/agents/lib/blank-agent.ts
@@ -0,0 +1,32 @@
+import {
+ AgentIcon,
+ ColorName,
+ CreateAgentRequest,
+ DEFAULT_AGENT_MAX_STEPS,
+} from '@activepieces/shared';
+import { t } from 'i18next';
+
+function blankAgentRequest({
+ projectId,
+ folderId,
+}: {
+ projectId: string;
+ folderId?: string | null;
+}): CreateAgentRequest {
+ return {
+ projectId,
+ displayName: t('New agent'),
+ description: null,
+ icon: AgentIcon.BOT,
+ color: ColorName.PURPLE,
+ folderId: folderId ?? null,
+ draft: {
+ instructions: '',
+ maxSteps: DEFAULT_AGENT_MAX_STEPS,
+ tools: [],
+ structuredOutput: [],
+ },
+ };
+}
+
+export const blankAgentUtils = { request: blankAgentRequest };
diff --git a/packages/web/src/features/automations/components/automations-empty-state.tsx b/packages/web/src/features/automations/components/automations-empty-state.tsx
index a526ee3a070..5a3647ebc83 100644
--- a/packages/web/src/features/automations/components/automations-empty-state.tsx
+++ b/packages/web/src/features/automations/components/automations-empty-state.tsx
@@ -6,6 +6,7 @@ import {
} from '@activepieces/shared';
import { t } from 'i18next';
import {
+ Bot,
ChevronRight,
Plus,
Sparkles,
@@ -196,10 +197,18 @@ const TemplateCardSkeleton = () => {
type AutomationsEmptyStateProps = {
onRefresh: () => void;
+ agentsVisible: boolean;
+ userHasPermissionToWriteAgent: boolean;
+ isCreatingAgent: boolean;
+ onCreateAgent: () => void;
};
export const AutomationsEmptyState = ({
onRefresh,
+ agentsVisible,
+ userHasPermissionToWriteAgent,
+ isCreatingAgent,
+ onCreateAgent,
}: AutomationsEmptyStateProps) => {
const navigate = useNavigate();
const { embedState } = useEmbedding();
@@ -330,6 +339,23 @@ export const AutomationsEmptyState = ({
/>
</GetStartedCard>
)}
+
+ {agentsVisible && (
+ <GetStartedCard
+ icon={<Bot className="h-5 w-5 text-primary" />}
+ iconBgClass="bg-primary-100"
+ title={t('Build an Agent')}
+ description={t('Delegate tasks to AI')}
+ >
+ <ActionRow
+ icon={<Plus className="h-4 w-4" />}
+ label={t('Start from scratch')}
+ onClick={onCreateAgent}
+ disabled={isCreatingAgent}
+ hasPermission={userHasPermissionToWriteAgent}
+ />
+ </GetStartedCard>
+ )}
</div>
</div>
diff --git a/packages/web/src/features/automations/components/automations-filters.tsx b/packages/web/src/features/automations/components/automations-filters.tsx
index 0a9ef0309f5..41375caf468 100644
--- a/packages/web/src/features/automations/components/automations-filters.tsx
+++ b/packages/web/src/features/automations/components/automations-filters.tsx
@@ -60,8 +60,11 @@ type AutomationsFiltersProps = {
userHasPermissionToWriteFlow: boolean;
userHasPermissionToWriteTable: boolean;
userHasPermissionToWriteFolder: boolean;
+ userHasPermissionToWriteAgent: boolean;
+ agentsVisible: boolean;
onCreateFlow: () => void;
onCreateTable: () => void;
+ onCreateAgent: () => void;
onCreateFolder: () => void;
onImportFlow: () => void;
onImportTable: () => void;
@@ -69,6 +72,7 @@ type AutomationsFiltersProps = {
hasActiveFilters: boolean;
isCreatingFlow?: boolean;
isCreatingTable?: boolean;
+ isCreatingAgent?: boolean;
};
export const AutomationsFilters = ({
@@ -91,8 +95,11 @@ export const AutomationsFilters = ({
userHasPermissionToWriteFlow,
userHasPermissionToWriteTable,
userHasPermissionToWriteFolder,
+ userHasPermissionToWriteAgent,
+ agentsVisible,
onCreateFlow,
onCreateTable,
+ onCreateAgent,
onCreateFolder,
onImportFlow,
onImportTable,
@@ -100,6 +107,7 @@ export const AutomationsFilters = ({
hasActiveFilters,
isCreatingFlow = false,
isCreatingTable = false,
+ isCreatingAgent = false,
}: AutomationsFiltersProps) => {
const navigate = useNavigate();
const { embedState } = useEmbedding();
@@ -109,6 +117,7 @@ export const AutomationsFilters = ({
const typeOptions = [
{ value: 'flow', label: t('Flows') },
...(embedState.hideTables ? [] : [{ value: 'table', label: t('Tables') }]),
+ ...(agentsVisible ? [{ value: 'agent', label: t('Agents') }] : []),
];
const statusOptions = Object.values(FlowStatus).map((status) => ({
@@ -144,11 +153,10 @@ export const AutomationsFilters = ({
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
- placeholder={
- embedState.hideTables
- ? t('Search flows...')
- : t('Search flows and tables...')
- }
+ placeholder={searchPlaceholder({
+ hideTables: embedState.hideTables,
+ agentsVisible,
+ })}
value={searchTerm}
onChange={(e) => {
onSearchChange(e.target.value);
@@ -300,8 +308,11 @@ export const AutomationsFilters = ({
userHasPermissionToWriteFolder={userHasPermissionToWriteFolder}
isCreatingFlow={isCreatingFlow}
isCreatingTable={isCreatingTable}
+ isCreatingAgent={isCreatingAgent}
+ userHasPermissionToWriteAgent={userHasPermissionToWriteAgent}
onCreateFlow={onCreateFlow}
onCreateTable={onCreateTable}
+ onCreateAgent={agentsVisible ? onCreateAgent : undefined}
onCreateFolder={onCreateFolder}
onImportFlow={onImportFlow}
onImportTable={onImportTable}
@@ -332,3 +343,18 @@ export const AutomationsFilters = ({
</>
);
};
+
+function searchPlaceholder({
+ hideTables,
+ agentsVisible,
+}: {
+ hideTables: boolean;
+ agentsVisible: boolean;
+}): string {
+ if (hideTables) {
+ return t('Search flows...');
+ }
+ return agentsVisible
+ ? t('Search flows, tables and agents...')
+ : t('Search flows and tables...');
+}
diff --git a/packages/web/src/features/automations/components/automations-selection-bar.tsx b/packages/web/src/features/automations/components/automations-selection-bar.tsx
index 413d20decff..792e33194d3 100644
--- a/packages/web/src/features/automations/components/automations-selection-bar.tsx
+++ b/packages/web/src/features/automations/components/automations-selection-bar.tsx
@@ -1,18 +1,21 @@
import { t } from 'i18next';
import { Download, FolderInput, Trash2, X } from 'lucide-react';
import { AnimatePresence, motion } from 'motion/react';
+import { toast } from 'sonner';
import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
import { LoadingSpinner } from '@/components/custom/spinner';
import { useEmbedding } from '@/components/providers/embed-provider';
import { Button } from '@/components/ui/button';
+import { api } from '@/lib/api';
type AutomationsSelectionBarProps = {
selectedCount: number;
isDeleting: boolean;
isMoving: boolean;
isExporting: boolean;
- hasMovableOrExportableItems: boolean;
+ hasMovableItems: boolean;
+ hasExportableItems: boolean;
onMoveClick: () => void;
onDeleteClick: () => void;
onExportClick: () => void;
@@ -24,7 +27,8 @@ export const AutomationsSelectionBar = ({
isDeleting,
isMoving,
isExporting,
- hasMovableOrExportableItems,
+ hasMovableItems,
+ hasExportableItems,
onMoveClick,
onDeleteClick,
onExportClick,
@@ -48,7 +52,7 @@ export const AutomationsSelectionBar = ({
variant="ghost"
size="sm"
onClick={onMoveClick}
- disabled={isMoving || !hasMovableOrExportableItems}
+ disabled={isMoving || !hasMovableItems}
>
<FolderInput className="h-4 w-4 mr-1" />
{t('Move to')}
@@ -59,7 +63,7 @@ export const AutomationsSelectionBar = ({
variant="ghost"
size="sm"
onClick={onExportClick}
- disabled={isExporting || !hasMovableOrExportableItems}
+ disabled={isExporting || !hasExportableItems}
>
{isExporting ? (
<LoadingSpinner className="size-4 mr-2" />
@@ -76,6 +80,14 @@ export const AutomationsSelectionBar = ({
{ count: selectedCount },
)}
mutationFn={async () => onDeleteClick()}
+ onError={(error) =>
+ toast.error(
+ api.extractServerErrorMessage(
+ error,
+ t('Failed to delete items'),
+ ),
+ )
+ }
entityName={t('items')}
buttonText={t('Delete')}
>
diff --git a/packages/web/src/features/automations/components/automations-table-row.tsx b/packages/web/src/features/automations/components/automations-table-row.tsx
index 62da17e1ceb..803f12b111a 100644
--- a/packages/web/src/features/automations/components/automations-table-row.tsx
+++ b/packages/web/src/features/automations/components/automations-table-row.tsx
@@ -1,7 +1,13 @@
-import { FolderDto, PopulatedFlow, Table } from '@activepieces/shared';
+import {
+ AgentSummary,
+ FolderDto,
+ PopulatedFlow,
+ Table,
+} from '@activepieces/shared';
import { t } from 'i18next';
import {
ArrowDown,
+ Bot,
ChevronDown,
ChevronRight,
Copy,
@@ -27,6 +33,7 @@ import { FormattedDate } from '@/components/custom/formatted-date';
import { LoadingSpinner } from '@/components/custom/spinner';
import { TextWithTooltip } from '@/components/custom/text-with-tooltip';
import { useEmbedding } from '@/components/providers/embed-provider';
+import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
@@ -41,6 +48,8 @@ import {
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
+import { AgentToolStack } from '@/features/agents/agent-tool-stack';
+import { DeleteAgentDialog } from '@/features/agents/delete-agent-dialog';
import { MoveToFolderDialog } from '@/features/automations/components/move-to-folder-dialog';
import { FlowCreatedByBadge } from '@/features/flows/components/flow-created-by-badge';
import { FlowStatusToggle } from '@/features/flows/components/flow-status-toggle';
@@ -71,8 +80,11 @@ type AutomationsTableRowProps = {
onCreateInFolder?: (folderId: string, kind: CreateInFolderKind) => void;
userHasPermissionToWriteFlow?: boolean;
userHasPermissionToWriteTable?: boolean;
+ userHasPermissionToWriteAgent: boolean;
+ agentsVisible?: boolean;
isCreatingFlow?: boolean;
isCreatingTable?: boolean;
+ isCreatingAgent?: boolean;
isMoving: boolean;
isDuplicating: boolean;
onLoadMore?: () => void;
@@ -95,8 +107,11 @@ export const AutomationsTableRow = ({
onCreateInFolder,
userHasPermissionToWriteFlow = true,
userHasPermissionToWriteTable = true,
+ userHasPermissionToWriteAgent,
+ agentsVisible = false,
isCreatingFlow,
isCreatingTable,
+ isCreatingAgent,
isMoving,
isDuplicating,
onLoadMore,
@@ -105,6 +120,7 @@ export const AutomationsTableRow = ({
const [isMoveOpen, setIsMoveOpen] = useState(false);
const [moveFolderId, setMoveFolderId] = useState('');
const [isCreateTooltipOpen, setIsCreateTooltipOpen] = useState(false);
+ const [isDeleteAgentOpen, setIsDeleteAgentOpen] = useState(false);
if (item.type === 'load-more-folder') {
return (
@@ -211,6 +227,12 @@ export const AutomationsTableRow = ({
<FlowCreatedByBadge createdBy={item.data.createdBy} />
</>
)}
+ {isAgentItem(item) &&
+ (item.data.isPublished ? (
+ <Badge variant="success">{t('Live')}</Badge>
+ ) : (
+ <Badge variant="outline">{t('Draft')}</Badge>
+ ))}
</div>
<div
className="w-[80px] shrink-0 px-2 flex items-center justify-end gap-1"
@@ -227,10 +249,17 @@ export const AutomationsTableRow = ({
userHasPermissionToWriteFlow={userHasPermissionToWriteFlow}
userHasPermissionToWriteTable={userHasPermissionToWriteTable}
userHasPermissionToWriteFolder={false}
+ userHasPermissionToWriteAgent={userHasPermissionToWriteAgent}
isCreatingFlow={isCreatingFlow}
isCreatingTable={isCreatingTable}
+ isCreatingAgent={isCreatingAgent}
onCreateFlow={() => onCreateInFolder(item.id, 'flow')}
onCreateTable={() => onCreateInFolder(item.id, 'table')}
+ onCreateAgent={
+ agentsVisible
+ ? () => onCreateInFolder(item.id, 'agent')
+ : undefined
+ }
onImportFlow={() => onCreateInFolder(item.id, 'import-flow')}
onImportTable={() => onCreateInFolder(item.id, 'import-table')}
onOpenChange={(open) => {
@@ -255,7 +284,12 @@ export const AutomationsTableRow = ({
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon" className="h-8 w-8">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ disabled={isAgentItem(item) && !userHasPermissionToWriteAgent}
+ >
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
@@ -293,18 +327,17 @@ export const AutomationsTableRow = ({
</DropdownMenuItem>
)}
- {(item.type === 'flow' || item.type === 'table') &&
- !embedState.hideFolders && (
- <DropdownMenuItem
- onClick={() => {
- setMoveFolderId('');
- setIsMoveOpen(true);
- }}
- >
- <CornerUpLeft className="h-4 w-4 mr-2" />
- {t('Move To')}
- </DropdownMenuItem>
- )}
+ {item.type !== 'folder' && !embedState.hideFolders && (
+ <DropdownMenuItem
+ onClick={() => {
+ setMoveFolderId('');
+ setIsMoveOpen(true);
+ }}
+ >
+ <CornerUpLeft className="h-4 w-4 mr-2" />
+ {t('Move To')}
+ </DropdownMenuItem>
+ )}
{isFlowItem(item) && !embedState.hideExportAndImportFlow && (
<DropdownMenuItem onClick={() => onExportFlow(item.data)}>
@@ -333,26 +366,44 @@ export const AutomationsTableRow = ({
)}
<DropdownMenuSeparator />
- <ConfirmationDeleteDialog
- title={t('Delete {type}', { type: item.type })}
- message={t('Deleting "{name}" cannot be undone.', {
- name: item.name,
- })}
- mutationFn={async () => onDelete()}
- entityName={item.type}
- buttonText={t('Delete')}
- >
+ {isAgentItem(item) ? (
<DropdownMenuItem
- onSelect={(e) => e.preventDefault()}
+ onSelect={() => setIsDeleteAgentOpen(true)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="h-4 w-4 mr-2" />
{t('Delete')}
</DropdownMenuItem>
- </ConfirmationDeleteDialog>
+ ) : (
+ <ConfirmationDeleteDialog
+ title={t('Delete {type}', { type: item.type })}
+ message={t('Deleting "{name}" cannot be undone.', {
+ name: item.name,
+ })}
+ mutationFn={async () => onDelete()}
+ entityName={item.type}
+ buttonText={t('Delete')}
+ >
+ <DropdownMenuItem
+ onSelect={(e) => e.preventDefault()}
+ className="text-destructive focus:text-destructive"
+ >
+ <Trash2 className="h-4 w-4 mr-2" />
+ {t('Delete')}
+ </DropdownMenuItem>
+ </ConfirmationDeleteDialog>
+ )}
</DropdownMenuContent>
</DropdownMenu>
+ {isAgentItem(item) && (
+ <DeleteAgentDialog
+ agent={item.data}
+ open={isDeleteAgentOpen}
+ onOpenChange={setIsDeleteAgentOpen}
+ />
+ )}
+
<MoveToFolderDialog
open={isMoveOpen}
onOpenChange={setIsMoveOpen}
@@ -376,6 +427,8 @@ const RowItemIcon = ({ item }: { item: TreeItem }) => {
return <Folder className="h-4 w-4 text-gray-400 fill-gray-400" />;
case 'flow':
return <Workflow className="h-4 w-4 text-primary" />;
+ case 'agent':
+ return <Bot className="h-4 w-4 text-amber-500" />;
default:
return <Table2 className="h-4 w-4 text-emerald-500" />;
}
@@ -389,6 +442,15 @@ const RowItemDetails = ({ item }: { item: TreeItem }) => {
</span>
);
}
+ if (isAgentItem(item)) {
+ return (
+ <AgentToolStack
+ toolCount={item.data.toolCount}
+ toolPieceNames={item.data.toolPieceNames}
+ toolTypes={item.data.toolTypes}
+ />
+ );
+ }
if (isFlowItem(item)) {
return (
<PieceIconList
@@ -402,7 +464,7 @@ const RowItemDetails = ({ item }: { item: TreeItem }) => {
};
const RowItemOwner = ({ item }: { item: TreeItem }) => {
- if (isFlowItem(item)) {
+ if (isFlowItem(item) || isAgentItem(item)) {
if (item.data.ownerId) {
return (
<ApAvatar
@@ -428,3 +490,9 @@ function isTableItem(
): item is Omit<TreeItem, 'data'> & { data: Table } {
return item.type === 'table';
}
+
+function isAgentItem(
+ item: TreeItem,
+): item is Omit<TreeItem, 'data'> & { data: AgentSummary } {
+ return item.type === 'agent';
+}
diff --git a/packages/web/src/features/automations/components/automations-table.tsx b/packages/web/src/features/automations/components/automations-table.tsx
index 0d914e0902b..97f08e64255 100644
--- a/packages/web/src/features/automations/components/automations-table.tsx
+++ b/packages/web/src/features/automations/components/automations-table.tsx
@@ -51,8 +51,11 @@ type AutomationsTableProps = {
onCreateInFolder?: (folderId: string, kind: CreateInFolderKind) => void;
userHasPermissionToWriteFlow?: boolean;
userHasPermissionToWriteTable?: boolean;
+ userHasPermissionToWriteAgent: boolean;
+ agentsVisible: boolean;
isCreatingFlow?: boolean;
isCreatingTable?: boolean;
+ isCreatingAgent?: boolean;
isMoving: boolean;
isDuplicating: boolean;
onLoadMoreInFolder: (folderId: string) => void;
@@ -122,8 +125,11 @@ export const AutomationsTable = ({
onCreateInFolder,
userHasPermissionToWriteFlow,
userHasPermissionToWriteTable,
+ userHasPermissionToWriteAgent,
+ agentsVisible,
isCreatingFlow,
isCreatingTable,
+ isCreatingAgent,
isMoving,
isDuplicating,
onLoadMoreInFolder,
@@ -243,8 +249,13 @@ export const AutomationsTable = ({
userHasPermissionToWriteTable={
userHasPermissionToWriteTable
}
+ userHasPermissionToWriteAgent={
+ userHasPermissionToWriteAgent
+ }
+ agentsVisible={agentsVisible}
isCreatingFlow={isCreatingFlow}
isCreatingTable={isCreatingTable}
+ isCreatingAgent={isCreatingAgent}
isMoving={isMoving}
isDuplicating={isDuplicating}
onLoadMore={undefined}
@@ -277,6 +288,9 @@ export const AutomationsTable = ({
onMoveTo={onMoveItem}
onExportFlow={onExportFlow}
onExportTable={onExportTable}
+ userHasPermissionToWriteAgent={
+ userHasPermissionToWriteAgent
+ }
isMoving={isMoving}
isDuplicating={isDuplicating}
onLoadMore={
@@ -316,6 +330,9 @@ export const AutomationsTable = ({
onMoveTo={onMoveItem}
onExportFlow={onExportFlow}
onExportTable={onExportTable}
+ userHasPermissionToWriteAgent={
+ userHasPermissionToWriteAgent
+ }
isMoving={isMoving}
isDuplicating={isDuplicating}
onLoadMore={undefined}
diff --git a/packages/web/src/features/automations/components/create-new-menu.tsx b/packages/web/src/features/automations/components/create-new-menu.tsx
index 98452e75462..19646afccbf 100644
--- a/packages/web/src/features/automations/components/create-new-menu.tsx
+++ b/packages/web/src/features/automations/components/create-new-menu.tsx
@@ -1,5 +1,6 @@
import { t } from 'i18next';
import {
+ Bot,
FolderPlus,
Loader2,
Sparkles,
@@ -28,8 +29,11 @@ export const CreateNewMenu = ({
userHasPermissionToWriteFolder,
isCreatingFlow = false,
isCreatingTable = false,
+ isCreatingAgent = false,
+ userHasPermissionToWriteAgent = false,
onCreateFlow,
onCreateTable,
+ onCreateAgent,
onCreateFolder,
onImportFlow,
onImportTable,
@@ -41,7 +45,7 @@ export const CreateNewMenu = ({
const showFolder = scope === 'root' && !embedState.hideFolders;
const showTemplate = scope === 'root';
- const busy = isCreatingFlow || isCreatingTable;
+ const busy = isCreatingFlow || isCreatingTable || isCreatingAgent;
return (
<DropdownMenu
@@ -107,6 +111,28 @@ export const CreateNewMenu = ({
</PermissionNeededTooltip>
)}
+ {onCreateAgent && (
+ <PermissionNeededTooltip
+ hasPermission={userHasPermissionToWriteAgent}
+ >
+ <DropdownMenuItem
+ disabled={!userHasPermissionToWriteAgent || busy}
+ onSelect={(e) => {
+ e.preventDefault();
+ onCreateAgent();
+ }}
+ className="cursor-pointer"
+ >
+ {isCreatingAgent ? (
+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />
+ ) : (
+ <Bot className="h-4 w-4 mr-2" />
+ )}
+ {isCreatingAgent ? t('Creating...') : t('New Agent')}
+ </DropdownMenuItem>
+ </PermissionNeededTooltip>
+ )}
+
{scope === 'folder' &&
(!embedState.hideExportAndImportFlow || !embedState.hideTables) && (
<>
@@ -173,8 +199,11 @@ type CreateNewMenuProps = {
userHasPermissionToWriteFolder: boolean;
isCreatingFlow?: boolean;
isCreatingTable?: boolean;
+ isCreatingAgent?: boolean;
+ userHasPermissionToWriteAgent?: boolean;
onCreateFlow: () => void;
onCreateTable: () => void;
+ onCreateAgent?: () => void;
onCreateFolder?: () => void;
onImportFlow: () => void;
onImportTable: () => void;
@@ -185,5 +214,6 @@ type CreateNewMenuProps = {
export type CreateInFolderKind =
| 'flow'
| 'table'
+ | 'agent'
| 'import-flow'
| 'import-table';
diff --git a/packages/web/src/features/automations/hooks/use-automations-data.ts b/packages/web/src/features/automations/hooks/use-automations-data.ts
index f8396a18f64..b1ebf538888 100644
--- a/packages/web/src/features/automations/hooks/use-automations-data.ts
+++ b/packages/web/src/features/automations/hooks/use-automations-data.ts
@@ -1,9 +1,11 @@
import { SeekPage } from '@activepieces/core-utils';
import {
+ AgentSummary,
FlowStatus,
FolderDto,
PopulatedFlow,
Table,
+ MAX_AGENT_PAGE_SIZE,
UncategorizedFolderId,
} from '@activepieces/shared';
import { useQuery, useQueryClient } from '@tanstack/react-query';
@@ -11,6 +13,8 @@ import { useCallback, useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useEmbedding } from '@/components/providers/embed-provider';
+import { useAgentsNavVisible } from '@/features/agents';
+import { agentsApi } from '@/features/agents/api/agents';
import { flowsApi } from '@/features/flows/api/flows-api';
import { foldersApi } from '@/features/folders/api/folders-api';
import { tablesApi } from '@/features/tables/api/tables-api';
@@ -44,6 +48,7 @@ export function useAutomationsData({
const queryClient = useQueryClient();
const { embedState } = useEmbedding();
const hideTables = embedState.hideTables;
+ const agentsVisible = useAgentsNavVisible() && !embedState.isEmbedded;
const isFiltered = hasNonFolderFilters(filters);
const [rootPage, setRootPage] = useState(0);
@@ -70,6 +75,27 @@ export function useAutomationsData({
const skipTables =
(filters.typeFilter.length > 0 && !filters.typeFilter.includes('table')) ||
hasConnectionFilter;
+ const skipAgents =
+ !agentsVisible ||
+ (filters.typeFilter.length > 0 && !filters.typeFilter.includes('agent')) ||
+ hasConnectionFilter ||
+ filters.statusFilter.length > 0;
+
+ const agentsQuery = useQuery({
+ queryKey: ['agents', 'automations', projectId],
+ queryFn: () => listAllProjectAgents(projectId),
+ enabled: !skipAgents,
+ staleTime: STALE_TIME,
+ refetchOnMount: 'always',
+ });
+ const allAgents = useMemo(
+ () => (skipAgents ? [] : agentsQuery.data ?? []),
+ [skipAgents, agentsQuery.data],
+ );
+ const agentsByFolder = useMemo(
+ () => groupAgentsByFolder(allAgents),
+ [allAgents],
+ );
const folderCounts = useMemo(() => {
const folders = foldersQuery.data ?? [];
@@ -77,10 +103,11 @@ export function useAutomationsData({
folders.map((folder) => [
folder.id,
(skipFlows ? 0 : folder.numberOfFlows) +
- (hideTables || skipTables ? 0 : folder.numberOfTables),
+ (hideTables || skipTables ? 0 : folder.numberOfTables) +
+ (agentsByFolder.get(folder.id)?.length ?? 0),
]),
);
- }, [foldersQuery.data, hideTables, skipFlows, skipTables]);
+ }, [foldersQuery.data, hideTables, skipFlows, skipTables, agentsByFolder]);
const folderContentsQuery = useQuery<FolderContentsMap>({
queryKey: ['all-folder-contents', projectId, folderIds, hideTables],
@@ -103,7 +130,11 @@ export function useAutomationsData({
cursor: undefined,
}),
]);
- return buildFolderContentsMap(folders, flowsPage.data, tablesPage.data);
+ return buildFolderContentsMap({
+ folders,
+ flows: flowsPage.data,
+ tables: tablesPage.data,
+ });
},
enabled: !!foldersQuery.data && foldersQuery.data.length > 0,
staleTime: STALE_TIME,
@@ -194,8 +225,18 @@ export function useAutomationsData({
let folders = foldersQuery.data ?? [];
let rootFlows = rootFlowsQuery.data?.data ?? [];
let rootTables = rootTablesQuery.data?.data ?? [];
+ let rootAgents = matchingAgents({
+ agents: allAgents,
+ searchTerm: filters.searchTerm,
+ onlyUnfiled: !isFiltered,
+ });
const folderContents = filterFolderContents({
- folderContents: folderContentsQuery.data ?? new Map(),
+ folderContents: new Map(
+ [...(folderContentsQuery.data ?? [])].map(([folderId, content]) => [
+ folderId,
+ { ...content, agents: agentsByFolder.get(folderId) ?? [] },
+ ]),
+ ),
skipFlows,
skipTables,
connectionFilter: filters.connectionFilter,
@@ -204,7 +245,9 @@ export function useAutomationsData({
? new Map(
[...folderContents].map(([folderId, content]) => [
folderId,
- content.flows.length + content.tables.length,
+ content.flows.length +
+ content.tables.length +
+ content.agents.length,
]),
)
: folderCounts;
@@ -220,11 +263,15 @@ export function useAutomationsData({
rootTables = rootTables.filter(
(t) => t.folderId && folderSet.has(t.folderId),
);
+ rootAgents = rootAgents.filter(
+ (a) => a.folderId && folderSet.has(a.folderId),
+ );
}
const { items, totalItems } = buildFilteredTreeItems({
flows: rootFlows,
tables: rootTables,
+ agents: rootAgents,
folders,
folderVisibleCounts,
page: rootPage,
@@ -243,12 +290,14 @@ export function useAutomationsData({
folders = folders.filter((f) => folderSet.has(f.id));
rootFlows = [];
rootTables = [];
+ rootAgents = [];
}
const { items, totalRootItems } = buildTreeItems({
folders,
rootFlows,
rootTables,
+ rootAgents,
folderContents,
folderCounts,
folderVisibleCounts,
@@ -263,6 +312,8 @@ export function useAutomationsData({
foldersQuery.data,
rootFlowsQuery.data,
rootTablesQuery.data,
+ allAgents,
+ agentsByFolder,
folderContentsQuery.data,
folderCounts,
folderVisibleCounts,
@@ -296,12 +347,14 @@ export function useAutomationsData({
foldersQuery.isLoading ||
(rootFlowsQuery.isLoading && !skipFlows) ||
(rootTablesQuery.isLoading && !skipTables && !hideTables) ||
+ (agentsQuery.isLoading && !skipAgents) ||
folderContentsQuery.isLoading;
const isError =
foldersQuery.isError ||
(rootFlowsQuery.isError && !skipFlows) ||
(rootTablesQuery.isError && !skipTables && !hideTables) ||
+ (agentsQuery.isError && !skipAgents) ||
folderContentsQuery.isError;
const invalidateAll = useCallback(() => {
@@ -310,18 +363,21 @@ export function useAutomationsData({
queryClient.invalidateQueries({ queryKey: ['root-flows'] }),
queryClient.invalidateQueries({ queryKey: ['root-tables'] }),
queryClient.invalidateQueries({ queryKey: ['all-folder-contents'] }),
+ queryClient.invalidateQueries({ queryKey: ['agents'] }),
]);
}, [queryClient]);
const invalidateRoot = useCallback(() => {
queryClient.invalidateQueries({ queryKey: ['root-flows'] });
queryClient.invalidateQueries({ queryKey: ['root-tables'] });
+ queryClient.invalidateQueries({ queryKey: ['agents'] });
}, [queryClient]);
const invalidateFolder = useCallback(
(_folderId: string) => {
queryClient.invalidateQueries({ queryKey: ['all-folder-contents'] });
queryClient.invalidateQueries({ queryKey: ['folders'] });
+ queryClient.invalidateQueries({ queryKey: ['agents'] });
},
[queryClient],
);
@@ -331,6 +387,8 @@ export function useAutomationsData({
folders: foldersQuery.data ?? [],
rootFlows: rootFlowsQuery.data?.data ?? [],
rootTables: rootTablesQuery.data?.data ?? [],
+ agents: allAgents,
+ agentsVisible,
isLoading,
isError,
isFiltered,
@@ -363,13 +421,65 @@ function sortOrder(sort: AutomationsSort): 'ASC' | 'DESC' | undefined {
type FolderContentsMap = Map<string, FolderContent>;
-function buildFolderContentsMap(
- folders: FolderDto[],
- flows: PopulatedFlow[],
- tables: Table[],
-): FolderContentsMap {
+async function listAllProjectAgents(
+ projectId: string,
+): Promise<AgentSummary[]> {
+ const agents: AgentSummary[] = [];
+ let cursor: string | undefined = undefined;
+ do {
+ const page: SeekPage<AgentSummary> = await agentsApi.list({
+ projectId,
+ limit: MAX_AGENT_PAGE_SIZE,
+ ...(cursor ? { cursor } : {}),
+ });
+ agents.push(...page.data);
+ cursor = page.next ?? undefined;
+ } while (cursor);
+ return agents;
+}
+
+function groupAgentsByFolder(
+ agents: AgentSummary[],
+): Map<string, AgentSummary[]> {
+ return agents.reduce((byFolder, agent) => {
+ if (agent.folderId) {
+ byFolder.set(agent.folderId, [
+ ...(byFolder.get(agent.folderId) ?? []),
+ agent,
+ ]);
+ }
+ return byFolder;
+ }, new Map<string, AgentSummary[]>());
+}
+
+function matchingAgents({
+ agents,
+ searchTerm,
+ onlyUnfiled,
+}: {
+ agents: AgentSummary[];
+ searchTerm: string;
+ onlyUnfiled: boolean;
+}): AgentSummary[] {
+ const term = searchTerm.trim().toLowerCase();
+ return agents.filter(
+ (agent) =>
+ (!onlyUnfiled || !agent.folderId) &&
+ (term.length === 0 || agent.displayName.toLowerCase().includes(term)),
+ );
+}
+
+function buildFolderContentsMap({
+ folders,
+ flows,
+ tables,
+}: {
+ folders: FolderDto[];
+ flows: PopulatedFlow[];
+ tables: Table[];
+}): FolderContentsMap {
const map: FolderContentsMap = new Map(
- folders.map((folder) => [folder.id, { flows: [], tables: [] }]),
+ folders.map((folder) => [folder.id, { flows: [], tables: [], agents: [] }]),
);
flows.forEach((flow) => {
if (flow.folderId) {
@@ -410,6 +520,7 @@ function filterFolderContents({
{
flows: skipFlows ? [] : content.flows.filter(keepFlow),
tables: skipTables ? [] : content.tables,
+ agents: content.agents,
},
]),
);
diff --git a/packages/web/src/features/automations/hooks/use-automations-mutations.ts b/packages/web/src/features/automations/hooks/use-automations-mutations.ts
index 568f4d25a35..f1005399b11 100644
--- a/packages/web/src/features/automations/hooks/use-automations-mutations.ts
+++ b/packages/web/src/features/automations/hooks/use-automations-mutations.ts
@@ -1,5 +1,6 @@
import { isNil } from '@activepieces/core-utils';
import {
+ Agent,
FlowOperationType,
PopulatedFlow,
Table,
@@ -8,9 +9,12 @@ import {
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { t } from 'i18next';
import { useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useLocation, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
+import { agentsApi } from '@/features/agents/api/agents';
+import { describeUsage } from '@/features/agents/delete-agent-dialog';
+import { blankAgentUtils } from '@/features/agents/lib/blank-agent';
import { flowsApi } from '@/features/flows/api/flows-api';
import { flowHooks } from '@/features/flows/hooks/flow-hooks';
import { foldersApi } from '@/features/folders/api/folders-api';
@@ -37,6 +41,7 @@ type MutationDeps = {
export function useAutomationsMutations(deps: MutationDeps) {
const openNewWindow = useNewWindow();
const navigate = useNavigate();
+ const location = useLocation();
const queryClient = useQueryClient();
const projectId = authenticationSession.getProjectId() ?? '';
@@ -76,6 +81,24 @@ export function useAutomationsMutations(deps: MutationDeps) {
},
});
+ const { mutate: createAgentMutation, isPending: isCreatingAgent } =
+ useMutation<Agent, Error, string | undefined>({
+ mutationFn: async (folderId) =>
+ agentsApi.create(
+ blankAgentUtils.request({
+ projectId,
+ folderId: toFolderId(folderId),
+ }),
+ ),
+ onSuccess: (agent) => {
+ deps.invalidateRoot();
+ navigate(`/projects/${agent.projectId}/agents/${agent.id}`, {
+ state: { backTo: `${location.pathname}${location.search}` },
+ });
+ },
+ onError: () => toast.error(t('Failed to create agent')),
+ });
+
const { mutate: exportFlows, isPending: isExportFlowsPending } =
flowHooks.useExportFlows();
@@ -102,20 +125,22 @@ export function useAutomationsMutations(deps: MutationDeps) {
const { mutateAsync: bulkDelete, isPending: isDeleting } = useMutation({
mutationFn: async (selectedItems: SelectedItemsMap) => {
- const { flowIds, tableIds, folderIds } =
+ const { flowIds, tableIds, agentIds, folderIds } =
getSelectedIdsByType(selectedItems);
+ await assertAgentsNotInUse(agentIds);
await Promise.all([
...flowIds.map((id) => flowsApi.delete(id)),
...tableIds.map((id) => tablesApi.delete(id)),
- ...folderIds.map((id) => foldersApi.delete(id)),
+ ...agentIds.map((id) => agentsApi.delete(id)),
]);
+ await Promise.all(folderIds.map((id) => foldersApi.delete(id)));
},
onSuccess: () => {
deps.clearSelection();
deps.invalidateAll();
toast.success(t('Items deleted successfully'));
},
- onError: () => toast.error(t('Failed to delete items')),
+ onError: () => deps.invalidateAll(),
});
const { mutateAsync: bulkMoveTo, isPending: isBulkMoving } = useMutation({
@@ -126,12 +151,13 @@ export function useAutomationsMutations(deps: MutationDeps) {
selectedItems: SelectedItemsMap;
targetFolderId: string;
}) => {
- const { flowIds, tableIds } = getSelectedIdsByType(selectedItems);
- const folderId =
- isNil(targetFolderId) || targetFolderId === UncategorizedFolderId
- ? null
- : targetFolderId;
+ const { flowIds, tableIds, agentIds } =
+ getSelectedIdsByType(selectedItems);
+ const folderId = toFolderId(targetFolderId);
await Promise.all([
+ ...agentIds.map((id) =>
+ agentsApi.update(id, { folderId, goLive: false }),
+ ),
...flowIds.map((id) =>
flowsApi.update(id, {
type: FlowOperationType.CHANGE_FOLDER,
@@ -169,6 +195,11 @@ export function useAutomationsMutations(deps: MutationDeps) {
});
} else if (item.type === 'table') {
await tablesApi.update(item.id, { name: newName });
+ } else if (item.type === 'agent') {
+ await agentsApi.update(item.id, {
+ displayName: newName,
+ goLive: false,
+ });
} else if (item.type === 'folder') {
await foldersApi.renameFolder(item.id, { displayName: newName });
}
@@ -215,10 +246,7 @@ export function useAutomationsMutations(deps: MutationDeps) {
item: TreeItem;
targetFolderId: string;
}) => {
- const folderId =
- isNil(targetFolderId) || targetFolderId === UncategorizedFolderId
- ? null
- : targetFolderId;
+ const folderId = toFolderId(targetFolderId);
if (item.type === 'flow') {
await flowsApi.update(item.id, {
type: FlowOperationType.CHANGE_FOLDER,
@@ -226,6 +254,8 @@ export function useAutomationsMutations(deps: MutationDeps) {
});
} else if (item.type === 'table') {
await tablesApi.update(item.id, { folderId });
+ } else if (item.type === 'agent') {
+ await agentsApi.update(item.id, { folderId, goLive: false });
}
},
onSuccess: (_data, { item, targetFolderId }) => {
@@ -295,8 +325,10 @@ export function useAutomationsMutations(deps: MutationDeps) {
createFlow: (folderId?: string) => startFromScratch(folderId),
createTable: (name: string, folderId?: string) =>
createTableMutation({ name, folderId }),
+ createAgent: (folderId?: string) => createAgentMutation(folderId),
isCreateFlowPending,
isCreatingTable,
+ isCreatingAgent,
handleDeleteItem: deleteItem,
handleBulkDelete: bulkDelete,
handleBulkMoveTo: (
@@ -319,6 +351,31 @@ export function useAutomationsMutations(deps: MutationDeps) {
};
}
+async function assertAgentsNotInUse(agentIds: string[]): Promise<void> {
+ const agents = await Promise.all(
+ agentIds.map((id) => agentsApi.get(id, { includeUsage: true })),
+ );
+ const inUse = agents.find(
+ (agent) => (agent.publishedFlowsUsingAgent?.total ?? 0) > 0,
+ );
+ if (inUse) {
+ throw new Error(
+ t('{name} cannot be deleted. {usage}', {
+ name: inUse.displayName,
+ usage: describeUsage(inUse.publishedFlowsUsingAgent),
+ }),
+ );
+ }
+}
+
+function toFolderId(folderId: string | undefined): string | null {
+ return isNil(folderId) ||
+ folderId === '' ||
+ folderId === UncategorizedFolderId
+ ? null
+ : folderId;
+}
+
function isFlowTreeItem(
item: TreeItem,
): item is TreeItem & { data: PopulatedFlow } {
diff --git a/packages/web/src/features/automations/hooks/use-automations-selection.ts b/packages/web/src/features/automations/hooks/use-automations-selection.ts
index 9eb1e0c96c2..9c7434a09f0 100644
--- a/packages/web/src/features/automations/hooks/use-automations-selection.ts
+++ b/packages/web/src/features/automations/hooks/use-automations-selection.ts
@@ -115,6 +115,7 @@ export function useAutomationsSelection(treeItems: TreeItem[]) {
export function getSelectedIdsByType(selected: SelectedItemsMap) {
const flowIds: string[] = [];
const tableIds: string[] = [];
+ const agentIds: string[] = [];
const folderIds: string[] = [];
for (const [key, type] of selected) {
@@ -126,20 +127,24 @@ export function getSelectedIdsByType(selected: SelectedItemsMap) {
case 'table':
tableIds.push(id);
break;
+ case 'agent':
+ agentIds.push(id);
+ break;
case 'folder':
folderIds.push(id);
break;
}
}
- return { flowIds, tableIds, folderIds };
+ return { flowIds, tableIds, agentIds, folderIds };
}
-export function hasMovableOrExportableItems(selected: SelectedItemsMap) {
- for (const type of selected.values()) {
- if (type === 'flow' || type === 'table') {
- return true;
- }
- }
- return false;
+export function hasMovableItems(selected: SelectedItemsMap) {
+ return [...selected.values()].some((type) => type !== 'folder');
+}
+
+export function hasExportableItems(selected: SelectedItemsMap) {
+ return [...selected.values()].some(
+ (type) => type === 'flow' || type === 'table',
+ );
}
diff --git a/packages/web/src/features/automations/lib/types.ts b/packages/web/src/features/automations/lib/types.ts
index 262151d7738..b877619a06f 100644
--- a/packages/web/src/features/automations/lib/types.ts
+++ b/packages/web/src/features/automations/lib/types.ts
@@ -1,8 +1,18 @@
-import { FolderDto, PopulatedFlow, Table } from '@activepieces/shared';
+import {
+ AgentSummary,
+ FolderDto,
+ PopulatedFlow,
+ Table,
+} from '@activepieces/shared';
-export type TreeItemType = 'folder' | 'flow' | 'table' | 'load-more-folder';
+export type TreeItemType =
+ | 'folder'
+ | 'flow'
+ | 'table'
+ | 'agent'
+ | 'load-more-folder';
-export type SelectableItemType = 'folder' | 'flow' | 'table';
+export type SelectableItemType = 'folder' | 'flow' | 'table' | 'agent';
export type SelectedItemsMap = Map<string, SelectableItemType>;
@@ -10,7 +20,7 @@ export type TreeItem = {
id: string;
type: TreeItemType;
name: string;
- data: FolderDto | PopulatedFlow | Table | null;
+ data: FolderDto | PopulatedFlow | Table | AgentSummary | null;
depth: number;
folderId: string | null;
childCount?: number;
@@ -29,6 +39,7 @@ export type AutomationsFilters = {
export type FolderContent = {
flows: PopulatedFlow[];
tables: Table[];
+ agents: AgentSummary[];
};
export type AutomationsSort = 'default' | 'name-asc' | 'name-desc';
diff --git a/packages/web/src/features/automations/lib/utils.ts b/packages/web/src/features/automations/lib/utils.ts
index 809a577dafa..87a0c57d406 100644
--- a/packages/web/src/features/automations/lib/utils.ts
+++ b/packages/web/src/features/automations/lib/utils.ts
@@ -1,4 +1,9 @@
-import { FolderDto, PopulatedFlow, Table } from '@activepieces/shared';
+import {
+ AgentSummary,
+ FolderDto,
+ PopulatedFlow,
+ Table,
+} from '@activepieces/shared';
import {
AutomationsFilters,
@@ -13,7 +18,7 @@ export const FOLDER_PAGE_SIZE = 50;
export const ROOT_ITEMS_LIMIT = 1000;
export function getUpdatedDate(
- item: PopulatedFlow | Table | FolderDto,
+ item: PopulatedFlow | Table | AgentSummary | FolderDto,
): number {
return new Date(item.updated).getTime();
}
@@ -21,38 +26,18 @@ export function getUpdatedDate(
export function mergeAndSortItems({
flows,
tables,
+ agents,
sort,
}: {
flows: PopulatedFlow[];
tables: Table[];
+ agents: AgentSummary[];
sort: AutomationsSort;
}): TreeItem[] {
- const items: TreeItem[] = [];
-
- flows.forEach((flow) => {
- items.push({
- id: flow.id,
- type: 'flow',
- name: flow.version.displayName,
- data: flow,
- depth: 0,
- folderId: null,
- });
- });
-
- tables.forEach((table) => {
- items.push({
- id: table.id,
- type: 'table',
- name: table.name,
- data: table,
- depth: 0,
- folderId: null,
- });
- });
-
- items.sort(treeItemComparator(sort));
- return items;
+ return toTreeItems({
+ content: { flows, tables, agents },
+ placeIn: () => null,
+ }).sort(treeItemComparator(sort));
}
export function buildFolderChildren({
@@ -68,31 +53,9 @@ export function buildFolderChildren({
totalCount: number;
sort: AutomationsSort;
}): TreeItem[] {
- const children: TreeItem[] = [];
-
- content.flows.forEach((flow) => {
- children.push({
- id: flow.id,
- type: 'flow',
- name: flow.version.displayName,
- data: flow,
- depth: 1,
- folderId,
- });
- });
-
- content.tables.forEach((table) => {
- children.push({
- id: table.id,
- type: 'table',
- name: table.name,
- data: table,
- depth: 1,
- folderId,
- });
- });
-
- children.sort(treeItemComparator(sort));
+ const children = toTreeItems({ content, placeIn: () => folderId }).sort(
+ treeItemComparator(sort),
+ );
const visible = children.slice(0, visibleCount);
const remaining = totalCount - Math.min(visibleCount, children.length);
@@ -116,6 +79,7 @@ export function buildTreeItems({
folders,
rootFlows,
rootTables,
+ rootAgents,
folderContents,
folderCounts,
folderVisibleCounts,
@@ -127,6 +91,7 @@ export function buildTreeItems({
folders: FolderDto[];
rootFlows: PopulatedFlow[];
rootTables: Table[];
+ rootAgents: AgentSummary[];
folderContents: Map<string, FolderContent>;
folderCounts: Map<string, number>;
folderVisibleCounts: Map<string, number>;
@@ -156,10 +121,14 @@ export function buildTreeItems({
const dedupedTables = rootTables.filter(
(t) => !t.folderId || !folderIdSet.has(t.folderId),
);
+ const dedupedAgents = rootAgents.filter(
+ (a) => !a.folderId || !folderIdSet.has(a.folderId),
+ );
const rootItems = mergeAndSortItems({
flows: dedupedFlows,
tables: dedupedTables,
+ agents: dedupedAgents,
sort,
});
const compareItems = treeItemComparator(sort);
@@ -215,6 +184,7 @@ export function buildTreeItems({
export function buildFilteredTreeItems({
flows,
tables,
+ agents,
folders,
folderVisibleCounts,
page,
@@ -227,6 +197,7 @@ export function buildFilteredTreeItems({
}: {
flows: PopulatedFlow[];
tables: Table[];
+ agents: AgentSummary[];
folders: FolderDto[];
folderVisibleCounts: Map<string, number>;
page: number;
@@ -244,37 +215,11 @@ export function buildFilteredTreeItems({
const folderChildren = new Map<string, TreeItem[]>();
const rootItems: TreeItem[] = [];
- flows.forEach((flow) => {
- const itemFolderId =
- flow.folderId && folderMap.has(flow.folderId) ? flow.folderId : null;
- const item: TreeItem = {
- id: flow.id,
- type: 'flow',
- name: flow.version.displayName,
- data: flow,
- depth: itemFolderId ? 1 : 0,
- folderId: itemFolderId,
- };
- if (item.folderId) {
- const list = folderChildren.get(item.folderId) ?? [];
- list.push(item);
- folderChildren.set(item.folderId, list);
- } else {
- rootItems.push(item);
- }
- });
-
- tables.forEach((table) => {
- const itemFolderId =
- table.folderId && folderMap.has(table.folderId) ? table.folderId : null;
- const item: TreeItem = {
- id: table.id,
- type: 'table',
- name: table.name,
- data: table,
- depth: itemFolderId ? 1 : 0,
- folderId: itemFolderId,
- };
+ toTreeItems({
+ content: { flows, tables, agents },
+ placeIn: (entityFolderId) =>
+ entityFolderId && folderMap.has(entityFolderId) ? entityFolderId : null,
+ }).forEach((item) => {
if (item.folderId) {
const list = folderChildren.get(item.folderId) ?? [];
list.push(item);
@@ -425,6 +370,42 @@ export function groupTreeItemsByFolder(items: TreeItem[]): TreeRow[] {
}, []);
}
+function toTreeItems({
+ content,
+ placeIn,
+}: {
+ content: FolderContent;
+ placeIn: (entityFolderId: string | null) => string | null;
+}): TreeItem[] {
+ const entries = [
+ ...content.flows.map((flow) => ({
+ id: flow.id,
+ type: 'flow' as const,
+ name: flow.version.displayName,
+ data: flow,
+ entityFolderId: flow.folderId ?? null,
+ })),
+ ...content.tables.map((table) => ({
+ id: table.id,
+ type: 'table' as const,
+ name: table.name,
+ data: table,
+ entityFolderId: table.folderId ?? null,
+ })),
+ ...content.agents.map((agent) => ({
+ id: agent.id,
+ type: 'agent' as const,
+ name: agent.displayName,
+ data: agent,
+ entityFolderId: agent.folderId ?? null,
+ })),
+ ];
+ return entries.map(({ entityFolderId, ...entry }) => {
+ const folderId = placeIn(entityFolderId);
+ return { ...entry, depth: folderId ? 1 : 0, folderId };
+ });
+}
+
function treeItemComparator(
sort: AutomationsSort,
): (a: TreeItem, b: TreeItem) => number {
diff --git a/packages/web/test/features/agents/agent-tool-stack.test.tsx b/packages/web/test/features/agents/agent-tool-stack.test.tsx
new file mode 100644
index 00000000000..82ac444ef4f
--- /dev/null
+++ b/packages/web/test/features/agents/agent-tool-stack.test.tsx
@@ -0,0 +1,75 @@
+// @vitest-environment jsdom
+import { AgentToolType } from '@activepieces/shared';
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/features/pieces/hooks/pieces-hooks', () => ({
+ piecesHooks: {
+ usePieceSummariesByNames: ({ names }: { names: string[] }) => ({
+ summaries: names.map((name) => ({
+ name,
+ displayName: name,
+ logoUrl: '',
+ })),
+ }),
+ },
+}));
+vi.mock('@/features/pieces/components/piece-icon', () => ({
+ PieceIcon: ({ displayName }: { displayName: string }) => (
+ <span data-testid="piece">{displayName}</span>
+ ),
+}));
+
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { AgentToolStack } from '@/features/agents/agent-tool-stack';
+
+describe('AgentToolStack', () => {
+ it('counts the hidden tools, not the hidden tiles', () => {
+ render(
+ <TooltipProvider>
+ <AgentToolStack
+ toolCount={8}
+ toolPieceNames={['gmail', 'slack', 'sheets']}
+ toolTypes={[
+ ...Array(3).fill(AgentToolType.PIECE),
+ ...Array(5).fill(AgentToolType.FLOW),
+ ]}
+ />
+ </TooltipProvider>,
+ );
+
+ expect(screen.getAllByTestId('piece')).toHaveLength(3);
+ expect(overflowChips()).toEqual(['+5']);
+ });
+
+ it('shows an app once and counts every tool it has', () => {
+ render(
+ <TooltipProvider>
+ <AgentToolStack
+ toolCount={5}
+ toolPieceNames={['gmail', 'gmail', 'gmail', 'slack', 'sheets']}
+ toolTypes={Array(5).fill(AgentToolType.PIECE)}
+ />
+ </TooltipProvider>,
+ );
+
+ expect(
+ screen.getAllByTestId('piece').map((element) => element.textContent),
+ ).toEqual(['gmail', 'slack', 'sheets']);
+ expect(overflowChips()).toEqual([]);
+ });
+
+ it('still counts tools when the server does not say what kind they are', () => {
+ render(
+ <TooltipProvider>
+ <AgentToolStack toolCount={2} toolPieceNames={[]} />
+ </TooltipProvider>,
+ );
+
+ expect(overflowChips()).toEqual(['+2']);
+ });
+});
+
+function overflowChips(): (string | null)[] {
+ return screen.queryAllByText(/^\+\d+$/).map((element) => element.textContent);
+}
diff --git a/packages/web/test/features/automations/lib/utils.test.ts b/packages/web/test/features/automations/lib/utils.test.ts
index 2cfc94d9bda..5b5f300b071 100644
--- a/packages/web/test/features/automations/lib/utils.test.ts
+++ b/packages/web/test/features/automations/lib/utils.test.ts
@@ -1,8 +1,19 @@
-import { FolderDto } from '@activepieces/shared';
+import {
+ AgentIcon,
+ AgentSummary,
+ AgentVisibility,
+ ColorName,
+ FolderDto,
+ Table,
+} from '@activepieces/shared';
import { describe, expect, it } from 'vitest';
import { AutomationsSort } from '@/features/automations/lib/types';
-import { buildTreeItems, nextSort } from '@/features/automations/lib/utils';
+import {
+ buildFilteredTreeItems,
+ buildTreeItems,
+ nextSort,
+} from '@/features/automations/lib/utils';
function folder({
id,
@@ -39,6 +50,7 @@ function sortedNames({
folders,
rootFlows: [],
rootTables: [],
+ rootAgents: [],
folderContents: new Map(),
folderCounts: new Map(),
folderVisibleCounts: new Map(),
@@ -160,3 +172,142 @@ describe('nextSort', () => {
expect(nextSort('name-desc')).toBe('default');
});
});
+
+describe('automations tree with agents', () => {
+ it('lists unfiled agents beside tables and files the rest under their folder', () => {
+ const folder = makeAgentFolder({ id: 'folder1' });
+ const filed = makeAgent({ id: 'agentFiled', folderId: folder.id });
+
+ const { items, totalRootItems } = buildTreeItems({
+ folders: [folder],
+ rootFlows: [],
+ rootTables: [makeTable({ id: 'table1', name: 'Leads' })],
+ rootAgents: [makeAgent({ id: 'agentRoot', displayName: 'Triage' })],
+ folderContents: new Map([
+ [folder.id, { flows: [], tables: [], agents: [filed] }],
+ ]),
+ folderCounts: new Map([[folder.id, 1]]),
+ folderVisibleCounts: new Map(),
+ rootPage: 0,
+ pageSize: 10,
+ sort: 'name-asc',
+ });
+
+ expect(totalRootItems).toBe(3);
+ expect(items.map((item) => [item.type, item.id, item.depth])).toEqual([
+ ['folder', 'folder1', 0],
+ ['agent', 'agentFiled', 1],
+ ['table', 'table1', 0],
+ ['agent', 'agentRoot', 0],
+ ]);
+ });
+
+ it('sorts agents by name together with tables', () => {
+ const { items } = buildTreeItems({
+ folders: [],
+ rootFlows: [],
+ rootTables: [makeTable({ id: 'b', name: 'Beta' })],
+ rootAgents: [
+ makeAgent({ id: 'c', displayName: 'Gamma' }),
+ makeAgent({ id: 'a', displayName: 'Alpha' }),
+ ],
+ folderContents: new Map(),
+ folderCounts: new Map(),
+ folderVisibleCounts: new Map(),
+ rootPage: 0,
+ pageSize: 10,
+ sort: 'name-desc',
+ });
+
+ expect(items.map((item) => item.name)).toEqual(['Gamma', 'Beta', 'Alpha']);
+ });
+
+ it('keeps a matching agent under its folder while searching', () => {
+ const folder = makeAgentFolder({ id: 'folder1' });
+
+ const { items } = buildFilteredTreeItems({
+ flows: [],
+ tables: [],
+ agents: [
+ makeAgent({ id: 'inFolder', folderId: folder.id }),
+ makeAgent({ id: 'atRoot' }),
+ ],
+ folders: [folder],
+ folderVisibleCounts: new Map(),
+ page: 0,
+ pageSize: 10,
+ sort: 'default',
+ });
+
+ expect(
+ items.map((item) => [item.type, item.id, item.folderId, item.depth]),
+ ).toEqual([
+ ['folder', 'folder1', null, 0],
+ ['agent', 'inFolder', 'folder1', 1],
+ ['agent', 'atRoot', null, 0],
+ ]);
+ });
+});
+
+function makeAgent({
+ id,
+ displayName = id,
+ folderId = null,
+}: {
+ id: string;
+ displayName?: string;
+ folderId?: string | null;
+}): AgentSummary {
+ return {
+ id,
+ created: CREATED,
+ updated: CREATED,
+ projectId: PROJECT_ID,
+ ownerId: 'owner1',
+ externalId: id,
+ folderId,
+ displayName,
+ description: null,
+ icon: AgentIcon.BOT,
+ color: ColorName.PURPLE,
+ visibility: AgentVisibility.PROJECT,
+ sharedWithUserIds: [],
+ isPublished: false,
+ toolCount: 0,
+ toolPieceNames: [],
+ toolTypes: [],
+ projectDisplayName: 'Project',
+ projectIsPrivate: false,
+ };
+}
+
+function makeTable({ id, name }: { id: string; name: string }): Table {
+ return {
+ id,
+ created: CREATED,
+ updated: CREATED,
+ name,
+ folderId: null,
+ projectId: PROJECT_ID,
+ externalId: id,
+ status: null,
+ trigger: null,
+ };
+}
+
+function makeAgentFolder({ id }: { id: string }): FolderDto {
+ return {
+ id,
+ created: CREATED,
+ updated: CREATED,
+ projectId: PROJECT_ID,
+ displayName: id,
+ displayOrder: 0,
+ externalId: id,
+ numberOfFlows: 0,
+ numberOfTables: 0,
+ };
+}
+
+const PROJECT_ID = 'project1';
+const CREATED = '2026-09-30T00:00:00.000Z';
diff --git a/packages/web/test/features/automations/use-automations-data.test.tsx b/packages/web/test/features/automations/use-automations-data.test.tsx
index 26c8c2dc2e2..c30f15f1a4f 100644
--- a/packages/web/test/features/automations/use-automations-data.test.tsx
+++ b/packages/web/test/features/automations/use-automations-data.test.tsx
@@ -1,5 +1,13 @@
// @vitest-environment jsdom
-import { FolderDto, PopulatedFlow, Table } from '@activepieces/shared';
+import {
+ AgentIcon,
+ AgentSummary,
+ AgentVisibility,
+ ColorName,
+ FolderDto,
+ PopulatedFlow,
+ Table,
+} from '@activepieces/shared';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook, waitFor } from '@testing-library/react';
import { ReactNode } from 'react';
@@ -18,6 +26,14 @@ vi.mock('@/lib/authentication-session', () => ({
const listFlows = vi.fn();
const listFolders = vi.fn();
const listTables = vi.fn();
+const listAgents = vi.fn();
+const agentsNavVisible = vi.fn();
+vi.mock('@/features/agents', () => ({
+ useAgentsNavVisible: () => agentsNavVisible(),
+}));
+vi.mock('@/features/agents/api/agents', () => ({
+ agentsApi: { list: (request: unknown) => listAgents(request) },
+}));
vi.mock('@/features/flows/api/flows-api', () => ({
flowsApi: { list: (request: unknown) => listFlows(request) },
}));
@@ -106,6 +122,8 @@ describe('useAutomationsData', () => {
listFolders.mockResolvedValue([]);
listFlows.mockResolvedValue({ data: [flow], next: null, previous: null });
listTables.mockResolvedValue({ data: [table], next: null, previous: null });
+ agentsNavVisible.mockReturnValue(false);
+ listAgents.mockResolvedValue({ data: [], next: null, previous: null });
});
it('does not fetch or show tables when a connection filter is active', async () => {
@@ -173,4 +191,147 @@ describe('useAutomationsData', () => {
expect(flowItems).toHaveLength(1);
expect(flowItems[0].id).toBe('flow_2');
});
+
+ it('never asks for agents when the plan or role does not show them', async () => {
+ const { result } = renderAutomationsData(emptyFilters);
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(listAgents).not.toHaveBeenCalled();
+ expect(result.current.agentsVisible).toBe(false);
+ });
+
+ it('shows unfiled agents at the root and counts filed ones in their folder', async () => {
+ agentsNavVisible.mockReturnValue(true);
+ listFolders.mockResolvedValue([folder]);
+ listFlows.mockResolvedValue({ data: [], next: null, previous: null });
+ listTables.mockResolvedValue({ data: [], next: null, previous: null });
+ listAgents.mockResolvedValue({
+ data: [
+ agent({ id: 'agent_root' }),
+ agent({ id: 'agent_filed', folderId: 'folder_1' }),
+ ],
+ next: null,
+ previous: null,
+ });
+
+ const { result } = renderAutomationsData(emptyFilters);
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ const byId = new Map(
+ result.current.treeItems.map((item) => [item.id, item]),
+ );
+ expect(byId.get('agent_root')?.depth).toBe(0);
+ expect(byId.get('agent_filed')?.folderId).toBe('folder_1');
+ expect(byId.get('folder_1')?.childCount).toBe(3);
+ });
+
+ it('walks every page of agents', async () => {
+ agentsNavVisible.mockReturnValue(true);
+ listAgents.mockImplementation((request: { cursor?: string }) =>
+ Promise.resolve(
+ request.cursor === 'page_2'
+ ? { data: [agent({ id: 'agent_2' })], next: null, previous: null }
+ : {
+ data: [agent({ id: 'agent_1' })],
+ next: 'page_2',
+ previous: null,
+ },
+ ),
+ );
+
+ const { result } = renderAutomationsData({
+ ...emptyFilters,
+ typeFilter: ['agent'],
+ });
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(
+ result.current.treeItems
+ .filter((item) => item.type === 'agent')
+ .map((item) => item.id)
+ .sort(),
+ ).toEqual(['agent_1', 'agent_2']);
+ expect(listFlows).not.toHaveBeenCalled();
+ });
+
+ it('leaves agents out under flow-only filters', async () => {
+ agentsNavVisible.mockReturnValue(true);
+ listAgents.mockResolvedValue({
+ data: [agent({ id: 'agent_root' })],
+ next: null,
+ previous: null,
+ });
+
+ const { result } = renderAutomationsData({
+ ...emptyFilters,
+ statusFilter: ['ENABLED'],
+ });
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(listAgents).not.toHaveBeenCalled();
+ expect(
+ result.current.treeItems.filter((item) => item.type === 'agent'),
+ ).toEqual([]);
+ });
+
+ it('matches agents by name while searching', async () => {
+ agentsNavVisible.mockReturnValue(true);
+ listFlows.mockResolvedValue({ data: [], next: null, previous: null });
+ listTables.mockResolvedValue({ data: [], next: null, previous: null });
+ listAgents.mockResolvedValue({
+ data: [
+ agent({ id: 'agent_triage', displayName: 'Ticket Triage' }),
+ agent({ id: 'agent_other', displayName: 'Researcher' }),
+ ],
+ next: null,
+ previous: null,
+ });
+
+ const { result } = renderAutomationsData({
+ ...emptyFilters,
+ searchTerm: 'triage',
+ });
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(result.current.treeItems.map((item) => item.id)).toEqual([
+ 'agent_triage',
+ ]);
+ });
});
+
+function agent({
+ id,
+ displayName = id,
+ folderId = null,
+}: {
+ id: string;
+ displayName?: string;
+ folderId?: string | null;
+}): AgentSummary {
+ return {
+ id,
+ created: '2026-01-01T00:00:00.000Z',
+ updated: '2026-01-02T00:00:00.000Z',
+ projectId: 'test_project',
+ ownerId: 'owner_1',
+ externalId: id,
+ folderId,
+ displayName,
+ description: null,
+ icon: AgentIcon.BOT,
+ color: ColorName.PURPLE,
+ visibility: AgentVisibility.PROJECT,
+ sharedWithUserIds: [],
+ isPublished: true,
+ toolCount: 0,
+ toolPieceNames: [],
+ toolTypes: [],
+ projectDisplayName: 'Project',
+ projectIsPrivate: false,
+ };
+}