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(pieces): core piece names like Text Helper now show in your language (#16653)

Hazem Adel2fe364a0c14d
diff --git a/brain/knowledge/pieces-engine/pieces.md b/brain/knowledge/pieces-engine/pieces.md
index d48e50f016a..42860a62636 100644
--- a/brain/knowledge/pieces-engine/pieces.md
+++ b/brain/knowledge/pieces-engine/pieces.md
@@ -27,6 +27,7 @@ The metadata catalog of automation integrations ("pieces") — each a named inte
- **`/v1/pieces` is uncached, so a new `piece_metadata` column must be added to `PIECE_COLUMNS_WITHOUT_TRANSLATIONS` or it silently will not appear in the list.** `pieceCache` caches only the *registry* (name/version/platformId tuples) for `get`/`findExactVersion`/`registry`; the list path never touches it, and the `dedupe()` helper in `piece-metadata-service.ts` is in-flight-only (it deletes the key in `finally`), so it collapses concurrent callers but caches nothing between requests. Every request therefore re-runs the whole pipeline against the DB. Because of that, `fetchLatestCompatiblePiecesFromDB` selects an explicit column list that deliberately omits `i18n` — that column holds every locale for the piece (~50 MB across the catalogue, written by `pieceInstallService`) and the list path discards it, so loading it was pure waste. Non-English requests now pull only the one locale in a second query (`pm."i18n" -> :locale`) and hand it to `pieceTranslation.translatePiece`. The single-piece path (`get`/`getOrThrow`) selects the same columns and goes through the same `translatePieces`, so no response ever carries `i18n`. The cost is that the explicit select is a list to keep in sync with the entity.
- **Piece sorting mutates its input, which is why the list result cannot simply be cached.** `pieceSorting`'s comparators and `reverseIfDesc` sort in place (`pieces.sort(...)`, `pieces.reverse()`). That is safe only because the array is rebuilt per request; making them non-mutating is a prerequisite for ever caching the built list, or requests would reorder shared state under each other.
- **`translatePiece` is copy-on-write: never deep-clone a piece to translate it, and never cache translated lists.** It copies only the objects on a translated path and returns the input's other subtrees by reference, in one walk over a tree built from `pathsToValuesToTranslate`. The input is shared through `dedupe()` across concurrent requests in different locales, so mutating it leaks one locale into another. The old `JSON.parse(JSON.stringify(piece))` made every non-English list ~3x slower than English (GIT-1891), and caching the translated catalogue per locale was tried twice (#15340, #15639) and dropped over memory. `packages/pieces/framework/test/i18n.test.ts` fails if a deep clone comes back. Translations are read from `piece_translation` (one row per piece version and locale, `pieceTranslationService`), not from the `json` `i18n` column: extracting one locale from that column re-parsed every locale (~160 ms on prod, paid even for a locale with no rows) and was ~5x slower than the table (GIT-2013).
+- **A piece's `displayName` is translated only for `PieceCategory.CORE` pieces.** Never add it to `pathsToValuesToTranslate`: PR 9124 removed it after brand names got translated (Salesforce became "Force de ventes"). `pieceTranslation.pathsToTranslate(categories)` is the one rule, used by `translatePiece` and the CLI generator. Search runs on the translated catalogue, so `fetchLatestPieces` also returns `untranslatedNames` (English name of every piece whose name was translated) and search matches it in both the Fuse piece match and `searchForSuggestion`. Miss the second and the picker gets the piece with no actions or triggers, which hides it (GIT-1995).
- **`piece_metadata.i18n` is still written but only read as a fallback, until it is dropped.** `pieceMetadataService.create` writes both the column and `piece_translation` in one transaction; `BackfillPieceTranslation` (background) copies existing rows. While the backfill runs, a piece with no `piece_translation` rows falls back to `i18n -> :locale`, so nobody sees English mid-backfill. The follow-up drops the column behind `assertBackgroundMigrationComplete` and deletes that fallback in `pieceTranslationService.getForLocale`. Synced pieces keep the cloud's `id`, so translation rows must use the id that was actually saved, never a freshly generated one.
- **DynamicProperties clears its value before it knows the new schema, so the merge source must be a snapshot.** `DynamicPropertiesImplementation` re-fetches the child schema on every refresher change, clearing the form value synchronously and re-populating it in the mutation callback. The merge source for `getDefaultValueForProperties` has to be a `lastKnownValue` ref captured *before* the clear — reading `form.getValues()` in the callback sees the cleared `null` and defaults every child (GIT-1514). The snapshot must be spread-cloned: RHF `getValues(name)` hands back the live object and the clear's `setValue(...child, null)` mutates it in place. Guard the ref with `isNil` so it survives rapid successive changes, where later effect runs already observe `null`.
- `DynamicPropertiesContext` tracks loading by property name only, so two in-flight requests for the same property let the first completion clear the flag for both — briefly re-enabling Test Step while the value is still cleared.
diff --git a/packages/cli/src/lib/commands/generate-translation-file-for-piece.ts b/packages/cli/src/lib/commands/generate-translation-file-for-piece.ts
index 5b6d0c49325..b80ee537d45 100644
--- a/packages/cli/src/lib/commands/generate-translation-file-for-piece.ts
+++ b/packages/cli/src/lib/commands/generate-translation-file-for-piece.ts
@@ -1,18 +1,18 @@
import { writeFile } from 'node:fs/promises';
import chalk from 'chalk';
import { Command } from 'commander';
-import { assertPieceExists, buildPackage, findPiece, findPieces } from '../utils/piece-utils';
+import { assertPieceExists, buildPackage, findPiece, findPieces, piecesPath } from '../utils/piece-utils';
import { makeFolderRecursive, readPackageJson } from '../utils/files';
import { basename, join } from 'node:path';
import { exec } from '../utils/exec';
-import { pieceTranslation } from '@activepieces/pieces-framework';
+import { Piece, pieceTranslation } from '@activepieces/pieces-framework';
import { MAX_KEY_LENGTH_FOR_CORWDIN } from '@activepieces/shared';
-const findPieceInModule= async (pieceOutputFile: string) => {
+const findPieceInModule= async (pieceOutputFile: string): Promise<Piece> => {
const module = await import(pieceOutputFile);
const exports = Object.values(module);
for (const e of exports) {
- if (e !== null && e !== undefined && e.constructor.name === 'Piece') {
+ if (isPiece(e)) {
return e
}
}
@@ -20,6 +20,10 @@ const findPieceInModule= async (pieceOutputFile: string) => {
throw new Error(`Piece not found in module, please check the piece output file ${pieceOutputFile}`);
}
+function isPiece(value: unknown): value is Piece {
+ return value instanceof Object && value.constructor.name === 'Piece'
+}
+
const installDependencies = async (pieceFolder: string) => {
console.log(chalk.blue(`Installing dependencies ${pieceFolder}`))
await exec(`bun install`, {cwd: pieceFolder,})
@@ -39,9 +43,9 @@ function getPropertyValue(object: Record<string, unknown>, path: string): unknow
return nextObject;
}
-const generateTranslationFileFromPiece = (piece: Record<string, unknown>) => { const translation: Record<string, string> = {}
+const generateTranslationFileFromPiece = (piece: ReturnType<Piece['metadata']>) => { const translation: Record<string, string> = {}
try {
- pieceTranslation.pathsToValuesToTranslate.forEach(path => {
+ pieceTranslation.pathsToTranslate(piece.categories).forEach(path => {
const value = getPropertyValue(piece, path)
if (value) {
if (typeof value === 'string') {
@@ -56,7 +60,7 @@ const generateTranslationFileFromPiece = (piece: Record<string, unknown>) => { c
})
}
catch (err) {
- console.error(`error generating translation file for piece ${piece.name}:`, err)
+ console.error(`error generating translation file for piece ${piece.displayName}:`, err)
}
return translation
@@ -72,7 +76,7 @@ const generateTranslationFile = async (pieceName: string) => {
try{
await installDependencies(pieceRoot)
const pieceFromModule = await findPieceInModule(pieceRoot);
- const i18n = generateTranslationFileFromPiece({actions: (pieceFromModule as any)._actions, triggers: (pieceFromModule as any)._triggers, description: (pieceFromModule as any).description, displayName: (pieceFromModule as any).displayName, auth: (pieceFromModule as any).auth});
+ const i18n = generateTranslationFileFromPiece(pieceFromModule.metadata());
const i18nFolder = join(pieceRoot, 'src', 'i18n')
await makeFolderRecursive(i18nFolder);
await writeFile(join(i18nFolder, 'translation.json'), JSON.stringify(i18n, null, 2));
@@ -94,8 +98,8 @@ export const generateTranslationFileForPieceCommand = new Command('generate-tran
.requiredOption('--shard-index <shardIndex>', 'Zero-based shard index to process', (value) => parseInt(value, 10))
.requiredOption('--shard-total <shardTotal>', 'Total number of shards', (value) => parseInt(value, 10))
.action(async ({shardIndex, shardTotal}: { shardIndex: number; shardTotal: number }) => {
- const piecesDirectory = join(process.cwd(), 'packages', 'pieces', 'community')
- const pieces = (await findPieces(piecesDirectory)).map(piece => basename(piece));
+ const piecesDirectories = ['community', 'core'].map(folder => join(piecesPath(), folder))
+ const pieces = (await Promise.all(piecesDirectories.map(directory => findPieces(directory)))).flat().map(piece => basename(piece));
let totalTime = 0
let indexAcrossAllPieces = 0
for (const piece of pieces) {
diff --git a/packages/pieces/framework/src/lib/i18n.ts b/packages/pieces/framework/src/lib/i18n.ts
index 62da87a3b7a..ce0fee75ef5 100644
--- a/packages/pieces/framework/src/lib/i18n.ts
+++ b/packages/pieces/framework/src/lib/i18n.ts
@@ -1,6 +1,6 @@
import { I18nForPiece, PieceMetadataModel, PieceMetadataModelSummary } from "./piece-metadata"
import { LocalesEnum } from "@activepieces/core-utils"
-import { MAX_KEY_LENGTH_FOR_CORWDIN } from "@activepieces/core-piece-types"
+import { MAX_KEY_LENGTH_FOR_CORWDIN, PieceCategory } from "@activepieces/core-piece-types"
import path from 'path';
import fs from 'fs/promises';
@@ -10,7 +10,12 @@ export const pieceTranslation = {
if (!translations) {
return piece
}
- return translateNode({ node: piece, tree: translationTree, translations })
+ const tree = isCorePiece(piece.categories) ? coreTranslationTree : translationTree
+ return translateNode({ node: piece, tree, translations })
+ },
+
+ pathsToTranslate: (categories?: PieceCategory[]): string[] => {
+ return isCorePiece(categories) ? [...pieceTranslation.pathsToValuesToTranslate, 'displayName'] : pieceTranslation.pathsToValuesToTranslate
},
/**Gets the piece metadata regardles of piece location (node_modules or dist), wasn't included inside piece.metadata() for backwards compatibility issues (if an old ap version installs a new piece it would fail)*/
@@ -57,7 +62,16 @@ export const pieceTranslation = {
]
}
-const translationTree = pieceTranslation.pathsToValuesToTranslate.reduce<TranslationTree>((tree, path) => addPath({ tree, keys: path.split('.') }), {})
+const translationTree = buildTree(pieceTranslation.pathsToTranslate())
+const coreTranslationTree = buildTree(pieceTranslation.pathsToTranslate([PieceCategory.CORE]))
+
+function buildTree(paths: string[]): TranslationTree {
+ return paths.reduce<TranslationTree>((tree, path) => addPath({ tree, keys: path.split('.') }), {})
+}
+
+function isCorePiece(categories: PieceCategory[] | undefined): boolean {
+ return categories?.includes(PieceCategory.CORE) ?? false
+}
function addPath({ tree, keys: [key, ...rest] }: AddPathParams): TranslationTree {
return { ...tree, [key]: rest.length === 0 ? null : addPath({ tree: tree[key] ?? {}, keys: rest }) }
diff --git a/packages/pieces/framework/test/i18n.test.ts b/packages/pieces/framework/test/i18n.test.ts
index 03ac0b0ac01..d991d05ddc8 100644
--- a/packages/pieces/framework/test/i18n.test.ts
+++ b/packages/pieces/framework/test/i18n.test.ts
@@ -1,15 +1,16 @@
import { describe, expect, it } from 'vitest';
import { LocalesEnum } from '@activepieces/core-utils';
-import { PackageType, PieceType } from '@activepieces/core-piece-types';
+import { PackageType, PieceCategory, PieceType } from '@activepieces/core-piece-types';
import { createAction } from '../src/lib/action/action';
import { pieceTranslation } from '../src/lib/i18n';
import { createPiece } from '../src/lib/piece';
import { PieceMetadataModel } from '../src/lib/piece-metadata';
import { PieceAuth, Property } from '../src/lib/property';
-const buildPiece = (): PieceMetadataModel => JSON.parse(JSON.stringify({
+const buildPiece = (categories: PieceCategory[] = []): PieceMetadataModel => JSON.parse(JSON.stringify({
...createPiece({
displayName: 'Mailer',
+ categories,
description: 'Send mail',
logoUrl: 'https://example.com/logo.png',
auth: PieceAuth.SecretText({ displayName: 'API key', description: 'Your API key', required: true }),
@@ -44,6 +45,7 @@ const buildPiece = (): PieceMetadataModel => JSON.parse(JSON.stringify({
packageType: PackageType.REGISTRY,
i18n: {
[LocalesEnum.JAPANESE]: {
+ 'Mailer': 'メーラー',
'Send mail': 'メール送信',
'Your API key': 'あなたのAPIキー',
'Send email': 'メールを送信',
@@ -89,4 +91,16 @@ describe('pieceTranslation.translatePiece', () => {
expect(pieceTranslation.translatePiece({ piece, locale: LocalesEnum.GERMAN })).toBe(piece);
});
+
+ it('translates the display name of a core piece', () => {
+ const translated = pieceTranslation.translatePiece({ piece: buildPiece([PieceCategory.CORE]), locale: LocalesEnum.JAPANESE });
+
+ expect(translated.displayName).toBe('メーラー');
+ });
+
+ it('keeps the display name of a non-core piece untranslated', () => {
+ const translated = pieceTranslation.translatePiece({ piece: buildPiece([PieceCategory.COMMUNICATION]), locale: LocalesEnum.JAPANESE });
+
+ expect(translated.displayName).toBe('Mailer');
+ });
});
diff --git a/packages/server/api/src/app/pieces/metadata/piece-metadata-service.ts b/packages/server/api/src/app/pieces/metadata/piece-metadata-service.ts
index c05b455d1b6..faf0fe1a203 100644
--- a/packages/server/api/src/app/pieces/metadata/piece-metadata-service.ts
+++ b/packages/server/api/src/app/pieces/metadata/piece-metadata-service.ts
@@ -25,7 +25,7 @@ export const pieceMetadataService = (log: FastifyBaseLogger) => {
},
async list(params: ListParams): Promise<PieceMetadataModelSummary[]> {
const locale = params.locale ?? LocalesEnum.ENGLISH
- const translatedPieces = await dedupe(`list:${params.platformId ?? ''}:${locale}`, () => fetchLatestPieces({
+ const { pieces: translatedPieces, untranslatedNames } = await dedupe(`list:${params.platformId ?? ''}:${locale}`, () => fetchLatestPieces({
platformId: params.platformId,
locale,
log,
@@ -36,6 +36,7 @@ export const pieceMetadataService = (log: FastifyBaseLogger) => {
const sortedPieces = await pieceListUtils(log).sortAndSearchPieces({
...params,
pieces: audiencePieces,
+ untranslatedNames,
suggestionType: params.suggestionType,
})
const visiblePieces = params.includeHidden ? sortedPieces : sortedPieces.filter((piece) => !piece.deprecated)
@@ -432,7 +433,7 @@ const increaseMajorVersion = (version: string): string => {
return incrementedVersion
}
-async function fetchLatestPieces({ platformId, locale = LocalesEnum.ENGLISH, log }: FetchLatestPiecesParams): Promise<PieceMetadataSchema[]> {
+async function fetchLatestPieces({ platformId, locale = LocalesEnum.ENGLISH, log }: FetchLatestPiecesParams): Promise<LatestPieces> {
const currentRelease = apVersionUtil.getCurrentRelease()
const latestPieces = await dedupe(`latest-pieces:${currentRelease}`, () => fetchLatestCompatiblePiecesFromDB(currentRelease))
@@ -442,7 +443,15 @@ async function fetchLatestPieces({ platformId, locale = LocalesEnum.ENGLISH, log
const merged = [...latestPieces.filter((p) => !devPieceNames.has(p.name)), ...devPieces]
.filter((piece) => filterPieceBasedOnType(platformId, piece))
.filter((piece) => isSupportedRelease(currentRelease, piece))
- return translatePieces({ pieces: lastVersionOfEachPiece(merged), locale })
+ const newestVersions = lastVersionOfEachPiece(merged)
+ const translatedPieces = await translatePieces({ pieces: newestVersions, locale })
+ return { pieces: translatedPieces, untranslatedNames: untranslatedNamesOf({ originalPieces: newestVersions, translatedPieces }) }
+}
+
+function untranslatedNamesOf({ originalPieces, translatedPieces }: UntranslatedNamesOfParams): Map<string, string> {
+ return new Map(originalPieces
+ .filter((piece, index) => piece.displayName !== translatedPieces[index].displayName)
+ .map((piece) => [piece.name, piece.displayName]))
}
async function fetchPieceVersion({ pieceName, version, platformId, log }: FetchPieceVersionParams): Promise<PieceMetadataSchema | null> {
@@ -643,6 +652,16 @@ type ToPieceMetadataModelSummaryParams<T extends PieceMetadataSchema | PieceMeta
suggestionType?: SuggestionType
}
+type LatestPieces = {
+ pieces: PieceMetadataSchema[]
+ untranslatedNames: Map<string, string>
+}
+
+type UntranslatedNamesOfParams = {
+ originalPieces: PieceMetadataSchema[]
+ translatedPieces: PieceMetadataSchema[]
+}
+
type TranslatePiecesParams = {
pieces: PieceMetadataSchema[]
locale: LocalesEnum
diff --git a/packages/server/api/src/app/pieces/metadata/utils/index.ts b/packages/server/api/src/app/pieces/metadata/utils/index.ts
index 7a517e4d5e4..cfc970bca30 100644
--- a/packages/server/api/src/app/pieces/metadata/utils/index.ts
+++ b/packages/server/api/src/app/pieces/metadata/utils/index.ts
@@ -17,6 +17,7 @@ export const pieceListUtils = (_log: FastifyBaseLogger) => ({
categories: params.categories,
searchQuery: params.searchQuery,
pieces: sortedPieces,
+ untranslatedNames: params.untranslatedNames,
suggestionType: params.suggestionType,
})
},
@@ -49,6 +50,7 @@ export type SortAndSearchPiecesParams = {
sortBy?: PieceSortBy
orderBy?: PieceOrderBy
pieces: PieceMetadataSchema[]
+ untranslatedNames: Map<string, string>
suggestionType?: SuggestionType
}
diff --git a/packages/server/api/src/app/pieces/metadata/utils/piece-searching.ts b/packages/server/api/src/app/pieces/metadata/utils/piece-searching.ts
index 7d93e8ba6d6..c9bd516b4ac 100644
--- a/packages/server/api/src/app/pieces/metadata/utils/piece-searching.ts
+++ b/packages/server/api/src/app/pieces/metadata/utils/piece-searching.ts
@@ -1,6 +1,7 @@
import { ActionBase, TriggerBase } from '@activepieces/pieces-framework'
import {
+ isNil,
PieceCategory,
SuggestionType,
} from '@activepieces/shared'
@@ -24,7 +25,7 @@ const MINIMUM_FUZZY_QUERY_LENGTH = 6
const FUZZY_THRESHOLD = 0.2
const EXACT_THRESHOLD = 0
-const filterBasedOnSearchQuery = ({ searchQuery, pieces, suggestionType }: SearchParams): PieceMetadataSchema[] => {
+const filterBasedOnSearchQuery = ({ searchQuery, pieces, suggestionType, untranslatedNames }: SearchParams): PieceMetadataSchema[] => {
if (!searchQuery) {
return pieces
}
@@ -39,7 +40,7 @@ const filterBasedOnSearchQuery = ({ searchQuery, pieces, suggestionType }: Searc
const fuse = new Fuse(searchablePieces, {
isCaseSensitive: false,
shouldSort: true,
- keys: PIECE_SEARCH_KEYS,
+ keys: [...PIECE_SEARCH_KEYS, { name: 'untranslatedName', weight: 3, getFn: (piece: PieceIdentity) => untranslatedNames.get(piece.name) ?? [] }],
threshold: thresholdFor(searchQuery),
distance: 250,
ignoreLocation: true,
@@ -59,11 +60,15 @@ const filterBasedOnSearchQuery = ({ searchQuery, pieces, suggestionType }: Searc
tokens.some((token) => pieceNameHaystack(piece).includes(token)),
)
- return [...nameMatches, ...descriptionMatches, ...substringMatches].map((piece) => ({
- ...piece,
- actions: searchForSuggestion({ actionsOrTriggers: piece.actions, searchQuery, pieceDisplayName: piece.displayName }),
- triggers: searchForSuggestion({ actionsOrTriggers: piece.triggers, searchQuery, pieceDisplayName: piece.displayName }),
- }))
+ return [...nameMatches, ...descriptionMatches, ...substringMatches].map((piece) => {
+ const untranslatedName = untranslatedNames.get(piece.name)
+ const pieceNames = isNil(untranslatedName) ? [piece.displayName] : [piece.displayName, untranslatedName]
+ return {
+ ...piece,
+ actions: searchForSuggestion({ actionsOrTriggers: piece.actions, searchQuery, pieceNames }),
+ triggers: searchForSuggestion({ actionsOrTriggers: piece.triggers, searchQuery, pieceNames }),
+ }
+ })
}
const filterBasedOnCategories = (categories: PieceCategory[] | undefined, pieces: PieceMetadataSchema[]): PieceMetadataSchema[] => {
@@ -129,13 +134,15 @@ function toSuggestionRecord<T extends { name: string }>(actionsOrTriggers: T[]):
function searchForSuggestion<T extends ActionBase | TriggerBase>({
actionsOrTriggers,
searchQuery,
- pieceDisplayName,
+ pieceNames,
}: SearchForSuggestionParams<T>): Record<string, T> {
if (actionsOrTriggers.length === 0) {
return {}
}
- const { pieceWasNamed, remainingQuery, wholeNameTyped } = matchPieceName({ searchQuery, pieceDisplayName })
+ const nameMatches = pieceNames.map((pieceDisplayName) => matchPieceName({ searchQuery, pieceDisplayName }))
+ const { pieceWasNamed, remainingQuery, wholeNameTyped } = nameMatches.find((match) => match.pieceWasNamed) ?? nameMatches[0]
+ const pieceDisplayName = pieceNames.join(' ')
if (pieceWasNamed && remainingQuery.length === 0) {
return toSuggestionRecord(actionsOrTriggers)
}
@@ -170,6 +177,7 @@ type SearchParams = {
categories: PieceCategory[] | undefined
searchQuery: string | undefined
pieces: PieceMetadataSchema[]
+ untranslatedNames: Map<string, string>
suggestionType?: SuggestionType
}
@@ -203,5 +211,5 @@ type PieceNameMatch = {
type SearchForSuggestionParams<T extends ActionBase | TriggerBase> = {
actionsOrTriggers: T[]
searchQuery: string
- pieceDisplayName: string
+ pieceNames: string[]
}
diff --git a/packages/server/api/test/integration/ce/pieces/dev-piece-translation.test.ts b/packages/server/api/test/integration/ce/pieces/dev-piece-translation.test.ts
index 860b96125e7..991247a9622 100644
--- a/packages/server/api/test/integration/ce/pieces/dev-piece-translation.test.ts
+++ b/packages/server/api/test/integration/ce/pieces/dev-piece-translation.test.ts
@@ -1,5 +1,5 @@
import { apId, LocalesEnum } from '@activepieces/core-utils'
-import { PackageType, PieceType, PrincipalType } from '@activepieces/shared'
+import { PackageType, PieceCategory, PieceType, PrincipalType } from '@activepieces/shared'
import { FastifyBaseLogger, FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
import { pieceCache } from '../../../../src/app/pieces/metadata/piece-cache'
@@ -11,19 +11,34 @@ import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/
const devPiece: PieceMetadataSchema = {
...createMockPieceMetadata({
name: 'dev-translated-piece',
+ displayName: 'Messenger',
version: '0.1.0',
pieceType: PieceType.OFFICIAL,
packageType: PackageType.REGISTRY,
description: 'Send a message',
i18n: {
- [LocalesEnum.GERMAN]: { 'Send a message': 'Eine Nachricht senden' },
+ [LocalesEnum.GERMAN]: { 'Messenger': 'Bote', 'Send a message': 'Eine Nachricht senden' },
+ },
+ }),
+}
+
+const coreDevPiece: PieceMetadataSchema = {
+ ...createMockPieceMetadata({
+ name: '@activepieces/piece-forms',
+ displayName: 'Human Input',
+ version: '0.1.0',
+ pieceType: PieceType.OFFICIAL,
+ packageType: PackageType.REGISTRY,
+ categories: [PieceCategory.CORE],
+ i18n: {
+ [LocalesEnum.GERMAN]: { 'Human Input': 'Menschliche Eingabe' },
},
}),
}
vi.mock('../../../../src/app/pieces/metadata/utils', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../../src/app/pieces/metadata/utils')>()),
- loadDevPiecesIfEnabled: async () => [devPiece],
+ loadDevPiecesIfEnabled: async () => [devPiece, coreDevPiece],
}))
let app: FastifyInstance | null = null
@@ -56,9 +71,26 @@ describe('dev pieces carrying their own translations', () => {
expect(single?.statusCode).toBe(StatusCodes.OK)
const listed = list?.json().find((piece: { name: string }) => piece.name === 'dev-translated-piece')
expect(listed.description).toBe('Eine Nachricht senden')
+ expect(listed.displayName).toBe('Messenger')
expect(listed.i18n).toBeUndefined()
expect(single?.json().description).toBe('Eine Nachricht senden')
expect(single?.json().i18n).toBeUndefined()
expect(devPiece.description).toBe('Send a message')
})
+
+ it('translate the display name of core pieces and still find them by their English name', async () => {
+ const testToken = await generateMockToken({
+ type: PrincipalType.UNKNOWN,
+ id: apId(),
+ })
+
+ const response = await app?.inject({
+ method: 'GET',
+ url: '/api/v1/pieces?locale=de&searchQuery=Human%20Input',
+ headers: { authorization: `Bearer ${testToken}` },
+ })
+
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(response?.json()[0]).toMatchObject({ name: '@activepieces/piece-forms', displayName: 'Menschliche Eingabe' })
+ })
})
diff --git a/packages/server/api/test/unit/app/pieces/piece-searching.test.ts b/packages/server/api/test/unit/app/pieces/piece-searching.test.ts
index 5b9e859c5d2..d1caf79ebbd 100644
--- a/packages/server/api/test/unit/app/pieces/piece-searching.test.ts
+++ b/packages/server/api/test/unit/app/pieces/piece-searching.test.ts
@@ -1,4 +1,4 @@
-import { SuggestionType } from '@activepieces/shared'
+import { SuggestionType, TriggerStrategy, TriggerTestStrategy } from '@activepieces/shared'
import { describe, expect, it } from 'vitest'
import { pieceSearching } from '../../../../src/app/pieces/metadata/utils/piece-searching'
import { createMockPieceMetadata } from '../../../helpers/mocks'
@@ -15,6 +15,7 @@ describe('pieceSearching.search — robustness to extra query words', () => {
categories: undefined,
searchQuery: 'Discord webhook',
pieces,
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.ACTION,
})
expect(results.map((p) => p.displayName)).toContain('Discord')
@@ -25,6 +26,7 @@ describe('pieceSearching.search — robustness to extra query words', () => {
categories: undefined,
searchQuery: 'Discord',
pieces,
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.ACTION,
})
expect(results.map((p) => p.displayName)).toContain('Discord')
@@ -35,8 +37,52 @@ describe('pieceSearching.search — robustness to extra query words', () => {
categories: undefined,
searchQuery: undefined,
pieces,
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.ACTION,
})
expect(results).toHaveLength(pieces.length)
})
})
+
+describe('pieceSearching.search — translated display names', () => {
+ it('finds a translated piece by its English name', () => {
+ const textAi = createMockPieceMetadata({ name: '@activepieces/piece-text-ai', displayName: 'Text AI', description: 'Generate text with AI' })
+ const textHelper = createMockPieceMetadata({ name: '@activepieces/piece-text-helper', displayName: 'テキストヘルパー', description: 'テキスト処理のためのツール' })
+ const results = pieceSearching.search({
+ categories: undefined,
+ searchQuery: 'Text Helper',
+ pieces: [...pieces, textAi, textHelper],
+ untranslatedNames: new Map([['@activepieces/piece-text-helper', 'Text Helper']]),
+ suggestionType: SuggestionType.ACTION,
+ })
+ expect(results[0]?.name).toBe('@activepieces/piece-text-helper')
+ })
+
+ it('suggests the triggers of a translated core piece searched by its English name', () => {
+ const manualTrigger = createMockPieceMetadata({
+ name: '@activepieces/piece-manual-trigger',
+ displayName: '手動トリガー',
+ triggers: {
+ manual_trigger: {
+ name: 'manual_trigger',
+ displayName: '手動トリガー',
+ description: 'フローを手動で開始',
+ props: {},
+ requireAuth: false,
+ type: TriggerStrategy.MANUAL,
+ sampleData: {},
+ testStrategy: TriggerTestStrategy.SIMULATION,
+ },
+ },
+ })
+ const [result] = pieceSearching.search({
+ categories: undefined,
+ searchQuery: 'manual',
+ pieces: [...pieces, manualTrigger],
+ untranslatedNames: new Map([['@activepieces/piece-manual-trigger', 'Manual Trigger']]),
+ suggestionType: SuggestionType.TRIGGER,
+ })
+ expect(result?.name).toBe('@activepieces/piece-manual-trigger')
+ expect(Object.keys(result?.triggers ?? {})).toEqual(['manual_trigger'])
+ })
+})
diff --git a/packages/server/api/test/unit/piece-searching.test.ts b/packages/server/api/test/unit/piece-searching.test.ts
index a98ce0d8688..952538bdb53 100644
--- a/packages/server/api/test/unit/piece-searching.test.ts
+++ b/packages/server/api/test/unit/piece-searching.test.ts
@@ -108,6 +108,7 @@ function search(searchQuery: string): PieceMetadataSchema[] {
categories: undefined,
searchQuery,
pieces: allPieces,
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.ACTION,
})
}
@@ -117,6 +118,7 @@ function searchTriggers(searchQuery: string): PieceMetadataSchema[] {
categories: undefined,
searchQuery,
pieces: allPieces,
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.TRIGGER,
})
}
@@ -226,6 +228,7 @@ describe('pieceSearching.search', () => {
categories: undefined,
searchQuery: undefined,
pieces: allPieces,
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.ACTION,
})
@@ -253,6 +256,7 @@ function searchWithLegacyPiece(searchQuery: string): PieceMetadataSchema[] {
categories: undefined,
searchQuery,
pieces: [...allPieces, legacyPiece],
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.ACTION_AND_TRIGGER,
})
}
@@ -285,6 +289,7 @@ describe('pieceSearching.search with null descriptions', () => {
categories: undefined,
searchQuery: 'submission',
pieces: [...allPieces, legacyPiece],
+ untranslatedNames: new Map(),
suggestionType: SuggestionType.TRIGGER,
})
diff --git a/tools/scripts/pieces/bump-translated-pieces.ts b/tools/scripts/pieces/bump-translated-pieces.ts
index 4d82cfa71f5..7e0ec6ce8f5 100644
--- a/tools/scripts/pieces/bump-translated-pieces.ts
+++ b/tools/scripts/pieces/bump-translated-pieces.ts
@@ -147,15 +147,16 @@ function main(): void {
console.log('Finding pieces with translation changes compared to main...');
const piecesWithChanges: string[] = [];
- const piecesDir = 'packages/pieces/community';
// Get all piece directories
- const pieceDirs = getPieceDirectories(piecesDir);
+ const piecePaths = ['packages/pieces/community', 'packages/pieces/core'].flatMap(piecesDir =>
+ getPieceDirectories(piecesDir).map(piece => path.join(piecesDir, piece))
+ );
- console.log(`Checking ${pieceDirs.length} pieces for changes...`);
+ console.log(`Checking ${piecePaths.length} pieces for changes...`);
- for (const piece of pieceDirs) {
- const piecePath = path.join(piecesDir, piece);
+ for (const piecePath of piecePaths) {
+ const piece = path.basename(piecePath);
// Check if piece has changes compared to main
if (hasChangesComparedToMain(piecePath)) {
// Check if it has i18n directory (indicating translations were added)
@@ -166,7 +167,7 @@ function main(): void {
if (hasVersionBeenBumped(piecePath)) {
console.log(` - ${piece} - has translation changes but version already bumped`);
} else {
- piecesWithChanges.push(piece);
+ piecesWithChanges.push(piecePath);
console.log(` ✓ ${piece} - has translation changes and needs version bump`);
}
} else {
@@ -193,8 +194,8 @@ function main(): void {
let successCount = 0;
let errorCount = 0;
- for (const piece of piecesWithChanges) {
- const packageJsonPath = path.join(piecesDir, piece, 'package.json');
+ for (const piecePath of piecesWithChanges) {
+ const packageJsonPath = path.join(piecePath, 'package.json');
if (fs.existsSync(packageJsonPath)) {
const result = updatePackageJson(packageJsonPath);
@@ -204,7 +205,7 @@ function main(): void {
errorCount++;
}
} else {
- console.error(`Package.json not found for ${piece}`);
+ console.error(`Package.json not found for ${piecePath}`);
errorCount++;
}
}