AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(agents): saving an agent no longer undoes a change someone made at the same time (#16990)
Hazem Adelbf96e825c6ce
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.mdindex f9a508e28cd..38333de05bc 100644--- a/brain/knowledge/ai-intelligence/ai-agents.md+++ b/brain/knowledge/ai-intelligence/ai-agents.md@@ -122,6 +122,7 @@ 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.+- **Every agent write builds untouched fields from the locked row.** `agentService.update` takes `lockedAgentInProjectOrThrow` and reads draft, published, visibility and share list from that row, like `move` and `editDraftTools`. Values read before the lock are only for permission checks; saving them back undoes a concurrent unpublish, draft edit or share revoke.- **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.diff --git a/packages/server/api/src/app/ee/agent/agent-service.ts b/packages/server/api/src/app/ee/agent/agent-service.tsindex dcf6679a080..e7c63e5522d 100644--- a/packages/server/api/src/app/ee/agent/agent-service.ts+++ b/packages/server/api/src/app/ee/agent/agent-service.ts@@ -117,27 +117,19 @@ export const agentService = (log: FastifyBaseLogger) => ({async update({ id, projectId, platformId, userId, request, goLive = false }: UpdateParams): Promise<Agent> {const agent = await this.getOneOrThrow({ id, projectId, userId })await assertMayChangeWhoCanSee({ agent, request, projectId, userId, log })- const visibility = request.visibility ?? agent.visibility- const sharedWithUserIds = await resolveShare({- visibility,- requested: request.sharedWithUserIds,- stored: agent.sharedWithUserIds,- projectId,- log,- })- const draft = isNil(request.draft) ? agent.draft : sanitizeObjectForPostgresql(await withPinnedKey({ draft: await withTierOrModel({ draft: request.draft, platformId, projectId, log }), platformId, projectId, log }))+ const requestedDraft = isNil(request.draft) ? null : sanitizeObjectForPostgresql(await withPinnedKey({ draft: await withTierOrModel({ draft: request.draft, platformId, projectId, log }), platformId, projectId, log }))await getFolderIdFromRequest({ projectId, folderId: request.folderId ?? undefined, folderName: undefined, log })- const goingLive = goLive && agentUtils.isPublishable(draft)- const published = goingLive ? draft : agent.published- if (goingLive) {- assertDraftIsCoherent(draft)- await assertMayPublishWhatFlowsAlreadyRun({ agent, projectId, platformId, userId, log })- }await transaction(async (entityManager) => {- await lockedAgentInProjectOrThrow({ entityManager, id, projectId })+ const locked = await lockedAgentInProjectOrThrow({ entityManager, id, projectId })+ const draft = requestedDraft ?? locked.draft+ const visibility = request.visibility ?? locked.visibility+ const sharedWithUserIds = await resolveShare({ visibility, requested: request.sharedWithUserIds, stored: locked.sharedWithUserIds, projectId, log })+ const goingLive = goLive && agentUtils.isPublishable(draft)if (goingLive) {- await assertMayPublishWhatFlowsAlreadyRun({ agent, projectId, platformId, userId, log })+ assertDraftIsCoherent(draft)+ await assertMayPublishWhatFlowsAlreadyRun({ agent: locked, projectId, platformId, userId, log })}+ const published = goingLive ? draft : locked.publishedawait entityManager.getRepository(AgentEntity).save({ id, ...omit(request, ['goLive', 'draft', 'visibility', 'sharedWithUserIds']), draft, published, visibility, sharedWithUserIds })})return this.getOneOrThrow({ id, projectId, userId })diff --git a/packages/server/api/test/integration/ee/agent/agent-controller.test.ts b/packages/server/api/test/integration/ee/agent/agent-controller.test.tsindex 4f381e80f06..3229daa7e47 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,5 +1,5 @@import { AIProviderName, apId, Permission, RoleType } from '@activepieces/core-utils'-import { AgentIcon, AgentPieceProps, AgentRunSource, AgentToolType, AgentVisibility, AI_PIECE_NAME, ColorName, DefaultProjectRole, FlowActionType, FlowStatus, FlowTriggerType, FlowVersionState, KnowledgeBaseSourceType } from '@activepieces/shared'+import { Agent, AgentIcon, AgentPieceProps, AgentRunSource, AgentToolType, AgentVisibility, AI_PIECE_NAME, ColorName, DefaultProjectRole, FlowActionType, FlowStatus, FlowTriggerType, FlowVersionState, KnowledgeBaseSourceType } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'import { SelectQueryBuilder } from 'typeorm'@@ -1138,3 +1138,33 @@ function triggerRunningAgent(agentExternalId: string) {},} as const}++describe('updating an agent while someone else changes it', () => {+ it.each([+ ['unpublishes it', { published: null }, (agent: Agent) => expect(agent.published).toBeNull()],+ ['edits its draft', { draft: { ...agentBody('').draft, instructions: 'Newer draft.' } }, (agent: Agent) => expect(agent.draft.instructions).toBe('Newer draft.')],+ ['revokes a share', { sharedWithUserIds: [] }, (agent: Agent) => expect(agent.sharedWithUserIds).toStrictEqual([])],+ ])('keeps the change when another writer %s just before a rename takes the row lock', async (_label, change, expectKept) => {+ const ctx = await context()+ const member = await createMemberContext(app, ctx, { projectRole: DefaultProjectRole.EDITOR })+ const agent = await createAgent(ctx, { visibility: AgentVisibility.RESTRICTED, sharedWithUserIds: [member.user.id] })+ await ctx.post(`/v1/agents/${agent.id}/publish`)+ expect(agent.sharedWithUserIds).toStrictEqual([member.user.id])+ const getOne = SelectQueryBuilder.prototype.getOne+ const concurrentWrite = vi.spyOn(SelectQueryBuilder.prototype, 'getOne').mockImplementation(async function (this: SelectQueryBuilder<Agent>) {+ if (this.expressionMap.lockMode === 'pessimistic_write') {+ concurrentWrite.mockRestore()+ await db.update('agent', agent.id, change)+ }+ return getOne.call(this)+ })++ const rename = await ctx.post(`/v1/agents/${agent.id}`, { displayName: 'Renamed', goLive: false })+ concurrentWrite.mockRestore()++ expect(rename.statusCode).toBe(StatusCodes.OK)+ const stored = await db.findOneByOrFail<Agent>('agent', { id: agent.id })+ expect(stored.displayName).toBe('Renamed')+ expectKept(stored)+ })+})