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

fix(templates): editing a custom template's details no longer erases its workflow (#16415)

Louai Boumedienea9dc502c88ea
diff --git a/brain/knowledge/flows-execution/templates.md b/brain/knowledge/flows-execution/templates.md
index cf5cc3452a4..93e7fb74e31 100644
--- a/brain/knowledge/flows-execution/templates.md
+++ b/brain/knowledge/flows-execution/templates.md
@@ -22,6 +22,7 @@ Templates are a library of reusable flow (and table) blueprints users can browse
- **Custom templates require the `manageTemplatesEnabled` plan flag** (off by default in CE). When disabled, custom listing is skipped silently — returns empty array, no error.
- OFFICIAL and SHARED templates cannot be updated or deleted via API; ownership is double-checked (`template.platformId === principal.platform.id`).
- Flow version migration (`migrateFlowVersionTemplateList`) runs as a `preValidation` hook on create/update to handle schema evolution in stored flows.
+- An update only replaces a template's workflow when it carries a non-empty `flows`. The update `preValidation` turns an absent `flows` into `[]`, so `templateService.update` treats an empty list as "keep what's stored": it validates and prepares flows (against the template's own platform) only when some are sent, then hands those prepared `flows` and `pieces` to `platformTemplateService.update` for CUSTOM. Before GIT-1834 the CUSTOM branch got the raw request instead, so a details-only edit wrote `flows: []` over the export, skipped validation, and took `pieces` from the first flow only.
- `pieces` and `categories` are denormalized + indexed for fast filtering.
- **A flow export (`GET /v1/flows/:id/template`) keeps its connection refs.** `removeConnectionsFromInput` in `flow-version.service.ts` strips only the old `{{connections.x}}` dot syntax, and the builder has written `{{connections['x']}}` since 2023. Import keeps the ref, so a flow re-imported where a connection with that External ID exists just works, and users rely on it. Fixing the regex is a functional breaking change, not a cleanup (GIT-1957).
diff --git a/packages/server/api/src/app/ee/template/platform-template.service.ts b/packages/server/api/src/app/ee/template/platform-template.service.ts
index 29c02eccf93..81f54c2335f 100644
--- a/packages/server/api/src/app/ee/template/platform-template.service.ts
+++ b/packages/server/api/src/app/ee/template/platform-template.service.ts
@@ -1,5 +1,5 @@
-import { apId, Metadata, sanitizeObjectForPostgresql, spreadIfDefined } from '@activepieces/core-utils'
-import { flowPieceUtil, FlowVersionTemplate, Template, TemplateStatus, TemplateTag, TemplateType, UpdateTemplateRequestBody } from '@activepieces/shared'
+import { apId, Metadata, spreadIfDefined } from '@activepieces/core-utils'
+import { FlowVersionTemplate, Template, TemplateStatus, TemplateTag, TemplateType, UpdateTemplateRequestBody } from '@activepieces/shared'
import { repoFactory } from '../../core/db/repo-factory'
import { TemplateEntity } from '../../template/template.entity'
@@ -27,10 +27,8 @@ export const platformTemplateService = () => ({
}
return templateRepo().save(newTemplate)
},
- async update({ id, params }: UpdateParams): Promise<Template> {
- const { name, description, summary, tags, blogUrl, metadata, categories, flows, status } = params
- const flow: FlowVersionTemplate | undefined = flows?.[0] ? sanitizeObjectForPostgresql(flows[0]) : undefined
- const pieces = flow ? flowPieceUtil.getUsedPieces(flow.trigger) : undefined
+ async update({ id, params, flows, pieces }: UpdateParams): Promise<Template> {
+ const { name, description, summary, tags, blogUrl, metadata, categories, status } = params
await templateRepo().update(id, {
...spreadIfDefined('name', name),
...spreadIfDefined('description', description),
@@ -66,4 +64,6 @@ type NewTemplate = Omit<Template, 'created' | 'updated'>
type UpdateParams = {
id: string
params: UpdateTemplateRequestBody
+ flows: FlowVersionTemplate[] | undefined
+ pieces: string[] | undefined
}
\ No newline at end of file
diff --git a/packages/server/api/src/app/template/template.service.ts b/packages/server/api/src/app/template/template.service.ts
index 2ebffaa0908..a01f89ff1ff 100644
--- a/packages/server/api/src/app/template/template.service.ts
+++ b/packages/server/api/src/app/template/template.service.ts
@@ -78,7 +78,7 @@ export const templateService = (log: FastifyBaseLogger) => ({
if (!isNil(params.flows) && params.flows.length > 0) {
const preparedTemplate = await templateValidator.validateAndPrepare({
flows: params.flows,
- platformId: undefined,
+ platformId: template.platformId ?? undefined,
log,
})
sanatizedFlows = preparedTemplate.flows
@@ -104,7 +104,7 @@ export const templateService = (log: FastifyBaseLogger) => ({
return templateRepo().findOneByOrFail({ id })
}
case TemplateType.CUSTOM: {
- return platformTemplateService().update({ id, params })
+ return platformTemplateService().update({ id, params, flows: sanatizedFlows, pieces })
}
}
},
diff --git a/packages/server/api/test/integration/cloud/flow-templates/flow-templates.test.ts b/packages/server/api/test/integration/cloud/flow-templates/flow-templates.test.ts
index 78ac12e2d65..a10348db94f 100644
--- a/packages/server/api/test/integration/cloud/flow-templates/flow-templates.test.ts
+++ b/packages/server/api/test/integration/cloud/flow-templates/flow-templates.test.ts
@@ -1,5 +1,6 @@
import { apId } from '@activepieces/core-utils'
-import { CreateTemplateRequestBody, PlatformPlan, PlatformRole, PrincipalType, TemplateType } from '@activepieces/shared'
+import { CreateTemplateRequestBody, FlowTrigger, FlowTriggerType, PlatformPlan, PlatformRole, PrincipalType, TemplateType } from '@activepieces/shared'
+import dayjs from 'dayjs'
import { FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
import { generateMockToken } from '../../../helpers/auth'
@@ -305,9 +306,120 @@ describe('Templates', () => {
expect(response?.statusCode).toBe(StatusCodes.OK)
expect(response?.json().name).toBe('updated-name')
})
+
+ it.each([
+ ['omits flows', { summary: 'updated-summary' }],
+ ['sends an empty flows list', { summary: 'updated-summary', flows: [] }],
+ ])('should keep the packaged flow when an update %s', async (_case, body) => {
+ // arrange
+ const { mockOwner, mockPlatform, mockPlatformTemplate } =
+ await createMockPlatformTemplate({ platformId: apId() })
+
+ const testToken = await generateMockToken({
+ type: PrincipalType.USER,
+ id: mockOwner.id,
+ platform: { id: mockPlatform.id },
+ })
+
+ // act
+ const response = await app?.inject({
+ method: 'POST',
+ url: `/api/v1/templates/${mockPlatformTemplate.id}`,
+ headers: {
+ authorization: `Bearer ${testToken}`,
+ },
+ body,
+ })
+
+ // assert
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(response?.json().summary).toBe('updated-summary')
+ expect(response?.json().flows).toHaveLength(mockPlatformTemplate.flows.length)
+ expect(response?.json().flows[0].displayName).toBe(mockPlatformTemplate.flows[0].displayName)
+ })
+
+ it('should replace the packaged flow when an update carries a new one', async () => {
+ // arrange
+ const { mockOwner, mockPlatform, mockPlatformTemplate } =
+ await createMockPlatformTemplate({ platformId: apId() })
+
+ const testToken = await generateMockToken({
+ type: PrincipalType.USER,
+ id: mockOwner.id,
+ platform: { id: mockPlatform.id },
+ })
+ const replacementFlow = { ...createMockTemplate().flows[0], displayName: 'replacement-flow' }
+
+ // act
+ const response = await app?.inject({
+ method: 'POST',
+ url: `/api/v1/templates/${mockPlatformTemplate.id}`,
+ headers: {
+ authorization: `Bearer ${testToken}`,
+ },
+ body: {
+ flows: [replacementFlow],
+ },
+ })
+
+ // assert
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(response?.json().flows).toHaveLength(1)
+ expect(response?.json().flows[0].displayName).toBe('replacement-flow')
+ })
+
+ it('should list the pieces of every flow when an update carries several', async () => {
+ // arrange
+ const { mockOwner, mockPlatform, mockPlatformTemplate } =
+ await createMockPlatformTemplate({ platformId: apId() })
+
+ const testToken = await generateMockToken({
+ type: PrincipalType.USER,
+ id: mockOwner.id,
+ platform: { id: mockPlatform.id },
+ })
+ const flowUsing = (pieceName: string) => ({
+ ...createMockTemplate().flows[0],
+ trigger: pieceTrigger({ pieceName }),
+ })
+
+ // act
+ const response = await app?.inject({
+ method: 'POST',
+ url: `/api/v1/templates/${mockPlatformTemplate.id}`,
+ headers: {
+ authorization: `Bearer ${testToken}`,
+ },
+ body: {
+ flows: [flowUsing('@activepieces/piece-slack'), flowUsing('@activepieces/piece-gmail')],
+ },
+ })
+
+ // assert
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(response?.json().flows).toHaveLength(2)
+ expect(response?.json().pieces).toEqual(expect.arrayContaining(['@activepieces/piece-slack', '@activepieces/piece-gmail']))
+ })
})
})
+function pieceTrigger({ pieceName }: { pieceName: string }): FlowTrigger {
+ return {
+ type: FlowTriggerType.PIECE,
+ name: 'trigger',
+ displayName: 'Trigger',
+ valid: true,
+ lastUpdatedDate: dayjs().toISOString(),
+ settings: {
+ pieceName,
+ pieceVersion: '0.1.0',
+ triggerName: 'new_message',
+ input: {},
+ propertySettings: {},
+ },
+ }
+}
+
async function createMockPlatformTemplate({ platformId, plan, type }: { platformId: string, plan?: Partial<PlatformPlan>, type?: TemplateType }) {
const { mockOwner, mockPlatform, mockProject } = await mockAndSaveBasicSetup({
platform: {