Files
twenty/packages/twenty-server/test/integration/graphql/suites/workspace/custom-application-translation.integration-spec.ts
T
Félix Malfait 1df00698cf feat(server): make workspace Custom application carry an applicationRegistration so custom labels are translatable (#22378)
## Why

Custom objects/fields belong to a per-workspace **Custom** application
(`workspace.workspaceCustomApplicationId`). That application was created
with `applicationRegistrationId = null`. Because the metadata label
resolver loads a translation catalog from `core.applicationTranslation`
**keyed by `applicationRegistrationId`**
(`ApplicationTranslationCacheService.getCatalog` →
`applicationTranslationCatalogLoader` →
`resolveObjectMetadataStandardOverride` /
`resolveFieldMetadataStandardOverride`), the Custom app had no catalog
and custom labels always resolved to the raw source string.

This is the foundational slice: it wires up the missing key so custom
labels can be translated **exactly like any installed third-party app**.
The read/resolve path already works once a catalog exists — confirmed
end-to-end. `flatApplicationMaps` carries `applicationRegistrationId`
straight from the entity column, so setting it + recomputing that cache
is all that's needed.

## What changed

- **`ApplicationService.createWorkspaceCustomApplication`** now creates
a workspace-scoped `applicationRegistration` and links it to the Custom
application. This covers both production creation sites (sign-in-up and
the dev-seeder), which are the only callers.
- **New idempotent workspace upgrade command**
`upgrade:2-18:backfill-workspace-custom-application-registration`
creates a registration for each existing workspace's Custom application
that lacks one and links it. It delegates the registration lifecycle
(create + link + `flatApplicationMaps` recompute) to
`ApplicationService`, so the command only decides *which* workspaces
need it.
- New `WORKSPACE_CUSTOM_APPLICATION_NAME` constant; the registration
creation lives in
`ApplicationService.createWorkspaceCustomApplicationRegistration`.

## Design decisions

- **Per-workspace registration (not a shared "custom" registration).**
`applicationTranslation` is keyed *only* by `applicationRegistrationId`
(cross-workspace). A shared registration would force every workspace's
custom translations into one catalog keyed by
`generateMessageId(sourceText)`, guaranteeing cross-workspace collisions
and leakage (two workspaces both naming an object "Project" would
clash). Each workspace's Custom app gets its own registration
(`ownerWorkspaceId = workspaceId`, `universalIdentifier = the Custom
app's per-workspace uuid`) and thus an isolated catalog — matching
installed-app behaviour, where `application.universalIdentifier ===
registration.universalIdentifier`.
- **Source-label keying kept** (`generateMessageId(sourceLabel)`). The
resolve path and the third-party manifest pipeline both key catalogs
this way. Re-keying by a stable `universalIdentifier` would require
changing the shared resolver/dataloader for *all* apps and would break
marketplace manifest translations — out of scope for this slice.
Consequence: renaming a label orphans its catalog entry (it falls back
to the source label until re-translated) — the same behaviour an
installed app has when it changes a source string. Re-keying on rename
can be handled later by the interactive write path.
- **Workspace command (not instance command)** for the backfill: it is
per-workspace data logic that must recompute the per-workspace
`flatApplicationMaps` cache the resolver reads from. It is idempotent
(skips Custom apps that already have a registration), supports
`--dry-run`, and is forward-only by design.
- **Interactive write path deferred** as an explicit follow-up. This
slice proves the read/resolve path; an editor that writes custom
translations into `applicationTranslation` (+ cache invalidation) is the
natural next step.

## Tests

- **Unit test** for the backfill command: creation + linking,
idempotency, dry-run, and the skip paths.
- **Integration test**
(`custom-application-translation.integration-spec.ts`): on a freshly
created workspace (so the registration's translation cache is guaranteed
cold), it asserts the Custom application is created with a registration,
seeds an `applicationTranslation` row, and verifies a custom object's
label resolves from that catalog while a label with no catalog entry
falls back to its source label.

## Notes for reviewers

- No new entity columns or migrations beyond the workspace command —
`ApplicationRegistrationEntity` already supports a workspace-scoped
`workspaceId`.
- The backfill follows the established upgrade-command pattern: it
imports `ApplicationModule` and delegates to `ApplicationService`
(consistent with the other version-command modules).

https://claude.ai/code/session_018heTgu4ew4AJ99VVz4bjqd

---
_Generated by [Claude
Code](https://claude.ai/code/session_018heTgu4ew4AJ99VVz4bjqd)_

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/22378?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
2026-06-30 23:08:38 +02:00

205 lines
6.7 KiB
TypeScript

import { randomUUID } from 'crypto';
import request from 'supertest';
import { activateWorkspace } from 'test/integration/graphql/utils/activate-workspace.util';
import { deleteUser } from 'test/integration/graphql/utils/delete-user.util';
import { getAuthTokensFromLoginToken } from 'test/integration/graphql/utils/get-auth-tokens-from-login-token.util';
import { getCurrentUser } from 'test/integration/graphql/utils/get-current-user.util';
import { signUpInNewWorkspace } from 'test/integration/graphql/utils/sign-up-in-new-workspace.util';
import { signUp } from 'test/integration/graphql/utils/sign-up.util';
import { createOneObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/create-one-object-metadata.util';
import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
import { SOURCE_LOCALE } from 'twenty-shared/translations';
import { isDefined } from 'twenty-shared/utils';
import { generateMessageId } from 'src/engine/core-modules/i18n/utils/generateMessageId';
const client = request(`http://localhost:${APP_PORT}`);
const SOURCE_LABEL_SINGULAR = 'My Robot';
const SOURCE_LABEL_PLURAL = 'My Robots';
const SOURCE_DESCRIPTION = 'A friendly robot';
const TRANSLATED_LABEL_SINGULAR = 'Translated Robot';
const TRANSLATED_LABEL_PLURAL = 'Translated Robots';
const TRANSLATED_DESCRIPTION = 'Translated robot description';
const CONTROL_LABEL_SINGULAR = 'My Gadget';
const CONTROL_LABEL_PLURAL = 'My Gadgets';
type ObjectNode = {
nameSingular: string;
labelSingular: string;
labelPlural: string;
description: string;
};
const queryObjects = (accessToken: string) =>
client
.post('/metadata')
.set('Authorization', `Bearer ${accessToken}`)
.send({
query: `
query CustomObjectsI18n {
objects(paging: { first: 200 }) {
edges {
node {
nameSingular
labelSingular
labelPlural
description
}
}
}
}
`,
});
const findObjectByName = (
edges: Array<{ node: ObjectNode }>,
nameSingular: string,
): ObjectNode | undefined =>
edges.find((edge) => edge.node.nameSingular === nameSingular)?.node;
describe('custom application translation resolve path', () => {
let createdUserAccessToken: string | undefined;
afterEach(async () => {
if (!isDefined(createdUserAccessToken)) {
return;
}
await deleteUser({
accessToken: createdUserAccessToken,
expectToFail: false,
});
createdUserAccessToken = undefined;
});
it('translates a custom object label from the application translation catalog, and falls back to the source label otherwise', async () => {
// A fresh workspace guarantees its Custom application registration has never
// had its translation catalog loaded, so the seeded row below is read
// straight from the database rather than from a warm (empty) cache.
const uniqueEmail = `test-custom-translation-${randomUUID()}@example.com`;
const { data: signUpData } = await signUp({
input: { email: uniqueEmail, password: 'Test123!@#' },
expectToFail: false,
});
createdUserAccessToken =
signUpData.signUp.tokens.accessOrWorkspaceAgnosticToken.token;
await testDataSource.query(
'UPDATE core."user" SET "isEmailVerified" = true WHERE email = $1',
[uniqueEmail],
);
const {
data: { signUpInNewWorkspace: signUpInNewWorkspaceData },
} = await signUpInNewWorkspace({
accessToken: createdUserAccessToken,
expectToFail: false,
});
const {
data: { getAuthTokensFromLoginToken: authTokensData },
} = await getAuthTokensFromLoginToken({
origin: signUpInNewWorkspaceData.workspace.workspaceUrls.subdomainUrl,
loginToken: signUpInNewWorkspaceData.loginToken.token,
expectToFail: false,
});
const workspaceAccessToken =
authTokensData.tokens.accessOrWorkspaceAgnosticToken.token;
await activateWorkspace({
accessToken: workspaceAccessToken,
expectToFail: false,
});
const {
data: { currentUser },
} = await getCurrentUser({
accessToken: workspaceAccessToken,
expectToFail: false,
});
jestExpectToBeDefined(currentUser.currentWorkspace);
const workspaceId = currentUser.currentWorkspace.id;
const workspaceCustomApplicationId =
currentUser.currentWorkspace.workspaceCustomApplicationId;
const [customApplicationRow] = await testDataSource.query(
`SELECT "applicationRegistrationId"
FROM core.application
WHERE id = $1 AND "workspaceId" = $2`,
[workspaceCustomApplicationId, workspaceId],
);
jestExpectToBeDefined(customApplicationRow);
const applicationRegistrationId =
customApplicationRow.applicationRegistrationId;
expect(applicationRegistrationId).toEqual(expect.any(String));
const messages = {
[generateMessageId(SOURCE_LABEL_SINGULAR)]: TRANSLATED_LABEL_SINGULAR,
[generateMessageId(SOURCE_LABEL_PLURAL)]: TRANSLATED_LABEL_PLURAL,
[generateMessageId(SOURCE_DESCRIPTION)]: TRANSLATED_DESCRIPTION,
};
await testDataSource.query(
`INSERT INTO core."applicationTranslation"
("applicationRegistrationId", locale, messages)
VALUES ($1, $2, $3::jsonb)`,
[applicationRegistrationId, SOURCE_LOCALE, JSON.stringify(messages)],
);
await createOneObjectMetadata({
input: {
nameSingular: 'myRobot',
namePlural: 'myRobots',
labelSingular: SOURCE_LABEL_SINGULAR,
labelPlural: SOURCE_LABEL_PLURAL,
description: SOURCE_DESCRIPTION,
isLabelSyncedWithName: false,
},
token: workspaceAccessToken,
expectToFail: false,
});
await createOneObjectMetadata({
input: {
nameSingular: 'myGadget',
namePlural: 'myGadgets',
labelSingular: CONTROL_LABEL_SINGULAR,
labelPlural: CONTROL_LABEL_PLURAL,
isLabelSyncedWithName: false,
},
token: workspaceAccessToken,
expectToFail: false,
});
const response = await queryObjects(workspaceAccessToken);
expect(response.body.errors).toBeUndefined();
const edges = response.body.data.objects.edges;
const myRobot = findObjectByName(edges, 'myRobot');
jestExpectToBeDefined(myRobot);
expect(myRobot.labelSingular).toBe(TRANSLATED_LABEL_SINGULAR);
expect(myRobot.labelPlural).toBe(TRANSLATED_LABEL_PLURAL);
expect(myRobot.description).toBe(TRANSLATED_DESCRIPTION);
const myGadget = findObjectByName(edges, 'myGadget');
jestExpectToBeDefined(myGadget);
expect(myGadget.labelSingular).toBe(CONTROL_LABEL_SINGULAR);
expect(myGadget.labelPlural).toBe(CONTROL_LABEL_PLURAL);
});
});