Skip to content

The open alternative to Salesforce, designed for AI.

chore: strict comment pass on recently touched files (#27027)

Charles Bochet4cc2770bd95a
diff --git a/packages/create-twenty-app/src/constants/template-packages.ts b/packages/create-twenty-app/src/constants/template-packages.ts
index 0dad93be8a6..9ef9e3b1c19 100644
--- a/packages/create-twenty-app/src/constants/template-packages.ts
+++ b/packages/create-twenty-app/src/constants/template-packages.ts
@@ -1,7 +1,5 @@
-// twenty-client-sdk, twenty-sdk and twenty-ui are released together at a single
-// version, so the scaffolder pins all of them to its own version. Keep this list
-// as the one source of truth: the template lockfile generator resolves exactly
-// these names, and a mismatch between the two silently ships an unusable lockfile.
+// Pinned to the scaffolder's own version; the template lockfile generator resolves exactly these names,
+// so a mismatch silently ships an unusable lockfile.
export const TEMPLATE_FIRST_PARTY_PACKAGES = [
'twenty-client-sdk',
'twenty-sdk',
diff --git a/packages/create-twenty-app/src/scripts/generate-template-lock.ts b/packages/create-twenty-app/src/scripts/generate-template-lock.ts
index 9204977b46f..6b2a5f93409 100644
--- a/packages/create-twenty-app/src/scripts/generate-template-lock.ts
+++ b/packages/create-twenty-app/src/scripts/generate-template-lock.ts
@@ -1,17 +1,5 @@
-// Generates the yarn.lock shipped inside the scaffold template.
-//
-// Without it, a generated project resolves every dependency from scratch on its
-// first install, which fails outright when the user's package manager enforces a
-// minimum release age (Yarn's npmMinimalAgeGate, pnpm's minimumReleaseAge, npm's
-// min-release-age): the first-party packages are only minutes old at that point,
-// and an exact pin leaves the resolver no older candidate to fall back to. A
-// lockfile removes the resolution step entirely, so the gate never applies — and
-// unlike loosening the pins or disabling the gate, it leaves the user's policy
-// in force for every dependency they add later.
-//
-// Run this AFTER `nx build create-twenty-app` and AFTER the libraries are live on
-// the registry, then publish; the publish workflow in twentyhq/twenty-infra runs
-// it in that order.
+// Ships a yarn.lock in the template so the first install skips resolution, which minimum-release-age gates
+// reject for minutes-old first-party packages. Run after `nx build create-twenty-app` and once the libraries are live.
import { execFileSync } from 'child_process';
import * as fs from 'fs-extra';
import { tmpdir } from 'os';
@@ -34,9 +22,7 @@ const DEFAULT_OUTPUT_PATH = join(
);
const PUBLIC_REGISTRY = 'https://registry.npmjs.org';
-// Matches the monorepo's own npmMinimalAgeGate. Stated explicitly because nothing
-// is inherited here: the lockfile is resolved in a temp directory outside the
-// repo, with YARN_* stripped, so the effective gate would otherwise be zero.
+// Matches the monorepo's npmMinimalAgeGate; stated explicitly since resolution runs outside the repo with YARN_* stripped.
const RELEASE_MINIMAL_AGE_GATE = '3d';
type Options = {
@@ -62,9 +48,7 @@ const parseOptions = (argv: string[]): Options => {
};
};
-// The generated project runs the Yarn its package.json pins. Generating the
-// lockfile with a different Yarn can produce a lockfile that release pins reject
-// with YN0028 on the user's first CI run, so refuse to guess.
+// A lockfile generated with another Yarn can be rejected with YN0028 by the project's pinned Yarn.
const resolveYarnBinary = (templatePackageManager: string) => {
const yarnrc = fs.readFileSync(join(REPO_ROOT, '.yarnrc.yml'), 'utf8');
const yarnPath = /^yarnPath:\s*(.+)$/m.exec(yarnrc)?.[1]?.trim();
@@ -110,17 +94,11 @@ const buildYarnrc = ({
'enableTelemetry: false',
'enableScripts: false',
`npmRegistryServer: "${registry}"`,
- // Yarn refuses plain HTTP unless the host is whitelisted by name, so take it
- // from the registry rather than assuming localhost.
+ // Yarn refuses plain HTTP unless the host is whitelisted by name.
...(protocol === 'http:'
? ['unsafeHttpWhitelist:', ` - ${hostname}`]
: []),
- // Scaffolded projects install this lockfile without re-resolving, which is
- // exactly what lets them satisfy a consumer's age gate -- and equally what
- // stops that gate from ever inspecting these versions. This resolution is
- // therefore the only point at which an age gate applies to the tree a
- // generated project receives, so hold one here, and waive it for nothing
- // beyond the exact first-party versions this release is publishing.
+ // The shipped lockfile bypasses consumers' age gates, so this resolution is the only place one applies.
`npmMinimalAgeGate: ${RELEASE_MINIMAL_AGE_GATE}`,
'npmPreapprovedPackages:',
...TEMPLATE_FIRST_PARTY_PACKAGES.map((name) => ` - "${name}@${version}"`),
@@ -137,8 +115,7 @@ const assertResolvedWithIntegrity = ({
packageName: string;
version: string;
}) => {
- // Entry keys merge when several descriptors share one resolution
- // ("pkg@npm:1.0.0, pkg@npm:^1.0.0":), so match the resolution line instead.
+ // Entry keys merge when descriptors share a resolution, so match the resolution line instead.
const resolution = `resolution: "${packageName}@npm:${version}"`;
const resolutionIndex = lockfile.indexOf(resolution);
@@ -161,9 +138,7 @@ const assertResolvedWithIntegrity = ({
}
};
-// A registry serving tarballs from non-conventional URLs makes Yarn pin each
-// entry to that exact host via __archiveUrl, which would not resolve for anyone
-// else. Only the public registry produces a lockfile we can ship.
+// Non-conventional tarball URLs make Yarn pin entries to that host via __archiveUrl, unresolvable for others.
const assertNoRegistryPinning = ({
lockfile,
registry,
@@ -172,9 +147,7 @@ const assertNoRegistryPinning = ({
registry: string;
}) => {
if (registry !== PUBLIC_REGISTRY) {
- // The release workflow always regenerates against the public registry right
- // before publishing, so a lockfile built here is only ever local scaffolding.
- // Say so out loud rather than passing silently.
+ // Only warn: the release workflow always regenerates against the public registry before publishing.
console.warn(
`Generated against ${registry}, not ${PUBLIC_REGISTRY}: this lockfile is for local testing and must not be published.`,
);
@@ -209,8 +182,7 @@ const generateTemplateLock = async ({
buildYarnrc({ registry, version }),
);
- // YARN_* variables outrank the .yarnrc.yml written above, so a registry or
- // gate exported by the surrounding CI job would silently change the result.
+ // YARN_* variables outrank .yarnrc.yml, so a CI job's exports would change the result.
const environment = Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith('YARN_')),
);
diff --git a/packages/create-twenty-app/src/utils/__tests__/install.spec.ts b/packages/create-twenty-app/src/utils/__tests__/install.spec.ts
index 9ac28e98a04..2cc75e9bce5 100644
--- a/packages/create-twenty-app/src/utils/__tests__/install.spec.ts
+++ b/packages/create-twenty-app/src/utils/__tests__/install.spec.ts
@@ -6,9 +6,7 @@ type ExecCallback = (error: Error | null, stdout?: string) => void;
jest.mock('child_process', () => ({ exec: jest.fn() }));
-// node's `exec` is overloaded and its widest overload does not accept this
-// callback shape, so take the mock from the module registry under the shape the
-// promisified call actually uses, rather than casting the imported binding.
+// node's `exec` overloads reject this callback shape, so take the mock typed as the promisified call uses it.
const { exec: mockExec } = jest.requireMock<{
exec: jest.Mock<void, [string, unknown, ExecCallback]>;
}>('child_process');
@@ -53,9 +51,7 @@ const quarantineOutput = ({
const APP_DIRECTORY = '/tmp/some-scaffolded-app';
-// The remediation is YAML the reader pastes into .yarnrc.yml, so assert it parses
-// rather than that it reads correctly: a scoped descriptor left unquoted looks
-// right in a substring check and is a YAML error in the file.
+// Parsed as YAML: an unquoted scoped descriptor passes a substring check but breaks .yarnrc.yml.
const parseSuggestedYarnrc = (message: string) => {
const lines = message.split('\n');
const blockStart = lines.findIndex(
@@ -148,7 +144,6 @@ describe('install', () => {
expect(parseSuggestedYarnrc(message)).toEqual({
npmPreapprovedPackages: ['[email protected]'],
});
- // Never advise lowering the gate itself.
expect(message).not.toContain('npmMinimalAgeGate');
});
diff --git a/packages/create-twenty-app/src/utils/app-template.ts b/packages/create-twenty-app/src/utils/app-template.ts
index 0ffec9143a7..481b132ae48 100644
--- a/packages/create-twenty-app/src/utils/app-template.ts
+++ b/packages/create-twenty-app/src/utils/app-template.ts
@@ -42,8 +42,7 @@ export const copyBaseApplicationProject = async ({
await updatePackageJson({ appName, appDirectory });
};
-// npm strips dotfiles/dotdirs (.gitignore, .github/) from published packages,
-// so we store them without the leading dot and rename after copying.
+// npm strips dotfiles from published packages, so they're stored without the dot and renamed after copying.
const renameDotfiles = async ({ appDirectory }: { appDirectory: string }) => {
const renames = [
{ from: 'gitignore', to: '.gitignore' },
@@ -60,8 +59,7 @@ const renameDotfiles = async ({ appDirectory }: { appDirectory: string }) => {
}
};
-// AGENTS.md is the cross-tool standard; Claude Code prefers CLAUDE.md and only
-// falls back to AGENTS.md, so we mirror the file to keep a single source of truth.
+// Claude Code prefers CLAUDE.md over the AGENTS.md standard, so mirror it.
const mirrorAgentsToClaude = async ({
appDirectory,
}: {
@@ -120,10 +118,7 @@ const updatePackageJson = async ({
}) => {
const packageJson = await fs.readJson(join(appDirectory, 'package.json'));
- // The template yarn.lock keeps its placeholder workspace name: the only entry
- // naming the project is the workspace root, which the scaffolder's `yarn install`
- // rewrites from package.json without re-resolving a single dependency. Renaming
- // it here would move the entry out of sort order and break `--immutable`.
+ // yarn.lock keeps its placeholder name: `yarn install` rewrites the root entry, and renaming here breaks `--immutable`.
packageJson.name = appName;
for (const packageName of TEMPLATE_FIRST_PARTY_PACKAGES) {
diff --git a/packages/create-twenty-app/src/utils/install.ts b/packages/create-twenty-app/src/utils/install.ts
index 69aba6a30fa..0f434cbac75 100644
--- a/packages/create-twenty-app/src/utils/install.ts
+++ b/packages/create-twenty-app/src/utils/install.ts
@@ -4,9 +4,7 @@ import { promisify } from 'util';
const execPromise = promisify(exec);
-// Raised as "All versions satisfying <range> are quarantined", or for a tag as
-// "The version for tag <tag> is quarantined", when every candidate version is
-// younger than the configured npmMinimalAgeGate.
+// Raised when every candidate version is younger than npmMinimalAgeGate.
const YARN_QUARANTINE_ERROR_CODE = 'YN0016';
const QUARANTINED_PACKAGE_PATTERN =
@@ -14,8 +12,7 @@ const QUARANTINED_PACKAGE_PATTERN =
const ANSI_ESCAPE_PATTERN = /\x1b\[[0-9;]*m/g;
-// A selector Yarn can test against a version works as a preapproval entry; a
-// dist-tag does not, and only the bare package name will waive it.
+// Yarn preapproves version selectors but not dist-tags, which only the bare package name waives.
const VERSION_SELECTOR_PATTERN = /^[\^~>=<\s]*\d/;
const OUTPUT_TAIL_LINES = 20;
@@ -58,8 +55,7 @@ const buildQuarantineMessage = ({
"that project's .yarnrc.yml:",
'',
' npmPreapprovedPackages:',
- // Quoted because a scoped descriptor starts with "@", which YAML reserves:
- // an unquoted `- @scope/pkg@^1.2.3` is a parse error, not a value.
+ // Quoted: YAML reserves a leading "@", so an unquoted scoped descriptor fails to parse.
...quarantinedPackages.map((descriptor) => ` - "${descriptor}"`),
'',
'That leaves the gate in force for every other dependency.',
@@ -78,9 +74,7 @@ export const install = async (
onProgress?.('Running yarn install');
try {
- // Yarn installs immutably by default when CI is set, but this install is what
- // finalises the template's lockfile: it rewrites the workspace root entry to
- // the project's real name. Immutable mode rejects that with YN0028.
+ // CI implies immutable installs, which reject (YN0028) the workspace root rename this install performs.
await execPromise('yarn install --no-immutable', { cwd: root });
} catch (error: any) {
const output = `${error.stdout ?? ''}\n${error.stderr ?? ''}`;
@@ -88,8 +82,6 @@ export const install = async (
? parseQuarantinedPackages(output)
: [];
- // Continuing here would authenticate, sync and report success over a project
- // that has no node_modules, so surface the failure instead.
throw new Error(
quarantinedPackages.length > 0
? buildQuarantineMessage({
@@ -101,8 +93,6 @@ export const install = async (
'',
tail(output),
'',
- // The project itself is intact: package.json carries its real name and
- // the lockfile is the shipped one, which a plain install reconciles.
'The project was created. Fix the problem above and run `yarn install` there.',
].join('\n'),
);
diff --git a/packages/twenty-apps/examples/media-notes/e2e/media-notes.spec.ts b/packages/twenty-apps/examples/media-notes/e2e/media-notes.spec.ts
index cf257ae1354..cfddf9e8b9a 100644
--- a/packages/twenty-apps/examples/media-notes/e2e/media-notes.spec.ts
+++ b/packages/twenty-apps/examples/media-notes/e2e/media-notes.spec.ts
@@ -33,8 +33,7 @@ test.describe('Media notes capture flow', () => {
fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
});
- // The front component runs in a sandboxed worker; surface browser output so
- // failures inside it are diagnosable from the test log.
+ // The component runs in a sandboxed worker, so forward browser output to the test log.
test.beforeEach(({ page }) => {
page.on('console', (message) => {
console.log(`[browser:${message.type()}] ${message.text()}`);
@@ -56,7 +55,6 @@ test.describe('Media notes capture flow', () => {
) => {
await page.goto(`${resolveWorkspaceUrl()}/`);
- // The pinned global command renders as a top bar action button.
await page
.getByRole('button', { name: 'Record media note' })
.first()
@@ -70,7 +68,6 @@ test.describe('Media notes capture flow', () => {
await page.getByTestId(MEDIA_NOTES_TEST_IDS.recordAudioButton).click();
- // The recording UX is the app's own UI: its timer and stop control.
const stopButton = page.getByTestId(
MEDIA_NOTES_TEST_IDS.stopRecordingButton,
);
@@ -86,7 +83,6 @@ test.describe('Media notes capture flow', () => {
await stopButton.click();
- // Uploaded: the component receives a playable file reference.
await expect(
page.getByTestId(MEDIA_NOTES_TEST_IDS.captureStatus),
).toHaveText('captured');
@@ -97,17 +93,12 @@ test.describe('Media notes capture flow', () => {
expect(audioSrc).toBeTruthy();
expect(audioSrc).toContain('/file');
- // Actually fetch it: a signed url for a folder the file guard does not
- // serve still looks correct in the src attribute but answers 401/403, so
- // asserting on the string alone would not catch an unplayable recording.
+ // An unservable signed url still looks right in src but answers 401/403, so fetch it.
const mediaResponse = await page.request.get(audioSrc as string);
expect(mediaResponse.status()).toBe(200);
- // The body, not content-length: the file route streams the response, so
- // the header is absent even on a perfectly good recording.
+ // The file route streams, so content-length is absent even on a good recording.
expect((await mediaResponse.body()).length).toBeGreaterThan(0);
- // The recording is attached to a record, which is what makes the
- // uploaded file permanent instead of a temporary orphan.
await expect(
page.getByTestId(MEDIA_NOTES_TEST_IDS.savedRecord),
).toContainText('Attached to media note');
diff --git a/packages/twenty-apps/examples/media-notes/playwright.config.ts b/packages/twenty-apps/examples/media-notes/playwright.config.ts
index 682703c5eb9..8b63ba40a04 100644
--- a/packages/twenty-apps/examples/media-notes/playwright.config.ts
+++ b/packages/twenty-apps/examples/media-notes/playwright.config.ts
@@ -30,8 +30,7 @@ export default defineConfig({
name: 'setup',
testMatch: /.*\.setup\.ts/,
},
- // Chromium only: the fake media device flags that make getUserMedia and
- // MediaRecorder deterministic in CI are Chromium-specific.
+ // The fake media device flags are Chromium-specific.
{
name: 'chromium',
use: {
@@ -39,8 +38,6 @@ export default defineConfig({
storageState: path.resolve(__dirname, 'e2e/.auth/user.json'),
permissions: ['microphone', 'camera'],
launchOptions: {
- // Lets sandboxed environments point at a preinstalled Chromium
- // instead of downloading the pinned revision.
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
args: [
'--use-fake-ui-for-media-stream',
diff --git a/packages/twenty-apps/examples/media-notes/src/components/media-notes.front-component.tsx b/packages/twenty-apps/examples/media-notes/src/components/media-notes.front-component.tsx
index f8d11613e94..e7b6ba302d6 100644
--- a/packages/twenty-apps/examples/media-notes/src/components/media-notes.front-component.tsx
+++ b/packages/twenty-apps/examples/media-notes/src/components/media-notes.front-component.tsx
@@ -57,10 +57,7 @@ const fetchObjectsPage = async (after: string | null): Promise<ObjectsPage> => {
};
};
-// An app declares its fields by universalIdentifier; the per-instance
-// fieldMetadataId the recording upload needs is resolved at runtime. The
-// metadata API cannot filter on universalIdentifier, so page through the
-// object list until the field turns up.
+// The metadata API can't filter on universalIdentifier, so page through objects until the field turns up.
const fetchRecordingFieldMetadataId = async (): Promise<string | null> => {
let cursor: string | null = null;
@@ -97,9 +94,6 @@ const getFileExtension = (mimeType: string): string =>
MIME_TYPE_TO_FILE_EXTENSION[mimeType.split(';')[0].trim().toLowerCase()] ??
'webm';
-// The recording engine is the standard web platform: getUserMedia and
-// MediaRecorder, polyfilled into the sandbox by the host. Errors surface as
-// DOMException names exactly like in a regular page.
const mapMediaErrorNameToReason = (errorName: string): string => {
switch (errorName) {
case 'NotAllowedError':
@@ -162,17 +156,14 @@ const MediaNotes = () => {
useState<ActiveRecording | null>(null);
const [elapsedSeconds, setElapsedSeconds] = useState(0);
const [savedRecordId, setSavedRecordId] = useState<string | null>(null);
- // Set only when attaching failed, so it doubles as the retry payload.
const [failedAttach, setFailedAttach] = useState<PendingAttach | null>(null);
const [isAttaching, setIsAttaching] = useState(false);
- // Covers the stop-and-upload window: without it the record buttons come
- // back while the previous recording is still uploading, and two flows race.
+ // Covers the stop-and-upload window: without it the record buttons return mid-upload and two flows race.
const [isStopping, setIsStopping] = useState(false);
const recordingSessionRef = useRef<RecordingSession | null>(null);
const stopAndSaveRef = useRef<(() => void) | null>(null);
- // Synchronous guard: a second click during the getUserMedia permission
- // prompt would otherwise start a second capture.
+ // Synchronous guard against a second click during the getUserMedia permission prompt.
const isStartingRef = useRef(false);
useEffect(() => {
@@ -181,9 +172,6 @@ const MediaNotes = () => {
.catch(() => setRecordingFieldMetadataId(null));
}, []);
- // The recording UX is the app's own: this timer is rendered and styled
- // here, and the app also owns its duration ceiling — the host imposes
- // none.
useEffect(() => {
if (activeRecording === null) {
return;
@@ -206,9 +194,7 @@ const MediaNotes = () => {
return () => clearInterval(elapsedInterval);
}, [activeRecording]);
- // Attaching the uploaded file to a record is what makes it permanent: until
- // then it is a temporary file owned by the FILES field, so a failure here
- // has to be recoverable rather than silent.
+ // Until attached the upload is a temporary file, so a failure here must be retryable.
const attachToNewMediaNote = async (pendingAttach: PendingAttach) => {
setFailedAttach(null);
setIsAttaching(true);
@@ -240,9 +226,7 @@ const MediaNotes = () => {
};
const handleStartRecording = async (mediaType: 'audio' | 'video') => {
- // Starting a new recording mid-attach would let the in-flight attach
- // settle against a recording the UI has already replaced, offering a
- // retry for the wrong file.
+ // An in-flight attach would settle against a replaced recording and offer a retry for the wrong file.
if (
recordingFieldMetadataId === null ||
isAttaching ||
@@ -300,9 +284,7 @@ const MediaNotes = () => {
recordingSession.errorName = errorEvent.error?.name ?? 'UnknownError';
};
- // A stop the app did not ask for means the recorder failed to start on
- // the host or died mid-recording (it fires error then stop, like the
- // native API): release the devices and surface the failure.
+ // An unrequested stop means the recorder failed on the host (error then stop, like the native API).
mediaRecorder.addEventListener('stop', () => {
if (recordingSession.isUserStopping || recordingSession.wasCancelled) {
return;
@@ -325,9 +307,6 @@ const MediaNotes = () => {
});
});
- // The host indicator's stop button (or a revoked device) surfaces as
- // standard track ended events; the app reacts by discarding, without
- // any bespoke callback from the host.
for (const track of mediaStream.getTracks()) {
track.onended = () => {
if (recordingSession.wasCancelled) {
@@ -337,9 +316,7 @@ const MediaNotes = () => {
recordingSession.wasCancelled = true;
recordingSessionRef.current = null;
- // One dead track ends the whole take: stop the recorder and the
- // remaining tracks so nothing keeps capturing behind the
- // cancelled state.
+ // One dead track ends the whole take.
if (mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
@@ -365,8 +342,6 @@ const MediaNotes = () => {
mediaRecorder,
});
} catch (error) {
- // The recorder can fail after the devices were granted; do not leave
- // them capturing behind a failure message.
if (acquiredMediaStream !== null) {
for (const track of acquiredMediaStream.getTracks()) {
track.stop();
@@ -421,8 +396,7 @@ const MediaNotes = () => {
return;
}
- // An errored recorder still resolves the stop, but with nothing worth
- // uploading.
+ // An errored recorder still resolves the stop, with nothing worth uploading.
if (recordingSession.errorName !== null || recordedBlob.size === 0) {
setCaptureResult({
status: 'failed',
diff --git a/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts b/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
index 4295390834f..8e353dc7991 100644
--- a/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
+++ b/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
@@ -369,9 +369,7 @@ const getPersonTimelineDiffFieldNames = async (
const TIMELINE_POLL_TIMEOUT_MS = 30_000;
const TIMELINE_POLL_INTERVAL_MS = 500;
-// Timeline activities are written asynchronously by the worker, so an empty
-// timeline alone proves nothing; a later write to a regular field gives the
-// check something it has to wait for.
+// Timeline activities are written async by the worker, so an empty timeline proves nothing; a later field write gives the check something to wait for.
const waitForPersonTimelineDiffFieldName = async (
client: CoreApiClient,
{ personId, fieldName }: { personId: string; fieldName: string },
diff --git a/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
index ca66236ca78..61756b1d54c 100644
--- a/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
+++ b/packages/twenty-client-sdk/src/generate/__tests__/client-wrapper-auth.test.ts
@@ -85,8 +85,6 @@ describe('Generated client wrapper auth behavior', () => {
});
it('should act as the application when nobody triggered the run', async () => {
- // The runtime points TWENTY_APP_ACCESS_TOKEN at the application in a cron
- // schedule or install hook, so the default client keeps working there.
process.env.TWENTY_APP_ACCESS_TOKEN = 'application-token';
process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'application-token';
diff --git a/packages/twenty-client-sdk/src/generate/twenty-client-template.ts b/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
index 58e07a0c246..00f4cc3358e 100644
--- a/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
+++ b/packages/twenty-client-sdk/src/generate/twenty-client-template.ts
@@ -1,7 +1,6 @@
import type { TwentyClientRunAs } from '../shared/twenty-client-run-as.type';
-// Ambient type stubs for the genql-generated code this template gets
-// injected into. They enable full typecheck/lint on this file.
+// Ambient stubs for the genql-generated code this template is injected into.
// __STRIPPED_DURING_INJECTION_START__
type QueryGenqlSelection = Record<string, unknown>;
type MutationGenqlSelection = Record<string, unknown>;
@@ -193,8 +192,6 @@ export class TwentyGeneratedClient {
typeof headers === 'function' ? undefined : headers,
);
- // Priority: explicit header > the token for the requested access > api key
- // (legacy).
this.authorizationToken =
tokenFromHeaders ??
processEnvironment[
diff --git a/packages/twenty-client-sdk/src/metadata/generated/index.ts b/packages/twenty-client-sdk/src/metadata/generated/index.ts
index f313a5e9efd..c67c6b89874 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/index.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/index.ts
@@ -69,8 +69,7 @@ function(options?: ClientOptions): Client {
// MetadataApiClient (auto-injected by twenty-client-sdk)
import type { TwentyClientRunAs } from '../shared/twenty-client-run-as.type';
-// Ambient type stubs for the genql-generated code this template gets
-// injected into. They enable full typecheck/lint on this file.
+// Ambient stubs for the genql-generated code this template is injected into.
const APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';
const APP_APPLICATION_ACCESS_TOKEN_ENV_KEY =
@@ -232,8 +231,6 @@ export class MetadataApiClient {
typeof headers === 'function' ? undefined : headers,
);
- // Priority: explicit header > the token for the requested access > api key
- // (legacy).
this.authorizationToken =
tokenFromHeaders ??
processEnvironment[
diff --git a/packages/twenty-client-sdk/src/rest/index.ts b/packages/twenty-client-sdk/src/rest/index.ts
index 2e400172730..919b5243ac0 100644
--- a/packages/twenty-client-sdk/src/rest/index.ts
+++ b/packages/twenty-client-sdk/src/rest/index.ts
@@ -62,8 +62,7 @@ const getProcessEnvironment = (): ProcessEnvironment => {
const isAppRoutePath = (path: string): boolean => /^\/?s\//.test(path);
-// The server serves app routes under /s/; isolated functions domains serve
-// them at the root, so the marker prefix is stripped before joining.
+// Isolated functions domains serve app routes at the root, without the server's /s/ prefix.
const stripAppRoutePrefix = (path: string): string =>
path.replace(/^(\/?)s\//, '$1');
@@ -193,9 +192,7 @@ export class RestApiClient {
return { baseUrl: this.resolveBaseUrl(), path };
}
- // /s/ marks an app HTTP route. TWENTY_FUNCTIONS_URL is a complete base
- // URL (isolated domains serve routes at the root, self-host bakes /s in);
- // fall back to the same-site /s route when it is not injected.
+ // TWENTY_FUNCTIONS_URL is a complete base URL (isolated domains serve at the root, self-host bakes /s in).
return {
baseUrl: this.resolveFunctionsBaseUrl() ?? `${this.resolveBaseUrl()}/s`,
path: stripAppRoutePrefix(path),
diff --git a/packages/twenty-docs/scripts/lint-mdx.ts b/packages/twenty-docs/scripts/lint-mdx.ts
index bf6e1f37232..ca472ef9889 100644
--- a/packages/twenty-docs/scripts/lint-mdx.ts
+++ b/packages/twenty-docs/scripts/lint-mdx.ts
@@ -6,9 +6,7 @@ import {
SUPPORTED_LANGUAGES,
} from '../navigation/supported-languages';
-// Crowdin parses `<foo>` in prose as a tag rather than literal text, so an angle
-// bracket placeholder is either dropped or mangled in every translated page.
-// Curly braces `{foo}` survive the round trip.
+// Crowdin parses `<foo>` in prose as a tag and mangles it in translations; `{foo}` survives.
const DOCS_ROOT = path.resolve(__dirname, '..');
@@ -102,8 +100,7 @@ type Range = {
const FENCE_LINE_PATTERN = /^\s*(`{3,})/;
-// A fence closes only on a run at least as long as the one that opened it, so a
-// block opened with ``` is not closed by the first ``` inside a ```` example.
+// A fence closes only on a run at least as long as its opener (CommonMark).
const getFencedCodeRanges = (text: string): Range[] => {
const ranges: Range[] = [];
const lines = text.split('\n');
@@ -138,9 +135,7 @@ const getFencedCodeRanges = (text: string): Range[] => {
const isInsideRange = (position: number, ranges: Range[]) =>
ranges.some((range) => position >= range.start && position < range.end);
-// Backtick runs are paired within a line, never across one. A running parity
-// counter would let a single unpaired backtick silently suppress every finding
-// in the rest of the file.
+// Paired per line: a running counter would let one unpaired backtick suppress every later finding.
const getInlineCodeRanges = (text: string, fencedRanges: Range[]): Range[] => {
const ranges: Range[] = [];
let lineStart = 0;
diff --git a/packages/twenty-e2e-testing/lib/fixtures/blank-workflow.ts b/packages/twenty-e2e-testing/lib/fixtures/blank-workflow.ts
index b65574f2361..5926c205162 100644
--- a/packages/twenty-e2e-testing/lib/fixtures/blank-workflow.ts
+++ b/packages/twenty-e2e-testing/lib/fixtures/blank-workflow.ts
@@ -287,7 +287,6 @@ export class WorkflowVisualizerPage {
await openInRecordPageOption.click();
}
- // Close the dropdown
await recordTableOptionsButton.click();
}
}
diff --git a/packages/twenty-e2e-testing/lib/pom/helper/insertFieldData.ts b/packages/twenty-e2e-testing/lib/pom/helper/insertFieldData.ts
index 562d726d2dd..2b545cecf9e 100644
--- a/packages/twenty-e2e-testing/lib/pom/helper/insertFieldData.ts
+++ b/packages/twenty-e2e-testing/lib/pom/helper/insertFieldData.ts
@@ -10,7 +10,6 @@ export class InsertFieldData {
private readonly countrySelect: Locator;
private readonly arrayValueInput: Locator;
private readonly arrayAddValueButton: Locator;
- // boolean react after click so no need to write special locator
private readonly currencySelect: Locator;
private readonly currencyAmountInput: Locator;
private readonly monthSelect: Locator;
@@ -78,7 +77,6 @@ export class InsertFieldData {
);
}
- // address
async typeAddress1(value: string) {
await this.address1Input.fill(value);
}
@@ -106,7 +104,6 @@ export class InsertFieldData {
.click();
}
- // array
async typeArrayValue(value: string) {
await this.arrayValueInput.fill(value);
}
@@ -115,7 +112,6 @@ export class InsertFieldData {
await this.arrayAddValueButton.click();
}
- // currency
async selectCurrency(value: string) {
await this.currencySelect.click();
await this.page
@@ -127,7 +123,6 @@ export class InsertFieldData {
await this.currencyAmountInput.fill(value);
}
- // date(-time)
async typeDate(value: string) {
await this.dateInput.fill(value);
}
@@ -164,7 +159,6 @@ export class InsertFieldData {
await this.clearDateButton.click();
}
- // email
async typeEmail(value: string) {
await this.page.locator(`//input[@placeholder='Email']`).fill(value);
}
@@ -173,7 +167,6 @@ export class InsertFieldData {
await this.addMailButton.click();
}
- // full name
async typeFirstName(name: string) {
await this.firstNameInput.fill(name);
}
@@ -182,15 +175,12 @@ export class InsertFieldData {
await this.lastNameInput.fill(name);
}
- // JSON
- // placeholder is dependent on the name of field
async typeJSON(placeholder: string, value: string) {
await this.page
.locator(`//input[@placeholder='${placeholder}']`)
.fill(value);
}
- // link
async typeLink(value: string) {
await this.page.locator("//input[@placeholder='URL']").fill(value);
}
@@ -199,22 +189,18 @@ export class InsertFieldData {
await this.addUrlButton.click();
}
- // (multi-)select
async selectValue(value: string) {
await this.page
.locator(`//div[@data-testid='tooltip' and contains(., '${value}')]`)
.click();
}
- // number
- // placeholder is dependent on the name of field
async typeNumber(placeholder: string, value: string) {
await this.page
.locator(`//input[@placeholder='${placeholder}']`)
.fill(value);
}
- // phones
async selectCountryPhoneCode(countryCode: string) {
await this.page
.locator(
@@ -231,14 +217,11 @@ export class InsertFieldData {
await this.addPhoneButton.click();
}
- // rating
// if adding rating for the first time, hover must be used
async selectRating(rating: number) {
await this.page.locator(`//div[@role='slider']/div[${rating}]`).click();
}
- // text
- // placeholder is dependent on the name of field
async typeText(placeholder: string, value: string) {
await this.page
.locator(`//input[@placeholder='${placeholder}']`)
diff --git a/packages/twenty-e2e-testing/lib/pom/settings/newFieldSection.ts b/packages/twenty-e2e-testing/lib/pom/settings/newFieldSection.ts
index 2d79558c724..deb092cecdb 100644
--- a/packages/twenty-e2e-testing/lib/pom/settings/newFieldSection.ts
+++ b/packages/twenty-e2e-testing/lib/pom/settings/newFieldSection.ts
@@ -52,7 +52,6 @@ export class NewFieldSection {
"//div[contains(., 'Number of decimals')]/../div[last()]/div/div/button[2]",
);
this.decimalsNumberInput = page.locator(
- // would be better if first div was span tag
"//div[contains(., 'Number of decimals')]/../div[last()]/div/div/div/div/input[2]",
);
this.increaseDecimalsButton = page.locator(
@@ -147,7 +146,6 @@ export class NewFieldSection {
await this.booleanFieldLink.click();
}
- // either True of False
async selectDefaultBooleanValue(value: string) {
await this.defaultBooleanSelect.click();
await this.page.getByTestId('tooltip').filter({ hasText: value }).click();
@@ -215,7 +213,6 @@ export class NewFieldSection {
await this.relationFieldLink.click();
}
- // either 'Has many' or 'Belongs to one'
async selectRelationType(name: string) {
await this.relationTypeSelect.click();
await this.page.getByTestId('tooltip').filter({ hasText: name }).click();
diff --git a/packages/twenty-e2e-testing/lib/requests/post-backend-graphql.ts b/packages/twenty-e2e-testing/lib/requests/post-backend-graphql.ts
index 7cd713dd63d..3d1dbc7d91b 100644
--- a/packages/twenty-e2e-testing/lib/requests/post-backend-graphql.ts
+++ b/packages/twenty-e2e-testing/lib/requests/post-backend-graphql.ts
@@ -14,9 +14,7 @@ declare global {
}
}
-// Sent from inside the page so it carries the same workspace origin and
-// session cookie as the app's own requests. The cookie is scoped to the
-// workspace subdomain, which Node-side requests can neither resolve nor reach.
+// Runs in the page: the session cookie is scoped to the workspace subdomain, which Node can't reach.
export const postBackendGraphQL = <TData>({
page,
data,
diff --git a/packages/twenty-e2e-testing/playwright.config.ts b/packages/twenty-e2e-testing/playwright.config.ts
index 6d3346dbbb3..334f59c2634 100644
--- a/packages/twenty-e2e-testing/playwright.config.ts
+++ b/packages/twenty-e2e-testing/playwright.config.ts
@@ -18,18 +18,17 @@ export default defineConfig({
fullyParallel: false,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
- workers: 1, // 1 worker = 1 test at the time, tests can't be parallelized
+ workers: 1, // tests can't be parallelized
timeout: process.env.CI ? 60_000 : 30 * 1000,
use: {
baseURL: process.env.FRONTEND_BASE_URL || 'http://localhost:3001',
- trace: 'retain-on-failure', // trace takes EVERYTHING from page source, records every single step, should be used only when normal debugging won't work
- screenshot: 'on', // either 'on' here or in different method in modules, if 'on' all screenshots are overwritten each time the test is run
+ trace: 'retain-on-failure',
+ screenshot: 'on',
headless: true, // instead of changing it to false, run 'yarn test:e2e:debug' or 'yarn test:e2e:ui'
testIdAttribute: 'data-testid',
},
expect: {
- // CI runners are slow enough that post-mutation UI transitions routinely
- // exceed 5s; locally keep the tight budget.
+ // CI runners routinely exceed 5s on post-mutation UI transitions.
timeout: process.env.CI ? 15_000 : 5000,
},
reporter: [
diff --git a/packages/twenty-e2e-testing/tests/authentication/signup_invite_email.spec.ts b/packages/twenty-e2e-testing/tests/authentication/signup_invite_email.spec.ts
index ca9e2c2775e..bfdd9478268 100644
--- a/packages/twenty-e2e-testing/tests/authentication/signup_invite_email.spec.ts
+++ b/packages/twenty-e2e-testing/tests/authentication/signup_invite_email.spec.ts
@@ -22,8 +22,7 @@ test('Sign up with invite link via email', async ({
const inviteLink: string =
await test.step('Go to Settings and copy invite link', async () => {
- // Later tests reuse the saved session, and signing out or signing up
- // from it would revoke it server-side.
+ // Signing out or up from the saved session would revoke it server-side for later tests.
const inviterPage = await browser.newPage({
storageState: AUTH_STORAGE_STATE_PATH,
permissions: ['clipboard-read', 'clipboard-write'],
diff --git a/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts b/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts
index 4f9f16fc2f0..4e8f50ee161 100644
--- a/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts
+++ b/packages/twenty-e2e-testing/tests/create-kanban-view.spec.ts
@@ -1,7 +1,6 @@
import { expect, test } from '../lib/fixtures/screenshot';
test.describe.serial('Create Kanban View', () => {
-// Unique per run: retries of this serial group re-run field creation against
-// the same database, and a duplicate label makes the form unsubmittable.
+// Unique per run: serial-group retries re-create the field, and a duplicate label blocks the form.
const industryLabel = `Industry ${Date.now()}`;
test('Create Industry Select Field', async ({ page }) => {
await page.getByRole('button', { name: 'Settings', exact: true }).click();
diff --git a/packages/twenty-e2e-testing/tests/create-record.spec.ts b/packages/twenty-e2e-testing/tests/create-record.spec.ts
index 85d693469a3..545776415c1 100644
--- a/packages/twenty-e2e-testing/tests/create-record.spec.ts
+++ b/packages/twenty-e2e-testing/tests/create-record.spec.ts
@@ -71,7 +71,6 @@ test('Create and update record', async ({ page }) => {
const randomEmail = `testuser_${Math.random().toString(36).substring(2, 10)}@example.com`;
- // Fill the record creation form in the side panel
const firstNameInput = page.locator('[contenteditable]').filter({
has: page.locator('p[data-placeholder="F‌‌irst name"]'),
});
@@ -96,7 +95,6 @@ test('Create and update record', async ({ page }) => {
await page.getByTestId('record-creation-form-create-button').click();
- // The created record opens in the side panel
const recordFieldList = page.getByTestId('record-fields-widget');
await expect(recordFieldList).toBeVisible({ timeout: 15_000 });
await expect(recordFieldList.getByText(randomEmail)).toBeVisible({
@@ -146,7 +144,6 @@ test('Create and update record', async ({ page }) => {
.first()
.click({ force: true });
- // Open full record page to get person ID
await page.getByRole('button', { name: 'Expand record' }).click();
await page.waitForURL(/\/object\/person\//);
const newPersonId = page.url().match(/\/object\/person\/([a-f0-9-]+)/)?.[1];
diff --git a/packages/twenty-e2e-testing/tests/login.setup.ts b/packages/twenty-e2e-testing/tests/login.setup.ts
index af8252c6fde..82688e1c000 100644
--- a/packages/twenty-e2e-testing/tests/login.setup.ts
+++ b/packages/twenty-e2e-testing/tests/login.setup.ts
@@ -17,7 +17,6 @@ test('Login test', async ({ loginPage, page }) => {
'Logging in '.concat(page.url(), ' as ', process.env.DEFAULT_LOGIN),
async () => {
await page.waitForLoadState('networkidle');
- // Click "Continue with Email" if visible (may be skipped if password is the only auth method)
await loginPage.clickLoginWithEmailIfVisible();
await loginPage.typeEmail(process.env.DEFAULT_LOGIN);
await loginPage.clickContinueButton();
diff --git a/packages/twenty-emails/src/emails/billing-subscription-renewing.email.tsx b/packages/twenty-emails/src/emails/billing-subscription-renewing.email.tsx
index 5e3b4ea7b26..55217ca0363 100644
--- a/packages/twenty-emails/src/emails/billing-subscription-renewing.email.tsx
+++ b/packages/twenty-emails/src/emails/billing-subscription-renewing.email.tsx
@@ -14,9 +14,7 @@ type BillingSubscriptionRenewingEmailProps = {
locale: keyof typeof APP_LOCALES;
};
-// Sent 7 days before a yearly subscription renews. Goal: never let a large annual
-// charge be a surprise. This is both fair to the customer and expected by auto-renewal
-// laws in several regions. Monthly subscriptions intentionally get no renewal reminders.
+// Sent 7 days before a yearly renewal, as auto-renewal laws in several regions expect; monthly plans get none.
export const BillingSubscriptionRenewingEmail = ({
userName,
workspaceDisplayName,
diff --git a/packages/twenty-emails/src/emails/billing-trial-converting.email.tsx b/packages/twenty-emails/src/emails/billing-trial-converting.email.tsx
index 0940417c78e..423393e8de1 100644
--- a/packages/twenty-emails/src/emails/billing-trial-converting.email.tsx
+++ b/packages/twenty-emails/src/emails/billing-trial-converting.email.tsx
@@ -15,9 +15,7 @@ type BillingTrialConvertingEmailProps = {
locale: keyof typeof APP_LOCALES;
};
-// Sent 7 days before a trial WITH a credit card ends, i.e. before the first charge.
-// Goal: be transparent and fair — no surprise charge. The user can cancel in one click
-// before the date if Twenty is not the right fit. This is intentionally not a dark pattern.
+// Sent 7 days before a carded trial converts, so the first charge is never a surprise.
export const BillingTrialConvertingEmail = ({
userName,
workspaceDisplayName,
diff --git a/packages/twenty-emails/src/emails/billing-trial-ending.email.tsx b/packages/twenty-emails/src/emails/billing-trial-ending.email.tsx
index e28ee4d9078..bfa10439629 100644
--- a/packages/twenty-emails/src/emails/billing-trial-ending.email.tsx
+++ b/packages/twenty-emails/src/emails/billing-trial-ending.email.tsx
@@ -15,9 +15,7 @@ type BillingTrialEndingEmailProps = {
locale: keyof typeof APP_LOCALES;
};
-// Sent the day before a trial WITHOUT a credit card ends. Goal: get the user to
-// add a payment method so they keep their workspace and data. No card on file means
-// there is no surprise charge risk, only a data-loss risk, so the framing is helpful.
+// Sent the day before a cardless trial ends; the risk is data loss, not a surprise charge.
export const BillingTrialEndingEmail = ({
userName,
workspaceDisplayName,
diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigator-clipboard.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigator-clipboard.front-component.tsx
index 3eed99d2a7c..5c716b81ec7 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigator-clipboard.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigator-clipboard.front-component.tsx
@@ -7,9 +7,7 @@ import {
STATUS_STYLE,
} from '@/__stories__/shared/front-components/styles';
-// Deliberately uses the standard web API rather than the SDK helper: this is
-// what a third-party library calls, and it only works if the worker polyfill
-// installed navigator.clipboard in the real sandbox realm.
+// Uses navigator.clipboard, not the SDK helper, to prove the polyfill reached the sandbox realm.
const HostApiNavigatorClipboardFrontComponent = () => {
const [status, setStatus] = useState('idle');
diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/navigator-clipboard.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/navigator-clipboard.stories.tsx
index 0e5c56e8c22..17713cbc22c 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/navigator-clipboard.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/navigator-clipboard.stories.tsx
@@ -26,9 +26,7 @@ export default meta;
type Story = StoryObj<typeof FrontComponentRenderer>;
-// Runs the real sandbox: iframe, worker, and bridge in an actual browser, so
-// it fails if the polyfill never reaches the worker realm — which the unit
-// tests of the install function cannot detect.
+// Runs the real sandbox to catch a polyfill that never reaches the worker realm, which unit tests can't.
export const NavigatorClipboard: Story = runFrontComponentStory({
frontComponentBundleName: 'host-api-navigator-clipboard',
play: async ({ canvasElement, args }) => {
diff --git a/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.front-component.tsx
index eb02d16bd1f..d2ccca3d26a 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.front-component.tsx
@@ -7,9 +7,7 @@ import {
STATUS_STYLE,
} from '@/__stories__/shared/front-components/styles';
-// Deliberately uses only the standard web APIs — getUserMedia, MediaStream,
-// MediaRecorder — the way a third-party recording library would. It only
-// works if the media polyfills reached the real sandbox worker realm.
+// Uses only standard web APIs, so it works only if the polyfills reached the sandbox worker realm.
const MediaRecorderPolyfillFrontComponent = () => {
const [status, setStatus] = useState('idle');
diff --git a/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.stories.tsx
index 55c8dbb5e27..bd6f72f7fd4 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/media/media-recorder-polyfill.stories.tsx
@@ -19,9 +19,7 @@ const TEST_TRACK_ID = 'track-under-test';
const TEST_RECORDER_ID = 'recorder-under-test';
const FAKE_RECORDED_BYTES = 'fake-audio-bytes';
-// A scripted session host: the worker side stays fully real (polyfills,
-// bridge, thread), while the host side answers with fabricated devices so
-// the story is deterministic without real hardware.
+// Real worker side; the host answers with fabricated devices so the story runs without hardware.
const createMockMediaSessionHost = () => {
let transport: MediaSessionEventTransport | null = null;
@@ -89,9 +87,6 @@ const baseStory = runFrontComponentStory({
await userEvent.click(subject);
- // The full loop ran: getUserMedia and MediaRecorder in the worker,
- // capture RPCs to the host, and the recorded Blob pushed back across
- // the bridge into standard dataavailable/stop events.
expect(
await canvas.findByText(
`media:captured:${FAKE_RECORDED_BYTES.length}`,
diff --git a/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentMediaSessionEffect.tsx b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentMediaSessionEffect.tsx
index 0024a3671e8..892b932e128 100644
--- a/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentMediaSessionEffect.tsx
+++ b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentMediaSessionEffect.tsx
@@ -17,8 +17,7 @@ export const FrontComponentMediaSessionEffect = ({
return () => {
mediaSessionHost.disconnectEventTransport();
- // The worker that could stop these devices is going away with the
- // renderer, so nothing may keep capturing past unmount.
+ // The worker that could stop these devices dies with the renderer, so stop them here or they keep capturing.
mediaSessionHost.stopAllSessions();
};
}, [thread, mediaSessionHost]);
diff --git a/packages/twenty-front-component-renderer/src/host/media/constants/MediaRecorderCandidateMimeTypes.ts b/packages/twenty-front-component-renderer/src/host/media/constants/MediaRecorderCandidateMimeTypes.ts
index 69e8747a192..27b62a0165e 100644
--- a/packages/twenty-front-component-renderer/src/host/media/constants/MediaRecorderCandidateMimeTypes.ts
+++ b/packages/twenty-front-component-renderer/src/host/media/constants/MediaRecorderCandidateMimeTypes.ts
@@ -1,6 +1,4 @@
-// isTypeSupported answers in the worker come from a snapshot, so the host
-// probes a list of the container/codec combinations applications actually
-// ask for. Anything outside the list reports as unsupported.
+// Worker isTypeSupported answers come from a host snapshot of these; anything else reports unsupported.
export const MEDIA_RECORDER_CANDIDATE_MIME_TYPES = [
'audio/webm',
'audio/webm;codecs=opus',
diff --git a/packages/twenty-front-component-renderer/src/host/media/utils/createFrontComponentMediaSessionHost.ts b/packages/twenty-front-component-renderer/src/host/media/utils/createFrontComponentMediaSessionHost.ts
index fedcbb6f92a..873e8c0f494 100644
--- a/packages/twenty-front-component-renderer/src/host/media/utils/createFrontComponentMediaSessionHost.ts
+++ b/packages/twenty-front-component-renderer/src/host/media/utils/createFrontComponentMediaSessionHost.ts
@@ -127,12 +127,10 @@ export const createFrontComponentMediaSessionHost = ({
let isMediaPolicyRequestPending = false;
let liveCaptureSessionCount = 0;
let transport: MediaSessionEventTransport | null = null;
- // Bumped by stopAllSessions so a getUserMedia still pending at teardown
- // cannot register a stream nobody owns anymore.
+ // Bumped on teardown so a pending getUserMedia can't register an orphaned stream.
let teardownGeneration = 0;
let cancelPendingStart: (() => void) | null = null;
- // Recorder chunks must survive the window before the worker transport is
- // connected, so events buffer instead of dropping.
+ // Buffered so recorder chunks survive until the worker transport connects.
let bufferedEvents: MediaSessionEvent[] = [];
const pushEvents = (events: MediaSessionEvent[]): void => {
@@ -399,8 +397,7 @@ export const createFrontComponentMediaSessionHost = ({
liveCaptureSessionCount += 1;
for (const track of mediaStream.getTracks()) {
- // Fires for external endings (device unplugged, permission revoked),
- // not for stop() calls: those are reported to the worker explicitly.
+ // Fires only for external endings; stop() calls are reported to the worker explicitly.
track.addEventListener('ended', () => {
pushEvents([{ type: 'track-ended', streamId, trackId: track.id }]);
refreshStreamSessionLiveness(streamId);
@@ -600,8 +597,7 @@ export const createFrontComponentMediaSessionHost = ({
}
track.stop();
- // stop() fires no native ended event, so the worker is told
- // explicitly that its tracks are gone.
+ // stop() fires no native ended event, so the worker is told explicitly.
endedTrackEvents.push({
type: 'track-ended',
streamId: streamSession.streamId,
diff --git a/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/installClipboardPolyfill.ts b/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/installClipboardPolyfill.ts
index c05b1761296..de40f628baa 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/installClipboardPolyfill.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/clipboard/utils/installClipboardPolyfill.ts
@@ -11,9 +11,7 @@ type InstallClipboardPolyfillInput = {
copyToClipboard: (text: string) => Promise<void>;
};
-// Libraries call the standard navigator.clipboard.writeText; the worker has
-// no clipboard access, so the write is delegated to the host. Only writeText
-// is polyfilled: reading the clipboard is not a capability the host grants.
+// The worker has no clipboard, so writeText is delegated to the host; reading is not a granted capability.
export const installClipboardPolyfill = ({
globalScope,
copyToClipboard,
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/__tests__/installMediaCapturePolyfills.test.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/__tests__/installMediaCapturePolyfills.test.ts
index 2b29a83d031..7e57534dfe7 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/__tests__/installMediaCapturePolyfills.test.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/__tests__/installMediaCapturePolyfills.test.ts
@@ -182,8 +182,7 @@ describe('installMediaCapturePolyfills', () => {
expect(mediaRecorder.state).toBe('recording');
- // The start acknowledgement crosses several await boundaries; a
- // macrotask drains them all.
+ // A macrotask drains the start acknowledgement's await boundaries.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(startHandler).toHaveBeenCalledTimes(1);
@@ -235,14 +234,11 @@ describe('installMediaCapturePolyfills', () => {
await new Promise((resolve) => setTimeout(resolve, 0));
mediaRecorder.stop();
- // Restart before the previous host stop event has arrived.
mediaRecorder.start();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(mediaRecorder.state).toBe('recording');
- // The late stop event of the previous recording must not end the new
- // one.
bridge.dispatchEvents({
events: [{ type: 'recorder-stop', recorderId: 'recorder-0' }],
});
@@ -285,8 +281,7 @@ describe('installMediaCapturePolyfills', () => {
expect(errorHandler).toHaveBeenCalledTimes(1);
expect(errorHandler.mock.calls[0][0].error.name).toBe('NotReadableError');
- // The stop event follows the error, like a native recorder, so callers
- // waiting on it never hang.
+ // Native recorders fire stop after error, so callers waiting on it never hang.
expect(stopHandler).toHaveBeenCalledTimes(1);
expect(mediaRecorder.state).toBe('inactive');
});
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.ts
index ad2a9dbff24..1af7f6782a4 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaRecorderClass.ts
@@ -51,11 +51,9 @@ export const createMediaRecorderClass = ({
#state: WorkerMediaRecorderState = 'inactive';
#mimeType: string;
#recorderId: string | null = null;
- // Restarting before the previous host stop event arrives must not let
- // stale acknowledgements or events touch the new recording.
+ // Lets a restart ignore stale acknowledgements and events from the previous start.
#startGeneration = 0;
- // A stop, pause, or data request can land while the start round trip is
- // still in flight; they are applied once the host recorder id is known.
+ // Stop/pause/data requests during the start round trip apply once the host recorder id is known.
#hasPendingStopRequest = false;
#hasPendingPauseRequest = false;
#hasPendingDataRequest = false;
@@ -213,8 +211,7 @@ export const createMediaRecorderClass = ({
})
.then((result) => {
if (!isCurrentGeneration()) {
- // A newer start owns this recorder object now; do not leak the
- // host recorder this stale acknowledgement created.
+ // A newer start owns this object; stop the host recorder this stale acknowledgement created.
if (result.status === 'started') {
bridge.stopRecorder(result.recorderId);
}
@@ -222,8 +219,7 @@ export const createMediaRecorderClass = ({
}
if (result.status === 'failed') {
- // Native recorders that fail to start fire error and then stop,
- // so waiting on the stop event never hangs.
+ // Native recorders fire error then stop on a failed start, so waiting on stop never hangs.
this.#state = 'inactive';
this.#hasPendingStopRequest = false;
this.dispatchEvent(
@@ -248,8 +244,6 @@ export const createMediaRecorderClass = ({
if (this.#hasPendingPauseRequest) {
this.#hasPendingPauseRequest = false;
- // The pause event was deferred so it follows the start event in
- // native order.
this.dispatchEvent(new Event('pause'));
bridge.pauseRecorder(result.recorderId);
}
@@ -300,8 +294,7 @@ export const createMediaRecorderClass = ({
return;
}
- // Event deferred until the start acknowledgement so pause never fires
- // before start.
+ // Deferred until the start acknowledgement so pause never fires before start, as natively.
this.#hasPendingPauseRequest = true;
}
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamClass.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamClass.ts
index ee74dabb410..661a5fece5b 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamClass.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamClass.ts
@@ -49,8 +49,7 @@ export const createMediaStreamClass = () => {
if (streamOrTracks instanceof MediaStreamImplementation) {
this.#tracks = [...streamOrTracks.getTracks()];
- // A clone of a captured stream stays recordable, like the native
- // constructor which keeps the same source tracks.
+ // Like the native constructor, a clone keeps the source tracks and stays recordable.
const sourceCapturedStreamId = capturedStreamIds.get(streamOrTracks);
if (isDefined(sourceCapturedStreamId)) {
@@ -104,8 +103,7 @@ export const createMediaStreamClass = () => {
}
}
- // Captured streams keep their host streamId out of band: the public id
- // stays a local value while the recorder resolves the host session id.
+ // The public id stays local; the host streamId is kept out of band for the recorder.
const instantiateCapturedMediaStream = ({
streamId,
tracks,
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamTrackClass.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamTrackClass.ts
index 8b7f8cf4916..67426a6107b 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamTrackClass.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createMediaStreamTrackClass.ts
@@ -42,8 +42,7 @@ export const createMediaStreamTrackClass = ({
constructor(key: symbol, init: WorkerMediaStreamTrackInit) {
super();
- // Real tracks only come from capture calls; direct construction is not
- // meaningful, which is also what native implementations enforce.
+ // Native implementations also forbid direct construction.
if (key !== constructionKey) {
throw new TypeError('Illegal constructor');
}
@@ -108,8 +107,7 @@ export const createMediaStreamTrackClass = ({
return;
}
- // Native stop() flips readyState synchronously and fires no ended
- // event: that event is reserved for externally caused endings.
+ // Native stop() flips readyState synchronously and fires no ended event.
this.#readyState = 'ended';
bridge.stopStreamTrack({ streamId: this.#streamId, trackId: this.id });
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createWorkerMediaBridge.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createWorkerMediaBridge.ts
index 5ccda421283..28fa278c725 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/createWorkerMediaBridge.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/createWorkerMediaBridge.ts
@@ -58,8 +58,7 @@ export const createWorkerMediaBridge = (): WorkerMediaBridge => {
};
const isRecorderMimeTypeSupported = (mimeType: string): boolean => {
- // The spec treats the empty string as "no preference", which is always
- // supported.
+ // The spec treats '' as "no preference", which is always supported.
if (mimeType === '') {
return true;
}
@@ -163,8 +162,7 @@ export const createWorkerMediaBridge = (): WorkerMediaBridge => {
return MEDIA_TRANSPORT_UNAVAILABLE_FAILURE;
}
- // Events for this recorder can only arrive after this response: both
- // travel the same message port, so registering now cannot miss any.
+ // Events travel the same message port after this response, so registering now cannot miss any.
if (result.status === 'started') {
recorderEventHandlersByRecorderId.set(result.recorderId, handlers);
}
diff --git a/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.ts b/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.ts
index 5a034178200..120e5daf154 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/media/utils/installMediaCapturePolyfills.ts
@@ -56,9 +56,7 @@ export const installMediaCapturePolyfills = ({
);
}
- // Detailed constraint objects (deviceId, resolution, ...) are accepted
- // but not forwarded: the host captures with its defaults for the
- // requested kinds.
+ // Detailed constraints are accepted but not forwarded: the host captures with its defaults.
const startStreamResult = await bridge.startStream({
audio: isAudioRequested,
video: isVideoRequested,
@@ -102,8 +100,7 @@ export const installMediaCapturePolyfills = ({
installTarget.navigator ??= targetNavigator;
- // The worker's own navigator is a platform object whose mediaDevices
- // does not exist; define it without clobbering anything already there.
+ // Worker navigators lack mediaDevices; define it without clobbering an existing one.
if (!isDefined(targetNavigator.mediaDevices)) {
Object.defineProperty(targetNavigator, 'mediaDevices', {
configurable: true,
diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/toGlobalScopeRecord.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/toGlobalScopeRecord.ts
index a3a9a6d2a00..95367ac3272 100644
--- a/packages/twenty-front-component-renderer/src/polyfills/utils/toGlobalScopeRecord.ts
+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/toGlobalScopeRecord.ts
@@ -1,6 +1,4 @@
-// Lib global types carry no index signature, but at runtime the worker
-// global scope is an ordinary mutable object the polyfills install onto.
-// The one assertion lives here so call sites stay cast-free.
+// Lib global types lack an index signature, but the worker global scope is a plain mutable object.
export const toGlobalScopeRecord = (
globalScope: object,
): Record<string, unknown> => globalScope as Record<string, unknown>;
diff --git a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts
index a90f90169c3..fae98736e95 100644
--- a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts
+++ b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts
@@ -135,8 +135,7 @@ installStorageBridge({
installClipboardPolyfill({
globalScope: toGlobalScopeRecord(globalThis),
- // Resolved lazily: the host communication api is populated after worker
- // boot, so the polyfill must not capture the function at install time.
+ // Resolved lazily: the host communication api is populated after worker boot.
copyToClipboard: (text) => {
const copyToClipboardFunction =
frontComponentHostCommunicationApi.copyToClipboard;
diff --git a/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts b/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts
index 4090be15b3c..30bbaefd459 100644
--- a/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts
+++ b/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts
@@ -18,7 +18,6 @@ export type HostToWorkerRenderContext = {
initialViewportGeometry?: ViewportGeometrySnapshot;
initialExecutionContext?: FrontComponentExecutionContext;
storageSnapshots?: FrontComponentStorageSnapshots;
- // MediaRecorder.isTypeSupported is synchronous, so the worker polyfill
- // answers from this snapshot instead of a round trip to the host.
+ // isTypeSupported is synchronous, so the worker polyfill answers from this snapshot.
mediaRecorderCapabilities?: MediaRecorderCapabilities;
};
diff --git a/packages/twenty-front-component-renderer/src/types/MediaSession.ts b/packages/twenty-front-component-renderer/src/types/MediaSession.ts
index a68e74c4c75..439d25e942c 100644
--- a/packages/twenty-front-component-renderer/src/types/MediaSession.ts
+++ b/packages/twenty-front-component-renderer/src/types/MediaSession.ts
@@ -5,9 +5,7 @@ export type MediaSessionTrackDescriptor = {
kind: MediaSessionMediaType;
};
-// Failures carry the standard DOMException name (NotAllowedError,
-// NotFoundError, NotReadableError, ...) so the worker polyfill can reject
-// with the same error shape native getUserMedia produces.
+// Standard DOMException names, so the polyfill rejects like native getUserMedia.
export type StartMediaStreamResult =
| {
status: 'started';
@@ -34,12 +32,9 @@ export type MediaRecorderCapabilities = {
supportedMimeTypes: string[];
};
-// Media capture crosses the sandbox boundary like hostFetch and geometry:
-// as dedicated thread functions owned by the renderer, not through the
-// application-facing host communication api.
+// Renderer-owned thread functions, not part of the application-facing host communication api.
export type MediaSessionHostFunctions = {
- // The requested kinds are forwarded as booleans so video-only capture
- // does not silently open the microphone.
+ // Per-kind booleans so video-only capture doesn't silently open the microphone.
mediaStartStream: (params: {
audio: boolean;
video: boolean;
@@ -48,8 +43,7 @@ export type MediaSessionHostFunctions = {
streamId: string;
trackId: string;
}) => Promise<void>;
- // track.enabled must reach the real track: a worker-local flag would let
- // an application believe it muted a device that is still being captured.
+ // Applied to the real track: a worker-local flag would let an app believe it muted a device still capturing.
mediaSetTrackEnabled: (params: {
streamId: string;
trackId: string;
diff --git a/packages/twenty-front-component-renderer/src/utils/generateRandomId.ts b/packages/twenty-front-component-renderer/src/utils/generateRandomId.ts
index 069080998b9..5995b520093 100644
--- a/packages/twenty-front-component-renderer/src/utils/generateRandomId.ts
+++ b/packages/twenty-front-component-renderer/src/utils/generateRandomId.ts
@@ -1,5 +1,4 @@
-// The sandboxed worker runs in an opaque origin, which is not a secure
-// context: crypto.randomUUID does not exist there, but getRandomValues does.
+// The sandboxed worker's opaque origin isn't a secure context, so crypto.randomUUID can be missing.
export const generateRandomId = (): string => {
if (typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
diff --git a/packages/twenty-front/.storybook/preview.tsx b/packages/twenty-front/.storybook/preview.tsx
index ed1931fb4e9..85bee6e629c 100644
--- a/packages/twenty-front/.storybook/preview.tsx
+++ b/packages/twenty-front/.storybook/preview.tsx
@@ -24,8 +24,7 @@ import { RootDecorator } from '../src/testing/decorators/RootDecorator';
import { resetJotaiStore } from '../src/modules/ui/utilities/state/jotai/jotaiStore';
// oxlint-disable-next-line no-restricted-imports
import { UserContext } from '../src/modules/users/contexts/UserContext';
-// Stories rendering CodeEditor / GraphiQL need Monaco's worker factory, which
-// the app normally sets up in src/index.tsx.
+// Monaco's worker factory for CodeEditor / GraphiQL stories, normally set up in src/index.tsx.
// oxlint-disable-next-line no-restricted-imports
import '../src/modules/app/utils/setupMonacoEnvironment';
@@ -97,10 +96,7 @@ initialize(
remoteImageMockHandlers,
);
-// Mirrors production's MinimalMetadataGater so any story rendering a
-// date-aware component (DateTimeDisplay, etc.) sees a real IANA timeZone
-// instead of UserContext's default `{}`. Stories needing a specific timezone
-// can still override by nesting their own UserContext.Provider.
+// Date-aware components need a real IANA timeZone, not UserContext's default `{}`; nest a UserContext.Provider to override.
const STORYBOOK_DEFAULT_USER_CONTEXT = {
dateFormat: DateFormat.DAY_FIRST,
timeFormat: TimeFormat.HOUR_24,
diff --git a/packages/twenty-front/jest.config.mjs b/packages/twenty-front/jest.config.mjs
index 6126421825e..9d19fd31562 100644
--- a/packages/twenty-front/jest.config.mjs
+++ b/packages/twenty-front/jest.config.mjs
@@ -16,8 +16,7 @@ process.env.TZ = 'GMT';
// oxlint-disable-next-line no-undef
process.env.LC_ALL = 'en_US.UTF-8';
const jestConfig = {
- // For more information please have a look to official docs https://jestjs.io/docs/configuration/#prettierpath-string
- // Prettier v3 will should be supported in jest v30 https://github.com/jestjs/jest/releases/tag/v30.0.0-alpha.1
+ // Jest 29 can't format inline snapshots with Prettier 3 (fixed in Jest 30).
prettierPath: null,
...(isCI && { reporters: ['./jest-failures-only-reporter.cjs'] }),
displayName: 'twenty-front',
diff --git a/packages/twenty-front/setupTests.ts b/packages/twenty-front/setupTests.ts
index aa6ef48e753..61f0edd12a1 100644
--- a/packages/twenty-front/setupTests.ts
+++ b/packages/twenty-front/setupTests.ts
@@ -13,8 +13,7 @@ import { messages as enMessages } from '~/locales/generated/en';
i18n.load({ [SOURCE_LOCALE]: enMessages });
i18n.activate(SOURCE_LOCALE);
-// jsdom has no TextEncoder/TextDecoder, and @ai-sdk/provider-utils builds one
-// while being imported.
+// jsdom lacks TextEncoder/TextDecoder, which @ai-sdk/provider-utils builds at import.
if (globalThis.TextDecoder === undefined) {
Object.assign(globalThis, { TextDecoder, TextEncoder });
}
@@ -40,8 +39,7 @@ if (typeof window !== 'undefined') {
});
}
-// jsdom does not implement ResizeObserver; @dnd-kit/dom expects it at import
-// time.
+// jsdom lacks ResizeObserver, which @dnd-kit/dom expects at import time.
class ResizeObserverMock {
observe() {}
unobserve() {}
diff --git a/packages/twenty-front/src/hooks/useNavigateApp.ts b/packages/twenty-front/src/hooks/useNavigateApp.ts
index 80f798eb344..e0f37af96c5 100644
--- a/packages/twenty-front/src/hooks/useNavigateApp.ts
+++ b/packages/twenty-front/src/hooks/useNavigateApp.ts
@@ -5,8 +5,7 @@ import { getAppPath } from 'twenty-shared/utils';
type NavigateAppOptions = NavigateOptions;
-// Stable across renders so an effect can list it as a dependency without
-// re-running every time the caller renders.
+// Stable across renders so effects can depend on it.
export const useNavigateApp = () => {
const navigate = useNavigate();
diff --git a/packages/twenty-front/src/hooks/useNavigateSettings.ts b/packages/twenty-front/src/hooks/useNavigateSettings.ts
index d129cd80f8f..51f53e3f0df 100644
--- a/packages/twenty-front/src/hooks/useNavigateSettings.ts
+++ b/packages/twenty-front/src/hooks/useNavigateSettings.ts
@@ -24,9 +24,7 @@ export const useNavigateSettings = () => {
) => {
const path = getSettingsPath(to, params, queryParams, hash);
- // A routed side-panel owns its location, and its navigator already opens
- // the settings shell when a path escapes to main. Every other surface
- // navigates the main router directly, so the shell has to be opened here.
+ // A routed side panel's navigator already opens the settings shell; other surfaces must open it here.
if (
workspaceSurface.type === 'main' ||
!workspaceSurface.ownsRouteLocation
diff --git a/packages/twenty-front/src/localization/hooks/useLocaleOptions.ts b/packages/twenty-front/src/localization/hooks/useLocaleOptions.ts
index d7ba21f3d42..1fd47072d05 100644
--- a/packages/twenty-front/src/localization/hooks/useLocaleOptions.ts
+++ b/packages/twenty-front/src/localization/hooks/useLocaleOptions.ts
@@ -8,8 +8,7 @@ export type LocaleOption = {
searchKeywords: string;
};
-// Language name in English and in its own language, so it is searchable
-// regardless of the UI language — e.g. typing "chinese" or "中文".
+// English and native names, so a locale is findable from any UI language ("chinese" or "中文").
const getLocaleSearchKeywords = (
locale: (typeof APP_LOCALES)[keyof typeof APP_LOCALES],
): string => {
@@ -36,9 +35,7 @@ const LOCALE_SEARCH_KEYWORDS: Record<string, string> = Object.fromEntries(
export const useLocaleOptions = (): LocaleOption[] => {
const { t } = useLingui();
- // Keyed by locale rather than listed, so a locale added to APP_LOCALES
- // without a label here fails the typecheck. Listed, it would ship its
- // translations and simply never appear in the picker, with no error.
+ // A Record, not a list, so a locale added to APP_LOCALES without a label fails the typecheck.
const labelByLocale: Record<keyof typeof APP_LOCALES, string> = {
'af-ZA': t`Afrikaans`,
'ar-SA': t`Arabic`,
diff --git a/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts b/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts
index b10dff16bfb..ff4f982e5c3 100644
--- a/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts
+++ b/packages/twenty-front/src/modules/activities/calendar/hooks/useCalendarEventComposer.ts
@@ -96,9 +96,7 @@ export const useCalendarEventComposer = ({
const hasTooManyAttendees =
sendInvitations && attendeeEmails.length > MAX_EMAIL_RECIPIENTS;
- // Guests that match a person are related to the event server-side once
- // participants are matched, so only the record the composer was opened from
- // needs to be offered here.
+ // Matched guests are linked server-side, so only the record the composer was opened from is offered.
const targetObjectMetadataItems = useCalendarEventTargetObjectMetadataItems();
const contextObjectMetadataItem = targetObjectMetadataItems.find(
({ nameSingular }) =>
@@ -107,8 +105,7 @@ export const useCalendarEventComposer = ({
const { record: contextRecord, loading: isContextRecordLoading } =
useFindOneRecord({
- // The composer can be opened from a record the junction cannot target; the
- // query is skipped there, but the hook still needs a resolvable object.
+ // Fallback for records the junction can't target: the query is skipped but needs a resolvable object.
objectNameSingular:
contextObjectMetadataItem?.nameSingular ??
CoreObjectNameSingular.Person,
@@ -187,8 +184,7 @@ export const useCalendarEventComposer = ({
invalidAttendeeEmails.length === 0 &&
!hasTooManyAttendees &&
hasValidDateRange &&
- // Creating before it resolves would silently drop the relation the composer
- // was opened for.
+ // Creating before it resolves would drop the relation the composer was opened for.
!(isDefined(contextObjectMetadataItem) && isContextRecordLoading) &&
!isCreating &&
!isCalendarEventComposerCreating;
@@ -259,10 +255,8 @@ export const useCalendarEventComposer = ({
return;
}
- // The event already exists at this point, so a failure to link the
- // related records must not keep the composer open: retrying would create
- // a second event. A missing id means persistence failed, and the next
- // provider sync then recreates the event without these links.
+ // The event exists by now, so a link failure must not keep the composer open: a retry would duplicate it.
+ // Without an id, persistence failed and the next provider sync recreates the event without these links.
if (targets.length > 0) {
let areTargetsLinked = false;
@@ -276,8 +270,7 @@ export const useCalendarEventComposer = ({
}
if (areTargetsLinked) {
- // createCalendarEvent already refetched, but that ran before these
- // links existed, so an event related only through them stays invisible.
+ // The earlier refetch ran before these links existed, so events related only through them were missing.
await refetchTimelineCalendarEvents();
} else {
enqueueToast({
diff --git a/packages/twenty-front/src/modules/activities/calendar/hooks/useCreateCalendarEventTargets.ts b/packages/twenty-front/src/modules/activities/calendar/hooks/useCreateCalendarEventTargets.ts
index 69c84526d36..5ca1743802b 100644
--- a/packages/twenty-front/src/modules/activities/calendar/hooks/useCreateCalendarEventTargets.ts
+++ b/packages/twenty-front/src/modules/activities/calendar/hooks/useCreateCalendarEventTargets.ts
@@ -15,9 +15,8 @@ export const useCreateCalendarEventTargets = () => {
const { createManyRecords: createCalendarEventTargetRecords } =
useCreateManyRecords({
- // Workspaces that predate the junction have no calendarEventTarget object
- // and resolving one throws, so this falls back to the calendar event
- // itself; without a junction config nothing is ever written.
+ // Workspaces predating the junction have no calendarEventTarget object and resolving one throws;
+ // the CalendarEvent fallback is never written to, since there is no junction config.
objectNameSingular:
junctionConfig?.junctionObjectMetadata.nameSingular ??
CoreObjectNameSingular.CalendarEvent,
@@ -60,9 +59,7 @@ export const useCreateCalendarEventTargets = () => {
return;
}
- // Participant matching already linked the guests it resolved, including
- // the record the composer was opened from, so these rows can collide with
- // the junction's unique indexes. Upsert resolves against them.
+ // Participant matching may already have linked these, colliding with the junction's unique indexes.
await createCalendarEventTargetRecords({ recordsToCreate, upsert: true });
},
[createCalendarEventTargetRecords, junctionConfig, objectMetadataItems],
diff --git a/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx b/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx
index c7eebf93f9d..47fcf18fc4b 100644
--- a/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx
+++ b/packages/twenty-front/src/modules/activities/components/ComposerFieldRow.tsx
@@ -47,14 +47,11 @@ type ComposerFieldRowProps = {
children: ReactNode;
trailing?: ReactNode;
onClick?: MouseEventHandler<HTMLDivElement>;
- // A floor, not a fixed width: mixed-length labels line up without a long
- // translation running underneath its control.
+ // A floor, not a fixed width, so a long translation doesn't run under its control.
labelMinWidth?: string;
};
-// The visible label is a plain span, so it cannot be associated with whatever
-// control the row wraps. Naming the row as a group gives assistive technology
-// the field name even for controls that take no label of their own.
+// The label is a plain span, so the row is named as a group to give assistive technology the field name.
export const ComposerFieldRow = ({
label,
children,
diff --git a/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx b/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx
index 51b70f5ea45..fef560984f3 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/CampaignBodyField.tsx
@@ -21,8 +21,7 @@ const StyledContainer = styled.div`
type CampaignBodyFieldProps = {
campaign: MessageCampaign;
- // Lets the composer follow the canvas: its width is a per-campaign design
- // setting, and the envelope block above lines up with it.
+ // Exposes the editor so the envelope block can follow the per-campaign canvas width.
onEditorReady?: (editor: Editor | null) => void;
};
diff --git a/packages/twenty-front/src/modules/activities/emails/components/CampaignComposer.tsx b/packages/twenty-front/src/modules/activities/emails/components/CampaignComposer.tsx
index 636672874c3..1bacb3cfbea 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/CampaignComposer.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/CampaignComposer.tsx
@@ -19,9 +19,7 @@ type CampaignComposerProps = {
campaign: MessageCampaign;
};
-// The envelope fields and the body are one surface rather than two widgets, so
-// the composer tab keeps a single full-bleed widget: stacking two widgets would
-// box each of them in its own card.
+// One widget, not two: stacked widgets would each get boxed in their own card.
export const CampaignComposer = ({ campaign }: CampaignComposerProps) => {
const [bodyEditor, setBodyEditor] = useState<Editor | null>(null);
const canvasWidth = useCampaignCanvasWidth(bodyEditor);
diff --git a/packages/twenty-front/src/modules/activities/emails/components/CampaignEnvelopeBox.tsx b/packages/twenty-front/src/modules/activities/emails/components/CampaignEnvelopeBox.tsx
index 81b46c7c669..4f713841c6f 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/CampaignEnvelopeBox.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/CampaignEnvelopeBox.tsx
@@ -4,8 +4,7 @@ import { themeCssVariables } from 'twenty-ui/theme';
import { ComposerFieldRow } from '@/activities/components/ComposerFieldRow';
-// Widest label the campaign rows use ("Unsubscribe topic"), so every value
-// starts on the same column.
+// Widest campaign row label ("Unsubscribe topic"), so every value starts on the same column.
const CAMPAIGN_ENVELOPE_LABEL_MIN_WIDTH = '116px';
const StyledContainer = styled.div`
@@ -17,8 +16,6 @@ const StyledContainer = styled.div`
width: 100%;
`;
-// Tracks the body page below rather than the window, so the two read as one
-// centred column.
const StyledColumn = styled.div<{ $width: string }>`
display: flex;
flex-direction: column;
@@ -45,8 +42,6 @@ type CampaignEnvelopeBoxProps = {
onBlur?: () => void;
};
-// The shell both campaign headers share, so the draft and the sent view line up
-// on the same column and cannot drift apart.
export const CampaignEnvelopeBox = ({
width,
children,
@@ -61,8 +56,6 @@ export const CampaignEnvelopeBox = ({
</StyledContainer>
);
-// Every envelope row shares one label width, so the draft and the sent view
-// cannot line their values up differently.
type CampaignEnvelopeRowProps = {
label: string;
children: ReactNode;
diff --git a/packages/twenty-front/src/modules/activities/emails/components/CampaignSentEnvelope.tsx b/packages/twenty-front/src/modules/activities/emails/components/CampaignSentEnvelope.tsx
index 4f103548667..f3b8be6c78e 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/CampaignSentEnvelope.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/CampaignSentEnvelope.tsx
@@ -39,9 +39,7 @@ type CampaignSentEnvelopeProps = {
width: string;
};
-// The sent counterpart of the draft envelope. It deliberately does not reuse
-// CampaignDetailsFields: that component owns the draft persistence state, which
-// has nothing to write for a campaign that has already gone out.
+// Doesn't reuse CampaignDetailsFields, which owns draft persistence state a sent campaign has no use for.
export const CampaignSentEnvelope = ({
campaign,
width,
@@ -51,30 +49,23 @@ export const CampaignSentEnvelope = ({
const { dateFormat, timeFormat, timeZone } = useDateTimeFormat();
const { localeCatalog } = useAtomStateValue(dateLocaleState);
- // withSoftDeleted so a list deleted after the send still names what the
- // campaign went to.
const hasList = isDefined(campaign.listId) && isValidUuid(campaign.listId);
const { record: list, loading: isListLoading } = useFindOneRecord({
objectNameSingular: CoreObjectNameSingular.MessageList,
objectRecordId: campaign.listId ?? '',
+ // A list deleted after the send must still name what the campaign went to.
withSoftDeleted: true,
skip: !hasList,
});
- // A lookup that returns nothing does not tell us why: the list may be
- // deleted, hidden by object or row-level permissions, or the query may have
- // failed — and useFindOneRecord skips entirely without read permission, which
- // is indistinguishable from an empty result. None of that is knowable here,
- // so the row reports what is true in every case instead of guessing at one.
+ // An empty lookup can't tell deletion, permissions or failure apart, so report what's true in every case.
const isListUnresolved = hasList && !isDefined(list) && !isListLoading;
const fromAddress = campaign.fromAddress?.primaryEmail;
const subject = campaign.subject;
- // The row follows the id the campaign was sent with, not whether the topic
- // still exists: a topic deleted afterwards must not erase the fact that this
- // send was scoped to one.
+ // Follows the sent id: a topic deleted afterwards must not erase that the send was scoped to one.
const hasUnsubscribeTopic = isDefined(campaign.unsubscribeTopicId);
const unsubscribeTopic = hasUnsubscribeTopic
@@ -83,8 +74,7 @@ export const CampaignSentEnvelope = ({
)
: undefined;
- // Same rule as the list row: an id missing from the topics we can see may be
- // deleted or may simply be one this role cannot read, and the two look alike.
+ // A missing topic may be deleted or unreadable by this role; the two look alike.
const isTopicUnresolved =
hasUnsubscribeTopic && !isDefined(unsubscribeTopic) && !areTopicsLoading;
diff --git a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
index 9341a47b1f4..f085740476f 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/EmailComposerFields.tsx
@@ -104,8 +104,7 @@ const StyledRecipientLimitWarning = styled.div`
type EmailComposerFieldsProps = {
composerState: EmailComposerState;
contextRecord?: EmailComposerContextRecord | null;
- // Surfaces without a composer footer of their own pass this so attaching
- // stays reachable from inside the form.
+ // For surfaces without a composer footer of their own.
onAttachFiles?: () => void;
};
diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/__tests__/useAttachEmailFiles.test.ts b/packages/twenty-front/src/modules/activities/emails/hooks/__tests__/useAttachEmailFiles.test.ts
index 39549d219c1..94554ecff39 100644
--- a/packages/twenty-front/src/modules/activities/emails/hooks/__tests__/useAttachEmailFiles.test.ts
+++ b/packages/twenty-front/src/modules/activities/emails/hooks/__tests__/useAttachEmailFiles.test.ts
@@ -19,8 +19,6 @@ const mockUseFileUpload = useFileUpload as jest.Mock;
const buildAttachment = (id: string): EmailAttachment =>
({ id, name: `${id}.pdf` }) as EmailAttachment;
-// Captures the onUpload callback the hook hands to the file picker, so a test
-// can drive an upload the way the picker would.
const setup = (uploadEmailAttachment: jest.Mock) => {
let triggerUpload: ((files: File[]) => Promise<void>) | undefined;
@@ -93,8 +91,6 @@ describe('useAttachEmailFiles', () => {
const appendToPreviousFiles = onFilesAttached.mock.calls[0][0];
- // The setter is called with an updater, so whatever the list holds when the
- // upload settles is what gets appended to.
expect(typeof appendToPreviousFiles).toBe('function');
expect(appendToPreviousFiles([buildAttachment('kept')])).toEqual([
buildAttachment('kept'),
diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/useAttachEmailFiles.ts b/packages/twenty-front/src/modules/activities/emails/hooks/useAttachEmailFiles.ts
index b3fa0ccf1aa..79852392303 100644
--- a/packages/twenty-front/src/modules/activities/emails/hooks/useAttachEmailFiles.ts
+++ b/packages/twenty-front/src/modules/activities/emails/hooks/useAttachEmailFiles.ts
@@ -37,9 +37,7 @@ export const useAttachEmailFiles = ({
return;
}
- // Appended against the latest state rather than the list captured when the
- // picker opened: an upload can finish after the user has removed or added
- // other attachments.
+ // An upload can finish after the user changed the attachments, so append to the latest state.
onFilesAttached((previousFiles) => [
...previousFiles,
...successfulUploads,
@@ -50,8 +48,7 @@ export const useAttachEmailFiles = ({
openFileUpload({ multiple: true, onUpload: handleUploadFiles });
};
- // Attachments only join the draft once their upload resolves, so sending has
- // to wait or the mail goes out without the file the user just picked.
+ // Attachments join the draft only once uploaded, so sending must wait for them.
return {
openAttachmentPicker,
isUploadingAttachments: pendingUploadCount > 0,
diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/useCampaignCanvasWidth.ts b/packages/twenty-front/src/modules/activities/emails/hooks/useCampaignCanvasWidth.ts
index 35623e76d64..ef5e97ad98b 100644
--- a/packages/twenty-front/src/modules/activities/emails/hooks/useCampaignCanvasWidth.ts
+++ b/packages/twenty-front/src/modules/activities/emails/hooks/useCampaignCanvasWidth.ts
@@ -6,16 +6,11 @@ import {
resolveCanvasTheme,
} from 'twenty-shared/utils';
-// The body renders as a centred page whose width the Design panel writes onto
-// the document, so the envelope block above it reads that width rather than
-// assuming the default. Falls back to the default until the editor mounts,
-// which is the same value for a campaign that never changed its design.
+// The envelope block reads the body width the Design panel writes onto the document; default until the editor mounts.
export const useCampaignCanvasWidth = (editor: Editor | null): string => {
const canvasWidth = useEditorState({
editor,
- // Reading the editor passed in rather than the snapshot one, which keeps
- // pointing at the instance `useEditor` destroyed when it recreated the
- // editor, until the next transaction refreshes the snapshot.
+ // Reads the editor passed in: the snapshot one can still be the instance `useEditor` destroyed when recreating it.
selector: () =>
isDefined(editor)
? (resolveCanvasTheme(editor.state.doc.attrs.canvasTheme)?.width ??
diff --git a/packages/twenty-front/src/modules/activities/emails/hooks/usePersistedCampaignDraft.ts b/packages/twenty-front/src/modules/activities/emails/hooks/usePersistedCampaignDraft.ts
index 06bd86d79d7..9dd369d55f9 100644
--- a/packages/twenty-front/src/modules/activities/emails/hooks/usePersistedCampaignDraft.ts
+++ b/packages/twenty-front/src/modules/activities/emails/hooks/usePersistedCampaignDraft.ts
@@ -42,8 +42,7 @@ export const usePersistedCampaignDraft = <TDraft extends object>({
draft,
updateDraft,
flush,
- // Inputs seeded through defaultValue (TipTap editors, record picker) read
- // the draft on mount only; key them with this to remount on adoption.
+ // defaultValue-seeded inputs (TipTap, record picker) read the draft on mount only; key them to remount.
draftResyncKey: `${campaignId}-${draftResyncKey}`,
};
};
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx
index 4ff08aa2b77..2187fc519e8 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldChipCell.tsx
@@ -16,8 +16,7 @@ const DROP_INDICATOR_WIDTH = '2px';
// Centers the bar in the 4px chip gap: half the gap plus half the bar.
const DROP_INDICATOR_OFFSET = '-3px';
-// The insertion bar is absolutely positioned so showing it never reflows the
-// wrapping chip row mid-drag.
+// Absolute so showing the bar never reflows the wrapping chip row mid-drag.
const StyledChipDropZone = styled.div`
position: relative;
@@ -92,8 +91,7 @@ export const EmailRecipientsFieldChipCell = ({
selectedIndices,
};
- // Intercepting in the capture phase keeps a modified click from reaching the
- // chip's dropdown, so shift/cmd click selects instead of opening the menu.
+ // Capture phase keeps a shift/cmd click from opening the chip's dropdown.
const handleClickCapture = (event: MouseEvent<HTMLDivElement>) => {
if (event.shiftKey) {
event.preventDefault();
@@ -122,8 +120,7 @@ export const EmailRecipientsFieldChipCell = ({
<StyledChipDropZone
data-drop-edge={dropEdge ?? undefined}
onClickCapture={handleClickCapture}
- // Keeps focus in the text input so chip keyboard navigation survives a
- // click on a chip.
+ // Keeps focus in the input so chip keyboard navigation survives a click.
onMouseDown={(event) => event.preventDefault()}
>
<EmailRecipientsFieldChip
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
index d2a1b8c6730..9c92711b5a6 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/components/EmailRecipientsFieldInput.tsx
@@ -55,8 +55,6 @@ import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/use
const SUGGESTIONS_SEARCH_DEBOUNCE_MS = 300;
-// The field sits inside a bordered composer row, so it carries no chrome of its
-// own; the drop-target tint is the only surface it paints.
const StyledRowContainer = styled.div<{ $isDropTarget: boolean }>`
align-content: flex-start;
align-items: center;
@@ -103,8 +101,7 @@ const StyledInput = styled.input`
type EmailRecipientsFieldInputProps = {
fieldId: EmailRecipientsFieldId;
- // Indices being dragged out of this field, or null when the drag started
- // elsewhere.
+ // null when the drag started in another field.
draggedSourceIndices: number[] | null;
label: string;
recipients: EmailRecipient[];
@@ -239,8 +236,7 @@ export const EmailRecipientsFieldInput = ({
const getChipId = (chipIndex: number) => `${focusId}-chip-${chipIndex}`;
- // Gaps at either end of the dragged run put the chips back exactly where they
- // came from, so marking them would promise a reorder that cannot happen.
+ // Gaps at either end of the dragged run are no-op drops, so marking them would promise a reorder.
const isNoOpDropGap = (gapIndex: number) => {
if (draggedSourceIndices === null || draggedSourceIndices.length === 0) {
return false;
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts
index 392d1711853..26838d00cf6 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/__tests__/useEmailRecipientsField.test.ts
@@ -341,8 +341,7 @@ describe('useEmailRecipientsField', () => {
expect(view.result.current.selectedChipIndices).toEqual([0, 1]);
- // A drag moved [email protected] to the end; the selection has to follow the
- // addresses rather than staying on positions 0 and 1.
+ // A drag moved [email protected] to the end; the selection must follow the addresses.
view.rerender({
recipients: [
{ address: '[email protected]' },
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop.ts b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop.ts
index 9e64cdcd8cb..ae7d8654056 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop.ts
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsDragAndDrop.ts
@@ -81,8 +81,7 @@ export const useEmailRecipientsDragAndDrop = ({
const resolvedDrop = resolveDropFromPointer({
target: event.operation.target,
pointer: event.operation.position.current,
- // Chips flow horizontally, so the insertion boundary is a vertical seam
- // and the pointer's x position decides which side of a chip it lands on.
+ // Chips flow horizontally, so the insertion seam is vertical.
defaultOrientation: 'vertical',
getDroppableItemCount,
});
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts
index ffd1e758e79..cd046441e40 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/hooks/useEmailRecipientsField.ts
@@ -17,12 +17,8 @@ type ChipFlash = {
nonce: number;
};
-// The selection is stored as recipient keys rather than array positions: a drag
-// can reorder the field underneath it, and positions would then point at
-// whichever chips happen to have moved into those slots.
-// anchorKey is where a shift-extended range starts and focusKey is the chip the
-// keyboard cursor sits on, so shift+arrow can grow and shrink the same range
-// the way a text selection does.
+// Keyed by recipient, not position: a drag can reorder the field underneath the selection.
+// anchorKey starts a shift-extended range and focusKey is the keyboard cursor chip, like a text selection.
type ChipSelection = {
anchorKey: string;
focusKey: string;
@@ -178,9 +174,7 @@ export const useEmailRecipientsField = ({
recipients.filter((_recipient, index) => !removedIndices.has(index)),
);
- // Selection collapses onto the chip just before the removed run, matching
- // how a text cursor lands after deleting a selection. That chip sits before
- // the lowest removed index, so it always survives the removal.
+ // Collapses onto the chip before the removed run, like a text cursor; it always survives the removal.
const indexBeforeRemoved = Math.min(...selectedChipIndices) - 1;
const keyBeforeRemoved = recipientKeys[indexBeforeRemoved];
@@ -224,8 +218,6 @@ export const useEmailRecipientsField = ({
const isAlreadySelected = previousSelection.keys.includes(chipKey);
if (!isAlreadySelected) {
- // Adding re-anchors on the clicked chip so a following shift+click
- // ranges from where the user last pointed.
return {
anchorKey: chipKey,
focusKey: chipKey,
@@ -239,8 +231,7 @@ export const useEmailRecipientsField = ({
return null;
}
- // Removing must not leave the anchor or the cursor on a chip that is no
- // longer selected, or Enter and shift+arrow would act on it.
+ // Move the anchor and cursor off the removed chip, or Enter and shift+arrow would act on an unselected chip.
const fallbackKey = nextKeys[nextKeys.length - 1];
return {
@@ -290,8 +281,6 @@ export const useEmailRecipientsField = ({
}
if (selectionFocusIndex === null || selectionAnchorIndex === null) {
- // Shift+Left out of the text input starts a selection on the last chip;
- // shift+Right has nowhere to go.
if (direction === 1) {
return null;
}
@@ -301,8 +290,7 @@ export const useEmailRecipientsField = ({
return lastIndex;
}
- // Unlike a plain arrow, extending past the last chip keeps the selection
- // rather than dropping the caret back into the input.
+ // Unlike a plain arrow, extending past the last chip keeps the selection.
const nextFocusIndex = Math.min(
Math.max(selectionFocusIndex + direction, 0),
recipients.length - 1,
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientDragData.ts b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientDragData.ts
index ea1318864a4..c723c766f71 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientDragData.ts
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/types/EmailRecipientDragData.ts
@@ -3,7 +3,6 @@ import { type EmailRecipientsFieldId } from '@/activities/emails/recipients/type
export type EmailRecipientDragData = {
fieldId: EmailRecipientsFieldId;
index: number;
- // Chips carry the field selection they were rendered with so a drag that
- // starts on a selected chip moves the whole selection, not just that chip.
+ // So a drag starting on a selected chip moves the whole selection.
selectedIndices: number[];
};
diff --git a/packages/twenty-front/src/modules/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields.ts b/packages/twenty-front/src/modules/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields.ts
index c42523c7b9a..d3541410b39 100644
--- a/packages/twenty-front/src/modules/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields.ts
+++ b/packages/twenty-front/src/modules/activities/emails/recipients/utils/moveEmailRecipientsBetweenFields.ts
@@ -8,8 +8,7 @@ export type EmailRecipientsByFieldId = Record<
EmailRecipient[]
>;
-// Both lists are built from the same recipient objects, so identity comparison
-// is enough to tell a real reorder from a drop that landed back in place.
+// Both lists share recipient objects, so identity comparison is enough.
const areRecipientListsEqual = (
recipients: EmailRecipient[],
otherRecipients: EmailRecipient[],
@@ -51,17 +50,14 @@ export const moveEmailRecipientsBetweenFields = ({
);
if (sourceFieldId === destinationFieldId) {
- // Removing the dragged chips first shifts every later slot left, so the
- // drop index has to lose the chips that used to sit before it.
+ // Removing the dragged chips first shifts every later slot left.
const removedBeforeDestinationCount = sortedMovedIndices.filter(
(index) => index < destinationIndex,
).length;
const adjustedDestinationIndex =
destinationIndex - removedBeforeDestinationCount;
- // Spliced back in directly rather than merged: a field seeded from a draft
- // can already hold the same address twice, and a reorder must never change
- // the recipient count.
+ // Spliced, not merged: a draft can hold the same address twice, and a reorder must keep the count.
const reorderedRecipients = toSpliced(
remainingSourceRecipients,
adjustedDestinationIndex,
diff --git a/packages/twenty-front/src/modules/activities/files/components/DocumentViewer.tsx b/packages/twenty-front/src/modules/activities/files/components/DocumentViewer.tsx
index 844c20e48bf..5e5806515c1 100644
--- a/packages/twenty-front/src/modules/activities/files/components/DocumentViewer.tsx
+++ b/packages/twenty-front/src/modules/activities/files/components/DocumentViewer.tsx
@@ -115,19 +115,9 @@ type DocumentViewerProps = {
documentExtension?: string;
};
-// MS Office Online viewer requires documents to be publicly accessible from the internet.
-// For private/local URLs, Microsoft's servers cannot fetch the document.
-//
-// We explored more sophisticated detection approaches but they don't work:
-// - postMessage: Microsoft's viewer doesn't send any error messages
-// - Fetching the embed URL: Blocked by CORS (no Access-Control-Allow-Origin header)
-// - Reading iframe content: Cross-origin restrictions prevent access
-//
-// This simple URL-based detection catches the most common cases (localhost, private IPs)
-// where the preview will definitely fail. For edge cases on non-standard private networks,
-// users will see Microsoft's error page but can still download the file.
-//
-// See: https://github.com/twentyhq/twenty/issues/16900
+// MS Office Online only fetches public URLs and its failure is undetectable (no postMessage, CORS, cross-origin),
+// so localhost and private IPs are caught by URL; other private hosts get Microsoft's error page but can still download.
+// See https://github.com/twentyhq/twenty/issues/16900
const isPrivateUrl = (url: string): boolean => {
try {
const { hostname } = new URL(url);
diff --git a/packages/twenty-front/src/modules/activities/hooks/useActivityTargetsForTargetableObjects.ts b/packages/twenty-front/src/modules/activities/hooks/useActivityTargetsForTargetableObjects.ts
index 6162e9bdf62..0de04748482 100644
--- a/packages/twenty-front/src/modules/activities/hooks/useActivityTargetsForTargetableObjects.ts
+++ b/packages/twenty-front/src/modules/activities/hooks/useActivityTargetsForTargetableObjects.ts
@@ -55,9 +55,7 @@ export const useActivityTargetsForTargetableObjects = ({
objectMetadataItems,
});
- // TODO: We want to optimistically remove from this request
- // If we are on a show page and we remove the current show page object corresponding activity target
- // See also if we need to update useTimelineActivities
+ // TODO: optimistically remove the current show page's activity target here (and in useTimelineActivities).
const {
records: activityTargets,
loading: loadingActivityTargets,
diff --git a/packages/twenty-front/src/modules/activities/hooks/useCreateActivityForTargetRecord.ts b/packages/twenty-front/src/modules/activities/hooks/useCreateActivityForTargetRecord.ts
index deb9d13da46..063f298ee40 100644
--- a/packages/twenty-front/src/modules/activities/hooks/useCreateActivityForTargetRecord.ts
+++ b/packages/twenty-front/src/modules/activities/hooks/useCreateActivityForTargetRecord.ts
@@ -12,9 +12,7 @@ type UseCreateActivityForTargetRecordParams = {
| CoreObjectNameSingular.Task;
};
-// Creating an activity attaches it to the target record, so it requires
-// update permission on the target object, not just create permission on the
-// activity object.
+// Attaching to the target needs update permission on its object, not just create on the activity.
export const useCreateActivityForTargetRecord = ({
targetRecord,
activityObjectNameSingular,
diff --git a/packages/twenty-front/src/modules/activities/timeline-activities/constants/TimelineIconSlotSize.ts b/packages/twenty-front/src/modules/activities/timeline-activities/constants/TimelineIconSlotSize.ts
index 82dcac041b9..c739ea5050d 100644
--- a/packages/twenty-front/src/modules/activities/timeline-activities/constants/TimelineIconSlotSize.ts
+++ b/packages/twenty-front/src/modules/activities/timeline-activities/constants/TimelineIconSlotSize.ts
@@ -1,2 +1 @@
-// One shared value is what keeps icon, rail and row text on the same center.
export const TIMELINE_ICON_SLOT_SIZE = 26;
diff --git a/packages/twenty-front/src/modules/activities/timeline-activities/states/timelineActivityTypeUniversalIdentifiersFilterFamilyState.ts b/packages/twenty-front/src/modules/activities/timeline-activities/states/timelineActivityTypeUniversalIdentifiersFilterFamilyState.ts
index e7476280668..1c16644fec7 100644
--- a/packages/twenty-front/src/modules/activities/timeline-activities/states/timelineActivityTypeUniversalIdentifiersFilterFamilyState.ts
+++ b/packages/twenty-front/src/modules/activities/timeline-activities/states/timelineActivityTypeUniversalIdentifiersFilterFamilyState.ts
@@ -1,6 +1,5 @@
import { createAtomFamilyState } from '@/ui/utilities/state/jotai/utils/createAtomFamilyState';
-// Keyed by target record id so each record's timeline keeps its own selection.
// An empty selection means no filter rather than nothing to show.
export const timelineActivityTypeUniversalIdentifiersFilterFamilyState =
createAtomFamilyState<string[], string>({
diff --git a/packages/twenty-front/src/modules/activities/timeline-activities/utils/getTimelineActivityRecordGqlFields.ts b/packages/twenty-front/src/modules/activities/timeline-activities/utils/getTimelineActivityRecordGqlFields.ts
index c367420c04e..e61a2d4951c 100644
--- a/packages/twenty-front/src/modules/activities/timeline-activities/utils/getTimelineActivityRecordGqlFields.ts
+++ b/packages/twenty-front/src/modules/activities/timeline-activities/utils/getTimelineActivityRecordGqlFields.ts
@@ -8,9 +8,8 @@ type GetTimelineActivityRecordGqlFieldsParams = Pick<
'objectMetadataItems' | 'fields'
>;
-// Cached linked labels are captured before record permissions are applied, so
-// only the authorized live record identifier may reach the native renderer.
-// Morph targets are resolved separately because each target has its own query.
+// Cached linked labels predate permission checks, so only the authorized live record identifier may render.
+// Morph relations are skipped because each morph target is resolved by its own query.
export const getTimelineActivityRecordGqlFields = ({
objectMetadataItems,
fields,
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx b/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
index d6b765637ea..5cb15f218d2 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
+++ b/packages/twenty-front/src/modules/advanced-text-editor/components/FormAdvancedTextFieldInput.tsx
@@ -31,8 +31,7 @@ const StyledAdvancedTextFieldContainerWrapper = styled.div<{
flex-grow: ${({ hasFieldChrome }) => (hasFieldChrome ? 0 : 1)};
min-height: ${({ hasFieldChrome }) => (hasFieldChrome ? 'auto' : '0')};
- /* Document editors stretch to their available height; field editors keep
- their intrinsic height so they compose naturally inside forms. */
+ /* Field editors keep their intrinsic height inside forms; document editors stretch. */
& > * {
flex-grow: ${({ hasFieldChrome }) => (hasFieldChrome ? 0 : 1)};
min-height: ${({ hasFieldChrome }) => (hasFieldChrome ? 'auto' : '0')};
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useLiveEditorState.ts b/packages/twenty-front/src/modules/advanced-text-editor/hooks/useLiveEditorState.ts
index 4dd0d6790f9..cf38a7851f1 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/hooks/useLiveEditorState.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/hooks/useLiveEditorState.ts
@@ -1,12 +1,8 @@
import { type Editor } from '@tiptap/core';
import { useEditorState } from '@tiptap/react';
-// `useEditorState` caches its snapshot until the next transaction: a selector
-// reading the snapshot editor still gets the previous instance after
-// `useEditor` recreated the editor on a dependency change, and that instance is
-// destroyed, so it has dropped its extension and command managers. Selecting
-// from the instance the caller holds keeps the selection on the live editor.
-// Drop this hook once https://github.com/ueberdosis/tiptap/issues/7346 ships.
+// useEditorState's snapshot can hold an editor `useEditor` already destroyed; select from the caller's instance.
+// TODO: drop this hook once https://github.com/ueberdosis/tiptap/issues/7346 ships.
export const useLiveEditorState = <TSelectorResult>(
editor: Editor,
select: (editor: Editor) => TSelectorResult,
diff --git a/packages/twenty-front/src/modules/advanced-text-editor/utils/hasEditorExtension.ts b/packages/twenty-front/src/modules/advanced-text-editor/utils/hasEditorExtension.ts
index 37cdaabec9f..1b92bbd800c 100644
--- a/packages/twenty-front/src/modules/advanced-text-editor/utils/hasEditorExtension.ts
+++ b/packages/twenty-front/src/modules/advanced-text-editor/utils/hasEditorExtension.ts
@@ -1,9 +1,7 @@
import { type Editor } from '@tiptap/core';
import { isDefined } from 'twenty-shared/utils';
-// A destroyed editor drops its extension manager, and components can still hold
-// a destroyed instance for a render, either from a state that has not been
-// updated yet or from a stale tiptap snapshot.
+// A destroyed editor drops its extension manager, and components can still hold one for a render.
export const hasEditorExtension = (editor: Editor, extensionName: string) =>
isDefined(editor.extensionManager) &&
editor.extensionManager.extensions.some(
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
index eafbcca9950..74542abb737 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
@@ -39,8 +39,7 @@ const AGENT_CHAT_THREADS_REFRESH_RETRY_DELAY_MS = 3000;
export const AgentChatThreadInitializationEffect = () => {
const { refreshAgentChatThreads } = useRefreshAgentChatThreads();
const hasAiPermission = useHasPermissionFlag(PermissionFlagType.AI);
- // Chats are read through the record API, whose query is built from the
- // chat object's fields
+ // The record API builds chat queries from the chat object's fields.
const areFieldMetadataItemsLoaded =
useAtomFamilySelectorValue(
metadataStoreStatusFamilySelector,
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
index 2610bf3236e..d792929baae 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx
@@ -45,8 +45,7 @@ export const AgentChatThreadRecordOperationsEffect = () => {
const store = useStore();
const isEnabled = isDefined(chatObjectMetadataItem);
- // The removal check looks the current chat up itself, so it runs even when
- // the reload could not settle
+ // The removal check looks the chat up itself, so it runs even if the reload fails.
const reloadAgentChatThreads = useCallback(async () => {
await refreshAgentChatThreads();
await leaveRemovedAiChatThread();
@@ -74,8 +73,7 @@ export const AgentChatThreadRecordOperationsEffect = () => {
const createdThread =
operation.createdRecord as AgentChatThreadRecord;
- // A workflow run's conversation is announced to whoever reads the
- // run, but it is listed with the run, not in the chat list
+ // Workflow run conversations are listed with the run, not in the chat list.
if (!isDefined(createdThread.workflowRunId)) {
addAgentChatThread(createdThread);
}
@@ -90,8 +88,7 @@ export const AgentChatThreadRecordOperationsEffect = () => {
applyUpdates(updateInputs.map(toThreadUpdate));
- // A chat past the loaded pages moves to the top once updated, and
- // reloading keeps workflow run conversations out of the list
+ // An updated chat past the loaded pages moves to the top; reloading keeps workflow run chats out.
const listedThreadIds =
store.get(agentChatThreadListState.atom)?.threadIds ?? [];
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
index 65c516d58ef..cec3fa2e24a 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
@@ -111,8 +111,6 @@ const StyledMessageListPlaceholder = styled.div`
flex-direction: column;
`;
-// Collapsing this spacer is what slides the composer from the middle of an
-// empty page down to the bottom once the conversation starts.
const StyledComposerBottomSpacer = styled.div`
flex-basis: 0;
flex-grow: 0;
@@ -123,8 +121,7 @@ const StyledComposerBottomSpacer = styled.div`
transition-property: flex-grow;
transition-timing-function: ease-out;
- // Only the collapse is animated: the composer becomes centered again on a
- // thread switch, where sliding it back up would trail the content change.
+ // Only the collapse animates: re-centering on a thread switch would trail the content change.
&.is-centered {
flex-grow: 1;
transition-property: none;
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx
index 773441f0bc5..a54c292dcd7 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx
@@ -99,8 +99,7 @@ export const AiChatEmailApprovalCard = ({
const [bcc, setBcc] = useState(() =>
parseEmailRecipients(email.recipients.bcc),
);
- // Shown from the start when the draft has any, and kept once opened, so
- // removing the last recipient does not take the field away.
+ // Kept once shown, so removing the last recipient doesn't hide the field.
const [isCcShown, setIsCcShown] = useState(cc.length > 0);
const [isBccShown, setIsBccShown] = useState(bcc.length > 0);
const [subject, setSubject] = useState(email.subject);
@@ -110,9 +109,7 @@ export const AiChatEmailApprovalCard = ({
const isAnswering = pendingDecision !== null;
- // Typing in the card must not trigger the page's keyboard shortcuts. Focus
- // events bubble up from every field, and from the buttons between them,
- // which are left out since a button removed on click may never blur.
+ // Blocks page shortcuts while typing; buttons are excluded since one removed on click may never blur.
const handleFieldFocus = (event: FocusEvent) => {
if (
!(event.target instanceof HTMLInputElement) &&
@@ -153,8 +150,7 @@ export const AiChatEmailApprovalCard = ({
const isAnswered = await answerAgentChatToolCall({
toolCallId,
response,
- // Only a discard is known before the server answers: sending or saving
- // can still fail.
+ // Only a discard is certain before the server answers: sending or saving can still fail.
optimisticToolOutput:
decision === 'discard'
? {
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx
index 48618d402b7..9bda5688702 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatErrorRenderer.tsx
@@ -16,8 +16,7 @@ export const AiChatErrorRenderer = ({
error,
onRetry,
}: AiChatErrorRendererProps) => {
- // Handled by AIChatNoMoreBillingCreditsBanner, which useHasReachedAiChatCreditsCap
- // keeps mounted for exactly this error so nothing is swallowed here
+ // Rendered by AIChatNoMoreBillingCreditsBanner, which stays mounted for this error.
if (isAiChatCreditsExhaustedError(error)) {
return null;
}
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx
index ada593a7897..88de990662e 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx
@@ -50,8 +50,7 @@ const StyledMessageText = styled.div<{ isUser?: boolean }>`
isUser ? `0 ${themeCssVariables.spacing[2]}` : '0'};
white-space: normal;
width: ${({ isUser }) => (isUser ? 'fit-content' : '100%')};
- /* Pre-wrap within the whole container turns every newline between block
- elements into extra spacing; keep normal flow and only pre-wrap code. */
+ /* Pre-wrap on the container turns newlines between blocks into spacing; only code pre-wraps. */
word-wrap: break-word;
code {
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
index 6f7af1881e2..88c59be220c 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
@@ -24,8 +24,7 @@ type AiChatPendingAskGateProps = {
children: ReactNode;
};
-// The agent continues once every call it paused on is answered, so the
-// cards come one at a time, oldest first, each taking the composer's place.
+// The agent resumes once every paused call is answered, so cards come one at a time, oldest first.
export const AiChatPendingAskGate = ({
children,
}: AiChatPendingAskGateProps) => {
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx
index cc78fbd8c9e..0766d193211 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx
@@ -56,8 +56,6 @@ const AiChatThreadCommandMenuItems = () => {
.map((item) => <CommandMenuItemRenderer item={item} key={item.id} />);
};
-// A conversation row offers the chat's record commands, next to the actions
-// that only make sense in a list
export const AiChatThreadActionsDropdown = ({
thread,
surface,
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx
index ab96232b864..1c233502ec1 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx
@@ -87,9 +87,7 @@ type AiChatThreadListItemProps = {
onDetach?: () => void;
};
-// The surface keys the row's dropdown state, so rows for one thread on two
-// surfaces do not share it. Every record page uses RECORD_PAGE, including one
-// open in the side panel, so two record pages on screen at once still do.
+// Keyed per surface; every record page uses RECORD_PAGE, so two record pages on screen share it.
export const AiChatThreadListItem = ({
thread,
surface = AI_CHAT_THREAD_ACTIONS_SURFACE.SIDE_PANEL,
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadRecordTargets.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadRecordTargets.tsx
index bd13e3aa239..efd3a8fc7bd 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadRecordTargets.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadRecordTargets.tsx
@@ -41,8 +41,6 @@ const StyledContainer = styled.div`
min-width: 0;
`;
-// Lets the list shrink in a narrow header, where it folds the chips that no
-// longer fit into a count.
const StyledRecordChips = styled.div`
min-width: 0;
`;
@@ -94,8 +92,7 @@ export const AiChatThreadRecordTargets = ({
skip: isThreadQuerySkipped,
});
- // The chat model files the conversation through its own tool on the server,
- // so its links are read again whenever one is written.
+ // The chat model links conversations through its own server tool, so links are reread on any write.
const linksOperationSignature = useMemo(
() => ({
objectNameSingular: CoreObjectNameSingular.AgentChatThreadTarget,
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatToolPartRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatToolPartRenderer.tsx
index 9a799d6ad09..ed50f94f712 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatToolPartRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatToolPartRenderer.tsx
@@ -30,8 +30,6 @@ export const AiChatToolPartRenderer = ({
const { message, recordReferences } = getToolRecordOutput(toolPart);
- // A record tool that matched nothing, or failed, has no records to show and
- // reads better as the step row it has always been.
if (!isNonEmptyArray(recordReferences)) {
return <ToolStepRenderer toolPart={toolPart} isStreaming={isStreaming} />;
}
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatToolWidget.tsx b/packages/twenty-front/src/modules/ai/components/AiChatToolWidget.tsx
index 90869d24bd0..f5d5e37411f 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatToolWidget.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatToolWidget.tsx
@@ -33,9 +33,7 @@ export const AiChatToolWidget = ({
frontComponentId,
isStreaming,
}: AiChatToolWidgetProps) => {
- // A call dispatched through execute_tool carries the real tool and its
- // arguments inside the wrapper; the widget is the dispatched tool's, so it
- // gets that identity rather than the dispatcher's.
+ // execute_tool wraps the real tool, and the widget belongs to the dispatched one.
const { toolName, toolInput } = unwrapToolInput({
input: toolPart.input as ToolInput,
toolName: getToolName(toolPart),
diff --git a/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx b/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx
index fcd99ab5798..58d66b4e48e 100644
--- a/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiModelTierDropdown.tsx
@@ -37,8 +37,7 @@ export const AiModelTierDropdown = ({
const [agentChatUserSelectedModelTier, setAgentChatUserSelectedModelTier] =
useAtomState(agentChatUserSelectedModelTierState);
- // The setup chat runs on the fast tier server-side whatever the workspace
- // setting says, so the control shows what will actually answer.
+ // The setup chat always runs on the fast tier server-side.
const workspaceTier: AiModelTier = isWorkspaceSetupChat ? 'fast' : chatTier;
const selectedTier = agentChatUserSelectedModelTier ?? workspaceTier;
diff --git a/packages/twenty-front/src/modules/ai/components/AiModelTierSlider.tsx b/packages/twenty-front/src/modules/ai/components/AiModelTierSlider.tsx
index e782daf82d2..840b0a3fe01 100644
--- a/packages/twenty-front/src/modules/ai/components/AiModelTierSlider.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiModelTierSlider.tsx
@@ -53,8 +53,7 @@ const StyledTrack = styled.div<{ disabled: boolean }>`
}
`;
-// The handle centre sits on a dot, so the fill runs from the track inset to
-// half a handle past that dot.
+// The handle centre sits on a dot, so the fill runs half a handle past it.
const StyledFill = styled.div`
background: ${themeCssVariables.color.blue};
border-radius: ${themeCssVariables.border.radius.sm};
diff --git a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx
index a7b3111e9eb..4433fc4d045 100644
--- a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx
@@ -29,8 +29,7 @@ export const MarkdownLoadingSkeleton = () => {
);
};
-// Protecting per block behind the memo means only the streaming tail blocks
-// pay the reference-parsing cost on each flush; settled blocks never re-run it.
+// Memoized per block so only the streaming tail re-parses references on each flush.
const MemoizedMarkdownBlock = memo(
({ blockText, noImage }: { blockText: string; noImage?: boolean }) => (
<MarkdownRenderer noImage={noImage}>
@@ -48,8 +47,7 @@ export const LazyMarkdownContent = ({
text,
noImage,
}: LazyMarkdownContentProps) => {
- // Not state: the blocks are a pure function of `text`, the ref only caches
- // the previous split so streaming appends skip re-tokenizing settled blocks.
+ // Not state: only caches the previous split so streaming appends skip settled blocks.
// oxlint-disable-next-line twenty/no-state-useref
const blockSplitCacheRef = useRef(EMPTY_MARKDOWN_BLOCK_SPLIT_CACHE);
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/ToolRecordsWidget.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/ToolRecordsWidget.stories.tsx
index 318fdc39e33..19cc9b3d858 100644
--- a/packages/twenty-front/src/modules/ai/components/__stories__/ToolRecordsWidget.stories.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/ToolRecordsWidget.stories.tsx
@@ -106,8 +106,7 @@ export const ManyRecordsAreTruncated: Story = {
displayName: `Company ${index + 1}`,
})),
},
- // The overflow label is translated, and Storybook renders a pseudo locale,
- // so the count of rendered links is what can be asserted here.
+ // Storybook renders a pseudo locale, so assert the link count, not the translated label.
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx
index 86b9e061958..89ed464078a 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx
@@ -19,8 +19,7 @@ jest.mock('@/ai/hooks/useAiChatEditor', () => ({
jest.mock('@/ai/components/AiChatStandaloneError', () => ({
AiChatStandaloneError: () => null,
}));
-// The gate's cards pull in the form fields' rich text editor, which
-// Jest cannot load; this suite is about the composer, not the gate.
+// The gate's cards pull in a rich text editor Jest cannot load.
jest.mock('@/ai/components/AiChatPendingAskGate', () => ({
AiChatPendingAskGate: ({ children }: { children: ReactNode }) => children,
}));
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx
index 42043ca469c..08bbb180b5a 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx
@@ -51,7 +51,6 @@ describe('AiChatEmailApprovalCard', () => {
},
optimisticToolOutput: undefined,
});
- // Nothing else can be decided while the answer is on its way.
expect(
screen.getByRole('button', { name: 'Save as draft' }),
).toBeDisabled();
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadRecordTargets.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadRecordTargets.test.tsx
index 36b34e387b3..f4b8c1092a3 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadRecordTargets.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadRecordTargets.test.tsx
@@ -25,8 +25,7 @@ const GLOBEX_ID = '20202020-0000-4000-8000-000000000003';
const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');
const personObjectMetadataItem = getMockObjectMetadataItemOrThrow('person');
-// The generated test workspace has no conversation objects, so a person's
-// company relation stands in for the conversation link's company leg.
+// The test workspace has no conversation objects; person.company stands in for the company leg.
const companyTargetField = getMockFieldMetadataItemOrThrow({
objectMetadataItem: personObjectMetadataItem,
fieldName: 'company',
@@ -78,8 +77,7 @@ jest.mock(
}),
);
-// Opening the picker searches records over the network, which MockedProvider
-// cannot answer, so the picker's own list is replaced by the choice it offers.
+// MockedProvider can't answer the picker's network search.
jest.mock(
'@/object-record/record-picker/multiple-record-picker/hooks/useMultipleRecordPickerPerformSearch',
() => ({
@@ -192,7 +190,6 @@ const renderRecordTargets = ({
{ wrapper: Wrapper },
);
- // The header renders once the workspace metadata is loaded.
return screen.findByRole('heading', { name: 'Pricing questions' });
};
@@ -246,8 +243,6 @@ describe('AiChatThreadRecordTargets', () => {
expect(attachChatThreadToRecord).not.toHaveBeenCalled();
});
- // A custom object leg carries no unique index, so a record can be linked
- // more than once, and unlinking it removes every link.
it('unlinks every link between the conversation and the record', async () => {
const user = userEvent.setup();
mockThread.current = buildThread({
@@ -298,7 +293,6 @@ describe('AiChatThreadRecordTargets', () => {
).not.toBeInTheDocument();
});
- // The chat model files the conversation through its own tool.
it('reads the links again when one is written elsewhere', async () => {
await renderRecordTargets();
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx
index 1a959ea2feb..9e1b174704a 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChip.test.tsx
@@ -59,7 +59,6 @@ const ALL_PERMISSION_FLAGS = [
PermissionFlagType.AI_SETTINGS,
];
-// The skill chip reads its icon from the skill catalog
const skillsApolloMock = {
request: { query: FindManySkillsForSuggestionDocument },
result: {
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx
index 6c0823994cd..c3947c7c78a 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx
@@ -17,9 +17,7 @@ export const AiChatEditorFocusEffect = ({
);
useLayoutEffect(() => {
- // An editor destroyed while its replacement mounts is still defined here,
- // and reading its commands throws. Leaving the request set hands the focus
- // to the live editor instead.
+ // A destroyed editor is still defined while its replacement mounts and its commands throw; keeping the request hands focus to the live one.
if (!shouldFocusChatEditor || !isDefined(editor) || editor.isDestroyed) {
return;
}
diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/contextual-suggested-prompts.ts b/packages/twenty-front/src/modules/ai/components/suggested-prompts/contextual-suggested-prompts.ts
index b621c745c8b..908a9ae8846 100644
--- a/packages/twenty-front/src/modules/ai/components/suggested-prompts/contextual-suggested-prompts.ts
+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/contextual-suggested-prompts.ts
@@ -59,8 +59,7 @@ export const RECORD_PAGE_SUGGESTED_PROMPTS: SuggestedPrompt[] = [
},
];
-// Only objects whose record page deserves its own wording need an entry: everything
-// else, custom objects included, falls back to RECORD_PAGE_SUGGESTED_PROMPTS.
+// Objects without an entry, custom ones included, fall back to RECORD_PAGE_SUGGESTED_PROMPTS.
export const RECORD_PAGE_SUGGESTED_PROMPTS_BY_OBJECT_NAME_SINGULAR: Record<
string,
SuggestedPrompt[]
diff --git a/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
index 45c639bc369..7b56ada19dc 100644
--- a/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
+++ b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
@@ -4,7 +4,6 @@ import {
REQUEST_FORM_TOOL_NAME,
} from 'twenty-shared/ai';
-// Tools whose call waits on a person, each rendered with its own status.
export const PAUSING_TOOL_NAMES: ReadonlySet<string> = new Set([
ASK_QUESTIONS_TOOL_NAME,
PROPOSE_EMAIL_TOOL_NAME,
diff --git a/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationEffect.tsx b/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationEffect.tsx
index 83caf603045..3c8614bea97 100644
--- a/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationEffect.tsx
@@ -46,9 +46,7 @@ export const AiChatDictationEffect = ({
const createdEngine = createWebSpeechDictationEngine({
isIOS,
- // Read from the store rather than subscribed to, so a language change
- // neither re-renders this nor rebuilds the engine; the next session
- // picks it up.
+ // Read imperatively so a language change doesn't rebuild the engine; the next session picks it up.
getLanguage: () =>
getDictationLanguage(
store.get(currentWorkspaceMemberState.atom)?.locale,
@@ -63,8 +61,7 @@ export const AiChatDictationEffect = ({
};
}, [isSupported, isIOS, store, setDictationEngine]);
- // Separate from construction so fresh handler identities re-subscribe instead
- // of tearing down a live recording.
+ // Separate so fresh handler identities re-subscribe without tearing down a live recording.
useEffect(() => {
if (!isDefined(dictationEngine)) {
return;
@@ -80,16 +77,12 @@ export const AiChatDictationEffect = ({
break;
case 'state':
setIsDictationRecording(event.state === 'recording');
- // The session took its pending words with it, settled or not.
if (event.state === 'idle') {
onInterimText('');
}
break;
case 'error':
- // Remembered only where a silent engine stays silent. A desktop
- // browser that missed one start — a cold speech service, a blip
- // reaching it — would otherwise lose the button for the life of the
- // origin, with clearing site data the only way back.
+ // iOS only: elsewhere one missed start (cold speech service) would hide the button for the origin's life.
if (event.reason === 'engine-silent' && isIOS) {
setHasWebSpeechProvenSilent(true);
}
@@ -110,8 +103,7 @@ export const AiChatDictationEffect = ({
enqueueToast,
]);
- // Both send paths dispatch this, so dictation does not have to be lifted into
- // the composer to be stopped by one.
+ // Both send paths dispatch this, so dictation needn't be lifted into the composer.
const handleSendMessage = useCallback(() => {
dictationEngine?.cancel();
}, [dictationEngine]);
diff --git a/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationHint.tsx b/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationHint.tsx
index b21bbe5639f..4e5010ca8f3 100644
--- a/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationHint.tsx
+++ b/packages/twenty-front/src/modules/ai/dictation/components/AiChatDictationHint.tsx
@@ -22,7 +22,5 @@ export const AiChatDictationHint = ({
return null;
}
- // Announced politely so a screen-reader user hears the recognition working
- // without it interrupting whatever they are reading.
return <StyledHint aria-live="polite">{interimText}</StyledHint>;
};
diff --git a/packages/twenty-front/src/modules/ai/dictation/constants/DictationLivenessTimeoutInMs.ts b/packages/twenty-front/src/modules/ai/dictation/constants/DictationLivenessTimeoutInMs.ts
index 398ad716234..b1aaf31e4d0 100644
--- a/packages/twenty-front/src/modules/ai/dictation/constants/DictationLivenessTimeoutInMs.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/constants/DictationLivenessTimeoutInMs.ts
@@ -1,4 +1,2 @@
-// Long enough that a slow engine start is not mistaken for a dead one, short
-// enough that a user on a surface where the API never emits is not left
-// talking to nothing.
+// Tolerates a slow engine start without leaving the user talking to a dead one.
export const DICTATION_LIVENESS_TIMEOUT_IN_MS = 2500;
diff --git a/packages/twenty-front/src/modules/ai/dictation/engines/__tests__/dictationEngineLifecycle.test.ts b/packages/twenty-front/src/modules/ai/dictation/engines/__tests__/dictationEngineLifecycle.test.ts
index ad843a74003..1bfd9f12cf8 100644
--- a/packages/twenty-front/src/modules/ai/dictation/engines/__tests__/dictationEngineLifecycle.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/engines/__tests__/dictationEngineLifecycle.test.ts
@@ -4,8 +4,7 @@ import { type WebSpeechRecognitionConstructor } from '@/ai/dictation/types/WebSp
import { type WebSpeechRecognitionEvent } from '@/ai/dictation/types/WebSpeechRecognitionEvent';
import { type WebSpeechRecognitionInstance } from '@/ai/dictation/types/WebSpeechRecognitionInstance';
-// endSession is the test's stand-in for the recognizer reporting it finished,
-// which is the only thing that releases the started slot below.
+// endSession stands in for the recognizer reporting it finished, the only thing releasing the started slot.
type FakeRecognition = WebSpeechRecognitionInstance & {
start: jest.Mock;
stop: jest.Mock;
@@ -42,9 +41,7 @@ const mockGetUserMedia = (implementation: () => Promise<MediaStream>) => {
});
};
-// Models the spec's [[started]] slot, so a test cannot assert a sequence a real
-// recognizer would refuse: start() throws while the previous session is still
-// started, and only the end event releases it.
+// Models the spec's [[started]] slot: start() throws until the end event releases it.
const stubSpeechRecognition = () => {
const instances: FakeRecognition[] = [];
@@ -121,8 +118,6 @@ describe('createWebSpeechDictationEngine', () => {
delete (window as SpeechRecognitionTestWindow).SpeechRecognition;
});
- // getUserMedia resolves whenever the user answers the permission prompt, which
- // can be long after the caller gave up. The engine has to notice.
it('does not start recognition when stopped during the microphone warm-up', async () => {
const deferred = createDeferred<MediaStream>();
const { stream } = createFakeStream();
@@ -164,8 +159,6 @@ describe('createWebSpeechDictationEngine', () => {
expect(instances[0]?.start).toHaveBeenCalledTimes(1);
});
- // A result that settles an utterance carries no interim for it, so without an
- // explicit clear the hint keeps showing words already inserted below it.
it('clears the interim hint when an utterance settles', async () => {
const engine = createTestEngine();
const events = collectEvents(engine);
@@ -180,8 +173,6 @@ describe('createWebSpeechDictationEngine', () => {
expect(events).toContainEqual({ type: 'interim', text: '' });
});
- // Sending takes the composer's content with it, so a half-heard utterance
- // belongs to neither the sent message nor the next draft.
it('discards in-flight audio on cancel without delivering a result', async () => {
const engine = createTestEngine();
@@ -191,8 +182,6 @@ describe('createWebSpeechDictationEngine', () => {
expect(instances[0]?.abort).toHaveBeenCalledTimes(1);
});
- // Re-instantiating per press is what produces the iOS system chime and the
- // first-attempt failures, so a recognizer that finished is used again.
it('reuses the recognizer once it has reported the session ended', async () => {
const engine = createTestEngine({ isIOS: true });
@@ -206,8 +195,7 @@ describe('createWebSpeechDictationEngine', () => {
expect(instances[0]?.start).toHaveBeenCalledTimes(2);
});
- // iOS can end a session without firing onend, and a recognizer that never
- // reported its end throws InvalidStateError on the next start().
+ // iOS can end a session without onend, and such a recognizer throws InvalidStateError on start().
it('replaces a recognizer that never reported the session ended', async () => {
const engine = createTestEngine({ isIOS: true });
const events = collectEvents(engine);
@@ -226,8 +214,6 @@ describe('createWebSpeechDictationEngine', () => {
});
});
- // The caller only starts again from 'idle', so a state left at 'recording'
- // wedges the button into offering to stop a session that is already over.
it.each(['stop', 'cancel'] as const)(
'reports idle on %s even when onend never fires',
async (method) => {
@@ -241,8 +227,6 @@ describe('createWebSpeechDictationEngine', () => {
},
);
- // The listener must not outlive its session: onend is what normally removes
- // it, and iOS can end a session without firing onend.
it.each(['stop', 'cancel'] as const)(
'removes the visibility listener on %s even when onend never fires',
async (method) => {
@@ -259,8 +243,6 @@ describe('createWebSpeechDictationEngine', () => {
},
);
- // A session ends once. onend arriving after an explicit stop must not report
- // a second one, or a caller counting session ends sees two per session.
it('reports idle once when stop is followed by onend', async () => {
const engine = createTestEngine();
const events = collectEvents(engine);
@@ -274,8 +256,6 @@ describe('createWebSpeechDictationEngine', () => {
);
});
- // Every message send cancels, dictating or not, so cancelling an idle engine
- // is the common case rather than an edge one.
it('does nothing when cancelling an engine that is not dictating', () => {
const engine = createTestEngine();
const events = collectEvents(engine);
@@ -286,9 +266,6 @@ describe('createWebSpeechDictationEngine', () => {
expect(events).toEqual([]);
});
- // stop() clears the session eagerly but the recognizer can still be settling.
- // A send in that window must abort it, or its last final result is inserted
- // into the composer the send just cleared.
it('still aborts a settling recognizer when cancelled after stop', async () => {
const engine = createTestEngine();
@@ -311,9 +288,6 @@ describe('createWebSpeechDictationEngine', () => {
expect(readStates(events).at(-1)).toBe('idle');
});
- // The API reads lang at start(), so a speaker who changes their language mid
- // session keeps that session and gets the new one on their next press —
- // rebuilding the engine to apply it would abort what they are saying.
it('reads the language at the start of each session', async () => {
const languages = ['en-US', 'fr-FR'];
const engine = createTestEngine({
@@ -333,8 +307,6 @@ describe('createWebSpeechDictationEngine', () => {
expect(instances[0]?.lang).toBe('fr-FR');
});
- // The end event of a session that is already over must not abandon a press
- // that is still warming up its microphone, or that press is silently lost.
it('keeps a start warming up when a previous session finally reports its end', async () => {
const engine = createTestEngine();
diff --git a/packages/twenty-front/src/modules/ai/dictation/engines/createWebSpeechDictationEngine.ts b/packages/twenty-front/src/modules/ai/dictation/engines/createWebSpeechDictationEngine.ts
index 28e424e5349..759fd795e48 100644
--- a/packages/twenty-front/src/modules/ai/dictation/engines/createWebSpeechDictationEngine.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/engines/createWebSpeechDictationEngine.ts
@@ -42,16 +42,12 @@ export const createWebSpeechDictationEngine = ({
}): DictationEngine => {
const emitter = createDictationEventEmitter();
- // Reused for the engine's lifetime: re-instantiating per press produces the
- // iOS system chime and the first-attempt failures.
+ // Reused: re-instantiating per press causes the iOS system chime and first-attempt failures.
let recognition: WebSpeechRecognitionInstance | null = null;
let isActive = false;
- // The recognizer's own started flag outlives the session the UI sees: stop()
- // and abort() only release it when the recognizer reports the session ended,
- // and start() throws InvalidStateError until then.
+ // start() throws InvalidStateError until the recognizer reports its session ended, even after stop().
let isRecognizerRunning = false;
- // A stop issued during the microphone warm-up has nothing to stop yet, so the
- // generation is what lets the resumed startup notice it was abandoned.
+ // Lets a startup resuming after the microphone warm-up notice a stop issued meanwhile.
let sessionGeneration = 0;
const watchdog = createLivenessWatchdog({
@@ -75,14 +71,7 @@ export const createWebSpeechDictationEngine = ({
isRecognizerRunning = false;
};
- // Announces that the session is over and undoes what start() set up. Every
- // ending funnels through here so it cannot drift between callers and cannot
- // run twice, and onend is
- // deliberately not trusted to arrive — iOS can end a session without firing
- // it, and leaving any of this to it wedges dictation. A stuck isActive
- // refuses every later start, a state left at 'recording' leaves the button
- // offering to stop a session that is already over, and a listener outliving
- // its session calls back into a stopped engine.
+ // Every ending funnels here, without trusting onend: iOS can end a session without firing it.
const endSession = ({
evenWhenIdle = false,
}: { evenWhenIdle?: boolean } = {}) => {
@@ -97,13 +86,8 @@ export const createWebSpeechDictationEngine = ({
emitter.emit({ type: 'state', state: 'idle' });
};
- // Asked to end the session, rather than told it ended. The recognizer is told
- // even when the session already reads as over: stop() clears isActive eagerly
- // but the recognizer can still be settling and deliver one last final result,
- // so a cancel arriving in that window has to abort it — otherwise that text
- // lands in a composer the send just cleared. Ending a session that was never
- // told to stop (onend, onerror) must not bump the generation, or a recognizer
- // reporting a previous session would abandon the start already warming up.
+ // Tells the recognizer even when the session reads as over: after stop() it can still deliver a final result.
+ // onend/onerror call endSession directly: bumping the generation there would abandon a warming start.
const requestSessionEnd = (
recognitionAction: 'stop' | 'abort',
{ evenWhenIdle = false }: { evenWhenIdle?: boolean } = {},
@@ -138,8 +122,7 @@ export const createWebSpeechDictationEngine = ({
const instance = new SpeechRecognitionConstructor();
- // Continuous mode never releases the iOS microphone and never delivers a
- // result.
+ // Continuous mode never releases the iOS microphone and never delivers a result.
instance.continuous = !isIOS;
instance.interimResults = true;
@@ -156,9 +139,7 @@ export const createWebSpeechDictationEngine = ({
emitter.emit({ type: 'final', text: finalText });
}
- // Emitted even when empty: the result that settles an utterance carries
- // no interim for it, so the hint would keep showing words that are
- // already in the document.
+ // Emitted even when empty: the settling result carries no interim, so the hint would keep showing settled words.
emitter.emit({ type: 'interim', text: interimText });
};
@@ -169,11 +150,7 @@ export const createWebSpeechDictationEngine = ({
emitter.emit({ type: 'error', reason });
}
- // An error terminates the session — the spec fires end after it — but the
- // WebKit surfaces this engine is written around can skip that, and waiting
- // for it would leave the button offering to stop a session that is over.
- // isRecognizerRunning deliberately stays set: only onend proves the
- // recognizer released itself, so the next start replaces it instead.
+ // WebKit can skip the end the spec fires after an error; only onend clears isRecognizerRunning.
endSession();
};
@@ -185,8 +162,6 @@ export const createWebSpeechDictationEngine = ({
return instance;
};
- // A press that never reached the recognizer still has to return the button to
- // idle, and there is nothing yet to tear down when it does.
const abandonStartup = (reason?: DictationFailureReason) => {
if (isDefined(reason)) {
emitter.emit({ type: 'error', reason });
@@ -220,9 +195,7 @@ export const createWebSpeechDictationEngine = ({
return;
}
- // iOS only: a context created outside a user gesture is suspended there,
- // and a suspended one blocks the capture path recognition runs on.
- // Everywhere else it is a create/resume/close the press pays for nothing.
+ // iOS suspends contexts created outside a gesture, blocking recognition's capture path.
if (isIOS) {
await unlockAudioContext();
@@ -233,9 +206,6 @@ export const createWebSpeechDictationEngine = ({
}
}
- // A recognizer that never reported its session ended cannot be started
- // again, so a press inside that window gets a fresh one rather than an
- // InvalidStateError.
if (isRecognizerRunning) {
discardRecognition();
}
@@ -248,9 +218,7 @@ export const createWebSpeechDictationEngine = ({
return;
}
- // Read per session rather than per engine: the API takes lang at start(),
- // so a speaker who changes their language does not need the engine torn
- // down and rebuilt — and a session in flight is not aborted to apply it.
+ // Per session: the API reads lang at start(), so a language change needs no engine rebuild.
recognition.lang = getLanguage();
isActive = true;
@@ -271,16 +239,13 @@ export const createWebSpeechDictationEngine = ({
stop: stopRecognition,
- // A send takes the composer's content with it, so a half-heard utterance
- // belongs to neither the sent message nor the next draft. abort() ends the
- // session without delivering a result, unlike stop().
+ // abort(), unlike stop(), delivers no result, so a half-heard utterance can't land in the draft after a send.
cancel: () => {
requestSessionEnd('abort');
},
dispose: () => {
- // evenWhenIdle because disposal has to release the recognizer and let a
- // caller holding interim text clear it whether or not a session was live.
+ // Disposal must release the recognizer and clear interim text whether or not a session was live.
requestSessionEnd('abort', { evenWhenIdle: true });
discardRecognition();
emitter.clear();
diff --git a/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useDictationAvailability.test.tsx b/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useDictationAvailability.test.tsx
index de71992a64a..6ff46a6c6f2 100644
--- a/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useDictationAvailability.test.tsx
+++ b/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useDictationAvailability.test.tsx
@@ -20,9 +20,7 @@ describe('useDictationAvailability', () => {
beforeEach(() => {
localStorage.clear();
getDefaultStore().set(hasWebSpeechProvenSilentState.atom, false);
- // SpeechRecognition is absent from the DOM lib because it never became a
- // standard, so the global is reached through the same structural type the
- // engine declares.
+ // SpeechRecognition isn't in the DOM lib, so reach it through the engine's structural type.
(window as unknown as SpeechRecognitionTestWindow).SpeechRecognition =
function SpeechRecognition() {} as unknown as WebSpeechRecognitionConstructor;
Object.defineProperty(navigator, 'mediaDevices', {
@@ -53,8 +51,6 @@ describe('useDictationAvailability', () => {
expect(result.current.isAvailable).toBe(false);
});
- // Offering the same dead button again only costs the user another recording,
- // and waiting for a remount to hide it costs one more.
it('withdraws dictation the moment the engine proves itself silent', () => {
const { result } = renderAvailability();
diff --git a/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useInsertDictatedText.test.ts b/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useInsertDictatedText.test.ts
index a70294e544f..9c0400b2826 100644
--- a/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useInsertDictatedText.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/hooks/__tests__/useInsertDictatedText.test.ts
@@ -15,8 +15,7 @@ describe('useInsertDictatedText', () => {
let editor: Editor;
beforeEach(() => {
- // The composer's schema carries marks, which is what makes a bare string
- // insertion parse as HTML rather than land literally.
+ // Marks in the schema are what make a bare string insertion parse as HTML.
editor = new Editor({
extensions: [Document, Paragraph, Text, Bold, Italic],
content: '<p></p>',
diff --git a/packages/twenty-front/src/modules/ai/dictation/hooks/useDictation.ts b/packages/twenty-front/src/modules/ai/dictation/hooks/useDictation.ts
index eaeb57a4331..5e688da451d 100644
--- a/packages/twenty-front/src/modules/ai/dictation/hooks/useDictation.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/hooks/useDictation.ts
@@ -5,8 +5,7 @@ import { dictationEngineState } from '@/ai/dictation/states/dictationEngineState
import { isDictationRecordingState } from '@/ai/dictation/states/isDictationRecordingState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-// The engine's lifecycle belongs to AiChatDictationEffect; this only reads what
-// it published and drives it.
+// AiChatDictationEffect owns the engine lifecycle.
export const useDictation = () => {
const dictationEngine = useAtomStateValue(dictationEngineState);
const isDictationRecording = useAtomStateValue(isDictationRecordingState);
diff --git a/packages/twenty-front/src/modules/ai/dictation/hooks/useDictationAvailability.ts b/packages/twenty-front/src/modules/ai/dictation/hooks/useDictationAvailability.ts
index 6e96b7d372b..b8b19299896 100644
--- a/packages/twenty-front/src/modules/ai/dictation/hooks/useDictationAvailability.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/hooks/useDictationAvailability.ts
@@ -10,8 +10,6 @@ export const useDictationAvailability = (): boolean => {
hasWebSpeechProvenSilentState,
);
- // Every field the surface reports is fixed for the life of the page; the
- // remembered failure is the only part of availability that moves.
const isSurfaceCapable = useMemo(
() => resolveDictationAvailability(readDictationSurface()),
[],
diff --git a/packages/twenty-front/src/modules/ai/dictation/hooks/useInsertDictatedText.ts b/packages/twenty-front/src/modules/ai/dictation/hooks/useInsertDictatedText.ts
index 4020d548d41..8c3df459732 100644
--- a/packages/twenty-front/src/modules/ai/dictation/hooks/useInsertDictatedText.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/hooks/useInsertDictatedText.ts
@@ -3,10 +3,7 @@ import { type Editor } from '@tiptap/react';
import { useCallback } from 'react';
import { isDefined } from 'twenty-shared/utils';
-// Only settled text is written to the document. Interim results are shown
-// beside the composer instead, because tracking a replaceable range inside
-// ProseMirror breaks as soon as the user edits while dictating — and they do,
-// since the composer stays focused throughout.
+// Interim results stay outside the document: a replaceable range breaks when the user edits while dictating.
export const useInsertDictatedText = (editor: Editor | null) =>
useCallback(
(text: string) => {
@@ -15,9 +12,6 @@ export const useInsertDictatedText = (editor: Editor | null) =>
}
const { from } = editor.state.selection;
- // A bare string is parsed as HTML against the editor's schema, so a
- // transcript containing "<b>" loses the tag and gains a mark. A text node
- // writes what was actually said.
const precedingCharacter = editor.state.doc.textBetween(
Math.max(from - 1, 0),
from,
@@ -26,6 +20,7 @@ export const useInsertDictatedText = (editor: Editor | null) =>
const needsSeparator =
isNonEmptyString(precedingCharacter) && !/\s/.test(precedingCharacter);
+ // A text node, not a string: a string parses as HTML, so "<b>" would become a mark.
editor
.chain()
.focus()
diff --git a/packages/twenty-front/src/modules/ai/dictation/states/dictationEngineState.ts b/packages/twenty-front/src/modules/ai/dictation/states/dictationEngineState.ts
index 30e50d5d6bf..c57f615e699 100644
--- a/packages/twenty-front/src/modules/ai/dictation/states/dictationEngineState.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/states/dictationEngineState.ts
@@ -1,8 +1,7 @@
import { type DictationEngine } from '@/ai/dictation/types/DictationEngine';
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-// Only set while a surface can dictate, so its presence is what the control
-// reads to decide whether to render at all.
+// Only set while the surface can dictate; the control renders on its presence.
export const dictationEngineState = createAtomState<DictationEngine | null>({
key: 'ai/dictationEngine',
defaultValue: null,
diff --git a/packages/twenty-front/src/modules/ai/dictation/states/hasWebSpeechProvenSilentState.ts b/packages/twenty-front/src/modules/ai/dictation/states/hasWebSpeechProvenSilentState.ts
index 24f0414af78..13b1aea1c06 100644
--- a/packages/twenty-front/src/modules/ai/dictation/states/hasWebSpeechProvenSilentState.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/states/hasWebSpeechProvenSilentState.ts
@@ -1,8 +1,6 @@
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-// Remembered per browser because a silent engine is a property of this WebView
-// rather than of the workspace or the user: once one has accepted start() and
-// then said nothing, offering the button again only costs another recording.
+// Per browser: a silent engine is a property of the WebView, not of the workspace or user.
export const hasWebSpeechProvenSilentState = createAtomState<boolean>({
key: 'ai/hasWebSpeechProvenSilent',
defaultValue: false,
diff --git a/packages/twenty-front/src/modules/ai/dictation/types/DictationFailureReason.ts b/packages/twenty-front/src/modules/ai/dictation/types/DictationFailureReason.ts
index 5612cce9bcc..13fe1e8799e 100644
--- a/packages/twenty-front/src/modules/ai/dictation/types/DictationFailureReason.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/types/DictationFailureReason.ts
@@ -2,8 +2,7 @@ export type DictationFailureReason =
| 'permission-denied'
| 'no-device'
| 'unsupported-surface'
- // iOS exposes webkitSpeechRecognition in contexts where it never emits, so
- // feature detection reports success while dictation does nothing.
+ // iOS exposes webkitSpeechRecognition where it never emits, so feature detection passes.
| 'engine-silent'
| 'network'
| 'engine-error';
diff --git a/packages/twenty-front/src/modules/ai/dictation/types/WebSpeechRecognitionInstance.ts b/packages/twenty-front/src/modules/ai/dictation/types/WebSpeechRecognitionInstance.ts
index 22011bad84a..711ac1edb4e 100644
--- a/packages/twenty-front/src/modules/ai/dictation/types/WebSpeechRecognitionInstance.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/types/WebSpeechRecognitionInstance.ts
@@ -1,8 +1,7 @@
import { type WebSpeechRecognitionErrorEvent } from '@/ai/dictation/types/WebSpeechRecognitionErrorEvent';
import { type WebSpeechRecognitionEvent } from '@/ai/dictation/types/WebSpeechRecognitionEvent';
-// The Web Speech API is not in TypeScript's DOM lib because it never became a
-// standard, so the parts this engine touches are declared structurally.
+// The Web Speech API isn't in TypeScript's DOM lib, so it's declared structurally.
export type WebSpeechRecognitionInstance = {
continuous: boolean;
interimResults: boolean;
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createDictationEventEmitter.test.ts b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createDictationEventEmitter.test.ts
index 0c6b184642b..4c84e4c6527 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createDictationEventEmitter.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createDictationEventEmitter.test.ts
@@ -26,8 +26,6 @@ describe('createDictationEventEmitter', () => {
expect(listener).not.toHaveBeenCalled();
});
- // A listener that tears itself down on its own event must not stop the ones
- // registered after it from being called for that same event.
it('still reaches later listeners when an earlier one unsubscribes mid-emit', () => {
const emitter = createDictationEventEmitter();
const later = jest.fn();
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createLivenessWatchdog.test.ts b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createLivenessWatchdog.test.ts
index c43ed157a93..0e66f15cf67 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createLivenessWatchdog.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/createLivenessWatchdog.test.ts
@@ -53,8 +53,6 @@ describe('createLivenessWatchdog', () => {
expect(onSilent).not.toHaveBeenCalled();
});
- // A second session must be judged on its own silence, not excused by the
- // activity of the one before it.
it('forgets activity from a previous session when re-armed', () => {
const onSilent = jest.fn();
const watchdog = createLivenessWatchdog({
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/getDictationLanguage.test.ts b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/getDictationLanguage.test.ts
index 2df2645e494..f6937683e45 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/getDictationLanguage.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/getDictationLanguage.test.ts
@@ -12,8 +12,6 @@ describe('getDictationLanguage', () => {
},
);
- // The pseudo locale is a translation-coverage tool, not a language anything
- // can be recognised in.
it('falls back to the source locale for the pseudo locale', () => {
expect(getDictationLanguage('pseudo-en')).toBe('en');
});
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/mapSpeechRecognitionError.test.ts b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/mapSpeechRecognitionError.test.ts
index 762b4b7074c..4a60dadd876 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/mapSpeechRecognitionError.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/mapSpeechRecognitionError.test.ts
@@ -11,8 +11,6 @@ describe('mapSpeechRecognitionError', () => {
expect(mapSpeechRecognitionError(error)).toBe(expected);
});
- // Both are ordinary endings rather than failures: one is the user pressing
- // stop, the other is a quiet room.
it.each(['aborted', 'no-speech'])('treats %s as a normal ending', (error) => {
expect(mapSpeechRecognitionError(error)).toBeUndefined();
});
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/resolveDictationAvailability.test.ts b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/resolveDictationAvailability.test.ts
index ef2ae53b140..0781594b8dc 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/resolveDictationAvailability.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/resolveDictationAvailability.test.ts
@@ -33,8 +33,6 @@ describe('resolveDictationAvailability', () => {
).toBe(false);
});
- // The Web Speech API is exposed in these iOS contexts but never emits, so
- // they are refused before a recording is spent proving it.
it('refuses an installed iOS app', () => {
expect(
resolveDictationAvailability({
@@ -64,8 +62,6 @@ describe('resolveDictationAvailability', () => {
).toBe(true);
});
- // The engine warms the microphone through getUserMedia before recognition, so
- // a WebView exposing SpeechRecognition without it fails on every press.
it('refuses a surface with no microphone capture support', () => {
expect(
resolveDictationAvailability({
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/unlockAudioContext.test.ts b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/unlockAudioContext.test.ts
index 2c31c73ef97..878d7868b94 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/unlockAudioContext.test.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/__tests__/unlockAudioContext.test.ts
@@ -39,9 +39,6 @@ describe('unlockAudioContext', () => {
expect(close).toHaveBeenCalledTimes(1);
});
- // A browser allows only a handful of live contexts, and resume() rejecting is
- // routine on the surface this exists for, so leaking one per press would
- // exhaust the pool the unlock depends on.
it('releases the context even when resuming it fails', async () => {
const { close } = stubAudioContext({ doesResumeReject: true });
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/createDictationEventEmitter.ts b/packages/twenty-front/src/modules/ai/dictation/utils/createDictationEventEmitter.ts
index c9d62d85c25..cd11a25c7ce 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/createDictationEventEmitter.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/createDictationEventEmitter.ts
@@ -5,8 +5,7 @@ export const createDictationEventEmitter = (): DictationEventEmitter => {
const listeners = new Set<DictationEngineListener>();
return {
- // Iterating a copy so a listener that unsubscribes on its own event cannot
- // skip the listener registered after it.
+ // Iterates a copy so a listener unsubscribing mid-emit can't skip the next one.
emit: (event) => {
for (const listener of Array.from(listeners)) {
listener(event);
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/createLivenessWatchdog.ts b/packages/twenty-front/src/modules/ai/dictation/utils/createLivenessWatchdog.ts
index 631d9697245..21a3fbf4858 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/createLivenessWatchdog.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/createLivenessWatchdog.ts
@@ -1,7 +1,5 @@
import { type LivenessWatchdog } from '@/ai/dictation/types/LivenessWatchdog';
-// iOS can accept start() and then emit nothing at all, so liveness is measured
-// rather than assumed. Kept free of browser APIs beyond timers so the rule that
-// decides whether dictation is working can be tested without a microphone.
+// iOS can accept start() and then emit nothing, so liveness is measured.
export const createLivenessWatchdog = ({
timeoutInMs,
onSilent,
@@ -30,8 +28,7 @@ export const createLivenessWatchdog = ({
}
}, timeoutInMs);
},
- // Any sign of life counts, not just a transcript: audio opening proves the
- // engine is running, and a slow speaker should not read as a dead engine.
+ // Any sign of life counts, so a slow speaker isn't read as a dead engine.
noteActivity: () => {
hasSeenActivity = true;
clear();
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/getDictationLanguage.ts b/packages/twenty-front/src/modules/ai/dictation/utils/getDictationLanguage.ts
index b371a120583..38485e4787b 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/getDictationLanguage.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/getDictationLanguage.ts
@@ -1,16 +1,13 @@
import { APP_LOCALES, SOURCE_LOCALE } from 'twenty-shared/translations';
import { normalizeLocale } from 'twenty-shared/utils';
-// Only the on-device engine needs this: the Web Speech API recognises exactly
-// one language per session and cannot detect it, so a wrong guess produces
-// confident nonsense rather than an error. The speaker's Twenty language beats
-// navigator.language, which is the browser UI's rather than the speaker's.
+// Web Speech can't detect the language and a wrong one yields confident nonsense, not an error, so the
+// member's locale wins over navigator.language, which is the browser UI's.
export const getDictationLanguage = (
workspaceMemberLocale?: string | null,
): string => {
const locale = normalizeLocale(workspaceMemberLocale ?? null);
- // The pseudo locale is a translation-coverage tool, not a language anything
- // can be recognised in.
+ // The pseudo locale is a translation-coverage tool, not a recognisable language.
return locale === APP_LOCALES['pseudo-en'] ? SOURCE_LOCALE : locale;
};
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/mapMediaDeviceError.ts b/packages/twenty-front/src/modules/ai/dictation/utils/mapMediaDeviceError.ts
index 3d4640b7dde..5f18fb33f00 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/mapMediaDeviceError.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/mapMediaDeviceError.ts
@@ -1,7 +1,6 @@
import { type DictationFailureReason } from '@/ai/dictation/types/DictationFailureReason';
-// getUserMedia rejects with a DOMException whose name is the only stable part
-// of the failure; the message is browser-specific prose.
+// The DOMException name is the only stable part; messages are browser-specific.
export const mapMediaDeviceError = (error: unknown): DictationFailureReason => {
const name = error instanceof Error ? error.name : '';
@@ -12,8 +11,7 @@ export const mapMediaDeviceError = (error: unknown): DictationFailureReason => {
case 'NotFoundError':
case 'OverconstrainedError':
return 'no-device';
- // The device exists but another application holds it, which the user fixes
- // the same way they would a missing one.
+ // Held by another app: the user fixes it the same way as a missing device.
case 'NotReadableError':
return 'no-device';
default:
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/mapSpeechRecognitionError.ts b/packages/twenty-front/src/modules/ai/dictation/utils/mapSpeechRecognitionError.ts
index fcc8d2cfcb5..3133f0e12a5 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/mapSpeechRecognitionError.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/mapSpeechRecognitionError.ts
@@ -1,7 +1,6 @@
import { type DictationFailureReason } from '@/ai/dictation/types/DictationFailureReason';
-// 'aborted' is absent on purpose: it is what a deliberate stop() produces, and
-// treating it as a failure would surface an error every time a user finishes.
+// 'aborted' is what a deliberate stop() produces, so it isn't a failure.
export const mapSpeechRecognitionError = (
error: string,
): DictationFailureReason | undefined => {
@@ -14,8 +13,6 @@ export const mapSpeechRecognitionError = (
case 'network':
return 'network';
case 'aborted':
- // The engine ran and heard nothing, which is a quiet room rather than a
- // broken engine — the session just ends with no transcript.
case 'no-speech':
return undefined;
default:
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/readDictationSurface.ts b/packages/twenty-front/src/modules/ai/dictation/utils/readDictationSurface.ts
index 25de76ac9f3..4618446471d 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/readDictationSurface.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/readDictationSurface.ts
@@ -3,8 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { getSpeechRecognitionConstructor } from '@/ai/dictation/utils/getSpeechRecognitionConstructor';
import { type DictationSurface } from '@/ai/dictation/types/DictationSurface';
-// Every browser shipped for iOS is WKWebView underneath, so these are detected
-// by name rather than by engine — the engine would report Safari for all of them.
+// Every iOS browser is WKWebView, so third-party ones are detected by name.
const THIRD_PARTY_IOS_BROWSER_PATTERN = /CriOS|FxiOS|EdgiOS|OPiOS/;
const IOS_DEVICE_PATTERN = /iPad|iPhone|iPod/;
@@ -15,9 +14,7 @@ const getIsIOS = (userAgent: string): boolean =>
// iPadOS reports itself as a Mac; the touch points are what give it away.
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
-// matchMedia is missing from some embedded WebViews, which are exactly the
-// surfaces this module exists to survive, so its absence falls back to the
-// legacy iOS flag rather than throwing.
+// matchMedia is missing from some embedded WebViews, so fall back to the legacy iOS flag.
const getIsStandaloneDisplayMode = (): boolean =>
(isDefined(window.matchMedia) &&
window.matchMedia('(display-mode: standalone)').matches) ||
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/resolveDictationAvailability.ts b/packages/twenty-front/src/modules/ai/dictation/utils/resolveDictationAvailability.ts
index 908d92e436f..c1d2d3325f2 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/resolveDictationAvailability.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/resolveDictationAvailability.ts
@@ -1,16 +1,11 @@
import { type DictationSurface } from '@/ai/dictation/types/DictationSurface';
-// On iOS the Web Speech API is exposed inside installed PWAs and third-party
-// browsers (all WKWebView) but never emits, so these surfaces would otherwise
-// cost the user a recording before failing.
+// iOS PWAs and third-party browsers (all WKWebView) expose Web Speech but it never emits, costing a recording before failing.
const isWebSpeechKnownDead = (surface: DictationSurface) =>
surface.isIOS &&
(surface.isStandaloneDisplayMode || surface.isThirdPartyIOSBrowser);
-// hasMediaDevices matters even though recognition does its own capture: the
-// engine warms the microphone through getUserMedia first, so a WebView that
-// exposes SpeechRecognition without it would offer a button that fails on
-// every press. Opening a microphone at all is gated on a secure context.
+// hasMediaDevices is required: the engine warms the microphone through getUserMedia first, which needs a secure context.
export const resolveDictationAvailability = (
surface: DictationSurface,
): boolean =>
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/unlockAudioContext.ts b/packages/twenty-front/src/modules/ai/dictation/utils/unlockAudioContext.ts
index f3effa3e937..20af6e6cd61 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/unlockAudioContext.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/unlockAudioContext.ts
@@ -5,8 +5,7 @@ type AudioContextWindow = {
webkitAudioContext?: typeof AudioContext;
};
-// close() rejects on a context that never finished opening, and releasing one
-// is never worth failing a start over.
+// close() rejects on a context that never finished opening.
const closeQuietly = async (audioContext: AudioContext): Promise<void> => {
try {
await audioContext.close();
@@ -15,10 +14,7 @@ const closeQuietly = async (audioContext: AudioContext): Promise<void> => {
}
};
-// iOS suspends any AudioContext created outside a user gesture, and a suspended
-// context blocks the capture path speech recognition runs on. Failures are
-// swallowed: this improves the odds of a clean start and is never the reason to
-// refuse one.
+// iOS suspends AudioContexts created outside a gesture, which blocks speech capture.
export const unlockAudioContext = async (): Promise<void> => {
const audioContextWindow = window as unknown as AudioContextWindow;
const AudioContextConstructor =
@@ -37,14 +33,9 @@ export const unlockAudioContext = async (): Promise<void> => {
await audioContext.resume();
}
} catch {
- // See above: a failed unlock costs the odds of a clean start, nothing more.
+ // A failed unlock only lowers the odds of a clean start.
} finally {
- // Closed here rather than after resume(), because resume() rejecting is
- // exactly when the context would otherwise be leaked — and a rejection is
- // expected on the surface this exists for, where the gesture that permits
- // it can have expired during the microphone warm-up. A browser allows only
- // a handful of live contexts, each holding an audio render thread, so
- // leaking one per press would starve the capture path this is unlocking.
+ // Closed in finally: resume() routinely rejects here (the gesture can expire during warm-up), and browsers allow only a few live contexts.
if (isDefined(audioContext)) {
await closeQuietly(audioContext);
}
diff --git a/packages/twenty-front/src/modules/ai/dictation/utils/warmUpMicrophone.ts b/packages/twenty-front/src/modules/ai/dictation/utils/warmUpMicrophone.ts
index efacf0d8481..b4e2b5ac5f1 100644
--- a/packages/twenty-front/src/modules/ai/dictation/utils/warmUpMicrophone.ts
+++ b/packages/twenty-front/src/modules/ai/dictation/utils/warmUpMicrophone.ts
@@ -1,8 +1,4 @@
-// Opening and immediately releasing the microphone on the user's gesture is
-// what makes the first dictation attempt work on iOS: WebKit otherwise starts
-// recognition against an audio stack that is still initialising and returns no
-// result at all. The tracks are stopped straight away — the warm-up exists for
-// its side effect on the audio stack, not to hold a stream open.
+// Briefly opening the microphone on the gesture makes iOS's first dictation work; WebKit otherwise returns nothing.
export const warmUpMicrophone = async (): Promise<void> => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx
index ca13114862d..538dd84a2bd 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx
@@ -63,8 +63,6 @@ const buildSendChatMessageMock = (
const readPersistedDrafts = () =>
JSON.parse(localStorage.getItem(DRAFTS_STORAGE_KEY) ?? '{}');
-// The composer subscribes to the drafts, which reads them back from local
-// storage.
const renderAgentChat = ({
persistedDrafts,
sendChatMessageOutcomes,
@@ -80,7 +78,6 @@ const renderAgentChat = ({
},
});
- // Set once the wrapper has reset the session's storage.
localStorage.setItem(DRAFTS_STORAGE_KEY, JSON.stringify(persistedDrafts));
const Wrapper = ({ children }: { children: ReactNode }) => (
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
index 0b1d40a45dd..d9a6ae03ffe 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
@@ -211,10 +211,7 @@ export const useAgentChat = (
},
});
- // The stream this send started can exhaust the balance and publish
- // credits-exhausted before this response resolves; that event marks the
- // thread error, so its presence means the exhaustion is newer information
- // than the gate pass this response proves.
+ // The stream may already have set a newer credits-exhausted error; don't clear it.
if (!isAiChatCreditsExhaustedError(store.get(errorAtom))) {
store.set(currentWorkspaceState.atom, markWorkspaceCreditsAvailable);
}
@@ -223,8 +220,7 @@ export const useAgentChat = (
store.set(lastSentBrowsingContextAtom, browsingContext);
}
- // Filed once the message is in: a failed send restores the draft with
- // its mentions, so the retry files it instead.
+ // Filed after the send: a failed send restores the draft, so the retry files it.
getConversationTargetsFromSerializedDocument(
serializedContentToSend,
).forEach((conversationTarget) => {
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatModelId.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatModelId.ts
index 12966327300..5bc0794020f 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatModelId.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatModelId.ts
@@ -5,8 +5,7 @@ import { agentChatUserSelectedModelTierState } from '@/ai/states/agentChatUserSe
import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-// An undefined request id lets the server fall back to the workspace chat
-// tier, so the client never has to know that setting to send a message.
+// undefined lets the server fall back to the workspace chat tier.
export const useAgentChatModelId = () => {
const agentChatUserSelectedModelTier = useAtomStateValue(
agentChatUserSelectedModelTierState,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingToolCalls.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingToolCalls.ts
index 3ee10843a55..fd2b5db5518 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingToolCalls.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingToolCalls.ts
@@ -9,8 +9,6 @@ import { parsePendingToolCall } from '@/ai/utils/parsePendingToolCall';
import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-// The conversation waits once its turn is over, on every call still pending,
-// in the order the agent made them.
export const useAgentChatPendingToolCalls = (): AgentChatPendingToolCall[] => {
const agentChatDisplayedThread = useAtomStateValue(
agentChatDisplayedThreadState,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
index b84b6838f62..bc6276c4222 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
@@ -44,10 +44,7 @@ import { markWorkspaceCreditsExhausted } from '@/workspace/utils/updateWorkspace
const THROTTLE_MS = 100;
const PERMISSIONS_REFRESH_INTERVAL_MS = 30_000;
-// readUIMessageStream requires initialization chunks (start, start-step,
-// text-start) before content chunks. When reconnecting to a thread mid-stream,
-// those chunks were already sent before we subscribed. This adapter injects
-// synthetic initialization chunks so the reader can process mid-stream content.
+// readUIMessageStream needs start chunks that a mid-stream reconnect missed, so inject synthetic ones.
const createMidStreamAdapter = () => {
let hasSeenStart = false;
const knownTextPartIds = new Set<string>();
@@ -393,8 +390,7 @@ export const useAgentChatSubscription = (threadId: string | null) => {
}
case 'keepalive': {
- // The initial/reconnect heartbeat also loads access for shared links.
- // Reuse this lifecycle to reflect edit downgrades without polling the list.
+ // The reconnect heartbeat also reloads shared link access, catching edit downgrades without polling.
if (
!isDefined(lastPermissionsRefreshAt) ||
Date.now() - lastPermissionsRefreshAt >=
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
index d6e00241bbb..7abea257917 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
@@ -103,8 +103,7 @@ export const useAiChatEditor = () => {
},
});
- // Keep search functions in sync via Tiptap extension storage,
- // avoiding stale closures without useRef
+ // Extension storage avoids stale closures without a ref.
if (isDefined(editor)) {
const storage = editor.extensionStorage as unknown as Record<
string,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatSuggestedPromptsContext.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatSuggestedPromptsContext.ts
index c74bf9d354e..7b91dc34252 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatSuggestedPromptsContext.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatSuggestedPromptsContext.ts
@@ -14,8 +14,7 @@ import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/use
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';
-// The reactive counterpart of useGetBrowsingContext, which reads the store
-// imperatively at send time and so cannot drive what the chat renders.
+// Reactive counterpart of useGetBrowsingContext, which reads the store only at send time.
export const useAiChatSuggestedPromptsContext =
(): AiChatSuggestedPromptsContext | null => {
const isSidePanelOpened = useAtomStateValue(isSidePanelOpenedState);
@@ -53,8 +52,7 @@ export const useAiChatSuggestedPromptsContext =
viewType: contextStoreCurrentViewType,
});
- // The chat page is the chat's own record page, which is not what the user
- // is asking about
+ // The chat page is the chat's own record page, not what the user is asking about.
if (
!isDefined(objectMetadataItem) ||
!isDefined(browsingContextType) ||
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiModelTiers.ts b/packages/twenty-front/src/modules/ai/hooks/useAiModelTiers.ts
index 44bae772797..95d08a31f56 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiModelTiers.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiModelTiers.ts
@@ -15,8 +15,7 @@ import { type ClientAiModelConfig } from '~/generated-metadata/graphql';
const REFERENCE_TIER: AiModelTier = 'balanced';
-// Every tier's cost delta must use the same basis: the publisher's cost per
-// task when every tier has one, the catalog price otherwise.
+// One basis for every tier: cost per task when all have one, catalog price otherwise.
const getCostDeltaPercent = ({
model,
referenceModel,
@@ -40,8 +39,7 @@ const getCostDeltaPercent = ({
});
};
-// Mirrors the server rule: a pin counts only while automatic selection is off
-// and the pinned model is still served by the instance.
+// Mirrors the server: a pin counts only with auto-selection off and the model still served.
export const useAiModelTiers = (): ResolvedAiModelTier[] => {
const aiModels = useAtomStateValue(aiModelsState);
const aiModelTiers = useAtomStateValue(aiModelTiersState);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatToolCall.ts b/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatToolCall.ts
index 63e2c35a426..b49e82af242 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatToolCall.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatToolCall.ts
@@ -28,8 +28,7 @@ export const useAnswerAgentChatToolCall = () => {
const { enqueueToast } = useToast();
const { modelIdForRequest } = useAgentChatModelId();
- // Returns whether the call was answered, so a card can keep itself disabled
- // until the call is closed rather than invite a second answer.
+ // Returns whether answered, so a card stays disabled until the call closes.
const answerAgentChatToolCall = useCallback(
async ({
toolCallId,
@@ -85,8 +84,7 @@ export const useAnswerAgentChatToolCall = () => {
modelId: modelIdForRequest,
});
- // No chunk follows when a workflow run resumes in its own executor,
- // or when other calls of the same step still wait on their answers.
+ // No chunk follows when a workflow run resumes in its own executor or other calls still wait.
if (!isDefined(streamId)) {
store.set(isAwaitingFirstChunkAtom, false);
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAttachChatThreadToRecord.ts b/packages/twenty-front/src/modules/ai/hooks/useAttachChatThreadToRecord.ts
index b0f681ce70c..afff8d64cf4 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAttachChatThreadToRecord.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAttachChatThreadToRecord.ts
@@ -34,8 +34,7 @@ export const useAttachChatThreadToRecord = () => {
});
const { refetchAggregateQueries } = useRefetchAggregateQueries();
- // The chat model may file the conversation under the same record through
- // its own tool during the same turn, so an existing link counts as success.
+ // The chat model may link the same record through its own tool, so an existing link counts as success.
const attachChatThreadToRecord = async ({
threadId,
objectNameSingular,
@@ -58,8 +57,7 @@ export const useAttachChatThreadToRecord = () => {
}
try {
- // Links to custom objects have no unique index for the upsert to
- // resolve, so an existing link is looked up first.
+ // Custom object links have no unique index to upsert on.
const { data: existingLinks, error: existingLinksError } =
await apolloCoreClient.query<RecordGqlOperationFindManyResult>({
query: findExistingLinksQuery,
@@ -101,8 +99,7 @@ export const useAttachChatThreadToRecord = () => {
return;
}
- // The link exists by now, so a failed refresh of the counts is not
- // reported as a failed attach.
+ // The link exists by now, so a failed count refresh isn't a failed attach.
refetchAggregateQueries({
objectMetadataNamePlural:
junctionConfig.junctionObjectMetadata.namePlural,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts b/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts
index 4f75f461db1..28b822b6c99 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts
@@ -61,8 +61,7 @@ export const useGetBrowsingContext = () => {
(item) => item.id === objectMetadataItemId,
);
- // The chat page is the chat's own record page, which is not what the user
- // is asking about
+ // The chat page is the chat's own record page, not what the user is asking about.
if (
!objectMetadataItem ||
objectMetadataItem.nameSingular === CoreObjectNameSingular.AgentChatThread
diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
index cdf0e6b4b1e..ebd654bcba1 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
@@ -218,8 +218,7 @@ export const useChatReferenceTarget = (
recordId: reference.recordId,
objectNameSingular: reference.objectNameSingular,
});
- // The application settings page is not routed on the side panel, so
- // its chip keeps navigating the way a plain link does.
+ // Application settings aren't routed in the side panel, so the chip navigates like a plain link.
case 'app':
return undefined;
default:
diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.ts b/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.ts
index 97db260fbb6..279c21fa207 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.ts
@@ -17,8 +17,7 @@ import { type ObjectRecordOperation } from '@/object-record/types/ObjectRecordOp
import { useListenToEventsForQuery } from '@/sse-db-event/hooks/useListenToEventsForQuery';
import { type TargetRecordIdentifier } from '@/ui/layout/contexts/TargetRecordIdentifier';
-// The widget shows the most recent conversations in a card rather than a
-// browsable list, so it asks for one page and never pages further.
+// A card of recent conversations, never paged further.
const CHAT_THREADS_FOR_RECORD_PAGE_SIZE = 20;
// Every turn updates its thread, so this ranks by the latest activity.
@@ -32,15 +31,13 @@ const CHAT_THREADS_FOR_RECORD_GQL_FIELDS = {
thread: { id: true, title: true, deletedAt: true, updatedAt: true },
};
-// A link's record event carries its columns but not its conversation, so a
-// new link is read back rather than taken from the event.
+// Link events carry no conversation, so new links are read back.
const LINK_OPERATION_TYPES: ObjectRecordOperation['type'][] = [
'create-one',
'create-many',
];
-// Title and activity changes reach the listed conversations through the
-// record cache; these change which conversations the page holds.
+// Title and activity changes arrive through the record cache; these change which conversations are listed.
const THREAD_OPERATION_TYPES: ObjectRecordOperation['type'][] = [
'delete-one',
'delete-many',
@@ -112,9 +109,7 @@ export const useChatThreadsForRecord = ({
enabled: isRecordLinkable,
});
- // A custom object leg carries no unique index, so a conversation can be
- // linked to the record more than once. Sorted here too, as an update to a
- // listed conversation does not reorder the fetched page.
+ // Custom legs allow duplicate links; sorted since an update doesn't reorder the fetched page.
const threads = sortChatThreadsByLastActivityDesc(
uniqBy(links.map(({ thread }) => thread).filter(isDefined), 'id'),
);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useDetachChatThreadFromRecord.ts b/packages/twenty-front/src/modules/ai/hooks/useDetachChatThreadFromRecord.ts
index 4543dba3eaa..c7274ef434a 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useDetachChatThreadFromRecord.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useDetachChatThreadFromRecord.ts
@@ -10,8 +10,7 @@ export const useDetachChatThreadFromRecord = () => {
objectNameSingular: CoreObjectNameSingular.AgentChatThreadTarget,
});
- // Takes every link between the conversation and the record: a custom leg
- // carries no unique index, so there can be more than one.
+ // A custom leg has no unique index, so there can be several links.
const detachChatThreadFromRecord = async (linkIds: string[]) => {
try {
await deleteLinks({ recordIdsToDelete: linkIds });
diff --git a/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts
index 68f9460e25a..9cfda6ea416 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useHasReachedAiChatCreditsCap.ts
@@ -7,12 +7,8 @@ import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomState
import { hasReachedCurrentBillingPeriodCapSelector } from '@/workspace/states/hasReachedCurrentBillingPeriodCapSelector';
import { isResourceCreditSubscriptionItem } from '@/workspace/utils/isResourceCreditSubscriptionItem';
-// The credits exhausted error renders nothing on its own, so the banner must
-// mount whenever the workspace is refused for lack of credits. The resource
-// credit item's flag is the authoritative signal: a refused send marks it, an
-// upgrade or a successful send clears it. The thread error only stands in when
-// client state carries no resource credit item to hold the flag; when the item
-// exists, trusting a leftover error would keep the banner up after an upgrade.
+// The credits error renders nothing, so this keeps the banner mounted. The resource credit item's flag is
+// authoritative; the thread error stands in only without the item, else it would outlive an upgrade.
export const useHasReachedAiChatCreditsCap = () => {
const hasReachedCurrentBillingPeriodCap = useAtomStateValue(
hasReachedCurrentBillingPeriodCapSelector,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useIsAiChatArtifactSurface.ts b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatArtifactSurface.ts
index 723e95601d8..1485f8a51ad 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useIsAiChatArtifactSurface.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatArtifactSurface.ts
@@ -4,9 +4,7 @@ import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/should
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { isAiChatPath } from '~/utils/isAiChatPath';
-// Only the full page chat has room beside it for a side panel to act as an
-// artifact surface. The onboarding chat owns the whole screen, so what it
-// references opens as a page instead.
+// Only the full page chat has room for a side panel artifact; the onboarding chat owns the screen.
export const useIsAiChatArtifactSurface = () => {
const { pathname } = useLocation();
const shouldOpenAiChatAfterOnboarding = useAtomStateValue(
diff --git a/packages/twenty-front/src/modules/ai/hooks/useIsAiChatComposerCentered.ts b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatComposerCentered.ts
index b0aac7d8052..6834ee7e114 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useIsAiChatComposerCentered.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatComposerCentered.ts
@@ -8,8 +8,7 @@ import { useShouldShowAiChatEmptyState } from '@/ai/hooks/useShouldShowAiChatEmp
export const useIsAiChatComposerCentered = () => {
const aiChatSurface = useContext(AiChatSurfaceContext);
- // A preamble is its own choreographed intro (onboarding); centering the
- // composer would fight with it.
+ // A preamble (onboarding) is its own intro; centering would fight it.
const messageListPreamble = useContext(AiChatMessageListPreambleContext);
const shouldShowAiChatEmptyState = useShouldShowAiChatEmptyState();
diff --git a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
index be3433d7909..9efb81c80e4 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts
@@ -137,8 +137,7 @@ export const useRefreshAgentChatThreads = () => {
return undefined;
}
- // Retry once rather than overwrite a record event applied while the
- // request was in flight
+ // Retry rather than overwrite a record event applied mid-request.
if (hasChangedSinceRequest()) {
continue;
}
@@ -195,8 +194,7 @@ export const useRefreshAgentChatThreads = () => {
[loadAgentChatThreads],
);
- // A chat opened by URL may sit past the loaded pages. Resolves to null
- // when the chat is not listed for this member, undefined when unknown
+ // A chat opened by URL may be past the loaded pages; null if not listed for this member, undefined if unknown.
const loadAgentChatThread = useCallback(
async (threadId: string) => {
for (let attempt = 0; attempt < 2; attempt++) {
@@ -229,8 +227,7 @@ export const useRefreshAgentChatThreads = () => {
addAgentChatThread(thread);
- // The chat may have been selected before its record was loaded, so
- // its usage could not be restored then
+ // The chat may have been selected before its record loaded, when usage couldn't be restored.
const usageAtom = agentChatUsageComponentFamilyState.atomFamily({
instanceId: AGENT_CHAT_INSTANCE_ID,
familyKey: { threadId: thread.id },
diff --git a/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts b/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts
index 154ec889bde..878c7df8fab 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useRetryChatMessage.ts
@@ -53,9 +53,7 @@ export const useRetryChatMessage = () => {
},
});
- // Same ordering guard as useAgentChat: a credits-exhausted event from
- // the stream this retry started may already have marked the thread error
- // before this response resolves, and that exhaustion is newer truth.
+ // Same guard as useAgentChat: the stream may already have set a newer credits-exhausted error.
if (!isAiChatCreditsExhaustedError(store.get(errorAtom))) {
store.set(currentWorkspaceState.atom, markWorkspaceCreditsAvailable);
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts b/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
index 3d9bbdfa6ee..1b3be55c2c9 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
@@ -5,9 +5,7 @@ import {
} from '@/ai/states/agentChatPrepromptState';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
-// Staging a preprompt is always these two steps: sending reads the draft rather
-// than the editor, so the draft has to be written before AgentChatPrepromptEffect
-// picks the preprompt up.
+// Sending reads the draft, not the editor, so it's written before AgentChatPrepromptEffect picks it up.
export const useStageAiChatPreprompt = () => {
const setAgentChatDraftsByThreadId = useSetAtomState(
agentChatDraftsByThreadIdState,
diff --git a/packages/twenty-front/src/modules/ai/hooks/useToolWidgetByName.ts b/packages/twenty-front/src/modules/ai/hooks/useToolWidgetByName.ts
index 6ee3edfa339..a06b0dad11c 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useToolWidgetByName.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useToolWidgetByName.ts
@@ -8,8 +8,6 @@ import { type ToolWidget } from '@/ai/types/ToolWidget';
const EMPTY_TOOL_WIDGETS: Map<string, ToolWidget> = new Map();
-// A tool names the widget that renders its calls; the chat resolves that
-// pointer instead of switching on tool names it would have to know about.
export const useToolWidgetByName = (): Map<string, ToolWidget> => {
const { toolIndex } = useGetToolIndex();
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatFavoriteThreadsSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatFavoriteThreadsSelector.ts
index 3e1d3fd8fa3..80c60892e00 100644
--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatFavoriteThreadsSelector.ts
+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatFavoriteThreadsSelector.ts
@@ -41,8 +41,7 @@ export const agentChatFavoriteThreadsSelector = createAtomSelector<
return [];
}
- // The loaded chat carries its latest title and deletion, which the
- // favorite's identifier does not follow
+ // The loaded chat carries its latest title and deletion, which the favorite's identifier doesn't follow.
const loadedThread = get(
recordStoreFamilyState,
item.targetRecordId,
diff --git a/packages/twenty-front/src/modules/ai/types/SuggestedPrompt.ts b/packages/twenty-front/src/modules/ai/types/SuggestedPrompt.ts
index d20d1557c1a..0f9b77e520d 100644
--- a/packages/twenty-front/src/modules/ai/types/SuggestedPrompt.ts
+++ b/packages/twenty-front/src/modules/ai/types/SuggestedPrompt.ts
@@ -7,8 +7,7 @@ export type SuggestedPrompt = {
id: string;
label: MessageDescriptor;
Icon: IconComponent;
- // PREFILL drops the prompt in the composer so it can be completed; SEND asks it
- // straight away, for prompts that need nothing from the user.
+ // PREFILL lets the user complete the prompt; SEND is for prompts needing nothing more.
mode?: AgentChatPrepromptMode;
prompts: MessageDescriptor[];
};
diff --git a/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts b/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
index 7d2ae616c19..175155b7b03 100644
--- a/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
+++ b/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts
@@ -1,9 +1,7 @@
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
import { type RecordGqlOperationFilter } from 'twenty-shared/types';
-// Deleted chats stay listed so they can be restored. Anyone who reads a
-// workflow run reads its agent's conversations, which belong to the run
-// rather than to the chat list
+// Deleted chats stay listed for restore; workflow run conversations belong to the run, not the list.
export const buildAgentChatThreadListFilter = (
chatObjectMetadataItem: Pick<EnrichedObjectMetadataItem, 'fields'>,
): RecordGqlOperationFilter => {
diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatContextStoreInstanceId.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatContextStoreInstanceId.ts
index 36e2d9188b9..97cf3afcb32 100644
--- a/packages/twenty-front/src/modules/ai/utils/getAiChatContextStoreInstanceId.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatContextStoreInstanceId.ts
@@ -2,8 +2,7 @@ import { isDefined } from 'twenty-shared/utils';
import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';
-// On the full page chat the side panel holds whatever the user is still looking at,
-// so it owns the context; anywhere else the chat sits beside the main page.
+// On the full page chat the side panel holds what the user is looking at, so it owns the context.
export const getAiChatContextStoreInstanceId = ({
isOnAiChatPage,
isSidePanelOpened,
diff --git a/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts b/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts
index 3ad530ccdd0..b49edfa0414 100644
--- a/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts
@@ -1,7 +1,6 @@
import { isDefined, isValidUuid } from 'twenty-shared/utils';
-// /chat without an id shows the current chat, which starts as the most recent
-// one; a new chat has no record to show yet
+// /chat without an id shows the current chat (initially the latest); a new chat has no record yet.
export const getDisplayedAiChatThreadId = ({
urlThreadId,
currentAiChatThread,
diff --git a/packages/twenty-front/src/modules/ai/utils/getEffectiveToolName.ts b/packages/twenty-front/src/modules/ai/utils/getEffectiveToolName.ts
index 56ec46dc6b3..68176e5d448 100644
--- a/packages/twenty-front/src/modules/ai/utils/getEffectiveToolName.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getEffectiveToolName.ts
@@ -3,8 +3,7 @@ import { getToolName, type DynamicToolUIPart, type ToolUIPart } from 'ai';
import { type ToolInput } from '@/ai/types/ToolInput';
import { unwrapToolInput } from '@/ai/utils/tool-display/unwrap-tool-input.util';
-// A call dispatched through execute_tool carries the real tool name in its
-// input; presentation belongs to that tool, not to the dispatcher.
+// execute_tool calls carry the real tool name, which owns presentation, in their input.
export const getEffectiveToolName = (
toolPart: ToolUIPart | DynamicToolUIPart,
): string =>
diff --git a/packages/twenty-front/src/modules/ai/utils/getMarkdownBlocksIncrementally.ts b/packages/twenty-front/src/modules/ai/utils/getMarkdownBlocksIncrementally.ts
index e0fc7b91cec..1209e822bfe 100644
--- a/packages/twenty-front/src/modules/ai/utils/getMarkdownBlocksIncrementally.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getMarkdownBlocksIncrementally.ts
@@ -1,25 +1,17 @@
import { type MarkdownBlockSplitCache } from '@/ai/types/MarkdownBlockSplitCache';
import { Lexer } from 'marked';
-// Appended text can reopen the last block, and a list followed by a blank-line
-// token merges with a later item ("- a\n\n" + "- b" is one loose list), so the
-// two trailing blocks must be re-tokenized on every flush. Anything before them
-// was terminated by content that is still present, so it can never change.
+// Appended text can reopen the last block or merge a list across a blank line, so the last two re-tokenize.
const UNSTABLE_TRAILING_BLOCK_COUNT = 2;
-// marked.lexer normalizes line endings before tokenizing; blockTokens does not,
-// so normalize here to keep raw offsets aligned with the sliced text.
+// marked.lexer normalizes line endings but blockTokens doesn't, which would misalign raw offsets.
const normalizeLineEndings = (text: string): string =>
text.replace(/\r\n|\r/g, '\n');
const splitIntoBlocks = (text: string): string[] =>
new Lexer().blockTokens(text, []).map((token) => token.raw);
-// A streamed message only grows, so instead of re-tokenizing the whole message
-// on every flush, reuse the blocks that can no longer change and re-tokenize
-// only the unstable tail, keeping each flush O(appended text) instead of
-// O(whole message). Any non-append change misses the stablePrefix guard and
-// falls back to a full split.
+// A streamed message only grows: settled blocks are reused, and any non-append change fully re-splits.
export const getMarkdownBlocksIncrementally = ({
text,
cache,
@@ -47,9 +39,7 @@ export const getMarkdownBlocksIncrementally = ({
0,
Math.max(0, blocks.length - UNSTABLE_TRAILING_BLOCK_COUNT),
);
- // Append newly stabilized raws instead of re-joining the whole prefix on
- // every flush. The stable set shrinks when the tail collapses into fewer
- // than two blocks; then trim the raws that fell out of it.
+ // The stable set shrinks when the tail collapses into fewer than two blocks.
const nextStablePrefix =
nextStableBlocks.length >= stableBlocks.length
? stablePrefix + nextStableBlocks.slice(stableBlocks.length).join('')
diff --git a/packages/twenty-front/src/modules/ai/utils/getNearestAiModelTier.ts b/packages/twenty-front/src/modules/ai/utils/getNearestAiModelTier.ts
index c0d17474e65..c3b2778595f 100644
--- a/packages/twenty-front/src/modules/ai/utils/getNearestAiModelTier.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getNearestAiModelTier.ts
@@ -4,9 +4,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type ResolvedAiModelTier } from '@/ai/types/ResolvedAiModelTier';
import { type ClientAiModelConfig } from '~/generated-metadata/graphql';
-// Where a pinned model sits on the slider: its own tier when a tier resolves
-// to it, otherwise the tier whose model is closest in intelligence, so the
-// handle lands somewhere honest rather than always in the middle.
+// A pinned model sits on its own tier, else on the tier closest in intelligence.
export const getNearestAiModelTier = (
model: ClientAiModelConfig | undefined,
tiers: ResolvedAiModelTier[],
diff --git a/packages/twenty-front/src/modules/ai/utils/hasCostPerTaskForEveryModel.ts b/packages/twenty-front/src/modules/ai/utils/hasCostPerTaskForEveryModel.ts
index 7bc590e7281..079590993e1 100644
--- a/packages/twenty-front/src/modules/ai/utils/hasCostPerTaskForEveryModel.ts
+++ b/packages/twenty-front/src/modules/ai/utils/hasCostPerTaskForEveryModel.ts
@@ -2,8 +2,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type ClientAiModelConfig } from '~/generated-metadata/graphql';
-// Cost per task and price per token are different bases, so a comparison
-// across tiers uses cost per task only when every resolved model has one.
+// Cost per task and price per token aren't comparable across tiers.
export const hasCostPerTaskForEveryModel = (
models: (Pick<ClientAiModelConfig, 'costPerTask'> | undefined)[],
): boolean =>
diff --git a/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts b/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
index 69571e24da1..c9603236152 100644
--- a/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
+++ b/packages/twenty-front/src/modules/ai/utils/parseChatReferenceBody.ts
@@ -75,9 +75,7 @@ export const parseChatReferenceBody = (
const segments = body.split(':');
const [kindPrefix, ...identityAndLabel] = segments;
- // A recognised prefix followed by an identity of the wrong shape is a
- // retired or malformed marker, not a record of an object bearing that
- // name, so it must not fall through to the unprefixed record form.
+ // A known prefix with a malformed identity is a retired marker, so it must not fall through to the unprefixed record form.
if (isChatReferenceKind(kindPrefix)) {
return parseSegments({ kind: kindPrefix, segments: identityAndLabel });
}
diff --git a/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts b/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts
index 609b95c876e..e6d5ff538a2 100644
--- a/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts
+++ b/packages/twenty-front/src/modules/ai/utils/parsePendingToolCall.ts
@@ -13,9 +13,7 @@ import { isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
import { type AgentChatPendingToolCall } from '@/ai/types/AgentChatPendingToolCall';
-// A call the agent paused on waits until its output says otherwise. The server
-// validated its input against the tool's schema when the call was made, so
-// only the shape each card needs is checked here.
+// The server validated input against the tool schema, so only each card's needed shape is checked.
export const parsePendingToolCall = (
part: ExtendedUIMessagePart,
): AgentChatPendingToolCall | null => {
diff --git a/packages/twenty-front/src/modules/ai/utils/shouldToolPartRenderStandalone.ts b/packages/twenty-front/src/modules/ai/utils/shouldToolPartRenderStandalone.ts
index 55b83ec6e93..9a0c997e8d2 100644
--- a/packages/twenty-front/src/modules/ai/utils/shouldToolPartRenderStandalone.ts
+++ b/packages/twenty-front/src/modules/ai/utils/shouldToolPartRenderStandalone.ts
@@ -10,13 +10,11 @@ export const shouldToolPartRenderStandalone = (
return false;
}
- // A record widget draws what the call returned, so it has nothing to show
- // before the call has run.
+ // A record widget draws the call's output, so it has nothing to show before the call has run.
if (widget.kind === 'builtin') {
return toolPart.state === 'output-available';
}
- // An app widget owns the whole call, approval and failure included, so it
- // mounts as soon as the input it renders has settled.
+ // An app widget owns the whole call, approval and failure included, so it mounts once its input has settled.
return toolPart.state !== 'input-streaming';
};
diff --git a/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.ts b/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.ts
index 1a69299a85d..8e253a7a416 100644
--- a/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.ts
+++ b/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.ts
@@ -2,8 +2,7 @@ type ThreadWithLastActivity = {
updatedAt: string | Date;
};
-// Sending a message touches its conversation, so updatedAt is its last
-// activity
+// Sending a message touches its conversation, so updatedAt is its last activity.
const getLastActivityMs = (thread: ThreadWithLastActivity): number =>
new Date(thread.updatedAt).getTime();
diff --git a/packages/twenty-front/src/modules/ai/utils/tool-display/unwrap-tool-input.util.ts b/packages/twenty-front/src/modules/ai/utils/tool-display/unwrap-tool-input.util.ts
index 893fbfec3ad..028b8bd890e 100644
--- a/packages/twenty-front/src/modules/ai/utils/tool-display/unwrap-tool-input.util.ts
+++ b/packages/twenty-front/src/modules/ai/utils/tool-display/unwrap-tool-input.util.ts
@@ -2,8 +2,7 @@ import { z } from 'zod';
import { type ToolInput } from '@/ai/types/ToolInput';
-// Coercing here would turn a missing name into the string "undefined", which
-// then reads as a real tool name downstream.
+// Coercing would turn a missing name into the tool name "undefined".
const ExecuteToolSchema = z.object({
toolName: z.string().min(1),
arguments: z.unknown(),
diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts
index 6383677fb7c..2b2e309f3bb 100644
--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts
+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts
@@ -162,9 +162,7 @@ export const triggerAttachRelationOptimisticEffect = ({
});
};
-// A target fetched without the relation field cannot be modified in the cache,
-// but it is still attached to the source record, which is all the target's
-// cached lists need to know to place it.
+// A target fetched without the relation field can't be modified in cache, but its lists only need it attached to the source.
const buildRelationValueFromSourceRecord = ({
sourceObjectNameSingular,
sourceRecord,
diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerCreateRecordsOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerCreateRecordsOptimisticEffect.ts
index ed5195da3a8..a1fcaf8316a 100644
--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerCreateRecordsOptimisticEffect.ts
+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerCreateRecordsOptimisticEffect.ts
@@ -18,11 +18,8 @@ import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { isRecordMatchingFilter } from '@/object-record/record-filter/utils/isRecordMatchingFilter';
import { parseApolloStoreFieldName } from '~/utils/parseApolloStoreFieldName';
-/*
- TODO: for now new records are added to all cached record lists, no matter what the variables (filters, orderBy, etc.) are.
- We need to refactor how the record creation works in the RecordTable so the created record row is temporarily displayed with a local state,
- then we'll be able to uncomment the code below so the cached lists are updated coherently with the variables.
-*/
+// TODO: new records join every cached list regardless of its variables unless shouldMatchRootQueryFilter;
+// make matching the default once RecordTable keeps a created row in local state.
type TriggerCreateRecordsOptimisticEffectArgs = {
cache: ApolloCache;
objectMetadataItem: EnrichedObjectMetadataItem;
diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.ts
index 7ace5572223..a9ee37887aa 100644
--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.ts
+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.ts
@@ -39,8 +39,7 @@ type TriggerUpdateRelationsOptimisticEffectArgs = {
upsertRecordsInStore: (props: { partialRecords: ObjectRecord[] }) => void;
};
-// A junction record only exists to link its two sides, so detaching one destroys it.
-// Comments are the one remaining relation that cascades without being a junction.
+// A junction only links its two sides, so detaching destroys it; comments are the one non-junction cascade.
const shouldCascadeDeleteOnDetach = ({
targetObjectMetadata,
junctionObjectMetadataIds,
@@ -422,8 +421,7 @@ const extractTargetRecordsFromRelation = (
value: RecordGqlConnectionEdgesRequired | RecordGqlNode | null,
relation: FieldMetadataItemRelation,
): RecordGqlNode[] => {
- // TODO investigate on the root cause of array injection here, should never occurs
- // Cache might be corrupted somewhere due to ObjectRecord and RecordGqlNode inclusion
+ // TODO: find why arrays get injected here; ObjectRecord/RecordGqlNode mixing may corrupt the cache.
if (!isDefined(value) || isArray(value)) {
return [];
diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect.ts
index da2d8762a82..0bc79dc2570 100644
--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect.ts
+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect.ts
@@ -56,10 +56,8 @@ export const triggerUpdateRootQueriesOptimisticEffect = ({
objectMetadataItems,
});
- // The count follows the edges rather than the filter alone: the same
- // change can reach a list several times (a record update, then the
- // detach of a relation it cascaded to), and only an edge that actually
- // comes or goes may move the count.
+ // Counted from edges, not the filter: one change can reach a list several times (update, then cascaded detach),
+ // so only an edge actually added or removed moves the count.
let rootQueryNextEdges = [
...(readField<RecordGqlRefEdge[]>('edges', rootQueryConnection) ??
[]),
diff --git a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
index 39a06bbd449..b12ddca5d88 100644
--- a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
+++ b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts
@@ -274,8 +274,7 @@ describe('ApolloFactory', () => {
}
}, 10000);
- // fetch normalises header names, so assert case-insensitively rather than
- // depending on the casing the mock happens to expose.
+ // fetch normalises header names.
const readHeader = (
headers: Record<string, string>,
name: string,
@@ -301,8 +300,7 @@ describe('ApolloFactory', () => {
expect(readHeader(headers, 'X-App-Version')).toBe('1.0.0');
});
- // The session cookie is issued and refreshed server-side, so a rejection is
- // the end of the session rather than something the client can retry.
+ // The session cookie is server-managed, so a rejection ends the session.
it('should sign out on an unauthenticated response', async () => {
fetchMock.mockResponse(UNAUTHENTICATED_RESPONSE);
mockOnUnauthenticatedError.mockImplementation(clearSessionGeneration);
diff --git a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
index ef971e02240..6af4ea99bb5 100644
--- a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
+++ b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts
@@ -121,9 +121,7 @@ export class ApolloFactory implements ApolloManager {
retryIf: (error, operation) => {
// oxlint-disable-next-line no-console
console.log('retryIf error from retryLink', error);
- // A retry is a fresh request seconds later, so it carries whatever
- // cookie exists by then rather than the one that was current when
- // the operation was issued. See PendingServerSignOutEffect.
+ // A retry carries whatever cookie exists by then. See PendingServerSignOutEffect.
if (operation.getContext().skipRetry === true) {
return false;
}
@@ -275,8 +273,7 @@ export class ApolloFactory implements ApolloManager {
}
});
- // Type assertion needed because third-party link packages (apollo-link-rest,
- // apollo-upload-client) reference their own @apollo/client ApolloLink type
+ // Cast because third-party links (apollo-link-rest, apollo-upload-client) reference their own ApolloLink type.
const links = [
errorLink,
authLink,
diff --git a/packages/twenty-front/src/modules/apollo/utils/__tests__/encodeCursor.test.ts b/packages/twenty-front/src/modules/apollo/utils/__tests__/encodeCursor.test.ts
index 7b7e22f73b7..af68555b29e 100644
--- a/packages/twenty-front/src/modules/apollo/utils/__tests__/encodeCursor.test.ts
+++ b/packages/twenty-front/src/modules/apollo/utils/__tests__/encodeCursor.test.ts
@@ -48,9 +48,7 @@ describe('encodeCursor', () => {
expect(decoded).toEqual({ id: '123', position: 1 });
});
- // The server mints its own cursors with Buffer.toString('base64url'), so the
- // bytes are pinned rather than only the shape of the alphabet: for this
- // payload the two alphabets coincide and only the padding differs
+ // The server mints cursors with Buffer.toString('base64url'), so pin the exact bytes.
it('should emit the same bytes the server would for the same payload', () => {
const record: ObjectRecord = {
__typename: 'ObjectRecord',
@@ -67,9 +65,7 @@ describe('encodeCursor', () => {
expect(encodeCursor(record)).toMatch(/^[A-Za-z0-9_-]+$/);
});
- // Jest resolves 'buffer' to Node's builtin, which implements 'base64url';
- // the browser build gets the polyfill, which throws on it. Without this the
- // suite would stay green while every optimistic cache write broke in the app
+ // Jest resolves 'buffer' to Node's builtin; the browser polyfill throws on 'base64url'.
it('should only use encodings the browser Buffer polyfill implements', async () => {
jest.resetModules();
jest.doMock('buffer', () => jest.requireActual('buffer/'));
diff --git a/packages/twenty-front/src/modules/apollo/utils/isUnauthenticatedGraphQLError.ts b/packages/twenty-front/src/modules/apollo/utils/isUnauthenticatedGraphQLError.ts
index 27fdfae8404..5c2f2e4c5ca 100644
--- a/packages/twenty-front/src/modules/apollo/utils/isUnauthenticatedGraphQLError.ts
+++ b/packages/twenty-front/src/modules/apollo/utils/isUnauthenticatedGraphQLError.ts
@@ -1,7 +1,6 @@
import { type GraphQLFormattedError } from 'graphql';
-// Guards that throw before the UNAUTHENTICATED code is attached reach the
-// client as a bare "Unauthorized" message.
+// Guards that throw before UNAUTHENTICATED is attached reach the client as a bare "Unauthorized".
export const isUnauthenticatedGraphQLError = (
graphQLError: GraphQLFormattedError,
): boolean =>
diff --git a/packages/twenty-front/src/modules/app/components/LocaleDirectionProvider.tsx b/packages/twenty-front/src/modules/app/components/LocaleDirectionProvider.tsx
index 8b182ea338a..35e90bd7be4 100644
--- a/packages/twenty-front/src/modules/app/components/LocaleDirectionProvider.tsx
+++ b/packages/twenty-front/src/modules/app/components/LocaleDirectionProvider.tsx
@@ -7,9 +7,6 @@ type LocaleDirectionProviderProps = {
children: ReactNode;
};
-// twenty-ui components already read their direction from Base UI, but nothing
-// ever provided one, so they all resolved to its ltr default no matter which
-// locale was active.
export const LocaleDirectionProvider = ({
children,
}: LocaleDirectionProviderProps) => {
diff --git a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
index 4404b313824..42fd5ee8109 100644
--- a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
+++ b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
@@ -37,8 +37,7 @@ const SettingsRestPlayground = lazy(() =>
),
);
-// TODO: remove these legacy /api-webhooks redirects after 2026-08-04, once
-// users have had time to update their bookmarks to the new API settings routes.
+// TODO: remove these legacy /api-webhooks redirects after 2026-08-04.
const LEGACY_API_WEBHOOKS_SETTINGS_PATHS = {
ApiWebhooks: 'api-webhooks',
NewApiKey: 'api-webhooks/apis/new',
diff --git a/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx b/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx
index 344465324b8..1a07379ff04 100644
--- a/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx
+++ b/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx
@@ -66,8 +66,7 @@ export const PageChangeEffect = () => {
const pageChangeEffectNavigateLocation =
usePageChangeEffectNavigateLocation();
- //TODO: refactor useResetTableRowSelection hook to not throw when the argument `recordTableId` is an empty string
- // - replace CoreObjectNamePlural.Person
+ // TODO: make useResetTableRowSelection accept an empty recordTableId, then drop CoreObjectNamePlural.Person
const objectNamePlural =
matchPath(AppPath.RecordIndexPage, location.pathname)?.params
.objectNamePlural ?? CoreObjectNamePlural.Person;
diff --git a/packages/twenty-front/src/modules/app/routing/utils/getWorkspaceRouteObjectsForSurface.tsx b/packages/twenty-front/src/modules/app/routing/utils/getWorkspaceRouteObjectsForSurface.tsx
index e81ada6e422..5b336655c5f 100644
--- a/packages/twenty-front/src/modules/app/routing/utils/getWorkspaceRouteObjectsForSurface.tsx
+++ b/packages/twenty-front/src/modules/app/routing/utils/getWorkspaceRouteObjectsForSurface.tsx
@@ -43,10 +43,8 @@ const getWorkspaceRouteObjects = (
];
});
-// Each surface has exactly one route context store provider. The main surface
-// hosts it in MainAppLayoutWithSidePanel, above its routes. The side panel
-// renders its routes against its own location, which only the routed tree can
-// read, and it remounts per location, so its provider lives inside the tree.
+// One context store provider per surface: the main one sits above its routes, while the side panel
+// remounts per location, so its provider lives inside the routed tree.
export const getWorkspaceRouteObjectsForSurface = (
routeObjects: WorkspaceRouteObject[],
surface: WorkspaceSurfaceType,
diff --git a/packages/twenty-front/src/modules/app/utils/setupMonacoEnvironment.ts b/packages/twenty-front/src/modules/app/utils/setupMonacoEnvironment.ts
index 6d3b62e226d..b1cc3983ffe 100644
--- a/packages/twenty-front/src/modules/app/utils/setupMonacoEnvironment.ts
+++ b/packages/twenty-front/src/modules/app/utils/setupMonacoEnvironment.ts
@@ -6,15 +6,8 @@ import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker.js?worker
import TypeScriptWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker.js?worker';
import GraphqlWorker from 'monaco-graphql/esm/graphql.worker.js?worker';
-// Monaco resolves every language worker through this single global, shared by
-// all editors on the page (GraphiQL's and CodeEditor's alike), so it has to be
-// set up once for the whole app rather than per feature.
-//
-// Every label Monaco can ask for must be mapped: an unmapped label silently
-// falls back to the generic editor worker, which carries no language service.
-// Requests to it then reject with "Missing requestHandler or method: <method>"
-// (`resetSchema`, `findDocumentColors`, `getCodeFixesAtPosition`, ...) and the
-// language features go quietly dead.
+// One global shared by every editor on the page, so it is set up once for the whole app.
+// Every label must be mapped: an unmapped one falls back to the generic worker and its language features silently die.
const monacoEnvironment: Environment = {
getWorker: (_workerId, label) => {
switch (label) {
diff --git a/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsx b/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsx
index c18d1b6c9f1..e5d31006a34 100644
--- a/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsx
+++ b/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsx
@@ -58,7 +58,6 @@ jest.mock('twenty-ui/components', () => ({
useToast: () => ({ enqueueToast: mockEnqueueToast }),
}));
-// Rendered by VerifyEmail in the error state; isolate it from Apollo.
jest.mock(
'@/auth/sign-in-up/hooks/useHandleResendEmailVerificationToken',
() => ({
@@ -114,8 +113,6 @@ describe('VerifyEmail', () => {
);
});
- // The workspace-agnostic flow only sets the next sign-in-up step, so the
- // effect must hand off to the SignInUp page for that step to render.
await waitFor(() => {
expect(navigateMock).toHaveBeenCalledWith(AppPath.SignInUp);
});
diff --git a/packages/twenty-front/src/modules/auth/effect-components/PendingServerSignOutEffect.tsx b/packages/twenty-front/src/modules/auth/effect-components/PendingServerSignOutEffect.tsx
index 042f7e9aedd..49cef240bae 100644
--- a/packages/twenty-front/src/modules/auth/effect-components/PendingServerSignOutEffect.tsx
+++ b/packages/twenty-front/src/modules/auth/effect-components/PendingServerSignOutEffect.tsx
@@ -8,8 +8,7 @@ import { clientConfigApiStatusState } from '@/client-config/states/clientConfigA
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { SignOutDocument } from '~/generated-metadata/graphql';
-// A signOut that never reached the server leaves the httpOnly cookie alive, and
-// only the server can revoke it, so the next boot has to retry.
+// Only the server can revoke the httpOnly cookie, so a signOut that never reached it is retried on next boot.
export const PendingServerSignOutEffect = () => {
const apolloClient = useApolloClient();
const store = useStore();
@@ -29,9 +28,7 @@ export const PendingServerSignOutEffect = () => {
}
try {
- // Never retried: a retry is issued seconds later and carries whatever
- // cookie exists by then, so it would revoke a session established in
- // the meantime. A failure waits for the next boot instead.
+ // Never retried: a delayed retry would carry, and revoke, a session established in the meantime.
await apolloClient.mutate({
mutation: SignOutDocument,
context: { skipRetry: true },
diff --git a/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.ts b/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.ts
index 872cc49a38f..332c9c10cd6 100644
--- a/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.ts
@@ -80,8 +80,7 @@ describe('useRedeemSsoExchangeToken', () => {
expect(jotaiStore.get(isAppEffectRedirectEnabledState.atom)).toBe(true);
});
- // The cookie is httpOnly, so nothing else can tell the client it is now
- // signed in; without this the user stays on the sign-in flow.
+ // The cookie is httpOnly, so nothing else tells the client it is signed in.
it('should mark the session active once the exchange succeeds', async () => {
const { result } = renderHooks();
diff --git a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
index 48edf0a8974..e3d6ee726d8 100644
--- a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
@@ -119,8 +119,7 @@ export const useAuth = () => {
const navigate = useNavigate();
const clearSession = useCallback(() => {
- // The assign below is the only navigation: keep the redirect effect from
- // racing it to the sign-in page once the session is cleared.
+ // The assign below is the only navigation: keep the redirect effect from racing it to the sign-in page.
store.set(isAppEffectRedirectEnabledState.atom, false);
sessionStorage.clear();
store.set(isCookieAuthActiveState.atom, false);
@@ -142,9 +141,7 @@ export const useAuth = () => {
const availableWorkspacesCount =
countAvailableWorkspaces(availableWorkspaces);
- // The in-app "Create Workspace" entry point redirects here with this
- // signal so an existing user with workspaces lands on the creation form
- // instead of the workspace selection step.
+ // Set by the in-app "Create Workspace" entry point to skip workspace selection.
const wantsToCreateNewWorkspace =
new URLSearchParams(window.location.search).get('action') ===
'create-new-workspace';
diff --git a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts
index c0b2c33cbe4..1f214f36ae9 100644
--- a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts
@@ -14,9 +14,7 @@ type StoredImpersonationSession = {
returnPath: string;
};
-// Session swaps without a full reload would require enumerating every
-// user-scoped atom, localStorage entry, and Apollo cache key — brittle, and
-// silently broken every time a new piece of user state is added.
+// A full reload avoids enumerating every user-scoped atom, localStorage key and Apollo cache entry.
const reloadWithSession = (returnPath: string) => {
window.location.assign(returnPath);
};
diff --git a/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts b/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts
index a172a4617fc..434211fbc70 100644
--- a/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts
@@ -5,9 +5,8 @@ import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';
import { isPendingServerSignOutState } from '@/auth/states/isPendingServerSignOutState';
import { rotateSessionGeneration } from '@/auth/utils/rotateSessionGeneration';
-// The auth mutations set the session cookie server-side, which the client
-// cannot read, so every flow that authenticates has to record that a session
-// now exists. Missing this leaves useIsLogged false on an authenticated client.
+// The session cookie is httpOnly, so every auth flow must record that a session now exists,
+// or useIsLogged stays false on an authenticated client.
export const useMarkSessionActive = () => {
const store = useStore();
diff --git a/packages/twenty-front/src/modules/auth/hooks/useRedeemSsoExchangeToken.ts b/packages/twenty-front/src/modules/auth/hooks/useRedeemSsoExchangeToken.ts
index c18419b6f08..970d4a7ffb3 100644
--- a/packages/twenty-front/src/modules/auth/hooks/useRedeemSsoExchangeToken.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/useRedeemSsoExchangeToken.ts
@@ -20,8 +20,7 @@ export const useRedeemSsoExchangeToken = () => {
const redeemSsoExchangeToken = useCallback(
async (ssoExchangeToken: string) => {
- // Keeps PageChangeEffect from consuming returnToPath while the server
- // swaps the session cookie
+ // Keeps PageChangeEffect from consuming returnToPath while the server swaps the session cookie
setIsAppEffectRedirectEnabled(false);
try {
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpSsoExchangeTokenEffect.tsx b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpSsoExchangeTokenEffect.tsx
index 06a212fc1cf..eff36990bb8 100644
--- a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpSsoExchangeTokenEffect.tsx
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpSsoExchangeTokenEffect.tsx
@@ -14,9 +14,7 @@ export const SignInUpSsoExchangeTokenEffect = () => {
return;
}
- // Stripping synchronously through window.history rather than the router
- // (whose data-router navigations defer the replace) latches re-invoked and
- // remounted effects out: they re-read window.location and find no token
+ // Synchronous strip (the router defers replace) so re-run or remounted effects find no token
window.history.replaceState(
window.history.state,
'',
diff --git a/packages/twenty-front/src/modules/auth/states/isPendingServerSignOutState.ts b/packages/twenty-front/src/modules/auth/states/isPendingServerSignOutState.ts
index d1406c9cee0..6ef3988325c 100644
--- a/packages/twenty-front/src/modules/auth/states/isPendingServerSignOutState.ts
+++ b/packages/twenty-front/src/modules/auth/states/isPendingServerSignOutState.ts
@@ -1,8 +1,6 @@
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-// Only the server can end an httpOnly session, so a signOut that never
-// reached it leaves the cookie alive and the next boot must retry the
-// revocation instead of probing back into the session.
+// Set when a signOut may not have reached the server, so the next boot retries the revocation.
export const isPendingServerSignOutState = createAtomState<boolean>({
key: 'isPendingServerSignOutState',
defaultValue: false,
diff --git a/packages/twenty-front/src/modules/auth/utils/isValidReturnToPath.ts b/packages/twenty-front/src/modules/auth/utils/isValidReturnToPath.ts
index 4e0b1d864e6..02877ad0a78 100644
--- a/packages/twenty-front/src/modules/auth/utils/isValidReturnToPath.ts
+++ b/packages/twenty-front/src/modules/auth/utils/isValidReturnToPath.ts
@@ -12,8 +12,7 @@ const EXCLUDED_PATH_PREFIXES = [
].map(extractPathPrefix);
export const isValidReturnToPath = (path: string): boolean => {
- // Redirecting after login needs a page to land on, so the hash-only paths
- // isSafeInternalPath allows are not valid here.
+ // Hash-only paths pass isSafeInternalPath but leave a login redirect nowhere to land.
if (!isSafeInternalPath(path) || !path.startsWith('/') || path === '/') {
return false;
}
diff --git a/packages/twenty-front/src/modules/auth/utils/sessionGenerationStore.ts b/packages/twenty-front/src/modules/auth/utils/sessionGenerationStore.ts
index 043d2bac530..ed75077f303 100644
--- a/packages/twenty-front/src/modules/auth/utils/sessionGenerationStore.ts
+++ b/packages/twenty-front/src/modules/auth/utils/sessionGenerationStore.ts
@@ -12,8 +12,7 @@ class SessionGenerationStore {
}
try {
- // Direct reads observe another tab's rotation immediately; persisted Jotai
- // state only reads storage when the atom initializes.
+ // Persisted Jotai state only reads storage on init, so it would miss another tab's rotation.
this.inMemorySessionGeneration = localStorage.getItem(
SESSION_GENERATION_LOCAL_STORAGE_KEY,
);
diff --git a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
index bb1aa2f926c..f77f3bd79c3 100644
--- a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
+++ b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts
@@ -1,8 +1,6 @@
import { type AllMetadataName } from 'twenty-shared/metadata';
-// Non-syncable entities that broadcast real-time events through the SSE
-// event stream via WorkspaceEventBroadcaster, but are NOT part of the
-// workspace migration / syncable entity system (ALL_METADATA_NAME).
+// Broadcast through WorkspaceEventBroadcaster but absent from ALL_METADATA_NAME.
const ALL_NON_SYNCABLE_BROADCAST_ENTITY_NAME = {
application: 'application',
applicationRegistration: 'applicationRegistration',
diff --git a/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.ts b/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.ts
index 77d25915af6..e95bc5c78b7 100644
--- a/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.ts
+++ b/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.ts
@@ -1,15 +1,7 @@
import { type MetadataOperation } from '@/browser-event/types/MetadataOperation';
import { type BroadcastEntityName } from '@/browser-event/types/BroadcastEntityName';
-// TODO: The browser event layer currently uses "Metadata" naming throughout
-// (MetadataOperation, MetadataOperationBrowserEventDetail, etc.) because it
-// originally only carried events for syncable metadata entities (views, fields,
-// etc.). With WorkspaceEventBroadcaster, non-syncable entities like
-// applications also broadcast through the same SSE stream.
-// BroadcastEntityName captures this distinction at the type level, but the
-// naming of the surrounding types/hooks/files still says "Metadata." A future
-// rename of this layer (e.g. Metadata* → Entity* or Broadcast*) would make
-// the naming consistent with the actual scope.
+// TODO: rename this layer (Metadata* -> Broadcast*): it now also carries non-syncable entities.
export type MetadataOperationBrowserEventDetail<
T extends Record<string, unknown>,
> = {
diff --git a/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelCommandMenuDropdown.tsx b/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelCommandMenuDropdown.tsx
index a243e8f46ba..5032f7f5818 100644
--- a/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelCommandMenuDropdown.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelCommandMenuDropdown.tsx
@@ -49,8 +49,6 @@ export const RecordPageSidePanelCommandMenuDropdown = () => {
const availableWidth = useSidePanelFooterPinnedItemsAvailableWidth();
- // Pinned items are buttons in the footer, so the dropdown only repeats the
- // ones the footer could not fit next to this dropdown's own footprint.
const { pinnedOverflowCommandMenuItems } =
usePinnedCommandMenuItemsInlineLayout({
pinnedCommandMenuItems,
@@ -58,8 +56,7 @@ export const RecordPageSidePanelCommandMenuDropdown = () => {
containerWidth: availableWidth,
});
- // A widget owning the footer suppresses those buttons entirely, and leaves
- // the footer measurements stale, so every pinned item belongs here instead.
+ // A widget owning the footer hides the pinned buttons and leaves their measurements stale, so list every pinned item here.
const hasPinnedWidgetCommandMenuItems =
sidePanelWidgetFooterCommandMenuItems.some(
(commandMenuItem) => commandMenuItem.isPinned !== false,
diff --git a/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelPinnedCommandMenuItems.tsx b/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelPinnedCommandMenuItems.tsx
index edad3d62cec..b2444af5767 100644
--- a/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelPinnedCommandMenuItems.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/components/RecordPageSidePanelPinnedCommandMenuItems.tsx
@@ -20,8 +20,7 @@ export const RecordPageSidePanelPinnedCommandMenuItems = () => {
const availableWidth = useSidePanelFooterPinnedItemsAvailableWidth();
- // A widget that contributes footer actions, such as the email composer,
- // supersedes the record's own actions rather than doubling up with them.
+ // Widget footer actions (e.g. the email composer) replace the record's own.
const hasPinnedWidgetCommandMenuItems =
sidePanelWidgetFooterCommandMenuItems.some(
(commandMenuItem) => commandMenuItem.isPinned !== false,
diff --git a/packages/twenty-front/src/modules/command-menu-item/constants/SidePanelFooterOptionsReservedWidth.ts b/packages/twenty-front/src/modules/command-menu-item/constants/SidePanelFooterOptionsReservedWidth.ts
index 35d49a97c24..3c16c90170c 100644
--- a/packages/twenty-front/src/modules/command-menu-item/constants/SidePanelFooterOptionsReservedWidth.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/constants/SidePanelFooterOptionsReservedWidth.ts
@@ -1,3 +1,2 @@
-// Footprint of the options dropdown in the side panel footer: a small icon
-// button (24px) plus the footer gap separating it from the pinned buttons.
+// 24px options icon button plus the footer gap.
export const SIDE_PANEL_FOOTER_OPTIONS_RESERVED_WIDTH = 32;
diff --git a/packages/twenty-front/src/modules/command-menu-item/display/components/PinnedCommandMenuItemButtons.tsx b/packages/twenty-front/src/modules/command-menu-item/display/components/PinnedCommandMenuItemButtons.tsx
index 459854a1b15..d5cf3b06d0e 100644
--- a/packages/twenty-front/src/modules/command-menu-item/display/components/PinnedCommandMenuItemButtons.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/display/components/PinnedCommandMenuItemButtons.tsx
@@ -49,22 +49,17 @@ const StyledItemsContainer = styled.div<{ shouldReverse: boolean }>`
export const PinnedCommandMenuItemButtons = ({
containerWidth,
}: {
- // Provided when an ancestor already knows the width available to the
- // buttons; the row then shrinks to fit instead of stretching over the free
- // space to measure it, so sibling actions stay adjacent to the buttons.
+ // When set, the row shrinks to fit instead of stretching to measure free space, keeping sibling actions adjacent.
containerWidth?: number;
}) => {
const theme = useTheme();
const { commandMenuItems, containerType } = useContext(CommandMenuContext);
const isMobile = useIsMobile();
- // The footer keeps its label rightmost. Headers reverse the row so labels sit
- // left of the icons.
const isSidePanelFooter =
containerType === CommandMenuItemContainerType.SidePanelFooter;
- // Every header keeps its title on mobile, so its actions stay icon-only and
- // leave the title room. The side panel footer has a full row to itself.
+ // Headers keep their title even on mobile, so their actions stay icon-only; only the footer has a full row for a label.
const shouldLabelSingleCommandMenuItem = isSidePanelFooter;
const pinnedCommandMenuItems = useMemo(
@@ -98,8 +93,7 @@ export const PinnedCommandMenuItemButtons = ({
isDefined(commandMenuItem.shortLabel) &&
!shouldHideCommandMenuItemLabel(commandMenuItem.id);
- // Labels last so they land rightmost in the footer, and leftmost in the
- // header once the row is reversed.
+ // Labelled items last: rightmost in the footer, leftmost in the reversed header row.
const displayedInlineCommandMenuItems = [
...pinnedInlineCommandMenuItems.filter(
(item) => !isCommandMenuItemLabelled(item),
diff --git a/packages/twenty-front/src/modules/command-menu-item/display/hooks/usePinnedCommandMenuItemsInlineLayout.ts b/packages/twenty-front/src/modules/command-menu-item/display/hooks/usePinnedCommandMenuItemsInlineLayout.ts
index 0308cfbc06f..f774adcb3e5 100644
--- a/packages/twenty-front/src/modules/command-menu-item/display/hooks/usePinnedCommandMenuItemsInlineLayout.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/display/hooks/usePinnedCommandMenuItemsInlineLayout.ts
@@ -15,8 +15,7 @@ type ElementDimensions = {
type UsePinnedCommandMenuItemsInlineLayoutParams = {
pinnedCommandMenuItems: CommandMenuItemFieldsFragment[];
layoutKey: PinnedCommandMenuItemsLayoutKey;
- // Overrides the self-measured container width when an ancestor already
- // knows how much space the inline buttons may occupy.
+ // Overrides the self-measured width when an ancestor already knows the space the inline buttons may take.
containerWidth?: number;
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/display/states/commandMenuPinnedInlineLayoutFamilyState.ts b/packages/twenty-front/src/modules/command-menu-item/display/states/commandMenuPinnedInlineLayoutFamilyState.ts
index 59e1893dffa..e85e435f1b1 100644
--- a/packages/twenty-front/src/modules/command-menu-item/display/states/commandMenuPinnedInlineLayoutFamilyState.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/display/states/commandMenuPinnedInlineLayoutFamilyState.ts
@@ -2,9 +2,7 @@ import { type CommandMenuPinnedInlineLayout } from '@/command-menu-item/display/
import { type PinnedCommandMenuItemsLayoutKey } from '@/command-menu-item/display/types/PinnedCommandMenuItemsLayoutKey';
import { createAtomFamilyState } from '@/ui/utilities/state/jotai/utils/createAtomFamilyState';
-// Surfaces measure the same items at different sizes and label policies, and a
-// header can be on screen while a side panel footer is, so each keeps its own
-// measurements.
+// Keyed per surface: a header and a side panel footer can show the same items at once at different sizes.
export const commandMenuPinnedInlineLayoutFamilyState = createAtomFamilyState<
CommandMenuPinnedInlineLayout,
PinnedCommandMenuItemsLayoutKey
diff --git a/packages/twenty-front/src/modules/command-menu-item/display/utils/__tests__/interpolateCommandMenuItemFields.test.ts b/packages/twenty-front/src/modules/command-menu-item/display/utils/__tests__/interpolateCommandMenuItemFields.test.ts
index 89a743a89f8..5d96c4ffc75 100644
--- a/packages/twenty-front/src/modules/command-menu-item/display/utils/__tests__/interpolateCommandMenuItemFields.test.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/display/utils/__tests__/interpolateCommandMenuItemFields.test.ts
@@ -58,8 +58,7 @@ describe('interpolateCommandMenuItemFields', () => {
).toBe('Add to Favorites');
});
- // Navigation items are filled server-side against their target object, so
- // the client must not blank out what it cannot resolve.
+ // Navigation items are filled server-side, so unresolved placeholders must survive.
it('leaves placeholders it cannot fill intact', () => {
expect(
interpolateCommandMenuItemFields(
diff --git a/packages/twenty-front/src/modules/command-menu-item/display/utils/getLabelledPinnedCommandMenuItemId.ts b/packages/twenty-front/src/modules/command-menu-item/display/utils/getLabelledPinnedCommandMenuItemId.ts
index 0bcc6e55155..05b9bb9d4f6 100644
--- a/packages/twenty-front/src/modules/command-menu-item/display/utils/getLabelledPinnedCommandMenuItemId.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/display/utils/getLabelledPinnedCommandMenuItemId.ts
@@ -1,8 +1,7 @@
import { isDefined } from 'twenty-shared/utils';
import { type CommandMenuItemFieldsFragment } from '~/generated-metadata/graphql';
-// A null shortLabel is how an item opts out of ever showing text, so the single
-// labelled slot goes to the first item by position that asked for one.
+// A null shortLabel opts an item out of text, so the single labelled slot goes to the first item that has one.
export const getLabelledPinnedCommandMenuItemId = (
pinnedCommandMenuItems: CommandMenuItemFieldsFragment[],
): string | null =>
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
index 6900485f35f..d7001f6aa62 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
@@ -141,8 +141,7 @@ export const ENGINE_COMPONENT_KEY_COMPONENT_MAP: Record<
<CancelDashboardSingleRecordCommand />
),
[EngineComponentKey.NAVIGATION]: <NavigationEngineCommand />,
- // TODO: Remove these keys once we have ran the migration command `upgrade:1-21:refactor-navigation-commands`
- // These keys are kept for backward compatibility during migration
+ // TODO: remove these keys once `upgrade:1-21:refactor-navigation-commands` has run
[EngineComponentKey.GO_TO_PEOPLE]: (
<HeadlessNavigateEngineCommand
to={AppPath.RecordIndexPage}
diff --git a/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts b/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
index db7dc2a447d..10d02a8f921 100644
--- a/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
@@ -89,8 +89,7 @@ export const useCurrentCommandMenuContextApi = (): CommandMenuContextApi => {
},
);
- // Records shared at a lower access level than the role grants carry their
- // own permissions, which availability expressions read per record
+ // Records shared below the role's access level carry their own permissions, which availability expressions read per record
const selectedRecords = storedSelectedRecords.map((record) =>
isDefined(recordPermissionsByRecordId[record.id])
? { ...record, recordPermissions: recordPermissionsByRecordId[record.id] }
diff --git a/packages/twenty-front/src/modules/command-menu-item/hooks/useSidePanelFooterPinnedItemsAvailableWidth.ts b/packages/twenty-front/src/modules/command-menu-item/hooks/useSidePanelFooterPinnedItemsAvailableWidth.ts
index 9d867ea75a9..acdd48097ae 100644
--- a/packages/twenty-front/src/modules/command-menu-item/hooks/useSidePanelFooterPinnedItemsAvailableWidth.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/hooks/useSidePanelFooterPinnedItemsAvailableWidth.ts
@@ -2,9 +2,7 @@ import { SIDE_PANEL_FOOTER_OPTIONS_RESERVED_WIDTH } from '@/command-menu-item/co
import { SidePanelFooterWidthContext } from '@/ui/layout/side-panel/contexts/SidePanelFooterWidthContext';
import { useContext } from 'react';
-// Width left for the pinned buttons once the options dropdown footprint is
-// reserved out of the measured footer row. The buttons and the overflow
-// dropdown both size against this so they can never disagree on what fits.
+// Shared by the buttons and the overflow dropdown so they never disagree on what fits.
export const useSidePanelFooterPinnedItemsAvailableWidth = () => {
const sidePanelFooterWidth = useContext(SidePanelFooterWidthContext);
diff --git a/packages/twenty-front/src/modules/command-menu-item/utils/getCommandMenuItemPlaceholderValues.ts b/packages/twenty-front/src/modules/command-menu-item/utils/getCommandMenuItemPlaceholderValues.ts
index d6821c5b6be..8b9770c2969 100644
--- a/packages/twenty-front/src/modules/command-menu-item/utils/getCommandMenuItemPlaceholderValues.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/utils/getCommandMenuItemPlaceholderValues.ts
@@ -5,8 +5,7 @@ import {
} from 'twenty-shared/i18n';
import { type CommandMenuContextApi } from 'twenty-shared/types';
-// objectLabel is the one only the client can supply: it follows the selection,
-// singular or plural.
+// objectLabel is the only placeholder the client supplies: singular or plural per selection.
export const getCommandMenuItemPlaceholderValues = (
commandMenuContextApi: CommandMenuContextApi,
): MetadataLabelPlaceholderValues => {
diff --git a/packages/twenty-front/src/modules/context-store/components/RouteContextStoreProviderEffect.tsx b/packages/twenty-front/src/modules/context-store/components/RouteContextStoreProviderEffect.tsx
index 031bdb860dc..e6bb4e99a6f 100644
--- a/packages/twenty-front/src/modules/context-store/components/RouteContextStoreProviderEffect.tsx
+++ b/packages/twenty-front/src/modules/context-store/components/RouteContextStoreProviderEffect.tsx
@@ -65,8 +65,7 @@ export const RouteContextStoreProviderEffect = ({
return;
}
- // The sidebar links each object to the view last opened on it, so writing
- // this from the panel would move where the left side takes you next.
+ // The sidebar links each object to its last opened view; the side panel must not move it.
if (!isMainSurface) {
return;
}
diff --git a/packages/twenty-front/src/modules/context-store/hooks/useContextStoreInstanceId.ts b/packages/twenty-front/src/modules/context-store/hooks/useContextStoreInstanceId.ts
index 36d1496025d..fd96981d016 100644
--- a/packages/twenty-front/src/modules/context-store/hooks/useContextStoreInstanceId.ts
+++ b/packages/twenty-front/src/modules/context-store/hooks/useContextStoreInstanceId.ts
@@ -2,10 +2,7 @@ import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainCo
import { ContextStoreComponentInstanceContext } from '@/context-store/states/contexts/ContextStoreComponentInstanceContext';
import { useComponentInstanceStateContext } from '@/ui/utilities/state/component-state/hooks/useComponentInstanceStateContext';
-// The surface a component renders on owns its context store: the main outlet
-// and a route hosted in the side panel each have one, so a page open on both
-// sides keeps its own selection. Reads through a hook resolve this from
-// context on their own; imperative store access has to ask for it.
+// Each surface owns its context store, so imperative store access must resolve which one.
export const useContextStoreInstanceId = () =>
useComponentInstanceStateContext(ContextStoreComponentInstanceContext)
?.instanceId ?? MAIN_CONTEXT_STORE_INSTANCE_ID;
diff --git a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx
index 8b492440888..4a287f33e2a 100644
--- a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx
+++ b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx
@@ -1080,8 +1080,7 @@ describe('useFrontComponentExecutionContext', () => {
new Blob(['recorded-bytes'], { type: 'audio/webm' });
beforeEach(() => {
- // clearAllMocks keeps implementations; drop resolved/rejected values
- // so these tests stay order-independent.
+ // clearAllMocks keeps resolved values; reset so these tests stay order-independent.
mockDirectUploadFile.mockReset();
});
diff --git a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts
index 8af8555f2d4..00b238557a4 100644
--- a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts
+++ b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts
@@ -446,8 +446,7 @@ export const useFrontComponentExecutionContext = ({
timelineActivityId: timelineActivityId ?? null,
toolCall,
colorScheme,
- // i18n.locale is a Lingui string; the host is always configured with the
- // APP_LOCALES set, so it is a valid AppLocale.
+ // The host is always configured with APP_LOCALES, so this is a valid AppLocale.
locale: i18n.locale as AppLocale,
};
@@ -491,16 +490,13 @@ export const useFrontComponentExecutionContext = ({
}
lastCopyToClipboardCallAtRef.current = now;
- // Front components notify their own users, so a host success toast
- // would show up on top of theirs.
+ // Front components show their own toast; a host one would stack on top.
await copyToClipboardWithoutSuccessToast(text);
};
const hostUploadFile: FrontComponentHostCommunicationApi['uploadFile'] =
async (file, params) => {
- // Arguments come from sandboxed application code: reject malformed
- // shapes here. fieldMetadataId is mandatory — a file uploaded outside
- // a FILES field could never be attached to a record and would leak.
+ // Sandboxed input; fieldMetadataId is mandatory since a file uploaded outside a FILES field could never be attached and would leak.
if (
!(file instanceof Blob) ||
file.size === 0 ||
@@ -510,8 +506,7 @@ export const useFrontComponentExecutionContext = ({
return { status: 'failed', reason: 'invalid-params' };
}
- // A non-FILES target would upload fine and then fail at attach time,
- // stranding the file; reject it before uploading anything.
+ // A non-FILES target would fail at attach time, stranding the uploaded file.
const { fieldMetadataItem } = getFieldMetadataItemById({
fieldMetadataId: params.fieldMetadataId,
objectMetadataItems,
diff --git a/packages/twenty-front/src/modules/mention/extensions/MentionTag.ts b/packages/twenty-front/src/modules/mention/extensions/MentionTag.ts
index e407d11aebc..63cdbc0f0c6 100644
--- a/packages/twenty-front/src/modules/mention/extensions/MentionTag.ts
+++ b/packages/twenty-front/src/modules/mention/extensions/MentionTag.ts
@@ -38,8 +38,7 @@ export const MentionTag = Node.create({
'data-image-url': attributes.imageUrl,
}),
},
- // Marks the record a conversation started from, to be filed under it when
- // sent. Left out of the HTML so a copied mention does not carry it along.
+ // Marks the record a conversation started from; left out of the HTML so a copied mention does not carry it.
isConversationTarget: {
default: false,
rendered: false,
diff --git a/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts b/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts
index 8847ecd6d48..578b6c79659 100644
--- a/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts
+++ b/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts
@@ -31,8 +31,7 @@ export const ALL_METADATA_ENTITY_KEYS = [
'skills',
'rowLevelPermissionPredicates',
'rowLevelPermissionPredicateGroups',
- // TODO: clarify what really is metadata (syncable entity?)
- // vs 'core engine entity' or 'broadcastable entity'
+ // TODO: clarify what is metadata (syncable entity?) vs core engine or broadcastable entity
'applications',
] as const;
diff --git a/packages/twenty-front/src/modules/navigation-menu-item/display/sections/workspace/components/WorkspaceSection.tsx b/packages/twenty-front/src/modules/navigation-menu-item/display/sections/workspace/components/WorkspaceSection.tsx
index 87af7bc48f9..7c9c5e30b3a 100644
--- a/packages/twenty-front/src/modules/navigation-menu-item/display/sections/workspace/components/WorkspaceSection.tsx
+++ b/packages/twenty-front/src/modules/navigation-menu-item/display/sections/workspace/components/WorkspaceSection.tsx
@@ -105,8 +105,7 @@ export const WorkspaceSection = () => {
sectionTitle={t`Workspace`}
items={items}
rightIcon={
- // Customising the menu is a desktop job, so mobile shows neither the
- // entry point nor the add button it turns into.
+ // Customising the menu is desktop-only.
isMobile ? undefined : (
<StyledRightIconsContainer>
{isLayoutCustomizationModeEnabled ? (
diff --git a/packages/twenty-front/src/modules/navigation/components/AppNavigationDrawer.tsx b/packages/twenty-front/src/modules/navigation/components/AppNavigationDrawer.tsx
index 3aa299f3826..788fbf6219a 100644
--- a/packages/twenty-front/src/modules/navigation/components/AppNavigationDrawer.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/AppNavigationDrawer.tsx
@@ -25,8 +25,7 @@ export const AppNavigationDrawer = ({
return (
<NavigationDrawer className={className}>
- {/* Mobile switches modes from the navigation bar at the bottom of the
- screen, so a second switcher inside the drawer only repeats it. */}
+ {/* Mobile switches modes from the bottom navigation bar instead. */}
{!isMobile && (
<NavigationDrawerFixedContent>
<MainNavigationDrawerModeSwitcher />
diff --git a/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsx b/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsx
index 730fd487a27..3a4a1e49b49 100644
--- a/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsx
@@ -15,8 +15,7 @@ import { NAVIGATION_DRAWER_TABS } from '@/ui/navigation/states/navigationDrawerT
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useIsMobile } from 'twenty-ui/utilities';
-// Expanded, the row is sized off the page card header beside it so the rules
-// read as one line across both columns.
+// Expanded, the row matches the page card header so their borders read as one line.
const StyledSwitcher = styled.div<{ isExpanded: boolean }>`
align-items: ${({ isExpanded }) => (isExpanded ? 'center' : 'flex-start')};
border-bottom: ${({ isExpanded }) =>
@@ -49,9 +48,7 @@ const StyledMode = styled.button<{ isActive: boolean; isExpanded: boolean }>`
corner-shape: round;
cursor: pointer;
display: flex;
- // Only the mode showing a label may give ground. "AI" is two characters in
- // English and eighteen in Hebrew, and with every mode refusing to shrink the
- // row overflowed and pushed the last one - Settings - off the drawer.
+ // Only the labelled mode may shrink: long translations otherwise push Settings off the drawer.
flex-shrink: ${({ isActive, isExpanded }) =>
isActive && isExpanded ? 1 : 0};
font-family: inherit;
@@ -65,8 +62,6 @@ const StyledMode = styled.button<{ isActive: boolean; isExpanded: boolean }>`
: `${NAVIGATION_DRAWER_COLLAPSED_BUTTON_SIZE}px`};
justify-content: ${({ isExpanded }) =>
isExpanded ? 'flex-start' : 'center'};
- // A flex item will not shrink past its content without this, so flex-shrink
- // above would have nothing to act on.
min-width: 0;
padding: ${({ isExpanded }) =>
isExpanded ? `0 ${themeCssVariables.spacing['1.5']}` : '0'};
diff --git a/packages/twenty-front/src/modules/navigation/components/MobileNavigationBar.tsx b/packages/twenty-front/src/modules/navigation/components/MobileNavigationBar.tsx
index 7e4298f281b..e58cc9b8f25 100644
--- a/packages/twenty-front/src/modules/navigation/components/MobileNavigationBar.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/MobileNavigationBar.tsx
@@ -12,9 +12,7 @@ import { IconButton } from 'twenty-ui/components';
import { themeCssVariables } from 'twenty-ui/theme';
import { isAiChatPath } from '~/utils/isAiChatPath';
-// The bar floats over the page, so the container has to let taps through to
-// whatever is scrolling underneath it. flex-start rather than left so the bar
-// follows the writing direction in RTL locales.
+// Lets taps reach the page scrolling underneath; flex-start follows the writing direction.
const StyledFloatingContainer = styled.div`
bottom: 0;
display: flex;
@@ -100,8 +98,7 @@ export const MobileNavigationBar = () => {
);
const { items, activeItemName } = useMobileNavigationBarItems();
- // The chat page keeps the keyboard up most of the time, which leaves no room
- // for the bar, and it carries its own close button to leave by.
+ // The chat page keeps the keyboard up and carries its own close button.
const isHidden =
isSidePanelOpened ||
!isMobileNavigationBarVisible ||
diff --git a/packages/twenty-front/src/modules/navigation/components/MobileNavigationBarScrollEffect.tsx b/packages/twenty-front/src/modules/navigation/components/MobileNavigationBarScrollEffect.tsx
index 085e76e127f..93e6c1ab159 100644
--- a/packages/twenty-front/src/modules/navigation/components/MobileNavigationBarScrollEffect.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/MobileNavigationBarScrollEffect.tsx
@@ -17,13 +17,8 @@ export const MobileNavigationBarScrollEffect = () => {
isMobileNavigationBarVisibleState,
);
- // The app has many independent scroll containers, so rather than wiring each
- // of them up we listen on the capture phase, where every scroll event passes
- // through the document on its way down.
- //
- // Re-subscribing on navigation and on side panel transitions is what resets
- // the tracking. The accumulated direction of the previous view must not carry
- // over, or the next small scroll would cross the threshold on its own.
+ // Capture phase sees every container's scrolls. Re-subscribing on navigation and side panel toggles resets the
+ // accumulated direction, otherwise the next small scroll in the new view would cross the threshold on its own.
useEffect(() => {
setIsMobileNavigationBarVisible(true);
diff --git a/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarClearance.ts b/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarClearance.ts
index 0faca95e46a..c8ddbae74a1 100644
--- a/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarClearance.ts
+++ b/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarClearance.ts
@@ -1,6 +1,4 @@
import { MOBILE_NAVIGATION_BAR_HEIGHT } from '@/navigation/constants/MobileNavigationBarHeight';
import { MOBILE_NAVIGATION_BAR_PADDING } from '@/navigation/constants/MobileNavigationBarPadding';
-// The bar floats over the page, so a surface that pins content to the bottom
-// has to reserve what it covers.
export const MOBILE_NAVIGATION_BAR_CLEARANCE = `calc(${MOBILE_NAVIGATION_BAR_HEIGHT} + 2 * ${MOBILE_NAVIGATION_BAR_PADDING} + env(safe-area-inset-bottom, 0px))`;
diff --git a/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarHeight.ts b/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarHeight.ts
index baa6e75d44b..47d54afd76b 100644
--- a/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarHeight.ts
+++ b/packages/twenty-front/src/modules/navigation/constants/MobileNavigationBarHeight.ts
@@ -1,5 +1,4 @@
import { themeCssVariables } from 'twenty-ui/theme';
-// NavigationBar builds its row out of the item height plus its own padding and
-// border, so the height has to be rebuilt from the same tokens here.
+// Mirrors NavigationBar's row: item height plus its padding and border.
export const MOBILE_NAVIGATION_BAR_HEIGHT = `calc(${themeCssVariables.spacing[10]} + 2 * ${themeCssVariables.spacing[1]} + 2px)`;
diff --git a/packages/twenty-front/src/modules/navigation/hooks/__tests__/useDefaultHomePagePath.test.ts b/packages/twenty-front/src/modules/navigation/hooks/__tests__/useDefaultHomePagePath.test.ts
index 6b5f11c899d..706a5b0338c 100644
--- a/packages/twenty-front/src/modules/navigation/hooks/__tests__/useDefaultHomePagePath.test.ts
+++ b/packages/twenty-front/src/modules/navigation/hooks/__tests__/useDefaultHomePagePath.test.ts
@@ -380,9 +380,7 @@ describe('useDefaultHomePagePath', () => {
);
});
});
- // Regression: during the post-login transition window object metadata may
- // not yet be loaded. We must not redirect the user to /settings/profile
- // (the genuine empty-fallback) until metadata has actually loaded.
+ // Metadata may not be loaded yet right after login; don't fall back to /settings/profile.
it('should defer to AppPath.Index when currentUser is defined but object metadata is not loaded yet', async () => {
const { result } = renderHooks({
withCurrentUser: true,
diff --git a/packages/twenty-front/src/modules/navigation/hooks/useActiveNavigationDrawerMode.ts b/packages/twenty-front/src/modules/navigation/hooks/useActiveNavigationDrawerMode.ts
index a344dbf8408..31493337123 100644
--- a/packages/twenty-front/src/modules/navigation/hooks/useActiveNavigationDrawerMode.ts
+++ b/packages/twenty-front/src/modules/navigation/hooks/useActiveNavigationDrawerMode.ts
@@ -9,9 +9,7 @@ import {
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { isAiChatPath } from '~/utils/isAiChatPath';
-// Settings and the AI chat own a full page each, so the route decides those two
-// modes. The stored tab only has the final say when neither page is open, which
-// is what keeps the chat history listed while the user works on another page.
+// Settings and AI chat pages decide their mode; elsewhere the stored tab wins so chat history stays listed.
export const useActiveNavigationDrawerMode = (): NavigationDrawerActiveTab => {
const { pathname } = useLocation();
const isSettingsDrawer = useIsSettingsDrawer();
diff --git a/packages/twenty-front/src/modules/navigation/hooks/useDefaultHomePagePath.ts b/packages/twenty-front/src/modules/navigation/hooks/useDefaultHomePagePath.ts
index 1f3642f09ba..11a21fb41e2 100644
--- a/packages/twenty-front/src/modules/navigation/hooks/useDefaultHomePagePath.ts
+++ b/packages/twenty-front/src/modules/navigation/hooks/useDefaultHomePagePath.ts
@@ -109,9 +109,7 @@ export const useDefaultHomePagePath = () => {
return AppPath.Home;
}
- // Both stores are transiently empty during the post-login window;
- // deciding the redirect before they are loaded could strand users on a
- // wrong fallback (/settings/profile or the alphabetically-first object).
+ // Both stores are empty right after login; deciding now would pick a wrong fallback.
if (!areObjectMetadataItemsLoaded || !areNavigationMenuItemsLoaded) {
return AppPath.Index;
}
diff --git a/packages/twenty-front/src/modules/navigation/hooks/useIsNavigationDrawerContentExpanded.ts b/packages/twenty-front/src/modules/navigation/hooks/useIsNavigationDrawerContentExpanded.ts
index cbbed5958f5..a3a67295701 100644
--- a/packages/twenty-front/src/modules/navigation/hooks/useIsNavigationDrawerContentExpanded.ts
+++ b/packages/twenty-front/src/modules/navigation/hooks/useIsNavigationDrawerContentExpanded.ts
@@ -1,10 +1,7 @@
import { useNavigationDrawerExpanded } from '@/navigation/hooks/useNavigationDrawerExpanded';
import { useIsMobile } from 'twenty-ui/utilities';
-// Whether the navigation content renders its full width rather than the icon
-// rail. Mobile has no rail: the content is either a full-width drawer or the
-// home page, so it always renders expanded there. Use this for the content,
-// and useNavigationDrawerExpanded for the drawer container itself.
+// For the content (useNavigationDrawerExpanded is for the drawer container); mobile has no icon rail, so it always renders expanded there.
export const useIsNavigationDrawerContentExpanded = () => {
const isMobile = useIsMobile();
const isNavigationDrawerExpanded = useNavigationDrawerExpanded();
diff --git a/packages/twenty-front/src/modules/navigation/hooks/useMobileNavigationBarItems.ts b/packages/twenty-front/src/modules/navigation/hooks/useMobileNavigationBarItems.ts
index 5f44077dca1..004f36fd210 100644
--- a/packages/twenty-front/src/modules/navigation/hooks/useMobileNavigationBarItems.ts
+++ b/packages/twenty-front/src/modules/navigation/hooks/useMobileNavigationBarItems.ts
@@ -59,8 +59,7 @@ export const useMobileNavigationBarItems = (): {
isNavigationDrawerExpandedState,
);
- // The expansion state is shared with the desktop drawer, so the guard keeps a
- // tap outside settings from collapsing it there.
+ // Expansion state is shared with the desktop drawer, so a tap outside settings must not collapse it.
const closeSettingsDrawer = () => {
if (!isSettingsDrawer) {
return;
@@ -80,9 +79,7 @@ export const useMobileNavigationBarItems = (): {
onClick: () => {
closeSidePanelMenu();
closeSettingsDrawer();
- // Leaving settings replaces its entry the way desktop does, so that
- // going back does not drop the user straight into the settings they
- // just left.
+ // Replace like desktop so going back doesn't land in the settings just left.
navigate(AppPath.Home, { replace: isSettingsDrawer });
},
},
diff --git a/packages/twenty-front/src/modules/navigation/hooks/useNavigationDrawerModes.ts b/packages/twenty-front/src/modules/navigation/hooks/useNavigationDrawerModes.ts
index 7fda625bcae..3aea3771469 100644
--- a/packages/twenty-front/src/modules/navigation/hooks/useNavigationDrawerModes.ts
+++ b/packages/twenty-front/src/modules/navigation/hooks/useNavigationDrawerModes.ts
@@ -30,9 +30,7 @@ export const useNavigationDrawerModes = (): NavigationDrawerMode[] => {
WorkspaceActivationStatus.SUSPENDED,
);
- // A suspended workspace is held on the billing settings by the route guard,
- // so offering the modes it would bounce back from only flashes the user out
- // and in again.
+ // The route guard holds a suspended workspace on billing settings, so other modes would bounce back.
if (isWorkspaceSuspended) {
return [];
}
diff --git a/packages/twenty-front/src/modules/navigation/hooks/useSwitchNavigationDrawerMode.ts b/packages/twenty-front/src/modules/navigation/hooks/useSwitchNavigationDrawerMode.ts
index 4dda249d2cd..9d295a45d9e 100644
--- a/packages/twenty-front/src/modules/navigation/hooks/useSwitchNavigationDrawerMode.ts
+++ b/packages/twenty-front/src/modules/navigation/hooks/useSwitchNavigationDrawerMode.ts
@@ -90,8 +90,7 @@ export const useSwitchNavigationDrawerMode = () => {
switchToNewChat();
};
- // The AI mode also covers the chat history listed next to another page, so it
- // is the chat page rather than the active mode that makes a click a no-op.
+ // AI mode also lists chat history beside other pages, so only the chat page makes a click a no-op.
const switchNavigationDrawerMode = (mode: NavigationDrawerActiveTab) => {
switch (mode) {
case NAVIGATION_DRAWER_TABS.NAVIGATION_MENU:
@@ -109,10 +108,7 @@ export const useSwitchNavigationDrawerMode = () => {
switchToAiChat();
break;
case NAVIGATION_DRAWER_TABS.SETTINGS:
- // The mobile settings drawer outlives the route that opened it, a
- // browser back out of settings for one, so the page rather than the
- // drawer says whether there is anywhere left to go. Desktop has no
- // such split: there the two are the same thing.
+ // The mobile settings drawer can outlive its route (browser back), so check the page, not the drawer.
if (isSettingsPage) {
return;
}
diff --git a/packages/twenty-front/src/modules/navigation/utils/__tests__/getNextNavigationBarScrollState.test.ts b/packages/twenty-front/src/modules/navigation/utils/__tests__/getNextNavigationBarScrollState.test.ts
index 46888e47d67..add3a74200b 100644
--- a/packages/twenty-front/src/modules/navigation/utils/__tests__/getNextNavigationBarScrollState.test.ts
+++ b/packages/twenty-front/src/modules/navigation/utils/__tests__/getNextNavigationBarScrollState.test.ts
@@ -110,8 +110,7 @@ describe('getNextNavigationBarScrollState', () => {
).toEqual(INITIAL_NAVIGATION_BAR_SCROLL_STATE);
});
- // The accumulator is what a route change or a side panel transition resets,
- // so a small scroll on the next view must not inherit the previous direction.
+ // Route changes and side panel transitions reset the accumulator.
it('should require the full threshold again from the initial state', () => {
expect(
getNextNavigationBarScrollState({
diff --git a/packages/twenty-front/src/modules/navigation/utils/getNavigationDrawerHomeDestination.ts b/packages/twenty-front/src/modules/navigation/utils/getNavigationDrawerHomeDestination.ts
index 30d3da9829e..94fba874c79 100644
--- a/packages/twenty-front/src/modules/navigation/utils/getNavigationDrawerHomeDestination.ts
+++ b/packages/twenty-front/src/modules/navigation/utils/getNavigationDrawerHomeDestination.ts
@@ -8,10 +8,8 @@ type GetNavigationDrawerHomeDestinationParams = {
defaultHomePagePath: string;
};
-// Each mode memorizes where it was opened from, so a memorized url can point at
-// another mode when the user chained them (settings opened from the chat, or
-// the reverse). Going back there would leave the switcher on the mode the user
-// just asked to leave.
+// A memorized url can point into another mode when modes were chained (e.g. settings opened from chat), and
+// going back there would leave the switcher on the mode the user just asked to leave.
export const getNavigationDrawerHomeDestination = ({
memorizedUrl,
defaultHomePagePath,
diff --git a/packages/twenty-front/src/modules/navigation/utils/getNextNavigationBarScrollState.ts b/packages/twenty-front/src/modules/navigation/utils/getNextNavigationBarScrollState.ts
index 47170fd5858..97c60190db1 100644
--- a/packages/twenty-front/src/modules/navigation/utils/getNextNavigationBarScrollState.ts
+++ b/packages/twenty-front/src/modules/navigation/utils/getNextNavigationBarScrollState.ts
@@ -24,16 +24,14 @@ export const getNextNavigationBarScrollState = ({
lastScrollTopInPx,
currentState,
}: GetNextNavigationBarScrollStateParams): NavigationBarScrollState => {
- // A container restoring its scroll position would otherwise read as a jump
- // down from 0 the first time it is seen.
+ // A container restoring its scroll position would otherwise read as a jump down from 0.
if (!isDefined(lastScrollTopInPx)) {
return currentState;
}
const deltaInPx = scrollTopInPx - lastScrollTopInPx;
- // A horizontal scroll fires the same event without moving the container
- // vertically, so it has to leave the accumulated direction alone.
+ // Horizontal scrolls fire the same event and must not touch the accumulated direction.
if (deltaInPx === 0) {
return currentState;
}
diff --git a/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflows.ts b/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflows.ts
index 1ac7f501421..6647224997d 100644
--- a/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflows.ts
+++ b/packages/twenty-front/src/modules/object-core/workflows/hooks/useCoreWorkflows.ts
@@ -37,8 +37,7 @@ const ORDER_BY_FIELD_BY_FIELD_NAME: Record<string, CoreWorkflowOrderByField> = {
updatedAt: CoreWorkflowOrderByField.UPDATED_AT,
};
-// Two refreshes racing each other would otherwise append the same page twice,
-// and the ids are what make the merge idempotent.
+// Merging by id keeps racing refreshes from appending the same page twice.
const mergeFetchedCoreWorkflowPage = (
previousResult: GetCoreWorkflowsQuery,
{ fetchMoreResult }: { fetchMoreResult: GetCoreWorkflowsQuery },
@@ -135,9 +134,7 @@ export const useCoreWorkflows = ({
const loadedCount = connection?.edges.length ?? 0;
- // A plain refetch re-runs the first page and drops what fetchMore accumulated,
- // so ask for as many rows as are displayed and page back up to them when that
- // is more than one request may return.
+ // A plain refetch drops fetchMore pages, so re-request every displayed row.
const refetchLoadedCoreWorkflows = useCallback(async () => {
const targetCount = Math.max(loadedCount, CORE_WORKFLOWS_PAGE_SIZE);
diff --git a/packages/twenty-front/src/modules/object-metadata/hooks/useActiveFieldMetadataItems.ts b/packages/twenty-front/src/modules/object-metadata/hooks/useActiveFieldMetadataItems.ts
index 3e220a77b51..4a7acad6385 100644
--- a/packages/twenty-front/src/modules/object-metadata/hooks/useActiveFieldMetadataItems.ts
+++ b/packages/twenty-front/src/modules/object-metadata/hooks/useActiveFieldMetadataItems.ts
@@ -16,7 +16,6 @@ export const useActiveFieldMetadataItems = ({
objectMetadataItem.readableFields.filter(
(fieldMetadata) =>
isActiveFieldMetadataItem({ fieldMetadata }) ||
- // Allow label identifier field even if it's a system field
fieldMetadata.id ===
objectMetadataItem.labelIdentifierFieldMetadataId,
),
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/isActiveFieldMetadataItem.ts b/packages/twenty-front/src/modules/object-metadata/utils/isActiveFieldMetadataItem.ts
index 9c3de09d50c..38be025e690 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/isActiveFieldMetadataItem.ts
+++ b/packages/twenty-front/src/modules/object-metadata/utils/isActiveFieldMetadataItem.ts
@@ -16,8 +16,7 @@ export const isActiveFieldMetadataItem = ({
return false;
}
- // A junction relation is a system field that must stay visible, since it is the only
- // way to reach the records it links to.
+ // A junction relation is a system field but the only way to reach the records it links.
if (isConfiguredJunctionRelationField(fieldMetadata)) {
return true;
}
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/isAdvancedRelationTargetObjectMetadata.ts b/packages/twenty-front/src/modules/object-metadata/utils/isAdvancedRelationTargetObjectMetadata.ts
index 3bd10e60c21..c49b6cba996 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/isAdvancedRelationTargetObjectMetadata.ts
+++ b/packages/twenty-front/src/modules/object-metadata/utils/isAdvancedRelationTargetObjectMetadata.ts
@@ -1,9 +1,7 @@
import { CoreObjectNameSingular } from 'twenty-shared/types';
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-// System objects are valid relation targets, but they are technical tables that
-// would confuse less technical users, so pickers list them under an "Advanced"
-// section instead of next to business objects.
+// System objects are technical tables that would confuse non-technical users, so pickers list them under "Advanced".
export const isAdvancedRelationTargetObjectMetadata = (
objectMetadataItem: Pick<
EnrichedObjectMetadataItem,
diff --git a/packages/twenty-front/src/modules/object-metadata/utils/isObjectMetadataEligibleAsRelationTarget.ts b/packages/twenty-front/src/modules/object-metadata/utils/isObjectMetadataEligibleAsRelationTarget.ts
index 2bf2e4308e5..452f57fae4e 100644
--- a/packages/twenty-front/src/modules/object-metadata/utils/isObjectMetadataEligibleAsRelationTarget.ts
+++ b/packages/twenty-front/src/modules/object-metadata/utils/isObjectMetadataEligibleAsRelationTarget.ts
@@ -1,9 +1,6 @@
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
-// Whether an object can be picked as the destination when creating a relation,
-// mirroring the server rule (field creation only rejects remote parent objects).
-// Distinct from isObjectMetadataAvailableForRelation, which answers whether a
-// relation cell targeting the object renders in record UIs by default.
+// Mirrors the server rule; distinct from isObjectMetadataAvailableForRelation (relation cell rendering).
export const isObjectMetadataEligibleAsRelationTarget = (
objectMetadataItem: Pick<EnrichedObjectMetadataItem, 'isRemote'>,
) => !objectMetadataItem.isRemote;
diff --git a/packages/twenty-front/src/modules/object-record/cache/hooks/useAddDuplicatedRecordToCache.ts b/packages/twenty-front/src/modules/object-record/cache/hooks/useAddDuplicatedRecordToCache.ts
index adb92d4ea70..7f5bd5d0c99 100644
--- a/packages/twenty-front/src/modules/object-record/cache/hooks/useAddDuplicatedRecordToCache.ts
+++ b/packages/twenty-front/src/modules/object-record/cache/hooks/useAddDuplicatedRecordToCache.ts
@@ -10,7 +10,6 @@ import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
import { type ApolloCache } from '@apollo/client';
import { isDefined } from 'twenty-shared/utils';
-// Makes a server created copy show up in lists and the record store without a refetch.
export const useAddDuplicatedRecordToCache = ({
objectNameSingular,
}: {
@@ -41,8 +40,7 @@ export const useAddDuplicatedRecordToCache = ({
};
createOneRecordInCache(createdRecord);
- // The optimistic effect only reaches the record store through relations,
- // and a duplicate response carries none.
+ // The optimistic effect only reaches the record store through relations, which a duplicate response lacks.
upsertRecordsInStore({ partialRecords: [createdRecord] });
const recordNode = getRecordNodeFromRecord({
diff --git a/packages/twenty-front/src/modules/object-record/hooks/__tests__/useCreateManyRecords.test.tsx b/packages/twenty-front/src/modules/object-record/hooks/__tests__/useCreateManyRecords.test.tsx
index a2842b0c92e..fa5be61107d 100644
--- a/packages/twenty-front/src/modules/object-record/hooks/__tests__/useCreateManyRecords.test.tsx
+++ b/packages/twenty-front/src/modules/object-record/hooks/__tests__/useCreateManyRecords.test.tsx
@@ -27,8 +27,7 @@ jest.mocked(useRefetchAggregateQueries).mockReturnValue({
});
jest
- // uuid v11+ types add a Uint8Array overload to v4; pin to the string
- // signature so the mocked return values type-check.
+ // uuid v11+ adds a Uint8Array overload to v4; pin the string signature for the mocks.
.mocked(v4 as () => string)
.mockReturnValueOnce(variables.data[0].id)
.mockReturnValueOnce(variables.data[1].id);
diff --git a/packages/twenty-front/src/modules/object-record/hooks/useBuildRecordInputFromRLSPredicates.ts b/packages/twenty-front/src/modules/object-record/hooks/useBuildRecordInputFromRLSPredicates.ts
index 96c1d3d78f9..8605feafc2b 100644
--- a/packages/twenty-front/src/modules/object-record/hooks/useBuildRecordInputFromRLSPredicates.ts
+++ b/packages/twenty-front/src/modules/object-record/hooks/useBuildRecordInputFromRLSPredicates.ts
@@ -179,7 +179,6 @@ export const useBuildRecordInputFromRLSPredicates = ({
}
});
- // Filters with rlsDynamicValue are already handled above
const staticFilters = rlsPredicatesAsRecordFilters.filter(
(filter) => !isDefined(filter.rlsDynamicValue),
);
diff --git a/packages/twenty-front/src/modules/object-record/object-filter-dropdown/components/ObjectFilterDropdownInnerSelectOperandDropdown.tsx b/packages/twenty-front/src/modules/object-record/object-filter-dropdown/components/ObjectFilterDropdownInnerSelectOperandDropdown.tsx
index c9765a8c1ea..b64db44a44b 100644
--- a/packages/twenty-front/src/modules/object-record/object-filter-dropdown/components/ObjectFilterDropdownInnerSelectOperandDropdown.tsx
+++ b/packages/twenty-front/src/modules/object-record/object-filter-dropdown/components/ObjectFilterDropdownInnerSelectOperandDropdown.tsx
@@ -48,9 +48,7 @@ export const ObjectFilterDropdownInnerSelectOperandDropdown = () => {
const objectMetadataItems = useAtomStateValue(objectMetadataItemsSelector);
- // The target field may have been deleted from the workspace since the
- // filter was saved — return null and let the parent skip rendering
- // rather than throwing.
+ // The target field may have been deleted since the filter was saved.
const relationTargetFieldMetadataItem = isDefined(
relationTargetFieldMetadataIdUsedInDropdown,
)
diff --git a/packages/twenty-front/src/modules/object-record/object-options-dropdown/hooks/useObjectOptionsForBoard.ts b/packages/twenty-front/src/modules/object-record/object-options-dropdown/hooks/useObjectOptionsForBoard.ts
index 13304b10ddc..1d44aba5799 100644
--- a/packages/twenty-front/src/modules/object-record/object-options-dropdown/hooks/useObjectOptionsForBoard.ts
+++ b/packages/twenty-front/src/modules/object-record/object-options-dropdown/hooks/useObjectOptionsForBoard.ts
@@ -139,8 +139,7 @@ export const useObjectOptionsForBoard = ({
const { updateRecordField } = useUpdateRecordField(recordBoardId);
const { upsertRecordField } = useUpsertRecordField(recordBoardId);
- // Todo : this seems over complex and should at least be extracted to an util with unit test.
- // Let's refactor this as we introduce the new viewBar
+ // TODO: overly complex; extract to a unit-tested util.
const handleBoardFieldVisibilityChange = useCallback(
async (
updatedFieldDefinition: Pick<
diff --git a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/utils/turnSortsIntoOrderBy.ts b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/utils/turnSortsIntoOrderBy.ts
index dbf19573603..6c55f3e4ae9 100644
--- a/packages/twenty-front/src/modules/object-record/object-sort-dropdown/utils/turnSortsIntoOrderBy.ts
+++ b/packages/twenty-front/src/modules/object-record/object-sort-dropdown/utils/turnSortsIntoOrderBy.ts
@@ -56,7 +56,6 @@ export const turnSortsIntoOrderBy = (
orderByDirection: direction,
});
}
- // Fallback if related object not found - sort by FK
return [{ [`${correspondingField.name}Id`]: direction }];
}
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/internal/isMetadataWritabilityRestricted.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/internal/isMetadataWritabilityRestricted.ts
index 240849eca95..b9023c360a9 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/internal/isMetadataWritabilityRestricted.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/internal/isMetadataWritabilityRestricted.ts
@@ -1,9 +1,8 @@
import { isDefined } from 'twenty-shared/utils';
import { MetadataWritability } from '~/generated-metadata/graphql';
-// Only OPEN metadata accepts writes from a user session: APPLICATION is
-// reserved to the owning application and SYSTEM to the platform itself.
-// Missing writability means the metadata predates the flag, which is OPEN.
+// Only OPEN accepts user-session writes: APPLICATION is reserved to the owning app, SYSTEM to the platform.
+// Missing writability predates the flag and means OPEN.
export const isMetadataWritabilityRestricted = (
writability: MetadataWritability | null | undefined,
): boolean =>
diff --git a/packages/twenty-front/src/modules/object-record/read-only/utils/isOneToManyRelationFieldReadOnlyDueToTargetUpdatePermission.ts b/packages/twenty-front/src/modules/object-record/read-only/utils/isOneToManyRelationFieldReadOnlyDueToTargetUpdatePermission.ts
index 3da00bea4d0..2915884a033 100644
--- a/packages/twenty-front/src/modules/object-record/read-only/utils/isOneToManyRelationFieldReadOnlyDueToTargetUpdatePermission.ts
+++ b/packages/twenty-front/src/modules/object-record/read-only/utils/isOneToManyRelationFieldReadOnlyDueToTargetUpdatePermission.ts
@@ -18,8 +18,7 @@ type IsOneToManyRelationFieldReadOnlyDueToTargetUpdatePermissionParams = {
objectPermissionsByObjectMetadataId: ObjectPermissionsByObjectMetadataId;
};
-// Attaching or detaching writes the join column owned by the inverse many-to-one
-// field, so a field-level restriction there blocks the edit too.
+// Attaching or detaching writes the inverse many-to-one's join column, so its field restriction applies.
const isTargetRecordUpdateBlocked = ({
objectPermissionsByObjectMetadataId,
targetObjectMetadataId,
@@ -45,8 +44,6 @@ const isTargetRecordUpdateBlocked = ({
);
};
-// One-to-many edits persist by updating the related (or junction) record, not the
-// source row — require canUpdate on that object metadata.
export const isOneToManyRelationFieldReadOnlyDueToTargetUpdatePermission = ({
fieldDefinition,
objectPermissionsByObjectMetadataId,
diff --git a/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnHeader.tsx b/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnHeader.tsx
index a9227b865b2..949ae1e3c2f 100644
--- a/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnHeader.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnHeader.tsx
@@ -48,9 +48,7 @@ const StyledHeaderActions = styled.div`
align-items: center;
display: flex;
flex-shrink: 0;
- // padding + negative margin cancel out in layout and exist only so
- // overflow:hidden clips 4px outside each button, leaving room for
- // LightIconButton's 3px focus ring
+ // Padding and negative margin cancel out in layout; they only let overflow:hidden keep LightIconButton's 3px focus ring.
margin: calc(-1 * ${themeCssVariables.spacing[1]});
max-width: 0;
min-width: 0;
@@ -150,8 +148,7 @@ export const RecordBoardColumnHeader = () => {
const recordTableWidgetContext = useContext(RecordTableWidgetContext);
- // Creating in a nested relation or junction widget requires picking the
- // related record, which only the table layout offers today.
+ // Creating through a nested relation or junction needs a record picker only the table layout offers.
const isCreateThroughRelationWidget =
isDefined(recordTableWidgetContext?.nestedRelationCreateThrough) ||
isDefined(recordTableWidgetContext?.junctionCreateThrough);
diff --git a/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnNewRecordButton.tsx b/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnNewRecordButton.tsx
index 60bcb47e163..0d2667190e4 100644
--- a/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnNewRecordButton.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-board/record-board-column/components/RecordBoardColumnNewRecordButton.tsx
@@ -56,8 +56,7 @@ export const RecordBoardColumnNewRecordButton = () => {
objectMetadataItem: objectMetadataItem,
});
- // Creating in a nested relation or junction widget requires picking the
- // related record, which only the table layout offers today.
+ // Creating through a nested relation or junction needs a record picker only the table layout offers.
const recordTableWidgetContext = useContext(RecordTableWidgetContext);
if (
diff --git a/packages/twenty-front/src/modules/object-record/record-board/record-board-column/hooks/useResizeBoardColumn.ts b/packages/twenty-front/src/modules/object-record/record-board/record-board-column/hooks/useResizeBoardColumn.ts
index 5eb7d78bd2e..d411279ae66 100644
--- a/packages/twenty-front/src/modules/object-record/record-board/record-board-column/hooks/useResizeBoardColumn.ts
+++ b/packages/twenty-front/src/modules/object-record/record-board/record-board-column/hooks/useResizeBoardColumn.ts
@@ -34,8 +34,7 @@ export const useResizeBoardColumn = () => {
const isResizing = isDefined(initialPointerPositionX);
- // captured once per drag: reading computed style on every move would
- // force a synchronous style recalc, and the zoom cannot change mid-drag
+ // Captured once per drag: reading computed style on every move forces a style recalc.
const [dragUiZoom, setDragUiZoom] = useState(1);
const handleResizeStart = useCallback(
diff --git a/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsx b/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsx
index c782797117b..d2e419aefdf 100644
--- a/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsx
@@ -24,8 +24,7 @@ export const RecordCalendarWidget = ({
const { objectNameSingular, recordIndexId, viewBarInstanceId } =
useRecordIndexContextOrThrow();
- // Hydrated per widget instance from the backing view (draft or persisted)
- // by the widget view load effect, so edit-mode previews work before save.
+ // Hydrated from the backing view (draft or persisted) so edit-mode previews work before save.
const recordIndexCalendarFieldMetadataId = useAtomComponentStateValue(
recordIndexCalendarFieldMetadataIdComponentState,
recordIndexId,
diff --git a/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidgetReadOnlyEffect.tsx b/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidgetReadOnlyEffect.tsx
index 23a33f59c8a..ef10a06764a 100644
--- a/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidgetReadOnlyEffect.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidgetReadOnlyEffect.tsx
@@ -16,13 +16,11 @@ export const RecordCalendarWidgetReadOnlyEffect = ({
recordCalendarId,
);
- // Synchronized before paint so read-only widgets never flash (or
- // briefly accept interaction on) their editable controls.
+ // Layout effect so read-only widgets never flash their editable controls.
useLayoutEffect(() => {
setIsRecordCalendarReadOnly(isReadOnly);
- // Reset to the default on unmount so the flag cannot outlive the
- // widget and leak into a later calendar mounted on the same instance id.
+ // Reset so the flag cannot leak into a later calendar on the same instance id.
return () => {
setIsRecordCalendarReadOnly(false);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarAddNew.tsx b/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarAddNew.tsx
index 048f1f2c699..b464be5cae1 100644
--- a/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarAddNew.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarAddNew.tsx
@@ -68,8 +68,7 @@ export const RecordCalendarAddNew = ({
})
: false;
- // Creating in a nested relation or junction widget requires picking the
- // related record, which only the table layout offers today.
+ // Creating through a nested relation or junction needs a record picker only the table layout offers.
const recordTableWidgetContext = useContext(RecordTableWidgetContext);
if (
diff --git a/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarTopBar.tsx b/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarTopBar.tsx
index dbdf3787ddc..9b3c06f04b0 100644
--- a/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarTopBar.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-calendar/components/RecordCalendarTopBar.tsx
@@ -72,9 +72,7 @@ export const RecordCalendarTopBar = () => {
isRecordCalendarReadOnlyComponentState,
);
- // The layout switcher persists via updateCurrentView (an index-page write),
- // so it must never render inside a dashboard widget; widget calendars drive
- // their layout from the side-panel settings instead.
+ // The layout switcher writes the index view, so widget calendars must never render it.
const widgetInstanceId = useAvailableComponentInstanceId(
WidgetComponentInstanceContext,
);
diff --git a/packages/twenty-front/src/modules/object-record/record-calendar/hooks/useRecordCalendarGroupByRecords.ts b/packages/twenty-front/src/modules/object-record/record-calendar/hooks/useRecordCalendarGroupByRecords.ts
index c88c0ebfd54..aa578403b1a 100644
--- a/packages/twenty-front/src/modules/object-record/record-calendar/hooks/useRecordCalendarGroupByRecords.ts
+++ b/packages/twenty-front/src/modules/object-record/record-calendar/hooks/useRecordCalendarGroupByRecords.ts
@@ -99,7 +99,6 @@ export const useRecordCalendarGroupByRecords = (
}),
);
- // Deduplicate records by ID to prevent duplicate keys in React
const uniqueRecordsMap = new Map<string, ObjectRecord>();
allRecords.forEach((record: ObjectRecord) => {
if (!uniqueRecordsMap.has(record.id)) {
diff --git a/packages/twenty-front/src/modules/object-record/record-calendar/states/isRecordCalendarReadOnlyComponentState.ts b/packages/twenty-front/src/modules/object-record/record-calendar/states/isRecordCalendarReadOnlyComponentState.ts
index 01be85efb46..ca871a0b7d1 100644
--- a/packages/twenty-front/src/modules/object-record/record-calendar/states/isRecordCalendarReadOnlyComponentState.ts
+++ b/packages/twenty-front/src/modules/object-record/record-calendar/states/isRecordCalendarReadOnlyComponentState.ts
@@ -1,12 +1,7 @@
import { RecordCalendarComponentInstanceContext } from '@/object-record/record-calendar/states/contexts/RecordCalendarComponentInstanceContext';
import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';
-// A fully read-only calendar: no card drag, no per-day record creation,
-// no layout switching — dashboard widgets render calendars as pure
-// projections. Unlike the board's view-settings flag
-// (isRecordBoardViewSettingsReadOnlyComponentState, which keeps record
-// data editable), this one disables data interactions too, which is why
-// it keeps the plain "read-only" name.
+// Unlike isRecordBoardViewSettingsReadOnlyComponentState, this also disables data interactions.
export const isRecordCalendarReadOnlyComponentState =
createAtomComponentState<boolean>({
key: 'isRecordCalendarReadOnlyComponentState',
diff --git a/packages/twenty-front/src/modules/object-record/record-calendar/utils/isFieldMetadataItemAvailableAsCalendarField.ts b/packages/twenty-front/src/modules/object-record/record-calendar/utils/isFieldMetadataItemAvailableAsCalendarField.ts
index 9712b44d988..94db980afce 100644
--- a/packages/twenty-front/src/modules/object-record/record-calendar/utils/isFieldMetadataItemAvailableAsCalendarField.ts
+++ b/packages/twenty-front/src/modules/object-record/record-calendar/utils/isFieldMetadataItemAvailableAsCalendarField.ts
@@ -4,9 +4,6 @@ import {
isFieldMetadataSupportedInGroupBy,
} from 'twenty-shared/utils';
-// Single availability rule for calendar date fields, shared by the
-// record index calendar picker and dashboard widget calendar settings:
-// active date fields, excluding system ones like deletedAt.
export const isFieldMetadataItemAvailableAsCalendarField = (
fieldMetadataItem: FieldMetadataItem,
) =>
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/components/RecordTargetsInlineCell.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/components/RecordTargetsInlineCell.tsx
index 16775cdb189..47fd432a98c 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/components/RecordTargetsInlineCell.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/components/RecordTargetsInlineCell.tsx
@@ -49,8 +49,7 @@ export const RecordTargetsInlineCell = ({
objectMetadataItem,
});
- // Opening pushes the picker onto the focus stack, so closing has to pop it or
- // the app keeps treating this dropdown as focused.
+ // Opening pushed the picker onto the focus stack, so closing must pop it.
const closeEditMode = () => {
setIsEditing(false);
@@ -80,8 +79,7 @@ export const RecordTargetsInlineCell = ({
>
<RecordInlineCell instanceIdPrefix={instanceIdPrefix} />
- {/* RecordInlineCell only renders display mode; the field input lives in
- an anchored portal that each container mounts for itself. */}
+ {/* RecordInlineCell only renders display mode; each container mounts its own input portal. */}
{isEditing && (
<RecordInlineCellAnchoredPortal
fieldMetadataItem={junctionField}
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/components/__tests__/RecordTargetsInlineCell.test.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/components/__tests__/RecordTargetsInlineCell.test.tsx
index 3d985be15fe..a048440b5bf 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/components/__tests__/RecordTargetsInlineCell.test.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/components/__tests__/RecordTargetsInlineCell.test.tsx
@@ -9,8 +9,7 @@ import { RecordTargetsInlineCell } from '@/object-record/record-field/ui/compone
import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';
import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
-// Opening the picker performs a record search over the network, which is out of
-// scope here and unreachable through MockedProvider.
+// Opening the picker searches records over the network, unreachable through MockedProvider.
jest.mock(
'@/object-record/record-picker/multiple-record-picker/hooks/useMultipleRecordPickerPerformSearch',
() => ({
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx
index 1283cf9f6a8..5679fbb180e 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/components/FormRichTextFieldInput.tsx
@@ -28,8 +28,7 @@ export const FormRichTextFieldInput = ({
}: FormRichTextFieldInputProps) => {
const handleChange = (value: string) => {
onChange({
- // RICH_TEXT still exposes the legacy BlockNote array contract. Keep the
- // compatibility projection here until that field is migrated to TipTap.
+ // TODO: drop once RICH_TEXT migrates off the legacy BlockNote array contract.
blocknote: convertTipTapDocumentToBlockNote(value),
markdown: null,
});
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts
index 0342c4c9764..fb7934964bf 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/form-types/hooks/useTextVariableEditor.ts
@@ -65,8 +65,7 @@ export const useTextVariableEditor = ({
onUpdate(editor);
},
editorProps: {
- // Re-applied props replace Tiptap's default attributes, so the role
- // has to be restated here or the editor loses it.
+ // Re-applied props replace Tiptap's default attributes, so the role must be restated.
attributes: {
role: 'textbox',
...(isDefined(ariaLabelledBy)
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useObjectMorphJunctionConfig.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useObjectMorphJunctionConfig.ts
index 64967835e79..1ba11d191cd 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useObjectMorphJunctionConfig.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useObjectMorphJunctionConfig.ts
@@ -12,8 +12,6 @@ export const useObjectMorphJunctionConfig = ({
const { objectMetadataItem } = useObjectMetadataItem({ objectNameSingular });
const { objectMetadataItems } = useObjectMetadataItems();
- // Record queries are built from this config, so it has to keep its identity
- // across renders or they would be rebuilt each time.
return useMemo(
() =>
getObjectMorphJunctionConfig({
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useUpdateJunctionRelationFromCell.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useUpdateJunctionRelationFromCell.ts
index 75d240a1b8b..f2566fe9ec6 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useUpdateJunctionRelationFromCell.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/hooks/useUpdateJunctionRelationFromCell.ts
@@ -50,7 +50,6 @@ export const useUpdateJunctionRelationFromCell = ({
const junctionObjectMetadata = junctionConfig?.junctionObjectMetadata;
const sourceFieldOnJunction = junctionConfig?.sourceField;
- // Use relation object name as fallback to prevent hook errors (hooks can't be conditional)
const junctionObjectNameSingular =
junctionObjectMetadata?.nameSingular ??
fieldDefinition.metadata.relationObjectMetadataNameSingular;
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx
index de025bb6579..410874491b4 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldInput.tsx
@@ -63,8 +63,7 @@ export const FilesFieldInput = () => {
if (isDefined(nextValue)) {
setDraftValue(nextValue);
- // This input renders nothing without files, so it has to be closed once
- // the last one is gone, the value itself being persisted by onSubmit
+ // This input renders nothing without files, so close it once the last is gone; persisting is left to onSubmit.
if (nextValue.length === 0) {
onEnter?.({ newValue: nextValue, skipPersist: true });
}
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsx
index 721651bdfa0..a061046b4ce 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/MultiItemFieldInput.tsx
@@ -58,8 +58,7 @@ type MultiItemFieldInputProps<T> = {
maxItemCount?: number;
};
-// Todo: the API of this component does not look healthy: we have renderInput, renderItem, formatInput, ...
-// This should be refactored with a hook instead that exposes those events in a context around this component and its children.
+// TODO: replace renderInput/renderItem/formatInput with a hook exposing them through context.
export const MultiItemFieldInput = <T,>({
items,
onChange,
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RichTextFieldEditor.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RichTextFieldEditor.tsx
index 9cd8841a561..51f00e5535f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RichTextFieldEditor.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RichTextFieldEditor.tsx
@@ -175,15 +175,11 @@ export const RichTextFieldEditor = ({
},
});
- // The BlockNote editor is uncontrolled; when a remote value is adopted,
- // replace its content in place instead of remounting to keep the instance.
+ // Replace the uncontrolled editor's content in place instead of remounting it.
const [lastAppliedResyncKey, setLastAppliedResyncKey] =
useState(draftResyncKey);
- // The editor reports programmatic replacements through the same change
- // callback as typing, so latch around the adoption: without it the adopted
- // body would be treated as a local edit, marked dirty and written straight
- // back, blocking the next remote update from being adopted.
+ // Programmatic replacements fire the typing callback, so latch to keep them from echoing back as local edits.
// oxlint-disable-next-line twenty/no-state-useref
const isApplyingUpstreamBodyRef = useRef(false);
@@ -239,10 +235,7 @@ export const RichTextFieldEditor = ({
| { blocknote?: string | null }
| undefined;
- // Only schedule the persist once the pre-edit body is captured above:
- // persisting optimistically rewrites the record, and doing that earlier
- // would make the attachment diff below compare the new body with itself,
- // leaving attachments removed from the body undeleted.
+ // Only after capturing the pre-edit body: persisting rewrites the record, so the diff would miss removed attachments.
updateDraft({ blocknote: newStringifiedBody });
await syncAttachments(newStringifiedBody, oldFieldValue?.blocknote);
@@ -255,9 +248,7 @@ export const RichTextFieldEditor = ({
return;
}
- // Serialization is debounced, so mark the draft dirty synchronously: a
- // remote adoption arriving in that window would otherwise replace content
- // the user is actively typing.
+ // Serialization is debounced, so mark dirty now or a remote adoption could replace in-progress typing.
markDirty();
handleBodyChangeDebounced(JSON.stringify(editor.document) ?? '');
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsx
index cb6c51a50e5..c19117bcd00 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/__stories__/LinksFieldInput.stories.tsx
@@ -121,7 +121,7 @@ const LinksInputWithContext = ({
};
const getPrimaryLinkBookmarkIcon = (canvasElement: HTMLElement) =>
- // It would be better to use an aria-label on the icon, but we'll do this for now
+ // TODO: query by an aria-label on the icon instead
canvasElement.querySelector('svg[class*="tabler-icon-bookmark"]');
const meta: Meta = {
@@ -548,7 +548,7 @@ export const MakeSecondaryLinkPrimary: Story = {
const openDropdownButtons = await canvas.findAllByRole('button', {
expanded: false,
});
- await userEvent.click(openDropdownButtons[1]); // Click the secondary link's dropdown
+ await userEvent.click(openDropdownButtons[1]);
const setPrimaryOption = await within(
canvasElement.ownerDocument.body,
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionConfig.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionConfig.ts
index f5f905e554a..da582a47462 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionConfig.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionConfig.ts
@@ -81,8 +81,7 @@ export const getJunctionConfig = ({
isValid: false,
};
- // Legacy workspaces can lack the target marker. Only infer a pure junction:
- // an unlabeled intermediate record with exactly one morph target.
+ // Legacy workspaces can lack the target marker; only infer a pure junction (unlabeled, one morph target).
const inferredMorphTargetFields = hasConfiguredTargetField
? []
: junctionObjectMetadata.fields.filter(
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionObjectMetadataIds.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionObjectMetadataIds.ts
index 937029faa5b..9e2398bb5aa 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionObjectMetadataIds.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getJunctionObjectMetadataIds.ts
@@ -3,8 +3,7 @@ import { getFieldRelations } from '@/object-record/record-field/ui/utils/junctio
import { isUsableJunctionConfig } from '@/object-record/record-field/ui/utils/junction/isUsableJunctionConfig';
import { type JunctionObjectMetadataItem } from '@/object-record/record-field/ui/utils/junction/types/JunctionObjectMetadataItem';
-// A junction object carries no marker of its own, so the relation graph is walked to
-// collect every object resolved as a junction.
+// A junction object carries no marker of its own, so walk the relation graph.
export const getJunctionObjectMetadataIds = (
objectMetadataItems: JunctionObjectMetadataItem[],
): Set<string> =>
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getObjectMorphJunctionConfig.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getObjectMorphJunctionConfig.ts
index 2f39fa6d243..1189122902a 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getObjectMorphJunctionConfig.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/getObjectMorphJunctionConfig.ts
@@ -75,8 +75,7 @@ export const getObjectMorphJunctionConfig = ({
inferredJunctionConfigs.push(resolvedJunctionConfig);
}
- // Older workspaces can lack the junction target marker. The relation graph is
- // still authoritative when it describes exactly one morph junction.
+ // Older workspaces can lack the junction target marker; infer when the graph shows exactly one morph junction.
return inferredJunctionConfigs.length === 1
? inferredJunctionConfigs[0]
: null;
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isJunctionRelationForbidden.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isJunctionRelationForbidden.ts
index 96abad2dafe..e4edf0b821c 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isJunctionRelationForbidden.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isJunctionRelationForbidden.ts
@@ -12,8 +12,6 @@ type ObjectPermissionsByObjectMetadataId = Record<
ObjectPermissions & { objectMetadataId: string }
>;
-// Returns true if a junction field's intermediate or final target object
-// is not readable by the current user.
export const isJunctionRelationForbidden = ({
fieldMetadataItem,
sourceObjectMetadataId,
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isValidJunctionTargetField.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isValidJunctionTargetField.ts
index de60b5d4237..183d2ddd6b4 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isValidJunctionTargetField.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/isValidJunctionTargetField.ts
@@ -11,9 +11,7 @@ export const isValidJunctionTargetField = ({
fieldMetadataItem: FieldMetadataItem;
sourceFieldMetadataId?: string;
}): boolean => {
- // The server validates universal flat metadata in
- // validateJunctionTargetSettings. Keep relation direction and source-group
- // exclusion aligned there when this resolved GraphQL representation changes.
+ // Keep relation direction and source-group exclusion aligned with the server's validateJunctionTargetSettings.
const relations = getFieldRelations(fieldMetadataItem);
return (
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/resolveReverseJunctionConfig.ts b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/resolveReverseJunctionConfig.ts
index 20d6e5fcd28..466b954a9fd 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/resolveReverseJunctionConfig.ts
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/utils/junction/resolveReverseJunctionConfig.ts
@@ -87,8 +87,7 @@ const findReciprocalField = ({
: undefined;
};
-// Junction relation metadata already names its inverse field. Following those
-// edges keeps unrelated fields elsewhere in the workspace out of resolution.
+// Following the named inverse fields keeps unrelated workspace fields out of resolution.
export const resolveReverseJunctionConfig = ({
junctionObjectMetadataId,
relationTargetFieldMetadataId,
diff --git a/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.ts b/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.ts
index b34b0079c1e..fddbca6e97f 100644
--- a/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.ts
+++ b/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.ts
@@ -106,18 +106,14 @@ const UUID_FILTER_OPERATOR_KEYS = new Set<string>([
'neq',
]);
-// A filter on a relation field name either holds UUID operators applied to
-// the related record id, or field names of the related record to match
-// against the related record itself, like { person: { companyId: { in: [...] } } }
-// produced by view filters traversing a relation.
+// Either UUID operators on the related id, or nested field filters from view filters traversing a relation.
const isNestedRelationFilter = (
filterValue: unknown,
): filterValue is RecordGqlOperationFilter =>
isObject(filterValue) &&
Object.keys(filterValue).some((key) => !UUID_FILTER_OPERATOR_KEYS.has(key));
-// A record fetched through a relation often carries the related record
-// without its join column, like { list: { id } } and no listId.
+// Records fetched through a relation often carry { list: { id } } without listId.
const getJoinColumnValue = ({
record,
joinColumnName,
@@ -149,10 +145,7 @@ const isRecordMatchingNestedRelationFilter = ({
objectMetadataItems: EnrichedObjectMetadataItem[];
isWithinNegatedFilter: boolean;
}): boolean => {
- // A null related record truthfully fails the nested predicate, matching
- // the backend NOT EXISTS semantics. A related record that was not loaded
- // leaves the outcome unknown: returning the negation parity keeps the
- // record excluded whether or not a surrounding not flips the result.
+ // Null fails the nested predicate (backend NOT EXISTS); unloaded returns the negation parity to stay excluded.
if (relationRecord === null) {
return false;
}
@@ -180,8 +173,7 @@ const isRecordMatchingNestedRelationFilter = ({
isWithinNegatedFilter,
});
- // A to-many relation matches when any of its loaded records does, the way
- // the backend EXISTS does.
+ // Matches when any loaded record does, like the backend EXISTS.
return getLoadedRelationRecords({
relationRecord,
relationTargetObjectNameSingular:
@@ -192,9 +184,7 @@ const isRecordMatchingNestedRelationFilter = ({
);
};
-// A relation value is a single record for a to-one relation, and for a to-many
-// relation either an array of records or a connection, depending on whether
-// the record comes from the store or from a GraphQL response.
+// To-many values are an array (store) or a connection (GraphQL response).
const getLoadedRelationRecords = ({
relationRecord,
relationTargetObjectNameSingular,
diff --git a/packages/twenty-front/src/modules/object-record/record-group/utils/isRecordGroupingOptionalForViewType.ts b/packages/twenty-front/src/modules/object-record/record-group/utils/isRecordGroupingOptionalForViewType.ts
index 59a55c7dc54..371ede43504 100644
--- a/packages/twenty-front/src/modules/object-record/record-group/utils/isRecordGroupingOptionalForViewType.ts
+++ b/packages/twenty-front/src/modules/object-record/record-group/utils/isRecordGroupingOptionalForViewType.ts
@@ -1,8 +1,6 @@
import { ViewType } from '@/views/types/ViewType';
-// A kanban board is its groups and a calendar is its dates, so those layouts
-// cannot drop their grouping; the layouts that render a flat run of records can,
-// and must keep offering the way back to none.
+// Kanban and calendar layouts are their grouping; flat layouts must keep offering none.
const VIEW_TYPES_WITH_OPTIONAL_RECORD_GROUPING: ViewType[] = [
ViewType.TABLE,
ViewType.LIST,
diff --git a/packages/twenty-front/src/modules/object-record/record-index/components/__stories__/RecordIndexEmptyStateDisplay.stories.tsx b/packages/twenty-front/src/modules/object-record/record-index/components/__stories__/RecordIndexEmptyStateDisplay.stories.tsx
index 5c51471c4cc..c775441b08a 100644
--- a/packages/twenty-front/src/modules/object-record/record-index/components/__stories__/RecordIndexEmptyStateDisplay.stories.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-index/components/__stories__/RecordIndexEmptyStateDisplay.stories.tsx
@@ -26,8 +26,7 @@ const playRenderAndClick: Story['play'] = async ({ args, canvasElement }) => {
expect(await canvas.findByText(args.title as string)).toBeVisible();
expect(canvas.getByText(args.subTitle as string)).toBeVisible();
- // The button renders a clipped ellipsis next to its title, so its
- // accessible name is not the bare title.
+ // The button's accessible name includes a clipped ellipsis, not just the title.
const button = canvas.getByText(args.buttonTitle as string).closest('button');
expect(button).not.toBeNull();
diff --git a/packages/twenty-front/src/modules/object-record/record-index/hooks/__tests__/useLoadRecordIndexStates.test.tsx b/packages/twenty-front/src/modules/object-record/record-index/hooks/__tests__/useLoadRecordIndexStates.test.tsx
index a89ded341ac..fa98c0a54ae 100644
--- a/packages/twenty-front/src/modules/object-record/record-index/hooks/__tests__/useLoadRecordIndexStates.test.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-index/hooks/__tests__/useLoadRecordIndexStates.test.tsx
@@ -14,8 +14,7 @@ import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectM
const recordIndexId = 'record-table-widget-record-index-id';
const objectMetadataItem = getMockObjectMetadataItemOrThrow('company');
-// View-scoped states resolve against the wrapper's ViewComponentInstanceContext,
-// not the recordIndexId passed to loadRecordIndexStates
+// View-scoped states resolve against the wrapper's ViewComponentInstanceContext, not recordIndexId
const viewInstanceId = 'instanceId';
const makeView = (
diff --git a/packages/twenty-front/src/modules/object-record/record-index/hooks/useOpenRecordFromIndexView.ts b/packages/twenty-front/src/modules/object-record/record-index/hooks/useOpenRecordFromIndexView.ts
index 3f71d9b9fc3..9ac1d8c47d9 100644
--- a/packages/twenty-front/src/modules/object-record/record-index/hooks/useOpenRecordFromIndexView.ts
+++ b/packages/twenty-front/src/modules/object-record/record-index/hooks/useOpenRecordFromIndexView.ts
@@ -59,9 +59,7 @@ export const useOpenRecordFromIndexView = () => {
parentViewSorts,
};
- // The record's related lists read this from the store of the surface they
- // render on, so it has to land on the destination rather than on the index
- // that is handing it over.
+ // Related lists read this from their own surface's store, so set it on the destination.
const setParentViewOn = (instanceId: string) =>
store.set(
contextStoreRecordShowParentViewComponentState.atomFamily({
diff --git a/packages/twenty-front/src/modules/object-record/record-list/components/RecordListResponsiveFieldsEffect.tsx b/packages/twenty-front/src/modules/object-record/record-list/components/RecordListResponsiveFieldsEffect.tsx
index b36a1198d8f..9fd5caa8ea6 100644
--- a/packages/twenty-front/src/modules/object-record/record-list/components/RecordListResponsiveFieldsEffect.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-list/components/RecordListResponsiveFieldsEffect.tsx
@@ -7,11 +7,7 @@ type RecordListResponsiveFieldsEffectProps = {
containerElement: HTMLElement | null;
};
-// Takes the element rather than a ref object. React attaches a host element's
-// ref only after the layout effects of its children have run, so reading the
-// parent's ref here on mount finds null and nothing re-runs the effect once it
-// is filled — the list would keep its default field count. A callback ref
-// stored in state re-renders instead, and the effect measures the real element.
+// Takes the element, not a ref: a parent's ref is still null in its children's layout effects on mount.
export const RecordListResponsiveFieldsEffect = ({
containerElement,
}: RecordListResponsiveFieldsEffectProps) => {
@@ -24,9 +20,7 @@ export const RecordListResponsiveFieldsEffect = ({
return;
}
- // clientWidth counts the container's own padding, which the rows never get
- // to use. Measuring the content box keeps the field widths handed to the
- // rows equal to the space they actually render in.
+ // Measure the content box: clientWidth includes padding the rows never get.
const updateDisplayedFields = () => {
const { paddingLeft, paddingRight } = getComputedStyle(containerElement);
diff --git a/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRowField.tsx b/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRowField.tsx
index 168d81e776e..4fc30dc5d96 100644
--- a/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRowField.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRowField.tsx
@@ -10,9 +10,7 @@ import { TooltipDelay } from '@/ui/layout/tooltip/constants/TooltipDelay';
import { styled } from '@linaria/react';
import { Tooltip } from 'twenty-ui/primitives/surfaces';
-// Shrinkable rather than fixed: a long record label can eat into the fields'
-// share of the row, and a field that refuses to give any of it back is clipped
-// off the left edge of the right-aligned group instead of narrowing.
+// Shrinkable so a long record label narrows fields instead of clipping them off the left edge.
const StyledFieldContainer = styled.div`
align-items: center;
display: flex;
diff --git a/packages/twenty-front/src/modules/object-record/record-list/utils/computeRecordListDisplayedFields.ts b/packages/twenty-front/src/modules/object-record/record-list/utils/computeRecordListDisplayedFields.ts
index 89bb3a704ca..d595a1a740e 100644
--- a/packages/twenty-front/src/modules/object-record/record-list/utils/computeRecordListDisplayedFields.ts
+++ b/packages/twenty-front/src/modules/object-record/record-list/utils/computeRecordListDisplayedFields.ts
@@ -7,9 +7,7 @@ import { type RecordListDisplayedFields } from '@/object-record/record-list/type
const ROW_HORIZONTAL_PADDING_WIDTH = 12;
const ROW_ITEM_GAP_WIDTH = 12;
-// Takes the width a row actually renders in, not the list container's own
-// width: a field told it may be wider than its slot is cut rather than
-// ellipsised.
+// Takes the row's rendered width, not the container's: an oversized field is cut, not ellipsised.
export const computeRecordListDisplayedFields = ({
rowWidth,
populatedFieldCount,
diff --git a/packages/twenty-front/src/modules/object-record/record-picker/single-record-picker/components/SingleRecordPickerMenuItems.tsx b/packages/twenty-front/src/modules/object-record/record-picker/single-record-picker/components/SingleRecordPickerMenuItems.tsx
index 0f407efca16..467512bf3c5 100644
--- a/packages/twenty-front/src/modules/object-record/record-picker/single-record-picker/components/SingleRecordPickerMenuItems.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-picker/single-record-picker/components/SingleRecordPickerMenuItems.tsx
@@ -97,8 +97,7 @@ export const SingleRecordPickerMenuItems = ({
selectableListInstanceId={selectableListComponentInstanceId}
selectableItemIdArray={selectableItemIds}
focusId={focusId}
- // The empty option leads the list, so preselecting it would make Enter
- // detach the relation instead of picking a record.
+ // The empty option leads, so preselecting it would make Enter detach the relation.
shouldPreselectFirstItem={!isDefined(emptyLabel)}
>
{emptyLabel && (
diff --git a/packages/twenty-front/src/modules/object-record/record-seeded-draft/hooks/useRecordSeededDraft.ts b/packages/twenty-front/src/modules/object-record/record-seeded-draft/hooks/useRecordSeededDraft.ts
index 13de00fe6d9..0699e43b616 100644
--- a/packages/twenty-front/src/modules/object-record/record-seeded-draft/hooks/useRecordSeededDraft.ts
+++ b/packages/twenty-front/src/modules/object-record/record-seeded-draft/hooks/useRecordSeededDraft.ts
@@ -6,14 +6,10 @@ import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
const PERSIST_DEBOUNCE_MS = 500;
type UseRecordSeededDraftArgs<TDraft extends object> = {
- // Derived from the record on every render; the single source of remote truth.
upstreamDraft: TDraft;
onPersist: (draft: TDraft) => void;
persistDebounceMs?: number;
- // Identity of the record being edited. When it changes, the draft is
- // reseeded from upstream and any pending persist is dropped so it cannot
- // write the previous record's content onto the new one. Consumers that
- // remount on record change (key={recordId}) do not need it.
+ // Changing it reseeds the draft and drops any pending persist of the previous record.
resetKey?: string;
};
@@ -22,23 +18,9 @@ type ScheduledPersist<TDraft> = {
scheduledResetGeneration: number;
};
-// Editing state seeded from a record, kept live against remote changes.
-//
-// Record data flows into local editing state exactly once per seed, so
-// changes persisted by someone else (the AI chat, another user, another tab)
-// arrive through the record without ever reaching the draft. This hook owns
-// the policy for that seam, the same way on every surface:
-// - a pristine draft adopts the remote value as soon as it arrives;
-// - a dirty draft wins, and overwrites the remote value when its debounced
-// persist flushes (last write wins);
-// - our own persists come back as an upstream value equal to the draft and
-// only mark the draft pristine again, never disrupting typing.
-//
-// Controlled inputs re-render from `draft`. Uncontrolled inputs remount via
-// `draftResyncKey`. Imperative editors (BlockNote) watch `draftResyncKey` and
-// replace their content when it changes; those that debounce their own
-// serialization call `markDirty` on the raw change so the gap before the
-// serialized value reaches `updateDraft` is never mistaken for pristine.
+// Remote changes reach a pristine draft at once; a dirty draft wins on its debounced persist (last write wins).
+// Our own persists echo back equal to the draft and only mark it pristine, never disrupting typing.
+// Editors that debounce their own serialization call markDirty on raw changes so the gap never reads as pristine.
export const useRecordSeededDraft = <TDraft extends object>({
upstreamDraft,
onPersist,
@@ -53,12 +35,8 @@ export const useRecordSeededDraft = <TDraft extends object>({
const [resetGeneration, setResetGeneration] = useState(0);
const [hasUncommittedEdit, setHasUncommittedEdit] = useState(false);
- // The reset check below runs during render, where cancelling the timer
- // would be an unsafe side effect; instead each scheduled persist remembers
- // the reset generation it was scheduled under and is dropped once that
- // generation is over. A counter rather than the key itself, so returning to
- // a previously edited record (A to B back to A) still drops A's first
- // pending persist instead of letting it land on the reseeded draft.
+ // Cancelling the timer during render is unsafe, so each persist carries its reset generation and is dropped once stale.
+ // A counter rather than the key, so going A to B back to A still drops A's first pending persist.
const persistDebounced = useDebouncedCallback(
({
draftToPersist,
@@ -108,8 +86,7 @@ export const useRecordSeededDraft = <TDraft extends object>({
});
};
- // Holds off adoption for editors whose serialized value only arrives later,
- // without scheduling a persist of a value we do not have yet.
+ // For editors whose serialized value arrives later: blocks adoption without scheduling a persist.
const markDirty = () => {
setHasUncommittedEdit(true);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-show/components/RecordIdentifierBarTitle.tsx b/packages/twenty-front/src/modules/object-record/record-show/components/RecordIdentifierBarTitle.tsx
index 992259f405f..b0611e59d99 100644
--- a/packages/twenty-front/src/modules/object-record/record-show/components/RecordIdentifierBarTitle.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-show/components/RecordIdentifierBarTitle.tsx
@@ -94,8 +94,7 @@ export const RecordIdentifierBarTitle = ({
shape: recordIdentifier?.avatarShape ?? 'circle',
}}
title={
- // A writable title has to stay click-to-edit, so only a read-only one
- // can double as a link to the record page.
+ // A writable title stays click-to-edit, so only a read-only one links to the record page.
isInSidePanel && titleFieldContextValue.isRecordFieldReadOnly ? (
<UndecoratedLink
to={getAppPath(AppPath.RecordShowPage, {
diff --git a/packages/twenty-front/src/modules/object-record/record-show/components/__stories__/PageLayoutRecordPageRendererEmailThread.stories.tsx b/packages/twenty-front/src/modules/object-record/record-show/components/__stories__/PageLayoutRecordPageRendererEmailThread.stories.tsx
index 8f542dd6e1f..8aa5f1e3641 100644
--- a/packages/twenty-front/src/modules/object-record/record-show/components/__stories__/PageLayoutRecordPageRendererEmailThread.stories.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-show/components/__stories__/PageLayoutRecordPageRendererEmailThread.stories.tsx
@@ -220,8 +220,7 @@ const buildThreadConnectedAccountHandlers = (connectedAccount: {
),
];
-// The mocked minimal metadata ships no page layouts, so the record page has no
-// layout to render until this seeds one holding the email thread widget.
+// The minimal metadata mocks ship no page layouts, so this seeds one holding the email thread widget.
const SeedEmailThreadPageLayoutEffect = () => {
const { replaceDraft, applyChanges } = useUpdateMetadataStoreDraft();
const isMinimalMetadataReady = useAtomStateValue(isMinimalMetadataReadyState);
@@ -312,8 +311,7 @@ export const ReplyOpensComposerInSidePanel: Story = {
await userEvent.click(replyButton);
- // The render loop this guards against killed the widget subtree, so the
- // composer never survived past its first frame.
+ // Guards against a render loop that killed the widget subtree.
await expect(
await canvas.findByRole('button', { name: /send/i }, { timeout: 20000 }),
).toBeVisible();
diff --git a/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetJunctionAddNewRow.tsx b/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetJunctionAddNewRow.tsx
index 58ec5c6ab6e..0acc221053a 100644
--- a/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetJunctionAddNewRow.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetJunctionAddNewRow.tsx
@@ -40,8 +40,7 @@ export const RecordTableWidgetJunctionAddNewRow = ({
junctionCreateThrough,
});
- // Linking an existing record only writes the junction object, so the
- // junction's own permissions gate the row rather than the target object's.
+ // Linking only writes the junction object, so its permissions gate the row.
if (
isObjectMetadataReadOnly({
objectPermissions: junctionObjectPermissions,
diff --git a/packages/twenty-front/src/modules/object-record/record-table-widget/contexts/RecordTableWidgetContext.ts b/packages/twenty-front/src/modules/object-record/record-table-widget/contexts/RecordTableWidgetContext.ts
index 7c0dad0b08d..18b3609682d 100644
--- a/packages/twenty-front/src/modules/object-record/record-table-widget/contexts/RecordTableWidgetContext.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table-widget/contexts/RecordTableWidgetContext.ts
@@ -2,20 +2,14 @@ import { type AggregateOperations } from '@/object-record/record-table/constants
import { createContext } from 'react';
import { type RecordGqlOperationFilter } from 'twenty-shared/types';
-// Creating a record in a nested relation widget requires picking the related
-// record to create through: the created record's join column has to point at
-// a record of the widget's first hop (e.g. picking one of the company's
-// people before creating an opportunity on a Company → People → Opportunities
-// widget).
+// Creating in a nested relation widget first picks a first-hop record for the join column (e.g. Company → People → Opportunities).
export type RecordTableWidgetNestedRelationCreateThrough = {
relationObjectMetadataNameSingular: string;
relationRecordsFilter: RecordGqlOperationFilter;
nestedRelationJoinColumnName: string;
};
-// A junction relation widget lists the records behind the junction, so adding
-// one means picking an existing target record and creating the junction
-// record linking it to the current record, not creating a target record.
+// Adding to a junction widget picks an existing target and creates the junction record linking it, not a new target.
export type RecordTableWidgetJunctionCreateThrough = {
junctionObjectMetadataId: string;
junctionObjectMetadataNameSingular: string;
diff --git a/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useCreateJunctionRecordFromTableWidget.ts b/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useCreateJunctionRecordFromTableWidget.ts
index 35f9cd7bae6..5282a6b2d03 100644
--- a/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useCreateJunctionRecordFromTableWidget.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useCreateJunctionRecordFromTableWidget.ts
@@ -12,8 +12,7 @@ export const useCreateJunctionRecordFromTableWidget = ({
junctionCreateThrough.junctionObjectMetadataNameSingular,
});
- // Upserting keeps a pick idempotent when the picker excluded a record that
- // was linked meanwhile, the way the junction field input links records.
+ // Upsert keeps a pick idempotent when the record was linked meanwhile.
const createJunctionRecord = useCallback(
async (targetRecordId: string) => {
await createManyRecords({
diff --git a/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useListenToJunctionRecordOperation.ts b/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useListenToJunctionRecordOperation.ts
index d16b7eef9fd..957aa34d2da 100644
--- a/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useListenToJunctionRecordOperation.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table-widget/hooks/useListenToJunctionRecordOperation.ts
@@ -4,8 +4,7 @@ import { RecordTableWidgetContext } from '@/object-record/record-table-widget/co
import { useContext } from 'react';
import { isDefined } from 'twenty-shared/utils';
-// A junction widget's rows come and go with junction records, which are
-// written on another object than the one the table lists.
+// Junction records are written on another object than the one the table lists.
export const useListenToJunctionRecordOperation = ({
onJunctionRecordOperation,
}: {
@@ -22,8 +21,7 @@ export const useListenToJunctionRecordOperation = ({
return;
}
- // Only operations carrying the written record can be scoped to the
- // widget's source record; the others may concern it, so they refresh.
+ // Operations without the written record can't be scoped, so they refresh.
const writtenRecord =
operation.type === 'create-one'
? operation.createdRecord
diff --git a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableContextProvider.tsx b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableContextProvider.tsx
index bbc70980775..e5e692e689c 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableContextProvider.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableContextProvider.tsx
@@ -61,8 +61,7 @@ export const RecordTableContextProvider = ({
const isTouchDevice = useIsTouchDevice();
- // Navigating on mouse down only buys a frame on a real pointer: a tap
- // synthesises its mouse events after the finger is already gone.
+ // A tap synthesises its mouse events after the finger lifts, so mouse down only helps real pointers.
const triggerEvent =
openRecordIn === OpenRecordIn.SIDE_PANEL || isTouchDevice
? 'CLICK'
diff --git a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupAddNew.tsx b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupAddNew.tsx
index 93da0448708..8e96dc70676 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupAddNew.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupAddNew.tsx
@@ -86,8 +86,7 @@ export const RecordTableNoRecordGroupAddNew = () => {
return null;
}
- // Linking through a junction never creates a record of the table's object,
- // so the target object's creatability does not apply.
+ // Linking through a junction never creates a record of the table's object, so its creatability does not apply.
if (isDefined(junctionCreateThrough)) {
return (
<RecordTableWidgetJunctionAddNewRow
diff --git a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupRows.tsx b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupRows.tsx
index 19bfc66b4e8..a250282a006 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupRows.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableNoRecordGroupRows.tsx
@@ -48,8 +48,7 @@ export const RecordTableNoRecordGroupRows = () => {
const virtualRowIndices = getContiguousIncrementalValues(numberOfRows);
- // Catches drops past the last row, where no row sortable is under the
- // pointer; the drop target inside only renders the insertion indicator.
+ // Catches drops past the last row, where no row sortable is under the pointer.
const { ref: endDropZoneRef } = useDroppable({
id: RECORD_TABLE_NO_RECORD_GROUP_DROPPABLE_ID,
accept: RECORD_TABLE_ROW_DND_TYPE,
@@ -70,8 +69,7 @@ export const RecordTableNoRecordGroupRows = () => {
);
})}
<StyledEndDropZone ref={endDropZoneRef}>
- {/* Zero footprint at rest; expands during a row drag so the zone
- stays droppable even when the add-new row is hidden. */}
+ {/* Expands during a row drag so the zone stays droppable when the add-new row is hidden. */}
<DragDropItemDropTarget
index={totalNumberOfRecordsToVirtualize}
droppableId={RECORD_TABLE_NO_RECORD_GROUP_DROPPABLE_ID}
diff --git a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableStyleWrapper.tsx b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableStyleWrapper.tsx
index 804e5dfe8f5..13769c8b075 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableStyleWrapper.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableStyleWrapper.tsx
@@ -87,9 +87,7 @@ const StyledTable = styled.div<{
var(${RECORD_TABLE_CHECKBOX_WIDTH_CSS_VAR})
);
- // On mobile the frozen column travels with the content instead of being
- // resized, so the data columns keep pace with the finger exactly and nothing
- // reflows mid-gesture. It pins once only the remnant is left.
+ // On mobile the frozen column travels with the content so nothing reflows mid-gesture.
@media (max-width: ${MOBILE_VIEWPORT}px) {
${RECORD_TABLE_FIRST_COLUMN_LEFT_CSS_VAR}: calc(
var(${RECORD_TABLE_DRAG_DROP_WIDTH_CSS_VAR}) +
@@ -101,8 +99,7 @@ const StyledTable = styled.div<{
);
}
- // The mobile navigation bar floats over the page, so the table reserves its
- // footprint to keep its last row reachable, grouped or not.
+ // Reserve the floating mobile navigation bar's footprint so the last row stays reachable.
@media (max-width: ${MOBILE_VIEWPORT}px) {
padding-bottom: ${themeCssVariables.spacing[20]};
}
@@ -206,9 +203,8 @@ const StyledTable = styled.div<{
}
@media (max-width: ${MOBILE_VIEWPORT}px) {
- // clip, not hidden: hidden would make the cell its own scroll container and
- // the anchor below would stick to it instead of the table. The margin keeps
- // the scroll shadow, which paints outside the box.
+ // clip, not hidden: hidden makes the cell a scroll container the sticky anchor would stick to.
+ // The clip margin keeps the scroll shadow, which paints outside the box.
div.header-cell.${getRecordTableColumnFieldWidthClassName(0)},
div.table-cell.${getRecordTableColumnFieldWidthClassName(0)},
div.footer-cell.${getRecordTableColumnFieldWidthClassName(0)},
@@ -217,10 +213,8 @@ const StyledTable = styled.div<{
overflow-clip-margin: 4px;
}
- // Re-pins the cell contents at the table's left edge while the cell slides
- // under it, so the record name holds still and truncates from the right.
- // The anchor has to stay zero-width or sticky's containing-block constraint
- // drags it along with the cell once the cell is narrower than the name.
+ // Pins the content at the table's left edge so the name holds still and truncates from the right.
+ // Must stay zero-width, or sticky's containing-block constraint drags it along with the cell.
div.table-cell.${getRecordTableColumnFieldWidthClassName(0)}
> .${RECORD_TABLE_CELL_CONTENT_CLASS_NAME},
div.table-cell-0-0
@@ -234,8 +228,7 @@ const StyledTable = styled.div<{
width: 0;
}
- // Absolute so it gives the chip its full layout width without adding any
- // width back to the anchor.
+ // Absolute so the chip gets its full width without widening the anchor.
div.table-cell.${getRecordTableColumnFieldWidthClassName(0)}
> .${RECORD_TABLE_CELL_CONTENT_CLASS_NAME}
> .${RECORD_TABLE_CELL_DISPLAY_CLASS_NAME},
@@ -253,9 +246,7 @@ const StyledTable = styled.div<{
);
}
- // Shrink-wrapped so the label's and the aggregate's own boxes stay narrower
- // than the pinned remnant; at full column width sticky's containing-block
- // constraint would drag them off with the cell instead of holding them.
+ // Shrink-wrapped: at full column width sticky's containing-block constraint would drag these off with the cell.
div.header-cell.${getRecordTableColumnFieldWidthClassName(0)}
.${RECORD_TABLE_CELL_CONTENT_CLASS_NAME},
div.footer-cell.${getRecordTableColumnFieldWidthClassName(0)}
diff --git a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableWithWrappers.tsx b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableWithWrappers.tsx
index fcebd7d1b57..c0a2ad1fb3f 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableWithWrappers.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/components/RecordTableWithWrappers.tsx
@@ -16,8 +16,7 @@ import { styled } from '@linaria/react';
const StyledRecordTablePrintBoundary = styled.div`
display: contents;
- // Without this, swiping the table back to its first column hands the gesture
- // to the browser and navigates back on iOS.
+ // Otherwise swiping back to the first column triggers iOS back navigation.
.scroll-wrapper-x-enabled {
overscroll-behavior-x: contain;
}
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableBodyDragDropContextProvider.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableBodyDragDropContextProvider.tsx
index c29a064e110..51835efcf26 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableBodyDragDropContextProvider.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableBodyDragDropContextProvider.tsx
@@ -115,8 +115,7 @@ export const RecordTableBodyDragDropContextProvider = ({
return;
}
- // Row targets and end drop zones mark the gap before them; convert that
- // gap into the index the dragged row will occupy after the move.
+ // Drop targets mark the gap before them; convert it to the dragged row's final index.
const destinationIndex = getDestinationIndex({
dropTargetIndex: resolvedDrop.dropTargetIndex,
sourceIndex: sourceData.index,
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useMoveHoverToCurrentCell.ts b/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useMoveHoverToCurrentCell.ts
index 2698dbee165..72480ddc28b 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useMoveHoverToCurrentCell.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useMoveHoverToCurrentCell.ts
@@ -26,9 +26,7 @@ export const useMoveHoverToCurrentCell = (recordTableId: string) => {
const moveHoverToCurrentCell = useCallback(
(cellPosition: TableCellPosition) => {
- // A tap synthesises a mousemove before its mousedown. Hovering on it
- // would mount the hover portal under the finger, and the click that
- // follows would hit that new subtree instead of what the user aimed at.
+ // A tap synthesises mousemove before mousedown; hovering would mount a portal that steals the click.
if (isTouchDevice || store.get(isSomeCellInEditMode)) {
return;
}
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useOpenRecordTableCell.ts b/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useOpenRecordTableCell.ts
index 083d55bff4a..86bd8fc41f0 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useOpenRecordTableCell.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-cell/hooks/useOpenRecordTableCell.ts
@@ -110,7 +110,6 @@ export const useOpenRecordTableCell = (recordTableId: string) => {
return;
}
- // Block editing for read-only records, but allow navigation (handled above)
if (isReadOnly) {
return;
}
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-header/components/RecordTableHeader.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-header/components/RecordTableHeader.tsx
index 536b85e3dd2..ba4eaae19ab 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-header/components/RecordTableHeader.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-header/components/RecordTableHeader.tsx
@@ -12,8 +12,7 @@ import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/use
import { styled } from '@linaria/react';
import { themeCssVariables } from 'twenty-ui/theme';
-// The header takes the first slot of the virtualized row grid, whose pitch is
-// RECORD_TABLE_ROW_HEIGHT + 1 (row plus its bottom border).
+// Takes the first slot of the virtualized row grid, pitched at RECORD_TABLE_ROW_HEIGHT + 1 (bottom border).
const StyledHeaderContainer = styled.div`
background-color: ${themeCssVariables.background.primary};
box-shadow: 0 -1px 0 ${themeCssVariables.background.primary};
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-header/hooks/useResizeTableHeader.ts b/packages/twenty-front/src/modules/object-record/record-table/record-table-header/hooks/useResizeTableHeader.ts
index c99d7de6134..cd4dff02c14 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-header/hooks/useResizeTableHeader.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-header/hooks/useResizeTableHeader.ts
@@ -81,8 +81,7 @@ export const useResizeTableHeader = () => {
const isRecordTableCheckboxColumnHidden =
useIsRecordTableCheckboxColumnHidden(recordTableId);
- // captured once per drag: reading computed style on every move would
- // force a synchronous style recalc, and the zoom cannot change mid-drag
+ // Captured once per drag: zoom cannot change mid-drag, and reading computed style per move forces a recalc.
const [dragUiZoom, setDragUiZoom] = useState(1);
const handleResizeHandlerStart = useCallback<PointerEventListener>(
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableDraggableTr.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableDraggableTr.tsx
index 3f96bf5a065..ecc16daa522 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableDraggableTr.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableDraggableTr.tsx
@@ -17,10 +17,7 @@ import { DND_KIT_PLUGINS_WITHOUT_OPTIMISTIC } from '@/ui/utilities/drag-and-drop
import { DRAG_SOURCE_OPACITY } from '@/ui/utilities/drag-and-drop/constants/DragSourceOpacity';
import { DragDropItemSortableHandleRefContext } from '@/ui/utilities/drag-and-drop/context/DragDropItemSortableHandleRefContext';
-// Overlays the row's leading edge without reflowing it. The grip, checkbox and
-// first field cells are sticky at TABLE_Z_INDEX.cell.sticky; without a higher
-// z-index they would paint over the insertion line and truncate it to the
-// scrollable columns.
+// Above TABLE_Z_INDEX.cell.sticky so sticky cells don't paint over the insertion line.
const StyledRowDropTargetSlot = styled.div`
left: 0;
position: absolute;
@@ -63,11 +60,7 @@ export const RecordTableDraggableTr = ({
focusIndex,
};
- // The sortable id must never change in place: when the virtualization
- // treadmill shifts recordIds across mounted rows after a reorder, dnd-kit
- // re-registers each row under its new id and disposes the row that
- // previously held it, leaving one row permanently undraggable. A stable
- // per-instance id avoids the collision; recordId travels in the drag data.
+ // Stable per instance: dnd-kit breaks a row when virtualization shifts recordIds across mounted rows.
const [sortableId] = useState(() => v4());
const { handleRef, ref, isDragSource } = useSortable({
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableRowDragOverlayContent.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableRowDragOverlayContent.tsx
index 9d79a69572e..56c15d63d3b 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableRowDragOverlayContent.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-row/components/RecordTableRowDragOverlayContent.tsx
@@ -50,8 +50,7 @@ const cloneColumnFieldWidthRules = Array.from(
},
).join('\n');
-// The overlay renders in a portal outside the table, so the column width CSS
-// variables and sticky cell rules of the table ancestors are redeclared here.
+// The overlay portals outside the table, so its column width variables and sticky rules are redeclared.
const StyledRowDragOverlayCSSBridge = styled.div`
position: relative;
@@ -119,10 +118,8 @@ const StyledRowDragOverlayCSSBridge = styled.div`
}
`;
-// The full-width row preview would overhang overlays such as the record side
-// panel when the visible table is narrower than the row, so it is clipped to
-// the scroll wrapper's width. The multi-drag counter chip renders outside
-// this container because it pokes past the row's top-left corner.
+// Clipped to the scroll wrapper so the preview doesn't overhang overlays; the counter chip sits outside
+// because it pokes past the row's top-left corner.
const StyledRowClipContainer = styled.div`
overflow: hidden;
`;
diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-section/components/RecordTableRecordGroupSectionAddNew.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-section/components/RecordTableRecordGroupSectionAddNew.tsx
index fe7bdf38642..dc781646c2d 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-section/components/RecordTableRecordGroupSectionAddNew.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-section/components/RecordTableRecordGroupSectionAddNew.tsx
@@ -62,9 +62,8 @@ export const RecordTableRecordGroupSectionAddNew = () => {
return null;
}
- // Linking through a junction never creates a record of the table's object,
- // so the target object's creatability does not apply. The picker only
- // offers records of this group, so the linked row lands where it was added.
+ // Linking through a junction creates no record of the table's object, so its creatability check doesn't apply;
+ // the group filter keeps the linked row in the group it was added from.
if (isDefined(junctionCreateThrough)) {
return (
<RecordTableWidgetJunctionAddNewRow
diff --git a/packages/twenty-front/src/modules/object-record/record-table/utils/buildRecordInputFromFilter.ts b/packages/twenty-front/src/modules/object-record/record-table/utils/buildRecordInputFromFilter.ts
index b0fab4211b7..572efb3f5d2 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/utils/buildRecordInputFromFilter.ts
+++ b/packages/twenty-front/src/modules/object-record/record-table/utils/buildRecordInputFromFilter.ts
@@ -30,8 +30,7 @@ export const buildRecordInputFromFilter = ({
return;
}
- // A relation-traversal filter constrains a field of the related record,
- // not a column of the record being created, so it cannot be prefilled.
+ // A relation-traversal filter constrains the related record, not a column to prefill.
if (isDefined(filter.relationTargetFieldMetadataId)) {
return;
}
diff --git a/packages/twenty-front/src/modules/object-record/record-table/virtualization/components/RecordTableNoRecordGroupScrollToPreviousRecordEffect.tsx b/packages/twenty-front/src/modules/object-record/record-table/virtualization/components/RecordTableNoRecordGroupScrollToPreviousRecordEffect.tsx
index 2d6662a63fd..182b69b2f3c 100644
--- a/packages/twenty-front/src/modules/object-record/record-table/virtualization/components/RecordTableNoRecordGroupScrollToPreviousRecordEffect.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table/virtualization/components/RecordTableNoRecordGroupScrollToPreviousRecordEffect.tsx
@@ -37,8 +37,7 @@ export const RecordTableNoRecordGroupScrollToPreviousRecordEffect = () => {
const { triggerFetchPagesWithoutDebounce } = useTriggerFetchPages();
useEffect(() => {
- // Read directly from the Jotai store to avoid stale values from useAtom's
- // internal useReducer, which can desync under high-frequency store updates.
+ // Read from the store directly: useAtom's useReducer can desync under high-frequency updates.
const lastShowPageRecordId = store.get(lastShowPageRecordIdAtom);
if (!isNonEmptyString(lastShowPageRecordId)) {
diff --git a/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts b/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts
index 9753828095d..4961b1b9c14 100644
--- a/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts
+++ b/packages/twenty-front/src/modules/object-record/utils/canCreateRecordsForObjectMetadataItem.ts
@@ -10,15 +10,8 @@ type CanCreateRecordsForObjectMetadataItemParams = {
>;
};
-// Single predicate for every generic "create a record" UI affordance.
-// Creatability is driven by isUICreatable: isSystem only controls Data-Model
-// visibility, so a system object can still be user-creatable (e.g. marketing
-// message lists kept out of the Data Model), while a non-OPEN writability
-// rules the user session out regardless of the affordance flags.
-// Creation requires effective editability because today's inline creation UX
-// creates a blank record that the user must then be able to edit.
-// There is no CREATE permission yet, so canUpdateObjectRecords (checked
-// through isObjectMetadataReadOnly) acts as a proxy.
+// isSystem only controls Data Model visibility; isUICreatable and OPEN writability govern creation.
+// No CREATE permission exists yet, so canUpdateObjectRecords is the proxy (inline creation edits a blank record).
export const canCreateRecordsForObjectMetadataItem = ({
objectPermissions,
objectMetadataItem,
diff --git a/packages/twenty-front/src/modules/object-record/utils/isFieldCellSupported.ts b/packages/twenty-front/src/modules/object-record/utils/isFieldCellSupported.ts
index ef9a4625f3b..13f8d40a68e 100644
--- a/packages/twenty-front/src/modules/object-record/utils/isFieldCellSupported.ts
+++ b/packages/twenty-front/src/modules/object-record/utils/isFieldCellSupported.ts
@@ -28,8 +28,7 @@ export const isFieldCellSupported = (
(item) => item.id === relationObjectMetadataItemId,
);
- // A junction object is a system object on purpose, so the relation holding its records
- // is still cell-supported even though relations to system objects are not.
+ // Junction objects are system objects by design, so their relation stays cell-supported.
const junctionConfig = resolveJunctionConfig({
settings: fieldMetadataItem.settings,
relationObjectMetadataId: relationObjectMetadataItemId ?? '',
diff --git a/packages/twenty-front/src/modules/object-record/utils/isPlainManyToOneRelationField.ts b/packages/twenty-front/src/modules/object-record/utils/isPlainManyToOneRelationField.ts
index e563a61387d..0767e0d072a 100644
--- a/packages/twenty-front/src/modules/object-record/utils/isPlainManyToOneRelationField.ts
+++ b/packages/twenty-front/src/modules/object-record/utils/isPlainManyToOneRelationField.ts
@@ -2,8 +2,7 @@ import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataIte
import { isManyToOneRelationField } from '@/object-metadata/utils/isManyToOneRelationField';
import { isConfiguredJunctionRelationField } from '@/object-record/record-field/ui/utils/junction/isConfiguredJunctionRelationField';
-// Junction relation fields also carry MANY_TO_ONE metadata but render through
-// a dedicated junction path, mirroring isPlainOneToManyRelationField.
+// Junction relation fields also carry MANY_TO_ONE metadata but render through a junction path.
export const isPlainManyToOneRelationField = (
fieldMetadataItem: FieldMetadataItem,
): fieldMetadataItem is FieldMetadataItem & {
diff --git a/packages/twenty-front/src/modules/object-record/utils/isPlainOneToManyRelationField.ts b/packages/twenty-front/src/modules/object-record/utils/isPlainOneToManyRelationField.ts
index 2d7293d60b4..df07938cae4 100644
--- a/packages/twenty-front/src/modules/object-record/utils/isPlainOneToManyRelationField.ts
+++ b/packages/twenty-front/src/modules/object-record/utils/isPlainOneToManyRelationField.ts
@@ -2,8 +2,7 @@ import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataIte
import { isOneToManyRelationField } from '@/object-metadata/utils/isOneToManyRelationField';
import { isConfiguredJunctionRelationField } from '@/object-record/record-field/ui/utils/junction/isConfiguredJunctionRelationField';
-// Junction relation fields also carry ONE_TO_MANY metadata but render through
-// a dedicated junction path, mirroring the backend's
+// Junction fields also carry ONE_TO_MANY metadata but render through the junction path; mirrors the backend's
// isPlainOneToManyRelationFlatFieldMetadata.
export const isPlainOneToManyRelationField = (
fieldMetadataItem: FieldMetadataItem,
diff --git a/packages/twenty-front/src/modules/object-record/utils/sanitizeRecordInput.ts b/packages/twenty-front/src/modules/object-record/utils/sanitizeRecordInput.ts
index 15b875bbd6b..a381eae5ca7 100644
--- a/packages/twenty-front/src/modules/object-record/utils/sanitizeRecordInput.ts
+++ b/packages/twenty-front/src/modules/object-record/utils/sanitizeRecordInput.ts
@@ -103,8 +103,7 @@ export const sanitizeRecordInput = ({
];
}
- // Todo: we should check that the fieldValue is a valid value
- // (e.g. a string for a string field, following the right composite structure for composite fields)
+ // TODO: validate fieldValue against the field type, including composite structures
return [fieldName, fieldValue];
})
.filter(isDefined),
diff --git a/packages/twenty-front/src/modules/onboarding/components/OnboardingPageLoader.tsx b/packages/twenty-front/src/modules/onboarding/components/OnboardingPageLoader.tsx
index 7f92577ee4c..0bd6fc64661 100644
--- a/packages/twenty-front/src/modules/onboarding/components/OnboardingPageLoader.tsx
+++ b/packages/twenty-front/src/modules/onboarding/components/OnboardingPageLoader.tsx
@@ -13,8 +13,7 @@ const StyledContainer = styled.div`
width: 100%;
`;
-// The verify screen renders its own pulsing logo, so the loader shown before it
-// omits the logo to avoid a double-logo flash on cold boot into the verify step.
+// No logo: the verify screen renders its own, which would flash twice on cold boot.
export const OnboardingPageLoader = () => (
<StyledContainer>
{!isOnOnboardingVerifyPath(window.location.pathname) && (
diff --git a/packages/twenty-front/src/modules/page-layout/components/PageLayoutGridLayout.tsx b/packages/twenty-front/src/modules/page-layout/components/PageLayoutGridLayout.tsx
index 49083ea3ad9..05ab7bf5439 100644
--- a/packages/twenty-front/src/modules/page-layout/components/PageLayoutGridLayout.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/PageLayoutGridLayout.tsx
@@ -97,10 +97,7 @@ const StyledGridContainer = styled.div`
height: auto !important;
}
- // Flow the absolutely-positioned grid items into the page, but keep the
- // pixel width and height react-grid-layout sets inline: the charts are sized
- // by a resize observer (Nivo SVG and a custom canvas bar chart), so changing
- // their box would re-measure mid-print and render them blank.
+ // Keep react-grid-layout's inline size: resize-observed charts would re-measure mid-print and render blank.
.react-grid-item {
break-inside: avoid;
margin-bottom: ${themeCssVariables.spacing[4]};
diff --git a/packages/twenty-front/src/modules/page-layout/components/PageLayoutPrerenderedTabIdsResetEffect.tsx b/packages/twenty-front/src/modules/page-layout/components/PageLayoutPrerenderedTabIdsResetEffect.tsx
index 0eb1a2db9d8..b9064c88a84 100644
--- a/packages/twenty-front/src/modules/page-layout/components/PageLayoutPrerenderedTabIdsResetEffect.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/PageLayoutPrerenderedTabIdsResetEffect.tsx
@@ -3,8 +3,7 @@ import { useEffect } from 'react';
import { pageLayoutPrerenderedTabIdsComponentState } from '@/page-layout/states/pageLayoutPrerenderedTabIdsComponentState';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
-// Prerendering is a within-visit optimization: without the reset, reopening
-// a record would mount every tab hovered during the previous visit at once.
+// Without the reset, reopening a record would mount every tab hovered on the previous visit.
export const PageLayoutPrerenderedTabIdsResetEffect = () => {
const setPageLayoutPrerenderedTabIds = useSetAtomComponentState(
pageLayoutPrerenderedTabIdsComponentState,
diff --git a/packages/twenty-front/src/modules/page-layout/components/PageLayoutRecordIdentifierBar.tsx b/packages/twenty-front/src/modules/page-layout/components/PageLayoutRecordIdentifierBar.tsx
index bedbd8db943..213a9f302ca 100644
--- a/packages/twenty-front/src/modules/page-layout/components/PageLayoutRecordIdentifierBar.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/PageLayoutRecordIdentifierBar.tsx
@@ -16,16 +16,14 @@ import { themeCssVariables } from 'twenty-ui/theme';
const SIDE_TRACK = `min(${PAGE_LAYOUT_LEFT_PANEL_CONTAINER_WIDTH}px, calc(100% / 3))`;
-// Equal side tracks center the tabs independently of the record name. Their
-// width stays independent of visible tabs so overflow can recover on resize.
+// Equal side tracks center the tabs; their width ignores visible tabs so overflow can recover on resize.
const StyledBar = styled.div<{
hasPinnedTab: boolean;
hasTabList: boolean;
}>`
align-items: stretch;
background: ${themeCssVariables.background.secondary};
- // The bottom line sits inside the box so the tab strip can fill the whole row
- // and land its active indicator on that line rather than above it.
+ // Inset so the tab strip's active indicator lands on the bottom line.
box-shadow: inset 0 -1px 0 ${themeCssVariables.border.color.light};
box-sizing: border-box;
display: grid;
diff --git a/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabList.tsx b/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabList.tsx
index cd4b6610d0a..5c1f75acdf7 100644
--- a/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabList.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabList.tsx
@@ -57,9 +57,7 @@ const StyledNodeDimension = styled(NodeDimension)`
min-width: 0;
`;
-// In the identifier bar the wrapper must fill its grid track so tabs can
-// reappear when the track grows after an overflow. Standalone it sits in a
-// flex column, where growing would eat the tab content's height.
+// Fill the identifier bar's track so tabs reappear when it grows; standalone, growing would eat content height.
const identifierBarTrackCssClass = css`
flex: 1;
`;
@@ -247,9 +245,7 @@ export const PageLayoutTabList = ({
closeDropdown(dropdownId);
}, [closeDropdown, dropdownId]);
- // The overflow dropdown must survive drops into itself: the dragging flag
- // suppresses its close-on-click-outside while a tab drag is in flight, and a
- // drop on the more button reopens it on the freshly appended tab.
+ // The dragging flag suppresses click-outside so the overflow dropdown survives drops into it; a drop on the more button reopens it.
useDragDropMonitor({
onDragStart: (event) => {
const sourceData = event.operation.source?.data as
@@ -309,8 +305,7 @@ export const PageLayoutTabList = ({
const isTabSettingsOpen = isDefined(pageLayoutTabSettingsOpenTabId);
- // The reorderable strip appends an end drop zone the tab measurement does
- // not know about; reserve its width so visible tabs never get clipped.
+ // Reserve the strip's end drop zone, which the tab measurement doesn't know about.
const handleContainerWidthChange = useCallback(
(dimensions: { width: number; height: number }) => {
onContainerWidthChange(
@@ -389,9 +384,7 @@ export const PageLayoutTabList = ({
const shouldRenderStaticDropdown =
hasHiddenTabs && !canReorderTabs && !shouldScrollTabs;
- // Record pages accept widget drops on vertical-list tabs (dnd-kit drags);
- // dashboards accept them on grid tabs (react-grid-layout drags bridged by
- // pointer hit-testing).
+ // Record pages take widget drops on vertical-list tabs, dashboards on grid tabs (hit-tested).
const widgetDropTargetWidgetsByTabId = new Map<string, PageLayoutWidget[]>(
pageLayoutType === PageLayoutType.RECORD_PAGE
? tabs
diff --git a/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabListEffect.tsx b/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabListEffect.tsx
index b56dc44aca4..a7dfb1fdbdb 100644
--- a/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabListEffect.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabListEffect.tsx
@@ -67,8 +67,8 @@ export const PageLayoutTabListEffect = ({
}, [componentInstanceId, nextActiveTabId, onChangeTab, store]);
useEffect(() => {
- // Cancelling customization can pin the active tab again. Replace its stale
- // hash without overwriting a different deep link or the main URL from a panel.
+ // Cancelling customization can re-pin the active tab; replace its stale hash
+ // without overwriting another deep link or the main URL from a panel.
if (
shouldSyncWithUrl &&
isDefined(activeTabId) &&
diff --git a/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabsRenderer.tsx b/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabsRenderer.tsx
index e6b5665fadd..b8898b7f5a2 100644
--- a/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabsRenderer.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/PageLayoutTabsRenderer.tsx
@@ -92,10 +92,7 @@ const StyledTabsAndDashboardContainer = styled.div`
}
`;
-// Hidden prerendered tabs use display: none rather than <Activity mode="hidden">:
-// Apollo starts useQuery fetches from effects, which hidden activities do not
-// mount, so nothing would preload (see pageLayoutTabPrerenderContract.test).
-// display: contents keeps the active tab's layout identical to an unwrapped mount.
+// display: none, not a hidden <Activity>, which skips the effects Apollo fetches from (see pageLayoutTabPrerenderContract.test).
const StyledTabContentDisplay = styled.div<{ isActiveTab: boolean }>`
display: ${({ isActiveTab }) => (isActiveTab ? 'contents' : 'none')};
`;
@@ -118,8 +115,7 @@ const StyledScrollWrapperContainer = styled.div`
container-type: size;
}
- // The mobile navigation bar floats over the page, so the content reserves its
- // footprint to stay readable once scrolled to the end.
+ // Reserve the floating mobile navigation bar's footprint.
@media (max-width: ${MOBILE_VIEWPORT}px) {
.page-layout-scroll-wrapper {
box-sizing: border-box;
diff --git a/packages/twenty-front/src/modules/page-layout/components/__stories__/PageLayoutTabList.stories.tsx b/packages/twenty-front/src/modules/page-layout/components/__stories__/PageLayoutTabList.stories.tsx
index c9dc4fa8e46..4ffeed0448e 100644
--- a/packages/twenty-front/src/modules/page-layout/components/__stories__/PageLayoutTabList.stories.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/__stories__/PageLayoutTabList.stories.tsx
@@ -103,8 +103,7 @@ const PageLayoutTabListPlayground = ({
containerWidth = 720,
}: PageLayoutTabListPlaygroundProps) => {
const isInIdentifierBar = presentation === 'identifier-bar';
- // Tab drops are routed into the page-layout draft by the dnd provider, so
- // the story renders from that draft to stay interactive.
+ // The dnd provider routes tab drops into the draft, so render from it.
const [pageLayoutDraft, setPageLayoutDraft] = useAtomComponentState(
pageLayoutDraftComponentState,
);
diff --git a/packages/twenty-front/src/modules/page-layout/components/__tests__/pageLayoutTabPrerenderContract.test.tsx b/packages/twenty-front/src/modules/page-layout/components/__tests__/pageLayoutTabPrerenderContract.test.tsx
index dcfb71d0ca0..dfca907a070 100644
--- a/packages/twenty-front/src/modules/page-layout/components/__tests__/pageLayoutTabPrerenderContract.test.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/__tests__/pageLayoutTabPrerenderContract.test.tsx
@@ -4,11 +4,8 @@ import { render, screen, waitFor } from '@testing-library/react';
import { Activity } from 'react';
import { of } from 'rxjs';
-// Prerendered tabs mount CSS-hidden (display: none) rather than inside a
-// hidden <Activity>. This test guards the platform behaviors that choice is
-// built on: Apollo's useQuery starts fetching from effects, so it fetches
-// under display: none but not under a hidden Activity, and revealing an
-// offscreen-mounted tab neither refetches nor flashes a loading state.
+// Guards what CSS-hidden prerendering relies on: useQuery fetches under display: none, not under a hidden <Activity>,
+// and revealing the tab neither refetches nor flashes a loading state.
const PRERENDER_PROBE_QUERY = gql`
query PrerenderProbe {
probe
diff --git a/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutTabWidgetDropTarget.tsx b/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutTabWidgetDropTarget.tsx
index 51236d0ee68..ce66ecc70ac 100644
--- a/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutTabWidgetDropTarget.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutTabWidgetDropTarget.tsx
@@ -53,8 +53,7 @@ export const PageLayoutTabWidgetDropTarget = ({
data,
});
- // Grid drags come from react-grid-layout, outside dnd-kit; their hover
- // highlight is driven by pointer hit-testing instead of isDropTarget.
+ // Grid drags bypass dnd-kit, so their hover highlight comes from pointer hit-testing.
const pageLayoutGridDragHoveredTabId = useAtomComponentStateValue(
pageLayoutGridDragHoveredTabIdComponentState,
);
diff --git a/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutWidgetDndProvider.tsx b/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutWidgetDndProvider.tsx
index 738832cc739..0b339b1d5a9 100644
--- a/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutWidgetDndProvider.tsx
+++ b/packages/twenty-front/src/modules/page-layout/components/dnd/PageLayoutWidgetDndProvider.tsx
@@ -11,10 +11,8 @@ type PageLayoutWidgetDndProviderProps = {
children: ReactNode;
};
-// Mounted in both view and edit mode so toggling edit mode does not remount the
-// layout subtree (which would reset scroll position and widget-local state).
-// Widget sortables are disabled and their terminal drop target is detached in
-// view mode, so the provider is inert there.
+// Mounted in view mode too so toggling edit mode doesn't remount the layout (scroll, widget state);
+// it is inert there since sortables are disabled and the terminal drop target is detached.
export const PageLayoutWidgetDndProvider = ({
children,
}: PageLayoutWidgetDndProviderProps) => {
diff --git a/packages/twenty-front/src/modules/page-layout/constants/MaxPrerenderedPageLayoutTabs.ts b/packages/twenty-front/src/modules/page-layout/constants/MaxPrerenderedPageLayoutTabs.ts
index 144c1873a56..92a3261a902 100644
--- a/packages/twenty-front/src/modules/page-layout/constants/MaxPrerenderedPageLayoutTabs.ts
+++ b/packages/twenty-front/src/modules/page-layout/constants/MaxPrerenderedPageLayoutTabs.ts
@@ -1,3 +1,2 @@
-// Each prerendered tab is a mounted (hidden) widget tree with live queries;
-// the cap bounds the memory and background work a hover trail can accumulate.
+// Bounds the memory and live queries a hover trail of hidden tabs can accumulate.
export const MAX_PRERENDERED_PAGE_LAYOUT_TABS = 3;
diff --git a/packages/twenty-front/src/modules/page-layout/constants/PageLayoutTabPrerenderHoverIntentDelayMs.ts b/packages/twenty-front/src/modules/page-layout/constants/PageLayoutTabPrerenderHoverIntentDelayMs.ts
index ffc0a96a641..f028c1fa4d2 100644
--- a/packages/twenty-front/src/modules/page-layout/constants/PageLayoutTabPrerenderHoverIntentDelayMs.ts
+++ b/packages/twenty-front/src/modules/page-layout/constants/PageLayoutTabPrerenderHoverIntentDelayMs.ts
@@ -1,3 +1,2 @@
-// Sweeping the cursor across the tab bar should not prerender every tab it
-// crosses; only a pause long enough to signal intent triggers the mount.
+// Sweeping across the tab bar should not prerender every tab it crosses.
export const PAGE_LAYOUT_TAB_PRERENDER_HOVER_INTENT_DELAY_MS = 100;
diff --git a/packages/twenty-front/src/modules/page-layout/constants/PrerenderablePageLayoutWidgetTypes.ts b/packages/twenty-front/src/modules/page-layout/constants/PrerenderablePageLayoutWidgetTypes.ts
index 53b344df0be..0d73dbee0f9 100644
--- a/packages/twenty-front/src/modules/page-layout/constants/PrerenderablePageLayoutWidgetTypes.ts
+++ b/packages/twenty-front/src/modules/page-layout/constants/PrerenderablePageLayoutWidgetTypes.ts
@@ -1,11 +1,7 @@
import { WidgetType } from '~/generated-metadata/graphql';
-// Prerendered tabs mount for real while hidden, so only widgets that behave
-// under display: none are eligible. Data cards fetch and render lists without
-// grabbing focus. FRONT_COMPONENT and IFRAME boot their sandbox worker or
-// embed on mount, which is the point: workspace applications are trusted, so
-// warming them on hover is wanted. Excluded: GRAPH and RECORD_TABLE measure
-// their container, which is zero-sized while hidden.
+// Prerendered tabs mount while hidden, so only widgets that behave under display: none qualify; apps are trusted, so warming FRONT_COMPONENT and IFRAME is wanted.
+// Excluded: GRAPH and RECORD_TABLE measure their container, which is zero-sized while hidden.
export const PRERENDERABLE_PAGE_LAYOUT_WIDGET_TYPES: WidgetType[] = [
WidgetType.FIELDS,
WidgetType.TIMELINE,
diff --git a/packages/twenty-front/src/modules/page-layout/constants/WidgetTypesRequiringRelationField.ts b/packages/twenty-front/src/modules/page-layout/constants/WidgetTypesRequiringRelationField.ts
index 067feac8f25..2a022488aed 100644
--- a/packages/twenty-front/src/modules/page-layout/constants/WidgetTypesRequiringRelationField.ts
+++ b/packages/twenty-front/src/modules/page-layout/constants/WidgetTypesRequiringRelationField.ts
@@ -1,9 +1,6 @@
import { WidgetType } from '~/generated-metadata/graphql';
-// These widgets read their records through the relation itself, so the target
-// object must expose the relation field. Emails and Calendar are absent on
-// purpose: they aggregate through the messaging timeline and work on objects
-// without a direct participants relation (e.g. Company through its people).
+// Emails and Calendar are absent on purpose: they aggregate through the messaging timeline.
export const WIDGET_TYPES_REQUIRING_RELATION_FIELD: WidgetType[] = [
WidgetType.TASKS,
WidgetType.NOTES,
diff --git a/packages/twenty-front/src/modules/page-layout/hooks/useMovePageLayoutTab.ts b/packages/twenty-front/src/modules/page-layout/hooks/useMovePageLayoutTab.ts
index 36885d3b588..12f4339be4b 100644
--- a/packages/twenty-front/src/modules/page-layout/hooks/useMovePageLayoutTab.ts
+++ b/packages/twenty-front/src/modules/page-layout/hooks/useMovePageLayoutTab.ts
@@ -19,9 +19,7 @@ export const useMovePageLayoutTab = (pageLayoutIdFromProps?: string) => {
const store = useStore();
- // Deleting a tab only deactivates it in the draft, so an inactive tab must
- // not become the neighbour a move swaps positions with: that would leave the
- // rendered order untouched.
+ // Deleted tabs are only deactivated in the draft; swapping with one would leave the rendered order unchanged.
const swapWithNeighborTab = useCallback(
(tabId: string, offset: -1 | 1) => {
store.set(pageLayoutDraftState, (prev) => {
diff --git a/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutGridCrossTabDrop.ts b/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutGridCrossTabDrop.ts
index 97a165cfc84..6e963464f3e 100644
--- a/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutGridCrossTabDrop.ts
+++ b/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutGridCrossTabDrop.ts
@@ -41,9 +41,7 @@ const findTabDropTargetIdAtPoint = (
return null;
};
-// Bridges react-grid-layout drags to the tab strip: grid drags never enter
-// dnd-kit, so hovering and dropping on tab buttons is resolved by hit-testing
-// the pointer against the tab drop targets.
+// Grid drags never enter dnd-kit, so tab hover and drop are resolved by pointer hit-testing.
export const usePageLayoutGridCrossTabDrop = ({ tabId }: { tabId: string }) => {
const pageLayoutId = useAvailableComponentInstanceIdOrThrow(
PageLayoutComponentInstanceContext,
diff --git a/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutRenderableTabs.ts b/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutRenderableTabs.ts
index 23565aa4a0f..da466fb132f 100644
--- a/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutRenderableTabs.ts
+++ b/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutRenderableTabs.ts
@@ -11,8 +11,6 @@ import { useWorkspaceSurface } from '@/ui/layout/hooks/useWorkspaceSurface';
import { isDefined } from 'twenty-shared/utils';
import { useIsMobile } from 'twenty-ui/utilities';
-// Single source of truth for which tabs render and which one is pinned, so
-// every consumer derives them from the same filtered tab set.
export const usePageLayoutRenderableTabs = () => {
const isMobile = useIsMobile();
const { targetRecordIdentifier } = useLayoutRenderingContext();
@@ -35,8 +33,7 @@ export const usePageLayoutRenderableTabs = () => {
context: widgetVisibilityContext,
});
- // Edit mode keeps every tab visible (like getTabsWithVisibleWidgets) so a
- // widget the object does not support can still be reached and removed.
+ // Edit mode keeps every tab visible so unsupported widgets can still be removed.
const renderableTabs = isPageLayoutInEditMode
? tabsWithVisibleWidgets
: getTabsRenderableForTargetObject({
diff --git a/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutTabWithVisibleWidgetsOrThrow.ts b/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutTabWithVisibleWidgetsOrThrow.ts
index 02d07545b3a..e9ad657123c 100644
--- a/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutTabWithVisibleWidgetsOrThrow.ts
+++ b/packages/twenty-front/src/modules/page-layout/hooks/usePageLayoutTabWithVisibleWidgetsOrThrow.ts
@@ -17,8 +17,6 @@ export const usePageLayoutTabWithVisibleWidgetsOrThrow = (
const tab = currentPageLayout.tabs.find((tab) => tab.id === tabId);
- // Memoized because consumers feed this widget array to dnd-kit and to
- // memoized callbacks, which a fresh array on every render would defeat.
const tabWithVisibleWidgets = useMemo(() => {
if (!isDefined(tab)) {
return undefined;
diff --git a/packages/twenty-front/src/modules/page-layout/hooks/useResolveFieldMetadataIdFromNameOrId.ts b/packages/twenty-front/src/modules/page-layout/hooks/useResolveFieldMetadataIdFromNameOrId.ts
index 67e29a1f30e..4ad58f11e94 100644
--- a/packages/twenty-front/src/modules/page-layout/hooks/useResolveFieldMetadataIdFromNameOrId.ts
+++ b/packages/twenty-front/src/modules/page-layout/hooks/useResolveFieldMetadataIdFromNameOrId.ts
@@ -12,8 +12,7 @@ export const useResolveFieldMetadataIdFromNameOrId = (
objectNameSingular: targetRecord.targetObjectNameSingular,
});
- // Only one field per morph group is served, so an id of another sibling
- // resolves to the field that represents its group.
+ // Only one field per morph group is served, so a sibling id resolves to its group's field.
return useMemo(
() =>
objectMetadataItem.fields.find(
diff --git a/packages/twenty-front/src/modules/page-layout/hooks/useSaveRecordTableWidgetViews.ts b/packages/twenty-front/src/modules/page-layout/hooks/useSaveRecordTableWidgetViews.ts
index 4d9b938c820..6ac36f540a7 100644
--- a/packages/twenty-front/src/modules/page-layout/hooks/useSaveRecordTableWidgetViews.ts
+++ b/packages/twenty-front/src/modules/page-layout/hooks/useSaveRecordTableWidgetViews.ts
@@ -74,8 +74,7 @@ export const useSaveRecordTableWidgetViews = () => {
continue;
}
- // Every view-backed widget gets a draft seeded on entering edit mode;
- // only the ones the user actually touched need an upsert.
+ // Every view-backed widget gets a draft on entering edit mode; only touched ones need an upsert.
if (
isDeeplyEqual(
recordTableWidgetViewPersisted[widget.id],
@@ -159,10 +158,7 @@ export const useSaveRecordTableWidgetViews = () => {
},
});
- // View groups are not part of the upsert input: the server
- // regenerates them from mainGroupByFieldMetadataId. Store the
- // server rows instead of the locally generated draft groups so
- // the persisted snapshot never claims client-side ids were saved.
+ // The server regenerates view groups from mainGroupByFieldMetadataId, so store its rows, not draft ids.
const upsertedViewGroups = data?.upsertViewWidget.viewGroups;
normalizedRecordTableWidgetViewDraft = {
diff --git a/packages/twenty-front/src/modules/page-layout/hooks/useWidgetVisibilityContext.ts b/packages/twenty-front/src/modules/page-layout/hooks/useWidgetVisibilityContext.ts
index 98850bc4163..b494d17f188 100644
--- a/packages/twenty-front/src/modules/page-layout/hooks/useWidgetVisibilityContext.ts
+++ b/packages/twenty-front/src/modules/page-layout/hooks/useWidgetVisibilityContext.ts
@@ -10,10 +10,6 @@ import { useMemo } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { useIsMobile } from 'twenty-ui/utilities';
-// The one place widget visibility is derived. Every consumer reads the same
-// context, so a widget cannot be visible to one caller and hidden from another
-// — which is what makes "is this widget last in its tab" agree with "which
-// widgets does this tab render".
export const useWidgetVisibilityContext = (): WidgetVisibilityContext => {
const isMobile = useIsMobile();
const { targetRecordIdentifier } = useLayoutRenderingContext();
@@ -25,8 +21,7 @@ export const useWidgetVisibilityContext = (): WidgetVisibilityContext => {
targetRecordIdentifier?.id ?? '',
);
- // Remove with the workspace workflow and workflowVersion objects, once the
- // core migration owns them.
+ // TODO: remove with the workspace workflow and workflowVersion objects once the core migration owns them.
const hiddenFieldMetadataIdsOrNames =
useHiddenWorkspaceWorkflowRunRelationFields(
targetRecordIdentifier?.targetObjectNameSingular,
diff --git a/packages/twenty-front/src/modules/page-layout/states/pageLayoutGridDragHoveredTabIdComponentState.ts b/packages/twenty-front/src/modules/page-layout/states/pageLayoutGridDragHoveredTabIdComponentState.ts
index 3a647309d83..7c56ec6748c 100644
--- a/packages/twenty-front/src/modules/page-layout/states/pageLayoutGridDragHoveredTabIdComponentState.ts
+++ b/packages/twenty-front/src/modules/page-layout/states/pageLayoutGridDragHoveredTabIdComponentState.ts
@@ -1,8 +1,7 @@
import { PageLayoutComponentInstanceContext } from '@/page-layout/states/contexts/PageLayoutComponentInstanceContext';
import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';
-// Tab hovered by a react-grid-layout widget drag; grid drags never enter
-// dnd-kit, so the tab highlight is driven through this state instead.
+// Grid drags never enter dnd-kit, so the tab highlight is driven through this state.
export const pageLayoutGridDragHoveredTabIdComponentState =
createAtomComponentState<string | null>({
key: 'pageLayoutGridDragHoveredTabIdComponentState',
diff --git a/packages/twenty-front/src/modules/page-layout/states/pageLayoutPrerenderedTabIdsComponentState.ts b/packages/twenty-front/src/modules/page-layout/states/pageLayoutPrerenderedTabIdsComponentState.ts
index 0752786b501..ce5303464f2 100644
--- a/packages/twenty-front/src/modules/page-layout/states/pageLayoutPrerenderedTabIdsComponentState.ts
+++ b/packages/twenty-front/src/modules/page-layout/states/pageLayoutPrerenderedTabIdsComponentState.ts
@@ -1,8 +1,7 @@
import { TabListComponentInstanceContext } from '@/ui/layout/tab-list/states/contexts/TabListComponentInstanceContext';
import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';
-// Tab ids the user hovered with intent, most recent last. The tabs renderer
-// keeps them mounted but hidden so opening one shows already-fetched content.
+// Tabs hovered with intent, most recent last; kept mounted but hidden so opening one shows already-fetched content.
export const pageLayoutPrerenderedTabIdsComponentState =
createAtomComponentState<string[]>({
key: 'pageLayoutPrerenderedTabIdsComponentState',
diff --git a/packages/twenty-front/src/modules/page-layout/states/pageLayoutShouldIgnoreNextGridLayoutChangeComponentState.ts b/packages/twenty-front/src/modules/page-layout/states/pageLayoutShouldIgnoreNextGridLayoutChangeComponentState.ts
index 7aa21f2d3e2..216cf4083d1 100644
--- a/packages/twenty-front/src/modules/page-layout/states/pageLayoutShouldIgnoreNextGridLayoutChangeComponentState.ts
+++ b/packages/twenty-front/src/modules/page-layout/states/pageLayoutShouldIgnoreNextGridLayoutChangeComponentState.ts
@@ -1,9 +1,7 @@
import { PageLayoutComponentInstanceContext } from '@/page-layout/states/contexts/PageLayoutComponentInstanceContext';
import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';
-// A grid drop routed to another tab rebuilds both tabs' layouts itself; the
-// grid's own post-drag layout commit must be skipped once so it does not
-// overwrite the cross-tab move.
+// A cross-tab grid drop rebuilds both layouts itself, so the grid's own post-drag commit is skipped once.
export const pageLayoutShouldIgnoreNextGridLayoutChangeComponentState =
createAtomComponentState<boolean>({
key: 'pageLayoutShouldIgnoreNextGridLayoutChangeComponentState',
diff --git a/packages/twenty-front/src/modules/page-layout/types/PageLayoutTabDragData.ts b/packages/twenty-front/src/modules/page-layout/types/PageLayoutTabDragData.ts
index abd2faadbd5..3543b9d4212 100644
--- a/packages/twenty-front/src/modules/page-layout/types/PageLayoutTabDragData.ts
+++ b/packages/twenty-front/src/modules/page-layout/types/PageLayoutTabDragData.ts
@@ -1,7 +1,6 @@
export type PageLayoutTabDragData = {
type: 'tab';
tabId: string;
- // The following visible tab (or the first hidden tab, null when none), so a
- // drop past this tab's midpoint resolves to the right beforeTabId.
+ // The next visible tab, else the first hidden one, so a drop past the midpoint resolves beforeTabId.
nextTabId: string | null;
};
diff --git a/packages/twenty-front/src/modules/page-layout/types/TabPresentation.ts b/packages/twenty-front/src/modules/page-layout/types/TabPresentation.ts
index 3bb3ce42dc5..e26acbcacf8 100644
--- a/packages/twenty-front/src/modules/page-layout/types/TabPresentation.ts
+++ b/packages/twenty-front/src/modules/page-layout/types/TabPresentation.ts
@@ -1,3 +1,2 @@
-// How a list-mode tab (non-dashboard) presents its widgets. A solo tab hosts a
-// single module widget full-bleed; a stack tab boxes its widgets vertically.
+// solo: a single widget full-bleed; stack: widgets boxed vertically.
export type TabPresentation = 'solo' | 'stack';
diff --git a/packages/twenty-front/src/modules/page-layout/types/WidgetVisibilityContext.ts b/packages/twenty-front/src/modules/page-layout/types/WidgetVisibilityContext.ts
index 0ca6b762388..2e73f5c2086 100644
--- a/packages/twenty-front/src/modules/page-layout/types/WidgetVisibilityContext.ts
+++ b/packages/twenty-front/src/modules/page-layout/types/WidgetVisibilityContext.ts
@@ -2,7 +2,6 @@ export type WidgetVisibilityContext = {
device: 'MOBILE' | 'DESKTOP';
selectedRecords: Record<string, unknown>[];
featureFlags: Record<string, boolean>;
- // Remove with the workspace workflow and workflowVersion objects, once the
- // core migration owns them.
+ // TODO: remove with the workspace workflow and workflowVersion objects once the core migration owns them.
hiddenFieldMetadataIdsOrNames?: string[];
};
diff --git a/packages/twenty-front/src/modules/page-layout/utils/__tests__/evaluateWidgetVisibility.test.ts b/packages/twenty-front/src/modules/page-layout/utils/__tests__/evaluateWidgetVisibility.test.ts
index a75225e6764..6e9158c474e 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/__tests__/evaluateWidgetVisibility.test.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/__tests__/evaluateWidgetVisibility.test.ts
@@ -221,8 +221,6 @@ describe('evaluateWidgetVisibility', () => {
},
});
- // Expression says MOBILE only, so DESKTOP should be hidden
- // even though conditionalDisplay says DESKTOP is visible
expect(result).toBe(false);
});
@@ -245,8 +243,6 @@ describe('evaluateWidgetVisibility', () => {
},
});
- // Expression is null, so conditionalDisplay takes over
- // conditionalDisplay says MOBILE only → DESKTOP hidden
expect(result).toBe(false);
});
diff --git a/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsRenderableForTargetObject.test.ts b/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsRenderableForTargetObject.test.ts
index bf946702b4f..341457491be 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsRenderableForTargetObject.test.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsRenderableForTargetObject.test.ts
@@ -114,8 +114,7 @@ describe('getTabsRenderableForTargetObject', () => {
expect(result.map((tab) => tab.id)).toEqual(['tab-4']);
});
- // Chats attach through a leg of agentChatThreadTarget, which only person,
- // company, opportunity and custom objects have.
+ // Only person, company, opportunity and custom objects have an agentChatThreadTarget leg.
it('keeps the chat threads tab only on objects that can hold chats', () => {
const tabs = [
createMockTab('chats-tab', [
diff --git a/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsWithVisibleWidgets.test.ts b/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsWithVisibleWidgets.test.ts
index 36ba30cd150..423b5e3aa54 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsWithVisibleWidgets.test.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/__tests__/getTabsWithVisibleWidgets.test.ts
@@ -361,10 +361,7 @@ describe('getTabsWithVisibleWidgets', () => {
conditionalAvailabilityExpression,
});
- // The campaign layout's sent-only gate. `noneEquals` rather than
- // `not everyEquals`: the two agree on a loaded record, but an empty
- // selection makes the first false and the second true, and the selection is
- // empty until the record loads.
+ // `noneEquals`, not `not everyEquals`: they differ on the empty selection held until the record loads.
const sentOnlyTab = () =>
createMockTab('sent-only', [
createRecordGatedWidget(
@@ -403,10 +400,7 @@ describe('getTabsWithVisibleWidgets', () => {
expect(result[0].id).toBe('sent-only');
});
- // The record store answers after the first render, so every campaign page
- // load passes through this state: it must not show a tab it is about to
- // take away. The second tab keeps the all-tabs-empty fallback, which would
- // return the first tab regardless, from hiding the result.
+ // The record arrives after first render; the second tab keeps the all-empty fallback from masking the result.
it('should drop a record-gated tab while no record is given', () => {
const result = getTabsWithVisibleWidgets({
tabs: [sentOnlyTab(), createMockTab('always', [createMockWidget('w')])],
diff --git a/packages/twenty-front/src/modules/page-layout/utils/buildWidgetVisibilityContext.ts b/packages/twenty-front/src/modules/page-layout/utils/buildWidgetVisibilityContext.ts
index 466b9c99fad..07d5915c45d 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/buildWidgetVisibilityContext.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/buildWidgetVisibilityContext.ts
@@ -4,9 +4,6 @@ import { isDefined } from 'twenty-shared/utils';
type BuildWidgetVisibilityContextParams = {
isMobile: boolean;
isInSidePanel: boolean;
- // Deliberately the context's own record shape rather than ObjectRecord: the
- // expression evaluator reads arbitrary fields by name and never needs the
- // GraphQL metadata a full record carries.
targetRecord?: Record<string, unknown>;
featureFlags?: Record<string, boolean>;
};
@@ -19,12 +16,7 @@ export const buildWidgetVisibilityContext = ({
}: BuildWidgetVisibilityContextParams): WidgetVisibilityContext => {
return {
device: isMobile || isInSidePanel ? 'MOBILE' : 'DESKTOP',
- // A record page has one record, but the expression language names this
- // variable for list views where a selection can hold several. It stays
- // plural so page layouts and command menu items keep one shared grammar.
- // An absent record yields an empty selection, on which record predicates
- // are false — so a widget gated on the record stays hidden until it loads
- // rather than appearing and being taken away.
+ // Plural to share the command menu grammar; empty when absent so record-gated widgets stay hidden until load.
selectedRecords: isDefined(targetRecord) ? [targetRecord] : [],
featureFlags: featureFlags ?? {},
};
diff --git a/packages/twenty-front/src/modules/page-layout/utils/filterVisibleWidgets.ts b/packages/twenty-front/src/modules/page-layout/utils/filterVisibleWidgets.ts
index 8710221050a..916337b5931 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/filterVisibleWidgets.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/filterVisibleWidgets.ts
@@ -12,8 +12,7 @@ export const filterVisibleWidgets = ({
widgets,
context,
}: FilterVisibleWidgetsParams): PageLayoutTab['widgets'] => {
- // Remove with the workspace workflow and workflowVersion objects, once the
- // core migration owns them.
+ // TODO: remove with the workspace workflow and workflowVersion objects once the core migration owns them.
const hiddenFieldMetadataIdsOrNames =
context.hiddenFieldMetadataIdsOrNames ?? [];
diff --git a/packages/twenty-front/src/modules/page-layout/utils/getTabPresentation.ts b/packages/twenty-front/src/modules/page-layout/utils/getTabPresentation.ts
index 4cf6a3233ef..8f631036419 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/getTabPresentation.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/getTabPresentation.ts
@@ -8,11 +8,7 @@ type GetTabPresentationParams = {
isInEditMode?: boolean;
};
-// Presentation is derived from content, never stored. In view mode, a list tab
-// hosting a single widget renders it solo: full-bleed, owning the tab. Any
-// other tab is a stack of boxed widgets. Edit mode always shows the stack
-// structure so every tab is edited through the same vertical-list editor.
-// Grid tabs (dashboards) are always stacks.
+// Edit mode always stacks so every tab is edited through the same vertical-list editor.
export const getTabPresentation = ({
widgets,
layoutMode,
diff --git a/packages/twenty-front/src/modules/page-layout/utils/getTabsRenderableForTargetObject.ts b/packages/twenty-front/src/modules/page-layout/utils/getTabsRenderableForTargetObject.ts
index 68be967131f..cfd50bbbba8 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/getTabsRenderableForTargetObject.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/getTabsRenderableForTargetObject.ts
@@ -12,9 +12,6 @@ type GetTabsRenderableForTargetObjectParams = {
| undefined;
};
-// A relation-scoped widget renders only if the target object supports it: a
-// deactivated relation always hides the widget, while a missing relation hides
-// it only for widgets that read their records through the relation itself.
export const getTabsRenderableForTargetObject = ({
tabs,
targetObjectFields,
diff --git a/packages/twenty-front/src/modules/page-layout/utils/getWidgetConfigurationViewId.ts b/packages/twenty-front/src/modules/page-layout/utils/getWidgetConfigurationViewId.ts
index 07618f9f2dd..e675903f2cf 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/getWidgetConfigurationViewId.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/getWidgetConfigurationViewId.ts
@@ -1,9 +1,7 @@
import { type PageLayoutWidget } from '@/page-layout/types/PageLayoutWidget';
import { isNonEmptyString } from '@sniptt/guards';
-// The single answer to "does this widget have a view to render?", so callers
-// cannot disagree over an empty id — which is no more a view than a missing
-// one, and would otherwise be committed to as if it were.
+// An empty id is no more a view than a missing one.
export const getWidgetConfigurationViewId = (
configuration: PageLayoutWidget['configuration'],
): string | null => {
diff --git a/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToGridTabInDraft.ts b/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToGridTabInDraft.ts
index 641a1e845bd..22a24b9877e 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToGridTabInDraft.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToGridTabInDraft.ts
@@ -10,8 +10,7 @@ type MoveWidgetToGridTabInDraftParams = {
destinationTabId: string;
};
-// Moves a widget into a grid tab, placing it full-left below the lowest
-// existing widget so it never overlaps the destination layout.
+// Placed full-left below the lowest widget so it never overlaps.
export const moveWidgetToGridTabInDraft = (
draft: DraftPageLayout,
{ widgetId, destinationTabId }: MoveWidgetToGridTabInDraftParams,
diff --git a/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToTabInDraft.ts b/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToTabInDraft.ts
index cf16ccd549b..0f0718fadce 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToTabInDraft.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/moveWidgetToTabInDraft.ts
@@ -29,8 +29,7 @@ export const moveWidgetToTabInDraft = (
const destinationTab = draft.tabs.find((tab) => tab.id === destinationTabId);
- // Widgets carry vertical-list positions, so moving one into a canvas/grid tab
- // would reindex that tab's widgets and clobber their native placement.
+ // Widgets carry vertical-list positions, so moving one into a grid tab would reindex its widgets and clobber their placement.
if (
!isDefined(destinationTab) ||
destinationTab.layoutMode !== PageLayoutTabLayoutMode.VERTICAL_LIST
diff --git a/packages/twenty-front/src/modules/page-layout/utils/reorderTabInDraft.ts b/packages/twenty-front/src/modules/page-layout/utils/reorderTabInDraft.ts
index 7c87e5d6578..98c0229b17b 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/reorderTabInDraft.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/reorderTabInDraft.ts
@@ -7,10 +7,7 @@ type ReorderTabInDraftParams = {
beforeTabId: string | null;
};
-// Repositions a tab relative to another one; beforeTabId null appends it after
-// the last active tab. Operating on ids instead of list indices keeps tabs not
-// rendered in the tab list (the pinned first tab) in place without index
-// arithmetic.
+// A null beforeTabId appends after the last active tab; ids keep unlisted tabs (the pinned one) in place.
export const reorderTabInDraft = (
draft: DraftPageLayout,
{ tabId, beforeTabId }: ReorderTabInDraftParams,
diff --git a/packages/twenty-front/src/modules/page-layout/utils/shouldPrerenderPageLayoutTab.ts b/packages/twenty-front/src/modules/page-layout/utils/shouldPrerenderPageLayoutTab.ts
index d282c9bc44f..76f633f79bb 100644
--- a/packages/twenty-front/src/modules/page-layout/utils/shouldPrerenderPageLayoutTab.ts
+++ b/packages/twenty-front/src/modules/page-layout/utils/shouldPrerenderPageLayoutTab.ts
@@ -16,8 +16,7 @@ export const shouldPrerenderPageLayoutTab = ({
return false;
}
- // Grid tabs size their widgets from the container, which measures zero
- // while hidden; vertical lists lay out correctly on reveal.
+ // Grid tabs size widgets from the container, which measures zero while hidden.
if (tab.layoutMode !== PageLayoutTabLayoutMode.VERTICAL_LIST) {
return false;
}
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/call-recording/hooks/useCallRecordingForWidget.ts b/packages/twenty-front/src/modules/page-layout/widgets/call-recording/hooks/useCallRecordingForWidget.ts
index 32e382044e2..8adbfd647d6 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/call-recording/hooks/useCallRecordingForWidget.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/call-recording/hooks/useCallRecordingForWidget.ts
@@ -46,8 +46,7 @@ export const useCallRecordingForWidget = ({
const isVideoRestricted = isFieldRestricted('video');
const isAudioRestricted = isFieldRestricted('audio');
- // The transcript widget plays media, but requesting a field the role
- // cannot read fails the whole query.
+ // Requesting a field the role cannot read fails the whole query.
const recordGqlFields = useMemo(
() =>
kind === 'transcript'
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/call-recording/types/CallRecordingWidgetKind.ts b/packages/twenty-front/src/modules/page-layout/widgets/call-recording/types/CallRecordingWidgetKind.ts
index 0cff585c6b3..4bef991fe79 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/call-recording/types/CallRecordingWidgetKind.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/call-recording/types/CallRecordingWidgetKind.ts
@@ -1,2 +1 @@
-// Named after the call recording field each widget shows
export type CallRecordingWidgetKind = 'summary' | 'transcript';
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsx
index 2296f63c735..8e42d5a800a 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsx
@@ -3,8 +3,7 @@ import { useDetachChatThreadFromRecord } from '@/ai/hooks/useDetachChatThreadFro
import { ChatThreadsCardContent } from '@/page-layout/widgets/chat-threads/components/ChatThreadsCardContent';
import { useTargetRecord } from '@/ui/layout/contexts/useTargetRecord';
-// No WidgetHeaderCountEffect: one page is fetched, so the rows in hand cap at
-// the page size and cannot stand in for the record's total.
+// No WidgetHeaderCountEffect: only one page is fetched, so the row count isn't the total.
export const ChatThreadsCard = () => {
const targetRecord = useTargetRecord();
const { threads, getLinkIdsToThread, loading, error, refetch } =
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/WidgetActionChatThreadCreate.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/WidgetActionChatThreadCreate.tsx
index 40657bd2724..1bc13b19bda 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/WidgetActionChatThreadCreate.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/WidgetActionChatThreadCreate.tsx
@@ -33,8 +33,7 @@ export const WidgetActionChatThreadCreate = () => {
return null;
}
- // The mention files the new conversation under the record on its first
- // send, unless the member deletes it before sending.
+ // The mention files the new conversation under the record on first send, unless removed before sending.
const handleClick = () =>
openAskAiPageWithPreprompt({
serializedDocument: serializeMentionTagAsAdvancedTextEditorDocument({
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/ChatThreadsCardContent.test.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/ChatThreadsCardContent.test.tsx
index feda6b1d5c3..a5bce25a35f 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/ChatThreadsCardContent.test.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/ChatThreadsCardContent.test.tsx
@@ -34,8 +34,6 @@ const renderContent = ({
);
describe('ChatThreadsCardContent', () => {
- // Every state below renders with no threads in hand, which is exactly when
- // the card could claim "No conversations" without knowing that to be true.
it('does not claim the record has no conversations while loading', () => {
renderContent({ loading: true });
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidget.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidget.tsx
index 939d9edb821..8a0e340cfc7 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidget.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidget.tsx
@@ -34,8 +34,7 @@ const StyledRecordTargets = styled.div`
export const ChatWidget = () => {
const targetRecord = useTargetRecord();
const isInSidePanel = useWorkspaceSurface().type === 'side-panel';
- // Checked once, so leaving for the chat page later does not pull this chat
- // into it
+ // Checked once so leaving for the chat page later does not pull this chat into it
const [isOpenedBesideChatPage] = useState(
() => isInSidePanel && isCurrentPathAiChatPage(),
);
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetOpenInChatPageEffect.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetOpenInChatPageEffect.tsx
index 86d80c72ad4..cbef10412b8 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetOpenInChatPageEffect.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetOpenInChatPageEffect.tsx
@@ -7,8 +7,7 @@ type ChatWidgetOpenInChatPageEffectProps = {
threadId: string;
};
-// The chat page and the side panel would share one current chat, so a chat
-// opened beside the chat page moves into it
+// The chat page and side panel share one current chat, so it moves into the chat page
export const ChatWidgetOpenInChatPageEffect = ({
threadId,
}: ChatWidgetOpenInChatPageEffectProps) => {
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetThreadSyncEffect.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetThreadSyncEffect.tsx
index fa29df6ee4e..99c318f8ddc 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetThreadSyncEffect.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat/components/ChatWidgetThreadSyncEffect.tsx
@@ -8,8 +8,7 @@ type ChatWidgetThreadSyncEffectProps = {
threadId: string;
};
-// The chat runs on the current thread, so the widget points it at its record
-// once per record; a later switch, such as starting a new chat, is left alone
+// Points the chat at the record's thread once per record, so a later switch (e.g. a new chat) is left alone
export const ChatWidgetThreadSyncEffect = ({
threadId,
}: ChatWidgetThreadSyncEffectProps) => {
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetFilesPreview.tsx b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetFilesPreview.tsx
index 3da85e0444c..55309f72313 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetFilesPreview.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetFilesPreview.tsx
@@ -55,8 +55,7 @@ export const FieldWidgetFilesPreview = ({
.toLowerCase()
.replace('.', '');
- // Files the viewer cannot render already come with their own download
- // action inside the unavailable-preview state.
+ // Unpreviewable files get their own download action in the unavailable state.
const isPreviewable = PREVIEWABLE_EXTENSIONS.includes(fileExtension);
return (
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetJunctionRelationCard.tsx b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetJunctionRelationCard.tsx
index f0158ee556c..0c4cc4de767 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetJunctionRelationCard.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetJunctionRelationCard.tsx
@@ -22,8 +22,7 @@ export const FieldWidgetJunctionRelationCard = ({
junctionConfig,
});
- // Detach/delete in RecordDetailRelationRecordsListItem assumes a direct
- // relation, so junction cards are forced read-only to prevent data corruption.
+ // Forced read-only: detach/delete in RecordDetailRelationRecordsListItem assumes a direct relation and would corrupt junction data.
return (
<FieldWidgetRelationRecordsCard
fieldDefinition={fieldDefinition}
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsx b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsx
index 8329d26ab77..9420a4bf80f 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsx
@@ -72,8 +72,6 @@ export const FieldWidgetRelationTable = ({
const { view: persistedView } = useViewById(viewId ?? null);
- // Memoized so the derived picker parameters below keep a stable identity
- // and do not churn the widget provider's context value on every render.
const resolvedNestedRelation = useMemo(
() =>
resolveFieldWidgetNestedRelation({
@@ -88,10 +86,8 @@ export const FieldWidgetRelationTable = ({
],
);
- // A junction widget lists the records behind the junction, like the card
- // and field display modes. A morph junction has no single object to list,
- // and a view saved on the junction object predates junction traversal, so
- // both keep listing the junction records their view was built for.
+ // A junction widget lists the records behind the junction, except morph junctions and views saved on the
+ // junction object, which keep listing the junction records.
const junctionTargetObjectMetadataId =
isDefined(junctionConfig) && !junctionConfig.isMorphRelation
? junctionConfig.targetFields[0]?.relation?.targetObjectMetadata.id
@@ -108,12 +104,7 @@ export const FieldWidgetRelationTable = ({
isDefined(junctionTableObjectMetadataId) &&
junctionTableObjectMetadataId === junctionTargetObjectMetadataId;
- // A widget with a broken nested relation (deleted or deactivated second hop)
- // resolves to no object and so renders nothing, rather than falling back to
- // the first hop's records and silently showing a different object than the
- // widget title claims. Likewise a persisted view listing yet another object
- // belongs to a previous relation chain and must not be rendered under this
- // one.
+ // A broken chain or a view of another object renders nothing, not records the title doesn't claim.
const directTableObjectMetadataId =
junctionTableObjectMetadataId ?? relationObjectMetadataId;
@@ -190,9 +181,7 @@ export const FieldWidgetRelationTable = ({
recordId,
]);
- // A many-to-one first hop points at a single intermediate record, so the
- // terminal view is scoped directly by it: the intermediate becomes the
- // filter's current record, read from the current record's join column.
+ // A many-to-one first hop scopes the view directly by the intermediate record, read from the current record's join column.
const isManyToOneNestedChain =
isDefined(nestedRelationFieldMetadataId) &&
relationType === RelationType.MANY_TO_ONE;
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetActionVisibility.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetActionVisibility.ts
index ea1821ce8f1..cceb2632c13 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetActionVisibility.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetActionVisibility.ts
@@ -51,9 +51,7 @@ export const useFieldWidgetActionVisibility = ({
const isOneToManyRelation =
relationMetadata?.relationType === RelationType.ONE_TO_MANY;
- // "See all" links to the relation field's own index, which lists the first
- // hop. A nested widget lists the second hop, so the link would point at a
- // different object than the widget shows.
+ // "See all" opens the first hop's index, but a nested widget lists the second hop.
const isNestedRelationWidget = isDefined(
widget.configuration.nestedRelationFieldMetadataId,
);
@@ -83,9 +81,6 @@ export const useFieldWidgetActionVisibility = ({
objectPermissionsByObjectMetadataId,
});
- // The read-only chain already hides edit during layout customization
- // (useIsRecordReadOnly returns true then); the explicit check states the
- // rule here instead of leaving it implicit.
const showEdit =
!isPageLayoutInEditMode &&
!isFieldReadOnly &&
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetEligibleFields.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetEligibleFields.ts
index 4cca746a68b..942df8a954e 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetEligibleFields.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/hooks/useFieldWidgetEligibleFields.ts
@@ -8,8 +8,7 @@ export const useFieldWidgetEligibleFields = (objectNameSingular: string) => {
inlineFieldMetadataItems,
} = useFieldListFieldMetadataItems({
objectNameSingular,
- // Allow advanced relation fields targeting system objects (e.g. calendarEventParticipants)
- // to appear in the FieldWidget selector — the widget can render them as boxed relations.
+ // The widget renders relations to system objects (e.g. calendarEventParticipants) as boxed relations.
includeSystemObjectRelations: true,
});
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetEffectiveDisplayMode.test.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetEffectiveDisplayMode.test.ts
index 729be3a5896..cb3abc16cba 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetEffectiveDisplayMode.test.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetEffectiveDisplayMode.test.ts
@@ -27,8 +27,6 @@ describe('getFieldWidgetEffectiveDisplayMode', () => {
).toBe(FieldDisplayMode.TABLE);
});
- // An embedded view is the only thing the table display mode can render, so
- // without one the widget must fall back rather than render nothing.
it.each([undefined, ''])(
'should fall back to the field display mode when the view id is %p',
(viewId) => {
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetNestedRelationCreateThrough.test.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetNestedRelationCreateThrough.test.ts
index e88909ecf7c..9dedbd175fa 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetNestedRelationCreateThrough.test.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetNestedRelationCreateThrough.test.ts
@@ -31,8 +31,6 @@ describe('getFieldWidgetNestedRelationCreateThrough', () => {
});
it('should return undefined for a many-to-one first hop', () => {
- // The intermediate is unambiguous there, so the created record's join
- // column is prefilled from the seeded direct filter instead of a picker.
expect(
getFieldWidgetNestedRelationCreateThrough({
fieldRelationMetadata: {
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetRelationTraversal.test.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetRelationTraversal.test.ts
index b35f177aae2..ab445c207ef 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetRelationTraversal.test.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/__tests__/getFieldWidgetRelationTraversal.test.ts
@@ -62,16 +62,12 @@ describe('getFieldWidgetRelationTraversal', () => {
objectMetadataItems,
});
- // The embedded view lists the terminal object...
expect(traversal.targetObjectMetadataId).toBe(
opportunityObjectMetadataItem.id,
);
- // ...scoped by the second hop's inverse (opportunity -> person)...
expect(traversal.inverseFieldMetadataId).toBe(
personOpportunitiesField?.relation?.targetFieldMetadata.id,
);
- // ...traversed one relation further out via the first hop's inverse
- // (person -> company), which is what makes it a two-hop filter.
expect(traversal.relationTargetFieldMetadataId).toBe(
companyPeopleField?.relation?.targetFieldMetadata.id,
);
@@ -105,8 +101,6 @@ describe('getFieldWidgetRelationTraversal', () => {
expect(traversal.inverseFieldMetadataId).toBe(
companyOpportunitiesField?.relation?.targetFieldMetadata.id,
);
- // The intermediate is the single record the current record points at, so
- // the seeded filter is a direct one on the terminal object.
expect(traversal.relationTargetFieldMetadataId).toBeNull();
});
@@ -116,16 +110,10 @@ describe('getFieldWidgetRelationTraversal', () => {
objectMetadataItems,
});
- // The embedded view lists the records behind the junction (companies),
- // not the junction records (employment histories)...
expect(traversal.targetObjectMetadataId).toBe(companyObjectMetadataItem.id);
- // ...scoped by the target's own junction relation (company -> employment
- // histories)...
expect(traversal.inverseFieldMetadataId).toBe(
companyPreviousEmployeesField?.id,
);
- // ...traversed to the junction field pointing at the current record
- // (employment history -> person).
expect(traversal.relationTargetFieldMetadataId).toBe(
employmentHistoryPersonField?.id,
);
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetEffectiveDisplayMode.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetEffectiveDisplayMode.ts
index 0e1872e3d2e..6511e202275 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetEffectiveDisplayMode.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetEffectiveDisplayMode.ts
@@ -3,10 +3,7 @@ import { getWidgetConfigurationViewId } from '@/page-layout/utils/getWidgetConfi
import { isDefined } from 'twenty-shared/utils';
import { FieldDisplayMode } from '~/generated-metadata/graphql';
-// The table display mode renders an embedded view, so it only means anything
-// once the widget has one. A widget stranded in that mode without a view — its
-// view deleted, or a layout picked before one could be created — renders its
-// inline relation instead of an empty card.
+// Table mode without a view (deleted, or not yet created) falls back to the inline relation.
export const getFieldWidgetEffectiveDisplayMode = (
configuration: FieldConfiguration,
): FieldDisplayMode =>
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetNestedRelationCreateThrough.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetNestedRelationCreateThrough.ts
index 980c695aa18..12ff0e9ddb8 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetNestedRelationCreateThrough.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetNestedRelationCreateThrough.ts
@@ -19,10 +19,7 @@ export const getFieldWidgetNestedRelationCreateThrough = ({
nestedRelationFieldMetadataItem: FieldMetadataItem;
recordId: string;
}): RecordTableWidgetNestedRelationCreateThrough | undefined => {
- // Only a one-to-many first hop leaves the record to create through
- // ambiguous. A many-to-one first hop points at a single intermediate
- // record, so the created record's join column is prefilled from the
- // seeded direct filter instead of a picker.
+ // A many-to-one first hop is unambiguous: the join column is prefilled from the seeded filter.
if (fieldRelationMetadata.relationType !== RelationType.ONE_TO_MANY) {
return undefined;
}
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetRelationTraversal.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetRelationTraversal.ts
index 237a98f350d..5a0948bb628 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetRelationTraversal.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/getFieldWidgetRelationTraversal.ts
@@ -26,11 +26,7 @@ const EMPTY_TRAVERSAL: FieldWidgetRelationTraversal = {
relationTargetFieldMetadataId: null,
};
-// A junction relation lists the records behind the junction, like the card
-// and field display modes do, so the embedded view targets the junction
-// target object and scopes it back through the junction: the target's inverse
-// field, traversed to the junction field pointing at the current record. A
-// morph junction has no single object to list, so it gets no embedded view.
+// Lists the junction's target records, scoped back through the junction; morph junctions get no view.
const getFieldWidgetJunctionTraversal = (
junctionConfig: FieldWidgetJunctionConfig,
): FieldWidgetRelationTraversal => {
@@ -56,10 +52,7 @@ const getFieldWidgetJunctionTraversal = (
};
};
-// The widget's embedded view lists records of the last hop's target object,
-// scoped back to the current record through that hop's inverse relation. A
-// nested widget scopes one relation further out, which the seeded view filter
-// expresses as relationTargetFieldMetadataId: the first hop's inverse.
+// A nested widget scopes one relation further out via relationTargetFieldMetadataId (the first hop's inverse).
export const getFieldWidgetRelationTraversal = ({
sourceFieldMetadataItem,
nestedRelationFieldMetadataItem,
@@ -81,11 +74,7 @@ export const getFieldWidgetRelationTraversal = ({
const lastHopFieldMetadataItem =
nestedRelationFieldMetadataItem ?? sourceFieldMetadataItem;
- // Only a one-to-many first hop needs the traversal: its intermediate
- // records carry the join column pointing back at the current record. A
- // many-to-one first hop points at a single intermediate record, which the
- // widget supplies as the filter's current record, so the seeded filter
- // stays a direct one.
+ // Only a one-to-many first hop needs traversal; a many-to-one first hop is supplied as the filter's current record, so the filter stays direct.
const shouldTraverseFirstHop =
isDefined(nestedRelationFieldMetadataItem) &&
isDefined(sourceFieldMetadataItem) &&
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/isFieldWidgetEligibleNestedParentField.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/isFieldWidgetEligibleNestedParentField.ts
index af91ae8bde9..dfea38341ba 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/isFieldWidgetEligibleNestedParentField.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/isFieldWidgetEligibleNestedParentField.ts
@@ -2,10 +2,7 @@ import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataIte
import { isPlainManyToOneRelationField } from '@/object-record/utils/isPlainManyToOneRelationField';
import { isPlainOneToManyRelationField } from '@/object-record/utils/isPlainOneToManyRelationField';
-// A nested chain can start from either relation direction: a one-to-many
-// first hop scopes the terminal view through a relation traversal filter,
-// while a many-to-one first hop scopes it directly by the single related
-// record the current record points at.
+// Either first-hop direction works: one-to-many through a traversal filter, many-to-one directly.
export const isFieldWidgetEligibleNestedParentField = (
fieldMetadataItem: FieldMetadataItem,
): fieldMetadataItem is FieldMetadataItem & {
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/resolveFieldWidgetNestedRelation.ts b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/resolveFieldWidgetNestedRelation.ts
index 65d43905587..ea781fc931d 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/field/utils/resolveFieldWidgetNestedRelation.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/utils/resolveFieldWidgetNestedRelation.ts
@@ -16,10 +16,7 @@ type ResolvedFieldWidgetNestedRelation = {
nestedRelationTargetObjectMetadataItem: EnrichedObjectMetadataItem;
};
-// Resolves the second hop of a nested relation field widget: the one-to-many
-// relation field on the first hop's target object, and the terminal object
-// whose records the widget lists. Returns undefined when the chain is broken
-// (deleted or deactivated field) so callers can degrade gracefully.
+// Returns undefined when the chain is broken (deleted or deactivated field).
export const resolveFieldWidgetNestedRelation = ({
objectMetadataItems,
relationTargetObjectMetadataId,
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/fields/components/__stories__/FieldsWidget.stories.tsx b/packages/twenty-front/src/modules/page-layout/widgets/fields/components/__stories__/FieldsWidget.stories.tsx
index 99fc1ab6ceb..b6202235a18 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/fields/components/__stories__/FieldsWidget.stories.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/fields/components/__stories__/FieldsWidget.stories.tsx
@@ -480,13 +480,7 @@ export const Empty: Story = {
},
};
-// Hovering a field mounts an interactive copy of the cell through
-// RecordInlineCellAnchoredPortal, which finds its anchor with
-// document.getElementById after resolving the list instance id through
-// useAvailableComponentInstanceIdOrThrow -- and that resolution surface-scopes
-// the id. If the list rendered its anchors from an unscoped id, the lookup
-// misses, nothing interactive mounts, and the click lands on the inert display
-// underneath: the cell highlights but no editor ever opens.
+// The anchored portal looks up a surface-scoped id; an unscoped anchor id would leave the cell inert.
const openEditModeOnEmployees = async ({
canvasElement,
}: {
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsx b/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsx
index 573e775a26a..c9c2f199078 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsx
@@ -67,9 +67,7 @@ export const RecordTableWidgetRendererContent = ({
const isCalendarLayout = widgetViewLayout === ViewType.CALENDAR;
- // Widget calendars are read-only month projections, except live (non
- // edit-mode) day/week calendars, which allow drag-to-reschedule and
- // record creation under the usual object permissions.
+ // Live day/week widget calendars allow rescheduling and creation; month and edit mode are read-only.
const isCalendarDayOrWeek =
widgetView?.calendarLayout === ViewCalendarLayout.DAY ||
widgetView?.calendarLayout === ViewCalendarLayout.WEEK;
@@ -77,8 +75,7 @@ export const RecordTableWidgetRendererContent = ({
isCalendarLayout && !isPageLayoutInEditMode && isCalendarDayOrWeek;
const calendarIsReadOnly = !canEditCalendar;
- // Keyed rather than chained so a layout added to RECORD_TABLE_WIDGET_LAYOUTS
- // fails to compile here instead of silently rendering as a table.
+ // Keyed so a new RECORD_TABLE_WIDGET_LAYOUTS entry fails to compile instead of rendering as a table.
const renderWidgetForLayout = {
[ViewType.TABLE]: () => (
<RecordTableWidget
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/__tests__/RecordTableWidgetRendererContent.test.tsx b/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/__tests__/RecordTableWidgetRendererContent.test.tsx
index 4375fa21a0b..9acb01e7062 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/__tests__/RecordTableWidgetRendererContent.test.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/__tests__/RecordTableWidgetRendererContent.test.tsx
@@ -109,8 +109,6 @@ describe('RecordTableWidgetRendererContent', () => {
},
);
- // A layout that fell through to the table renderer was the bug this widget
- // type set out to fix, so every layout has to claim its own renderer.
it.each([
[ViewType.TABLE_WIDGET, 'record table widget'],
[ViewType.KANBAN_WIDGET, 'record board widget'],
@@ -122,7 +120,6 @@ describe('RecordTableWidgetRendererContent', () => {
expect(screen.getByText(expectedWidget)).toBeVisible();
});
- // A widget can be backed by a plain view, which keeps that view's layout.
it('should render a non-widget list view as a list', () => {
renderWidgetForViewType(ViewType.LIST);
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/__tests__/useResolveFieldWidgetRelationTableViewIdChange.test.tsx b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/__tests__/useResolveFieldWidgetRelationTableViewIdChange.test.tsx
index 70004b1aaab..11c2becc78d 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/__tests__/useResolveFieldWidgetRelationTableViewIdChange.test.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/__tests__/useResolveFieldWidgetRelationTableViewIdChange.test.tsx
@@ -123,8 +123,6 @@ describe('useResolveFieldWidgetRelationTableViewIdChange', () => {
expect(draft[WIDGET_ID].view.objectMetadataId).toBe(
opportunityObjectMetadataItem.id,
);
- // The intermediate is the single record the current record points at, so
- // the seeded filter carries no relation traversal.
expect(draft[WIDGET_ID].viewFilters).toEqual([
expect.objectContaining({
fieldMetadataId:
@@ -157,8 +155,6 @@ describe('useResolveFieldWidgetRelationTableViewIdChange', () => {
}),
);
- // The view lists companies, not employment histories, scoped back to the
- // current person through the junction.
expect(draft[WIDGET_ID].view.objectMetadataId).toBe(
companyObjectMetadataItem.id,
);
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useInitializeRecordTableWidgetViewDrafts.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useInitializeRecordTableWidgetViewDrafts.ts
index b6657b208d1..197f8e0bb89 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useInitializeRecordTableWidgetViewDrafts.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useInitializeRecordTableWidgetViewDrafts.ts
@@ -10,12 +10,8 @@ import { viewsSelector } from '@/views/states/selectors/viewsSelector';
import { useStore } from 'jotai';
import { useEffect } from 'react';
-// Seeds the editable view snapshot of every widget backed by a persisted
-// view as soon as the layout is in edit mode, and again whenever a widget
-// gains a view (e.g. a field widget configured to table display) or views
-// finish loading. The draft is the write target of all widget view settings,
-// so it must exist before any of them run — including the ones in the side
-// panel, which mounts outside this layout tree and cannot seed it itself.
+// The draft is every widget view setting's write target, so it must exist before any runs, including in the side
+// panel, which mounts outside this layout tree and can't seed it.
export const useInitializeRecordTableWidgetViewDrafts = () => {
const isPageLayoutInEditMode = useIsPageLayoutInEditMode();
@@ -52,8 +48,7 @@ export const useInitializeRecordTableWidgetViewDrafts = () => {
return;
}
- // Spread order lets entries added elsewhere in the meantime win over the
- // freshly built snapshots.
+ // Entries added elsewhere meanwhile win over the fresh snapshots.
store.set(recordTableWidgetViewDraftState, (previousSnapshots) => ({
...missingSnapshotsByWidgetId,
...previousSnapshots,
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutCallbacks.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutCallbacks.ts
index 6a3ea538d52..77f0c7d773e 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutCallbacks.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutCallbacks.ts
@@ -25,8 +25,7 @@ export const useRecordTableWidgetLayoutCallbacks = ({
const store = useStore();
- // Returning the received snapshot unchanged from the updater leaves the
- // whole draft map untouched (no state update is published).
+ // Returning the snapshot unchanged publishes no state update.
const setWidgetViewDraft = useCallback(
(
updater: (
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutPickerOptions.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutPickerOptions.ts
index e2100b83dca..cbd01894396 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutPickerOptions.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useRecordTableWidgetLayoutPickerOptions.ts
@@ -4,9 +4,6 @@ import { getRecordTableWidgetLayoutPickerOptions } from '@/page-layout/widgets/r
import { isFieldMetadataItemAvailableAsWidgetGroupByField } from '@/page-layout/widgets/record-table/utils/isFieldMetadataItemAvailableAsWidgetGroupByField';
import { isDefined } from 'twenty-shared/utils';
-// Which layouts a record table widget over this object can offer, plus the
-// fields a layout switch needs to seed. Both layout pickers ask this so they
-// cannot disagree about what is on offer.
export const useRecordTableWidgetLayoutPickerOptions = (
objectMetadataItem: EnrichedObjectMetadataItem | undefined,
) => {
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useResolveFieldWidgetRelationTableViewIdChange.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useResolveFieldWidgetRelationTableViewIdChange.ts
index 69c2a6b2804..02c8acffb68 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useResolveFieldWidgetRelationTableViewIdChange.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/hooks/useResolveFieldWidgetRelationTableViewIdChange.ts
@@ -28,11 +28,7 @@ export const useResolveFieldWidgetRelationTableViewIdChange = (
const objectMetadataItems = useAtomStateValue(objectMetadataItemsSelector);
- // The embedded view must always list the selected chain's terminal object.
- // Whenever the selection results in a table widget, a fresh draft view is
- // generated on a chain change or a missing view id; otherwise a view id
- // belonging to the previous chain is cleared so the layout dropdown can
- // lazily create the right one.
+ // The view must list the chain's terminal object: regenerate on chain change, else clear a stale id for lazy creation.
const resolveFieldWidgetRelationTableViewIdChange = ({
selectedField,
selectedNestedField,
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/RecordTableWidgetLayoutViewType.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/RecordTableWidgetLayoutViewType.ts
index 3406d26f383..30ef44cdd8e 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/RecordTableWidgetLayoutViewType.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/RecordTableWidgetLayoutViewType.ts
@@ -46,9 +46,6 @@ export const RECORD_TABLE_WIDGET_LAYOUT_OPTIONS = {
}
>;
-// A widget view backed by a record table renders as a table unless its type
-// names another layout, so anything else — including a missing view — reads as
-// TABLE_WIDGET.
export const getRecordTableWidgetLayoutViewType = (
viewType: ViewType | null | undefined,
): RecordTableWidgetLayoutViewType =>
@@ -56,8 +53,7 @@ export const getRecordTableWidgetLayoutViewType = (
(layoutViewType) => layoutViewType === viewType,
) ?? ViewType.TABLE_WIDGET;
-// The layouts a record table widget can render, as opposed to the widget view
-// types above: a widget backed by a plain LIST view still renders as a list.
+// Layouts the widget can render, unlike the widget view types above: a plain LIST view still renders as a list.
export const RECORD_TABLE_WIDGET_LAYOUTS = [
ViewType.TABLE,
ViewType.KANBAN,
@@ -81,7 +77,6 @@ export const isRecordTableWidgetContentEditingSupported = (
) => {
const layout = getRecordTableWidgetLayout(viewType);
- // List is intrinsically read-only. Calendar editing needs layout-specific
- // rules before it can share this setting and is deferred to a follow-up PR.
+ // List is read-only by nature. TODO: let calendar share this setting once it has layout-specific editing rules.
return layout === ViewType.TABLE || layout === ViewType.KANBAN;
};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/__tests__/RecordTableWidgetLayoutViewType.test.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/__tests__/RecordTableWidgetLayoutViewType.test.ts
index cf21d24c057..16cb672e079 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/__tests__/RecordTableWidgetLayoutViewType.test.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/types/__tests__/RecordTableWidgetLayoutViewType.test.ts
@@ -60,7 +60,6 @@ describe('getRecordTableWidgetLayout', () => {
expect(getRecordTableWidgetLayout(viewType)).toBe(expectedLayout);
});
- // A widget backed by a plain view keeps that view's layout.
it.each([
[ViewType.LIST, ViewType.LIST],
[ViewType.KANBAN, ViewType.KANBAN],
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildDraftViewGroupsForFieldMetadataItem.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildDraftViewGroupsForFieldMetadataItem.ts
index 9f1841c7ef6..9e746703e9c 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildDraftViewGroupsForFieldMetadataItem.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildDraftViewGroupsForFieldMetadataItem.ts
@@ -4,10 +4,7 @@ import { isManyToOneRelationField } from '@/object-metadata/utils/isManyToOneRel
import { VIEW_GROUP_VISIBLE_OPTIONS_MAX } from 'twenty-shared/constants';
import { v4 } from 'uuid';
-// Mirrors the server-side computeFlatViewGroupsOnViewCreate so the edit-mode draft
-// preview matches what the server generates on save: one group per select option (in
-// option order), none for relations since their groups are picked by the user, plus
-// an empty group for nullable fields.
+// Mirrors the server's computeFlatViewGroupsOnViewCreate so the draft preview matches what save generates.
export const buildDraftViewGroupsForFieldMetadataItem = ({
viewId,
fieldMetadataItem,
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildMissingRecordTableWidgetViewDraftSnapshots.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildMissingRecordTableWidgetViewDraftSnapshots.ts
index bbd3a769fc1..bdf0f791acb 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildMissingRecordTableWidgetViewDraftSnapshots.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/buildMissingRecordTableWidgetViewDraftSnapshots.ts
@@ -37,8 +37,7 @@ export const buildMissingRecordTableWidgetViewDraftSnapshots = ({
const view = views.find((viewToFind) => viewToFind.id === viewId);
- // A view without fields has not finished being created server-side;
- // snapshotting it now would lock an empty column set into the draft.
+ // No fields yet means server-side creation hasn't finished; snapshotting would lock in an empty column set.
if (!isDefined(view) || view.viewFields.length === 0) {
continue;
}
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/getRecordTableWidgetLayoutPickerOptions.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/getRecordTableWidgetLayoutPickerOptions.ts
index 1ed550f567d..bed2722ba87 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/getRecordTableWidgetLayoutPickerOptions.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/getRecordTableWidgetLayoutPickerOptions.ts
@@ -22,9 +22,6 @@ type GetRecordTableWidgetLayoutPickerOptionsParams = {
isCalendarAvailable: boolean;
};
-// Kanban and calendar stay visible but disabled when the object has no field
-// to drive them, so the layout exists in the picker with the reason why it
-// can't be picked.
export const getRecordTableWidgetLayoutPickerOptions = ({
isKanbanAvailable,
isCalendarAvailable,
@@ -59,8 +56,7 @@ export const getSelectableLayoutViewTypes = (
.filter((layoutOption) => !layoutOption.isDisabled)
.map((layoutOption) => layoutOption.viewType);
-// A layout that is disabled must not be applied even if its row is reached by
-// keyboard, so selection asks the same options the picker renders.
+// A disabled row can still be reached by keyboard, so selection checks the same options the picker renders.
export const isSelectableLayout = (
layoutOptions: RecordTableWidgetLayoutPickerOption[],
viewType: RecordTableWidgetLayoutViewType,
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/isFieldMetadataItemAvailableAsWidgetGroupByField.ts b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/isFieldMetadataItemAvailableAsWidgetGroupByField.ts
index 34aa1cfe603..e457254cf05 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/isFieldMetadataItemAvailableAsWidgetGroupByField.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/utils/isFieldMetadataItemAvailableAsWidgetGroupByField.ts
@@ -2,9 +2,7 @@ import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataIte
import { canGroupRecordsByFieldMetadataItem } from '@/object-record/record-group/utils/canGroupRecordsByFieldMetadataItem';
import { FieldMetadataType } from 'twenty-shared/types';
-// Widgets only offer select-field grouping: the server auto-generates
-// view groups from select options, and widgets have no per-record
-// add-group flow like the record index page.
+// Select fields only: the server generates their groups and widgets lack an add-group flow.
export const isFieldMetadataItemAvailableAsWidgetGroupByField = (
fieldMetadataItem: FieldMetadataItem,
) =>
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCard.tsx b/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCard.tsx
index fcfc028497c..549e63612cb 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCard.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCard.tsx
@@ -33,9 +33,7 @@ const shouldUseSecondaryBackground = (
props: Pick<WidgetCardStyledProps, 'variant' | 'isEditable' | 'isDragging'>,
) => (props.isEditable && props.isDragging) || props.variant === 'framed';
-// The card is the single owner of how far its header and body are inset:
-// WidgetCardHeader and WidgetCardContent both read these, widget bodies never
-// declare their own inline padding.
+// WidgetCardHeader and WidgetCardContent read these insets; widget bodies never declare their own padding.
// oxlint-disable-next-line twenty/sort-css-properties-alphabetically
const StyledWidgetCard = styled.div<WidgetCardStyledProps>`
--widget-card-padding-inline: ${({ variant, isEditable }) =>
@@ -56,8 +54,7 @@ const StyledWidgetCard = styled.div<WidgetCardStyledProps>`
: 'transparent';
}};
- // Declared only when the card actually paints a surface, so a transparent
- // card leaves the layout container's value in place for its content to read.
+ // Only when painting a surface, so a transparent card leaves the container's value for its content.
&[data-secondary-background='true'] {
--record-card-background-color: ${themeCssVariables.background.secondary};
}
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardHeaderActionsRenderer.tsx b/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardHeaderActionsRenderer.tsx
index 912d14cbfec..bb2d722625d 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardHeaderActionsRenderer.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardHeaderActionsRenderer.tsx
@@ -23,9 +23,7 @@ export const WidgetCardHeaderActionsRenderer = () => {
return null;
}
- // Activity actions create records, so they hide while the layout is being
- // arranged. Field widgets keep their actions: see-all is a read-only link,
- // and edit hides itself through useFieldWidgetActionVisibility.
+ // Activity actions create records, so they hide while arranging; field widget actions handle their own visibility.
if (isPageLayoutInEditMode && widget.type !== WidgetType.FIELD) {
return null;
}
diff --git a/packages/twenty-front/src/modules/settings/accounts/components/message-folders/SettingsMessageFoldersBreadcrumb.tsx b/packages/twenty-front/src/modules/settings/accounts/components/message-folders/SettingsMessageFoldersBreadcrumb.tsx
index 29b05f19b31..73bea909359 100644
--- a/packages/twenty-front/src/modules/settings/accounts/components/message-folders/SettingsMessageFoldersBreadcrumb.tsx
+++ b/packages/twenty-front/src/modules/settings/accounts/components/message-folders/SettingsMessageFoldersBreadcrumb.tsx
@@ -10,8 +10,7 @@ export type SettingsMessageFoldersBreadcrumbProps = {
parentsIsLastList: boolean[];
};
-// Every offset here is an inset from the side the tree grows out of, so the
-// whole connector mirrors with the document under dir="rtl".
+// Insets from the side the tree grows out of, so the connector mirrors under dir="rtl".
const StyledBreadcrumbOverlay = styled.div<{ depth: number }>`
height: 28px;
inset-inline-start: 0;
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx b/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx
index d2b3d0aabc9..4b18130e31a 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx
@@ -131,8 +131,7 @@ export const SettingsAdminAI = () => {
const defaultModelByTier = data?.getAdminAiModels?.defaultModelByTier ?? [];
- // A tier default names the model that answers chats and agent runs, so only a
- // language model can fill one: an evaluation model here is refused server-side.
+ // Tier defaults answer chats and agent runs, so the server refuses evaluation models here.
const enabledModels = models.filter(
(model) =>
model.kind === 'language' &&
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/constants/ProviderConfig.ts b/packages/twenty-front/src/modules/settings/admin-panel/ai/constants/ProviderConfig.ts
index 8e617c30979..0896582ac9a 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/ai/constants/ProviderConfig.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/constants/ProviderConfig.ts
@@ -17,7 +17,6 @@ export const PROVIDER_ICON_CONFIG: Record<string, { Icon: IconComponent }> = {
mistral: { Icon: IconBrandMistral },
xai: { Icon: IconBrandXai },
'openai-compatible': { Icon: IconProviderOpenai },
- // models.dev serves no logo for an evaluation-only provider, and the fallback
- // renders a broken image rather than nothing.
+ // models.dev has no logo for evaluation-only providers and the fallback renders a broken image.
'typesafe-ai': { Icon: IconBrandTypesafeAi },
};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/hooks/useCustomAiProviderAccess.ts b/packages/twenty-front/src/modules/settings/admin-panel/ai/hooks/useCustomAiProviderAccess.ts
index 660264e72ec..61a8463862e 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/ai/hooks/useCustomAiProviderAccess.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/hooks/useCustomAiProviderAccess.ts
@@ -17,9 +17,7 @@ export const useCustomAiProviderAccess = () => {
const access = data?.getCustomAiProviderAccess;
- // Only assume access while the query is in flight, so the section never
- // flashes its locked state; once it settles without an answer the creation
- // paths stay closed rather than failing at the mutation.
+ // Assume access only while loading, so the section never flashes locked; with no answer, creation stays closed.
const hasAccess = access?.hasAccess ?? loading;
const tooltipContent = !isDefined(access)
@@ -32,8 +30,6 @@ export const useCustomAiProviderAccess = () => {
? t`Custom providers are complimentary up to ${access.seatThreshold} seats. This instance has ${access.seatCount}. Upgrade to add more.`
: t`This instance's plan could not be verified. Reload the page to try again.`;
- // The seat count and threshold stay internal: every caller wants the copy
- // built from them, not the numbers.
return {
hasAccess,
tooltipContent,
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx
index 5f4e45772de..abcf8f003b2 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx
@@ -61,11 +61,7 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({
);
const [reason, setReason] = useState('');
const [expiresInDays, setExpiresInDays] = useState<number | null>(null);
- // Identifies one intended grant, so a RetryLink retry or a resubmit after a
- // lost response is answered with the grant the first attempt wrote rather
- // than crediting the workspace twice. Keyed on the submitted values, since
- // editing the amount and resubmitting is a different intent that must not be
- // answered with the earlier grant.
+ // Idempotency key per submitted values: retries reuse it, an edited amount is a new grant.
const [submittedGrant, setSubmittedGrant] = useState<{
payload: string;
clientOperationId: string;
@@ -82,8 +78,7 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({
const parsedAmount = Number(amount);
const isAmountValid = Number.isFinite(parsedAmount) && parsedAmount > 0;
- // The modal is mounted for the whole page, so without this the next admin to
- // open it starts from the last grant's amount and reason.
+ // The modal stays mounted, so reset it for the next admin.
const handleClose = () => {
setAmount('');
setType(BillingCreditGrantType.COMPENSATION);
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx
index 9c0503d0b81..03395a6b27c 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx
@@ -38,10 +38,7 @@ type SettingsAdminWorkspaceCreditGrantsTableProps = {
onGrantCreditsClick: () => void;
};
-// Every row is its own grid, so a fr track is sized by that row's own content
-// and a wide tag pushes the columns after it out of line with the rows above.
-// Fixed widths for all but the reason, which takes what is left because its
-// cell hides the overflow.
+// Each row is its own grid, so fr tracks would misalign rows; only the overflow-hidden reason flexes.
const CREDIT_GRANTS_GRID_AUTO_COLUMNS = '88px 140px 88px 108px 108px 1fr 36px';
const REVOKE_CREDIT_GRANT_MODAL_ID = 'revoke-credit-grant-modal';
const EM_DASH = '—';
@@ -96,9 +93,7 @@ export const SettingsAdminWorkspaceCreditGrantsTable = ({
};
const handleRevoke = async (creditGrantId: string) => {
- // The refetch that clears the row lands well after the mutation resolves,
- // so without this the button stays live and a second click revokes an
- // already revoked grant.
+ // The refetch removing the row lands well after the mutation, so block a second revoke.
setIsRevoking(true);
try {
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantExpiryOptions.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantExpiryOptions.ts
index ce26a9a20d7..61f711bee44 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantExpiryOptions.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantExpiryOptions.ts
@@ -1,10 +1,7 @@
import { type MessageDescriptor } from '@lingui/core';
import { msg } from '@lingui/core/macro';
-// Null is the default: credits stay spendable until they are used up. The
-// bounded choices exist for deliberately time-boxed handouts. The server rounds
-// the chosen day up to the end of the billing period it falls in, because
-// credits are only ever spent and settled a period at a time.
+// Null (default) keeps credits until used up; the server rounds a chosen day up to its billing period end, as credits settle per period.
export const CREDIT_GRANT_EXPIRY_OPTIONS: {
value: number | null;
label: MessageDescriptor;
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts
index 3c2346456e1..13dd2b18fb8 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts
@@ -1,8 +1,6 @@
import { BillingCreditGrantType } from '~/generated-admin/graphql';
-// Rollover grants are written by the period transition and onboarding rewards
-// by the onboarding jobs, so neither can be written by hand. The server
-// enforces this too, in ADMIN_GRANTABLE_CREDIT_GRANT_TYPES.
+// Rollover and onboarding grants are written by jobs; the server enforces ADMIN_GRANTABLE_CREDIT_GRANT_TYPES too.
export const GRANTABLE_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [
BillingCreditGrantType.COMPENSATION,
BillingCreditGrantType.SALES,
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/collapseCreditGrantChains.test.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/collapseCreditGrantChains.test.ts
index ea6db8cd820..8b10b7145e1 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/collapseCreditGrantChains.test.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/collapseCreditGrantChains.test.ts
@@ -45,8 +45,7 @@ describe('collapseCreditGrantChains', () => {
expect(rows.map((row) => row.current.id)).toEqual(['b', 'a2']);
});
- // Revoking a grant leaves its successors behind, and a truncated list is the
- // normal case once older rows are filtered out server side.
+ // Revoked sources and server-truncated lists both leave successors without their source.
it('treats a grant whose source is missing as an origin of its own', () => {
const orphan = grant('b', 20, 'missing');
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/formatSubscriptionItemValue.test.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/formatSubscriptionItemValue.test.ts
index 3082c11eead..58db8f7efb3 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/formatSubscriptionItemValue.test.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/formatSubscriptionItemValue.test.ts
@@ -62,8 +62,6 @@ describe('formatSubscriptionItemValue', () => {
});
it('formats the amount through the caller formatter, not its own', () => {
- // The digits have to honour the workspace member's number format, so the
- // injected formatter is what decides how an amount reads.
expect(
formatSubscriptionItemValue({
item: {
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/collapseCreditGrantChains.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/collapseCreditGrantChains.ts
index 1f031e14b6b..f08b7b0a725 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/collapseCreditGrantChains.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/collapseCreditGrantChains.ts
@@ -6,21 +6,15 @@ type CreditGrantChainLink = {
};
export type CollapsedCreditGrant<TGrant extends CreditGrantChainLink> = {
- // The origin's id, which stays the same as the grant is settled from one
- // period to the next.
+ // The origin's id, stable across period settlements.
id: string;
- // The row still holding the credits: its amount is what is left of the grant
- // and its status is the one that matters.
+ // The row still holding the credits: its amount and status are current.
current: TGrant;
- // The row the operator actually created, which carries the reason they typed
- // and the date they handed the credits out.
+ // The row the operator created, carrying their reason and date.
origin: TGrant;
};
-// Every period transition settles a grant and writes its unspent part as a new
-// row, so one handout of credits shows up once per period it survived. The rows
-// are linked by sourceGrantId, so the chain can be shown as the single grant it
-// represents.
+// Each period transition writes a grant's unspent part as a new row linked by sourceGrantId.
export const collapseCreditGrantChains = <TGrant extends CreditGrantChainLink>(
creditGrants: TGrant[],
): CollapsedCreditGrant<TGrant>[] => {
@@ -56,8 +50,7 @@ export const collapseCreditGrantChains = <TGrant extends CreditGrantChainLink>(
return { id: origin.id, current, origin };
};
- // A grant whose source is not in the list still reads as an origin, because
- // truncating the chain is better than dropping the row.
+ // A grant whose source is missing reads as an origin: a truncated chain beats a dropped row.
const rows = creditGrants
.filter(
(grant) =>
@@ -69,8 +62,7 @@ export const collapseCreditGrantChains = <TGrant extends CreditGrantChainLink>(
return rows;
}
- // Only reachable if the ledger ever held a cycle, which it should not. Rows
- // no walk touched are still shown on their own rather than disappearing.
+ // Only reachable on a ledger cycle; untouched rows still show on their own.
const orphanedRows = creditGrants
.filter((grant) => !collapsedIds.has(grant.id))
.map((grant) => ({ id: grant.id, current: grant, origin: grant }));
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/formatSubscriptionItemValue.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/formatSubscriptionItemValue.ts
index a479b16557b..ac92ed2dbf6 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/formatSubscriptionItemValue.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/formatSubscriptionItemValue.ts
@@ -22,9 +22,7 @@ type FormatSubscriptionItemValueArgs = {
) => string;
};
-// Only the symbol comes from Intl. The digits go through formatNumber like
-// every other number on the page, so an amount does not ignore the workspace
-// member's number format while the counts beside it honour it.
+// Only the symbol comes from Intl; digits use formatNumber to honour the member's number format.
const getCurrencySymbol = (currency: string): string => {
const normalizedCurrency = currency.toUpperCase();
@@ -50,9 +48,7 @@ export const formatSubscriptionItemValue = ({
const parts: string[] = [];
if (isDefined(item.quantity)) {
- // Only a licensed base-product item sells seats. A metered item carries a
- // Stripe bookkeeping quantity that bills nothing, so naming it seats states
- // something untrue about what the workspace is paying for.
+ // Metered items carry a Stripe bookkeeping quantity that bills nothing, so only licensed base items are seats.
parts.push(
item.productKey === BillingProductKey.BASE_PRODUCT
? `${formatNumber(item.quantity)} ${plural(item.quantity, {
diff --git a/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelsTable.tsx b/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelsTable.tsx
index 5d5c8e10475..fb276a5eab2 100644
--- a/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelsTable.tsx
+++ b/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelsTable.tsx
@@ -42,8 +42,7 @@ const StyledDeprecatedSuffix = styled.span`
color: ${themeCssVariables.font.color.light};
`;
-// An evaluation model cannot be chatted with or given to an agent, so a row
-// that looks like every other row would read as interchangeable with them.
+// Evaluation models can't chat or run agents, so their rows are badged apart.
const StyledKindBadge = styled.span`
background: ${themeCssVariables.background.transparent.light};
border-radius: ${themeCssVariables.border.radius.sm};
diff --git a/packages/twenty-front/src/modules/settings/ai/types/PinnableAiModel.ts b/packages/twenty-front/src/modules/settings/ai/types/PinnableAiModel.ts
index 17e2cf50d1c..e2c7ffc47dc 100644
--- a/packages/twenty-front/src/modules/settings/ai/types/PinnableAiModel.ts
+++ b/packages/twenty-front/src/modules/settings/ai/types/PinnableAiModel.ts
@@ -1,6 +1,5 @@
import { type ModelFamily } from '~/generated-metadata/graphql';
-// The fields a pin select needs, shared by the workspace and admin model DTOs.
export type PinnableAiModel = {
modelId: string;
label: string;
diff --git a/packages/twenty-front/src/modules/settings/ai/utils/getAiModelBlendedCostPerMillionTokens.ts b/packages/twenty-front/src/modules/settings/ai/utils/getAiModelBlendedCostPerMillionTokens.ts
index 006a9b18565..ed48199ec57 100644
--- a/packages/twenty-front/src/modules/settings/ai/utils/getAiModelBlendedCostPerMillionTokens.ts
+++ b/packages/twenty-front/src/modules/settings/ai/utils/getAiModelBlendedCostPerMillionTokens.ts
@@ -2,8 +2,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type ClientAiModelConfig } from '~/generated-metadata/graphql';
-// The 3:1 input to output split Artificial Analysis uses for its blended price,
-// so the number lines up with what a reader will find on their site.
+// Artificial Analysis's 3:1 input/output blend, so the number matches their site.
const INPUT_WEIGHT = 3;
const OUTPUT_WEIGHT = 1;
diff --git a/packages/twenty-front/src/modules/settings/ai/utils/getAiModelPinOptions.ts b/packages/twenty-front/src/modules/settings/ai/utils/getAiModelPinOptions.ts
index 621e259906c..c4c92a903a5 100644
--- a/packages/twenty-front/src/modules/settings/ai/utils/getAiModelPinOptions.ts
+++ b/packages/twenty-front/src/modules/settings/ai/utils/getAiModelPinOptions.ts
@@ -5,9 +5,7 @@ import { type PinnableAiModel } from '@/settings/ai/types/PinnableAiModel';
import { getDataResidencyDisplay } from '@/settings/ai/utils/getDataResidencyDisplay';
import { getModelIcon } from '@/settings/ai/utils/getModelIcon';
-// Effort variants are picked through their base model and a separate effort
-// select, so only base models are listed. A deprecated model stays listed
-// while it is the current pin, so an existing choice is visible until changed.
+// Effort variants are picked via their base model; a deprecated current pin stays listed.
export const getAiModelPinOptions = ({
aiModels,
keepModelId,
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsx
index 893bc4f29b4..598b57a809e 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsx
@@ -79,8 +79,7 @@ export const ResourceCreditPriceSelector = ({
const currentResourceCreditPrice = currentResourceCreditBillingPrice;
- // The catalog price is gone once the workspace's package is archived, so
- // identity and the amount it pays both come from the subscription first.
+ // An archived package's catalog price is gone, so read from the subscription first.
const currentResourceCreditStripePriceId =
currentResourceCreditSubscriptionItem?.stripePriceId ??
currentResourceCreditPrice?.stripePriceId;
@@ -181,9 +180,7 @@ export const ResourceCreditPriceSelector = ({
(price) => price.stripePriceId !== currentResourceCreditStripePriceId,
);
- // Compared against the subscription's own package: the catalog price is gone
- // once it is archived, which would otherwise confirm every change as a
- // downgrade.
+ // Against the subscription's package: an archived catalog price would read every change as a downgrade.
const isUpgrade = () => {
if (!isChanged || !isDefined(selectedPrice)) {
return false;
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionCost.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionCost.ts
index c3d072c01d2..fcddda3eaed 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionCost.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionCost.ts
@@ -4,8 +4,6 @@ import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomState
import { isDefined } from 'twenty-shared/utils';
import { findBaseProductSubscriptionItem } from '@/settings/billing/utils/findBaseProductSubscriptionItem';
-// Centralizes the monthly/yearly bill breakdown so the subscription card and
-// the add-credits selector compute the same numbers from a single source.
export const useBillingSubscriptionCost = () => {
const currentWorkspace = useAtomStateValue(currentWorkspaceState);
const subscription = currentWorkspace?.currentBillingSubscription;
@@ -18,11 +16,8 @@ export const useBillingSubscriptionCost = () => {
const seats = baseProductSubscriptionItem?.quantity;
- // Amounts come from the subscription's own prices rather than the catalog:
- // superseded prices keep billing the workspaces already on them, so a
- // workspace would otherwise be shown a total it is not charged. Per-seat is
- // expressed at the subscription interval (full yearly amount for yearly
- // subscriptions), so subtotals match the actual charge.
+ // Subscription prices, not the catalog: superseded prices keep billing the workspaces on them.
+ // Per-seat is per subscription interval (a full year for yearly), so subtotals match the charge.
const perSeatAmountCents = baseProductSubscriptionItem?.unitAmount;
const seatsSubtotalCents =
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useCurrentResourceCredit.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useCurrentResourceCredit.ts
index 5ea2d748b95..b039b4d01a2 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useCurrentResourceCredit.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useCurrentResourceCredit.ts
@@ -44,8 +44,7 @@ export const useCurrentResourceCredit = () => {
return {
currentResourceCreditSubscriptionItem,
currentResourceCreditBillingPrice,
- // Read off the subscription rather than the catalog: an archived package is
- // no longer in listPlans, and the workspace is still being billed for it.
+ // Subscription item first: an archived package is gone from listPlans but still billed.
currentResourceCreditUnitAmount:
currentResourceCreditSubscriptionItem?.unitAmount ??
currentResourceCreditBillingPrice?.unitAmount,
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded.ts
index 317f0595d7c..a991c72d49b 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded.ts
@@ -5,8 +5,7 @@ import { isDefined } from 'twenty-shared/utils';
export const useMarkBillingPaymentMethodAsAdded = () => {
const setCurrentWorkspace = useSetAtomState(currentWorkspaceState);
- // Stripe confirms the setup intent before the payment method webhook lands,
- // so the workspace billing state has to be updated client-side
+ // Stripe confirms the setup intent before the payment method webhook lands, so update the workspace client-side
const markBillingPaymentMethodAsAdded = () => {
setCurrentWorkspace((previousWorkspace) =>
isDefined(previousWorkspace) &&
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/usePaymentMethodFlow.ts b/packages/twenty-front/src/modules/settings/billing/hooks/usePaymentMethodFlow.ts
index 159639b1887..a9df58e67be 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/usePaymentMethodFlow.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/usePaymentMethodFlow.ts
@@ -20,8 +20,7 @@ export const usePaymentMethodFlow = (modalInstanceId: string) => {
const { isBillingPortalSessionDisabled, openBillingPortal } =
useBillingPortalSession(getSettingsPath(SettingsPath.Billing));
- // Adding the first payment method is the only flow the in-product form can
- // handle, everything else needs the billing portal
+ // The in-product form only handles adding the first payment method; the rest needs the billing portal
const shouldAddPaymentMethodInProduct =
hasPermissionToManageBilling && billingHasPaymentMethod === false;
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/findSellableBaseProductOrThrow.ts b/packages/twenty-front/src/modules/settings/billing/utils/findSellableBaseProductOrThrow.ts
index bdd6bd102f1..06dd548ceb1 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/findSellableBaseProductOrThrow.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/findSellableBaseProductOrThrow.ts
@@ -6,8 +6,7 @@ type SellableBaseProductCandidate = {
metadata: { productKey: BillingProductKey; isLegacy?: string | null };
};
-// Mirrors the server: two live sellable products would make the price we show
-// depend on catalog order, so surface the misconfiguration instead of picking.
+// Mirrors the server: with two live sellable products the shown price would depend on catalog order.
export const findSellableBaseProductOrThrow = <
TProduct extends SellableBaseProductCandidate,
>(
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/findSellablePriceForIntervalOrThrow.ts b/packages/twenty-front/src/modules/settings/billing/utils/findSellablePriceForIntervalOrThrow.ts
index e180cd640df..ab93fe27957 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/findSellablePriceForIntervalOrThrow.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/findSellablePriceForIntervalOrThrow.ts
@@ -8,8 +8,7 @@ type SellablePriceCandidate = {
isSellable?: boolean | null;
};
-// Mirrors the server: two live sellable prices at one interval would make the
-// displayed and charged amount depend on catalog order.
+// Mirrors the server: two live sellable prices at one interval would make the amount depend on catalog order.
export const findSellablePriceForIntervalOrThrow = <
TPrice extends SellablePriceCandidate,
>(
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/getSubscriptionPlanKey.ts b/packages/twenty-front/src/modules/settings/billing/utils/getSubscriptionPlanKey.ts
index 2271c5b06bc..1c4c64b9507 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/getSubscriptionPlanKey.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/getSubscriptionPlanKey.ts
@@ -15,9 +15,7 @@ type SubscriptionWithPlan = {
| null;
};
-// The product the subscription sits on, not subscription.metadata.plan: that
-// copy is written at checkout and by immediate plan switches, and is never
-// updated when a scheduled switch takes effect.
+// Not subscription.metadata.plan: scheduled plan switches never update it.
export const getSubscriptionPlanKey = (
billingSubscription: SubscriptionWithPlan | null | undefined,
): BillingPlanKey | undefined =>
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/isSellableBillingPrice.ts b/packages/twenty-front/src/modules/settings/billing/utils/isSellableBillingPrice.ts
index 00721ae00c5..fc836b9a313 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/isSellableBillingPrice.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/isSellableBillingPrice.ts
@@ -2,8 +2,7 @@ type BillingPriceSellability = {
isSellable?: boolean | null;
};
-// Strict rather than fail-open: the server always sets this, so an absent value
-// means a stale payload, and letting a superseded price through would defeat the
-// exactly-one checks it feeds.
+// Strict: the server always sets this, so absence means a stale payload, and letting a superseded
+// price through would defeat the exactly-one checks this feeds.
export const isSellableBillingPrice = (billingPrice: BillingPriceSellability) =>
billingPrice.isSellable === true;
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/waitForSubscriptionRecovery.ts b/packages/twenty-front/src/modules/settings/billing/utils/waitForSubscriptionRecovery.ts
index ac5c6bd6200..6e1c8b23341 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/waitForSubscriptionRecovery.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/waitForSubscriptionRecovery.ts
@@ -38,8 +38,7 @@ export const waitForSubscriptionRecovery = async <TWorkspaceBilling>({
return { outcome: 'recovered', workspaceBilling };
}
- // Only a definite status that cannot recover ends the wait early, no
- // status at all is not a verdict on the payment
+ // A missing status is no verdict on the payment, so only a definite unrecoverable one ends the wait
if (
isDefined(subscriptionStatus) &&
!isSubscriptionPaymentOverdue(subscriptionStatus)
diff --git a/packages/twenty-front/src/modules/settings/components/SettingsCustomizeVideoModal.tsx b/packages/twenty-front/src/modules/settings/components/SettingsCustomizeVideoModal.tsx
index 087078526e4..e0d66ddbb3f 100644
--- a/packages/twenty-front/src/modules/settings/components/SettingsCustomizeVideoModal.tsx
+++ b/packages/twenty-front/src/modules/settings/components/SettingsCustomizeVideoModal.tsx
@@ -19,8 +19,7 @@ type SettingsCustomizeVideoModalProps = {
tabs: SettingsCustomizeVideoModalTab[];
};
-// the tab list draws its own separator, so the header only needs one when the
-// single tab is replaced by a plain title
+// The tab list draws its own separator, so the header needs one only when it shows a plain title
const StyledHeader = styled.div<{ $hasBottomBorder: boolean }>`
align-items: center;
border-bottom: ${({ $hasBottomBorder }) =>
diff --git a/packages/twenty-front/src/modules/settings/components/SettingsListItemCardContent.tsx b/packages/twenty-front/src/modules/settings/components/SettingsListItemCardContent.tsx
index 56b6bc397fa..7c43546c34d 100644
--- a/packages/twenty-front/src/modules/settings/components/SettingsListItemCardContent.tsx
+++ b/packages/twenty-front/src/modules/settings/components/SettingsListItemCardContent.tsx
@@ -47,9 +47,7 @@ const StyledLabel = styled.span`
white-space: nowrap;
`;
-// Rows are a fixed height, so the description has to give way rather than wrap
-// out of the row. A zero basis means it only ever takes the space the label
-// leaves, so the label stays readable and the description truncates first.
+// Rows are fixed-height, so the description truncates first rather than wrapping or squeezing the label
const StyledDescription = styled.span`
color: ${themeCssVariables.font.color.light};
flex: 1 1 0;
diff --git a/packages/twenty-front/src/modules/settings/components/SettingsProtectedRouteWrapper.tsx b/packages/twenty-front/src/modules/settings/components/SettingsProtectedRouteWrapper.tsx
index 4f4312eceb4..7968a917413 100644
--- a/packages/twenty-front/src/modules/settings/components/SettingsProtectedRouteWrapper.tsx
+++ b/packages/twenty-front/src/modules/settings/components/SettingsProtectedRouteWrapper.tsx
@@ -35,9 +35,7 @@ export const SettingsProtectedRouteWrapper = ({
return null;
}
- // TODO: this should be part of PageChangeEffect as otherwise we will have multiple sources of redirection that can:
- // - conflict (race conditions)
- // - degrade performance as we will redirect multiple times
+ // TODO: move into PageChangeEffect to avoid conflicting and repeated redirects
if ((requiredFeatureFlag && !requiredFeatureFlagEnabled) || !hasPermission) {
if (workspaceSurface.type === 'side-panel') {
return (
diff --git a/packages/twenty-front/src/modules/settings/components/layout/useSettingsActiveTabId.ts b/packages/twenty-front/src/modules/settings/components/layout/useSettingsActiveTabId.ts
index 9649ec71ef4..579b79013e0 100644
--- a/packages/twenty-front/src/modules/settings/components/layout/useSettingsActiveTabId.ts
+++ b/packages/twenty-front/src/modules/settings/components/layout/useSettingsActiveTabId.ts
@@ -3,9 +3,7 @@ import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/use
import { useLocation } from 'react-router-dom';
import { isDefined } from 'twenty-shared/utils';
-// Resolves the active tab synchronously so the content never renders a null/blank
-// frame before the effects settle: the URL hash if it points to a tab (so deep-links
-// win), else the stored tab if still valid, else the first tab.
+// Resolved synchronously so the content never renders a blank frame before effects settle
export const useSettingsActiveTabId = (
componentInstanceId: string,
tabIds: string[],
diff --git a/packages/twenty-front/src/modules/settings/data-model/fields/forms/morph-relation/components/SettingsDataModelFieldRelationJunctionForm.tsx b/packages/twenty-front/src/modules/settings/data-model/fields/forms/morph-relation/components/SettingsDataModelFieldRelationJunctionForm.tsx
index 013ff0c536c..dcd7d54d2ea 100644
--- a/packages/twenty-front/src/modules/settings/data-model/fields/forms/morph-relation/components/SettingsDataModelFieldRelationJunctionForm.tsx
+++ b/packages/twenty-front/src/modules/settings/data-model/fields/forms/morph-relation/components/SettingsDataModelFieldRelationJunctionForm.tsx
@@ -68,7 +68,6 @@ export const SettingsDataModelFieldRelationJunctionForm = ({
targetObjectMetadata.id === junctionObjectMetadataItem.id,
)?.targetFieldMetadata.id;
- // Self-referential relations cannot be junction objects
if (sourceObjectMetadataId === junctionObjectMetadataItem.id) {
return null;
}
diff --git a/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectLayout.tsx b/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectLayout.tsx
index e2314bc1582..43af570484a 100644
--- a/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectLayout.tsx
+++ b/packages/twenty-front/src/modules/settings/data-model/object-details/components/tabs/ObjectLayout.tsx
@@ -68,8 +68,7 @@ export const ObjectLayout = ({ objectMetadataItem }: ObjectLayoutProps) => {
return;
}
- // Customizing a layout takes over the whole page, so it is the main outlet
- // that has to move even when this settings page is hosted in the panel.
+ // Customizing a layout takes over the whole page, so it targets the main outlet even from the panel
navigateApp(
AppPath.RecordShowPage,
{
diff --git a/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useMostlyEmptyFieldMetadataIds.ts b/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useMostlyEmptyFieldMetadataIds.ts
index 1149c5668e6..16873403b90 100644
--- a/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useMostlyEmptyFieldMetadataIds.ts
+++ b/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useMostlyEmptyFieldMetadataIds.ts
@@ -7,8 +7,7 @@ type MostlyEmptyFieldMetadataIdsResult = {
mostlyEmptyFieldMetadataIds: string[];
};
-// Approximate, computed server-side from Postgres planner statistics; on any
-// error the hint simply doesn't show
+// Approximate (Postgres planner statistics); on error the hint just does not show
export const useMostlyEmptyFieldMetadataIds = ({
objectMetadataItemId,
skip,
diff --git a/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useSaveUpdateDataModelObjectAboutForm.ts b/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useSaveUpdateDataModelObjectAboutForm.ts
index 4c02b439ab9..82d7c516f62 100644
--- a/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useSaveUpdateDataModelObjectAboutForm.ts
+++ b/packages/twenty-front/src/modules/settings/data-model/object-details/hooks/useSaveUpdateDataModelObjectAboutForm.ts
@@ -30,9 +30,6 @@ const OBJECT_TRANSLATABLE_PROPERTIES =
type ObjectTranslatableProperty =
(typeof OBJECT_TRANSLATABLE_PROPERTIES)[number];
-// The translate-vs-rename save state machine behind the About form: a label
-// edit made through a translation prompts for intent; every other save is a
-// plain canonical update.
export const useSaveUpdateDataModelObjectAboutForm = ({
objectMetadataItem,
formConfig,
@@ -71,9 +68,7 @@ export const useSaveUpdateDataModelObjectAboutForm = ({
isDefined(formConfig.formState.dirtyFields[property]),
);
- // Only dirty fields are ever sent: untouched values hold the viewer-locale
- // resolved labels, and sending those back would silently turn a translation
- // into a rename. Standard objects additionally cannot change their names.
+ // Only dirty fields are sent: untouched values hold viewer-locale labels, and sending them back would turn a translation into a rename
const pickDirtyValues = (
formValues: SettingsDataModelObjectAboutFormValues,
): Partial<SettingsDataModelObjectAboutFormValues> => {
@@ -177,8 +172,7 @@ export const useSaveUpdateDataModelObjectAboutForm = ({
const dirtyTranslatableProperties = pickDirtyTranslatableProperties();
- // Editing a label the viewer sees through a translation is ambiguous:
- // fix the translation, or rename the concept for every language? Ask.
+ // A label seen through a translation is ambiguous: fix the translation, or rename for every language?
if (
dirtyTranslatableProperties.length > 0 &&
currentLocale !== SOURCE_LOCALE
@@ -225,15 +219,11 @@ export const useSaveUpdateDataModelObjectAboutForm = ({
property,
value: pendingFormValues[property] ?? null,
}));
- // With label↔name sync on, the name fields were auto-derived from the
- // label being translated (they are not editable directly in that state):
- // a translation must not rename the API.
+ // With label/name sync on, the names derive from the translated label, and a translation must not rename the API
const isPendingLabelSyncedWithName =
pendingFormValues.isLabelSyncedWithName ?? isLabelSyncedWithName;
const syncDerivedNameProperties: readonly string[] =
isPendingLabelSyncedWithName ? ['nameSingular', 'namePlural'] : [];
- // Unrelated dirty edits (icon, ...) ride along as canonical updates —
- // only the label edits become locale-scoped.
const dirtyNonTranslatableValues = Object.fromEntries(
Object.entries(pickDirtyValues(pendingFormValues)).filter(
([key]) =>
@@ -252,8 +242,7 @@ export const useSaveUpdateDataModelObjectAboutForm = ({
setPendingFormValues(null);
if (updateResult.status === 'successful') {
- // The form must reflect what was saved: the unchanged API names, not
- // the ones the sync derived from the translated label.
+ // Reflect the unchanged API names, not the ones sync derived from the translated label
formConfig.reset(
isPendingLabelSyncedWithName
? { ...pendingFormValues, nameSingular, namePlural }
diff --git a/packages/twenty-front/src/modules/settings/domains/components/SettingPublicDomain.tsx b/packages/twenty-front/src/modules/settings/domains/components/SettingPublicDomain.tsx
index ad0abc23af8..57afeadde31 100644
--- a/packages/twenty-front/src/modules/settings/domains/components/SettingPublicDomain.tsx
+++ b/packages/twenty-front/src/modules/settings/domains/components/SettingPublicDomain.tsx
@@ -73,9 +73,7 @@ export const SettingPublicDomain = () => {
const isEditingPublicDomain = isDefined(publicDomainId);
- // Scoped to the application in the URL: the query is workspace-wide, so a
- // domain id from another application would otherwise be editable and
- // deletable from this page.
+ // The query is workspace-wide, so scope to the URL application or other apps' domains become editable here
const selectedPublicDomain = isEditingPublicDomain
? publicDomainsData?.findManyPublicDomains?.find(
(publicDomain) =>
@@ -112,8 +110,7 @@ export const SettingPublicDomain = () => {
const { isLoading, publicDomainRecords, checkPublicDomainRecords } =
useCheckPublicDomainValidRecords();
- // Also used once the create and delete mutations resolve, so it cannot be
- // replaced by a Link.
+ // Also navigates after the create and delete mutations resolve, so it cannot be a Link
// oxlint-disable-next-line twenty/no-navigate-prefer-link
const navigateToApplication = () =>
navigate(SettingsPath.ApplicationDetail, { applicationId });
diff --git a/packages/twenty-front/src/modules/settings/domains/components/SettingsPublicDomainsListCard.tsx b/packages/twenty-front/src/modules/settings/domains/components/SettingsPublicDomainsListCard.tsx
index 1d3492a5c02..7d47cd480f8 100644
--- a/packages/twenty-front/src/modules/settings/domains/components/SettingsPublicDomainsListCard.tsx
+++ b/packages/twenty-front/src/modules/settings/domains/components/SettingsPublicDomainsListCard.tsx
@@ -35,8 +35,7 @@ export const SettingsPublicDomainsListCard = ({
return null;
}
- // The empty-state card and the footer button are plain buttons, they cannot
- // carry a Link.
+ // The empty-state card and the footer button are plain buttons that cannot carry a Link
// oxlint-disable-next-line twenty/no-navigate-prefer-link
const navigateToCreate = () =>
navigate(SettingsPath.ApplicationPublicDomainNew, { applicationId });
diff --git a/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsx b/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsx
index 99e38df7587..e2d70fe9dac 100644
--- a/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsx
+++ b/packages/twenty-front/src/modules/settings/profile/devices/components/SettingsProfileDevicesSection.tsx
@@ -29,8 +29,6 @@ const StyledContainer = styled.div`
gap: ${themeCssVariables.spacing[2]};
`;
-// A flex row so the button keeps its natural width while the card above it
-// stretches to the section.
const StyledButtonContainer = styled.div`
display: flex;
`;
diff --git a/packages/twenty-front/src/modules/settings/profile/devices/utils/parseUserAgentDescription.ts b/packages/twenty-front/src/modules/settings/profile/devices/utils/parseUserAgentDescription.ts
index 8ef7239b765..04f67a59884 100644
--- a/packages/twenty-front/src/modules/settings/profile/devices/utils/parseUserAgentDescription.ts
+++ b/packages/twenty-front/src/modules/settings/profile/devices/utils/parseUserAgentDescription.ts
@@ -5,8 +5,7 @@ type UserAgentMatcher = {
pattern: RegExp;
};
-// Order matters: several browsers embed competitor tokens in their user
-// agent (Edge and Opera contain "Chrome", Chrome contains "Safari").
+// Order matters: Edge and Opera user agents contain "Chrome", and Chrome's contains "Safari"
const BROWSER_MATCHERS: UserAgentMatcher[] = [
{ label: 'Edge', pattern: /Edg(e|A|iOS)?\// },
{ label: 'Opera', pattern: /(OPR|Opera)\// },
diff --git a/packages/twenty-front/src/modules/settings/security/utils/parseSamlMetadataFromXmlFile.ts b/packages/twenty-front/src/modules/settings/security/utils/parseSamlMetadataFromXmlFile.ts
index de92cf92492..f5c43716151 100644
--- a/packages/twenty-front/src/modules/settings/security/utils/parseSamlMetadataFromXmlFile.ts
+++ b/packages/twenty-front/src/modules/settings/security/utils/parseSamlMetadataFromXmlFile.ts
@@ -102,9 +102,7 @@ export const parseSamlMetadataFromXmlFile = (
location: service.getAttribute('Location'),
}));
- // Prefer HTTP-Redirect (the default authnRequestBinding on the SP side),
- // fall back to HTTP-POST since both are valid SAML 2.0 bindings and many
- // IdPs (e.g. JumpCloud) only advertise HTTP-POST.
+ // Prefer HTTP-Redirect (the SP default), falling back to HTTP-POST, the only binding some IdPs (e.g. JumpCloud) advertise
const ssoUrl =
singleSignOnServices.find((s) => s.binding === HTTP_REDIRECT_BINDING)
?.location ??
diff --git a/packages/twenty-front/src/modules/settings/translations/hooks/useMetadataTranslations.ts b/packages/twenty-front/src/modules/settings/translations/hooks/useMetadataTranslations.ts
index ae52a3b0870..43287980815 100644
--- a/packages/twenty-front/src/modules/settings/translations/hooks/useMetadataTranslations.ts
+++ b/packages/twenty-front/src/modules/settings/translations/hooks/useMetadataTranslations.ts
@@ -23,8 +23,7 @@ export const useMetadataTranslations = (
const { updateOneObjectMetadataItem } = useUpdateOneObjectMetadataItem();
const { updateOneFieldMetadataItem } = useUpdateOneFieldMetadataItem();
- // A null value removes the stored translation, reverting the locale to
- // shipped-or-canonical.
+ // null removes the stored translation, reverting the locale to the shipped or canonical label
const saveTranslationRows = async (
rowValues: MetadataTranslationRowValue[],
) => {
diff --git a/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx b/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
index 1aec933583c..c01e64895fd 100644
--- a/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
+++ b/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
@@ -67,8 +67,7 @@ export const UsageBreakdownPieSection = ({
const total = breakdownData.reduce((sum, item) => sum + item.creditsUsed, 0);
- // Operation types are a fixed platform vocabulary translated here; the other
- // breakdowns name workspace data, which only the server can resolve.
+ // Operation types are a fixed vocabulary translated here; other breakdowns name workspace data only the server resolves
const formatLabel = ({
key,
label,
diff --git a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
index cb061fce90c..f79e1ef8664 100644
--- a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
+++ b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
@@ -3,8 +3,6 @@ import { msg } from '@lingui/core/macro';
import { UsageOperationType } from '~/generated-metadata/graphql';
-// Exhaustive over the enum, so a new operation type is a compile error here
-// rather than a raw key on screen.
export const USAGE_OPERATION_TYPE_LABELS: Record<
UsageOperationType,
MessageDescriptor
diff --git a/packages/twenty-front/src/modules/settings/usage/utils/getUsageOperationTypeLabel.ts b/packages/twenty-front/src/modules/settings/usage/utils/getUsageOperationTypeLabel.ts
index cfe7a2cf1fb..943e1ae9b64 100644
--- a/packages/twenty-front/src/modules/settings/usage/utils/getUsageOperationTypeLabel.ts
+++ b/packages/twenty-front/src/modules/settings/usage/utils/getUsageOperationTypeLabel.ts
@@ -2,9 +2,7 @@ import { type MessageDescriptor } from '@lingui/core';
import { USAGE_OPERATION_TYPE_LABELS } from '@/settings/usage/constants/UsageOperationTypeLabels';
-// A Map rather than a direct record index: a source key can name an
-// application, and without `noUncheckedIndexedAccess` indexing the record
-// would type that miss as a MessageDescriptor instead of undefined.
+// A Map, not a record index: keys can name an application, and without noUncheckedIndexedAccess a miss would not type as undefined
const LABEL_BY_OPERATION_TYPE: ReadonlyMap<string, MessageDescriptor> = new Map(
Object.entries(USAGE_OPERATION_TYPE_LABELS),
);
diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandButton.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandButton.tsx
index 45484f8f202..3c0b6ad8516 100644
--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandButton.tsx
+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandButton.tsx
@@ -10,8 +10,7 @@ import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/conte
import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';
import { useComponentInstanceStateContext } from '@/ui/utilities/state/component-state/hooks/useComponentInstanceStateContext';
-// Registered only for targets that claim the shortcut, so pages whose content
-// owns cmd+enter keep it to themselves.
+// Registered only for targets that claim it, so pages whose content owns cmd+enter keep it
const SidePanelExpandShortcutEffect = ({ expand }: { expand: () => void }) => {
useHotkeysOnFocusedElement({
keys: ['ctrl+Enter,meta+Enter'],
@@ -61,9 +60,7 @@ export const SidePanelExpandButton = () => {
SidePanelPageComponentInstanceContext,
)?.instanceId;
- // Expand targets read state scoped to the side panel page. The context
- // defaults to a blank instance id, which those reads reject, so match the
- // condition they enforce rather than merely checking the context exists.
+ // The context defaults to a blank instance id that expand targets reject, so check for that rather than presence
if (!isNonEmptyString(sidePanelPageInstanceId)) {
return null;
}
diff --git a/packages/twenty-front/src/modules/side-panel/hooks/useOpenRecordInSidePanel.ts b/packages/twenty-front/src/modules/side-panel/hooks/useOpenRecordInSidePanel.ts
index 784acd0ad57..71f37a3cce5 100644
--- a/packages/twenty-front/src/modules/side-panel/hooks/useOpenRecordInSidePanel.ts
+++ b/packages/twenty-front/src/modules/side-panel/hooks/useOpenRecordInSidePanel.ts
@@ -43,8 +43,7 @@ export const useOpenRecordInSidePanel = () => {
resetNavigationStack?: boolean;
}) => {
if (isMobile) {
- // Mobile escapes the panel router and cannot hand its hash to the main
- // navigator, so seed the main tab as a compatibility transition.
+ // Mobile escapes the panel router and cannot hand its hash to the main navigator, so seed the main tab
if (isDefined(tab)) {
setRecordPageActiveTabId({
recordId,
@@ -74,8 +73,7 @@ export const useOpenRecordInSidePanel = () => {
closeSidePanelMenu();
- // Deliberately the main outlet: on mobile the panel is the viewport, so
- // hosting the record on the right would be the thing being escaped.
+ // Main outlet on purpose: on mobile the panel is the viewport being escaped
navigate(
AppPath.RecordShowPage,
{
@@ -161,8 +159,7 @@ export const useOpenRecordInSidePanel = () => {
}
}
- // The panel page owns its own context store, so a caller with state to
- // hand the record needs to know which instance will read it.
+ // Callers seeding state for the record need the panel page's own context store instance
return pageComponentInstanceId;
},
[
diff --git a/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelCloseAnimationCompleteCleanup.ts b/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelCloseAnimationCompleteCleanup.ts
index 29960030847..de7424558f1 100644
--- a/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelCloseAnimationCompleteCleanup.ts
+++ b/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelCloseAnimationCompleteCleanup.ts
@@ -40,8 +40,7 @@ export const useSidePanelCloseAnimationCompleteCleanup = () => {
(options?: { emitSidePanelCloseEvent?: boolean }) => {
closeDropdown(SIDE_PANEL_CONTEXT_CHIP_GROUPS_DROPDOWN_ID);
- // Snapshot values before any mutations (Jotai store.get is live and
- // reflects the latest state, so we capture before mutating).
+ // store.get is live, so snapshot before mutating
const currentNavigationStack = store.get(
sidePanelNavigationStackState.atom,
);
diff --git a/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelExpandTarget.ts b/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelExpandTarget.ts
index e3d3e473037..31a424738d8 100644
--- a/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelExpandTarget.ts
+++ b/packages/twenty-front/src/modules/side-panel/hooks/useSidePanelExpandTarget.ts
@@ -20,9 +20,7 @@ export const useSidePanelExpandTarget = (): SidePanelExpandTarget | null => {
const richTextExpandTarget = useExpandRichTextSidePanelPage();
const routedExpandTarget = useExpandRoutedSidePanelPage();
- // On mobile the panel already fills the viewport, so there is nothing to
- // expand into. A sub page has taken over the panel content, so expanding the
- // page underneath it would discard what the user is currently doing.
+ // Nothing to expand into on mobile, and expanding under a sub page would discard what the user is doing
if (isMobile || hasSidePanelSubPages) {
return null;
}
diff --git a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/SidePanelPageLayoutTabSettingsContent.tsx b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/SidePanelPageLayoutTabSettingsContent.tsx
index ed1384c8b78..8e1111f48dd 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/SidePanelPageLayoutTabSettingsContent.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/SidePanelPageLayoutTabSettingsContent.tsx
@@ -79,8 +79,7 @@ export const SidePanelPageLayoutTabSettingsContent = ({
return null;
}
- // Deleting a tab only deactivates it in the draft, and the placement actions
- // have to line up with the tabs the layout actually renders.
+ // Deleted tabs are only deactivated in the draft, so placement must follow the active ones
const tabsSorted = sortTabsByPosition(
pageLayoutDraft.tabs.filter((draftTab) => draftTab.isActive),
);
diff --git a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetFieldDropdownContent.tsx b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetFieldDropdownContent.tsx
index a7d75172d4a..092cb7429ab 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetFieldDropdownContent.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetFieldDropdownContent.tsx
@@ -158,10 +158,7 @@ export const FieldWidgetFieldDropdownContent = () => {
return candidatesByFieldId;
}, [allFieldWidgetFieldMetadataItems, objectMetadataItems]);
- // Keyboard focus carries over between the browse list and the drill-in
- // submenu since both share the dropdown's selectable list instance. Align
- // it on the checked option when entering the submenu, and back on the
- // parent row when leaving, so Enter never activates a stale row.
+ // The browse list and submenu share one selectable list, so realign focus on enter and leave or Enter hits a stale row
const handleDrillIn = (fieldMetadataItem: FieldMetadataItem) => {
setDrillInFieldMetadataItem(fieldMetadataItem);
@@ -244,8 +241,7 @@ export const FieldWidgetFieldDropdownContent = () => {
parentFieldMetadataItem: FieldMetadataItem,
nestedFieldMetadataItem: FieldMetadataItem,
) => {
- // A nested relation widget always renders as an embedded view, so the
- // effective display mode is TABLE regardless of the current one.
+ // A nested relation widget always renders as an embedded view, so TABLE is the effective display mode
const relationTableViewIdChange =
resolveFieldWidgetRelationTableViewIdChange({
selectedField: parentFieldMetadataItem,
diff --git a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetLayoutDropdownContent.tsx b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetLayoutDropdownContent.tsx
index 72b8cf71b5c..3e7a5519fb7 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetLayoutDropdownContent.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/dropdown-content/FieldWidgetLayoutDropdownContent.tsx
@@ -51,9 +51,7 @@ const DISPLAY_MODE_ICONS: Record<FieldDisplayMode, IconComponent> = {
[FieldDisplayMode.TABLE]: IconTable,
};
-// One flat picker: inline display modes followed by the embedded-view layouts.
-// Picking a layout selects the TABLE display mode under the hood — users choose
-// "Kanban" directly instead of "Table" first and a layout second.
+// Picking an embedded-view layout implicitly selects the TABLE display mode
export const FieldWidgetLayoutDropdownContent = () => {
const { t } = useLingui();
@@ -88,8 +86,7 @@ export const FieldWidgetLayoutDropdownContent = () => {
nestedRelationFieldMetadataId: currentNestedRelationFieldMetadataId,
});
- // Gate on the configured id, not on resolution success: a widget whose
- // second hop was deleted must not fall back to first-hop behavior.
+ // Gate on the configured id, not resolution: a widget whose second hop was deleted must not fall back to first-hop behavior
const isNestedRelationWidget = isDefined(
currentNestedRelationFieldMetadataId,
);
@@ -101,17 +98,13 @@ export const FieldWidgetLayoutDropdownContent = () => {
)
: [FieldDisplayMode.FIELD];
- // A nested relation widget only makes sense as an embedded view: inline
- // display modes would render the first hop's relation field, contradicting
- // the widget's two-hop title.
+ // Inline display modes would render the first hop's field, contradicting the nested widget's two-hop title
const inlineDisplayModes = isNestedRelationWidget
? []
: availableDisplayModes.filter(
(displayMode) => displayMode !== FieldDisplayMode.TABLE,
);
- // A configured but unresolvable second hop yields no traversal at all, so a
- // stale nested widget cannot fall back to scoping by its first hop.
const relationTraversal =
isNestedRelationWidget && !isDefined(resolvedNestedRelation)
? undefined
@@ -127,9 +120,7 @@ export const FieldWidgetLayoutDropdownContent = () => {
const relationTargetFieldMetadataId =
relationTraversal?.relationTargetFieldMetadataId ?? null;
- // Every embedded layout renders a view scoped by the relation's inverse
- // field, so a relation the traversal cannot resolve offers none of them
- // rather than entries that would leave the widget with nothing to render.
+ // Every embedded layout scopes its view by the relation's inverse field, so none are offered when it cannot resolve
const hasEmbeddedViewLayouts =
availableDisplayModes.includes(FieldDisplayMode.TABLE) &&
isDefined(targetObjectMetadataId) &&
@@ -201,9 +192,7 @@ export const FieldWidgetLayoutDropdownContent = () => {
return;
}
- // A view listing another object than the traversal's target predates
- // junction traversal and would embed the wrong object, and a view id that
- // resolves to nothing was deleted, so both are replaced.
+ // A view on another object predates junction traversal and an unresolved id was deleted, so both are replaced
const isCurrentViewOnTargetObject =
isDefined(currentViewId) &&
isDefined(embeddedWidgetView) &&
@@ -220,9 +209,7 @@ export const FieldWidgetLayoutDropdownContent = () => {
})
: undefined);
- // Creating the draft view still fails if the target object is not loaded,
- // and switching to the table display mode without one would leave the
- // widget with nothing to render, so it keeps the display mode it has.
+ // Draft view creation fails without the target object, so keep the current display mode
if (!isDefined(viewId)) {
closeDropdown();
return;
diff --git a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-page/SidePanelRecordPageFieldSettings.tsx b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-page/SidePanelRecordPageFieldSettings.tsx
index e31773bbf45..8fb01344770 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-page/SidePanelRecordPageFieldSettings.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-page/SidePanelRecordPageFieldSettings.tsx
@@ -98,12 +98,7 @@ export const SidePanelRecordPageFieldSettings = () => {
nestedRelationFieldMetadataId: currentNestedRelationFieldMetadataId,
});
- // A relation field widget in table display mode embeds a widget view scoped to
- // the current record's related records; its source object is the relation
- // target (or the nested relation target two hops away), not the record
- // page's own object. A configured but unresolvable nested relation keeps
- // the target undefined so the terminal view's settings stay hidden instead
- // of being edited against the first hop's object.
+ // The embedded view lists the relation target, not the page's object; an unresolvable nested hop stays undefined to hide its settings
const targetObjectMetadataId = isDefined(currentNestedRelationFieldMetadataId)
? resolvedNestedRelation?.nestedRelationTargetObjectMetadataItem.id
: currentFieldMetadataItem?.relation?.targetObjectMetadata.id;
diff --git a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/RecordTableWidgetLayoutMenuItems.tsx b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/RecordTableWidgetLayoutMenuItems.tsx
index 96ed4988896..b6a8f2a3285 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/RecordTableWidgetLayoutMenuItems.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/RecordTableWidgetLayoutMenuItems.tsx
@@ -8,8 +8,7 @@ import { ListItem } from 'twenty-ui/primitives/navigation';
type RecordTableWidgetLayoutMenuItemsProps = {
layoutOptions: RecordTableWidgetLayoutPickerOption[];
- // Undefined when the host widget is not currently showing an embedded view,
- // so no layout reads as selected.
+ // Undefined when no embedded view is shown, so no layout reads as selected
selectedViewType: RecordTableWidgetLayoutViewType | undefined;
focusedItemId: string | null;
onSelect: (viewType: RecordTableWidgetLayoutViewType) => void;
diff --git a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/WidgetViewLayoutSettingsRows.tsx b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/WidgetViewLayoutSettingsRows.tsx
index ee057522da6..acf83c2ee33 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/WidgetViewLayoutSettingsRows.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/WidgetViewLayoutSettingsRows.tsx
@@ -31,13 +31,6 @@ type WidgetViewLayoutSettingsRowsProps = {
isLayoutRowHidden?: boolean;
};
-// The embedded-view layout rows (layout type + group-by / calendar field /
-// calendar view / hide-empty-groups) shared by widgets backed by a record table
-// view: dashboard record table widgets and relation field widgets in table
-// display mode. The source object is passed in (fixed to the relation target
-// for field widgets), so this component makes no assumption about where the
-// widget lives. Hosts that surface the layout choice elsewhere (the field
-// widget's merged layout picker) hide the layout row via isLayoutRowHidden.
export const WidgetViewLayoutSettingsRows = ({
pageLayoutId,
widgetId,
diff --git a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/__tests__/WidgetViewLayoutSettingsRows.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/__tests__/WidgetViewLayoutSettingsRows.test.tsx
index f93eeae9cef..ed8c42a401e 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/__tests__/WidgetViewLayoutSettingsRows.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/page-layout/components/record-table-settings/__tests__/WidgetViewLayoutSettingsRows.test.tsx
@@ -96,8 +96,6 @@ describe('WidgetViewLayoutSettingsRows', () => {
expect(screen.getByTestId('row-Calendar view')).toHaveTextContent('Month');
});
- // The layout row used to fall through to Table for anything that was not
- // kanban or calendar, so a list widget described itself as a table.
it.each([
[ViewType.TABLE_WIDGET, 'Table', 'Table'],
[ViewType.KANBAN_WIDGET, 'Kanban', 'LayoutKanban'],
diff --git a/packages/twenty-front/src/modules/side-panel/pages/record-page/hooks/__tests__/useNavigateToRecordPageFromSidePanel.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/record-page/hooks/__tests__/useNavigateToRecordPageFromSidePanel.test.tsx
index df29adfffc9..c7fe2ed4db9 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/record-page/hooks/__tests__/useNavigateToRecordPageFromSidePanel.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/record-page/hooks/__tests__/useNavigateToRecordPageFromSidePanel.test.tsx
@@ -76,8 +76,7 @@ const renderNavigateToRecordPage = ({
}
if (parentView !== undefined) {
- // The panel page holds it, since that is the surface the peek read it
- // from; expanding is what moves it to the main one.
+ // The peek read it from the panel page; expanding is what moves it to the main one
initializedStore.set(
contextStoreRecordShowParentViewComponentState.atomFamily({
instanceId: PAGE_INSTANCE_ID,
diff --git a/packages/twenty-front/src/modules/side-panel/pages/search/components/SidePanelSearchRecordPreviewCard.tsx b/packages/twenty-front/src/modules/side-panel/pages/search/components/SidePanelSearchRecordPreviewCard.tsx
index 3864dfc045e..c4516f405d7 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/search/components/SidePanelSearchRecordPreviewCard.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/search/components/SidePanelSearchRecordPreviewCard.tsx
@@ -138,8 +138,6 @@ export const SidePanelSearchRecordPreviewCard = ({
{ recordId, allowRequestsToTwentyIcons },
);
- // Collapsed shows at most a handful of the view's visible columns; everything
- // past that, plus the view's hidden columns, sits behind the expander
const collapsedFields = visibleFields.slice(
0,
SIDE_PANEL_SEARCH_RECORD_PREVIEW_MAX_COLLAPSED_FIELDS,
diff --git a/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewFields.ts b/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewFields.ts
index e533e451996..b1ba0fcaa03 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewFields.ts
+++ b/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewFields.ts
@@ -5,9 +5,7 @@ import { useViewOrDefaultView } from '@/views/hooks/useViewOrDefaultView';
import { useMemo } from 'react';
import { isDefined } from 'twenty-shared/utils';
-// The preview mirrors the columns of the object's index view, so what you see
-// while searching matches the list view you came from. Columns hidden in that
-// view stay available behind the "More" expander.
+// Mirrors the index view's columns so the preview matches the list view you came from
export const useSidePanelSearchRecordPreviewFields = (
objectMetadataItem: EnrichedObjectMetadataItem,
): {
diff --git a/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewItem.ts b/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewItem.ts
index 4e6e2511d98..b0d7ac5af50 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewItem.ts
+++ b/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewItem.ts
@@ -3,8 +3,7 @@ import { type SearchResultItem } from '@/side-panel/pages/search/types/SearchRes
import { selectedItemIdComponentState } from '@/ui/layout/selectable-list/states/selectedItemIdComponentState';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
-// Follows the selection immediately so the card never unmounts between
-// records. Fetching is what gets debounced, one level down.
+// Not debounced so the card never unmounts between records; fetching is debounced one level down
export const useSidePanelSearchRecordPreviewItem = (
searchResultItems: SearchResultItem[],
): SearchResultItem | null => {
diff --git a/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewRecord.ts b/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewRecord.ts
index 32e36ea03da..9eaccd324f2 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewRecord.ts
+++ b/packages/twenty-front/src/modules/side-panel/pages/search/hooks/useSidePanelSearchRecordPreviewRecord.ts
@@ -8,9 +8,7 @@ import { useEffect } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { useDebounce } from 'use-debounce';
-// Field displays read from the record store, so the previewed record has to be
-// hydrated there before its values can render. The fetch lags behind the
-// selection to avoid firing a query for every row crossed with arrow keys.
+// Field displays read from the record store, so hydrate it; debounced to skip rows crossed with arrow keys
export const useSidePanelSearchRecordPreviewRecord = ({
objectNameSingular,
recordId,
@@ -25,8 +23,7 @@ export const useSidePanelSearchRecordPreviewRecord = ({
SEARCH_RECORD_PREVIEW_DEBOUNCE_MS,
);
- // objectNameSingular tracks the selection, so it only matches the debounced
- // record once the selection has settled
+ // objectNameSingular tracks the selection, so it matches the debounced record only once settled
const isDebouncedRecordIdSettled = debouncedRecordId === recordId;
const { record } = useFindOneRecord({
diff --git a/packages/twenty-front/src/modules/side-panel/routing/components/SidePanelPathUrlSyncEffect.tsx b/packages/twenty-front/src/modules/side-panel/routing/components/SidePanelPathUrlSyncEffect.tsx
index 60ab17c45f9..4792b090c6c 100644
--- a/packages/twenty-front/src/modules/side-panel/routing/components/SidePanelPathUrlSyncEffect.tsx
+++ b/packages/twenty-front/src/modules/side-panel/routing/components/SidePanelPathUrlSyncEffect.tsx
@@ -80,9 +80,7 @@ export const SidePanelPathUrlSyncEffect = () => {
if (pathInUrl !== currentRoutedPath) {
openRoutedPageInSidePanel({
path: pathInUrl,
- // The URL is an external projection of the secondary location.
- // Selecting another projected artifact starts a fresh stack entry
- // and state flow; only in-panel replace navigation inherits them.
+ // Each URL selection starts a fresh stack entry; only in-panel replace navigation inherits state
resetNavigationStack: true,
});
}
diff --git a/packages/twenty-front/src/modules/side-panel/routing/components/__tests__/SidePanelPathRestore.test.tsx b/packages/twenty-front/src/modules/side-panel/routing/components/__tests__/SidePanelPathRestore.test.tsx
index 775962cef1c..c1d454a34e9 100644
--- a/packages/twenty-front/src/modules/side-panel/routing/components/__tests__/SidePanelPathRestore.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/routing/components/__tests__/SidePanelPathRestore.test.tsx
@@ -42,9 +42,7 @@ const routeObjects: WorkspaceRouteObject[] = [
},
];
-// Restoring opens the panel, which is what the sync effect writes the param
-// from. Writing before that lands would clear the param being restored, so
-// this records every value the url took rather than only where it settled.
+// Writing before the panel opens would clear the param being restored, so record every value the url took
const useRecordedSearchValues = (recorded: string[]) => {
const { search } = useLocation();
diff --git a/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRecordSidePanelPage.ts b/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRecordSidePanelPage.ts
index 424419a0ef0..b576aa3f8e4 100644
--- a/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRecordSidePanelPage.ts
+++ b/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRecordSidePanelPage.ts
@@ -6,8 +6,7 @@ import { useCurrentSidePanelRoutedPath } from '@/side-panel/routing/hooks/useCur
import { getRecordShowParamsFromPath } from '@/side-panel/routing/utils/getRecordShowParamsFromPath';
import { type SidePanelExpandTarget } from '@/side-panel/types/SidePanelExpandTarget';
-// A record expands through its own hook rather than the generic routed one,
-// because it also carries the open tab across and clears a stale parent view.
+// Not the generic routed hook: a record also carries the open tab across and clears a stale parent view
export const useExpandRecordSidePanelPage =
(): SidePanelExpandTarget | null => {
const { t } = useLingui();
diff --git a/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRoutedSidePanelPage.ts b/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRoutedSidePanelPage.ts
index 73736e62854..d85dc98b011 100644
--- a/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRoutedSidePanelPage.ts
+++ b/packages/twenty-front/src/modules/side-panel/routing/hooks/useExpandRoutedSidePanelPage.ts
@@ -8,8 +8,7 @@ import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';
import { useCurrentSidePanelRoutedPath } from '@/side-panel/routing/hooks/useCurrentSidePanelRoutedPath';
import { type SidePanelExpandTarget } from '@/side-panel/types/SidePanelExpandTarget';
-// A route opts into generic expansion only when moving it between surface
-// stores cannot discard in-progress state.
+// Only for routes whose in-progress state survives moving between surface stores
export const useExpandRoutedSidePanelPage =
(): SidePanelExpandTarget | null => {
const { t } = useLingui();
diff --git a/packages/twenty-front/src/modules/side-panel/routing/hooks/useOpenRoutedPageInSidePanel.ts b/packages/twenty-front/src/modules/side-panel/routing/hooks/useOpenRoutedPageInSidePanel.ts
index 121ee3378be..10355feb3d9 100644
--- a/packages/twenty-front/src/modules/side-panel/routing/hooks/useOpenRoutedPageInSidePanel.ts
+++ b/packages/twenty-front/src/modules/side-panel/routing/hooks/useOpenRoutedPageInSidePanel.ts
@@ -102,8 +102,6 @@ export const useOpenRoutedPageInSidePanel = () => {
resetNavigationStack,
});
- // The caller keys its own per-visit state off this, the way the morph
- // navigation stack does for a record.
return pageComponentInstanceId;
},
[navigateSidePanel, routeObjects, store],
diff --git a/packages/twenty-front/src/modules/side-panel/routing/utils/getRecordShowParamsFromPath.ts b/packages/twenty-front/src/modules/side-panel/routing/utils/getRecordShowParamsFromPath.ts
index 94be032ac61..4df7f18d7ad 100644
--- a/packages/twenty-front/src/modules/side-panel/routing/utils/getRecordShowParamsFromPath.ts
+++ b/packages/twenty-front/src/modules/side-panel/routing/utils/getRecordShowParamsFromPath.ts
@@ -2,8 +2,6 @@ import { matchPath, parsePath } from 'react-router-dom';
import { AppPath } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-// The panel stack still needs to know which of its routed entries is a record,
-// because a record entry carries its own top bar, chip and expand behaviour.
export const getRecordShowParamsFromPath = (path: string) => {
const match = matchPath(
AppPath.RecordShowPage,
diff --git a/packages/twenty-front/src/modules/side-panel/types/SidePanelExpandTarget.ts b/packages/twenty-front/src/modules/side-panel/types/SidePanelExpandTarget.ts
index b6f04157597..28f8890c902 100644
--- a/packages/twenty-front/src/modules/side-panel/types/SidePanelExpandTarget.ts
+++ b/packages/twenty-front/src/modules/side-panel/types/SidePanelExpandTarget.ts
@@ -1,6 +1,4 @@
-// A side panel page declares how it expands into its full page equivalent.
-// `expand` is deliberately opaque so a page can navigate to a route, open a
-// full screen overlay, or anything else, without the top bar knowing.
+// `expand` is opaque so a page can navigate, open an overlay or anything else without the top bar knowing
export type SidePanelExpandTarget = {
label: string;
disabledReason?: string;
diff --git a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillIcon.ts b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillIcon.ts
index 1cc6a149c9a..e2f5f6853d8 100644
--- a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillIcon.ts
+++ b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillIcon.ts
@@ -3,8 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { FindManySkillsForSuggestionDocument } from '~/generated-metadata/graphql';
-// Skill references only carry an id and a label, so the icon comes from the
-// cached skill catalog; the query is skipped when no skill is referenced.
+// Skill references only carry an id and a label, so the icon comes from the cached catalog
export const useSkillIcon = (skillId: string | null): string | null => {
const { data } = useQuery(FindManySkillsForSuggestionDocument, {
skip: !isDefined(skillId),
diff --git a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
index 745dce0de01..38e46435bfd 100644
--- a/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
+++ b/packages/twenty-front/src/modules/skill-suggestion/hooks/useSkillSuggestionSearch.ts
@@ -10,9 +10,7 @@ export const useSkillSuggestionSearch = () => {
const searchSkills = useCallback(
async (query: string): Promise<SkillSuggestionItem[]> => {
- // Settings can delete or deactivate a skill without refetching the
- // catalog, so the list is refreshed when the menu opens (empty query)
- // and served from cache while the user narrows it down.
+ // Settings can delete or deactivate a skill without refetching, so refresh on open (empty query) and cache while narrowing
const { data } = await apolloMetadataClient.query({
query: FindManySkillsForSuggestionDocument,
fetchPolicy: query === '' ? 'network-only' : 'cache-first',
diff --git a/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts b/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts
index d50aef878b3..a62a6d134dd 100644
--- a/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts
+++ b/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts
@@ -13,8 +13,6 @@ jest.mock('~/utils/sleep', () => ({
sleep: jest.fn().mockResolvedValue(undefined),
}));
-// The hook only ever calls dispose, but the atom holds a full Client, so the
-// unused members are stubbed rather than cast away.
const buildSseClient = (dispose: () => void): Client => ({
subscribe: () => () => {},
iterate: async function* () {},
diff --git a/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts b/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts
index 81367d1fbe0..f04b378605b 100644
--- a/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts
+++ b/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts
@@ -21,9 +21,7 @@ const destroyStream = async (
store.set(sseClientState.atom, null);
};
-// The session cookie is httpOnly, so the client cannot inspect its own
-// credential; clearSession dropping this flag is what "signed out" looks like
-// from here.
+// The session cookie is httpOnly, so this flag is the only signed-out signal the client has
const hasCredential = (store: ReturnType<typeof useStore>): boolean =>
store.get(isCookieAuthActiveState.atom);
@@ -46,9 +44,7 @@ export const useHandleSseClientConnectionRetry = () => {
return;
}
- // Without this the loop is unbounded: graphql-sse resets its retry count
- // whenever a result arrives, so retryCount alone never trips on a stream
- // that keeps reconnecting. A signed-out client has to stop here.
+ // graphql-sse resets its retry count on every result, so a signed-out client must stop here or loop forever
if (!hasCredential(store)) {
await destroyStream(store, sseClient);
return;
diff --git a/packages/twenty-front/src/modules/ui/field/display/utils/__tests__/getDateFnsLocale.test.ts b/packages/twenty-front/src/modules/ui/field/display/utils/__tests__/getDateFnsLocale.test.ts
index 0eeeccc4e7b..1a7653e4250 100644
--- a/packages/twenty-front/src/modules/ui/field/display/utils/__tests__/getDateFnsLocale.test.ts
+++ b/packages/twenty-front/src/modules/ui/field/display/utils/__tests__/getDateFnsLocale.test.ts
@@ -16,8 +16,7 @@ describe('getDateFnsLocale', () => {
expect(locale?.code).toBe('fr');
});
- // The switch has an en-US default, so a case pointing at a module path that
- // does not exist fails the same silent way a missing case would.
+ // The switch defaults to en-US, so a wrong module path fails as silently as a missing case
it.each([
['hy-AM', 'hy'],
['sr-Latn', 'sr-Latn'],
diff --git a/packages/twenty-front/src/modules/ui/field/display/utils/getDateFnsLocale.ts b/packages/twenty-front/src/modules/ui/field/display/utils/getDateFnsLocale.ts
index 34414d1893a..88a32ba4458 100644
--- a/packages/twenty-front/src/modules/ui/field/display/utils/getDateFnsLocale.ts
+++ b/packages/twenty-front/src/modules/ui/field/display/utils/getDateFnsLocale.ts
@@ -72,10 +72,7 @@ export const getDateFnsLocaleImport = (locale: AppLocale) => {
case 'zh-TW':
return import('date-fns/locale/zh-TW');
default: {
- // getDateFnsLocale passes an arbitrary string, so unknown input still
- // lands here at runtime. A locale in APP_LOCALES must not: without this
- // the switch would silently format its dates in US English, and nothing
- // - not a type, not a test, not a lint rule - would say so.
+ // Unknown strings land here at runtime, but an APP_LOCALES locale must not silently format in en-US
locale satisfies never;
return import('date-fns/locale/en-US');
diff --git a/packages/twenty-front/src/modules/ui/layout/constants/RootStackingContextZIndices.ts b/packages/twenty-front/src/modules/ui/layout/constants/RootStackingContextZIndices.ts
index 53730efb9d4..baea4aec121 100644
--- a/packages/twenty-front/src/modules/ui/layout/constants/RootStackingContextZIndices.ts
+++ b/packages/twenty-front/src/modules/ui/layout/constants/RootStackingContextZIndices.ts
@@ -1,5 +1,3 @@
-// Every stacking context created on top of the document's root one gets its z-index here, so it no longer has to be
-// guessed from the dev console: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Stacking_context
// TODO: add the other remaining components that can appear in the root stacking context
export enum RootStackingContextZIndices {
LogConsole = 20,
diff --git a/packages/twenty-front/src/modules/ui/layout/contexts/LayoutRenderingContext.tsx b/packages/twenty-front/src/modules/ui/layout/contexts/LayoutRenderingContext.tsx
index e1a07dadd3a..ba1e3747c90 100644
--- a/packages/twenty-front/src/modules/ui/layout/contexts/LayoutRenderingContext.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/contexts/LayoutRenderingContext.tsx
@@ -3,9 +3,6 @@ import { createRequiredContext } from '~/utils/createRequiredContext';
import { type TargetRecordIdentifier } from './TargetRecordIdentifier';
export type LayoutRenderingContextType = {
- // Optional target record - only present for record pages that display data about a specific record
- // Undefined for dashboards which are standalone
- // Uses ActivityTargetableObject shape for compatibility with existing components
targetRecordIdentifier: TargetRecordIdentifier | undefined;
layoutType: PageLayoutType;
diff --git a/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableItem.tsx b/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableItem.tsx
index e94adf25663..4316ed44548 100644
--- a/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableItem.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableItem.tsx
@@ -42,7 +42,6 @@ export const DraggableItem = ({
},
});
- // Items report their presence so the list can size its trailing drop target.
useEffect(() => {
if (!isDefined(draggableListGroupContext)) {
return;
diff --git a/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableList.tsx b/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableList.tsx
index 9bf09e04c8a..27a08485ef8 100644
--- a/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableList.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/draggable-list/components/DraggableList.tsx
@@ -36,13 +36,10 @@ export const DraggableList = ({
draggableItems,
onDragEnd,
}: DraggableListProps) => {
- // The group id doubles as the items' dnd type, so drags from this list can't
- // land on outer providers' targets (or the other way around).
+ // The group id doubles as the items' dnd type, so drags cannot cross with outer providers' targets
const [group] = useState(() => v4());
- // Items register their index so the list can place the trailing drop target
- // and resolve the append position in the consumers' own index space, which
- // may be offset (a non-draggable header can occupy the leading indices).
+ // Consumer indices can be offset by a non-draggable header, so items register theirs to resolve the append position
const [itemIndexByDraggableId] = useState(() => new Map<string, number>());
const [trailingIndex, setTrailingIndex] = useState(0);
diff --git a/packages/twenty-front/src/modules/ui/layout/hooks/useWorkspaceSurfaceScopedComponentInstanceId.ts b/packages/twenty-front/src/modules/ui/layout/hooks/useWorkspaceSurfaceScopedComponentInstanceId.ts
index 3e105974d2b..4e42b4792c0 100644
--- a/packages/twenty-front/src/modules/ui/layout/hooks/useWorkspaceSurfaceScopedComponentInstanceId.ts
+++ b/packages/twenty-front/src/modules/ui/layout/hooks/useWorkspaceSurfaceScopedComponentInstanceId.ts
@@ -23,12 +23,8 @@ export const getWorkspaceSurfaceScopedComponentInstanceId = ({
return `${componentInstanceId}-${surfaceInstanceId}`;
};
-// Only for the place that creates an id for something the same page instance
-// can mount once per workspace surface (a record index, a page layout, a
-// settings tab bar). The id it returns is then passed around and used verbatim:
-// Dropdown, Modal, SelectableList, TabList and ScrollWrapper never rewrite the
-// id they are given, so a reader holding the same id always reads the same
-// state.
+// Only where an id is created for something mounted once per workspace surface; Dropdown, Modal, SelectableList,
+// TabList and ScrollWrapper use ids verbatim, so every reader of the returned id shares its state
export const useWorkspaceSurfaceScopedComponentInstanceId = (
componentInstanceId: string,
) => {
diff --git a/packages/twenty-front/src/modules/ui/layout/page/components/MainAppLayoutWithSidePanel.tsx b/packages/twenty-front/src/modules/ui/layout/page/components/MainAppLayoutWithSidePanel.tsx
index 08f9778951b..17125f7a3c0 100644
--- a/packages/twenty-front/src/modules/ui/layout/page/components/MainAppLayoutWithSidePanel.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/page/components/MainAppLayoutWithSidePanel.tsx
@@ -21,8 +21,6 @@ const StyledRow = styled.div`
min-height: auto;
min-width: auto;
- // Only the main content (first child) is printed; the side panel and its
- // resize chrome that follow it are hidden.
> *:not(:first-child) {
display: none;
}
diff --git a/packages/twenty-front/src/modules/ui/layout/page/components/__tests__/MainAppLayoutWithSidePanel.test.tsx b/packages/twenty-front/src/modules/ui/layout/page/components/__tests__/MainAppLayoutWithSidePanel.test.tsx
index 0997607e8de..dccddce0b0d 100644
--- a/packages/twenty-front/src/modules/ui/layout/page/components/__tests__/MainAppLayoutWithSidePanel.test.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/page/components/__tests__/MainAppLayoutWithSidePanel.test.tsx
@@ -104,8 +104,7 @@ describe('MainAppLayoutWithSidePanel', () => {
);
expect(await screen.findByText('record index page')).toBeInTheDocument();
- // Hosted above the routes, the provider still reads the matched leaf's
- // params: react-router shares one params object across a matched branch.
+ // react-router shares one params object across a matched branch, so the provider above the routes reads leaf params
expect(mockSeenParams.at(-1)?.objectNamePlural).toBe('companies');
act(() => {
diff --git a/packages/twenty-front/src/modules/ui/layout/side-panel/contexts/SidePanelFooterWidthContext.ts b/packages/twenty-front/src/modules/ui/layout/side-panel/contexts/SidePanelFooterWidthContext.ts
index 0d97c83d735..f81f8c50a32 100644
--- a/packages/twenty-front/src/modules/ui/layout/side-panel/contexts/SidePanelFooterWidthContext.ts
+++ b/packages/twenty-front/src/modules/ui/layout/side-panel/contexts/SidePanelFooterWidthContext.ts
@@ -1,5 +1,4 @@
import { createContext } from 'react';
-// Content width of the footer actions row, so an action that adapts to the
-// available space can size itself without stretching over the row to measure.
+// Lets an action adapt to the footer row width without stretching over the row to measure it
export const SidePanelFooterWidthContext = createContext<number>(0);
diff --git a/packages/twenty-front/src/modules/ui/layout/tab-list/hooks/useScrollActiveTabIntoView.ts b/packages/twenty-front/src/modules/ui/layout/tab-list/hooks/useScrollActiveTabIntoView.ts
index 1daca934a23..af3568900e9 100644
--- a/packages/twenty-front/src/modules/ui/layout/tab-list/hooks/useScrollActiveTabIntoView.ts
+++ b/packages/twenty-front/src/modules/ui/layout/tab-list/hooks/useScrollActiveTabIntoView.ts
@@ -5,9 +5,7 @@ type UseScrollActiveTabIntoViewParams = {
isScrollable: boolean;
};
-// A tab selected from the URL or from initial state can sit outside the
-// scrolled region, and a rotation can push it back out, which would leave the
-// row looking like nothing is selected.
+// A tab selected from the URL or initial state, or after a rotation, can sit outside the scrolled region
export const useScrollActiveTabIntoView = ({
activeTabId,
isScrollable,
diff --git a/packages/twenty-front/src/modules/ui/layout/tab-list/styles/ScrollableTabRowCSS.ts b/packages/twenty-front/src/modules/ui/layout/tab-list/styles/ScrollableTabRowCSS.ts
index 3dc0a424255..83dbe242e41 100644
--- a/packages/twenty-front/src/modules/ui/layout/tab-list/styles/ScrollableTabRowCSS.ts
+++ b/packages/twenty-front/src/modules/ui/layout/tab-list/styles/ScrollableTabRowCSS.ts
@@ -1,6 +1,4 @@
-// The breakpoint is width-based, so a narrow desktop window matches it too. A
-// mouse there has no swipe to fall back on, so only coarse pointers lose the
-// scrollbar.
+// A width breakpoint also matches narrow desktop windows, where a mouse cannot swipe, so only coarse pointers lose the scrollbar
export const SCROLLABLE_TAB_ROW_CSS = `
overflow-y: hidden;
diff --git a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/MultiWorkspaceDropdown/MultiWorkspaceDropdownButton.tsx b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/MultiWorkspaceDropdown/MultiWorkspaceDropdownButton.tsx
index 69b74d65488..835b23a5e2c 100644
--- a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/MultiWorkspaceDropdown/MultiWorkspaceDropdownButton.tsx
+++ b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/MultiWorkspaceDropdown/MultiWorkspaceDropdownButton.tsx
@@ -39,10 +39,7 @@ export const MultiWorkspaceDropdownButton = ({
return (
<Dropdown
dropdownId={MULTI_WORKSPACE_DROPDOWN_ID}
- // The trigger spans the whole row so the panel can overlay it. Aligned
- // to the row's end that lands on the drawer edge on desktop, but on
- // mobile the row is the full screen and the panel drifted away from the
- // workspace name it belongs to.
+ // On mobile the row is the full screen, so end alignment would drift the panel away from the workspace name
dropdownPlacement={isMobile ? 'bottom-start' : 'bottom-end'}
middlewareBoundaryPadding={
isMobile
@@ -53,8 +50,7 @@ export const MultiWorkspaceDropdownButton = ({
: undefined
}
dropdownOffset={
- // The drawer trigger is full width and the panel sits over it; the
- // icon-only trigger is too small for that, so the panel drops below.
+ // The icon-only trigger is too small for the panel to overlay, so it drops below
shouldHideLabel ? { y: 4, x: 0 } : { y: -31, x: -5 }
}
clickableComponent={
diff --git a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItemBreadcrumb.tsx b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItemBreadcrumb.tsx
index 3e3fae91754..d815d69dea8 100644
--- a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItemBreadcrumb.tsx
+++ b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItemBreadcrumb.tsx
@@ -54,8 +54,7 @@ const StyledRoundedProtrusion = styled.div<{ darker: boolean }>`
darker
? themeCssVariables.font.color.tertiary
: themeCssVariables.border.color.strong};
- // The elbow is the border minus two sides. Written physically it keeps its
- // left-hand shape under dir="rtl" and hangs off the wrong side of the item.
+ // Logical, not physical, so the elbow mirrors under dir="rtl"
border-end-start-radius: 4px;
border-inline-end: none;
diff --git a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/constants/MultiWorkspaceDropdownMobileBoundaryPadding.ts b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/constants/MultiWorkspaceDropdownMobileBoundaryPadding.ts
index 0fc02225c8e..c51989d5199 100644
--- a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/constants/MultiWorkspaceDropdownMobileBoundaryPadding.ts
+++ b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/constants/MultiWorkspaceDropdownMobileBoundaryPadding.ts
@@ -1,4 +1,2 @@
-// On mobile the page inset is 20px and the panel overlays its trigger 5px to
-// the left, so its edge lands at 16px. The default 32px boundary would make
-// floating-ui flip the alignment and send the panel to the far edge instead.
+// The panel edge lands at 16px on mobile; floating-ui's default 32px boundary would flip it to the far edge
export const MULTI_WORKSPACE_DROPDOWN_MOBILE_BOUNDARY_PADDING = 16;
diff --git a/packages/twenty-front/src/modules/ui/navigation/utils/isSafeInternalPath.ts b/packages/twenty-front/src/modules/ui/navigation/utils/isSafeInternalPath.ts
index 361fa1f3711..df021db28bc 100644
--- a/packages/twenty-front/src/modules/ui/navigation/utils/isSafeInternalPath.ts
+++ b/packages/twenty-front/src/modules/ui/navigation/utils/isSafeInternalPath.ts
@@ -1,7 +1,6 @@
import { isNonEmptyString } from '@sniptt/guards';
-// A leading '#' keeps the current page and only moves the hash, so it cannot
-// leave the app either.
+// A leading '#' only moves the hash, so it cannot leave the app either
export const isSafeInternalPath = (path: string): boolean =>
isNonEmptyString(path) &&
(path.startsWith('/') || path.startsWith('#')) &&
diff --git a/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
index 1f2ecbea0da..19021166812 100644
--- a/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
+++ b/packages/twenty-front/src/modules/ui/suggestion/components/SuggestionMenu.tsx
@@ -159,8 +159,7 @@ const SuggestionMenuInner = <TItem,>(
scrollableContainer.scrollTop = offsetTop - offsetHeight;
}, [clampedSelectedIndex]);
- // The preview is anchored to the selected row, so once the user scrolls that
- // row out of the list it would float detached from the menu.
+ // The preview is anchored to the selected row, so it would float detached once that row scrolls out
useLayoutEffect(() => {
const scrollableContainer =
listContainerRef.current?.firstElementChild ?? null;
diff --git a/packages/twenty-front/src/modules/ui/theme/components/UserUiScaleProviderEffect.tsx b/packages/twenty-front/src/modules/ui/theme/components/UserUiScaleProviderEffect.tsx
index 559ddea7cc7..3ed6d354ce9 100644
--- a/packages/twenty-front/src/modules/ui/theme/components/UserUiScaleProviderEffect.tsx
+++ b/packages/twenty-front/src/modules/ui/theme/components/UserUiScaleProviderEffect.tsx
@@ -6,9 +6,7 @@ import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomState
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { isDefined } from 'twenty-shared/utils';
-// BaseThemeProvider renders from the persisted step so the scale is right
-// before login resolves; this keeps the persisted copy following the
-// workspace member, which is the synced source of truth.
+// BaseThemeProvider reads the persisted step before login; keep it following the workspace member, the synced source of truth
export const UserUiScaleProviderEffect = () => {
const currentWorkspaceMember = useAtomStateValue(currentWorkspaceMemberState);
const setPersistedUiScaleStep = useSetAtomState(persistedUiScaleStepState);
diff --git a/packages/twenty-front/src/modules/ui/theme/constants/UiScaleMultipliers.ts b/packages/twenty-front/src/modules/ui/theme/constants/UiScaleMultipliers.ts
index 09bc853928d..3dbba055ab2 100644
--- a/packages/twenty-front/src/modules/ui/theme/constants/UiScaleMultipliers.ts
+++ b/packages/twenty-front/src/modules/ui/theme/constants/UiScaleMultipliers.ts
@@ -1,9 +1,7 @@
import { type UiScale } from '@/workspace-member/types/WorkspaceMember';
-// Multiplies --t-scale-user, which every dimension token in the theme derives
-// from. Default is exactly today's rendering; the steps bracket the range
-// where layout survives without reflowing (breakpoints do not move with the
-// scale, unlike browser zoom).
+// Multiplies --t-scale-user, which every dimension token derives from; Default is today's rendering.
+// Steps bracket the range where layout survives, as breakpoints do not move with the scale (unlike browser zoom)
export const UI_SCALE_MULTIPLIERS: Record<UiScale, number> = {
Smaller: 0.9,
Default: 1,
diff --git a/packages/twenty-front/src/modules/ui/theme/utils/getUiZoom.ts b/packages/twenty-front/src/modules/ui/theme/utils/getUiZoom.ts
index 782f537e976..351c549b46c 100644
--- a/packages/twenty-front/src/modules/ui/theme/utils/getUiZoom.ts
+++ b/packages/twenty-front/src/modules/ui/theme/utils/getUiZoom.ts
@@ -1,6 +1,5 @@
-// Pointer coordinates arrive in visual-viewport pixels while layout runs in
-// design pixels under the root zoom rule, so pointer deltas are divided by
-// the effective zoom before entering stored sizes.
+// Pointer coordinates are in visual-viewport pixels while layout uses design pixels under the root zoom,
+// so pointer deltas are divided by this before entering stored sizes
export const getUiZoom = (): number => {
if (typeof document === 'undefined') {
return 1;
diff --git a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/DragDropItemSortableCell.tsx b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/DragDropItemSortableCell.tsx
index 2a16c4b60bf..a5d5bb5a13b 100644
--- a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/DragDropItemSortableCell.tsx
+++ b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/DragDropItemSortableCell.tsx
@@ -49,8 +49,6 @@ const StyledSortableRoot = styled.div<{
transition: background 0.1s ease;
will-change: transform;
- /* When the cell delegates dragging to an explicit handle, only the handle
- is grabbable, so the rest of the cell keeps its ambient cursor. */
&:has([data-dnd-sortable-handle]) {
cursor: inherit;
}
@@ -71,8 +69,7 @@ type DragDropItemSortableCellProps = {
id: string;
index: number;
restrictMovementTo?: 'x' | 'y' | 'none';
- // Tags the split axis on the sortable's data so a pointer resolver can pick
- // the drop boundary per hovered item across lists of mixed orientations.
+ // Lets a pointer resolver pick the drop boundary per item across lists of mixed orientations
orientation?: DragDropItemDropTargetOrientation;
type?: string;
};
@@ -103,8 +100,7 @@ export const DragDropItemSortableCell = ({
accept,
collisionPriority: SORTABLE_COLLISION_PRIORITY,
collisionDetector,
- // Sortable metadata stays authoritative over consumer data so drag
- // handlers always resolve the cell's real group and position.
+ // Sortable metadata overrides consumer data so handlers resolve the cell's real group and position
data: {
...data,
droppableId: group,
@@ -129,10 +125,7 @@ export const DragDropItemSortableCell = ({
$fill={fill}
$isDragSourceFaded={fadeSourceWhileDragging && isDragSource}
$isDraggingHighlighted={highlightWhileDragging && isDragging}
- // dnd-kit's accessibility plugin stamps role="button" and tabindex on
- // any registered draggable that declares neither, so a disabled cell
- // would join the tab order and make pointer automation resolve clicks
- // on its content to a disabled button. Declaring both opts out.
+ // dnd-kit stamps role="button" and tabindex unless both are declared, putting disabled cells in the tab order and breaking automation clicks
role={disabled ? 'none' : undefined}
tabIndex={disabled ? -1 : undefined}
onDragStart={
diff --git a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/__tests__/DragDropItemSortableCell.test.tsx b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/__tests__/DragDropItemSortableCell.test.tsx
index d7a1865593f..ae304a46db8 100644
--- a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/__tests__/DragDropItemSortableCell.test.tsx
+++ b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/components/__tests__/DragDropItemSortableCell.test.tsx
@@ -2,10 +2,7 @@ import { DragDropItemSortableCell } from '@/ui/utilities/drag-and-drop/component
import { DragDropProvider } from '@dnd-kit/react';
import { render, screen, waitFor } from '@testing-library/react';
-// Playwright resolves a click on a non-interactive element to its closest
-// button-like ancestor before deciding whether the click target is enabled,
-// so a sortable wrapper that advertises itself as a disabled button makes
-// every element inside it unclickable for automation.
+// Playwright resolves clicks to the closest button-like ancestor, so a disabled-button wrapper makes its content unclickable
const CLICK_TARGET_ANCESTOR_SELECTOR =
'button, [role=button], [role=checkbox], [role=radio]';
diff --git a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitPluginsWithoutOptimistic.ts b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitPluginsWithoutOptimistic.ts
index a299d028aef..e32d7515c85 100644
--- a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitPluginsWithoutOptimistic.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitPluginsWithoutOptimistic.ts
@@ -1,6 +1,4 @@
import { SortableKeyboardPlugin } from '@dnd-kit/dom/sortable';
-// Deliberately excludes dnd-kit's optimistic sorting plugin: application state
-// stays the single source of truth for item order, so lists only reorder once
-// a drop is committed.
+// No optimistic sorting: application state owns item order, so lists reorder only once a drop commits
export const DND_KIT_PLUGINS_WITHOUT_OPTIMISTIC = [SortableKeyboardPlugin];
diff --git a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitProviderPluginsWithoutDropAnimation.ts b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitProviderPluginsWithoutDropAnimation.ts
index 61723defc2e..3f3b382a28b 100644
--- a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitProviderPluginsWithoutDropAnimation.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/constants/DndKitProviderPluginsWithoutDropAnimation.ts
@@ -1,10 +1,6 @@
import { defaultPreset, Feedback } from '@dnd-kit/dom';
-// Twenty applies reorders to application state the moment a drop commits, so
-// dnd-kit's default drop animation, which flies the dragged element back to
-// its pre-drag position, reads as the drop being reverted. The animating
-// element is also position: fixed with an infinite z-index, so it paints over
-// overlays such as the record side panel while it flies back.
+// Reorders commit on drop, so the default fly-back animation reads as a revert and paints over the side panel
export const DND_KIT_PROVIDER_PLUGINS_WITHOUT_DROP_ANIMATION =
defaultPreset.plugins.map((plugin) =>
plugin === Feedback ? Feedback.configure({ dropAnimation: null }) : plugin,
diff --git a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/PointerSensorWithSourceGuard.ts b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/PointerSensorWithSourceGuard.ts
index 97594106ccf..c20c65c2ffb 100644
--- a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/PointerSensorWithSourceGuard.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/PointerSensorWithSourceGuard.ts
@@ -1,12 +1,7 @@
import { type Draggable } from '@dnd-kit/dom';
import { PointerSensor } from '@dnd-kit/react';
-// A drag only activates once the pointer travels past the activation
-// constraints, so a re-render can unregister the pressed draggable between
-// pointerdown and activation: virtualized rows remounting under new sortable
-// ids, a widget or tab remounting while a page loads. The base sensor then
-// throws "Cannot start a drag operation without a drag source"; there is
-// nothing left to drag, so the gesture is canceled instead.
+// A re-render can unregister the pressed draggable before activation, which makes the base sensor throw
export class PointerSensorWithSourceGuard extends PointerSensor {
protected handleStart(source: Draggable, event: PointerEvent): void {
if (!this.manager.registry.draggables.has(source.id)) {
diff --git a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/__tests__/PointerSensorWithSourceGuard.test.ts b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/__tests__/PointerSensorWithSourceGuard.test.ts
index 6488105e9eb..86f9c572c22 100644
--- a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/__tests__/PointerSensorWithSourceGuard.test.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/sensors/__tests__/PointerSensorWithSourceGuard.test.ts
@@ -80,8 +80,7 @@ describe('PointerSensorWithSourceGuard', () => {
const sensor = new TestablePointerSensorWithSourceGuard(manager);
- // An already-aborted controller makes the base handleStart return before
- // pointer capture, which jsdom does not implement.
+ // An aborted controller makes the base handleStart return before pointer capture, which jsdom does not implement
const abortedController = new AbortController();
abortedController.abort();
const startSpy = jest
diff --git a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/utils/preventNativeDragStart.ts b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/utils/preventNativeDragStart.ts
index 30eec39a584..688b420f31c 100644
--- a/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/utils/preventNativeDragStart.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/drag-and-drop/utils/preventNativeDragStart.ts
@@ -1,7 +1,6 @@
import { type DragEvent } from 'react';
-// Links and images inside draggable items are natively draggable, which lets
-// the browser start a URL drag that cancels the dnd-kit pointer drag.
+// Native link and image drags would cancel the dnd-kit pointer drag
export const preventNativeDragStart = (event: DragEvent) => {
event.preventDefault();
};
diff --git a/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/__tests__/useAvailableComponentInstanceIdOrThrow.test.tsx b/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/__tests__/useAvailableComponentInstanceIdOrThrow.test.tsx
index 865819dab18..a9596f2a8f3 100644
--- a/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/__tests__/useAvailableComponentInstanceIdOrThrow.test.tsx
+++ b/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/__tests__/useAvailableComponentInstanceIdOrThrow.test.tsx
@@ -41,11 +41,8 @@ const buildWrapper =
</WorkspaceSurfaceContext.Provider>
);
-// Surface isolation is opted into where an id is created, at the provider.
-// These hooks must hand back exactly what they were given on every surface:
-// a side panel may deliberately provide the same id as the main surface to
-// share state with it, and ids are also rendered into DOM anchors that get
-// looked up by the exact string the provider used.
+// Ids must come back unchanged: a side panel may provide the main surface's id to share its state,
+// and DOM anchors are looked up by the exact string the provider used
describe('useAvailableComponentInstanceIdOrThrow', () => {
it.each(['main', 'side-panel'] as const)(
'returns the context id verbatim on a %s surface',
diff --git a/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceId.ts b/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceId.ts
index bf3de9465d3..d40caac48c4 100644
--- a/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceId.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceId.ts
@@ -2,8 +2,6 @@ import { useComponentInstanceStateContext } from '@/ui/utilities/state/component
import { type ComponentInstanceStateContext } from '@/ui/utilities/state/component-state/types/ComponentInstanceStateContext';
import { isNonEmptyString } from '@sniptt/guards';
-// Returns the id exactly as provided; see useAvailableComponentInstanceIdOrThrow
-// for why surface scoping belongs at the provider, not here.
export const useAvailableComponentInstanceId = <
T extends { instanceId: string },
>(
diff --git a/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow.ts b/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow.ts
index 64b6b165fe6..6141bac3987 100644
--- a/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow.ts
@@ -2,12 +2,8 @@ import { useComponentInstanceStateContext } from '@/ui/utilities/state/component
import { type ComponentInstanceStateContext } from '@/ui/utilities/state/component-state/types/ComponentInstanceStateContext';
import { isNonEmptyString } from '@sniptt/guards';
-// Returns the id exactly as provided. An id is made unique where it is created
-// (from the record, page, view or step it belongs to), never rewritten here:
-// this hook cannot tell state meant to be shared across surfaces (a side panel
-// reading the main diagram's flow) from state that must be isolated, and ids
-// also escape into DOM anchors that are looked up by the exact string a
-// provider rendered.
+// Callers make the id unique where they create it; it is never rewritten here, since some state is deliberately
+// shared across surfaces and ids are looked up verbatim as DOM anchors
export const useAvailableComponentInstanceIdOrThrow = <
T extends { instanceId: string },
>(
diff --git a/packages/twenty-front/src/modules/ui/utilities/state/jotai/utils/createAtomState.ts b/packages/twenty-front/src/modules/ui/utilities/state/jotai/utils/createAtomState.ts
index 789f77fbaaa..2df7887e190 100644
--- a/packages/twenty-front/src/modules/ui/utilities/state/jotai/utils/createAtomState.ts
+++ b/packages/twenty-front/src/modules/ui/utilities/state/jotai/utils/createAtomState.ts
@@ -25,9 +25,6 @@ type StateAtom<ValueType> = WritableAtom<
type LocalStorageOptions = { getOnInit?: boolean };
-// Wraps the default JSON localStorage so a persisted value that fails
-// validateInitFn falls back to the initial value instead of hydrating the atom
-// with an invalid payload.
const createValidatedLocalStorage = <ValueType>(
validateInitFn: (payload: NonNullable<ValueType>) => boolean,
) => {
diff --git a/packages/twenty-front/src/modules/views/hooks/__tests__/useQueryVariablesFromParentView.test.tsx b/packages/twenty-front/src/modules/views/hooks/__tests__/useQueryVariablesFromParentView.test.tsx
index 2df1a6ec50a..bba6af45e96 100644
--- a/packages/twenty-front/src/modules/views/hooks/__tests__/useQueryVariablesFromParentView.test.tsx
+++ b/packages/twenty-front/src/modules/views/hooks/__tests__/useQueryVariablesFromParentView.test.tsx
@@ -11,8 +11,7 @@ import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectM
const WORKFLOW_RECORD_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';
-// The hook reads the context store of the surface it renders on, which under
-// this wrapper is the instance getJestMetadataAndApolloMocksWrapper binds.
+// The context store instance getJestMetadataAndApolloMocksWrapper binds, which the hook reads
const CONTEXT_STORE_INSTANCE_ID = 'instanceId';
const workflowVersionObjectMetadataItem =
diff --git a/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewApiUpdate.ts b/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewApiUpdate.ts
index 34250a4e17b..91ec98ee691 100644
--- a/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewApiUpdate.ts
+++ b/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewApiUpdate.ts
@@ -31,8 +31,7 @@ export const usePerformViewApiUpdate = () => {
const store = useStore();
- // The server recreates the view groups when mainGroupByFieldMetadataId changes,
- // so the store has to be realigned on the groups returned by the mutation
+ // The server recreates view groups when mainGroupByFieldMetadataId changes
const syncViewGroupsFromMutationResult = useCallback(
({
viewId,
diff --git a/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewFilterApiPersist.ts b/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewFilterApiPersist.ts
index 0e41ac6e130..f23f133f13f 100644
--- a/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewFilterApiPersist.ts
+++ b/packages/twenty-front/src/modules/views/hooks/internal/usePerformViewFilterApiPersist.ts
@@ -16,8 +16,7 @@ import {
UpdateViewFilterDocument,
} from '~/generated-metadata/graphql';
-// Normalize value like the fetch path (splitViewWithRelated) so store
-// comparisons against string-converted values stay consistent
+// Normalized like the fetch path (splitViewWithRelated) so store comparisons stay consistent
const toFlatViewFilter = ({
__typename,
...viewFilter
diff --git a/packages/twenty-front/src/modules/workflow/hooks/__tests__/useFlowOrThrow.test.tsx b/packages/twenty-front/src/modules/workflow/hooks/__tests__/useFlowOrThrow.test.tsx
index bb45adab961..d830f8d2e5e 100644
--- a/packages/twenty-front/src/modules/workflow/hooks/__tests__/useFlowOrThrow.test.tsx
+++ b/packages/twenty-front/src/modules/workflow/hooks/__tests__/useFlowOrThrow.test.tsx
@@ -41,10 +41,7 @@ const buildWrapper =
);
describe('useFlowOrThrow', () => {
- // The workflow diagram on the main surface writes the flow, and the side
- // panel step editor deliberately provides the same visualizer instance id to
- // read it. If component ids were rewritten per surface, the side panel would
- // read a different atom and every step click would crash.
+ // The side panel step editor reuses the main diagram's visualizer instance id; per-surface ids would read another atom and crash on step click
it('reads a flow written on the main surface from a side panel sharing the instance id', () => {
const store = createStore();
const flow = {
diff --git a/packages/twenty-front/src/modules/workflow/workflow-diagram/components/WorkflowSSESubscribeEffect.tsx b/packages/twenty-front/src/modules/workflow/workflow-diagram/components/WorkflowSSESubscribeEffect.tsx
index 6a9500d7a84..dcf5a4690a4 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-diagram/components/WorkflowSSESubscribeEffect.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-diagram/components/WorkflowSSESubscribeEffect.tsx
@@ -31,8 +31,7 @@ export const WorkflowSSESubscribeEffect = ({
setShouldWorkflowRefetchRequest(true);
}, [setShouldWorkflowRefetchRequest]);
- // Subset of the workflow query the page already runs, so the version ids
- // are served from the Apollo cache without an extra request.
+ // Subset of the page's workflow query, so version ids come from the Apollo cache
const { record: workflowWithVersionIds } = useFindOneRecord<{
__typename: string;
id: string;
@@ -61,11 +60,7 @@ export const WorkflowSSESubscribeEffect = ({
onSseReconnected: requestWorkflowRefetch,
});
- // Creations cover new draft versions; updates cover step and trigger edits
- // on the current draft (the AI chat, another user, another tab). Local
- // workflow mutations do not dispatch these events, only SSE deliveries do,
- // and refetching on an own-persist echo reseeds the diagram with the state
- // it already shows.
+ // Local mutations do not dispatch these events, so this only follows remote edits (AI chat, other users or tabs)
const handleWorkflowVersionOperationBrowserEvent = useCallback(
(detail: ObjectRecordOperationBrowserEventDetail) => {
if (detail.operation.type === 'create-one') {
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields.tsx
index c5372739f3c..82978a98e31 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormFields.tsx
@@ -13,8 +13,6 @@ type WorkflowFormFieldsProps = {
onError?: (error: string | undefined) => void;
};
-// The fields a person fills in to answer a form, whether a workflow form step
-// or an agent asked for it.
export const WorkflowFormFields = ({
fields,
readonly,
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts
index ccdf116c2c2..828612272f4 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStep.ts
@@ -39,8 +39,6 @@ export const useAnswerFormStep = ({
fetchPolicy: 'network-only',
});
- // A form step's call is named after the step, in the conversation its
- // current execution recorded.
const answerFormStep = async (
response: Record<string, unknown>,
): Promise<boolean> => {
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/generateClassifyOutputSchema.test.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/generateClassifyOutputSchema.test.ts
index e600bd834ed..2f33a6f95f1 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/generateClassifyOutputSchema.test.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/__tests__/generateClassifyOutputSchema.test.ts
@@ -119,8 +119,7 @@ describe('generateClassifyOutputSchema', () => {
});
});
- // A half-written question would otherwise publish an empty variable name that
- // no downstream step can reference.
+ // A half-written question would publish an empty variable name no downstream step can reference
it('should leave out questions that have no name yet', () => {
const outputSchema = generateClassifyOutputSchema([
{
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
index b754b8c6756..32d25e9cdf1 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
@@ -139,7 +139,6 @@ export const computeStepOutputSchema = ({
};
}
- // BULK_RECORDS - array indicator nested under payload
return {
[WORKFLOW_TRIGGER_PAYLOAD_KEY]: {
isLeaf: false,
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/generateClassifyOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/generateClassifyOutputSchema.ts
index 43a014c5ca9..90ecba57096 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/generateClassifyOutputSchema.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/generateClassifyOutputSchema.ts
@@ -60,8 +60,7 @@ const buildAnswerSchema = (
label: 'Score',
value: 0,
},
- // Native scores carry a distribution over level indices, so the picker
- // advertises it the same way it does for a choice.
+ // Native scores carry a distribution over level indices, advertised like a choice's
probabilities: buildProbabilitiesNode(
question.criteria.map((_, level) => String(level)),
),
@@ -79,8 +78,7 @@ const buildAnswerSchema = (
}
};
-// Answers are keyed by the question's name, so a downstream step reads
-// {{stepId.answers.<name>.choice}} whatever model answered.
+// Keyed by question name, so downstream steps read {{stepId.answers.<name>.choice}} whatever model answered
export const generateClassifyOutputSchema = (
questions: WorkflowClassifyQuestion[],
): BaseOutputSchemaV2 => ({
diff --git a/packages/twenty-front/src/modules/workspace/utils/updateWorkspaceResourceCreditCap.ts b/packages/twenty-front/src/modules/workspace/utils/updateWorkspaceResourceCreditCap.ts
index 8fafe43cf50..e98b3db35c3 100644
--- a/packages/twenty-front/src/modules/workspace/utils/updateWorkspaceResourceCreditCap.ts
+++ b/packages/twenty-front/src/modules/workspace/utils/updateWorkspaceResourceCreditCap.ts
@@ -37,9 +37,7 @@ export const markWorkspaceCreditsExhausted = (
): CurrentWorkspace | null =>
updateWorkspaceResourceCreditCap(currentWorkspace, true);
-// The optimistic inverse of markWorkspaceCreditsExhausted: a send that passed
-// the server credit gate proves credits are available right now, which is the
-// only client-side signal after an external top-up while the app stays open.
+// A send that passed the server credit gate is the only client-side signal of an external top-up
export const markWorkspaceCreditsAvailable = (
currentWorkspace: CurrentWorkspace | null,
): CurrentWorkspace | null =>
diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
index fe886a3bf21..1d5d2a60b8b 100644
--- a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
@@ -49,8 +49,6 @@ export const AiChatPage = () => {
objectRecordId: displayedThreadId,
}}
headerActions={isMobile && <AiChatCloseButton />}
- // The chat's title is all its header needs, and the conversation
- // takes the whole page
headerTitleMode="record-title"
isRecordIdentifierBarHidden
/>
diff --git a/packages/twenty-front/src/pages/auth/SignInUp.tsx b/packages/twenty-front/src/pages/auth/SignInUp.tsx
index 26c4b15c2fb..de9db78ece3 100644
--- a/packages/twenty-front/src/pages/auth/SignInUp.tsx
+++ b/packages/twenty-front/src/pages/auth/SignInUp.tsx
@@ -145,9 +145,7 @@ export const SignInUp = () => {
);
}
- // The workspace creation form is shared by both multi-workspace and
- // single-workspace self-host, so it must render regardless of domain or
- // workspace scope.
+ // Shared by multi-workspace and single-workspace self-host, so it renders regardless of domain or workspace scope
if (signInUpStep === SignInUpStep.WorkspaceCreation) {
return <SignInUpWorkspaceCreationForm />;
}
diff --git a/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx b/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx
index f25a6f4a353..b9608ce9f29 100644
--- a/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx
+++ b/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx
@@ -27,9 +27,7 @@ export const SettingsAccountsEmails = () => {
(channel) =>
channel.isSyncEnabled &&
channel.syncStage !== MessageChannelSyncStage.PENDING_CONFIGURATION &&
- // Every setting on this page is a mailbox setting, so it lists
- // mailboxes only: group inboxes have their own page, and app-owned
- // channels are configured by the app that created them.
+ // Mailboxes only: group inboxes have their own page and app-owned channels are configured by their app
channel.type === MessageChannelType.EMAIL,
),
[allMessageChannels],
diff --git a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsx b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsx
index 3b58c09f4bd..3794f2f61a5 100644
--- a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsx
+++ b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminNewAiProvider.tsx
@@ -182,8 +182,7 @@ export const SettingsAdminNewAiProvider = () => {
const accessKeyId = values.accessKeyId.trim();
const secretAccessKey = values.secretAccessKey.trim();
- // Half a key pair is a slip, not a mode: role auth ignores both fields,
- // so accepting it would run under an identity nobody chose.
+ // Role auth ignores both fields, so half a key pair would run under an identity nobody chose
if (isNonEmptyString(accessKeyId) !== isNonEmptyString(secretAccessKey)) {
form.setError(
isNonEmptyString(accessKeyId) ? 'secretAccessKey' : 'accessKeyId',
diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsx
index dbdebe5b4fa..236fe2e3238 100644
--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsx
@@ -70,9 +70,6 @@ export const SettingsAgentRoleTab = ({
1
: false;
- // Role is only editable if it's not shared and either:
- // 1. Assigned exclusively to this agent (edit mode)
- // 2. Not yet assigned to anyone (create mode)
const isRoleExclusiveToThisAgent =
!isRoleShared &&
selectedRole &&
diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSkillsTab.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSkillsTab.tsx
index ccbc92a4a5e..98d1b3d5b76 100644
--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSkillsTab.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSkillsTab.tsx
@@ -51,8 +51,7 @@ export const SettingsAgentSkillsTab = () => {
const currentWorkspace = useAtomStateValue(currentWorkspaceState);
const installedApplications = currentWorkspace?.installedApplications;
- // not memoized: getApplicationDisplayName translates the standard and custom
- // labels, so a cached label would survive a locale change
+ // not memoized: the label is translated, so a cached one would survive a locale change
const skillTableItems = (data?.skills ?? []).map((skill) => {
const application = installedApplications?.find(
(installedApplication) => installedApplication.id === skill.applicationId,
diff --git a/packages/twenty-front/src/pages/settings/ai/components/__tests__/SettingsAgentSkillsTab.test.tsx b/packages/twenty-front/src/pages/settings/ai/components/__tests__/SettingsAgentSkillsTab.test.tsx
index 763fef0213e..cc7154a8eb9 100644
--- a/packages/twenty-front/src/pages/settings/ai/components/__tests__/SettingsAgentSkillsTab.test.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/components/__tests__/SettingsAgentSkillsTab.test.tsx
@@ -172,7 +172,6 @@ describe('SettingsAgentSkillsTab', () => {
renderSkillsTab();
- // fr-FR translates the workspace custom application label
expect(await screen.findByText('Personnalisé')).toBeInTheDocument();
await userEvent.type(
diff --git a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentSave.ts b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentSave.ts
index a2f8f3eff55..e57bb7784f4 100644
--- a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentSave.ts
+++ b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentSave.ts
@@ -123,8 +123,7 @@ export const useSettingsAgentSave = ({
}
}, 1_000);
- // Role permissions are edited by the shared roles module through Jotai
- // state, so there is no change handler to schedule the save from.
+ // Role permissions are edited through Jotai state by the shared roles module, so no change handler can schedule the save
useEffect(() => {
if (isRoleDirty) {
autoSave();
diff --git a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAiModelsActions.ts b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAiModelsActions.ts
index 5327d931ef4..4665a712e04 100644
--- a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAiModelsActions.ts
+++ b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAiModelsActions.ts
@@ -14,9 +14,8 @@ import {
UpdateWorkspaceDocument,
} from '~/generated-metadata/graphql';
-// Typed with the generated enum so the same object is both the optimistic
-// workspace patch and the mutation input; the enum's keys are the shared tier
-// literals, which is what makes the lookup below total.
+// Typed with the generated enum so one object is both the optimistic workspace patch and the mutation input;
+// the enum's keys are the shared tier literals, which keeps the GraphqlAiModelTier[tier] lookups total
type WorkspaceAiModelSettingsChanges = Partial<
Pick<
CurrentWorkspace,
diff --git a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
index 77c37dafe35..7b9662cfeb3 100644
--- a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
@@ -195,8 +195,7 @@ export const SettingsApplicationDetails = () => {
const tabs: SingleTabProps[] = [
{ id: GENERAL_TAB_ID, title: t`General`, Icon: IconSettings },
- // A custom settings tab lays out the application variables itself, so
- // exposing them again would duplicate the same fields.
+ // A custom settings tab lays out the application variables itself, so this tab would duplicate them
...(hasVariablesTab
? [{ id: VARIABLES_TAB_ID, title: t`Variables`, Icon: IconVariable }]
: []),
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx
index 3e5e98a1787..6c29a3f4c74 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx
@@ -43,9 +43,7 @@ const StyledContentContainer = styled.div`
width: 100%;
`;
-// The sidebar only sticks while both columns fit side by side: once they
-// stack, a sticky sidebar would cover the description below it. It sticks
-// at the page's top padding so it does not jump when scrolling starts.
+// Sticks only while the columns sit side by side, otherwise it would cover the stacked description
const StyledSidebarColumn = styled.div`
flex: 1 1 0;
min-width: ${SIDEBAR_COLUMN_MIN_WIDTH_PX}px;
@@ -146,8 +144,7 @@ export const SettingsApplicationDetailAboutTab = ({
const descriptionSummary = getApplicationDescriptionSummary(description);
- // The sidebar shows the first paragraph of the description, so the content
- // column only renders the description itself when it holds more than that.
+ // The sidebar already shows the first paragraph of the description
const getMarkdownText = () => {
if (isNonEmptyString(aboutDescription)) {
return aboutDescription;
diff --git a/packages/twenty-front/src/pages/settings/data-model/new-index/SettingsObjectNewIndex.tsx b/packages/twenty-front/src/pages/settings/data-model/new-index/SettingsObjectNewIndex.tsx
index fa25f5954d1..0d513652bbe 100644
--- a/packages/twenty-front/src/pages/settings/data-model/new-index/SettingsObjectNewIndex.tsx
+++ b/packages/twenty-front/src/pages/settings/data-model/new-index/SettingsObjectNewIndex.tsx
@@ -34,8 +34,7 @@ const isFieldIndexable = (field: FieldMetadataItem): boolean => {
if (field.isSystem === true) return false;
if (field.isActive !== true) return false;
- // Only MANY_TO_ONE relations have a join column on this side; ONE_TO_MANY
- // and MANY_TO_MANY have nothing concrete to index.
+ // Only MANY_TO_ONE relations have a join column on this side to index
const relationType =
field.relation?.type ?? field.morphRelations?.[0]?.type ?? null;
diff --git a/packages/twenty-front/src/testing/graphqlMocks.ts b/packages/twenty-front/src/testing/graphqlMocks.ts
index 7d78e301cdd..9f1f05c2bd4 100644
--- a/packages/twenty-front/src/testing/graphqlMocks.ts
+++ b/packages/twenty-front/src/testing/graphqlMocks.ts
@@ -57,8 +57,6 @@ const flatTaskRecords = mockedTaskRecords.map((record) =>
getRecordFromRecordNode<Task>({ recordNode: record }),
);
-// Wraps raw server-fetched records (which already have correct field shapes)
-// into a GraphQL connection response structure.
const wrapRecordsAsConnection = (
objectNameSingular: string,
records: Record<string, unknown>[],
diff --git a/packages/twenty-oxlint-rules/rules/no-icu-escaping-apostrophe.ts b/packages/twenty-oxlint-rules/rules/no-icu-escaping-apostrophe.ts
index 186aacbcd14..fc878ccbc27 100644
--- a/packages/twenty-oxlint-rules/rules/no-icu-escaping-apostrophe.ts
+++ b/packages/twenty-oxlint-rules/rules/no-icu-escaping-apostrophe.ts
@@ -9,8 +9,7 @@ const getTagName = (tag: any): string | undefined => {
return tag.name;
}
- // useLingui() hands the macro back on an object, so `i18n.t` and `_.t` reach
- // the extractor exactly as a bare tag does.
+ // useLingui() returns the macro on an object, so `i18n.t` and `_.t` are extracted like a bare tag
if (tag.type === 'MemberExpression' && tag.property.type === 'Identifier') {
return tag.property.name;
}
@@ -24,10 +23,7 @@ const countTrailingApostrophes = (text: string): number => {
return trailing === null ? 0 : trailing[0].length;
};
-// ICU reads an apostrophe placed directly before `{` as the start of a quoted
-// literal, so `'{name}'` prints the placeholder instead of substituting it.
-// Apostrophes pair up first: an even run is that many escaped literal
-// apostrophes, and only an odd run leaves one to swallow the placeholder.
+// ICU reads an apostrophe before `{` as a quote; apostrophes pair up, so only an odd run swallows the placeholder
const escapesFollowingPlaceholder = (text: string): boolean =>
countTrailingApostrophes(text) % 2 === 1;
diff --git a/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.spec.ts b/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.spec.ts
index b82e19272c2..7364afbce09 100644
--- a/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.spec.ts
+++ b/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.spec.ts
@@ -18,8 +18,7 @@ ruleTester.run(RULE_NAME, rule, {
code: "const label = msg({ message: `ID`, context: 'fieldMetadata.label' });",
filename: 'compute-company.ts',
},
- // The acronym is the tail of a field name the sentence is naming, so the
- // lowercase spelling is the correct one.
+ // The acronym is the tail of a field name the sentence names, so lowercase is correct
{
code: 'const message = msg`${fieldName} and ${fieldName}Id cannot be both provided.`;',
filename: 'connect-query.ts',
diff --git a/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.ts b/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.ts
index d09798131e4..29ced987325 100644
--- a/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.ts
+++ b/packages/twenty-oxlint-rules/rules/no-miscased-acronym-in-message.ts
@@ -44,10 +44,8 @@ const CORRECT_CASING: Record<string, string> = {
Yaml: 'YAML',
};
-// `}` joins the boundary characters so that `${fieldName}Id` is left alone: the
-// acronym there is the tail of a code identifier the sentence is naming, not an
-// English word. The trailing guard rejects `Identity` and `Urls` alike - `Urls`
-// only matches because the map lists it in its own right.
+// `}` is a boundary so `${fieldName}Id`, a code identifier rather than a word, is left alone.
+// The trailing guard rejects `Identity` and `Urls` alike; `Urls` only matches because the map lists it.
const MISCASED_ACRONYM_REGEX = new RegExp(
`(?<![A-Za-z}])(${Object.keys(CORRECT_CASING).join('|')})(?![a-z])`,
'g',
@@ -58,8 +56,7 @@ const getTagName = (tag: any): string | undefined => {
return tag.name;
}
- // useLingui() hands the macro back on an object, so `i18n.t` and `_.t` reach
- // the extractor exactly as a bare tag does.
+ // useLingui() returns the macro on an object, so `i18n.t` and `_.t` are extracted like a bare tag
if (tag.type === 'MemberExpression' && tag.property.type === 'Identifier') {
return tag.property.name;
}
@@ -71,10 +68,7 @@ const findMiscasedAcronyms = (text: string): string[] => [
...new Set([...text.matchAll(MISCASED_ACRONYM_REGEX)].map(([word]) => word)),
];
-// A template literal reaches the rule already split at its placeholders, so the
-// `Id` of `${fieldName}Id` opens its own chunk with nothing in front of it and
-// the boundary guard would wave it through. Putting the brace back restores the
-// context the split removed.
+// Quasis are split at placeholders, so restore the brace or the boundary guard would wave `Id` through
const withPrecedingPlaceholder = (
text: string,
isPrecededByPlaceholder: boolean,
@@ -127,8 +121,7 @@ export const rule = defineRule({
});
},
- // The descriptor form the standard field metadata uses, and where this
- // defect collected.
+ // The descriptor form standard field metadata uses, where this defect collected
CallExpression: (node: any) => {
const calleeName = getTagName(node.callee);
@@ -172,8 +165,7 @@ export const rule = defineRule({
}
},
- // Trans children only: plain JSX text is not a translatable string, so
- // flagging it here would report a different problem under this rule's name.
+ // Trans children only: plain JSX text is not a translatable string
JSXElement: (node: any) => {
if (
node.openingElement.name.type !== 'JSXIdentifier' ||
diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts
index 75611a03b08..9e37dc507a1 100644
--- a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts
+++ b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/expected-manifest.ts
@@ -343,7 +343,6 @@ export const EXPECTED_MANIFEST: Manifest = {
],
fields: [
- // User-defined relation and field definitions
{
label: 'Post Card',
name: 'postCard',
@@ -452,7 +451,6 @@ export const EXPECTED_MANIFEST: Manifest = {
relationType: RelationType.MANY_TO_ONE,
},
},
- // Field on standard company object
{
defaultValue: false,
description: 'Whether the company can receive postcards',
diff --git a/packages/twenty-sdk/src/cli/commands/dev/add.ts b/packages/twenty-sdk/src/cli/commands/dev/add.ts
index 5167980f1d7..e3756965c88 100644
--- a/packages/twenty-sdk/src/cli/commands/dev/add.ts
+++ b/packages/twenty-sdk/src/cli/commands/dev/add.ts
@@ -49,8 +49,7 @@ export class EntityAddCommand {
async execute(entityType?: SyncableEntity, path?: string): Promise<void> {
try {
- // Generated files embed identifiers derived from the application
- // universal identifier, so scaffolding is blocked until it is defined.
+ // Generated files embed identifiers derived from the application universal identifier
const applicationUniversalIdentifier =
await getApplicationUniversalIdentifierOrThrow(
CURRENT_EXECUTION_DIRECTORY,
@@ -490,12 +489,7 @@ export class EntityAddCommand {
);
}
- // Connection providers reference two serverVariables (`<NAME>_CLIENT_ID`
- // and `<NAME>_CLIENT_SECRET`) that the dev needs to declare on
- // `defineApplication.serverVariables`. Auto-append them so the dev
- // doesn't have to remember the wiring after `twenty dev:add connection-provider`.
- // The util is best-effort: it handles the common file shapes and falls
- // back to a printed snippet for anything it can't safely modify.
+ // Best-effort: falls back to printing a snippet for file shapes it cannot safely modify
private async registerConnectionProviderServerVariables(
name: string,
): Promise<void> {
diff --git a/packages/twenty-sdk/src/cli/utilities/build/common/build-application.ts b/packages/twenty-sdk/src/cli/utilities/build/common/build-application.ts
index fb72a8c376e..abbe641fe48 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/common/build-application.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/common/build-application.ts
@@ -76,10 +76,7 @@ export const buildApplication = async (
const sharedDependencies =
options.manifest.application.frontComponentSharedDependencies;
- // Bake the app's compiled translation catalogs into every front-component
- // bundle so the runtime t()/<Trans> resolves them in the sandboxed worker
- // without a server round-trip. Omitted entirely when the app has no
- // translations, leaving the runtime to fall back to source strings.
+ // Baked into each bundle so t()/<Trans> resolve in the sandboxed worker without a server round-trip
const frontComponentTranslationCatalogs =
await loadFrontComponentTranslationCatalogs(options.appPath);
diff --git a/packages/twenty-sdk/src/cli/utilities/translations/__tests__/application-translations.spec.ts b/packages/twenty-sdk/src/cli/utilities/translations/__tests__/application-translations.spec.ts
index 062211fa076..14e6ba153c1 100644
--- a/packages/twenty-sdk/src/cli/utilities/translations/__tests__/application-translations.spec.ts
+++ b/packages/twenty-sdk/src/cli/utilities/translations/__tests__/application-translations.spec.ts
@@ -60,15 +60,13 @@ describe('collectTranslatableStrings', () => {
{ message: 'A company', context: 'objectMetadata.description' },
{ message: 'Name', context: 'fieldMetadata.label' },
{ message: 'Name', context: 'fieldMetadata.description' },
- // the same string in two roles is two entries now
+ // the same string in two roles is two entries
{ message: 'Company', context: 'fieldMetadata.label' },
]),
);
});
- // Pins every manifest collection the shared registry maps, so a change to
- // TRANSLATABLE_PROPERTIES_BY_METADATA_NAME that silently drops a collection
- // shows up here rather than as an app shipping untranslatable strings.
+ // Pins every collection the shared registry maps, so dropping one fails here instead of shipping untranslatable strings
it('collects the fields declared inline on an object', () => {
const manifest = buildManifest({
objects: [
diff --git a/packages/twenty-sdk/src/cli/utilities/translations/__tests__/compile-catalog-to-message-ids.spec.ts b/packages/twenty-sdk/src/cli/utilities/translations/__tests__/compile-catalog-to-message-ids.spec.ts
index 71a0591bfd3..a14b0904034 100644
--- a/packages/twenty-sdk/src/cli/utilities/translations/__tests__/compile-catalog-to-message-ids.spec.ts
+++ b/packages/twenty-sdk/src/cli/utilities/translations/__tests__/compile-catalog-to-message-ids.spec.ts
@@ -35,8 +35,7 @@ describe('compileCatalogToMessageIds', () => {
it('reports a collision and keeps the later entry', () => {
const onCollision = vi.fn();
- // An empty-string context group hashes like no context at all, so two
- // distinct authored entries can claim one message id.
+ // An empty-string context hashes like no context, so two authored entries can claim one message id
const compiled = compileCatalogToMessageIds({
catalog: {
Export: 'first',
diff --git a/packages/twenty-sdk/src/cli/utilities/translations/collect-translatable-strings.ts b/packages/twenty-sdk/src/cli/utilities/translations/collect-translatable-strings.ts
index e6d35175a3d..0e193827e18 100644
--- a/packages/twenty-sdk/src/cli/utilities/translations/collect-translatable-strings.ts
+++ b/packages/twenty-sdk/src/cli/utilities/translations/collect-translatable-strings.ts
@@ -7,10 +7,7 @@ import {
import { type MessageDescriptor } from '@/sdk/front-component/translations/message';
-// Which manifest collection carries which metadata entity. The properties to
-// extract are not listed here on purpose: they come from the shared registry,
-// so the SDK cannot drift from what the server actually resolves at runtime.
-// Metadata names with no manifest collection (viewFieldGroup) are simply absent.
+// Manifest collection per metadata entity; the properties come from the shared registry so the SDK cannot drift from the server
const MANIFEST_KEY_BY_METADATA_NAME = {
objectMetadata: 'objects',
fieldMetadata: 'fields',
@@ -27,9 +24,7 @@ const MANIFEST_KEY_BY_METADATA_NAME = {
export const collectTranslatableStrings = (
manifest: Manifest,
): MessageDescriptor[] => {
- // The same string can label several roles ('Invoice' as an object name and a
- // field label), and each role is its own catalog entry, so descriptors are
- // deduplicated per (context, message) rather than per message.
+ // One string can label several roles, each its own catalog entry, so dedupe per (context, message)
const descriptorByKey = new Map<string, MessageDescriptor>();
const addEntityStrings = (
@@ -78,8 +73,7 @@ export const collectTranslatableStrings = (
}
}
- // Tab and widget titles live nested under pageLayouts[].tabs[], not in the
- // flat pageLayoutTabs array, so walk the tree to reach them.
+ // Tab and widget titles are nested under pageLayouts[].tabs[], not in the flat pageLayoutTabs array
for (const pageLayout of manifest.pageLayouts ?? []) {
for (const tab of pageLayout.tabs ?? []) {
addEntityStrings(tab, 'pageLayoutTab');
diff --git a/packages/twenty-sdk/src/cli/utilities/translations/compile-catalog-to-message-ids.ts b/packages/twenty-sdk/src/cli/utilities/translations/compile-catalog-to-message-ids.ts
index 2075603ae68..eca8cb41b06 100644
--- a/packages/twenty-sdk/src/cli/utilities/translations/compile-catalog-to-message-ids.ts
+++ b/packages/twenty-sdk/src/cli/utilities/translations/compile-catalog-to-message-ids.ts
@@ -3,9 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { flattenLocaleCatalog } from '@/cli/utilities/translations/locale-catalog-format';
-// Authoring files are keyed readable (context groups + plain messages) for
-// translators; runtime lookups are by message id, so every consumer compiles
-// through here.
+// Authoring files are keyed readably for translators; runtime lookups are by message id
export const compileCatalogToMessageIds = ({
catalog,
onCollision,
diff --git a/packages/twenty-sdk/src/cli/utilities/translations/extract-application-translations.ts b/packages/twenty-sdk/src/cli/utilities/translations/extract-application-translations.ts
index 801e7be3805..41c4d63f313 100644
--- a/packages/twenty-sdk/src/cli/utilities/translations/extract-application-translations.ts
+++ b/packages/twenty-sdk/src/cli/utilities/translations/extract-application-translations.ts
@@ -73,8 +73,7 @@ export const extractApplicationTranslations = async ({
await ensureDir(localesDir);
- // The source file carries the message as its own translation, so a
- // translator sees the original next to every hole they are filling.
+ // The source file carries the message as its own translation, so translators see the original
await writeJson(
path.join(localesDir, `${SOURCE_LOCALE}.json`),
buildLocaleCatalog(
diff --git a/packages/twenty-sdk/src/cli/utilities/translations/locale-catalog-format.ts b/packages/twenty-sdk/src/cli/utilities/translations/locale-catalog-format.ts
index db858fd2c8b..9c25f0e8058 100644
--- a/packages/twenty-sdk/src/cli/utilities/translations/locale-catalog-format.ts
+++ b/packages/twenty-sdk/src/cli/utilities/translations/locale-catalog-format.ts
@@ -1,17 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
-// A locale file is authored by hand, so its shape is optimized for reading:
-// context-free messages sit at the top level, and contextual messages are
-// grouped under their context so a translator sees the role ('Invoice' under
-// objectMetadata.labelSingular is an object name, not a field label).
-//
-// {
-// "Saved {count} cards": "{count} cartes enregistrées",
-// "objectMetadata.labelSingular": { "Invoice": "Facture" }
-// }
-//
-// A string value is a translation, an object value is a context group -- which
-// is also how the two are told apart when reading.
+// Hand-authored: messages at the top level, contextual ones grouped under their context (string = translation, object = group)
export type LocaleCatalogEntry = {
message: string;
context?: string;
diff --git a/packages/twenty-sdk/src/sdk/billing/charge-credits.ts b/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
index ec4e81822c3..c4b1b84e78d 100644
--- a/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
+++ b/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
@@ -10,32 +10,24 @@ const BILLING_CHARGE_TIMEOUT_MS = 5_000;
export type ChargeCreditsParams = {
creditsUsedMicro: number;
quantity?: number;
- // Who the spend belongs to, for runs with no triggering user (a webhook, a
- // cron). Ignored otherwise: the token already names them.
+ // Who the spend belongs to when no user triggered the run (webhook, cron); ignored otherwise
userWorkspaceId?: string;
} & (
| {
- // An operation name declared in `billing.operations` on the application
- // manifest. The platform resolves its billing category and its label.
+ // An operation declared in the manifest's `billing.operations`; the platform resolves its category and label
operation: string;
operationType?: never;
resourceContext?: never;
}
| {
- // For applications that declare no billable operations: name the
- // platform billing category directly, unlabelled.
+ // For applications that declare no billable operations: names the platform billing category directly
operationType: UsageOperationTypeValue;
operation?: never;
resourceContext?: string;
}
);
-// Records credit usage against the running application via the Twenty
-// server's `/app/billing/charge` endpoint. Reads `TWENTY_API_URL` and the
-// application access token from the execution env (injected by the
-// logic-function runtime). No-ops silently when either is missing so
-// local/test runs don't crash. Failures are non-fatal — a billing error
-// never surfaces as a tool failure.
+// No-ops without an API URL or access token, and never throws: a billing error must not fail a tool
export const chargeCredits = async ({
creditsUsedMicro,
quantity = 1,
diff --git a/packages/twenty-sdk/src/sdk/billing/get-credit-availability.ts b/packages/twenty-sdk/src/sdk/billing/get-credit-availability.ts
index 3d812c6da37..b2c0ed9aeac 100644
--- a/packages/twenty-sdk/src/sdk/billing/get-credit-availability.ts
+++ b/packages/twenty-sdk/src/sdk/billing/get-credit-availability.ts
@@ -9,8 +9,7 @@ import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-to
const CREDIT_AVAILABILITY_TIMEOUT_MS = 5_000;
-// A fresh object per call: the returned value is handed to app code, and a
-// shared constant could be mutated by one caller and observed by the next.
+// A fresh object per call, since app code could mutate a shared constant
const available = (): CreditAvailability => ({ hasAvailableCredits: true });
const parseCreditAvailability = (body: unknown): CreditAvailability | null => {
@@ -40,15 +39,7 @@ const parseCreditAvailability = (body: unknown): CreditAvailability | null => {
return null;
};
-// Asks whether the workspace can still spend, so an app can stop before doing
-// expensive work rather than finding out when a downstream call it did not
-// write throws. Mirrors the gate the platform applies to AI work and outbound
-// email.
-//
-// Fails open, like the platform's own usage read: a timeout, an unreachable
-// server or an unparseable body reports credits available rather than stopping
-// an app over an infrastructure hiccup. An app must not treat this as an
-// authorization decision, only as a hint worth honouring.
+// Fails open on timeouts or bad responses: a hint before expensive work, never an authorization decision
export const getCreditAvailability = async (): Promise<CreditAvailability> => {
const apiUrl = process.env[DEFAULT_API_URL_NAME];
const token = getApplicationAccessToken();
diff --git a/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts b/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts
index bb1f8327814..b2c25c07f96 100644
--- a/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts
+++ b/packages/twenty-sdk/src/sdk/define/logic-functions/logic-function-config.ts
@@ -6,17 +6,14 @@ import {
import { type LogicFunctionExecutionContext } from 'twenty-shared/logic-function';
import { type LogicFunctionHttpResponse } from 'twenty-shared/types';
-// TPayload defaults to any so handlers that declare a concrete payload type
-// stay assignable; the second parameter is what authors need to discover.
+// TPayload defaults to any so handlers declaring a concrete payload type stay assignable
export type LogicFunctionHandler<TPayload = any> = (
payload: TPayload,
context: LogicFunctionExecutionContext,
) => any | Promise<any>;
-// A resolver attached to `serverRouteTriggerSettings` runs in the owner workspace and is the single
-// point of authorization: the URL only carries the resolver's universalIdentifier. Returning a
-// dispatch result enqueues the target, returning a `Response` answers the caller synchronously
-// instead, for providers whose webhook URL requires a handshake reply.
+// The resolver runs in the owner workspace and is the only authorization point: the URL carries just its universalIdentifier.
+// A dispatch result enqueues the target; a Response answers synchronously, for providers needing a handshake reply.
export type ServerRouteResolverResult =
| ServerRouteDispatchResult
| LogicFunctionHttpResponse;
diff --git a/packages/twenty-sdk/src/sdk/front-component/components/Trans.tsx b/packages/twenty-sdk/src/sdk/front-component/components/Trans.tsx
index c894ab4fab9..b8bfb48e075 100644
--- a/packages/twenty-sdk/src/sdk/front-component/components/Trans.tsx
+++ b/packages/twenty-sdk/src/sdk/front-component/components/Trans.tsx
@@ -9,8 +9,7 @@ import { resolveTranslation } from '../translations/resolveTranslation';
export type TransProps = {
children?: ReactNode;
- // Use this (with `values`) for interpolation; inlined child expressions
- // cannot be statically extracted.
+ // Use with `values` for interpolation: inlined child expressions cannot be statically extracted
message?: string;
context?: string;
values?: TranslationValues;
diff --git a/packages/twenty-sdk/src/sdk/front-component/constants/front-component-translations-key.ts b/packages/twenty-sdk/src/sdk/front-component/constants/front-component-translations-key.ts
index 6cef3bf8e54..3c6d41c207d 100644
--- a/packages/twenty-sdk/src/sdk/front-component/constants/front-component-translations-key.ts
+++ b/packages/twenty-sdk/src/sdk/front-component/constants/front-component-translations-key.ts
@@ -1,4 +1,3 @@
-// globalThis key under which the build bakes the app's compiled translation
-// catalogs so the runtime resolver can read them inside the sandboxed worker.
+// Where the build bakes compiled catalogs, so the runtime can read them inside the sandboxed worker
export const FRONT_COMPONENT_TRANSLATIONS_KEY =
'__twentySdkFrontComponentTranslations__';
diff --git a/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.ts b/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.ts
index a8b48d472aa..9099b5389af 100644
--- a/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.ts
+++ b/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.ts
@@ -129,8 +129,7 @@ export type UploadedFrontComponentFile = {
};
export type UploadFileParams = {
- // Uploads target a FILES field so the file can be attached to a record;
- // anything else would strand it as a temporary orphan.
+ // Must be a FILES field so the file attaches to a record; anything else would strand it as a temporary orphan
fieldMetadataId: string;
fileName?: string;
};
diff --git a/packages/twenty-sdk/src/sdk/front-component/hooks/useLocale.ts b/packages/twenty-sdk/src/sdk/front-component/hooks/useLocale.ts
index af3c51ab2be..567eb3194e3 100644
--- a/packages/twenty-sdk/src/sdk/front-component/hooks/useLocale.ts
+++ b/packages/twenty-sdk/src/sdk/front-component/hooks/useLocale.ts
@@ -6,8 +6,7 @@ import { useFrontComponentExecutionContext } from './useFrontComponentExecutionC
const selectLocale = (context: FrontComponentExecutionContext): AppLocale =>
context.locale ?? SOURCE_LOCALE;
-// Reactive locale of the host UI. Re-renders the component when the user
-// switches language, mirroring useColorScheme.
+// Re-renders when the user switches language, like useColorScheme
export const useLocale = (): AppLocale => {
return useFrontComponentExecutionContext(selectLocale);
};
diff --git a/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentToolCallStatus.ts b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentToolCallStatus.ts
index b235378f70e..483247a2bf2 100644
--- a/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentToolCallStatus.ts
+++ b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentToolCallStatus.ts
@@ -1,5 +1,4 @@
-// Mirrors the tool part states the chat runtime emits, approval states
-// included, so a widget can render a call at any point in its life.
+// Mirrors the chat runtime's tool part states, approval states included
export type FrontComponentToolCallStatus =
| 'input-streaming'
| 'input-available'
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index 119542d97d3..e22376686c1 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -1,14 +1,5 @@
-// Runtime-facing barrel for logic-function authors.
-//
-// Anything imported from this entry point is allowed to reach the Lambda
-// runtime. Today we only re-export type-only payload shapes; all of these
-// disappear at TS compile time so the compiled bundle is empty.
-//
-// `defineLogicFunction`, `definePostInstallLogicFunction`, etc. intentionally
-// stay in `twenty-sdk/define` — they are build-time metadata factories that
-// the SDK CLI stubs out before bundling. Logic-function source files keep
-// importing them from `twenty-sdk/define`, but should reach for *types* (and
-// future runtime helpers) here, never directly from `twenty-shared/*`.
+// Only what may reach the Lambda runtime; build-time define* factories stay in twenty-sdk/define.
+// Logic functions import types from here, never directly from twenty-shared/*.
export type {
LogicFunctionConfig,
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
index aeabf7ef303..09b4ed19d1e 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
@@ -13,17 +13,13 @@ const CREATE_APP_MESSAGE_CHANNEL_MUTATION = `
`;
export type CreateMessageChannelInput = {
- // An app connection id, from `getConnection`/`listConnections`. The channel
- // speaks through this credential and inherits who may see it.
+ // An app connection id (from getConnection/listConnections); the channel speaks through it and inherits who may see it
connectedAccountId: string;
- // This account's identity on the provider — whatever the provider calls it.
- // Inbound participants matching it are treated as the account itself.
+ // The account's provider identity; inbound participants matching it are treated as the account itself
handle: string;
displayName?: string;
- // Required rather than defaulted: this decides whether one member's
- // conversations are readable by the whole workspace, and only the app
- // knows how private its provider's messages are. Prefer 'METADATA' for
- // personal inboxes and 'SHARE_EVERYTHING' for shared ones.
+ // Required: decides whether one member's conversations are readable by the whole workspace, and only the app
+ // knows how private its messages are ('METADATA' for personal inboxes, 'SHARE_EVERYTHING' for shared ones)
visibility: MessageChannelVisibility;
};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/delete-message-channel.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/delete-message-channel.ts
index 773d9696aaf..56df6db0d63 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/delete-message-channel.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/delete-message-channel.ts
@@ -10,10 +10,8 @@ const DELETE_APP_MESSAGE_CHANNEL_MUTATION = `
}
`;
-// Deleting a channel also deletes the messages ingested through it, and any
-// thread left with no messages. Call this from the connection provider's
-// onDisconnect hook to retire a channel along with its credential; to stop
-// ingesting while keeping the history, set `isSyncEnabled` to false instead.
+// Also deletes the channel's ingested messages and emptied threads; call from onDisconnect to retire a channel with its credential.
+// To stop ingesting but keep the history, set `isSyncEnabled` to false instead.
export const deleteMessageChannel = async (
id: string,
): Promise<AppMessageChannel> => {
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/ingest-messages.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/ingest-messages.ts
index 4862b196765..7356585052b 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/ingest-messages.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/ingest-messages.ts
@@ -16,13 +16,8 @@ const INGEST_APP_MESSAGES_MUTATION = `
}
`;
-// Writes messages into Twenty's Message/Message Thread records. Threading,
-// de-duplication, channel association and per-message privacy are handled
-// server-side; the whole batch lands in one transaction.
-//
-// At most 100 messages per call: one call is one transaction inside one
-// logic-function timeout, so page a provider backfill rather than sending it
-// whole.
+// Threading, dedup and privacy are handled server-side. At most 100 messages per call (one transaction
+// within one logic-function timeout), so page provider backfills
export const ingestMessages = async ({
messageChannelId,
messages,
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
index d06beed19e1..45ecca9a91b 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
@@ -1,5 +1,4 @@
-// Every helper selects the same fields, so an AppMessageChannel returned by
-// one is interchangeable with one returned by another.
+// Shared by every helper, so channels returned by any of them are interchangeable
export const APP_MESSAGE_CHANNEL_SELECTION = `
id
handle
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/types/app-message-channel.type.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/app-message-channel.type.ts
index fc77212d7e6..13b0d072c74 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/types/app-message-channel.type.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/app-message-channel.type.ts
@@ -1,6 +1 @@
-// One messaging channel the running app owns. Returned from
-// `createMessageChannel` and `listMessageChannels`.
-//
-// The shape lives in twenty-shared so this re-export and the server-side
-// projection always agree — changes propagate to both at once.
export type { AppMessageChannel } from 'twenty-shared/application';
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/types/ingest-message.type.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/ingest-message.type.ts
index b7ad01dd5ff..8a84665cf82 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/types/ingest-message.type.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/ingest-message.type.ts
@@ -1,41 +1,24 @@
import { type MessageParticipantRole } from 'twenty-shared/types';
export type IngestMessageParticipant = {
- // 'FROM' marks the sender; exactly one participant must carry it. When its
- // handle equals the channel's, the message is recorded as outgoing.
+ // Exactly one participant must be 'FROM'; when its handle equals the channel's, the message is outgoing
role: MessageParticipantRole;
- // The participant's identity on the provider, in the same namespace as the
- // channel's own handle.
+ // Same namespace as the channel's own handle
handle: string;
- // Omitting it on a later delivery keeps whatever name is already stored,
- // so enriching a participant with an identity does not require resending
- // the rest of the row.
+ // Omitting it on a later delivery keeps the stored name
displayName?: string;
- // Twenty resolves email participants to People by email address, which
- // cannot match a provider handle. Supply the record yourself when you know
- // it — look the handle up against `Person.linkedinLink` or an identity
- // field your app added. Without it the participant stays unlinked and the
- // thread never appears on anyone's record page.
- //
- // Ingesting the same message again with an identity you have since
- // resolved links the existing participant, so a late match is not lost.
+ // Handles cannot match People by email, so without this the thread lands on no record; re-ingesting links a late match
personId?: string;
- // For a participant who is a member of this workspace rather than a contact.
- // Attribution only: record-page placement is built from `personId` alone, so
- // a participant linked only to a workspace member shows in the thread but
- // pulls the conversation onto no record.
+ // Attribution only: record-page placement is built from `personId` alone
workspaceMemberId?: string;
};
export type IngestMessage = {
- // The provider's id for this message. Ingesting it twice is a no-op, so
- // redelivered webhooks are safe to replay.
+ // Ingesting it twice is a no-op, so redelivered webhooks are safe to replay
externalId: string;
- // The provider's id for the conversation. Messages sharing one land in the
- // same Message Thread.
+ // Messages sharing one land in the same Message Thread
threadExternalId: string;
- // Most non-email providers have none; the thread falls back to its
- // participants for a title.
+ // Most non-email providers have none; the thread then takes its title from participants
subject?: string;
text: string;
receivedAt: Date;
@@ -44,8 +27,7 @@ export type IngestMessage = {
export type IngestedMessage = {
externalId: string;
- // Stable across re-ingestion, so it is safe to hang timeline activities or
- // your own records off it.
+ // Stable across re-ingestion, so safe to hang timeline activities or your own records off
messageId: string;
messageThreadId: string;
};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/update-message-channel.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/update-message-channel.ts
index 79b89b5a63f..2a6c35e65d8 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/messaging/update-message-channel.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/update-message-channel.ts
@@ -16,11 +16,9 @@ export type UpdateMessageChannelInput = {
id: string;
// Omitted leaves the current label untouched; null clears it.
displayName?: string | null;
- // Changing this changes who can read every message already ingested into
- // the channel, not just the ones that follow.
+ // Changes who can read every message already ingested, not just the ones that follow
visibility?: MessageChannelVisibility;
- // False pauses ingestion without deleting the history; ingesting into a
- // paused channel is rejected.
+ // False pauses ingestion (further ingests are rejected) without deleting the history
isSyncEnabled?: boolean;
};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/timeline/create-timeline-activity.ts b/packages/twenty-sdk/src/sdk/logic-function/timeline/create-timeline-activity.ts
index 06884fa44e4..2036ee65f5c 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/timeline/create-timeline-activity.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/timeline/create-timeline-activity.ts
@@ -50,8 +50,7 @@ const getObjectMetadataSelection = (universalIdentifiers: string[]) => ({
},
});
-// App code addresses manifest entities by their stable universal identifier;
-// the workspace row deliberately stores the installation-specific metadata ID.
+// Apps address manifest entities by universal identifier; the row stores the installation-specific metadata id
export const createTimelineActivity = async ({
timelineActivityTypeUniversalIdentifier,
targetObjectUniversalIdentifier,
diff --git a/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts b/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
index bca34761fd0..9b348e23882 100644
--- a/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
+++ b/packages/twenty-sdk/src/sdk/utils/get-application-access-token.ts
@@ -3,9 +3,7 @@ import {
DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME,
} from 'twenty-shared/application';
-// These calls reach the application's own resources rather than acting for
-// whoever triggered the run, so they take the application token whenever the
-// logic function runtime injects one. Front components only ever get the other.
+// These reach the application's own resources, so prefer the application token when the runtime injects one
export const getApplicationAccessToken = (): string | undefined =>
process.env[DEFAULT_APP_APPLICATION_ACCESS_TOKEN_NAME] ??
process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];
diff --git a/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts b/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts
index 86ab63703c0..c87e0e34ffc 100644
--- a/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts
+++ b/packages/twenty-sdk/src/sdk/utils/get-public-asset-url.ts
@@ -13,9 +13,7 @@ const decodeTokenPayload = (
};
};
-// Returns the public URL for a file in the app's public/ directory.
-// Works in both logic functions and front components.
-// The path is relative to the public/ folder (e.g. "images/logo.png").
+// Path is relative to the app's public/ folder (e.g. "images/logo.png")
export const getPublicAssetUrl = (path: string): string => {
const apiUrl = process.env[DEFAULT_API_URL_NAME];
const token = getApplicationAccessToken();
diff --git a/packages/twenty-server/jest-integration.config.ts b/packages/twenty-server/jest-integration.config.ts
index bb6a0f94265..e231ab30ef5 100644
--- a/packages/twenty-server/jest-integration.config.ts
+++ b/packages/twenty-server/jest-integration.config.ts
@@ -17,8 +17,7 @@ const isClickhouseEnabled = process.env.CLICKHOUSE_URL !== undefined;
const tsConfig = require('./tsconfig.json');
const jestConfig: JestConfigWithTsJest = {
- // For more information please have a look to official docs https://jestjs.io/docs/configuration/#prettierpath-string
- // Prettier v3 should be supported in jest v30 https://github.com/jestjs/jest/releases/tag/v30.0.0-alpha.1
+ // Prettier v3 is only supported from jest v30 (https://github.com/jestjs/jest/releases/tag/v30.0.0-alpha.1)
prettierPath: null,
silent: false,
errorOnDeprecated: true,
@@ -29,8 +28,7 @@ const jestConfig: JestConfigWithTsJest = {
testPathIgnorePatterns: [
...(isBillingEnabled ? [] : ['<rootDir>/test/integration/billing']),
...(isClickhouseEnabled ? [] : ['<rootDir>/test/integration/audit']),
- // Requires an app booted as a secure deployment; run through
- // jest-integration-secure.config.ts (nx test:integration:secure).
+ // Needs a secure-deployment app; runs via jest-integration-secure.config.ts (nx test:integration:secure)
'<rootDir>/test/integration/secure-deployment',
],
testRegex: '\\.integration-spec\\.ts$',
@@ -42,11 +40,7 @@ const jestConfig: JestConfigWithTsJest = {
],
testTimeout: 20000,
maxWorkers: 1,
- // jsdom 29 and msw ship ESM-only transitive deps (parse5, entities,
- // tough-cookie, @exodus/bytes via html-encoding-sniffer, @csstools/@asamuzakjp
- // css engine, @mswjs/interceptors and friends), and ai, @ai-sdk/* and their
- // @workflow/serde dependency ship ESM only; let swc transform them
- // (and .mjs below) so jest can require them.
+ // ESM-only deps (jsdom 29 and msw chains, ai, @ai-sdk/*, @workflow/serde) that swc must transform for jest
transformIgnorePatterns: [
'/node_modules/(?!(.*/node_modules/)?(jsdom|html-encoding-sniffer|whatwg-encoding|@exodus|parse5|entities|tough-cookie|@csstools|@asamuzakjp|msw|@mswjs|until-async|@bundled-es-modules|@open-draft|strict-event-emitter|headers-polyfill|outvariant|is-node-process|path-to-regexp|statuses|cookie|digest-fetch|md5|email-reply-parser|ai|@ai-sdk|@workflow|htmlparser2|domhandler|domutils|dom-serializer|domelementtype|@faker-js)/)',
],
@@ -91,8 +85,6 @@ const jestConfig: JestConfigWithTsJest = {
globals: {
APP_PORT: 4000,
NODE_ENV: NodeEnvironment.TEST,
- // Test tokens are loaded from a shared JSON file to ensure consistency
- // with CI workflows and other tools that need these tokens
...testTokens,
},
};
diff --git a/packages/twenty-server/jest.config.mjs b/packages/twenty-server/jest.config.mjs
index b0b296a0d1e..e8b8648f5db 100644
--- a/packages/twenty-server/jest.config.mjs
+++ b/packages/twenty-server/jest.config.mjs
@@ -4,8 +4,7 @@ const require = createRequire(import.meta.url);
const isCI = process.env.CI === 'true';
const jestConfig = {
- // For more information please have a look to official docs https://jestjs.io/docs/configuration/#prettierpath-string
- // Prettier v3 should be supported in jest v30 https://github.com/jestjs/jest/releases/tag/v30.0.0-alpha.1
+ // Prettier v3 is only supported from jest v30 (https://github.com/jestjs/jest/releases/tag/v30.0.0-alpha.1)
prettierPath: null,
// to enable logs, comment out the following line
silent: true,
@@ -17,14 +16,7 @@ const jestConfig = {
testEnvironment: 'node',
setupFilesAfterEnv: ['./setupTests.ts'],
transformIgnorePatterns: [
- // jsdom 29 pulls ESM-only transitive deps (parse5, entities, tough-cookie,
- // @exodus/bytes via html-encoding-sniffer, @csstools/@asamuzakjp css engine),
- // and e2b/@e2b pull ESM-only chalk; ai, @ai-sdk/* and their @workflow/serde dependency ship ESM only.
- // sanitize-html >=2.17.6 pulls htmlparser2 12 (ESM-only, with its domhandler/domutils/dom-serializer/domelementtype chain),
- // @faker-js/faker 10 ships ESM only (it is a runtime dependency of the OpenAPI module and used by the metadata mocks);
- // nested under sanitize-html/node_modules because other consumers hold htmlparser2 8/10 at the root -- the optional
- // (.*/node_modules/)? prefix lets the allow-list match a package at any nesting depth, not only the hoisted copy.
- // jest's CJS runtime can't load their `export` syntax, so let swc transform them.
+ // ESM-only deps jest's CJS runtime cannot load; (.*/node_modules/)? also matches nested copies like sanitize-html's htmlparser2
'/node_modules/(?!(.*/node_modules/)?(file-type|@file-type|strtok3|token-types|@borewit|@tokenizer|uint8array-extras|read-next-line|digest-fetch|md5|js-sha256|js-sha512|base-64|charenc|crypt|email-reply-parser|jsdom|html-encoding-sniffer|whatwg-encoding|@exodus|parse5|entities|tough-cookie|@csstools|@asamuzakjp|graphql-upload|fs-capacitor|e2b|@e2b|chalk|ai|@ai-sdk|@workflow|htmlparser2|domhandler|domutils|dom-serializer|domelementtype|@faker-js|twenty-oxlint-rules)/)',
],
testRegex: '.*\\.spec\\.ts$',
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/fetch-artificial-analysis.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/fetch-artificial-analysis.spec.ts
index d9872996af5..aa10b789fcc 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/fetch-artificial-analysis.spec.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/fetch-artificial-analysis.spec.ts
@@ -52,9 +52,8 @@ describe('fetchArtificialAnalysisBenchmarks', () => {
])(
'keeps the highest-scoring configuration whatever the order (%s)',
async (_label, bestFirst) => {
- // The rows for one model are the same model at different reasoning
- // efforts. Picking by how populated a row is scored Sonnet 4.6 at low
- // effort against Sonnet 5 at max, and the gap read as capability.
+ // A model's rows differ only by reasoning effort; picking the most populated one once scored
+ // Sonnet 4.6 at low effort against Sonnet 5 at max, and the gap read as capability
const lowEffort = {
slug: 'claude-sonnet-4-6',
name: 'Claude Sonnet 4.6 (Non-reasoning, Low Effort)',
@@ -78,8 +77,7 @@ describe('fetchArtificialAnalysisBenchmarks', () => {
);
expect(record?.intelligenceIndex).toBe(36.2);
- // The whole row travels together, so speed and cost describe the same
- // configuration the index was measured in.
+ // The whole row travels together, so speed and cost match the index's configuration
expect(record?.outputTokensPerSecond).toBe(80);
expect(record?.costPerTask).toBeUndefined();
},
@@ -199,8 +197,7 @@ describe('fetchArtificialAnalysisBenchmarks', () => {
const index = await fetchArtificialAnalysisBenchmarks('key');
- // The bare key still carries the ceiling, so nothing a consumer reads today
- // changes.
+ // The bare key still carries the ceiling, so nothing a consumer reads today changes
expect(index.get('gpt56sol')?.intelligenceIndex).toBe(47.1);
expect(index.get('gpt56sol')?.effort).toBe('max');
expect(index.get('gpt56sol@max')?.intelligenceIndex).toBe(47.1);
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/match-benchmarks.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/match-benchmarks.spec.ts
index 39c07ea94a9..46c2cd62b12 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/match-benchmarks.spec.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/match-benchmarks.spec.ts
@@ -65,8 +65,7 @@ describe('buildLookupCandidates', () => {
});
it('resolves the same way whatever order an undated provider lists twins in', () => {
- // Nothing in models.dev hits this today, but the resolution must not depend
- // on the order a third party happens to serialize its models in.
+ // Resolution must not depend on the order a third party serializes its models in
const undated = {
'mistral-large-latest': modelsDevModel({ id: 'mistral-large-latest' }),
'mistral-large-2506': modelsDevModel({ id: 'mistral-large-2506' }),
@@ -94,9 +93,7 @@ describe('buildLookupCandidates', () => {
});
it('does not offer the undated name once the alias resolves to a release', () => {
- // The leaderboard's bare `mistral-large` row is the Feb '24 model. Letting
- // it stand in for the release `-latest` currently points at published a
- // two-year-old score as the current one.
+ // The bare `mistral-large` row is the Feb '24 model and once published a stale score as current
const candidates = buildLookupCandidates({
modelName: 'mistral-large-latest',
siblingModels: MISTRAL_MODELS,
@@ -107,8 +104,7 @@ describe('buildLookupCandidates', () => {
});
it('offers no undated spelling of a resolved full-date release either', () => {
- // The publisher's undated row is whichever snapshot it last measured, which
- // is the same trap as the bare rolling name in a longer date format.
+ // An undated row is whichever snapshot was last measured, the same trap as a bare rolling name
const candidates = buildLookupCandidates({
modelName: 'claude-sonnet-5-latest',
siblingModels: {
@@ -179,8 +175,7 @@ describe('matchBenchmarks', () => {
});
it('returns nothing for a matched row carrying no measurement at all', () => {
- // The publisher lists models it has measured nothing about; matching one
- // must not produce an entry holding only a timestamp.
+ // Matching an unmeasured model must not produce an entry holding only a timestamp
expect(
match(
'mistral-large-2512',
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/merge-evaluation-models.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/merge-evaluation-models.spec.ts
index b65cf1d72e3..4298ce45da0 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/merge-evaluation-models.spec.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/merge-evaluation-models.spec.ts
@@ -32,9 +32,7 @@ describe('mergeEvaluationModels', () => {
]);
});
- // The whole point of merging per model: the day an existing provider ships an
- // evaluation model, it is one entry in the hand-maintained file and the
- // language models the sync just fetched stay where they are.
+ // An existing provider's evaluation model must not displace the language models the sync fetched
it('should keep the fetched models of a vendor that also ships an evaluation model', () => {
const catalog: GeneratedCatalog = {
openai: { models: [languageModel('gpt-5'), languageModel('gpt-5-mini')] },
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/read-committed-benchmarks.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/read-committed-benchmarks.spec.ts
index 57ef4d2378a..d522cc7f467 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/read-committed-benchmarks.spec.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/read-committed-benchmarks.spec.ts
@@ -52,8 +52,7 @@ describe('readCommittedBenchmarks', () => {
});
it('keeps a preserved measurement dated when it was taken, not today', () => {
- // Restamping recovered data as measured today would present a stale
- // benchmark as fresh on every failed run.
+ // Restamping recovered data would present a stale benchmark as fresh on every failed run
const index = readCommittedBenchmarks(writeOverlay(PUBLISHED));
const result = matchBenchmarks({
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/self-host-projection.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/self-host-projection.spec.ts
index d434686c940..b613d13edc1 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/self-host-projection.spec.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/self-host-projection.spec.ts
@@ -8,8 +8,7 @@ import {
projectCatalog,
} from '../utils/project-catalog.util';
-// The shipped catalog is generated, and a hand edit to it is the drift this
-// pipeline exists to remove, so it has to stay what its spec produces.
+// The shipped catalog is generated, so a hand edit is the drift this pipeline exists to remove
describe('the shipped catalog', () => {
it('is what the self-host spec projects from the model catalog', () => {
const projected = projectCatalog({
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/index.ts b/packages/twenty-server/scripts/ai-catalog-sync/index.ts
index b11a1030ca7..3ffee5f09fd 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/index.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/index.ts
@@ -57,8 +57,7 @@ const readCommittedModels = (filePath: string): GeneratedCatalog =>
? (JSON.parse(fs.readFileSync(filePath, 'utf-8')) as GeneratedCatalog)
: {};
-// The vendors the shipped catalog carries are the ones the self-host spec
-// serves; nothing else needs to be fetched, checked or written.
+// The shipped catalog carries exactly the vendors the self-host spec serves
const readVendors = (spec: CatalogSpec): string[] => {
const vendors = [
...new Set(
@@ -68,8 +67,7 @@ const readVendors = (spec: CatalogSpec): string[] => {
),
];
- // An empty list would fetch nothing, assert nothing and write an empty
- // catalog over the real one, and the sync PR automerges.
+ // An empty list would write an empty catalog over the real one, and the sync PR automerges
if (!isNonEmptyArray(vendors)) {
throw new Error(
`${SELF_HOST_SPEC_PATH} names no vendor to carry: every route lists models explicitly`,
@@ -99,8 +97,7 @@ const fetchModelsDev = async ({
return data;
};
-// A leaderboard outage must never break the model catalog, so a failed fetch
-// degrades to an empty index and the catalog is written without benchmarks.
+// A leaderboard outage must never break the model catalog, so a failed fetch degrades to an empty index
const fetchBenchmarks = async (): Promise<BenchmarkIndex> => {
const apiKey = process.env.ARTIFICIAL_ANALYSIS_API_KEY;
@@ -155,9 +152,7 @@ const main = async (): Promise<void> => {
const fetched = await fetchBenchmarks();
- // A failed fetch must not delete measurements we already published: the
- // catalog PR is automerged, so an empty index would silently strip every
- // benchmark until the next healthy run.
+ // The catalog PR automerges, so a failed fetch must not strip already published benchmarks
const benchmarkIndex =
fetched.size > 0 ? fetched : readCommittedBenchmarks(BENCHMARKS_PATH);
@@ -201,8 +196,7 @@ const main = async (): Promise<void> => {
}
await writeJson(MODELS_PATH, catalog);
- // Self-host runs the same projection cloud does, from a spec that names the
- // five direct routes and lets each serve its whole vendor.
+ // The spec names the five direct routes and lets each serve its whole vendor
await writeJson(
CATALOG_PATH,
projectCatalog({ canonicalCatalog: catalog, spec: selfHostSpec }),
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/project.ts b/packages/twenty-server/scripts/ai-catalog-sync/project.ts
index 26adbecc9b9..7cf4c1a791c 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/project.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/project.ts
@@ -1,8 +1,5 @@
-// Projects the canonical catalog through a deployment spec. See README.md.
-//
-// This entry point and the files it imports resolve through node builtins and
-// source paths only, so a repository holding a private spec can run them
-// straight from a sparse checkout without installing the monorepo.
+// See README.md. This file and its imports use node builtins and source paths only, so a private-spec repo can
+// run them from a sparse checkout without an install
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
@@ -25,8 +22,7 @@ const DEFAULT_CATALOG_PATH = resolve(
'ai-models.json',
);
-// A flag whose value is missing would otherwise swallow the next flag and write
-// the catalog to a file named after it.
+// A missing value would otherwise swallow the next flag and write the catalog to a file named after it
const readArgument = (flag: string): string | undefined => {
const index = process.argv.indexOf(flag);
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-index.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-index.type.ts
index 2b256e62279..51d05016866 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-index.type.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-index.type.ts
@@ -1,5 +1,4 @@
import { type BenchmarkRecord } from './benchmark-record.type';
-// Keyed by normalized model name, so a single lookup resolves every alias a
-// source publishes for the same underlying model.
+// Keyed by normalized model name, so one lookup resolves every alias of a model
export type BenchmarkIndex = Map<string, BenchmarkRecord>;
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-overlay-entry.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-overlay-entry.type.ts
index d919958f272..68f929ed5ba 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-overlay-entry.type.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-overlay-entry.type.ts
@@ -2,15 +2,12 @@ import { type AiModelEffort } from 'twenty-shared/ai';
import { type AiModelBenchmark } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type';
-// A reading plus the alias set a joining consumer needs to find it under the
-// publisher's own spelling.
+// Aliases let a joining consumer find the reading under the publisher's own spelling
export type BenchmarkOverlayReading = AiModelBenchmark & {
aliases: string[];
};
-// The overlay is the cross-repo artifact: it carries what the catalog embeds
-// plus the aliases. Per-effort readings nest under the model's entry so a
-// consumer that reads only the top-level fields keeps working.
+// Per-effort readings nest under the model entry so top-level-only consumers keep working
export type BenchmarkOverlayEntry = BenchmarkOverlayReading & {
benchmarkByEffort?: Partial<Record<AiModelEffort, BenchmarkOverlayReading>>;
};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-record.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-record.type.ts
index ae405031bdf..7233cd46c2a 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-record.type.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-record.type.ts
@@ -6,8 +6,7 @@ export type BenchmarkRecord = {
costPerTask?: number;
// The effort the publisher's row was measured at, when its name says so.
effort?: AiModelEffort;
- // Set only on a record recovered from the committed overlay, so preserved
- // measurements keep the date they were actually taken.
+ // Set only when recovered from the committed overlay, so preserved measurements keep their real date
measuredAt?: string;
aliases: string[];
};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/catalog-spec.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/catalog-spec.type.ts
index 489833d9d5f..d0373122f00 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/types/catalog-spec.type.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/catalog-spec.type.ts
@@ -1,5 +1,4 @@
-// Deliberately not extensible: a field a route cannot restate is a field it
-// cannot drift on, which is the property this pipeline is for.
+// Deliberately not extensible: a field a route cannot restate is one it cannot drift on
export type CatalogSpecModelOverrides = {
label?: string;
isDeprecated?: boolean;
@@ -13,13 +12,11 @@ export type CatalogSpecModelOverrides = {
export type CatalogSpecModel = CatalogSpecModelOverrides & {
model: string;
- // `eu.anthropic.claude-opus-4-7` for a Bedrock deployment of
- // `claude-opus-4-7`.
+ // e.g. `eu.anthropic.claude-opus-4-7` for a Bedrock deployment of `claude-opus-4-7`
as?: string;
};
-// Every model the vendor publishes, so a route that serves a whole vendor
-// picks up new models with the daily sync instead of waiting for an edit here.
+// A route serving a whole vendor picks up new models with the daily sync
export type CatalogSpecModelSelector = {
vendor: string;
};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/assert-payload-is-usable.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/assert-payload-is-usable.util.ts
index 7225fa18d8f..7aba4e09e09 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/assert-payload-is-usable.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/assert-payload-is-usable.util.ts
@@ -1,7 +1,6 @@
import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
-// A 200 carrying an empty or reshaped payload would otherwise generate an
-// empty catalog, and the sync PR automerges over the real one.
+// A 200 with an empty or reshaped payload would produce an empty catalog, and the sync PR automerges
export const assertPayloadIsUsable = ({
data,
vendors,
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-catalog.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-catalog.util.ts
index 80da59ff9ea..2dfe78fb7bd 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-catalog.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-catalog.util.ts
@@ -122,8 +122,7 @@ const buildModel = ({
return model;
};
-// Which vendors we carry is a deployment decision, so it is read from the
-// spec that states it rather than inferred from how the SDK names a package.
+// Carried vendors are a deployment decision, read from the spec rather than inferred from SDK package names
export const buildCatalog = ({
data,
vendors,
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-coverage-report.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-coverage-report.util.ts
index e6874e4fd90..8c8f8cc045a 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-coverage-report.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-coverage-report.util.ts
@@ -3,10 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type CoverageReport } from '../types/coverage-report.type';
import { type GeneratedCatalog } from '../types/generated-catalog.type';
-// Models whose job is not general reasoning (speech, image, embeddings,
-// computer use, deep research). A capability index for them would be
-// meaningless, so they are excluded from the coverage denominator rather than
-// counted as gaps.
+// Non-reasoning models (speech, image, embeddings...) have no meaningful capability index, so they are not counted as gaps
const SPECIALIZED_MODEL_PATTERN =
/realtime|voxtral|tts|audio|-live|computer-use|deep-research|-image|pixtral|codestral|embed/;
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-effort-lookup-key.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-effort-lookup-key.util.ts
index 7a81b08bf10..3342631286a 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-effort-lookup-key.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-effort-lookup-key.util.ts
@@ -1,9 +1,6 @@
import { type AiModelEffort } from 'twenty-shared/ai';
-// A per-effort row is filed beside the bare model key, so the ceiling lookup the
-// catalog has always done keeps working while a variant can ask for the figure
-// taken at its own effort. `@` survives name normalization, so the two key
-// spaces cannot collide.
+// `@` survives name normalization, so effort keys cannot collide with the bare model key the ceiling lookup uses
export const buildEffortLookupKey = (
normalizedModelName: string,
effort: AiModelEffort,
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-lookup-candidates.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-lookup-candidates.util.ts
index 1807c88aa66..5044131b97e 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-lookup-candidates.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-lookup-candidates.util.ts
@@ -8,10 +8,7 @@ const ROLLING_SUFFIX = /-(latest|preview|exp)$/;
const fingerprint = (model: ModelsDevModel): string =>
JSON.stringify([model.cost ?? {}, model.limit ?? {}]);
-// `mistral-large-latest` is never benchmarked under that name, so it is
-// resolved to the dated release it currently points at by matching price and
-// limits against its non-rolling siblings. Re-resolves on its own when the
-// provider repoints the alias.
+// Rolling aliases are never benchmarked by name, so resolve the dated release they point at by price and limits
const resolveRollingAlias = (
modelName: string,
siblingModels: Record<string, ModelsDevModel>,
@@ -31,9 +28,7 @@ const resolveRollingAlias = (
!ROLLING_SUFFIX.test(siblingName) &&
fingerprint(sibling) === target,
)
- // Falling back to the name keeps this deterministic when a provider dates
- // neither twin, and for the date-stamped ids providers actually use it
- // still lands on the newer one.
+ // Name fallback keeps this deterministic when a provider dates neither twin
.sort(
([nameA, a], [nameB, b]) =>
(b.release_date ?? '').localeCompare(a.release_date ?? '') ||
@@ -55,15 +50,10 @@ export const buildLookupCandidates = ({
const resolved = resolveRollingAlias(modelName, siblingModels);
if (isDefined(resolved)) {
- // Once the release an alias points at is known, only a row naming that
- // release will do. Every undated spelling is some other release the
- // publisher happens to have measured: `mistral-large` on the leaderboard is
- // the Feb '24 model, and standing in for `mistral-large-2512` it published a
- // two-year-old score as current.
+ // Only the resolved release, not the bare name: undated `mistral-large` is the Feb '24 model and once published a stale score as current
return [...new Set([...candidates, resolved])];
}
- // No dated release to point at, so the bare name is the only thing left and
- // whichever release the publisher measured is the best answer available.
+ // No dated release to point at, so whichever release the publisher measured is the best answer
return [...new Set([...candidates, modelName.replace(ROLLING_SUFFIX, '')])];
};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/carry-over-committed-fields.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/carry-over-committed-fields.util.ts
index 32b1a577ad2..03463f0b12c 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/carry-over-committed-fields.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/carry-over-committed-fields.util.ts
@@ -3,8 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type GeneratedCatalog } from '../types/generated-catalog.type';
import { type GeneratedModel } from '../types/generated-model.type';
-// models.dev knows neither which effort levels a model takes nor its routing
-// facts, so a rebuild would drop them without this.
+// models.dev knows neither effort levels nor routing facts, so a rebuild would drop them
const CARRIED_OVER_FIELDS = [
'efforts',
'dataResidency',
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/enrich-catalog.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/enrich-catalog.util.ts
index 05149da8aea..ed0e74609b7 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/enrich-catalog.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/enrich-catalog.util.ts
@@ -11,8 +11,7 @@ import { type EnrichCatalogArgs } from '../types/enrich-catalog-args.type';
import { matchBenchmarks } from './match-benchmarks.util';
-// The catalog embeds the figures only; the aliases stay in the overlay, which
-// is where a joining consumer looks for them.
+// Aliases stay in the overlay, where a joining consumer looks for them
const toCatalogReadings = (
readings: Partial<Record<AiModelEffort, BenchmarkOverlayReading>>,
): Partial<Record<AiModelEffort, AiModelBenchmark>> =>
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts
index 4af4bb433df..f2c44fe8e13 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts
@@ -22,8 +22,7 @@ type ArtificialAnalysisPage = {
pagination?: { has_more?: unknown };
};
-// This endpoint returns 0 for "not measured", and a zero tokens-per-second is a
-// lie rather than a datum.
+// The endpoint returns 0 for "not measured"
const readPositiveNumber = (value: unknown): number | undefined =>
typeof value === 'number' && Number.isFinite(value) && value > 0
? value
@@ -52,9 +51,7 @@ const readNested = ({
const readModels = (page: ArtificialAnalysisPage): ArtificialAnalysisModel[] =>
Array.isArray(page.data) ? (page.data as ArtificialAnalysisModel[]) : [];
-// How much a row actually says. The endpoint carries several rows per model and
-// some hosts publish no measurements at all, so an unmeasured row must never
-// displace a measured one under the same key.
+// Some hosts publish no measurements, so an unmeasured row must never displace a measured one under the same key
const informationScore = (record: BenchmarkRecord): number =>
[
record.intelligenceIndex,
@@ -62,12 +59,7 @@ const informationScore = (record: BenchmarkRecord): number =>
record.costPerTask,
].filter(isDefined).length;
-// The rows for one model are the same model at different reasoning efforts, and
-// the publisher spells the effort only inside a display name. Taking the
-// best-scoring row gives every model its ceiling, measured the same way, which
-// is the whole reason for standing on one publisher. Picking by how populated a
-// row happened to be scored Sonnet 4.6 at low effort against Sonnet 5 at max,
-// and the gap read as a capability difference.
+// Take the best-scoring row (the ceiling): picking by populated fields once compared Sonnet 4.6 at low effort to Sonnet 5 at max
const preferOver = (
candidate: BenchmarkRecord,
existing: BenchmarkRecord,
@@ -108,8 +100,7 @@ const fetchPage = async ({
return (await response.json()) as ArtificialAnalysisPage;
};
-// The list is paginated and the free tier allows ten requests a day, so every
-// page is read in one run rather than spread across runs.
+// The free tier allows ten requests a day, so every page is read in one run
const fetchAllModels = async ({
url,
apiKey,
@@ -161,9 +152,7 @@ export const fetchArtificialAnalysisBenchmarks = async (
const aliases = [model.slug, model.id, model.name].filter(isDefined);
- // Cost per task is the price of one task of the intelligence index run at
- // this row's effort, so it reflects reasoning volume where per-token
- // pricing cannot.
+ // Price of one intelligence-index task at this effort, which reflects reasoning volume unlike per-token pricing
const record: BenchmarkRecord = {
intelligenceIndex: readNested({
model,
@@ -199,8 +188,7 @@ export const fetchArtificialAnalysisBenchmarks = async (
continue;
}
- // The bare key keeps the ceiling; the effort key lets a pinned variant
- // read the figure taken at its own effort.
+ // The bare key keeps the ceiling; the effort key lets a pinned variant read its own effort's figure
file(key, record);
if (isDefined(record.effort)) {
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/match-benchmarks.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/match-benchmarks.util.ts
index 7dfde6b0fb5..5ec6ba20b19 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/match-benchmarks.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/match-benchmarks.util.ts
@@ -28,8 +28,7 @@ const lookup = (
return undefined;
};
-// The publisher lists plenty of models it has measured nothing about, and a row
-// of pure aliases says nothing worth carrying into either artifact.
+// A row of pure aliases says nothing worth carrying into either artifact
const hasMeasurement = (record: BenchmarkRecord): boolean =>
[
record.intelligenceIndex,
@@ -69,8 +68,7 @@ export const matchBenchmarks = ({
Record<AiModelEffort, BenchmarkOverlayReading>
> = {};
- // A declared effort without a row of its own stays blank: the ceiling was
- // measured at another effort and would overstate it.
+ // An effort without its own row stays blank: the ceiling was measured at another effort and would overstate it
for (const effort of efforts ?? []) {
const effortRecord = lookup(
benchmarkIndex,
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/merge-evaluation-models.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/merge-evaluation-models.util.ts
index a86a8015df2..e940883cb09 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/merge-evaluation-models.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/merge-evaluation-models.util.ts
@@ -1,13 +1,7 @@
import { type GeneratedCatalog } from '../types/generated-catalog.type';
-// models.dev describes language models only — it has no notion of an evaluation
-// model, and the sync filters on tool calling besides — so these are
-// hand-maintained and folded into the catalog here, before anything is written
-// or projected.
-//
-// Merged per model rather than per vendor: a vendor that ships both kinds keeps
-// the language models the sync just fetched, which is what lets an evaluation
-// model from an existing provider need nothing but an entry in the source file.
+// models.dev has no evaluation models, so they are hand-maintained and merged per model so a vendor keeps the
+// language models the sync fetched
export const mergeEvaluationModels = ({
catalog,
evaluationModels,
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/normalize-model-name.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/normalize-model-name.util.ts
index f2492879a95..87ef7c4e3bd 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/normalize-model-name.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/normalize-model-name.util.ts
@@ -1,8 +1,4 @@
-// Benchmark publishers, providers and the AI SDK all spell the same model
-// differently (`claude-sonnet-4-6`, `claude-sonnet-4.6`, `Claude Sonnet 4.6`),
-// so every lookup key goes through this before it is compared. The trailing
-// `-v1:0` strip lets a Bedrock deployment id join the same row as the model it
-// serves.
+// Publishers, providers and the AI SDK spell models differently; stripping `-v1:0` joins Bedrock ids to their model
export const normalizeModelName = (modelName: string): string =>
modelName
.toLowerCase()
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/parse-artificial-analysis-effort.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/parse-artificial-analysis-effort.util.ts
index 40761d3c9f1..b39ec0c3470 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/parse-artificial-analysis-effort.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/parse-artificial-analysis-effort.util.ts
@@ -4,10 +4,7 @@ import { isDefined } from 'twenty-shared/utils';
// A row run with reasoning switched off carries no effort word at all.
const NO_REASONING_MARKERS = new Set(['non-reasoning', 'nonreasoning']);
-// The publisher spells the configuration only inside the trailing parentheses
-// of a display name: `GPT-5.6 Sol (max)`, `Gemini 3.8 Flash (high)`,
-// `Claude Opus 5 (Adaptive Reasoning, Max Effort)`. Dates, fallbacks and a
-// bare "Reasoning" in the same place name no effort.
+// Effort only appears in trailing parentheses, e.g. `(max)`; dates, fallbacks and a bare "Reasoning" there name none
export const parseArtificialAnalysisEffort = (
displayName: string,
): AiModelEffort | undefined => {
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/project-catalog.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/project-catalog.util.ts
index 51011df4c4b..dd2a23edbeb 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/project-catalog.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/project-catalog.util.ts
@@ -1,6 +1,4 @@
-// twenty-shared by source path rather than by package name: the consuming
-// repository runs this from a sparse checkout with no workspace install, so
-// 'twenty-shared/ai' would not resolve there.
+// By source path: the consuming repo runs this from a sparse checkout where 'twenty-shared/ai' does not resolve
import { isAiSdkPackage } from '../../../../twenty-shared/src/ai/utils/is-ai-sdk-package.util';
import { isDataResidency } from '../../../../twenty-shared/src/ai/utils/is-data-residency.util';
@@ -11,8 +9,7 @@ import {
type CatalogSpecProvider,
} from '../types/catalog-spec.type';
-// Structural, so the catalog needs no schema here and this file can run from a
-// checkout that has not installed the monorepo.
+// Structural, so this file runs from a checkout that has not installed the monorepo
type CanonicalModel = { name: string; label?: string } & Record<
string,
unknown
@@ -100,8 +97,7 @@ const projectModel = ({
...routeFields,
...overrides,
name: specModel.as ?? canonicalModel.name,
- // The suffix marks the route, so it is appended to whichever name the model
- // ends up with rather than to the catalog's.
+ // The suffix marks the route, so it applies to whichever name the model ends up with
label: `${specModel.label ?? canonicalModel.label ?? canonicalModel.name}${provider.labelSuffix ?? ''}`,
};
};
@@ -113,8 +109,7 @@ const assertProviderIsUsable = ({
provider: CatalogSpecProvider;
seenNames: Set<string>;
}): void => {
- // Providers key an object, so a repeat would drop the first one's credentials
- // and models on the floor, and `__proto__` would drop its own.
+ // Providers key an object, so a repeat would drop the first one's credentials and models, and `__proto__` its own
if (seenNames.has(provider.name) || provider.name === '__proto__') {
throw new Error(`Provider "${provider.name}" is repeated or reserved`);
}
@@ -153,9 +148,7 @@ const assertNumbersAreUsable = ({
}
};
-// A spec naming a model the catalog does not carry is the failure this whole
-// pipeline exists to prevent: it publishes a route to nothing, and the tier
-// chains then fall through to a neighbouring rung in silence.
+// A route to a model the catalog lacks would make tier chains silently fall through to a neighbouring rung
const resolveModels = ({
provider,
canonicalCatalog,
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/read-committed-benchmarks.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/read-committed-benchmarks.util.ts
index 19816f33c33..7e0b4f78390 100644
--- a/packages/twenty-server/scripts/ai-catalog-sync/utils/read-committed-benchmarks.util.ts
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/read-committed-benchmarks.util.ts
@@ -61,9 +61,7 @@ const file = ({
}
};
-// The last published measurements, read back so a failed fetch degrades to
-// stale data rather than deleting the catalog's benchmarks. Each record keeps
-// its own measuredAt, so a stale entry stays visibly stale.
+// Read back so a failed fetch degrades to stale data; each record keeps its own measuredAt
export const readCommittedBenchmarks = (filePath: string): BenchmarkIndex => {
if (!fs.existsSync(filePath)) {
return new Map();
diff --git a/packages/twenty-server/src/app.module.ts b/packages/twenty-server/src/app.module.ts
index f4d340e919b..943d9256c53 100644
--- a/packages/twenty-server/src/app.module.ts
+++ b/packages/twenty-server/src/app.module.ts
@@ -100,8 +100,7 @@ export class AppModule {
// Before any middleware that authenticates from the session cookie.
consumer
.apply(CookieSessionCsrfMiddleware)
- // A cross-origin form post from the identity provider, authenticated on the
- // assertion rather than the cookie.
+ // A cross-origin form post from the identity provider, authenticated on the assertion, not the cookie
.exclude({
path: `${ApiPath.Auth}/saml/callback/:identityProviderId`,
method: RequestMethod.POST,
diff --git a/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-state.service.ts b/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-state.service.ts
index 2f29e141a7c..9f0641b87de 100644
--- a/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-state.service.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-state.service.ts
@@ -10,8 +10,7 @@ import { AGENT_HISTORY_MIGRATION_STORAGE_KEY } from 'src/database/commands/agent
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
-// This frozen protocol intentionally remains compatible with deployed 2.42 servers.
-// Runtime changes must not redefine the persisted migration cursor.
+// Frozen to stay compatible with deployed 2.42 servers: never redefine the persisted migration cursor
@Injectable()
export class AgentHistoryMigrationStateService {
async readState(
diff --git a/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-validation.service.ts b/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-validation.service.ts
index b1ffe080ed7..4d8853fa787 100644
--- a/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-validation.service.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/agent-history-migration-validation.service.ts
@@ -14,10 +14,8 @@ type Storage = AgentHistoryMigrationState['storage'];
@Injectable()
export class AgentHistoryMigrationValidationService {
- // agentChatThreadTarget rows point at the workspace-schema thread table. A
- // rollback leaves that store in place, but the next forward migration clears
- // it, cascading the links away with no way to rebuild them from core. Refuse
- // instead of losing them silently.
+ // A rollback keeps the workspace thread store, but the next forward migration clears it and cascades these links away
+ // with no way to rebuild them from core, so refuse instead
async assertNoThreadTargets({
runner,
workspaceId,
@@ -36,10 +34,7 @@ export class AgentHistoryMigrationValidationService {
return;
}
- // A custom object leg is set to null when its record is destroyed, as on
- // noteTarget, so such a row links nothing and there is no record left to
- // detach it from. Every leg's column is target<Object>Id, whatever the
- // object, which finds the legs without reading the metadata.
+ // A destroyed custom record nulls its leg, so only non-null legs count; every leg column is target<Object>Id, found without metadata
const rows: { id: string }[] = await runner.query(
`SELECT target.id FROM ${table} target
WHERE target."deletedAt" IS NULL
diff --git a/packages/twenty-server/src/database/commands/agent-history/agent-history-schema.service.ts b/packages/twenty-server/src/database/commands/agent-history/agent-history-schema.service.ts
index e668e0ee1fa..6f962e8f991 100644
--- a/packages/twenty-server/src/database/commands/agent-history/agent-history-schema.service.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/agent-history-schema.service.ts
@@ -16,8 +16,7 @@ export class AgentHistorySchemaService {
) {}
async prepare(workspaceId: string, dryRun: boolean): Promise<void> {
- // The migration builder mutates its optimistic maps, even on dry runs.
- // Keep those changes out of the live metadata cache until DDL succeeds.
+ // The migration builder mutates its optimistic maps even on dry runs, so keep them out of the cache until DDL succeeds
const existing = structuredClone(
await this.workspaceCacheService.getOrRecompute(workspaceId, [
'flatObjectMetadataMaps',
@@ -45,8 +44,7 @@ export class AgentHistorySchemaService {
if (objects.length + fields.length + indexes.length === 0) {
return;
}
- // Standard definitions use the same from/to path as standard application
- // synchronization; custom-object side effects must not expand this schema.
+ // Same from/to path as standard application sync; custom-object side effects must not expand this schema
const result =
await this.migrations.validateBuildAndRunWorkspaceMigrationFromTo({
workspaceId,
diff --git a/packages/twenty-server/src/database/commands/agent-history/agent-history-upgrade-storage.service.ts b/packages/twenty-server/src/database/commands/agent-history/agent-history-upgrade-storage.service.ts
index 334052ea2ad..24ff8e496fe 100644
--- a/packages/twenty-server/src/database/commands/agent-history/agent-history-upgrade-storage.service.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/agent-history-upgrade-storage.service.ts
@@ -53,9 +53,7 @@ export class AgentHistoryUpgradeStorageService extends AgentHistoryMigrationStat
'AI history is being migrated. Please retry shortly.',
);
}
- // History still in core belongs to a workspace whose 2.42 upgrade has
- // not finished. Serving the empty workspace tables would hide it, and
- // writing to them would be wiped when the copy resumes.
+ // History still in core means an unfinished 2.42 upgrade; workspace tables would hide it and writes would be wiped
if (state.storage !== 'workspace') {
throw new ServiceUnavailableException(
'AI history is unavailable until this workspace finishes upgrading.',
@@ -90,8 +88,7 @@ export class AgentHistoryUpgradeStorageService extends AgentHistoryMigrationStat
const runner = this.dataSource.createQueryRunner('master');
try {
await runner.connect();
- // One MVCC snapshot sees both the route and its data before or after a
- // cutover. Reports need no per-workspace locks or second pool.
+ // One MVCC snapshot sees the route and its data on one side of a cutover, with no per-workspace locks
await runner.startTransaction('REPEATABLE READ');
await runner.query('SET TRANSACTION READ ONLY');
const states = await this.readStates(runner, workspaceIds);
diff --git a/packages/twenty-server/src/database/commands/agent-history/utils/__tests__/get-agent-history-schema-additions.util.spec.ts b/packages/twenty-server/src/database/commands/agent-history/utils/__tests__/get-agent-history-schema-additions.util.spec.ts
index 1d9d9dc110e..5bc08c4c446 100644
--- a/packages/twenty-server/src/database/commands/agent-history/utils/__tests__/get-agent-history-schema-additions.util.spec.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/utils/__tests__/get-agent-history-schema-additions.util.spec.ts
@@ -165,8 +165,7 @@ describe('getAgentHistorySchemaAdditions', () => {
const targetIdentifier =
STANDARD_OBJECTS.agentChatThreadTarget.universalIdentifier;
- // The target is provisioned by its own command, later in the upgrade, so
- // anything emitted here would land on an object that does not exist yet.
+ // The target is provisioned later in the upgrade by its own command, so nothing here may reference it yet
expect(
additions.fields
.filter(
diff --git a/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.ts b/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.ts
index f634042275e..63e3be7cf84 100644
--- a/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.ts
@@ -32,8 +32,7 @@ export const getAgentHistorySchemaAdditions = ({
((current.readability === MetadataReadability.SYSTEM &&
current.writability === MetadataWritability.SYSTEM) ||
(identifier === STANDARD_OBJECTS.agentChatThread.universalIdentifier &&
- // INHERITED once threads can belong to a workflow run; a thread
- // without one still reads only through its own grants.
+ // INHERITED once threads can belong to a workflow run; a thread without one reads through its own grants
(current.readability === MetadataReadability.PRIVATE ||
current.readability === MetadataReadability.INHERITED) &&
current.writability === MetadataWritability.OPEN));
@@ -62,17 +61,14 @@ export const getAgentHistorySchemaAdditions = ({
],
),
);
- // Preparation can run before history is copied and ownership is backfilled.
- // Keep newly provisioned legacy objects protected until the sharing upgrade.
+ // Preparation can run before history is copied and ownership backfilled, so stay protected until the sharing upgrade
const protectedObjects: typeof objects = objects.map((object) => ({
...object,
readability: MetadataReadability.SYSTEM,
writability: MetadataWritability.SYSTEM,
}));
- // Objects standard metadata adds after this migration (e.g.
- // agentChatThreadTarget) are created, with both legs of their relation to
- // history, by their own command; a leg emitted here before that object
- // exists would have no other side and fail validation.
+ // Objects added later (e.g. agentChatThreadTarget) get both relation legs from their own command; a leg emitted
+ // here before that object exists would have no other side and fail validation
const existsOnceProvisioned = (objectUniversalIdentifier: string) =>
objectIdentifiers.has(objectUniversalIdentifier) ||
isDefined(
@@ -80,9 +76,7 @@ export const getAgentHistorySchemaAdditions = ({
objectUniversalIdentifier
],
);
- // Relations from other standard objects into history objects (e.g. the
- // attachment morph target) must be provisioned with the history objects,
- // otherwise only the history-side half of the relation gets created.
+ // Relations into history objects (e.g. the attachment morph target) must be provisioned with them, or only one half exists
const historyFields = Object.values(
standard.flatFieldMetadataMaps.byUniversalIdentifier,
)
@@ -127,8 +121,7 @@ export const getAgentHistorySchemaAdditions = ({
],
),
);
- // Inverse fields on other objects keep their standard definition so every
- // provisioning path creates them identically.
+ // Inverse fields keep their standard definition so every provisioning path creates them identically
const protectedFields: typeof fields = fields.map((field) =>
objectIdentifiers.has(field.objectMetadataUniversalIdentifier)
? { ...field, writability: MetadataWritability.SYSTEM }
diff --git a/packages/twenty-server/src/database/commands/list-and-delete-orphaned-workspace-entities.command.ts b/packages/twenty-server/src/database/commands/list-and-delete-orphaned-workspace-entities.command.ts
index c7e3fa6a439..a5f1ee3e91d 100644
--- a/packages/twenty-server/src/database/commands/list-and-delete-orphaned-workspace-entities.command.ts
+++ b/packages/twenty-server/src/database/commands/list-and-delete-orphaned-workspace-entities.command.ts
@@ -56,10 +56,8 @@ type DeletionResult = {
error?: string;
};
-// All entities that extend WorkspaceRelatedEntity or SyncableEntity
-// Ordered by dependency: CHILDREN FIRST to minimize CASCADE overhead
+// Children first to minimize CASCADE overhead
const WORKSPACE_RELATED_ENTITIES: EntityTarget<ObjectLiteral>[] = [
- // Level 4: Deepest children - delete these first to avoid CASCADE overhead
ViewFieldEntity,
ViewFilterEntity,
ViewGroupEntity,
@@ -73,20 +71,17 @@ const WORKSPACE_RELATED_ENTITIES: EntityTarget<ObjectLiteral>[] = [
RowLevelPermissionPredicateEntity,
PageLayoutWidgetEntity,
- // Level 3: Mid-level children
RowLevelPermissionPredicateGroupEntity,
ViewEntity,
IndexMetadataEntity,
PageLayoutTabEntity,
- // Level 2: Children that depend on core entities
FieldMetadataEntity,
PageLayoutEntity,
PermissionFlagEntity,
SkillEntity,
LogicFunctionEntity,
- // Level 1: Core entities with CASCADE deletes - delete after their children
ObjectMetadataEntity,
RoleEntity,
AgentEntity,
@@ -94,7 +89,6 @@ const WORKSPACE_RELATED_ENTITIES: EntityTarget<ObjectLiteral>[] = [
ApiKeyEntity,
LogicFunctionLayerEntity,
- // Level 0: Independent entities (no foreign keys to other workspace entities)
ApplicationEntity,
ApprovedAccessDomainEntity,
BillingCustomerEntity,
diff --git a/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts b/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts
index 29c28cc218d..008ff9b85ef 100644
--- a/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts
+++ b/packages/twenty-server/src/engine/api/common/common-nested-relations-processor/process-nested-relations.helper.ts
@@ -207,8 +207,7 @@ export class ProcessNestedRelationsHelper {
const targetObjectNameSingular = targetObjectMetadata.nameSingular;
- // A joined relation to such records reads as empty, so a nested one does
- // too rather than failing the parent's read
+ // A joined relation to such records reads as empty, so a nested one does too instead of failing the parent
if (targetObjectRepository.isReadDeniedByReadability()) {
this.assignRelationResults({
parentRecords: parentObjectRecords,
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
index 57fbdb62c95..b20c90c6b0b 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-base-query-runner.service.ts
@@ -392,9 +392,7 @@ export abstract class CommonBaseQueryRunnerService<
};
}
- // useReplica follows isReadOnly so reads on read-only runners hit the replica
- // and everything else the primary, keeping root read and nested-relation
- // loading consistent.
+ // The repository already uses the replica only on read-only runners, so root reads and nested-relation loading agree
protected getReadRepository({
repository,
}: Pick<
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts
index b655273d78c..d98001c2937 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-create-many-query-runner/common-create-many-query-runner.service.ts
@@ -79,8 +79,7 @@ export class CommonCreateManyQueryRunnerService extends CommonBaseQueryRunnerSer
const isGatedThroughRecordShares =
this.isGatedThroughRecordShares(queryRunnerContext);
- // An inherited record is reachable through its parent, so shareWith stays
- // optional there and is checked only when given
+ // An inherited record is reachable through its parent, so shareWith is optional there
if (isPrivateObject || isNonEmptyArray(args.shareWith)) {
await this.shareWithService.validateShareWithOrThrow({
authContext: queryRunnerContext.authContext,
diff --git a/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts b/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts
index 9afed1425b9..6a7ed65bcab 100644
--- a/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts
+++ b/packages/twenty-server/src/engine/api/common/common-query-runners/common-find-many-query-runner.service.ts
@@ -91,9 +91,7 @@ export class CommonFindManyQueryRunnerService extends CommonBaseQueryRunnerServi
appliedFilters,
);
- // Normalizing to deduplicated leaves makes the appended id tie-breaker
- // yield to a caller-provided id ordering, and guarantees the SQL scan
- // order and the keyset conditions derive from the same list
+ // Deduplicated leaves let a caller id ordering override the tie-breaker and keep scan order and keyset conditions in sync
const orderByLeaves = resolveOrderByLeaves({
orderBy: [
...(args.orderBy ?? []),
@@ -160,8 +158,7 @@ export class CommonFindManyQueryRunnerService extends CommonBaseQueryRunnerServi
flatObjectMetadataMaps,
flatFieldMetadataMaps,
}),
- // Order columns must be hydrated onto the records even when not requested:
- // cursor encoding reads the sort values from them (issue #24333)
+ // Selected even when unrequested: cursor encoding reads the sort values off the records (issue #24333)
...buildOrderByColumnsToSelect({
orderBy: args.orderBy,
flatObjectMetadata,
@@ -171,9 +168,7 @@ export class CommonFindManyQueryRunnerService extends CommonBaseQueryRunnerServi
queryBuilder.setFindOptions({ select: columnsToSelect });
- // A join that can duplicate root rows makes a row-level LIMIT return fewer records than
- // asked, so it is rejected rather than paginated with take/skip, which drops the LIMIT
- // from the scan.
+ // A row-duplicating join makes LIMIT return too few records, and take/skip would drop LIMIT from the scan
const nonToOneJoinAliases = getNonToOneJoinAliases(queryBuilder);
if (nonToOneJoinAliases.length > 0) {
@@ -191,8 +186,7 @@ export class CommonFindManyQueryRunnerService extends CommonBaseQueryRunnerServi
}
queryBuilder.limit(limit + 1);
- // Add order columns AFTER setFindOptions (setFindOptions clears addSelect)
- // Pass columnsToSelect so we only add columns that aren't already selected
+ // setFindOptions clears addSelect, so this must come after it
commonQueryParser.addRelationOrderColumnsToBuilder(
queryBuilder,
parsedOrderBy,
@@ -200,9 +194,7 @@ export class CommonFindManyQueryRunnerService extends CommonBaseQueryRunnerServi
columnsToSelect,
);
- // Raw rows travel along the entities: the ordered join columns already
- // selected for the relation ordering are read out of them, so cursors get
- // their relation values whatever the client selected (or the REST depth)
+ // Raw rows carry the ordered join columns, so cursors get relation values whatever the client selected
const { entities: fetchedObjectRecords, raw: fetchedRawRows } =
(await queryBuilder.getRawAndEntities()) as {
entities: ObjectRecord[];
@@ -218,8 +210,7 @@ export class CommonFindManyQueryRunnerService extends CommonBaseQueryRunnerServi
fetchedItems: fetchedObjectRecords,
limit,
direction: isForwardPagination ? 'forward' : 'backward',
- // getCursor applies cursors on truthiness, so an empty-string cursor
- // must not advertise navigation from a cursor.
+ // getCursor applies cursors on truthiness, so an empty-string cursor must not advertise navigation
hasAfterCursor: Boolean(args.after),
hasBeforeCursor: Boolean(args.before),
});
diff --git a/packages/twenty-server/src/engine/api/common/types/common-find-many-output.type.ts b/packages/twenty-server/src/engine/api/common/types/common-find-many-output.type.ts
index 71a76b68891..9e6de8f1dbe 100644
--- a/packages/twenty-server/src/engine/api/common/types/common-find-many-output.type.ts
+++ b/packages/twenty-server/src/engine/api/common/types/common-find-many-output.type.ts
@@ -9,8 +9,7 @@ export type CommonFindManyOutput = {
aggregatedValues: Record<string, number> | undefined;
totalCount: number | undefined;
pageInfo: CommonPageInfo;
- // Cursor values read from the scan's raw rows, so edge cursors carry the
- // exact SQL sort values whatever the selection presents
+ // Read from raw rows, so cursors carry the exact SQL sort values whatever the selection presents
orderByValuesByRecordId: OrderByValuesByRecordId;
selectedFieldsResult: CommonSelectedFieldsResult;
};
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-filter/graphql-query-filter-field.parser.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-filter/graphql-query-filter-field.parser.ts
index d350c567240..818cc0dd0fa 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-filter/graphql-query-filter-field.parser.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-filter/graphql-query-filter-field.parser.ts
@@ -209,12 +209,9 @@ export class GraphqlQueryFilterFieldParser {
this.depth + 1,
);
- // A join on a to-many relation would duplicate root rows, which the
- // find-many runner rejects, so the related rows are matched through a
- // correlated EXISTS instead.
+ // A to-many join would duplicate root rows, which the find-many runner rejects, so match through a correlated EXISTS
if (isToManyRelation) {
- // The EXISTS is correlated with the root alias, so a to-many filter
- // reached through a joined to-one relation would match the wrong rows.
+ // The EXISTS is correlated with the root alias, so through a joined to-one it would match the wrong rows
if (parentAlias !== outerQueryBuilder.alias) {
throw new GraphqlQueryRunnerException(
`To-many relation filter on "${fieldMetadata.name}" must apply to the root object`,
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/graphql-query-order.parser.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/graphql-query-order.parser.ts
index a8950338fbb..2f3d92f9f13 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/graphql-query-order.parser.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/graphql-query-order.parser.ts
@@ -22,10 +22,7 @@ import { type RelationJoinInfo } from './types/relation-join-info.type';
// Re-export types for backward compatibility
export { OrderByClause, ParseOrderByResult, RelationJoinInfo };
-// Compiles SQL ORDER BY clauses from the resolved orderBy leaves: walking,
-// validation and permission checks live in resolveOrderByLeaves, shared with
-// column selection and the cursor utilities, so the scan order can never
-// diverge from what cursors continue.
+// Leaves come from resolveOrderByLeaves, shared with cursors, so the scan order cannot diverge from cursor continuation
export class GraphqlQueryOrderFieldParser {
private flatObjectMetadata: FlatObjectMetadata;
private flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/__tests__/convert-order-by-to-find-options-order.spec.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/__tests__/convert-order-by-to-find-options-order.spec.ts
index 7778d18c1ca..5d518d9cf54 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/__tests__/convert-order-by-to-find-options-order.spec.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/__tests__/convert-order-by-to-find-options-order.spec.ts
@@ -18,8 +18,7 @@ describe('convertOrderByToFindOptionsOrder', () => {
},
);
- // The backward scan is the exact reverse of the requested order, so the NULLS
- // placement reverses along with the direction
+ // The backward scan exactly reverses the requested order, NULLS placement included
it.each([
[OrderByDirection.AscNullsFirst, 'DESC', 'NULLS LAST'],
[OrderByDirection.AscNullsLast, 'DESC', 'NULLS FIRST'],
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/convert-order-by-to-find-options-order.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/convert-order-by-to-find-options-order.ts
index 4ba985757eb..67c33e0e63a 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/convert-order-by-to-find-options-order.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/utils/convert-order-by-to-find-options-order.ts
@@ -9,8 +9,7 @@ import { isOrderByDirection } from 'src/engine/api/graphql/graphql-query-runner/
import { type OrderByClause } from 'src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query-order/graphql-query-order.parser';
import { getEffectiveScanOrder } from 'src/engine/api/utils/get-effective-scan-order.utils';
-// Derives ORDER BY from the same scan-order primitive the keyset cursor
-// conditions use, so the SQL scan and the WHERE continuation cannot disagree
+// Same scan-order primitive as the keyset cursor conditions, so ORDER BY and the WHERE continuation cannot disagree
export const convertOrderByToFindOptionsOrder = (
direction: OrderByDirection,
isForwardPagination = true,
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query.parser.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query.parser.ts
index 9ba2e60f04b..013188b6020 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query.parser.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/graphql-query.parser.ts
@@ -101,10 +101,7 @@ export class GraphqlQueryParser {
return true;
}
- // Only recurse into boolean-operator wrappers (and / or / not) — those
- // are transparent w.r.t. which entity owns a deletedAt. Composite
- // sub-field and relation-traversal nesting refers to a different
- // entity's deletedAt, which must not widen the root query.
+ // Only and/or/not are transparent: nested composite or relation deletedAt belongs to another entity and must not widen the root query
if (
(key === 'and' || key === 'or' || key === 'not') &&
typeof value === 'object' &&
@@ -142,7 +139,6 @@ export class GraphqlQueryParser {
queryBuilder.orderBy(parseResult.orderBy);
- // Return parsed orderBy so caller can add relation columns after setFindOptions
return parseResult.orderBy;
}
@@ -153,16 +149,14 @@ export class GraphqlQueryParser {
objectNameSingular: string,
columnsToSelect: Record<string, boolean>,
): void {
- // Add ORDER BY columns with underscore alias for DISTINCT compatibility
- // This must be called AFTER setFindOptions because setFindOptions clears addSelect
+ // Must run after setFindOptions, which clears addSelect; the underscore alias keeps DISTINCT working
for (const orderByKey of Object.keys(parsedOrderBy)) {
const parts = orderByKey.split('.');
if (parts.length === 2) {
const [alias, column] = parts;
- // For relation columns: always add (they're never in columnsToSelect)
- // For main entity columns: only add if NOT already in columnsToSelect
+ // Relation columns are never in columnsToSelect
const isMainEntity = alias === objectNameSingular;
const isAlreadySelected = isMainEntity && columnsToSelect[column];
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/utils/assert-field-is-readable-or-throw.util.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/utils/assert-field-is-readable-or-throw.util.ts
index 565812a674b..cceab9875c3 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/utils/assert-field-is-readable-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/graphql-query-parsers/utils/assert-field-is-readable-or-throw.util.ts
@@ -6,8 +6,7 @@ import {
PermissionsExceptionMessage,
} from 'src/engine/metadata-modules/permissions/permissions.exception';
-// Filtering or ordering by a non-readable field would leak its values (orderBy
-// additionally embeds them into pagination cursors)
+// Filtering or ordering by a non-readable field would leak its values (orderBy embeds them into cursors)
export const assertFieldIsReadableOrThrow = ({
objectsPermissions,
objectMetadataId,
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/build-order-by-columns-to-select.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/build-order-by-columns-to-select.ts
index b723d9ee88d..3a2879136e1 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/build-order-by-columns-to-select.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/build-order-by-columns-to-select.ts
@@ -11,10 +11,7 @@ import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/typ
import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
-// Cursor encoding reads orderBy values from the hydrated record, so every column the
-// query is ordered by must be selected even when the client did not request it.
-// Otherwise the cursor silently degrades to an id-only cursor and pagination skips
-// records (see issue #24333).
+// Cursors read orderBy values from the record: an unselected one degrades to an id-only cursor that skips records (#24333)
export const buildOrderByColumnsToSelect = ({
orderBy,
flatObjectMetadata,
@@ -31,8 +28,7 @@ export const buildOrderByColumnsToSelect = ({
flatObjectMetadata,
flatFieldMetadataMaps,
}).filter(checkIfLeafCanCarryCursorValue)) {
- // Relation orderBy values live on a joined alias, not on a root column:
- // cursors read them from the ordering join's raw rows instead
+ // Cursors read relation values from the ordering join's raw rows, not a root column
if (leaf.kind === 'relation') {
continue;
}
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/compute-where-condition-parts.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/compute-where-condition-parts.ts
index 57e08aaff05..a4e3bcb792a 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/compute-where-condition-parts.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/compute-where-condition-parts.ts
@@ -130,10 +130,8 @@ export const computeWhereConditionParts = ({
? { [`${key}${secondParamSuffix}`]: nullEquivalentFieldValue }
: {},
};
- // Exact variants used by keyset pagination conditions: cursor continuation
- // must mirror the SQL scan order, where only actual SQL NULLs sort into the
- // NULL block, so the empty-value widening of 'is' and 'eq' would skip or
- // duplicate rows around the block boundaries
+ // Keyset cursors must mirror SQL scan order, where only real NULLs sort into the NULL block, so the
+ // empty-value widening of 'is' and 'eq' would skip or duplicate rows at the block boundaries
case 'isStrictly':
return {
sql: `${fieldReference} IS ${value === 'NULL' ? 'NULL' : 'NOT NULL'}`,
diff --git a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/cursors.util.ts b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/cursors.util.ts
index 2ed6649c0e6..d88a53a8712 100644
--- a/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/cursors.util.ts
+++ b/packages/twenty-server/src/engine/api/graphql/graphql-query-runner/utils/cursors.util.ts
@@ -47,10 +47,7 @@ export const encodeCursor = <T extends ObjectRecord = ObjectRecord>({
flatObjectMetadata: FlatObjectMetadata;
flatObjectMetadataMaps?: FlatEntityMaps<FlatObjectMetadata>;
flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
- // Sort values read from the scan's raw rows by the find-many runner: they
- // carry the exact SQL values (NULLs included) the continuation must mirror.
- // Falling back to the formatted record covers callers without them (e.g.
- // nested connections), whose cursors do not continue a root scan.
+ // Exact SQL values (NULLs included) the continuation must mirror; absent for nested connections
orderByValuesFromScan?: Record<string, unknown>;
}): string => {
// oxlint-disable-next-line typescript/no-explicit-any
@@ -62,9 +59,6 @@ export const encodeCursor = <T extends ObjectRecord = ObjectRecord>({
flatObjectMetadataMaps,
flatFieldMetadataMaps,
}).filter(checkIfLeafCanCarryCursorValue)) {
- // Read the ordered value along the leaf's path: a null container yields
- // null (the row belongs to the NULL block of the ordering), a missing one
- // yields undefined, which JSON serialization drops
const [rootKey, ...nestedKeys] = leaf.path;
const valueSource = orderByValuesFromScan ?? objectRecord;
let leafValue: unknown = valueSource[rootKey];
@@ -76,8 +70,6 @@ export const encodeCursor = <T extends ObjectRecord = ObjectRecord>({
leafValue = isPlainObject(leafValue) ? leafValue[key] : undefined;
}
- // An unloaded relation cannot contribute a value at all: leave the key out
- // instead of writing an empty object
if (leaf.kind === 'relation' && leafValue === undefined) {
continue;
}
diff --git a/packages/twenty-server/src/engine/api/mcp/constants/mcp-execute-tool-annotations.const.ts b/packages/twenty-server/src/engine/api/mcp/constants/mcp-execute-tool-annotations.const.ts
index bab471293a6..26427fadbc5 100644
--- a/packages/twenty-server/src/engine/api/mcp/constants/mcp-execute-tool-annotations.const.ts
+++ b/packages/twenty-server/src/engine/api/mcp/constants/mcp-execute-tool-annotations.const.ts
@@ -1,8 +1,6 @@
import { type McpToolAnnotations } from 'src/engine/api/mcp/types/mcp-tool-annotations.type';
-// execute_tool dispatches every write, deletes included, but flagging it
-// destructive makes clients gate each call behind a confirmation prompt. What
-// the caller may write is enforced by their role, not by this hint.
+// Not flagged destructive: clients would prompt on every call, and writes are gated by role anyway
export const MCP_EXECUTE_TOOL_ANNOTATIONS: McpToolAnnotations = {
readOnlyHint: false,
openWorldHint: true,
diff --git a/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts b/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts
index a53b4fa24c0..5fa01a1a434 100644
--- a/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts
+++ b/packages/twenty-server/src/engine/api/mcp/services/mcp-tool-executor.service.ts
@@ -83,9 +83,7 @@ export class McpToolExecutorService {
const executionStartedAt = performance.now();
try {
- // ToolSet widens execute to a union no argument satisfies. The client's
- // arguments arrive as raw JSON-RPC input and the output shape is checked by
- // isToolOutputSuccessful, so both sides stay unknown here.
+ // ToolSet widens execute to a union no argument satisfies
const execute = tool.execute as ToolExecuteFunction<
unknown,
unknown,
@@ -166,8 +164,7 @@ export class McpToolExecutorService {
.filter(([, def]) => !!def.inputSchema)
.map(([name, def]) => {
const toolDefinition = def as McpToolDefinition;
- // Unwrap the AI SDK's jsonSchema wrapper if present
- // The AI SDK serializes schemas as { jsonSchema: {...} } but MCP expects {...} directly
+ // The AI SDK wraps schemas as { jsonSchema } but MCP expects the bare schema
const inputSchema = unwrapJsonSchema(toolDefinition.inputSchema);
return {
diff --git a/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts b/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
index a2d7f0e3d78..c9b0ecc6885 100644
--- a/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
+++ b/packages/twenty-server/src/engine/api/rest/core/controllers/rest-api-core.controller.ts
@@ -161,9 +161,7 @@ export class RestApiCoreController {
res.status(200).send(result);
}
- // This endpoint is not documented in the OpenAPI schema.
- // We keep it to avoid a breaking change since it initially used PUT instead
- // of PATCH, and because the PUT verb is often used as a PATCH.
+ // Undocumented legacy alias of PATCH, kept to avoid a breaking change
@Put('*path')
async handleApiPut(
@Req() request: AuthenticatedRequest,
diff --git a/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/__tests__/parse-core-path.utils.spec.ts b/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/__tests__/parse-core-path.utils.spec.ts
index 8c1f55d9b12..aa87a15ea99 100644
--- a/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/__tests__/parse-core-path.utils.spec.ts
+++ b/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/__tests__/parse-core-path.utils.spec.ts
@@ -117,8 +117,6 @@ describe('parseCorePath', () => {
);
});
- // Every method has a wildcard route on this controller, so without the
- // method check DELETE would read the id as a destroy target.
it.each(['DELETE', 'GET', 'POST', 'PUT'])(
'should throw for a restore-shaped path on %s',
(method) => {
diff --git a/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/parse-core-path.utils.ts b/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/parse-core-path.utils.ts
index d207f93daa7..f502b1eb8bd 100644
--- a/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/parse-core-path.utils.ts
+++ b/packages/twenty-server/src/engine/api/rest/input-request-parsers/path-parser-utils/parse-core-path.utils.ts
@@ -12,11 +12,7 @@ export const parseCorePath = (
.split('/')
.filter(Boolean);
- // Restore is the only action on a single record, so /{object}/{id}/restore
- // is the one path with a third segment. It is mounted on PATCH alone;
- // allowing the segment on other methods would let a restore-shaped path
- // through their wildcard routes, where DELETE would read the id as a
- // destroy target.
+ // /{object}/{id}/restore is PATCH only: other methods' wildcard routes would read the id as a target (DELETE would destroy it)
const isRestoreRequest =
request.method === 'PATCH' &&
queryAction[queryAction.length - 1] === 'restore';
diff --git a/packages/twenty-server/src/engine/api/utils/__tests__/compute-cursor-arg-filter.utils.spec.ts b/packages/twenty-server/src/engine/api/utils/__tests__/compute-cursor-arg-filter.utils.spec.ts
index a293d53da7c..69e02573fa9 100644
--- a/packages/twenty-server/src/engine/api/utils/__tests__/compute-cursor-arg-filter.utils.spec.ts
+++ b/packages/twenty-server/src/engine/api/utils/__tests__/compute-cursor-arg-filter.utils.spec.ts
@@ -222,8 +222,7 @@ describe('computeCursorArgFilter', () => {
isForwardPagination: true,
});
- // TEXT columns hold SQL NULL for rows written empty or without the
- // field, so the trailing NULL block is part of the continuation
+ // Empty TEXT values are stored as SQL NULL, so the trailing NULL block continues the scan
expect(result).toEqual([
{ or: [{ name: { gt: 'John' } }, { name: { isStrictly: 'NULL' } }] },
]);
@@ -749,8 +748,6 @@ describe('computeCursorArgFilter', () => {
});
describe('relation orderBy on a composite target field', () => {
- // The web app sorts person-labeled relation columns exactly like this: one
- // entry per ordered FULL_NAME property of the target's label identifier
const relationCompositeOrderBy = [
{
company: { contactName: { firstName: OrderByDirection.AscNullsLast } },
@@ -774,9 +771,7 @@ describe('computeCursorArgFilter', () => {
isForwardPagination: true,
});
- // The joined column is NULL both for rows without a related record and
- // for related records holding an empty value: they all sort into the
- // NULL block, which the exact nested check matches
+ // Missing related records and empty values both sort into the joined column's NULL block
expect(result).toEqual([
{
or: [
diff --git a/packages/twenty-server/src/engine/api/utils/build-cursor-keyset-condition.utils.ts b/packages/twenty-server/src/engine/api/utils/build-cursor-keyset-condition.utils.ts
index 2aba34e88d2..4d97298a239 100644
--- a/packages/twenty-server/src/engine/api/utils/build-cursor-keyset-condition.utils.ts
+++ b/packages/twenty-server/src/engine/api/utils/build-cursor-keyset-condition.utils.ts
@@ -8,20 +8,13 @@ type BuildCursorKeysetConditionParams = {
isForwardPagination: boolean;
isEqualityCondition: boolean;
canFieldHoldNullValue: boolean;
- // Wraps a leaf filter (e.g. { gt: value }) into the field's filter path
buildLeafCondition: (
leafFilter: Record<string, unknown>,
) => Record<string, unknown>;
- // Overridable for fields whose NULL block is better matched through another
- // column (e.g. a relation's join column)
buildNullCheckCondition?: (isNull: boolean) => Record<string, unknown>;
};
-// The single home of the null-aware keyset algebra shared by scalar, composite
-// and relation orderBy keys. Returns null when no row can sort strictly after
-// the cursor on this key alone (cursor inside the trailing NULL block): the
-// caller must then drop the or-branch and rely on the tie-breaking keys.
-// Equality conditions always exist, which the overloads make visible to callers.
+// Null when the cursor sits in the trailing NULL block: callers drop the or-branch and rely on tie-breakers
export function buildCursorKeysetCondition(
params: BuildCursorKeysetConditionParams & { isEqualityCondition: true },
): Record<string, unknown>;
@@ -35,8 +28,7 @@ export function buildCursorKeysetCondition({
isEqualityCondition,
canFieldHoldNullValue,
buildLeafCondition,
- // The strict operators compare exactly: the empty-value widening of 'is'
- // and 'eq' does not mirror the SQL scan order the cursor continues
+ // Strict operators, not 'is' or 'eq': their empty-value widening does not mirror the SQL scan order
buildNullCheckCondition = (isNull) =>
buildLeafCondition({ isStrictly: isNull ? 'NULL' : 'NOT_NULL' }),
}: BuildCursorKeysetConditionParams): Record<string, unknown> | null {
@@ -52,8 +44,6 @@ export function buildCursorKeysetCondition({
);
if (cursorValue === null) {
- // Inside the leading NULL block only the tie-breaking keys can advance the
- // scan; inside the trailing one nothing sorts after on this key at all
return areNullsScannedLast ? null : buildNullCheckCondition(false);
}
diff --git a/packages/twenty-server/src/engine/api/utils/build-cursor-leaf-where-condition.utils.ts b/packages/twenty-server/src/engine/api/utils/build-cursor-leaf-where-condition.utils.ts
index e8111da0612..a50868eee52 100644
--- a/packages/twenty-server/src/engine/api/utils/build-cursor-leaf-where-condition.utils.ts
+++ b/packages/twenty-server/src/engine/api/utils/build-cursor-leaf-where-condition.utils.ts
@@ -1,11 +1,8 @@
import { buildCursorKeysetCondition } from 'src/engine/api/utils/build-cursor-keyset-condition.utils';
import { type OrderByLeaf } from 'src/engine/api/utils/resolve-order-by-leaves.utils';
-// SQL NULL can sit in any nullable column whatever its type: write-side
-// normalization stores empty TEXT-like values as NULL, and rows written
-// without the field hold NULL too, so they all sort into the NULL block.
-// Composite sub-columns and joined columns carry no own nullability metadata
-// and are treated as nullable; a needless IS NULL branch matches nothing.
+// Any nullable column can hold NULL whatever its type (empty text is stored as NULL).
+// Composite sub-columns and joined columns have no nullability metadata; a needless IS NULL branch matches nothing
const checkIfLeafCanHoldNullValue = (leaf: OrderByLeaf): boolean =>
leaf.kind === 'scalar' ? leaf.fieldMetadata.isNullable !== false : true;
@@ -16,9 +13,7 @@ type BuildCursorLeafWhereConditionParams = {
isEqualityCondition: boolean;
};
-// The leaf's path is also its filter nesting: { company: { name: { gt: v } } }
-// resolves against the same column the ordering uses (relation paths through
-// the LEFT JOIN of the ordering, composite paths through the flat sub-column).
+// The path's filter nesting resolves against the column the ordering uses (relations via its LEFT JOIN)
export function buildCursorLeafWhereCondition(
params: BuildCursorLeafWhereConditionParams & { isEqualityCondition: true },
): Record<string, unknown>;
diff --git a/packages/twenty-server/src/engine/api/utils/build-order-by-values-by-record-id.util.ts b/packages/twenty-server/src/engine/api/utils/build-order-by-values-by-record-id.util.ts
index 694b555ba5b..3e8e0b61574 100644
--- a/packages/twenty-server/src/engine/api/utils/build-order-by-values-by-record-id.util.ts
+++ b/packages/twenty-server/src/engine/api/utils/build-order-by-values-by-record-id.util.ts
@@ -9,11 +9,7 @@ import {
export type OrderByValuesByRecordId = Record<string, Record<string, unknown>>;
-// Cursors are encoded from the raw rows of the scan rather than from the
-// formatted records: result formatting presents SQL NULLs of TEXT-like columns
-// as empty values, but only actual SQL NULLs sort into the NULL block the
-// cursor must continue from. This also carries relation orderBy values without
-// requiring the ordered relation in the selection (or any REST depth).
+// Raw rows, not formatted records: formatting shows SQL NULLs as empty values, but only real NULLs sort into the NULL block
export const buildOrderByValuesByRecordId = ({
orderByLeaves,
records,
@@ -31,8 +27,7 @@ export const buildOrderByValuesByRecordId = ({
return {};
}
- // The runner rejects row-multiplying joins, so raw rows and entities match
- // one to one; the root id raw alias keys the pairing when available
+ // The runner rejects row-multiplying joins, so raw rows and records match one to one
const rootIdRawAlias = `${objectNameSingular}_id`;
const rawRowsByRecordId = new Map<string, Record<string, unknown>>();
@@ -64,9 +59,6 @@ export const buildOrderByValuesByRecordId = ({
continue;
}
- // Every ordered column is selected under this raw alias, by the find
- // options for root columns and by addRelationOrderColumnsToBuilder for
- // joined ones
const rawValue =
rawRow[`${leafColumn.tableAlias}_${leafColumn.columnName}`];
diff --git a/packages/twenty-server/src/engine/api/utils/compute-cursor-arg-filter.utils.ts b/packages/twenty-server/src/engine/api/utils/compute-cursor-arg-filter.utils.ts
index acc43941446..a24128bbf62 100644
--- a/packages/twenty-server/src/engine/api/utils/compute-cursor-arg-filter.utils.ts
+++ b/packages/twenty-server/src/engine/api/utils/compute-cursor-arg-filter.utils.ts
@@ -30,12 +30,7 @@ type ComputeCursorArgFilterParams = {
isForwardPagination: boolean;
};
-// Builds the cumulative keyset conditions continuing a scan from a cursor:
-// (k1 after v1) OR (k1 = v1 AND k2 after v2) OR ... over the ordered leaves.
-// A keyset cursor can only continue the scan if it carries a value for every
-// leaf of the requested ordering: a cursor generated under another orderBy (or
-// by a version that failed to capture a sort value) must fail loudly, because
-// continuing on the remaining leaves silently skips records (issue #24333).
+// A cursor missing a leaf value must fail loudly: continuing on the remaining leaves silently skips records (#24333)
export const computeCursorArgFilter = ({
cursor,
orderBy,
@@ -66,7 +61,6 @@ export const computeCursorArgFilter = ({
return { leaf, cursorValue };
});
- // Each equality condition is reused by every later branch: compute them once
const equalityConditions = leavesWithCursorValues.map(
({ leaf, cursorValue }) =>
buildCursorLeafWhereCondition({
@@ -85,9 +79,6 @@ export const computeCursorArgFilter = ({
isEqualityCondition: false,
});
- // A null main condition means no row can sort strictly after the cursor on
- // this leaf alone (e.g. inside a trailing NULL block): only the tie-breaking
- // leaves of the following branches can advance the scan
if (!isDefined(mainCondition)) {
return [];
}
diff --git a/packages/twenty-server/src/engine/api/utils/compute-order-by-leaf-column.util.ts b/packages/twenty-server/src/engine/api/utils/compute-order-by-leaf-column.util.ts
index a05c719eb5e..22f3a829670 100644
--- a/packages/twenty-server/src/engine/api/utils/compute-order-by-leaf-column.util.ts
+++ b/packages/twenty-server/src/engine/api/utils/compute-order-by-leaf-column.util.ts
@@ -5,17 +5,12 @@ import { type OrderByLeaf } from 'src/engine/api/utils/resolve-order-by-leaves.u
import { computeCompositeColumnName } from 'src/engine/metadata-modules/field-metadata/utils/compute-column-name.util';
export type OrderByLeafColumn = {
- // The SQL alias the column lives on: the root object for scalar and
- // composite leaves, the relation's join alias for relation leaves
tableAlias: string;
columnName: string;
columnType: FieldMetadataType;
};
-// The one mapping from an orderBy leaf to the column its values live in. The
-// SQL ORDER BY expression, the hidden column selection and the raw-row alias
-// the cursor side channel reads back (`"<tableAlias>_<columnName>"`) all
-// derive from it, so they cannot drift apart.
+// ORDER BY, hidden column selection and the cursor raw-row alias all derive from this so they cannot drift apart
export const computeOrderByLeafColumn = (
leaf: OrderByLeaf,
objectNameSingular: string,
@@ -23,7 +18,6 @@ export const computeOrderByLeafColumn = (
switch (leaf.kind) {
case 'relation': {
if (!isDefined(leaf.targetFieldMetadata)) {
- // A relation without a resolvable target contributes no ordering
return null;
}
diff --git a/packages/twenty-server/src/engine/api/utils/get-effective-scan-order.utils.ts b/packages/twenty-server/src/engine/api/utils/get-effective-scan-order.utils.ts
index 2d0085703ad..5ff2f5b5f07 100644
--- a/packages/twenty-server/src/engine/api/utils/get-effective-scan-order.utils.ts
+++ b/packages/twenty-server/src/engine/api/utils/get-effective-scan-order.utils.ts
@@ -7,11 +7,7 @@ export type EffectiveScanOrder = {
areNullsScannedLast: boolean;
};
-// The single definition of the scan a paginated query performs: backward
-// pagination scans the exact reverse of the requested order, which flips both
-// the direction and the side the NULL block sits on. Both the SQL ORDER BY and
-// the keyset WHERE conditions must derive from this so they cannot disagree —
-// their prior independent encodings are how issue #24333 happened.
+// SQL ORDER BY and keyset WHERE conditions must both derive from this or they disagree (#24333)
export const getEffectiveScanOrder = (
direction: OrderByDirection,
isForwardPagination: boolean,
diff --git a/packages/twenty-server/src/engine/api/utils/resolve-order-by-leaves.utils.ts b/packages/twenty-server/src/engine/api/utils/resolve-order-by-leaves.utils.ts
index cfe76eb6377..988582600c0 100644
--- a/packages/twenty-server/src/engine/api/utils/resolve-order-by-leaves.utils.ts
+++ b/packages/twenty-server/src/engine/api/utils/resolve-order-by-leaves.utils.ts
@@ -26,10 +26,7 @@ import { isMorphOrRelationFlatFieldMetadata } from 'src/engine/metadata-modules/
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
export type OrderByLeaf = {
- // Path of the ordered value from the record root, e.g. ['closeDate'],
- // ['name', 'firstName'], ['company', 'name'] or ['company', 'name',
- // 'firstName']. It is at once the cursor value path and the filter nesting
- // of the keyset conditions.
+ // Both the cursor value path and the keyset filter nesting, e.g. ['company', 'name', 'firstName']
path: string[];
direction: OrderByDirection;
fieldMetadata: OrmFlatFieldMetadata;
@@ -39,8 +36,7 @@ export type OrderByLeaf = {
| { kind: 'composite'; compositeProperty: CompositeProperty }
| {
kind: 'relation';
- // Resolved against the target object when flatObjectMetadataMaps is
- // provided; the keyset condition builder relies on it for NULL semantics
+ // Only resolved when flatObjectMetadataMaps is provided; the keyset condition builder needs it for NULL semantics
targetFieldMetadata?: OrmFlatFieldMetadata;
targetCompositeProperty?: CompositeProperty;
}
@@ -66,9 +62,6 @@ const throwInvalidOrderByInput = (message: string): never => {
);
};
-// Flattens the nested value of a relation orderBy entry into its leaf paths,
-// e.g. { name: 'AscNullsLast' } -> [['name']] and, for a composite target
-// field, { name: { firstName: 'AscNullsLast' } } -> [['name', 'firstName']].
const flattenNestedOrderByValue = (
value: Record<string, unknown>,
): Array<{ path: string[]; direction: OrderByDirection }> =>
@@ -84,10 +77,7 @@ const flattenNestedOrderByValue = (
: [];
});
-// Resolves one flattened relation orderBy path (e.g. ['company', 'name'] or
-// ['pointOfContact', 'name', 'firstName']) against the relation's target
-// object. Without the object metadata maps the leaf stays unresolved, which is
-// enough for consumers that ignore relation leaves (e.g. column selection).
+// Without flatObjectMetadataMaps the leaf stays unresolved, enough for consumers ignoring relation leaves
const resolveRelationLeaf = ({
fieldMetadata,
path,
@@ -192,16 +182,9 @@ const resolveRelationLeaf = ({
};
};
-// Single source of truth for walking an orderBy: every entry is flattened into
-// ordered leaves that carry their own direction, and the SQL order parser
-// compiles its clauses from these leaves, so the SQL ordering, column
-// selection, cursor encoding, cursor validation and keyset conditions all
-// consume the same list and cannot drift apart. Duplicated leaves keep their
-// first occurrence, which lets callers append the id tie-breaker untouched: a
-// caller-provided id ordering wins over the appended default.
-// Strict validation rejects unknown or malformed entries; the lenient mode
-// skips them instead, for callers that re-walk an already-validated orderBy
-// against another object (e.g. nested connections).
+// Single walk shared by SQL ordering, column selection, cursors and keyset conditions, so they cannot drift apart
+// Duplicates keep their first occurrence, so a caller-provided id ordering wins over the appended tie-breaker
+// Lenient mode skips invalid entries, for re-walks of an already-validated orderBy (e.g. nested connections)
export const resolveOrderByLeaves = ({
orderBy,
flatObjectMetadata,
@@ -212,13 +195,10 @@ export const resolveOrderByLeaves = ({
}: {
orderBy: ObjectRecordOrderBy | undefined;
flatObjectMetadata: FlatObjectMetadata;
- // Needed to resolve relation leaves against their target object; without it
- // they stay unresolved, which lenient callers tolerate
flatObjectMetadataMaps?: FlatEntityMaps<FlatObjectMetadata>;
flatFieldMetadataMaps: FlatEntityMaps<OrmFlatFieldMetadata>;
strictValidation?: boolean;
- // Sort values embed into cursors, so ordering by a field the role cannot
- // read is rejected like filtering by one is
+ // Sort values embed into cursors, so ordering by an unreadable field is rejected
objectsPermissions?: ObjectsPermissions;
}): OrderByLeaf[] => {
if (!isDefined(orderBy) || !isNonEmptyArray(orderBy)) {
@@ -286,8 +266,6 @@ export const resolveOrderByLeaves = ({
const flattenedRelationPaths = flattenNestedOrderByValue(orderByValue);
- // An entry whose nested values are no directions at all would
- // otherwise order by nothing without telling the caller
if (flattenedRelationPaths.length === 0 && strictValidation) {
throwInvalidOrderByInput(
`Relation field "${fieldName}" requires nested field ordering (e.g., { ${fieldName}: { fieldName: 'AscNullsFirst' } })`,
@@ -382,9 +360,6 @@ export const resolveOrderByLeaves = ({
return leaves;
};
-// Rebuilds the canonical orderBy the SQL order parser consumes, one entry per
-// leaf, so the scan order and the keyset conditions derive from the same
-// deduplicated list.
export const buildOrderByFromLeaves = (
leaves: OrderByLeaf[],
): ObjectRecordOrderBy =>
@@ -396,8 +371,7 @@ export const buildOrderByFromLeaves = (
) as ObjectRecordOrderBy[number],
);
-// Reads the leaf's value out of a decoded cursor. Composite values of legacy
-// cursors were carried under dotted keys (e.g. "name.firstName").
+// Legacy cursors carried composite values under dotted keys (e.g. "name.firstName")
export const getCursorValueForLeaf = (
cursor: Record<string, unknown>,
leaf: OrderByLeaf,
diff --git a/packages/twenty-server/src/engine/constants/settings/index.ts b/packages/twenty-server/src/engine/constants/settings/index.ts
index 38701b4e090..3e52080997f 100644
--- a/packages/twenty-server/src/engine/constants/settings/index.ts
+++ b/packages/twenty-server/src/engine/constants/settings/index.ts
@@ -3,9 +3,7 @@ import { type Settings } from './interfaces/settings.interface';
export const settings: Settings = {
storage: {
maxMultipartFileSize: '5MB',
- // Direct uploads (createFileUpload/completeFileUpload) stream to storage
- // without transiting the server memory, so they get a much higher cap
- // than multipart uploads.
+ // Direct uploads stream to storage without transiting server memory
maxDirectUploadFileSize: '1GB',
maxCorePictureFileSize: '10MB',
},
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
index 49032384014..cf5c8bbca3e 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
@@ -351,9 +351,6 @@ export class AdminPanelResolver {
}),
);
- // Listed alongside language models rather than on a page of their own: an
- // administrator enables and disables them the same way, and the table says
- // which kind each one is.
const evaluationModels = this.aiModelRegistryService
.getAllEvaluationModelsWithStatus()
.map(({ modelConfig, isAvailable, isAdminEnabled }) => ({
@@ -374,8 +371,7 @@ export class AdminPanelResolver {
return {
models: [...languageModels, ...evaluationModels],
- // The model the tier actually runs on here, not the head of the chain: a
- // chain can start with a provider this instance holds no key for.
+ // Not the chain head: it can start with a provider this instance holds no key for
defaultModelByTier: AI_MODEL_TIERS.map((tier) => ({
tier,
modelId:
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto.ts
index 02c8f2ffbcc..745774af72b 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto.ts
@@ -23,8 +23,7 @@ export class AdminPanelWorkspaceCreditGrantDTO {
@Field(() => Date, { nullable: true })
revokedAt: Date | null;
- // Set when this grant carries the unspent part of an earlier one forward, so
- // the admin panel can show one row per grant instead of one row per period.
+ // Set when this grant carries forward the unspent part of an earlier one
@Field(() => UUIDScalarType, { nullable: true })
sourceGrantId: string | null;
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input.ts
index 985dac44632..ee0538a21f1 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input.ts
@@ -15,10 +15,7 @@ import {
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
-// Kept at a year, which is the longest the picker offers and comfortably
-// inside the number of periods alignGrantExpiryToPeriodEnd will walk on the
-// shortest interval. Raising it means raising MAX_PERIODS_AHEAD with it, or a
-// long validity silently comes back short.
+// Raising it means raising MAX_PERIODS_AHEAD too, or a long validity silently comes back short
const MAX_CREDIT_GRANT_VALIDITY_IN_DAYS = 365;
@ArgsType()
@@ -43,8 +40,7 @@ export class GrantWorkspaceCreditsInput {
@MaxLength(500)
reason?: string;
- // Left out, the credits do not expire: they stay spendable until a period
- // transition settles them against usage. Set only for a time-boxed grant.
+ // Omitted, credits stay spendable until a period transition settles them against usage
@Field(() => Int, { nullable: true })
@IsOptional()
@IsInt()
@@ -52,8 +48,7 @@ export class GrantWorkspaceCreditsInput {
@Max(MAX_CREDIT_GRANT_VALIDITY_IN_DAYS)
expiresInDays?: number;
- // Identifies one intended grant, so a retried mutation returns the grant the
- // first attempt wrote instead of handing out the credits a second time.
+ // Idempotency key: a retried mutation returns the first attempt's grant
@Field(() => UUIDScalarType)
@IsNotEmpty()
@IsUUID()
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service.ts
index bfe8a809e01..a96f03144b5 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-ai-provider.service.ts
@@ -31,8 +31,7 @@ export class AdminPanelAiProviderService {
private readonly defaultAiCatalogService: DefaultAiCatalogService,
) {}
- // Counting here rather than reading the cached verdict keeps the admin panel
- // exact, and refreshes what model resolution will use on its next read.
+ // Recomputed rather than cached so the admin panel is exact and model resolution refreshed
async getCustomAiProviderAccess(): Promise<CustomAiProviderAccess> {
return this.customAiProviderAccessService.computeAccess();
}
@@ -84,8 +83,6 @@ export class AdminPanelAiProviderService {
return masked;
}
- // Both configs arrive as untyped JSON from the GraphQL layer, so they are
- // taken as unknown and given their shape by the schemas below.
async addProvider({
providerName,
providerConfig,
@@ -99,9 +96,7 @@ export class AdminPanelAiProviderService {
throw new UserInputError('Invalid provider name');
}
- // The GraphQL arg is untyped JSON, so an unsupported npm package would only
- // surface later when the registry builds the provider, taking down model
- // resolution for every provider on the instance.
+ // An invalid config would otherwise break model resolution for every provider on the instance
const validatedProviderConfig =
aiProviderConfigSchema.safeParse(providerConfig);
@@ -123,8 +118,7 @@ export class AdminPanelAiProviderService {
return true;
}
- // Removal stays open so an instance that grows past the threshold can still
- // clean up the providers it configured while it was under it.
+ // No access check so an instance past the threshold can still clean up its providers
async removeProvider(providerName: string): Promise<boolean> {
const customProviders = {
...this.twentyConfigService.get('AI_PROVIDERS'),
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
index afd83dc72df..d5c4bb903ce 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
@@ -68,9 +68,7 @@ export class AdminPanelBillingService {
clientOperationId: string;
grantedByUserId: string;
}): Promise<AdminPanelWorkspaceCreditGrantDTO> {
- // Enforced server side because the mutation is reachable directly, not only
- // through the admin panel's picker. See ADMIN_GRANTABLE_CREDIT_GRANT_TYPES
- // for why these two are excluded.
+ // The mutation is reachable directly, not only through the admin panel picker; see ADMIN_GRANTABLE_CREDIT_GRANT_TYPES for the exclusions
if (!ADMIN_GRANTABLE_CREDIT_GRANT_TYPES.includes(type)) {
throw new BillingException(
`Cannot grant credits of type ${type} by hand`,
@@ -86,8 +84,7 @@ export class AdminPanelBillingService {
'BILLING_MAX_ADMIN_CREDIT_GRANT_MICRO',
);
- // The field is micro-denominated, so a slipped decimal is four orders of
- // magnitude. Bound what a single grant can hand out.
+ // A slipped decimal on a micro-denominated amount is four orders of magnitude
if (amountMicro > maxAmountMicro) {
throw new BillingException(
`Cannot grant ${toDisplayCredits(amountMicro)} credits at once, the maximum is ${toDisplayCredits(maxAmountMicro)}`,
@@ -107,9 +104,6 @@ export class AdminPanelBillingService {
grantedByUserId,
});
- // Answered with the grant either way, whether this attempt wrote it or a
- // previous one did, so nothing is left but the instance that has no ledger
- // to write to at all.
if (!isDefined(grant)) {
throw new BillingException(
`Could not grant credits to workspace ${workspaceId}, billing is disabled on this instance`,
@@ -183,8 +177,7 @@ export class AdminPanelBillingService {
this.getWorkspaceCreditGrants(workspaceId),
]);
- // A workspace can hold granted credits before it has a customer or a
- // subscription, and the admin panel still has to show and manage them.
+ // Granted credits can exist before a customer or subscription does
if (!customer && !subscription && creditGrants.length === 0) {
return null;
}
@@ -307,7 +300,6 @@ export class AdminPanelBillingService {
}
}
-// Namespaced so an operation id can never collide with the carry-forward or
-// backfill keys, which live in the same unique index.
+// Namespaced to never collide with carry-forward or backfill keys in the same unique index
const buildAdminGrantIdempotencyKey = (clientOperationId: string): string =>
`admin-grant:${clientOperationId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts
index 334cdd170b7..5b192309321 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts
@@ -96,7 +96,6 @@ export class AdminPanelGlobalChatThreadsService {
await this.historyStorage.runReadOnlyReport(
workspaces.map((workspace) => workspace.id),
async ({ manager, partitions }) => {
- // Bound each statement's size and keep only the global page candidates.
for (
let offsetIndex = 0;
offsetIndex < partitions.length;
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.entity.ts
index 3275c1ba13c..3d6ae8eba55 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.entity.ts
@@ -15,15 +15,9 @@ import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-// One row per user who has completed an OAuth authorization_code exchange for
-// an application. Application tokens are stateless JWTs carrying the user as a
-// claim, so without this row the server has no record that the authorization
-// happened and nothing to list or revoke. Only authorization_code issues a
-// refresh token; client_credentials returns an access token alone and involves
-// no user, so it has no row here.
+// One row per user authorization_code exchange: tokens are stateless JWTs, so this is the only record to list or revoke.
+// client_credentials involves no user and has no row.
@Entity({ name: 'applicationAuthorization', schema: 'core' })
-// Re-authorizing the same application updates this row rather than adding a
-// second one, so a user never accumulates duplicate entries for one app.
@Index(
'IDX_APPLICATION_AUTHORIZATION_USER_APPLICATION_UNIQUE',
['userId', 'applicationId'],
@@ -42,8 +36,7 @@ export class ApplicationAuthorizationEntity {
})
user: Relation<UserEntity>;
- // No index of its own: it leads the unique index declared on the class, which
- // already serves both the per-user listing and the cascade delete.
+ // No index of its own: it leads the class's unique index, which serves the per-user listing and the cascade delete
@Column({ type: 'uuid' })
userId: string;
@@ -60,9 +53,6 @@ export class ApplicationAuthorizationEntity {
@Column({ type: 'uuid' })
workspaceId: string;
- // Uninstalling deletes the application row, which already invalidates every
- // token issued for it. Cascading here stops the grants outliving the install
- // they describe.
@ManyToOne(() => ApplicationEntity, {
onDelete: 'CASCADE',
})
@@ -76,9 +66,7 @@ export class ApplicationAuthorizationEntity {
@Column({ type: 'uuid' })
applicationId: string;
- // Cascades only on a hard delete. Removing a member soft-deletes the
- // membership instead, which leaves this row intact, so the refresh path
- // rechecks the membership rather than trusting the grant to have gone.
+ // Cascades only on hard delete; member removal soft-deletes, so the refresh path rechecks membership
@ManyToOne(() => UserWorkspaceEntity, {
onDelete: 'CASCADE',
})
@@ -92,11 +80,7 @@ export class ApplicationAuthorizationEntity {
@Column({ type: 'uuid' })
userWorkspaceId: string;
- // Scopes as granted at the last exchange, which is what the user consented to
- // and therefore what the revocation screen should show them. Null on a row
- // reconstructed from a refresh token that predates this table: those tokens
- // carry no scope claim, and what the application declares today is not
- // evidence of what the user agreed to back then.
+ // As granted at the last exchange, i.e. what the user consented to; null on rows backfilled from pre-table refresh tokens (no scope claim)
@Column({ type: 'text', array: true, nullable: true })
scopes: string[] | null;
@@ -104,13 +88,11 @@ export class ApplicationAuthorizationEntity {
@Column({ type: 'timestamptz', nullable: true })
lastAuthorizedAt: Date | null;
- // Touched on refresh. Refreshes happen at most once per access-token TTL, so
- // this needs no write throttling of its own.
+ // Touched on refresh, at most once per access-token TTL, so no write throttling needed
@Column({ type: 'timestamptz' })
lastUsedAt: Date;
- // Kept forever once set: a revoked row is what tells a still-signed refresh
- // token apart from one issued before authorizations were recorded.
+ // Revoked rows are kept: they tell a revoked refresh token apart from one predating this table
@Column({ type: 'timestamptz', nullable: true })
revokedAt: Date | null;
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.resolver.ts
index dcff27bf8cc..ea4efcb12b2 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-authorization/application-authorization.resolver.ts
@@ -15,11 +15,6 @@ import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorat
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
-// Scoped to this person within this workspace: an authorization grants an
-// application access to one workspace's data, so it is listed and revoked from
-// that workspace only, and revoking affects nobody else. Removing an
-// integration for the whole workspace is uninstalling it, an admin action that
-// lives elsewhere.
@UsePipes(ResolverValidationPipe)
@UseFilters(AuthGraphqlApiExceptionFilter)
@UseGuards(
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-authorization/dtos/application-authorization.dto.ts b/packages/twenty-server/src/engine/core-modules/application/application-authorization/dtos/application-authorization.dto.ts
index bc1ee98047e..4257658b028 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-authorization/dtos/application-authorization.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-authorization/dtos/application-authorization.dto.ts
@@ -16,14 +16,11 @@ export class ApplicationAuthorizationDTO {
@Field(() => String)
applicationName: string;
- // Two custom applications in a workspace can carry the same name, so the
- // name alone cannot tell the user which authorization they are revoking.
+ // Custom applications can share a name, so the name alone is ambiguous
@Field(() => String, { nullable: true })
applicationUniversalIdentifier: string | null;
- // Null when the grant was reconstructed from a refresh token predating the
- // authorization record, so the screen can say the original consent is
- // unknown instead of inventing one.
+ // Null for grants backfilled from refresh tokens predating the authorization record
@Field(() => [String], { nullable: true })
scopes: string[] | null;
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-authorization/services/application-authorization.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-authorization/services/application-authorization.service.ts
index 93e04f183ef..0f420b225dd 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-authorization/services/application-authorization.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-authorization/services/application-authorization.service.ts
@@ -13,8 +13,6 @@ export class ApplicationAuthorizationService {
private readonly applicationAuthorizationRepository: Repository<ApplicationAuthorizationEntity>,
) {}
- // Re-authorizing an application the user previously revoked reinstates the
- // same row: they have just consented again, so the revocation is spent.
async recordAuthorization({
userId,
workspaceId,
@@ -48,11 +46,8 @@ export class ApplicationAuthorizationService {
);
}
- // Stands in for the consent event that happened before this table existed.
- // The refresh token proves the authorization took place but carries no scope
- // claim and no timestamp for it, so both are left null instead of being
- // guessed from what the application declares today. Insert-only, so it can
- // never overwrite a row written by a real consent.
+ // Scopes and consent time stay null: pre-table refresh tokens carry neither, and today's declared scopes prove nothing.
+ // Insert-only, so it never overwrites a row written by a real consent.
async backfillAuthorizationFromRefreshToken({
userId,
workspaceId,
@@ -81,8 +76,7 @@ export class ApplicationAuthorizationService {
.execute();
}
- // Returns revoked rows too: the caller has to tell "never authorized" apart
- // from "authorized then revoked", which are opposite answers.
+ // Includes revoked rows: callers must tell "never authorized" from "revoked"
async findByUserAndApplication({
userId,
applicationId,
@@ -96,12 +90,7 @@ export class ApplicationAuthorizationService {
});
}
- // Inner join, so an application that has been soft-deleted takes its
- // authorizations off the list rather than surfacing them with nothing to
- // name them.
- // Scoped to one workspace: an authorization grants an application access to
- // this workspace's data, so it is this workspace's to list and revoke. The
- // same person's grants elsewhere are not visible from here.
+ // Inner join drops authorizations of soft-deleted applications
async findActiveAuthorizationsForUserWorkspace({
userId,
workspaceId,
@@ -128,9 +117,7 @@ export class ApplicationAuthorizationService {
);
}
- // Scoped in the UPDATE itself rather than read-then-write, so one user can
- // never revoke another user's authorization, or their own in another
- // workspace, by guessing an id.
+ // Scoped in the UPDATE itself so a guessed id cannot revoke someone else's authorization
async revokeAuthorizationByIdForUserWorkspace({
authorizationId,
userId,
@@ -157,9 +144,7 @@ export class ApplicationAuthorizationService {
return await this.revokeMatching({ userId, applicationId });
}
- // Returns whether this call was the one that revoked it, so a repeated
- // revocation reports false rather than moving revokedAt forward. The union
- // rules out an empty criteria object, which would revoke every row.
+ // The union rules out empty criteria, which would revoke every row
private async revokeMatching(
criteria:
| { id: string; userId: string; workspaceId: string }
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
index c421b49f4a4..3552860ceeb 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
@@ -132,10 +132,7 @@ export class ApplicationManifestMigrationService {
const validateAndBuildResult =
await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunWorkspaceMigrationFromTo(
{
- // inferDeletionFromMissingEntities is intentionally omitted (undefined)
- // so this pared-down sync is purely additive — existing metadata for
- // objects/fields/other logic functions that are absent from
- // preInstallOnlyManifest are left untouched on upgrades.
+ // inferDeletionFromMissingEntities omitted so this pre-install sync is purely additive
buildOptions: {
isSystemBuild: false,
applicationUniversalIdentifier:
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
index 0a9656fb678..9bf0049efad 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
@@ -76,8 +76,7 @@ export class ApplicationSyncService {
workspaceMigration: WorkspaceMigration;
hasSchemaMetadataChanged: boolean;
}> {
- // Server variables are written to the registration after this sync, so
- // reserved names are checked here to fail before the workspace changes
+ // Checked upfront: server variables reach the registration only after the workspace changes
const reservedVariableNames =
findReservedVariableNamesInApplicationManifest(manifest.application);
@@ -118,10 +117,7 @@ export class ApplicationSyncService {
}
if (!dryRun && isDefined(ownerFlatApplication.applicationRegistrationId)) {
- // Translation sync runs after the metadata migration is already applied
- // and is non-critical to the application itself, so a failure here must
- // never abort an otherwise successful install/sync. It is idempotent and
- // self-heals on the next sync.
+ // Non-critical and self-healing on next sync, so a failure must not abort the install
try {
await this.applicationTranslationSyncService.syncFromManifest({
applicationRegistrationId:
@@ -212,10 +208,7 @@ export class ApplicationSyncService {
};
}
- // Registers the application + only the pre-install logic function in
- // workspace metadata so the pre-install hook can resolve and execute it
- // before the main synchronizeFromManifest runs the full migrations.
- // No-op when the manifest does not declare a pre-install logic function.
+ // Lets the pre-install hook resolve its logic function before the full migrations run
public async preInstallSynchronizeFromManifest({
workspaceId,
manifest,
@@ -429,9 +422,8 @@ export class ApplicationSyncService {
},
);
- // Uninstall also removes engine-owned and workspace-local metadata that
- // manifest omission intentionally preserves. Expand these explicit deletions
- // so dependents owned by other applications are cleaned up too.
+ // Unlike manifest omission, uninstall also removes engine-owned and workspace-local metadata, so expand the deletions
+ // to dependents owned by other applications
const allFlatEntityOperationRecordByMetadataName: AllFlatEntityOperationRecordByMetadataName =
Object.fromEntries(
Object.values(ALL_METADATA_NAME).map((metadataName) => [
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
index af00995499b..566d8165086 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
@@ -24,10 +24,7 @@ export class OAuthDiscoveryController {
@UseGuards(PublicEndpointGuard, NoPermissionGuard)
async getAuthorizationServerMetadata(@Req() request: Request) {
const issuer = getRequestBaseUrl(request);
- // /authorize is served by the frontend; SERVER_URL (API-only) has no such
- // route, so we route the client to the default frontend base URL in that
- // case. All other hosts (app.twenty.com, workspace subdomains, custom
- // domains) serve both frontend and API.
+ // The API-only SERVER_URL has no frontend /authorize route
const authorizeBase = this.isApiHost(request)
? cleanServerUrl(this.domainServerConfigService.getBaseUrl().toString())
: issuer;
@@ -59,19 +56,13 @@ export class OAuthDiscoveryController {
token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],
revocation_endpoint_auth_methods_supported: ['client_secret_post'],
introspection_endpoint_auth_methods_supported: ['client_secret_post'],
- // RFC 9207: advertise `iss` in authorization responses to defend against
- // OAuth mix-up attacks. Required by OAuth 2.1 security BCP.
+ // RFC 9207: advertise `iss` to defend against OAuth mix-up attacks
authorization_response_iss_parameter_supported: true,
cli_client_id: cliRegistration.oAuthClientId,
};
}
- // RFC 9728 §3.2: the `resource` value MUST equal the resource identifier
- // into which the well-known path suffix was inserted. So the root form maps
- // to the origin as-a-resource, and the /mcp-suffixed form maps to
- // <origin>/mcp. Strict clients probing the path-aware variant will reject
- // mismatching metadata.
-
+ // RFC 9728 §3.2: `resource` must equal the identifier the well-known suffix was inserted into; strict clients reject a mismatch
@Get('oauth-protected-resource')
@UseGuards(PublicEndpointGuard, NoPermissionGuard)
getProtectedResourceMetadataRoot(@Req() request: Request) {
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/oauth.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/oauth.service.ts
index 368861758f6..85e0a5467c6 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/oauth.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/oauth.service.ts
@@ -36,9 +36,7 @@ export class OAuthService {
private readonly appTokenRepository: Repository<AppTokenEntity>,
@InjectWorkspaceScopedRepository(ApplicationEntity)
private readonly applicationRepository: WorkspaceScopedRepository<ApplicationEntity>,
- // The client-credentials grant counts a registration's installs across
- // every workspace to enforce that exactly one exists, so that one read has
- // no workspace to scope by.
+ // Client-credentials counts a registration's installs across every workspace to enforce exactly one, so there is no workspace to scope by
// eslint-disable-next-line twenty/prefer-workspace-scoped-repository
@InjectRepository(ApplicationEntity)
private readonly unscopedApplicationRepository: Repository<ApplicationEntity>,
@@ -122,8 +120,7 @@ export class OAuthService {
);
}
- // RFC 6749 §4.1.2: if a previously used code is presented, this indicates
- // a potential compromise — log a security warning
+ // RFC 6749 §4.1.2: a reused code signals a potential compromise
if (authCodeToken.revokedAt) {
this.logger.warn(
`Authorization code replay detected for client ${clientId}. ` +
@@ -169,7 +166,6 @@ export class OAuthService {
}
}
- // PKCE: if code_challenge was stored, code_verifier is required
const storedCodeChallenge = authCodeToken.context?.codeChallenge;
if (storedCodeChallenge) {
@@ -251,8 +247,7 @@ export class OAuthService {
authCodeToken.context?.scope ??
applicationRegistration.oAuthScopes.join(' ');
- // Recorded before the tokens exist, so a refresh token is never handed out
- // without the grant that makes it redeemable and revocable.
+ // Recorded first so a refresh token never exists without a revocable grant
await this.applicationAuthorizationService.recordAuthorization({
userId: authCodeToken.userId,
workspaceId: authCodeToken.workspaceId,
@@ -475,9 +470,7 @@ export class OAuthService {
token,
);
- // RFC 7009 §2.1: revoking a refresh token invalidates the authorization
- // behind it, and only the client the token was issued to may ask for
- // that. Access tokens stay stateless and live out their few minutes.
+ // RFC 7009 §2.1: only the issuing client may revoke; access tokens stay valid until expiry
if (isDefined(applicationRegistration) && isDefined(payload.userId)) {
const application = await this.applicationRepository.findOne(
payload.workspaceId,
@@ -501,8 +494,7 @@ export class OAuthService {
`Token revocation requested for application ${payload.applicationId}`,
);
} catch {
- // Per RFC 7009 §2.2: the server responds with HTTP 200 for both
- // valid and invalid tokens
+ // RFC 7009 §2.2: respond 200 for both valid and invalid tokens
}
return { success: true };
@@ -651,11 +643,7 @@ export class OAuthService {
return null;
}
- // Refresh tokens issued before authorizations were recorded have no row to
- // check against. Rejecting them would sign every live integration out the
- // moment this ships, so the first refresh backfills the grant that was always
- // implied. A revoked authorization keeps its row, so this never resurrects
- // access the user turned off.
+ // Refresh tokens predating this table have no row: backfill it rather than sign every integration out
private async consumeUserAuthorization({
userId,
workspaceId,
@@ -678,9 +666,7 @@ export class OAuthService {
);
}
- // Rechecked on every refresh, not just when backfilling: removing a member
- // soft-deletes the membership, so an existing grant outlives it and nothing
- // else in this path would notice.
+ // Member removal soft-deletes the membership, which an existing grant outlives
const userWorkspace = await this.userWorkspaceRepository.findOne({
where: { userId, workspaceId },
});
@@ -712,11 +698,7 @@ export class OAuthService {
return null;
}
- // A token predating the authorization record has no row to mark revoked, and
- // the refresh path would then happily backfill a fresh active one. Lay the
- // row down first so the revocation has something to stick to. If the
- // membership is gone the refresh already fails on that, so there is nothing
- // worth recording.
+ // Lays a row down first, or the refresh path would backfill a fresh active one for a pre-table token
private async revokeUserAuthorization({
userId,
workspaceId,
@@ -765,8 +747,7 @@ export class OAuthService {
return isDefined(authorization?.revokedAt);
}
- // RFC 6749 §3.3: scope is a space-delimited list, so an empty value has to
- // collapse to no scopes rather than to one blank one.
+ // RFC 6749 §3.3: an empty scope means no scopes, not one blank one
private parseScopes(scope: string): string[] {
return scope.split(' ').filter((entry) => entry.length > 0);
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts
index 4287e1513c9..8c28623f4ec 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts
@@ -85,8 +85,7 @@ export class ApplicationRegistrationEntity {
@JoinColumn({ name: 'createdByUserId' })
createdByUser: Relation<UserEntity> | null;
- // Ownership (who can edit). Null for catalog-synced marketplace apps that
- // have no explicit owner — these are managed via the Admin Panel.
+ // Null for catalog-synced marketplace apps, managed from the Admin Panel
@Field(() => UUIDScalarType, { nullable: true })
@Column({ name: 'workspaceId', nullable: true, type: 'uuid' })
ownerWorkspaceId: string | null;
@@ -132,8 +131,7 @@ export class ApplicationRegistrationEntity {
])
isVetted: boolean;
- // Auto-installed on every new workspace; existing workspaces are
- // backfilled by the `install-pre-installed-apps` CLI command.
+ // Auto-installed on new workspaces; existing ones are backfilled by the `install-pre-installed-apps` command
@Field(() => Boolean)
@Column({ type: 'boolean', default: false })
isPreInstalled: boolean;
@@ -194,8 +192,7 @@ export class ApplicationRegistrationEntity {
})
aboutDescription: string | null;
- // Free text: app pricing is tiered, per-minute, per-match with minimums, so
- // a single rate cannot express it. Shown on the marketplace listing.
+ // Free text: tiered, per-minute or per-match pricing cannot fit a single rate
@Column({ nullable: true, type: 'text' })
@WasIntroducedInUpgrade({
upgradeCommandName:
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
index 9cd3f8000d8..c846d3894d1 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
@@ -137,8 +137,7 @@ export class ApplicationRegistrationService {
constructor(
@InjectRepository(ApplicationRegistrationEntity)
private readonly applicationRegistrationRepository: Repository<ApplicationRegistrationEntity>,
- // Registration-owner stats: version distribution and the installed-workspace
- // list are aggregates over every workspace that installed it.
+ // Stats aggregate over every workspace that installed the app
// eslint-disable-next-line twenty/prefer-workspace-scoped-repository
@InjectRepository(ApplicationEntity)
private readonly applicationRepository: Repository<ApplicationEntity>,
@@ -236,8 +235,7 @@ export class ApplicationRegistrationService {
}
}
- // Best-effort: a queue outage must not fail the publish flow that
- // triggered the upgrade.
+ // Best-effort: a queue outage must not fail the publish flow
async enqueueAutoUpgradeApplications(
applicationRegistrationId: string,
): Promise<void> {
@@ -362,8 +360,7 @@ export class ApplicationRegistrationService {
);
}
- // Configuration status is computed from variables and installs, not stored
- // on the registration, so this filter paginates in memory.
+ // Configuration status is computed, not stored, so this filter paginates in memory
if (isDefined(isConfigured)) {
const allRegistrations = await queryBuilder.getMany();
@@ -466,7 +463,6 @@ export class ApplicationRegistrationService {
return applicationRegistration;
}
- // Global lookup — used by OAuth flow (no workspace scoping)
async findOneByClientId(
clientId: string,
): Promise<ApplicationRegistrationEntity | null> {
@@ -475,7 +471,6 @@ export class ApplicationRegistrationService {
});
}
- // Global lookup — used by OAuth authorize page (no workspace scoping)
async findPublicByClientId(
clientId: string,
): Promise<PublicApplicationRegistrationDTO | null> {
@@ -620,8 +615,7 @@ export class ApplicationRegistrationService {
return this.findOneByIdGlobal(id);
}
- // Instance-wide flags travel apart from the payload so the
- // workspace-scoped update has no way to set them.
+ // Instance-wide flags are kept apart from the payload so the workspace-scoped update cannot set them
private async applyUpdate({
id,
update,
@@ -750,9 +744,7 @@ export class ApplicationRegistrationService {
const updatePayload =
updateFields as QueryDeepPartialEntity<ApplicationRegistrationEntity>;
- // Partial update in one transaction: the row and its variable schemas
- // stay on the same manifest without clobbering columns written by
- // flows outside this lock.
+ // One transaction keeps the row and its variable schemas on the same manifest; partial so columns written outside this lock survive
await this.applicationRegistrationRepository.manager.transaction(
async (entityManager) => {
await entityManager
@@ -798,8 +790,7 @@ export class ApplicationRegistrationService {
ownerWorkspaceId,
});
- // Stored assets (logo, gallery images) go with the registration; deleting
- // them first also removes the bytes, which the row FK cascade cannot do.
+ // Deleted explicitly: the FK cascade removes rows, not stored bytes
try {
await this.serverFileStorageService.deleteByApplicationRegistrationId(
applicationRegistrationId,
@@ -1177,8 +1168,7 @@ export class ApplicationRegistrationService {
};
}
- // Installed workspaces are only exposed in the admin panel, which views apps
- // across all workspaces, so ownership is not enforced.
+ // Admin panel only, which views apps across all workspaces, so ownership is not enforced
async getInstalledWorkspacesGlobal(
applicationRegistrationId: string,
limit: number,
@@ -1299,8 +1289,7 @@ export class ApplicationRegistrationService {
);
}
- // Claim atomically: only update while still unowned so concurrent
- // claimers can't overwrite each other (first-claimant-wins).
+ // Conditional update so concurrent claimers cannot overwrite each other
const updateResult = await this.applicationRegistrationRepository.update(
{ id: registration.id, ownerWorkspaceId: IsNull() },
{ ownerWorkspaceId: params.claimingWorkspaceId },
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-translation/application-translation-sync.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-translation/application-translation-sync.service.ts
index 962cc02f17c..cd02bbd1dfe 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-translation/application-translation-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-translation/application-translation-sync.service.ts
@@ -26,9 +26,7 @@ export class ApplicationTranslationSyncService {
applicationRegistrationId: string;
translations: TranslationsManifest | undefined;
}): Promise<void> {
- // Absence says nothing about translations, so it must not prune: this
- // table is cross-workspace, and a sync from a toolchain that does not
- // compile them would drop the locales an app published, everywhere.
+ // Absence must not prune: this cross-workspace table would lose the app's locales everywhere
if (!isDefined(translations)) {
return;
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-translation/utils/compute-application-translation-sync-plan.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-translation/utils/compute-application-translation-sync-plan.util.ts
index eb876d13dbe..59c22a36411 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-translation/utils/compute-application-translation-sync-plan.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-translation/utils/compute-application-translation-sync-plan.util.ts
@@ -17,8 +17,7 @@ export type ApplicationTranslationSyncPlan = {
rowIdsToSoftDelete: string[];
};
-// A soft-deleted row is preferred over none, so a locale that comes back is
-// revived rather than duplicated.
+// Prefer a soft-deleted row over none so a returning locale is revived, not duplicated
const pickRowByLocale = (
existingRows: StoredTranslationRow[],
): Map<keyof typeof APP_LOCALES, StoredTranslationRow> => {
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
index 7cfb8be5feb..e89a43299ea 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
@@ -122,9 +122,6 @@ export class ApplicationEntity extends WorkspaceRelatedEntity {
@Column({ type: 'jsonb', nullable: false, default: {} })
availablePackages: Record<string, string>;
- // What the app declares it bills for: recurring charges the platform raises
- // each period, and the operations it charges against, each with the billing
- // category metered and the app-authored label shown for that spend.
@Column({ type: 'jsonb', nullable: false, default: {} })
@WasIntroducedInUpgrade({
upgradeCommandName:
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
index c7b67cb18c9..c80f1a10bf6 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
@@ -42,8 +42,7 @@ export class ConnectionProviderOAuthController {
private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
) {}
- // Public endpoint — the transient token carries workspace + user context
- // so we don't need a session cookie here.
+ // Public: the transient token carries workspace and user context
@Get('authorize')
async authorize(
@Query('applicationId') applicationId: string,
@@ -55,8 +54,7 @@ export class ConnectionProviderOAuthController {
@Query('redirectLocation') redirectLocation: string | undefined,
@Res() res: Response,
) {
- // Captured early so the error-redirect lands on the user's own
- // subdomain (different cookie domain otherwise = de-facto logout).
+ // Captured early so error redirects land on the user's subdomain (another cookie domain logs them out)
let workspace: WorkspaceEntity | null = null;
try {
@@ -139,8 +137,7 @@ export class ConnectionProviderOAuthController {
return res.redirect(authorizationUrl);
} catch (error) {
- // Without an explicit log, CustomException would 500 silently
- // (it doesn't extend HttpException, so Nest's default filter swallows it).
+ // CustomException doesn't extend HttpException, so Nest's filter would 500 it silently
this.logger.error(
`OAuth authorize failed (applicationId=${applicationId}, providerName=${providerName}): ${error instanceof Error ? error.message : String(error)}`,
error instanceof Error ? error.stack : undefined,
diff --git a/packages/twenty-server/src/engine/core-modules/approved-access-domain/services/approved-access-domain.spec.ts b/packages/twenty-server/src/engine/core-modules/approved-access-domain/services/approved-access-domain.spec.ts
index 17e3c19f9c8..ac5afea7d4d 100644
--- a/packages/twenty-server/src/engine/core-modules/approved-access-domain/services/approved-access-domain.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/approved-access-domain/services/approved-access-domain.spec.ts
@@ -23,9 +23,7 @@ import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-membe
import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
import { ApprovedAccessDomainService } from './approved-access-domain.service';
-// render() resolves through a streaming scheduler that never advances under the
-// globally enabled fake timers; the real render path is covered by
-// email-templates-rendering.spec.ts.
+// render() never resolves under the global fake timers; covered by email-templates-rendering.spec.ts
jest.mock('twenty-emails', () => ({
...jest.requireActual('twenty-emails'),
renderEmail: jest.fn().mockImplementation(async (_template, options) => {
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
index 5c6185624ad..c05ee1e0abe 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
@@ -161,9 +161,7 @@ import { JwtAuthStrategy } from './strategies/jwt.auth.strategy';
RefreshTokenService,
LoginTokenService,
ResetPasswordService,
- // So far, it's not possible to have controllers in business modules
- // which forces us to have these services in the auth module
- // TODO: Move these calendar, message, and connected account services to the business modules once possible
+ // TODO: move these calendar, message and connected account services to business modules once they can hold controllers
CalendarChannelSyncStatusService,
CreateMessageChannelService,
CreateCalendarChannelService,
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
index 9c69c3eb931..4df4742884a 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
@@ -1129,8 +1129,7 @@ export class AuthResolver {
refreshToken,
});
} finally {
- // This mutation is public and SameSite=Lax keeps the cookie off cross-site
- // POSTs, so clearing unconditionally would let any site sign a visitor out.
+ // Public, and SameSite=Lax keeps the cookie off cross-site POSTs: clearing unconditionally lets any site sign visitors out
if (
isDefined(context.req.res) &&
this.userSessionCookieService.hasSessionCookie(context.req)
diff --git a/packages/twenty-server/src/engine/core-modules/auth/controllers/google-apis-auth.controller.ts b/packages/twenty-server/src/engine/core-modules/auth/controllers/google-apis-auth.controller.ts
index 9672006628c..aaa2a2436ae 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/controllers/google-apis-auth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/controllers/google-apis-auth.controller.ts
@@ -55,7 +55,6 @@ export class GoogleAPIsAuthController {
NoPermissionGuard,
)
async googleAuth() {
- // As this method is protected by Google Auth guard, it will trigger Google SSO flow
return;
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/controllers/google-auth.controller.ts b/packages/twenty-server/src/engine/core-modules/auth/controllers/google-auth.controller.ts
index 47c9e248e0a..6937d9c887c 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/controllers/google-auth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/controllers/google-auth.controller.ts
@@ -33,7 +33,6 @@ export class GoogleAuthController {
NoPermissionGuard,
)
async googleAuth() {
- // As this method is protected by Google Auth guard, it will trigger Google SSO flow
return;
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-apis-auth.controller.ts b/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-apis-auth.controller.ts
index 229b3cee78a..b025a3435cf 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-apis-auth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-apis-auth.controller.ts
@@ -55,7 +55,6 @@ export class MicrosoftAPIsAuthController {
NoPermissionGuard,
)
async MicrosoftAuth() {
- // As this method is protected by Microsoft Auth guard, it will trigger Microsoft SSO flow
return;
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-auth.controller.ts b/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-auth.controller.ts
index e845be9a306..5364a9881dc 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-auth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/controllers/microsoft-auth.controller.ts
@@ -32,7 +32,6 @@ export class MicrosoftAuthController {
NoPermissionGuard,
)
async microsoftAuth() {
- // As this method is protected by Microsoft Auth guard, it will trigger Microsoft SSO flow
return;
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/controllers/sso-auth.controller.ts b/packages/twenty-server/src/engine/core-modules/auth/controllers/sso-auth.controller.ts
index 4464c60a421..d52ac9a5cf3 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/controllers/sso-auth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/controllers/sso-auth.controller.ts
@@ -90,7 +90,6 @@ export class SsoAuthController {
NoPermissionGuard,
)
async oidcAuth() {
- // As this method is protected by OIDC Auth guard, it will trigger OIDC SSO flow
return;
}
@@ -102,7 +101,6 @@ export class SsoAuthController {
NoPermissionGuard,
)
async samlAuth() {
- // As this method is protected by SAML Auth guard, it will trigger SAML SSO flow
return;
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts
index 73b0ba31b0a..72ad06950fd 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/services/auth.service.ts
@@ -394,7 +394,6 @@ export class AuthService {
new AuthException('User not found', AuthExceptionCode.USER_NOT_FOUND),
);
- // passwordHash is hidden for security reasons
user.passwordHash = '';
const accessToken = await this.accessTokenService.generateAccessToken({
@@ -537,10 +536,7 @@ export class AuthService {
);
}
- // OAuth 2.1 / MCP auth spec: PKCE is mandatory for public clients
- // (clients registered with token_endpoint_auth_method=none, i.e. no
- // client secret hash). Confidential clients are authenticated at the
- // token endpoint instead.
+ // OAuth 2.1 / MCP auth spec: PKCE is mandatory for public clients (no client secret)
const isPublicClient = !applicationRegistration.oAuthClientSecretHash;
if (isPublicClient && !codeChallenge) {
@@ -550,9 +546,8 @@ export class AuthService {
);
}
- // RFC 8252 §7.3: Native apps using loopback redirect URIs may use any port.
- // When a registration has no explicit redirect URIs (e.g. the seeded CLI registration),
- // allow any loopback redirect URI.
+ // RFC 8252 §7.3: native apps may use any loopback port, so a registration without redirect URIs
+ // (e.g. the seeded CLI one) accepts any loopback redirect URI
const hasRegisteredRedirectUris =
applicationRegistration.oAuthRedirectUris.length > 0;
@@ -991,8 +986,6 @@ export class AuthService {
const existingUser =
await this.userService.findUserByEmailWithWorkspaces(email);
- // Route SSO sign-ins through the same create-or-select flow as credentials
- // instead of landing straight on a workspace subdomain.
if (!workspaceId && !workspaceInviteHash) {
const user =
existingUser ??
@@ -1016,8 +1009,7 @@ export class AuthService {
authProvider,
});
- // The token rides in the fragment so it never reaches access logs,
- // proxies or Referer headers: browsers keep it out of the request line.
+ // The fragment keeps the token out of access logs, proxies and Referer headers
const url = this.domainServerConfigService.buildBaseUrl({
pathname: AppPath.SignInUp,
searchParams: {
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
index aead54d7117..3e076b62ba3 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
@@ -474,8 +474,7 @@ export class SignInUpService {
}
}
- // Enforced here rather than at workspace creation so a restricted instance
- // stops accumulating verified users that can never reach a workspace.
+ // Enforced at sign-up so a restricted instance stops accumulating users who can never reach a workspace
private async assertSignUpWithoutWorkspaceAllowed(
email: string,
): Promise<void> {
@@ -507,9 +506,7 @@ export class SignInUpService {
}
private async hasProvisionedDestination(email: string): Promise<boolean> {
- // Invitations are read directly instead of through the sign-in picker,
- // which hides HIDDEN workspaces: that is a listing rule, not a statement
- // that the invitee has nowhere to land.
+ // Read directly: the sign-in picker hides HIDDEN workspaces, which is only a listing rule
const invitations =
await this.workspaceInvitationService.findInvitationsByEmail(email);
@@ -800,13 +797,8 @@ export class SignInUpService {
queryRunner,
);
- // Click-through DPA: the DPA is incorporated by reference into the
- // ToS/signup, so acceptance = execution. Only relevant on Twenty's
- // managed cloud (multi-workspace), where Twenty is the Processor
- // hosting the data; on self-hosted deployments Twenty is not the
- // Processor, so there is nothing to record. Done atomically with
- // workspace creation so we can later prove what was agreed. (Billing
- // is an independent feature flag and must not be used to detect cloud.)
+ // Click-through DPA, recorded with the workspace as proof: only on managed cloud, where Twenty is the Processor
+ // Billing is an independent flag and must not be used to detect cloud
if (
this.twentyConfigService.get('IS_MULTIWORKSPACE_ENABLED') === true
) {
diff --git a/packages/twenty-server/src/engine/core-modules/auth/strategies/google-apis-oauth-request-code.auth.strategy.ts b/packages/twenty-server/src/engine/core-modules/auth/strategies/google-apis-oauth-request-code.auth.strategy.ts
index b40d65d604b..e3e7c5e0d50 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/strategies/google-apis-oauth-request-code.auth.strategy.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/strategies/google-apis-oauth-request-code.auth.strategy.ts
@@ -43,8 +43,7 @@ export class GoogleAPIsOauthRequestCodeStrategy extends GoogleAPIsOauthCommonStr
_profile: unknown,
done: VerifyCallback,
): Promise<void> {
- // This strategy is only used for requesting authorization code
- // No validation is performed here
+ // Only used to request an authorization code
done(null, {});
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/strategies/jwt.auth.strategy.ts b/packages/twenty-server/src/engine/core-modules/auth/strategies/jwt.auth.strategy.ts
index f75483649d2..1752886a4c9 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/strategies/jwt.auth.strategy.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/strategies/jwt.auth.strategy.ts
@@ -472,7 +472,6 @@ export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
}
private async dispatch(payload: JwtPayload): Promise<AuthContext> {
- // Support legacy api keys
if (
payload.type === JwtTokenTypeEnum.API_KEY ||
this.isLegacyApiKeyPayload(payload)
diff --git a/packages/twenty-server/src/engine/core-modules/auth/strategies/saml.auth.strategy.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/strategies/saml.auth.strategy.spec.ts
index 87ed97083a2..748413e2862 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/strategies/saml.auth.strategy.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/strategies/saml.auth.strategy.spec.ts
@@ -57,9 +57,7 @@ describe('SamlAuthStrategy.validate', () => {
strategy = new SamlAuthStrategy(ssoService);
});
- // Regression test for the workspace-confusion finding. An attacker-controlled
- // RelayState that claims a different identity-provider id than the one whose
- // cert verified the assertion must have zero influence on the resolved IdP.
+ // A RelayState claiming another IdP than the one whose cert verified the assertion must not influence the resolved IdP
it('ignores RelayState.identityProviderId and sources it exclusively from the URL path', async () => {
const request = buildRequest({
paramsIdpId: IDP_A,
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/access-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/access-token.service.ts
index 772fe62de63..40370302df0 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/access-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/access-token.service.ts
@@ -197,8 +197,7 @@ export class AccessTokenService {
if (token) {
if (isUserSessionToken(token)) {
- // Session tokens are cookie-only by design: accepting them as Bearer would
- // reopen the XSS-exfiltration surface cookie sessions close.
+ // Session tokens are cookie-only: accepting them as Bearer reopens XSS exfiltration
throw new AuthException(
'Session tokens are only accepted from the session cookie',
AuthExceptionCode.UNAUTHENTICATED,
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/sso-exchange-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/sso-exchange-token.service.ts
index ddabeaaec1a..c6e80545004 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/sso-exchange-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/sso-exchange-token.service.ts
@@ -24,8 +24,7 @@ import { type AuthProviderEnum } from 'src/engine/core-modules/workspace/types/w
const hashSsoExchangeToken = (ssoExchangeToken: string) =>
crypto.createHash('sha256').update(ssoExchangeToken).digest('hex');
-// A single opaque error for missing, expired and already-consumed tokens:
-// distinguishing them would turn this endpoint into a redemption oracle.
+// One opaque error for every failure, or this endpoint becomes a redemption oracle
const buildInvalidSsoExchangeTokenException = () =>
new AuthException(
'Invalid SSO exchange token',
@@ -85,10 +84,7 @@ export class SsoExchangeTokenService {
throw buildInvalidSsoExchangeTokenException();
}
- // Deleting the row is the single-use claim: under concurrent redemption
- // only the request whose delete affects the row proceeds to mint a token.
- // Re-checking revokedAt/deletedAt here keeps the claim atomic with
- // revocation: a token revoked after the lookup cannot redeem.
+ // The delete is the single-use claim; rechecking revokedAt/deletedAt keeps it atomic with revocation
const { affected } = await this.appTokenRepository.delete({
id: appToken.id,
revokedAt: IsNull(),
diff --git a/packages/twenty-server/src/engine/core-modules/auth/types/raw-auth-context.type.ts b/packages/twenty-server/src/engine/core-modules/auth/types/raw-auth-context.type.ts
index 0f31e1e6bc8..89cc4a3e7b8 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/types/raw-auth-context.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/types/raw-auth-context.type.ts
@@ -22,7 +22,6 @@ export type RawAuthContext = {
impersonatedUserWorkspaceId?: string;
};
tokenType?: JwtTokenTypeEnum;
- // When the user last proved their identity. Only sessions can express this:
- // a JWT's iat is its renewal time, not the moment the user authenticated.
+ // Sessions only: a JWT's iat is its renewal time, not when the user authenticated
authenticatedAt?: Date;
};
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/has-provisioned-sign-up-destination.util.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/has-provisioned-sign-up-destination.util.spec.ts
index fb21ca3e05f..c3d44e3f37e 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/has-provisioned-sign-up-destination.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/has-provisioned-sign-up-destination.util.spec.ts
@@ -17,8 +17,7 @@ describe('hasProvisionedSignUpDestination', () => {
).toBe(true);
});
- // Suspension is temporary and membership survives it, unlike a workspace
- // that was never provisioned.
+ // Suspension is temporary and membership survives it
it('should find a destination in a suspended workspace', () => {
expect(
hasProvisionedSignUpDestination([
@@ -39,8 +38,7 @@ describe('hasProvisionedSignUpDestination', () => {
).toBe(false);
});
- // Callers pass invitations to hidden workspaces straight in, so nothing here
- // may key off discoverability.
+ // Callers pass invitations to hidden workspaces straight in
it('should find a destination regardless of workspace discoverability', () => {
const hiddenWorkspaceInvitation = {
workspace: {
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/can-credential-auto-login-into-workspaces.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/can-credential-auto-login-into-workspaces.util.ts
index 89207fef676..b50834c08ca 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/utils/can-credential-auto-login-into-workspaces.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/can-credential-auto-login-into-workspaces.util.ts
@@ -4,9 +4,8 @@ import { isDefined } from 'twenty-shared/utils';
import { DEFAULT_WORKSPACE_AUTO_LOGIN_WINDOW } from 'src/engine/core-modules/auth/constants/default-workspace-auto-login-window.constant';
-// A workspace-agnostic session outlives a sign-out performed on a workspace
-// subdomain, since the workspace cannot clear a cookie it does not own, so
-// converting it into workspace access would hand the workspace back.
+// A workspace can't clear a cookie it doesn't own, so an agnostic session outlives a subdomain sign-out and,
+// converted into workspace access without a bound, would hand the workspace back
const DEFAULT_WORKSPACE_AUTO_LOGIN_WINDOW_MS = ms(
DEFAULT_WORKSPACE_AUTO_LOGIN_WINDOW,
);
@@ -26,16 +25,14 @@ export const canCredentialAutoLoginIntoWorkspaces = ({
return true;
}
- // Legacy JWT pairs carry no authentication time, so they keep the
- // pre-session behavior until the cutover retires them.
+ // Legacy JWT pairs carry no authentication time, so they keep pre-session behavior
if (!isDefined(authenticatedAt)) {
return true;
}
const parsedWindowMs = ms(autoLoginWindow);
- // An unparseable or negative window would silently drop the boundary or lock
- // everyone out. Zero is kept, since it deliberately turns the bridge off.
+ // An unparseable or negative window would drop the boundary or lock everyone out; zero deliberately turns the bridge off
const isUsableWindow =
Number.isFinite(parsedWindowMs) && (parsedWindowMs as number) >= 0;
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/get-sign-up-without-workspace-decision.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/get-sign-up-without-workspace-decision.util.ts
index b03b4e73ff4..bcaa19881ce 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/utils/get-sign-up-without-workspace-decision.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/get-sign-up-without-workspace-decision.util.ts
@@ -3,8 +3,7 @@ export type SignUpWithoutWorkspaceDecision =
| 'refused'
| 'requiresDestination';
-// Tri-state rather than a boolean so callers only pay for the destination
-// lookup on instances that restrict workspace creation.
+// Tri-state so callers only pay for the destination lookup on instances restricting workspace creation
export const getSignUpWithoutWorkspaceDecision = ({
isMultiWorkspaceEnabled,
isWorkspaceCreationLimitedToServerAdmins,
diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/commands/billing-sync-entitlements.command.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/commands/billing-sync-entitlements.command.ts
index 159dbdc8af0..9a7490fd8ef 100644
--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/commands/billing-sync-entitlements.command.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/commands/billing-sync-entitlements.command.ts
@@ -18,11 +18,7 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
-// Entitlements otherwise only ever arrive through the
-// entitlements.active_entitlement_summary.updated webhook. Stripe stops
-// retrying a failed delivery after a few days and a missing row reads as
-// denied, so without a reconciliation pass a dropped event silently removes a
-// paid feature until the customer's subscription happens to change again.
+// Stripe stops retrying failed webhooks and a missing entitlement reads as denied, so dropped events need reconciling
@Command({
name: 'billing:sync-entitlements',
description: 'Reconcile billing entitlements with Stripe for all workspaces',
@@ -47,8 +43,6 @@ export class BillingSyncEntitlementsCommand extends WorkspaceCommandRunner {
options,
index,
}: RunOnWorkspaceArgs): Promise<void> {
- // The Stripe client is only built when billing is enabled, so there is
- // nothing to reconcile against on a self-hosted instance.
if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
if (index === 0) {
this.logger.log(
diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-entitlement-sync.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-entitlement-sync.service.ts
index c45c1af6296..7e0afecc108 100644
--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-entitlement-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-entitlement-sync.service.ts
@@ -22,10 +22,7 @@ type EntitlementTransitionArgs = {
type SyncedEntitlement = { key: BillingEntitlementKey; value: boolean };
-// Shared by the Stripe webhook and the reconciliation command so a repaired
-// entitlement carries the same consequences as one that arrived on time.
-// Transitions are read from the stored rows rather than from Stripe's
-// previous_attributes, which the reconciliation path never has.
+// Transitions come from stored rows, not Stripe's previous_attributes, which reconciliation never has
@Injectable()
export class BillingEntitlementSyncService {
constructor(
@@ -42,10 +39,7 @@ export class BillingEntitlementSyncService {
stripeCustomerId,
activeLookupKeys,
}: EntitlementTransitionArgs): Promise<SyncedEntitlement[]> {
- // The whole transition is one unit. Reading the stored rows, acting on the
- // difference and committing it are three steps, and this service is the
- // only writer of those rows, so serializing here is what makes the
- // difference a transition rather than a guess about one.
+ // Serialized so read-diff-commit forms one transition; this service is the rows' only writer
return await this.cacheLockService.withLock(
() =>
this.applyEntitlementTransition({
@@ -80,11 +74,7 @@ export class BillingEntitlementSyncService {
billingEntitlements.find((entitlement) => entitlement.key === key)
?.value === true;
- // Counters accumulated while the limit was unenforced would otherwise be
- // charged against the workspace the moment the entitlement turns on. Done
- // before the rows are committed: a failure here then leaves the transition
- // unapplied and the next sync retries it, where committing first would make
- // every retry skip the reset and charge that usage.
+ // Unenforced counters would be charged on enable; reset before committing so a failed reset is retried
if (
!wasGranted(BillingEntitlementKey.USAGE_LIMIT) &&
isGranted(BillingEntitlementKey.USAGE_LIMIT)
@@ -107,14 +97,7 @@ export class BillingEntitlementSyncService {
'billingEntitlements',
]);
- // The opposite order to the reset above, because the unsafe direction is
- // reversed: predicates deleted while the row still grants RLS would leave
- // row filtering on with nothing to filter by. Query-time filtering reads
- // the predicate cache and never the entitlement, so committing the revoke
- // first is the direction that fails closed: a failure here leaves rows
- // filtered by predicates that outlived the feature, not unfiltered.
- // Asked on every pass rather than on the revoke transition, so a cleanup
- // that failed after the revoke committed is retried by the next sync.
+ // After the commit so a failure fails closed (rows stay filtered); checked every pass so a failed cleanup retries
if (!isGranted(BillingEntitlementKey.RLS)) {
await this.rowLevelPermissionPredicateGroupService.deleteAllRowLevelPermissionPredicateGroups(
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts
index b420bb8a5a9..828853e8169 100644
--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts
@@ -99,8 +99,7 @@ export class BillingWebhookInvoiceService {
await this.processRollover({
subscription,
- // Stripe's own clock, so it can be compared to the subscription's
- // boundaries without allowing for skew against ours.
+ // Stripe's own clock, comparable to subscription boundaries without skew
invoiceCreatedAt: new Date(invoiceCreatedAtInSeconds * 1000),
});
}
@@ -127,9 +126,7 @@ export class BillingWebhookInvoiceService {
subscription.id,
);
- // Skipping the transition leaves every grant of this workspace to reach its
- // expiry with nothing carrying the unspent part forward, so it is the one
- // early return here that costs the workspace credits it was given.
+ // Skipping the transition forfeits the unspent part of every grant of this workspace
if (!isDefined(params)) {
this.logger.error(
`Skipping credit rollover for workspace ${subscription.workspaceId}: subscription ${subscription.id} carries no priced resource credit item`,
@@ -144,8 +141,7 @@ export class BillingWebhookInvoiceService {
subscriptionCurrentPeriodEnd: subscription.currentPeriodEnd,
});
- // Only needed while subscriptions that predate previousPeriodStart are
- // still transitioning for the first time.
+ // Only needed while subscriptions predating previousPeriodStart transition for the first time
const ledgerPeriodStart =
await this.billingCreditGrantService.findPeriodStartBefore({
workspaceId: subscription.workspaceId,
@@ -167,9 +163,7 @@ export class BillingWebhookInvoiceService {
ledgerPeriodStart,
});
- // Credits earned during the trial follow the workspace into its first paid
- // period, so the trial closes like any other period. Its allowance comes
- // from config rather than the price, which only applies once paid.
+ // Trial credits carry into the first paid period; the trial allowance comes from config, not the price
const closingAllowanceMicro = isFirstPeriodAfterTrial
? this.billingUsageService.getTrialResourceUsageCap(subscription)
: params.tierQuantity;
@@ -200,9 +194,7 @@ export class BillingWebhookInvoiceService {
);
}
- // Paying a past-due invoice won't reactivate the subscription if Stripe
- // already generated a draft for the next period. Finalize it so Stripe
- // can collect payment and resume the subscription.
+ // Stripe won't reactivate on a paid past-due invoice while a next-period draft exists
await this.finalizePastDueDraftInvoicesAfterPaidInvoice(
stripeSubscriptionId,
paidInvoicePeriodEnd,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
index 8626820ee4e..0faae6903c0 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
@@ -33,8 +33,7 @@ import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
-// Belt-and-suspenders on top of LogicFunctionExecutorService's execution
-// throttle: application-access tokens are JWTs usable outside the runtime.
+// On top of the executor's throttle: application-access tokens are JWTs usable outside the runtime
const APP_BILLING_CHARGE_THROTTLE_LIMIT = 1000;
const APP_BILLING_CHARGE_THROTTLE_TTL_MS = 60_000;
@@ -71,10 +70,7 @@ export class AppBillingController {
private readonly twentyConfigService: TwentyConfigService,
) {}
- // Lets an app ask the question the platform already asks before AI, workflow
- // and email work, so it can stop up front instead of failing partway through
- // on a downstream call it did not write. Returns the verdict and a reason,
- // never a balance: an app has no business reading what the workspace pays.
+ // Lets an app check credits before starting work; returns a verdict, never a balance an app has no business reading
@Get('credits')
async credits(@Req() request: Request): Promise<CreditAvailability> {
if (!isDefined(request.application) || !isDefined(request.workspace)) {
@@ -113,14 +109,12 @@ export class AppBillingController {
@Req() request: Request,
@Body() charge: ChargeDto,
): Promise<void> {
- // Billing disabled: no listener consumes the event — fail fast so apps
- // don't silently discard charges on Community instances.
+ // Without billing no listener consumes the event, so fail fast rather than silently drop charges
if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
throw new NotFoundException();
}
- // Reject user-access / api-key tokens — only application-access tokens
- // populate `request.application`.
+ // Only application-access tokens populate `request.application`
if (!isDefined(request.application) || !isDefined(request.workspace)) {
throw new ForbiddenException(
'App billing endpoint requires an APPLICATION_ACCESS token.',
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
index ec2d8d61c75..67a22579e76 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
@@ -23,9 +23,8 @@ import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/works
type AppChargeableOperationType =
(typeof UsageOperationType)[UsageOperationTypeValue];
-// An app sends a quantity and never a unit, so the platform names what the
-// number counts. Keyed on the app-facing vocabulary, so adding a value to
-// twenty-shared's USAGE_OPERATION_TYPES fails to compile until it has a unit.
+// Apps send a quantity, never a unit, so the platform names what it counts.
+// Keyed on the app-facing vocabulary so a new USAGE_OPERATION_TYPES value fails to compile until it has a unit
const USAGE_UNIT_BY_OPERATION_TYPE: Record<
AppChargeableOperationType,
UsageUnit
@@ -39,9 +38,7 @@ const USAGE_UNIT_BY_OPERATION_TYPE: Record<
[UsageOperationType.EMAIL_SEND]: UsageUnit.INVOCATION,
};
-// `workspaceId` + `applicationId` come from the application-access token,
-// never from the body — an app can't charge a different workspace or
-// masquerade as a different app.
+// workspaceId and applicationId come from the token, never the body, so an app can't charge another workspace or pose as another app
@Injectable()
export class AppBillingService {
private readonly logger = new Logger(AppBillingService.name);
@@ -138,8 +135,7 @@ export class AppBillingService {
);
// Undefined until the upgrade that adds the column has run.
const billableOperations = application?.billing?.operations ?? {};
- // Own-property only: an operation named `constructor` or `__proto__` would
- // otherwise resolve to an inherited value and charge under no category.
+ // Own-property only: `constructor` or `__proto__` would resolve to inherited values and charge under no category
const billableOperation = Object.prototype.hasOwnProperty.call(
billableOperations,
charge.operation,
@@ -153,25 +149,19 @@ export class AppBillingService {
);
}
- // `operations` is jsonb, so the declaration is untrusted at the point it is
- // used however the manifest typed it. An unknown value indexes the enum to
- // undefined and records a row with no category and no unit, and a
- // platform-only value like SUBSCRIPTION would let the declared-operation
- // path raise what ChargeDto's @IsIn stops an app raising directly.
+ // jsonb is untrusted: an unknown value would record a row with no category or unit,
+ // and a platform-only value like SUBSCRIPTION would bypass ChargeDto's @IsIn
if (!isUsageOperationTypeValue(billableOperation.operationType)) {
throw new BadRequestException(
`Billable operation "${charge.operation}" declares an unknown operationType.`,
);
}
- // Indexing the enum by the manifest literal is also what stops
- // twenty-shared's USAGE_OPERATION_TYPES from promising apps a category the
- // platform does not meter: a drifted value fails to compile here.
+ // Indexing by the manifest literal makes a drifted USAGE_OPERATION_TYPES value fail to compile
return UsageOperationType[billableOperation.operationType];
}
- // Scoped to the token's workspace, so an app cannot attribute its spend to
- // someone outside the workspace its token was issued for.
+ // Scoped to the token's workspace so an app cannot attribute spend outside it
private async findWorkspaceScopedUserWorkspaceId({
workspaceId,
userWorkspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
index 09731e4f1cc..697b7393881 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
@@ -18,10 +18,8 @@ import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
-// Flat fees and per-seat fees an app declares in its manifest, raised by the
-// platform once per billing period as ordinary credit usage. Recording through
-// the same usage path as app-initiated charges is what makes them show up in
-// Usage by App and on the credit meter without any separate plumbing.
+// Manifest-declared flat and per-seat fees, raised once per billing period through the app-charge usage path
+// so they appear in Usage by App and on the credit meter
@Injectable()
export class ApplicationRecurringChargeService {
private readonly logger = new Logger(ApplicationRecurringChargeService.name);
@@ -56,19 +54,13 @@ export class ApplicationRecurringChargeService {
this.reportRejectedCharges(workspaceId, malformedCharges);
- // Reading what the period already carries costs a ClickHouse query per
- // workspace per day, so it waits until an app actually declares something.
+ // Bail before the already-charged lookup, which costs a ClickHouse query per workspace per day
if (declaredCharges.length === 0) {
return 0;
}
- // A MONTH charge on a yearly subscription would be raised once a year, not
- // twelve times, so it is skipped rather than silently under-charged. Only
- // reached once an app actually declares one, so the workspaces this is said
- // about are the ones running an app that expects to be paid and is not.
- // Reported at the level and cadence of a successful raise rather than as a
- // warning: the condition is by design and unchanging, so a daily warning
- // would only teach people to ignore it.
+ // Skipped rather than under-charged: a MONTH charge would be raised once a year
+ // Logged, not warned: the condition is by design, so a daily warning would be ignored
if (currentBillingSubscription.interval !== SubscriptionInterval.Month) {
this.logger.log(
`Skipped ${declaredCharges.length} recurring app charge(s) for workspace ${workspaceId}: the workspace is on a ${currentBillingSubscription.interval} subscription and only MONTH charges can be raised`,
@@ -120,8 +112,7 @@ export class ApplicationRecurringChargeService {
return events.length;
}
- // A refused charge means an installed app is not being billed for the period,
- // which is invisible to everyone unless it is said out loud.
+ // Logged as errors: otherwise an installed app going unbilled is invisible to everyone
private reportRejectedCharges(
workspaceId: string,
rejectedCharges: RejectedRecurringCharge[],
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job.ts
index 8d45d6a83f2..bb6872c10d3 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job.ts
@@ -14,9 +14,7 @@ import { Processor } from 'src/engine/core-modules/message-queue/decorators/proc
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-// Daily rather than monthly: the charge is keyed to the workspace's own billing
-// period, which starts on a different day for every workspace, and the service
-// skips periods it has already charged.
+// Daily: each workspace's billing period starts on its own day, and charged periods are skipped
export const APPLICATION_RECURRING_CHARGE_CRON_PATTERN = '0 5 * * *';
const WORKSPACE_BATCH_SIZE = 10;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts
index b24abb860b7..5234501f809 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts
@@ -17,8 +17,7 @@ import {
} from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
-// $1000 in micro-credits (1 USD = 1_000_000 micro-credits). Bounds a single
-// charge so a compromised or buggy app can't drain credits in one request.
+// $1000 in micro-credits, so a compromised or buggy app can't drain credits in one request
const MAX_CREDITS_USED_MICRO_PER_CHARGE = 1_000_000_000;
const MAX_QUANTITY_PER_CHARGE = 10_000;
@@ -33,15 +32,12 @@ export class ChargeDto {
@Max(MAX_QUANTITY_PER_CHARGE)
quantity!: number;
- // An operation name declared in `billing.operations` on the application
- // manifest; the server resolves its billing category and its label.
+ // Declared in the manifest's `billing.operations`; the server resolves its category and label
@IsOptional()
@IsString()
operation?: string;
- // Applications that declare no billable operations name the platform billing
- // category directly. Restricted to the app-facing vocabulary in
- // twenty-shared, so platform-raised categories cannot be charged by an app.
+ // For apps declaring no operations; restricted so platform-raised categories cannot be charged
@ValidateIf((charge: ChargeDto) => !isDefined(charge.operation))
@IsIn(USAGE_OPERATION_TYPES)
operationType?: UsageOperationTypeValue;
@@ -50,8 +46,7 @@ export class ChargeDto {
@IsString()
resourceContext?: string;
- // Webhook and cron runs carry no triggering person on the token, so an app
- // that knows who the spend belongs to names them here instead.
+ // Webhook and cron runs carry no triggering person on the token, so the app names who the spend belongs to
@IsOptional()
@IsUUID()
userWorkspaceId?: string;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/build-recurring-charge-usage-events.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/build-recurring-charge-usage-events.util.spec.ts
index 48706d82a51..9631a739797 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/build-recurring-charge-usage-events.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/build-recurring-charge-usage-events.util.spec.ts
@@ -127,8 +127,7 @@ describe('buildRecurringChargeUsageEvents', () => {
).toEqual([]);
});
- // The declared rate is bounded per member, but the member count is not, so a
- // legitimate rate can still multiply past what the platform will debit.
+ // The rate is bounded per member, but the member count is not
it('should drop a per member charge whose multiplied total exceeds the period maximum', () => {
const { events, rejectedCharges } = buildRecurringChargeUsageEvents({
dueCharges: [SEAT_CHARGE],
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-declared-recurring-charges.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-declared-recurring-charges.util.spec.ts
index 333837cdba9..ea7c8f8b0fe 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-declared-recurring-charges.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-declared-recurring-charges.util.spec.ts
@@ -32,8 +32,7 @@ const SEAT_FEE = {
label: 'Per member',
} as const;
-// The column is jsonb, so a declaration reaching the raise path is untrusted
-// whatever the RecurringCharge type claims.
+// The column is jsonb, so declarations are untrusted whatever the type claims
const collectOne = (charge: unknown) =>
collectDeclaredRecurringCharges({
flatApplicationMaps: buildFlatApplicationMaps([
@@ -140,8 +139,7 @@ describe('collectDeclaredRecurringCharges', () => {
expect(declaredCharges).toEqual([]);
});
- // A negative amount would subtract from the period's usage sum, handing the
- // workspace credits rather than charging it.
+ // A negative amount would credit the workspace rather than charge it
it('should reject a negative amount rather than crediting the workspace', () => {
const { declaredCharges, rejectedCharges } = collectOne({
...PLATFORM_FEE,
@@ -190,8 +188,7 @@ describe('collectDeclaredRecurringCharges', () => {
]);
});
- // An array is typeof 'object', so without an explicit check Object.entries
- // would bill each element under its numeric index.
+ // Arrays are typeof 'object', so Object.entries would bill each element by index
it('should ignore a recurring block that is an array rather than a map', () => {
const { declaredCharges, rejectedCharges } =
collectDeclaredRecurringCharges({
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util.ts
index 1b4168c25de..4d8b341e013 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util.ts
@@ -22,14 +22,8 @@ export type BuildRecurringChargeUsageEventsResult = {
rejectedCharges: RejectedRecurringCharge[];
};
-// A per-member charge multiplies by the member count at the moment the period is
-// raised, so a workspace with no members raises nothing rather than a zero-credit
-// row that would still count as charged and suppress the next attempt.
-//
-// The declared rate is already bounded per unit, but the member count is not, so
-// the multiplied total is bounded again here. Over-cap charges are dropped
-// rather than clamped: raising a different amount than the app declared would be
-// a silent mispricing, where dropping leaves the period unraised and reportable.
+// No members raises nothing: a zero-credit row would count as charged and suppress the next attempt
+// Over-cap totals are dropped, not clamped: raising another amount than declared is silent mispricing
export const buildRecurringChargeUsageEvents = ({
dueCharges,
workspaceMemberCount,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util.ts
index bc7a78043fd..e82c56ae0e0 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util.ts
@@ -30,18 +30,7 @@ type CollectDeclaredRecurringChargesParams = {
flatApplicationMaps: FlatApplicationCacheMaps;
};
-// The recurring charges installed applications declare, read straight from the
-// already-loaded cache. Uninstalled applications are skipped so a removed app
-// stops billing from the next period; the period it was removed in was already
-// raised. Collected before the already-charged lookup so a workspace whose apps
-// declare nothing costs no ClickHouse read.
-//
-// `billing` is jsonb, so a declaration is untrusted input however it got there:
-// the manifest is persisted without a shape check, and nothing stops a row
-// being written by another route. Every declaration is validated here, at the
-// point the platform decides to debit, rather than relying on the SDK having
-// validated it at build time. A rejected declaration is returned rather than
-// dropped silently so the caller can report an app that will not be billed.
+// `billing` is jsonb persisted without a shape check, so declarations are validated here, at the point of debit
export const collectDeclaredRecurringCharges = ({
flatApplicationMaps,
}: CollectDeclaredRecurringChargesParams): CollectDeclaredRecurringChargesResult => {
@@ -57,8 +46,7 @@ export const collectDeclaredRecurringCharges = ({
const billing: ApplicationBilling = application.billing ?? {};
const recurring = billing.recurring;
- // An array is typeof 'object', and Object.entries would then bill each
- // element under its numeric index as if it were a charge name.
+ // Arrays are typeof 'object': Object.entries would bill each element by index
if (
!isDefined(recurring) ||
typeof recurring !== 'object' ||
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util.ts
index 74fad3a10d9..3b59377afd5 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util.ts
@@ -8,9 +8,7 @@ type CollectDueRecurringChargesParams = {
alreadyChargedKeys: Set<string>;
};
-// The declared charges this period does not already carry. The usage row is its
-// own record of the charge, so keying on application and charge is what keeps
-// the daily job idempotent without separate bookkeeping.
+// The usage row is its own record of the charge, which keeps the daily job idempotent
export const collectDueRecurringCharges = ({
declaredCharges,
alreadyChargedKeys,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts
index 8546b9824fb..2108f03439a 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts
@@ -26,8 +26,7 @@ export class BillingSubscriptionItemResolver {
constructor(
private readonly billingUsageService: BillingUsageService,
- // Field resolver: the workspace is discovered from the parent item's
- // subscription row, so it cannot be an input here.
+ // Field resolver: the workspace comes from the parent item's subscription row
// eslint-disable-next-line twenty/prefer-workspace-scoped-repository
@InjectRepository(BillingSubscriptionEntity)
private readonly billingSubscriptionRepository: Repository<BillingSubscriptionEntity>,
@@ -35,9 +34,7 @@ export class BillingSubscriptionItemResolver {
private readonly billingPriceRepository: Repository<BillingPriceEntity>,
) {}
- // What this item is actually charged and grants, which is not what the plan
- // catalog says once pricing changes: superseded prices keep billing the
- // workspaces already on them, and are dropped from the catalog once archived.
+ // Not the catalog: superseded prices keep billing existing workspaces and leave the catalog once archived
@ResolveField(() => Number, { nullable: true })
async unitAmount(
@Parent() billingSubscriptionItem: BillingSubscriptionItemEntity,
@@ -70,9 +67,7 @@ export class BillingSubscriptionItemResolver {
return Number.isFinite(creditAmount) ? creditAmount : null;
}
- // currentWorkspace loads the item's product with its prices, so the common
- // path resolves in memory rather than one query per item on app boot. Other
- // callers load the subscription without relations and still need the read.
+ // currentWorkspace preloads product prices so app boot resolves in memory; other callers load no relations and need the query
private async findItemPrice(
billingSubscriptionItem: BillingSubscriptionItemEntity,
): Promise<BillingPriceEntity | null> {
@@ -90,10 +85,7 @@ export class BillingSubscriptionItemResolver {
);
}
- // Derived from the live credit balance instead of read from the stored
- // column: a persisted flag that every balance-mutating path must remember to
- // sync drifts as soon as one path misses, and a workspace stuck with a stale
- // flag gets refused with no banner explaining why.
+ // Derived from the live balance: a stored flag drifts as soon as one balance-mutating path misses it
@ResolveField(() => Boolean)
async hasReachedCurrentPeriodCap(
@Parent() billingSubscriptionItem: BillingSubscriptionItemEntity,
@@ -105,11 +97,7 @@ export class BillingSubscriptionItemResolver {
return false;
}
- // This field rides on the currentWorkspace query, which is app boot: a
- // billing read failure (stale period right after a rollover, ClickHouse or
- // Redis unavailable) must degrade to "no banner", never fail the query.
- // Failing open matches the usage gate, whose availability checks also fail
- // open so telemetry never blocks a paying customer.
+ // Rides on currentWorkspace (app boot): a billing read failure must degrade to no banner, never fail the query
try {
const billingSubscription =
await this.billingSubscriptionRepository.findOne({
diff --git a/packages/twenty-server/src/engine/core-modules/billing/constants/__tests__/billing-entitlement-state-lock-options.constant.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/constants/__tests__/billing-entitlement-state-lock-options.constant.spec.ts
index a834b1da2d5..c51dae861ce 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/constants/__tests__/billing-entitlement-state-lock-options.constant.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/constants/__tests__/billing-entitlement-state-lock-options.constant.spec.ts
@@ -6,9 +6,7 @@ describe('BILLING_ENTITLEMENT_STATE_LOCK_OPTIONS', () => {
it('waits past the expiry so a waiter can take a key its holder abandoned', () => {
const { ttl, ms, maxRetries } = BILLING_ENTITLEMENT_STATE_LOCK_OPTIONS;
- // withLock attempts at 0, ms, 2*ms ... (maxRetries - 1) * ms, so a budget
- // that only equals the expiry makes its last attempt just before the key
- // frees. Tuning either number without the other reintroduces that.
+ // withLock's last attempt is at (maxRetries - 1) * ms, just before an expiry-equal budget frees the key
const lastAttemptAt = (maxRetries - 1) * ms;
expect(lastAttemptAt).toBeGreaterThan(ttl);
diff --git a/packages/twenty-server/src/engine/core-modules/billing/constants/billing-entitlement-state-lock-options.constant.ts b/packages/twenty-server/src/engine/core-modules/billing/constants/billing-entitlement-state-lock-options.constant.ts
index b3a6822222d..db7cc971053 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/constants/billing-entitlement-state-lock-options.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/constants/billing-entitlement-state-lock-options.constant.ts
@@ -2,16 +2,8 @@
import { type CacheLockOptions } from 'src/engine/core-modules/cache-lock/cache-lock.service';
-// The default 5.5s expiry is shorter than this transition can run: revoking
-// RLS recomputes the workspace's role and predicate caches, which is unbounded
-// in the workspace's size. A lock that expires mid-transition hands the key to
-// a second sync and restores the races this lock exists to remove.
-//
-// maxRetries * ms must stay above ttl. withLock attempts at 0, ms, 2*ms and so
-// on, so a waiter whose budget only equals the expiry makes its last attempt
-// just before the key frees and throws instead of taking it, which is exactly
-// the case that matters: a holder that died leaves the key held for the full
-// expiry. The extra retries buy a waiter attempts on the far side of it.
+// Above the default 5.5s expiry: revoking RLS recomputes caches unbounded in workspace size
+// maxRetries * ms must stay above ttl, or a waiter gives up just before a dead holder's key frees
export const BILLING_ENTITLEMENT_STATE_LOCK_OPTIONS = {
ttl: 60_000,
ms: 500,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-credit-grant.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-credit-grant.entity.ts
index a5418efe73e..d16651cae98 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-credit-grant.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-credit-grant.entity.ts
@@ -39,12 +39,8 @@ export class BillingCreditGrantEntity extends WorkspaceRelatedEntity {
@Column({ nullable: false, type: 'timestamptz' })
effectiveAt: Date;
- // A tombstone rather than a deadline: null while the credits are spendable,
- // then the instant they stopped being. Writing a future expiry at grant time
- // would put the balance at the mercy of the period transition running, and a
- // transition that never fires would delete credits nobody spent. Only an
- // operator asking for a time-boxed grant sets one in advance, and that date
- // caps how long the available credit count may stay cached.
+ // A tombstone: null while spendable, then when they stopped being. A preset expiry would lose unspent credits if a transition never ran,
+ // so only operator time-boxed grants set one ahead, and that date caps how long the available credit count is cached.
@Column({ nullable: true, type: 'timestamptz' })
expiresAt: Date | null;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts
index 841c2fa911c..22479e95039 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts
@@ -17,14 +17,13 @@ import {
import type Stripe from 'stripe';
-// Serialized types for JSONB storage - uses Stripe's enum types but normalizes expandable fields
-// These avoid TypeORM's DeepPartialEntity issues with Stripe's expandable object types (e.g. Stripe.Account)
+// Normalizes Stripe's expandable fields, which break TypeORM's DeepPartialEntity
export type AutomaticTaxJson = {
disabled_reason: Stripe.Subscription.AutomaticTax['disabled_reason'];
enabled: boolean;
liability: {
type: Stripe.Subscription.AutomaticTax.Liability.Type;
- account?: string; // Normalized: always string ID, never expanded Stripe.Account
+ account?: string;
} | null;
};
@@ -132,12 +131,8 @@ export class BillingSubscriptionEntity extends WorkspaceRelatedEntity {
})
currentPeriodStart: Date;
- // Where the period before the current one began. Stripe only ever reports the
- // current window, so once currentPeriodStart advances the previous boundary
- // is unrecoverable: calendar arithmetic clamps month-end anchors, and the
- // ledger only shows it when the last transition happened to close a grant.
- // Written whenever the period moves, and read by the rollover to bound the
- // usage it settles.
+ // Stripe only reports the current window, so the previous boundary is unrecoverable once it advances;
+ // written whenever the period moves, and read by the rollover to bound the usage it settles
@Column({ nullable: true, type: 'timestamptz' })
previousPeriodStart: Date | null;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts
index 5045220892e..261a2ec9c36 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts
@@ -2,8 +2,7 @@
import { registerEnumType } from '@nestjs/graphql';
-// Why a workspace was given credits, not how. Whether a human wrote the grant
-// is already on the row as grantedByUserId, so there is no "manual" type.
+// No "manual" type: whether a human wrote the grant is grantedByUserId
export enum BillingCreditGrantType {
ROLLOVER = 'ROLLOVER',
ONBOARDING_REWARD = 'ONBOARDING_REWARD',
@@ -16,17 +15,11 @@ registerEnumType(BillingCreditGrantType, {
description: 'The origin of a batch of credits granted to a workspace',
});
-// Only ROLLOVER credits are capped when they carry over to the next period.
-// Credits we granted deliberately (compensation, sales, onboarding rewards)
-// keep their full value until spent or expired.
export const CAPPED_BILLING_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [
BillingCreditGrantType.ROLLOVER,
];
-// What an operator may write by hand. ROLLOVER belongs to the period
-// transition and ONBOARDING_REWARD to the onboarding jobs, so granting either
-// by hand would change carry-forward behaviour and misclassify the audit
-// trail.
+// ROLLOVER and ONBOARDING_REWARD belong to their jobs: by hand they would change carry-forward and the audit trail
export const ADMIN_GRANTABLE_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [
BillingCreditGrantType.COMPENSATION,
BillingCreditGrantType.SALES,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/reminders/services/billing-reminder.service.ts b/packages/twenty-server/src/engine/core-modules/billing/reminders/services/billing-reminder.service.ts
index 76aaf0d7ed8..42657190799 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/reminders/services/billing-reminder.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/reminders/services/billing-reminder.service.ts
@@ -32,7 +32,7 @@ import { UserService } from 'src/engine/core-modules/user/services/user.service'
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
-// Reminders the cron can send. A given trial gets exactly one of "ending" / "converting".
+// A given trial gets exactly one of "ending" / "converting"
type BillingReminderEmail =
| { type: 'trial-ending'; trialEndsAt: Date }
| { type: 'trial-converting'; trialEndsAt: Date; interval: 'month' | 'year' }
@@ -183,11 +183,8 @@ export class BillingReminderService {
return false;
}
- // Fallback when the payment-method flag isn't synced yet: a with-credit-card trial
- // is longer than a no-credit-card one, so the trial duration disambiguates. Fall back
- // to createdAt when trialStart is missing so this still holds during sync gaps —
- // otherwise a real card-on-file trial could be misread as no-card and wrongly told
- // "no card will be charged" right before it is actually charged.
+ // Unsynced payment-method flag: card trials are longer, so trial length tells them apart. createdAt covers a
+ // missing trialStart, else a card trial could be told "no card will be charged" right before it is charged
const withoutCardTrialDurationDays = this.twentyConfigService.get(
'BILLING_FREE_TRIAL_WITHOUT_CREDIT_CARD_DURATION_IN_DAYS',
);
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts
index d23694ee6af..8b96b31a4eb 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts
@@ -19,8 +19,7 @@ export type CreateBillingCreditGrantParams = {
amountMicro: number;
type: BillingCreditGrantType;
effectiveAt: Date;
- // Null means the credits stay spendable until something settles them, which
- // is the default. See the entity for why an expiry is a tombstone here.
+ // Null keeps the credits spendable until something settles them
expiresAt: Date | null;
reason?: string | null;
grantedByUserId?: string | null;
@@ -28,9 +27,7 @@ export type CreateBillingCreditGrantParams = {
sourceGrantId?: string | null;
};
-// Owns the billingCreditGrant table. Deliberately free of side effects so that
-// read paths (available credits) can depend on it without pulling in the cache
-// and subscription services that BillingCreditService needs.
+// Side-effect free so read paths can depend on it without BillingCreditService's cache and subscription deps
@Injectable()
export class BillingCreditGrantService {
constructor(
@@ -38,8 +35,7 @@ export class BillingCreditGrantService {
private readonly billingCreditGrantRepository: WorkspaceScopedRepository<BillingCreditGrantEntity>,
) {}
- // Returns null when idempotencyKey has already been used, so callers can tell
- // a fresh grant from a replayed one.
+ // Null when idempotencyKey was already used
async createGrant(
params: CreateBillingCreditGrantParams,
entityManager?: EntityManager,
@@ -72,10 +68,7 @@ export class BillingCreditGrantService {
const repository = this.getRepository(entityManager);
- // Idempotency is enforced by letting Postgres drop the duplicate rather
- // than by catching the unique violation: the rollover inserts inside a
- // transaction, where a raised constraint error would abort every write
- // that came before it.
+ // orIgnore drops duplicates: a caught unique violation would abort every earlier write in the rollover transaction
const { raw } = await repository
.createQueryBuilder()
.insert()
@@ -101,8 +94,7 @@ export class BillingCreditGrantService {
return null;
}
- // Read back rather than returning the raw row, which skips the bigint
- // transformer and would hand callers amountMicro as a string.
+ // Read back: the raw row skips the bigint transformer and holds amountMicro as a string
return repository.findOne(workspaceId, { where: { id: grantId } });
}
@@ -115,10 +107,7 @@ export class BillingCreditGrantService {
return balanceMicro;
}
- // One statement, so the balance and the expiry that bounds its validity come
- // from the same snapshot: read separately, a grant lapsing between the two
- // reads is counted in the balance yet missing from the expiry, and the
- // counter would keep its credits spendable until the period ends.
+ // One statement so the balance and its bounding expiry come from the same snapshot
async getActiveCreditBalance({
workspaceId,
boundary,
@@ -151,8 +140,7 @@ export class BillingCreditGrantService {
const balanceMicro = Number(result?.total ?? 0);
- // Rounding a balance would hand out or withhold credits that were never
- // granted, so refuse rather than serve a number we cannot represent.
+ // Refuse rather than round: rounding would hand out or withhold credits never granted
if (!Number.isSafeInteger(balanceMicro)) {
throw new BillingException(
`Credit balance for workspace ${workspaceId} is not a safe integer (${balanceMicro})`,
@@ -197,11 +185,8 @@ export class BillingCreditGrantService {
});
}
- // The previous transition pulled every grant it closed back to the instant
- // the period ended, so the ledger records where the closing period started.
- // Calendar arithmetic cannot recover it once the subscription has moved on:
- // a month-end anchor clamps, and subtracting a month from February 28 gives
- // January 28 rather than the January 31 the period actually started on.
+ // The previous transition expired its grants at its period end, so the ledger holds the period start;
+ // calendar arithmetic can't recover it, as month-end anchors clamp (Feb 28 minus a month is Jan 28)
async findPeriodStartBefore({
workspaceId,
boundary,
@@ -218,10 +203,7 @@ export class BillingCreditGrantService {
return row?.expiresAt ?? null;
}
- // Settles every grant the closing period could still spend, so that the
- // carry-forward rows written next in the same transaction are the only ones
- // left live. Matched by predicate rather than by id so a grant created while
- // the transition runs is covered too.
+ // Settles every grant the closing period could spend so only the carry-forward rows stay live; by predicate, not id, to cover mid-transition grants
async closeGrantsAtPeriodEnd(
{
workspaceId,
@@ -234,9 +216,7 @@ export class BillingCreditGrantService {
): Promise<void> {
const repository = this.getRepository(entityManager);
- // The OR keeps an operator-set expiry already inside the period alone,
- // which it has to stay: stamping it forward would hand back credits that
- // had lapsed before the boundary.
+ // The OR leaves an operator-set expiry inside the period alone, or lapsed credits would come back
await repository
.createQueryBuilder()
.update()
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts
index 2fd63ee5100..a8520355334 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts
@@ -29,8 +29,7 @@ type ProcessRolloverParams = {
nextAllowanceMicro: number;
};
-// The transition writes more rows than a single grant does, so it is given more
-// room than the lock's default before it gives up.
+// The transition writes more rows than a single grant, so it gets more lock room than the default
const ROLLOVER_LOCK_OPTIONS = { ms: 200, maxRetries: 50, ttl: 30_000 };
@Injectable()
@@ -50,9 +49,7 @@ export class BillingCreditRolloverService {
): Promise<void> {
const { workspaceId, closingPeriodStart, closingPeriodEnd } = params;
- // Read outside the lock: usage comes from ClickHouse and no credit write
- // can change it, so paying that latency while holding the lock would only
- // stall concurrent grants.
+ // Outside the lock: no credit write changes ClickHouse usage, and its latency would stall grants
const usageMicro =
await this.billingUsageService.getCreditsUsedBetweenOrNull({
workspaceId,
@@ -60,12 +57,7 @@ export class BillingCreditRolloverService {
to: closingPeriodEnd,
});
- // Reading usage as zero when the query failed would roll a full unused
- // allowance over to every workspace invoiced during the outage. Throwing
- // fails the webhook so Stripe redelivers it; returning normally would
- // answer 200 and the transition would never run, closing no grants and
- // carrying nothing forward, so the workspace silently loses its balance
- // at expiry.
+ // Throw so Stripe redelivers: zero usage would roll a full allowance over, and a 200 never reruns the transition
if (!isDefined(usageMicro)) {
throw new BillingException(
`Cannot roll credits over for workspace ${workspaceId}: usage for the period starting ${closingPeriodStart.toISOString()} could not be read`,
@@ -73,9 +65,7 @@ export class BillingCreditRolloverService {
);
}
- // Everything from here reads the ledger, decides from that snapshot, then
- // writes it back. A grant landing in between would either be carried twice
- // or dropped, so the whole read-decide-write runs alone.
+ // Read-decide-write runs alone: a grant landing in between would be carried twice or dropped
await this.cacheLockService.withLock(
() => this.carryGrantsForward({ ...params, usageMicro }),
buildBillingCreditStateLockKey(workspaceId),
@@ -92,9 +82,7 @@ export class BillingCreditRolloverService {
'BILLING_ROLLOVER_TOTAL_CAP_MULTIPLIER',
);
- // Closing the old grants and writing their successors is one settlement:
- // committing the first half alone would leave the workspace with every
- // grant closed and nothing carrying the unspent part forward.
+ // One transaction: closing grants without their successors loses the unspent credits
await this.dataSource.transaction(async (entityManager) =>
this.settleGrants({
...params,
@@ -157,14 +145,9 @@ export class BillingCreditRolloverService {
type: carryForwardGrant.type,
sourceGrantId: carryForwardGrant.sourceGrantId,
effectiveAt: nextPeriodStart,
- // Null for everything but a time-boxed grant, whose deadline the
- // successor inherits. Stamping the period end here instead would make
- // every balance depend on the next transition running, which is the
- // failure this settlement exists to survive.
+ // Inherited rather than stamped with the period end: balances must not depend on the next transition running
expiresAt: carryForwardGrant.expiresAt,
- // Pinned to UTC: Stripe's boundaries are UTC instants, and a
- // midnight boundary rendered in the server's local zone dates to the
- // previous day.
+ // UTC: Stripe boundaries are UTC instants, and local-zone midnight dates to the previous day
reason: `Carried over from the period starting ${i18n.date(
closingPeriodStart,
{ day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' },
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts
index 279ec795a44..12b3df4b785 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts
@@ -28,10 +28,7 @@ type GrantCreditsParams = {
grantedByUserId?: string | null;
idempotencyKey?: string | null;
effectiveAt?: Date;
- // Only set for a deliberately time-boxed grant. Left out, the credits stay
- // spendable until a period transition settles them. Taken as the operator's
- // intent rather than a date so that the alignment onto a period end happens
- // here, where the invariant belongs, whoever the caller is.
+ // Only for time-boxed grants (unset: spendable until a transition settles them); a day count so period-end alignment happens here for every caller
expiresInDays?: number | null;
sourceGrantId?: string | null;
};
@@ -76,10 +73,7 @@ export class BillingCreditService {
const effectiveAt = params.effectiveAt ?? new Date();
- // A replay answers with what the first attempt wrote, so the operator's
- // intent is never re-derived: the subscription that anchored the original
- // expiry may have been canceled since, and the insert would discard the
- // answer anyway.
+ // A replay answers with the first write instead of re-deriving the expiry: its anchoring subscription may be gone
const knownGrant = await this.findGrantByIdempotencyKey(params);
const grant = isDefined(knownGrant)
@@ -95,11 +89,7 @@ export class BillingCreditService {
}),
});
- // Answers with the row that already exists rather than null, so a caller
- // recovering from a lost response does not have to look it up again. Read
- // again when the check above came back empty: the insert still reported a
- // duplicate, so another attempt won the key between the two, and only the
- // second read can see it.
+ // Returns the existing row, not null; reread when the check above was empty, as another attempt won the key in between
if (!isDefined(grant)) {
const alreadyWrittenGrant =
knownGrant ?? (await this.findGrantByIdempotencyKey(params));
@@ -181,19 +171,10 @@ export class BillingCreditService {
}
}
-// Exact 24-hour days rather than calendar ones: the result is only ever
-// compared against UTC period boundaries, and local-time day arithmetic drifts
-// by an hour across a DST change.
+// Exact 24-hour days: local-time day arithmetic drifts by an hour across DST
const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
-// Null unless the caller asked for a time-boxed grant, and then a period end
-// rather than the exact day, for the reasons alignGrantExpiryToPeriodEnd
-// documents.
-//
-// Refuses rather than falling back to null when there is no period to align to:
-// returning null there would read as "no expiry" and hand out credits that
-// never lapse, which is the opposite of what was asked for and cannot be
-// noticed from the result.
+// Throws with no period to align to: null would read as credits that never lapse
const resolveGrantExpiry = ({
effectiveAt,
expiresInDays,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
index 03dfa91cd57..eb0fdf9345b 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
@@ -222,9 +222,7 @@ export class BillingPortalWorkspaceService {
};
}
- // A failed earlier attempt leaves an incomplete subscription; it must not
- // count, or a retry would be charged immediately instead of getting the
- // trial. Only a real (non-incomplete) subscription blocks a new trial.
+ // An incomplete subscription from a failed attempt must not block the trial, or a retry is charged immediately
private isCustomerEligibleForTrialPeriod(
customer: BillingCustomerEntity | null,
): boolean {
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-price.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-price.service.ts
index 721dd4f5792..b0e42fbdbea 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-price.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-price.service.ts
@@ -132,9 +132,6 @@ export class BillingPriceService {
).sort((a, b) => a.tiers[0].up_to - b.tiers[0].up_to);
}
- // V2 counterpart of findEquivalentMeteredPrice.
- // Finds a RESOURCE_CREDIT price matching the target interval and plan,
- // with the largest credit_amount that does not exceed the reference credit_amount.
async findEquivalentResourceCreditPrice({
targetInterval,
targetPlanKey,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
index 00517eb0bf3..db387679d50 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
@@ -54,8 +54,7 @@ export class BillingSubscriptionService {
private readonly billingPriceService: BillingPriceService,
@InjectWorkspaceScopedRepository(BillingSubscriptionEntity)
private readonly billingSubscriptionRepository: WorkspaceScopedRepository<BillingSubscriptionEntity>,
- // Stripe webhooks resolve by stripeCustomerId before any workspaceId
- // is known. Used only when the criteria has no workspaceId.
+ // Stripe webhooks resolve by stripeCustomerId before any workspaceId is known
// eslint-disable-next-line twenty/prefer-workspace-scoped-repository
@InjectRepository(BillingSubscriptionEntity)
private readonly billingSubscriptionRepositoryUnscoped: Repository<BillingSubscriptionEntity>,
@@ -162,9 +161,7 @@ export class BillingSubscriptionService {
? data.object.customer
: data.object.customer?.id;
- // The Stripe account receives every setup intent, including ones that are
- // not tied to a workspace subscription. Those can never be recovered, and
- // failing would only have Stripe redeliver them
+ // Setup intents unrelated to a subscription can't be recovered; failing only makes Stripe redeliver
if (!isDefined(stripeCustomerId)) {
this.logger.warn(
`Ignoring successful setup intent ${data.object.id} without customer`,
@@ -209,9 +206,7 @@ export class BillingSubscriptionService {
{ default_payment_method: stripePaymentMethodId },
);
- // The persisted status can lag behind Stripe when this event lands before
- // the subscription update one, so the live status decides whether an
- // overdue invoice has to be retried
+ // The persisted status can lag Stripe when this event precedes the subscription update, so the live one decides
if (
[SubscriptionStatus.PastDue, SubscriptionStatus.Unpaid].includes(
getSubscriptionStatus(stripeSubscription.status),
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
index c463b23dccd..4ebdd2c6a1d 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
@@ -257,11 +257,7 @@ export class BillingUsageService {
return Number(resourceCreditPrice.metadata?.credit_amount ?? 0);
}
- // Returns null when usage could not be read. ClickHouseService.select
- // swallows query errors and returns [], but a bare sum() aggregate always
- // yields exactly one row, so an empty result means the read failed rather
- // than "nothing was used". Callers that hand out credits must not confuse
- // the two.
+ // Null on a failed read: select swallows errors into [], while sum() always yields one row
private async sumCreditsUsedMicroOrNull(
condition: string,
params: Record<string, unknown>,
@@ -284,10 +280,7 @@ export class BillingUsageService {
return Number.isFinite(total) ? total : 0;
}
- // Sums by event timestamp rather than by the stamped periodStart dimension.
- // At a period transition the subscription's currentPeriodStart has already
- // moved on, so an equality match on periodStart would read the new period
- // and report a period that has barely started as unused.
+ // By event timestamp: at a transition currentPeriodStart has moved on, so periodStart would read the new period
async getCreditsUsedBetweenOrNull({
workspaceId,
from,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-price.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-price.service.ts
index b6f55609ece..3051ae45871 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-price.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-price.service.ts
@@ -30,8 +30,7 @@ export class StripePriceService {
});
}
- // Superseding a price leaves the old one on the product forever, so the page
- // this returns is not a safe bound on how many a product accumulates.
+ // Paginates fully: superseded prices stay on the product forever
async getPricesByProductId(productId: string) {
const prices: Stripe.Price[] = [];
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-product.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-product.service.ts
index 0fc5a88651b..00eef110e4c 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-product.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-product.service.ts
@@ -24,8 +24,7 @@ export class StripeProductService {
);
}
- // Archived products are fetched too: the sync is the only thing that can repair
- // a local active flag left stale by a missed product.updated webhook.
+ // Includes archived: only the sync repairs an active flag left stale by a missed product.updated webhook
async getAllProducts() {
const products: Stripe.Product[] = [];
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts
index bd6c0261677..4f14024e729 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts
@@ -62,8 +62,7 @@ export class StripeSubscriptionService {
payment_method: stripePaymentMethodId,
});
} catch (error) {
- // A decline is final for this webhook, Stripe dunning retries the invoice
- // on its own schedule
+ // A decline is final for this webhook; Stripe dunning retries on its own schedule
if (error instanceof this.stripe.errors.StripeCardError) {
this.logger.error(
`Card declined for invoice ${invoice.id} of subscription ${stripeSubscriptionId}: ${error.message}`,
@@ -72,8 +71,7 @@ export class StripeSubscriptionService {
continue;
}
- // Stripe dunning or a concurrent webhook can have settled the invoice
- // in the meantime, only a still open one is worth a webhook retry
+ // Dunning or a concurrent webhook may have settled it; only a still-open invoice merits a retry
const refreshedInvoice = await this.stripe.invoices.retrieve(
invoice.id,
);
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/align-grant-expiry-to-period-end.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/align-grant-expiry-to-period-end.util.spec.ts
index 2dd45e22094..189e0148687 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/align-grant-expiry-to-period-end.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/align-grant-expiry-to-period-end.util.spec.ts
@@ -47,11 +47,7 @@ describe('alignGrantExpiryToPeriodEnd', () => {
).toEqual(new Date('2028-01-01T00:00:00.000Z'));
});
- // Stripe re-expands a month-end anchor rather than walking it down: a
- // subscription anchored on the 31st renews Feb 28, Mar 31, Apr 30. Stepping
- // off each clamped result instead would stamp the grant with Mar 28 and
- // Apr 28, dates the subscription never renews on, putting the deadline back
- // inside a period.
+ // Stripe re-expands a month-end anchor (Feb 28, Mar 31, Apr 30) rather than walking it down
it('keeps a month-end anchor on the days the subscription actually renews', () => {
const alignOnMonthEndAnchor = (requestedExpiresAt: Date) =>
alignGrantExpiryToPeriodEnd({
@@ -72,9 +68,7 @@ describe('alignGrantExpiryToPeriodEnd', () => {
);
});
- // The subscription has already renewed into a short month, so its stored
- // start is the clamped February date and no boundary on record holds the
- // anchor on its own. Projecting straight off that start would give Apr 28.
+ // The stored start is the clamped February date, so projecting straight off it would give Apr 28
it('recovers a month-end anchor the stored period start no longer carries', () => {
const result = alignGrantExpiryToPeriodEnd({
requestedExpiresAt: new Date('2026-04-15T00:00:00.000Z'),
@@ -86,8 +80,7 @@ describe('alignGrantExpiryToPeriodEnd', () => {
expect(result).toEqual(new Date('2026-04-30T00:00:00.000Z'));
});
- // A leap-day yearly anchor clamps to the 28th in common years and re-expands
- // to the 29th when it lands back on a leap one.
+ // A leap-day yearly anchor clamps to the 28th in common years and re-expands in leap ones
it('keeps a leap-day yearly anchor on the day each year actually has', () => {
const alignOnLeapDayAnchor = (requestedExpiresAt: Date) =>
alignGrantExpiryToPeriodEnd({
@@ -105,9 +98,7 @@ describe('alignGrantExpiryToPeriodEnd', () => {
);
});
- // Between leap years a Feb 29 anchor is indistinguishable from a Feb 28 one:
- // both boundaries read 28. Landing a day early costs the tail of one period,
- // where landing a day late would carry the grant into the whole next one.
+ // Feb 29 and Feb 28 anchors look alike between leap years; a day early beats a whole extra period
it('reads an anchor it cannot tell apart as the earlier day', () => {
const result = alignGrantExpiryToPeriodEnd({
requestedExpiresAt: new Date('2027-06-01T00:00:00.000Z'),
@@ -119,9 +110,7 @@ describe('alignGrantExpiryToPeriodEnd', () => {
expect(result).toEqual(new Date('2028-02-28T00:00:00.000Z'));
});
- // The column is nullable, and the interval is only needed to project past the
- // current period. Falling back to null expiry instead would read as "never
- // expires" and hand out permanent credits for a time-boxed request.
+ // A null expiry fallback would hand out permanent credits for a time-boxed request
it('stops at the current period end when the interval is unknown', () => {
expect(alignFrom(new Date('2026-06-15T00:00:00.000Z'), null)).toEqual(
CURRENT_PERIOD_END,
@@ -136,10 +125,7 @@ describe('alignGrantExpiryToPeriodEnd', () => {
);
});
- // Stripe's boundaries are UTC instants. Projecting them with local-time
- // arithmetic moves each one by the server's offset, which lands the expiry
- // inside the period it is meant to close: under Europe/Paris this case
- // returned 2026-03-31T23:00:00Z.
+ // Stripe boundaries are UTC instants: local-time arithmetic lands the expiry inside the period
describe.each(['Europe/Paris', 'Pacific/Kiritimati', 'America/Los_Angeles'])(
'with the server in %s',
(timeZone) => {
@@ -150,8 +136,7 @@ describe('alignGrantExpiryToPeriodEnd', () => {
});
afterAll(() => {
- // Assigning undefined would leave the string 'undefined' behind, which
- // is not the unset state the process started in.
+ // Assigning undefined would leave the string 'undefined' behind
if (isDefined(originalTimeZone)) {
process.env.TZ = originalTimeZone;
} else {
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts
index db75ca4eb1e..981ed1fbb29 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts
@@ -20,8 +20,7 @@ const grant = (
});
const ALLOWANCE = 1_000_000;
-// A cap multiplier of 2 means total credits never exceed twice the allowance,
-// so at most one full allowance can roll over.
+// A cap multiplier of 2 lets at most one full allowance roll over
const ROLLOVER_CAP = ALLOWANCE;
describe('computeCarryForwardGrants', () => {
@@ -289,8 +288,7 @@ describe('computeCarryForwardGrants', () => {
boundary: BOUNDARY,
});
- // The half micro-credit left of the allowance floors to nothing, so no
- // rollover grant is emitted at all.
+ // The half micro-credit left floors to nothing, so no rollover grant is emitted
expect(result).toEqual([
{
type: BillingCreditGrantType.COMPENSATION,
@@ -388,8 +386,7 @@ describe('computeCarryForwardGrants', () => {
expect(result).toEqual([]);
});
- // It was spendable for part of the period, so the usage it absorbed must
- // not fall back onto the grants that outlive it.
+ // Usage it absorbed while spendable must not fall onto the grants outliving it
it('still absorbs usage before lapsing', () => {
const result = computeCarryForwardGrants({
allowanceMicro: 0,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/derive-billing-period-transition.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/derive-billing-period-transition.util.spec.ts
index 248b320177b..5d3a1e7e1de 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/derive-billing-period-transition.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/derive-billing-period-transition.util.spec.ts
@@ -50,10 +50,7 @@ describe('deriveBillingPeriodTransition', () => {
expect(result.closingPeriodStart).toEqual(JANUARY);
});
- // The whole point of resolving the boundary from the subscription is that the
- // invoice's stamped period is unreliable. Classifying the trial off that same
- // stamped period_start put an arrears-stamped first paid period on the paid
- // tier allowance instead of the trial one.
+ // The invoice's stamped period is unreliable, so the trial must not be classified off it
it('reads the trial from the boundary, not from where the closing period began', () => {
const trialStart = new Date('2026-01-20T00:00:00.000Z');
@@ -76,8 +73,7 @@ describe('deriveBillingPeriodTransition', () => {
expect(result.closingPeriodStart).toEqual(JANUARY);
});
- // The subscription still carries the closing period, so it is exact and
- // nothing has to be reconstructed from a calendar or from the ledger.
+ // The subscription still carries the closing period, so it is exact
it('keeps the subscription period start when it precedes the boundary', () => {
const result = deriveFrom({
ledgerPeriodStart: new Date('2026-01-15T00:00:00.000Z'),
@@ -87,9 +83,7 @@ describe('deriveBillingPeriodTransition', () => {
expect(result.closingPeriodStart).toEqual(JANUARY);
});
- // The subscription records the boundary when it advances, so it is exact for
- // any anchor. The ledger only knows it when the previous transition happened
- // to close a grant there.
+ // The subscription records the boundary when it advances, so it is exact for any anchor
it('prefers the period start the subscription recorded over the ledger', () => {
const monthEndBoundary = new Date('2026-02-28T00:00:00.000Z');
@@ -105,10 +99,7 @@ describe('deriveBillingPeriodTransition', () => {
);
});
- // A subscription anchored on the 31st runs January 31 to February 28, and
- // subMonths clamps February 28 back to January 28. Three days of the previous
- // period would count as usage here, and grants that expired on January 31
- // would read as live and be carried forward a second time.
+ // subMonths clamps Feb 28 back to Jan 28 for a 31st anchor, miscounting usage and grants
it('prefers the period start the ledger recorded over clamped calendar arithmetic', () => {
const monthEndBoundary = new Date('2026-02-28T00:00:00.000Z');
const ledgerPeriodStart = new Date('2026-01-31T00:00:00.000Z');
@@ -160,9 +151,7 @@ describe('deriveBillingPeriodTransition', () => {
);
});
- // The column is nullable while its type says otherwise. Treating a missing
- // interval as monthly would settle a yearly subscription against one month of
- // usage and carry eleven months of allowance forward as unspent.
+ // Nullable despite its type: assuming monthly would settle a yearly subscription on one month of usage
it('refuses to guess a period length when the subscription records no interval', () => {
expect(() =>
deriveFrom({
@@ -172,8 +161,7 @@ describe('deriveBillingPeriodTransition', () => {
).toThrow(/records no interval/);
});
- // Only the calendar fallback needs the interval, so an exact source still
- // settles correctly without one.
+ // Only the calendar fallback needs the interval
it('settles without an interval when the subscription recorded the period start', () => {
const result = deriveFrom({
subscriptionCurrentPeriodStart: FEBRUARY,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts
index 797a4bb6b74..98432cb9ddf 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts
@@ -31,9 +31,7 @@ describe('resolveBillingPeriodBoundaryUpdate', () => {
).toEqual({});
});
- // Two subscription events for the same subscription can be processed out of
- // order, and the older one would otherwise rewind the window the rollover
- // settles against.
+ // Out-of-order events must not rewind the window the rollover settles against
it('keeps the stored window when a late event carries an older one', () => {
expect(
resolveBillingPeriodBoundaryUpdate({
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-transition-boundary.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-transition-boundary.util.spec.ts
index c936da342a1..0cf212db4bf 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-transition-boundary.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-transition-boundary.util.spec.ts
@@ -27,10 +27,7 @@ describe('resolveBillingTransitionBoundary', () => {
expect(boundary).toEqual(FEBRUARY);
});
- // Stripe stamps an invoice carrying metered items with the period that just
- // closed, so reading the boundary off invoicePeriodStart used to settle the
- // period before the one that ended and carry its grants into a window that
- // was already over. The subscription pins the handover whatever the stamp.
+ // Stripe stamps metered invoices with the period that just closed; the subscription pins the handover
it('does not move to the start of the period that just closed', () => {
const boundary = resolveBillingTransitionBoundary({
invoiceCreatedAt: new Date('2026-02-01T00:04:00.000Z'),
@@ -41,10 +38,7 @@ describe('resolveBillingTransitionBoundary', () => {
expect(boundary).toEqual(FEBRUARY);
});
- // invoice.created is stamped when Stripe raised the invoice, not when we got
- // to it, so a redelivery days later resolves exactly as the first attempt did.
- // Reading our own clock here used to drag the observation point with the
- // delay and pick the period end still in the future.
+ // invoice.created is Stripe's stamp, so a redelivery days later resolves like the first attempt
it('resolves a redelivery days later to the same handover', () => {
const boundary = resolveBillingTransitionBoundary({
invoiceCreatedAt: FEBRUARY,
@@ -55,10 +49,7 @@ describe('resolveBillingTransitionBoundary', () => {
expect(boundary).toEqual(FEBRUARY);
});
- // Settling March here would run on partial usage and reserve the idempotency
- // key the real March transition then needs. The invoice was raised at the
- // February handover, so that is the boundary it announces however far into
- // the period we happen to process it.
+ // Settling March would run on partial usage and burn the real March transition's idempotency key
it('never settles a period that has not ended yet', () => {
const boundary = resolveBillingTransitionBoundary({
invoiceCreatedAt: FEBRUARY,
@@ -79,11 +70,7 @@ describe('resolveBillingTransitionBoundary', () => {
expect(boundary).toEqual(FEBRUARY);
});
- // Stripe can raise the invoice a moment before it rolls the subscription's
- // period end. Rejecting the boundary outright here would hand back the period
- // start, and on a first cycle there is no spent idempotency key to make that
- // a no-op: the transition would reconstruct a pre-subscription window and
- // write carry-forward rows into the period still open.
+ // Stripe can raise the invoice just before rolling the period end; rejecting it writes carry-forward into the open period
it('still reads a boundary the invoice was raised a moment before', () => {
const boundary = resolveBillingTransitionBoundary({
invoiceCreatedAt: new Date('2026-01-31T23:59:59.000Z'),
@@ -94,9 +81,7 @@ describe('resolveBillingTransitionBoundary', () => {
expect(boundary).toEqual(FEBRUARY);
});
- // The handover is a whole period away from the other candidate, so nothing
- // realistic reaches the midpoint. An invoice raised nearer the period start
- // than its end is announcing that start, not a period end still to come.
+ // An invoice raised nearer the period start than its end announces that start
it('does not reach forward to a period end the invoice predates by most of a period', () => {
const boundary = resolveBillingTransitionBoundary({
invoiceCreatedAt: new Date('2026-01-05T00:00:00.000Z'),
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/shift-utc-months.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/shift-utc-months.util.spec.ts
index 188cf3b0e67..3789856340f 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/shift-utc-months.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/shift-utc-months.util.spec.ts
@@ -21,8 +21,7 @@ describe('shiftUtcMonths', () => {
).toEqual(new Date('2024-02-29T00:00:00.000Z'));
});
- // The stored boundary has already been clamped, so the anchor has to be
- // re-applied rather than read off the date being shifted.
+ // The stored boundary is already clamped, so the anchor must be re-applied
it('applies an anchor day the date itself no longer carries', () => {
expect(
shiftUtcMonths({
@@ -79,8 +78,7 @@ describe('shiftUtcMonths', () => {
).toEqual(new Date('2023-02-28T00:00:00.000Z'));
});
- // Stripe's boundaries are instants, not dates, and a subscription anchored
- // mid-day hands over at that time of day in every period.
+ // Stripe boundaries are instants: a mid-day anchor hands over at that time every period
it('carries the time of day through the shift', () => {
expect(
shiftUtcMonths({ date: new Date('2026-01-15T09:41:07.123Z'), months: 1 }),
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util.ts
index 36b25905be7..30f8791f008 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util.ts
@@ -5,26 +5,12 @@ import { isDefined } from 'twenty-shared/utils';
import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
import { shiftUtcMonths } from 'src/engine/core-modules/billing/utils/shift-utc-months.util';
-// Bounds the walk so it cannot run away. Must stay above what the longest
-// accepted validity needs on the shortest interval: a year of monthly periods
-// is thirteen, so this leaves room to spare. Walking out of it returns a date
-// short of the one asked for, so the accepted validity and this bound have to
-// move together.
+// Must cover the longest accepted validity on the shortest interval (13 monthly periods for a year);
+// exceeding it returns a date short of the one asked for, so raise both together
const MAX_PERIODS_AHEAD = 24;
-// Stripe keeps the day a subscription was anchored on and clamps it to each
-// short month, so a subscription anchored on the 31st renews Jan 31, Feb 28,
-// Mar 31. Neither stored boundary is reliably the anchor once it has renewed
-// into a short month, so take the later day of the two: for monthly periods
-// that is always the anchor, since no two consecutive months are short enough
-// to clamp the same one.
-//
-// Yearly periods have one case the two dates cannot settle, a Feb 29 anchor
-// read between leap years, where both say 28. Reading it as 28 leaves a
-// deadline a day short of a leap-year boundary; reading it as 29 would push it
-// past a common-year one and buy a whole extra period, so the low reading is
-// the one worth keeping. Recovering the anchor this way avoids having to
-// persist Stripe's billing_cycle_anchor.
+// Stripe clamps the anchor day to short months, so the later day of the two boundaries recovers it
+// A Feb 29 yearly anchor reads as 28 between leap years; the low reading avoids buying a whole extra period
const resolveAnchorDayOfMonth = ({
periodStart,
periodEnd,
@@ -54,13 +40,7 @@ const projectPeriodEnd = ({
});
};
-// A grant's expiry is always a period end. Both mechanisms that spend credits
-// work a whole period at a time: the available credit count is cached until the
-// period ends, and the carry-forward settles a period's usage against the
-// grants that were live for it. A deadline inside a period is invisible to
-// both, so the counter would keep spending credits that had lapsed and the
-// settlement would let them absorb usage incurred after they died. Asking for
-// thirty days therefore buys the period that day falls in, never less.
+// Always a period end: the cached credit count and the carry-forward both work a whole period at a time
export const alignGrantExpiryToPeriodEnd = ({
requestedExpiresAt,
currentPeriodStart,
@@ -70,13 +50,10 @@ export const alignGrantExpiryToPeriodEnd = ({
requestedExpiresAt: Date;
currentPeriodStart: Date;
currentPeriodEnd: Date;
- // Nullable on the subscription, and only needed to project past the current
- // period. Without it the current period end is the last boundary that can be
- // named, which is short of what was asked for but still a real one.
+ // Nullable: without it the current period end is the last nameable boundary
interval: SubscriptionInterval | null | undefined;
}): Date => {
- // Known exactly, and the only boundary that survives a period whose length
- // was changed by a plan switch rather than by the schedule.
+ // The only boundary that survives a period resized by a plan switch
if (
currentPeriodEnd.getTime() >= requestedExpiresAt.getTime() ||
!isDefined(interval)
@@ -89,10 +66,7 @@ export const alignGrantExpiryToPeriodEnd = ({
periodEnd: currentPeriodEnd,
});
- // Every later boundary is projected from the period start rather than by
- // stepping off the previous result, which would walk a month-end anchor down
- // to the 28th and stamp the grant with days the subscription never renews on,
- // putting the deadline back inside a period.
+ // Projected from the period start: stepping off the previous result walks month-end anchors down to the 28th
let periodEnd = currentPeriodEnd;
for (
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/bigint-column-transformer.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/bigint-column-transformer.util.ts
index e21cf7e6b81..bf43b1b9814 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/bigint-column-transformer.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/bigint-column-transformer.util.ts
@@ -1,12 +1,6 @@
/* @license Enterprise */
-// Postgres returns bigint as a string, so it needs coercing back.
-//
-// Number() is only lossless below 2^53, which is 9e9 credits at
-// INTERNAL_CREDITS_PER_DISPLAY_CREDIT. Balances are bounded well under that by
-// BILLING_MAX_ADMIN_CREDIT_GRANT_MICRO and the rollover cap, and
-// getActiveCreditsMicro throws rather than serve a total that is not a safe
-// integer, so the range is asserted rather than assumed.
+// Postgres returns bigint as a string; Number() is safe because getActiveCreditsMicro asserts totals stay below 2^53.
export const bigintColumnTransformer = {
to: (value: number) => value,
from: (value: string | number | null) =>
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
index 7b06fd35d7d..8d9c486bedb 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
@@ -1,7 +1,5 @@
/* @license Enterprise */
-// Serializes every write to a workspace's credit ledger. The rollover reads the
-// ledger, decides from that snapshot, then writes it back, so a grant landing
-// in between would be carried twice or dropped.
+// The rollover reads then rewrites the ledger, so a concurrent grant would be carried twice or dropped.
export const buildBillingCreditStateLockKey = (workspaceId: string): string =>
`billing-credit-state:${workspaceId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-entitlements-from-lookup-keys.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-entitlements-from-lookup-keys.util.ts
index 2201bea76e0..093f3d7f1e0 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-entitlements-from-lookup-keys.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-entitlements-from-lookup-keys.util.ts
@@ -2,9 +2,7 @@
import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';
-// A row is written for every key, not only the granted ones: a key absent from
-// the table reads as denied, so a key added to the enum stays denied for every
-// existing workspace until something writes its row.
+// A missing row reads as denied, so every key gets a row or new enum keys stay denied for existing workspaces.
export const buildBillingEntitlementsFromLookupKeys = ({
workspaceId,
stripeCustomerId,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts
index 65925732a49..e54d3de6bd7 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts
@@ -42,9 +42,7 @@ const hasLapsedBy = ({
}): boolean =>
isDefined(expiresAt) && expiresAt.getTime() <= boundary.getTime();
-// Capped credits are spent first so that deliberately granted credits
-// (compensation, partnership, onboarding rewards) survive the period and carry
-// over at their full value instead of being clipped by the rollover cap.
+// Capped credits are spent first so deliberate grants carry over in full instead of being clipped by the rollover cap.
const compareSpendingOrder = (a: CreditBucket, b: CreditBucket): number => {
const [isACapped, isBCapped] = [isCappedType(a.type), isCappedType(b.type)];
@@ -58,10 +56,7 @@ const compareSpendingOrder = (a: CreditBucket, b: CreditBucket): number => {
return byCreatedAt;
}
- // Grants written in the same transaction share a timestamp, and the order
- // decides which grant id ends up on which carry-forward row. That id is part
- // of the replay key, so without a stable tie-break a redelivery could write
- // a second set of rows for the same credits.
+ // Grant id is part of the replay key, so same-timestamp grants need a stable order or a redelivery writes duplicate rows.
return (a.grantId ?? '').localeCompare(b.grantId ?? '');
};
@@ -76,8 +71,6 @@ export const computeCarryForwardGrants = ({
liveGrants: CarryForwardGrantInput[];
usageMicro: number;
rolloverCapMicro: number;
- // Where the closing period ends, which decides whether a time-boxed grant is
- // still alive on the other side of it.
boundary: Date;
}): CarryForwardGrantOutput[] => {
const allowanceBucket: CreditBucket = {
@@ -123,11 +116,7 @@ export const computeCarryForwardGrants = ({
]
: [];
- // A lapsed grant keeps its place in the waterfall above and only loses its
- // remainder: carrying that would hand back credits the deadline took away.
- // The waterfall spends a whole period at once with no event times, so this is
- // only exact because every deadline is a period end, which is the invariant
- // alignGrantExpiryToPeriodEnd holds at the point an expiry is set.
+ // A lapsed grant keeps its waterfall place but loses its remainder; exact only because every deadline is a period end (alignGrantExpiryToPeriodEnd).
const preservedGrants: CarryForwardGrantOutput[] = unspentBuckets
.filter(
(bucket) =>
@@ -139,8 +128,6 @@ export const computeCarryForwardGrants = ({
type: bucket.type,
amountMicro: Math.floor(bucket.amountMicro),
sourceGrantId: bucket.grantId,
- // The successor inherits the deadline rather than outliving it, so a
- // time-boxed grant does not become permanent by crossing a renewal.
expiresAt: bucket.expiresAt,
}));
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/derive-billing-period-transition.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/derive-billing-period-transition.util.ts
index 2cb543c06b1..6bf067bfa3c 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/derive-billing-period-transition.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/derive-billing-period-transition.util.ts
@@ -14,13 +14,10 @@ export type BillingPeriodTransition = {
closingPeriodStart: Date;
closingPeriodEnd: Date;
nextPeriodStart: Date;
- // Whether the period being closed is the trial. Its allowance comes from
- // config rather than the price, which only applies once paid.
isFirstPeriodAfterTrial: boolean;
};
-// Stripe stamps the trial end and the boundary from the same schedule, so they
-// agree to the second; the slack only absorbs rounding.
+// Stripe stamps the trial end and the boundary from the same schedule; the slack only absorbs rounding.
const TRIAL_END_TOLERANCE_IN_MS = 60 * 1000;
const subtractOneInterval = ({
@@ -46,8 +43,6 @@ const resolveClosingPeriodStart = ({
}: {
boundary: Date;
subscriptionCurrentPeriodStart: Date;
- // Nullable on the subscription despite its type. Only the calendar fallback
- // below needs it, and that branch refuses rather than assuming a length.
subscriptionInterval: SubscriptionInterval | null | undefined;
trialStart: Date | null | undefined;
isFirstPeriodAfterTrial: boolean;
@@ -58,20 +53,13 @@ const resolveClosingPeriodStart = ({
return trialStart;
}
- // Stripe reports one window at a time, so at the instant a cycle invoice is
- // raised the subscription either still holds the period that is closing or
- // has already been moved on to the next one. In the first case it still
- // carries the closing period's exact start and nothing has to be
- // reconstructed.
+ // Stripe reports one window at a time; a subscription not yet advanced still holds the closing start.
if (boundary.getTime() !== subscriptionCurrentPeriodStart.getTime()) {
return subscriptionCurrentPeriodStart;
}
- // Recorded when the subscription advanced, so it is exact whatever the
- // anchor. Calendar arithmetic cannot reproduce it for month-end anchors: a
- // period running January 31 to February 28 comes back as starting January
- // 28, which widens the usage window into the period before and drags
- // already expired grants back into the carry-forward.
+ // Recorded when the subscription advanced, so exact for any anchor; calendar arithmetic turns a Jan 31 start into Jan 28,
+ // widening the usage window and dragging expired grants into the carry-forward.
if (
isDefined(subscriptionPreviousPeriodStart) &&
subscriptionPreviousPeriodStart.getTime() < boundary.getTime()
@@ -79,9 +67,7 @@ const resolveClosingPeriodStart = ({
return subscriptionPreviousPeriodStart;
}
- // Only until each subscription has transitioned once with the column in
- // place. The ledger records the boundary whenever the previous transition
- // closed a grant there, which is most workspaces but not all.
+ // Fallback for subscriptions that have not transitioned since subscriptionPreviousPeriodStart was added.
if (
isDefined(ledgerPeriodStart) &&
ledgerPeriodStart.getTime() < boundary.getTime()
@@ -89,12 +75,7 @@ const resolveClosingPeriodStart = ({
return ledgerPeriodStart;
}
- // Nothing on record says where the closing period began, so the only way
- // left is to step back one interval — and without one there is no honest
- // guess. Treating a missing interval as monthly would settle a yearly
- // subscription against a month of usage and roll eleven months of allowance
- // forward as unspent. Throwing fails the webhook so Stripe redelivers it,
- // and a settlement that is late beats one that is wrong.
+ // Assuming monthly would settle a yearly subscription against one month; throwing makes Stripe redeliver the webhook.
if (!isDefined(subscriptionInterval)) {
throw new BillingException(
`Cannot settle the period closing at ${boundary.toISOString()}: the subscription records no interval and neither it nor the ledger says where the period began`,
@@ -102,10 +83,7 @@ const resolveClosingPeriodStart = ({
);
}
- // Calendar arithmetic, not the invoiced duration: consecutive periods
- // differ in length, so a February renewal bills 28 days and subtracting
- // those from February 1 would place the closing period at January 4 and
- // drop three days of usage, which then reads as unspent allowance.
+ // Calendar arithmetic, not the invoiced duration: a February renewal bills 28 days and would drop three days of usage.
return subtractOneInterval({
date: boundary,
interval: subscriptionInterval,
@@ -121,25 +99,13 @@ export const deriveBillingPeriodTransition = ({
subscriptionPreviousPeriodStart,
ledgerPeriodStart,
}: {
- // Resolved through resolveBillingTransitionBoundary before the ledger is
- // read, since which period start the ledger is asked for depends on it.
boundary: Date;
subscriptionCurrentPeriodStart: Date;
- // Nullable on the subscription despite its type. Only the calendar fallback
- // needs it, and that branch refuses rather than assuming a length.
subscriptionInterval: SubscriptionInterval | null | undefined;
trialStart: Date | null | undefined;
- // A trial ends at a period handover, so this transition closes the trial
- // exactly when the boundary it settles is the trial end. Compared against
- // that resolved boundary and never against the invoice's stamped period,
- // which on an arrears-stamped invoice reports the window that just closed.
+ // Compare to the resolved boundary: an arrears-stamped invoice reports the window that just closed.
trialEnd: Date | null | undefined;
- // Where the subscription recorded the previous period starting, captured when
- // it advanced. Null for a subscription that has not transitioned since the
- // column was added.
subscriptionPreviousPeriodStart: Date | null;
- // Where the ledger says the closing period started, used only when the
- // subscription has no record of it.
ledgerPeriodStart: Date | null;
}): BillingPeriodTransition => {
const isFirstPeriodAfterTrial =
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/find-product-price-for-interval-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/find-product-price-for-interval-or-throw.util.ts
index a82bf37d00a..22611ecc326 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/find-product-price-for-interval-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/find-product-price-for-interval-or-throw.util.ts
@@ -13,10 +13,8 @@ type IntervalPrice = {
metadata?: { isLegacy?: string | null } | null;
};
-// Switching interval is not a sale: a workspace on superseded packaging is
-// changing interval on the product it already has, so this resolves what is
-// billable on that product rather than what is sellable. isLegacy only breaks a
-// tie between two live prices at the same interval.
+// Switching interval is not a sale, so this resolves what is billable on the current product rather than what is sellable.
+// isLegacy only breaks a tie between two active prices at the same interval.
export const findProductPriceForIntervalOrThrow = <
TPrice extends IntervalPrice,
>(
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/find-sellable-base-product-price-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/find-sellable-base-product-price-or-throw.util.ts
index 4a49ca99cb5..9f993f15755 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/find-sellable-base-product-price-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/find-sellable-base-product-price-or-throw.util.ts
@@ -17,9 +17,7 @@ type SellableBaseProductPrice = {
} | null;
};
-// Callers pass prices already narrowed to a single plan and interval, so more than
-// one match means two sellable packagings are live at once and the price we would
-// charge depends on row order. Refuse rather than pick.
+// More than one match means two sellable packagings are live; refuse rather than charge by row order.
export const findSellableBaseProductPriceOrThrow = <
TPrice extends SellableBaseProductPrice,
>(
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/is-sellable-catalog-price.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/is-sellable-catalog-price.util.ts
index 30fc50983b9..3034fef3b5f 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/is-sellable-catalog-price.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/is-sellable-catalog-price.util.ts
@@ -12,8 +12,6 @@ type SellableCatalogPrice = {
} | null;
};
-// A price is only sellable if its product is too, so superseding a whole
-// packaging takes all of its prices out of circulation in one edit.
export const isSellableCatalogPrice = (
billingPrice: SellableCatalogPrice,
): boolean =>
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts
index f3eb40a41b9..bfbf89991b3 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts
@@ -13,10 +13,8 @@ type BillingPeriodBoundaryUpdate = {
currentPeriodEnd?: Date;
};
-// Stripe only ever reports the current window, so the boundary a period moves
-// off is captured at the moment it moves or lost for good. The rollover needs
-// it to bound the usage it settles, which is why every path that writes a
-// subscription resolves its period fields through this.
+// Stripe only reports the current window, so the boundary a period moves off must be captured here or is lost;
+// the rollover bounds the usage it settles with it, so every subscription write resolves period fields through this.
export const resolveBillingPeriodBoundaryUpdate = ({
incomingPeriodStart,
storedSubscription,
@@ -34,9 +32,7 @@ export const resolveBillingPeriodBoundaryUpdate = ({
return { previousPeriodStart: currentPeriodStart };
}
- // Stripe never moves a period backwards, so an older window is an event
- // delivered late. Letting it land would rewind the boundary the rollover
- // settles against and leave it behind the one already recorded.
+ // Stripe never moves a period backwards, so an older window is a late event and must not rewind the boundary.
if (incomingPeriodStart.getTime() < currentPeriodStart.getTime()) {
return { currentPeriodStart, currentPeriodEnd };
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util.ts
index 05282d17fde..f4cf31c3a8a 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util.ts
@@ -1,32 +1,7 @@
/* @license Enterprise */
-// Stripe stamps a subscription_cycle invoice with the period it bills, which is
-// the upcoming one for licensed items but the one that just closed for metered
-// items. Resource credits are sold as a metered item, so on a subscription
-// carrying both the invoice can arrive stamped with either window and its
-// period_start is not the handover instant. The subscription is unambiguous
-// about where its own periods hand over, so the boundary is read off it: the
-// invoice only tells us that a handover happened.
-//
-// Which of the subscription's two boundaries is the handover depends on whether
-// our copy of it has advanced yet, and Stripe raises the invoice at the
-// handover itself. So the answer is whichever boundary the invoice was created
-// nearest to: it is the period end while the subscription still holds the
-// closing window, and the period start once it has moved on.
-//
-// The two candidates are a whole period apart and the invoice sits on the
-// handover, so this resolves with half a period of room on either side. That is
-// what makes it safe where comparing against our own wall clock was not: a
-// redelivery processed days late used to drag the observation point with it,
-// where invoice.created stays pinned to the handover however late we get to it.
-// It also cannot drift toward a period end that has not arrived, because the
-// nearer boundary to the handover is the handover.
-//
-// That last part rests on the caller passing only subscription_cycle invoices,
-// which Stripe raises at the handover. Given any other invoice, raised at an
-// arbitrary point inside the period, nearness would answer with whichever
-// boundary happened to be closer and could name a period end still to come.
-// Widening what reaches this, or dropping that filter, breaks the guarantee.
+// Invoice period stamps are ambiguous (metered items bill in arrears), so use the subscription boundary nearest invoice.created.
+// Only valid for subscription_cycle invoices, which Stripe raises at the handover.
export const resolveBillingTransitionBoundary = ({
invoiceCreatedAt,
subscriptionCurrentPeriodStart,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/shift-utc-months.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/shift-utc-months.util.ts
index 4b06396db43..e443e9c3fb7 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/shift-utc-months.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/shift-utc-months.util.ts
@@ -1,10 +1,6 @@
/* @license Enterprise */
-// Stripe's period boundaries are UTC instants, and date-fns shifts dates in the
-// server's local time: that moves each boundary by the offset and, around a
-// daylight-saving change, lands it on the wrong side of the period it defines.
-// Every billing period projection goes through here so the arithmetic stays in
-// UTC in one place.
+// date-fns shifts in server local time, which moves Stripe's UTC boundaries around daylight-saving changes.
export const shiftUtcMonths = ({
date,
months,
@@ -12,15 +8,12 @@ export const shiftUtcMonths = ({
}: {
date: Date;
months: number;
- // Defaults to the day the date already carries. Passed explicitly to re-apply
- // a billing anchor that the stored boundary had clamped away.
+ // Re-applies a billing anchor that the stored boundary had clamped away.
dayOfMonth?: number;
}): Date => {
const year = date.getUTCFullYear();
const targetMonth = date.getUTCMonth() + months;
- // Day 0 of the month after the target is the last day of the target itself,
- // and Date.UTC rolls a month index past either end of the year.
const daysInTargetMonth = new Date(
Date.UTC(year, targetMonth + 1, 0),
).getUTCDate();
diff --git a/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts b/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
index 48f8ee0f9c5..c265ad0ce3c 100644
--- a/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
@@ -226,9 +226,7 @@ export class CacheStorageService {
do {
const result = await redisClient.scan(cursor, {
- // Through getKey, not the namespace alone: under NODE_ENV=test every
- // key carries a further prefix, so a raw namespace match scans for
- // keys that do not exist and the flush silently does nothing.
+ // Through getKey: under NODE_ENV=test keys carry an extra prefix, so a raw namespace match flushes nothing.
MATCH: this.getKey(scanPattern),
COUNT: 100,
});
diff --git a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts
index 28404c5e1b9..9d1544f8ab4 100644
--- a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts
@@ -58,14 +58,8 @@ export class TimelineCalendarEventService {
return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
const offset = (page - 1) * pageSize;
- // Runs under a system auth context, which resolves no role, so without
- // this the participant relations (person, workspaceMember) are read with
- // empty permissions and denied for everyone. Channel-level redaction of
- // title and description below is what gates the caller's access.
- // TODO run under the caller's role via resolveRolePermissionConfig instead
- // of bypassing, once roles that cannot read person degrade to a redacted
- // timeline rather than a denied one
- // https://github.com/twentyhq/core-team-issues/issues/2777
+ // System auth context resolves no role, so participant relations would be denied; channel-level redaction below gates access.
+ // TODO: run under the caller's role once unreadable person degrades to redaction https://github.com/twentyhq/core-team-issues/issues/2777
const calendarEventRepository =
this.workspaceOrmManager.getRepository<CalendarEventWorkspaceEntity>(
'calendarEvent',
diff --git a/packages/twenty-server/src/engine/core-modules/client-config/client-config.entity.ts b/packages/twenty-server/src/engine/core-modules/client-config/client-config.entity.ts
index d6e1d0d79d3..47c32cc7d29 100644
--- a/packages/twenty-server/src/engine/core-modules/client-config/client-config.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/client-config/client-config.entity.ts
@@ -38,7 +38,6 @@ export class NativeModelCapabilities {
@ObjectType()
export class ClientAiModelConfig {
@Field(() => String)
- // Composite model id (`provider/modelName`) for this workspace; matches registry and admin APIs.
modelId: ModelId;
@Field(() => String)
@@ -89,24 +88,19 @@ export class ClientAiModelConfig {
@Field(() => Number, { nullable: true })
costPerTask?: number;
- // Reasoning levels a pin may name as `modelId@effort`; empty for a model
- // that takes none, unset on a variant that already names its own.
+ // Reasoning levels a pin may name as `modelId@effort`; empty when the model takes none, unset on a variant naming its own.
@Field(() => [String], { nullable: true })
efforts?: string[];
@Field(() => String, { nullable: true })
effort?: string;
- // A pinned effort without a reading of its own shows the base model's
- // figures until the benchmark sync measures it.
@Field(() => Boolean, { nullable: true })
isBenchmarkInherited?: boolean;
}
@ObjectType()
-// Evaluation models are kept in their own list rather than mixed into
-// aiModels: every existing picker reads that list, and a model that cannot
-// answer a chat turn must not be offered by one that forgot to filter.
+// Kept out of aiModels so existing pickers never offer a model that cannot answer a chat turn.
export class ClientAiEvaluationModelConfig {
@Field(() => String)
modelId: string;
@@ -120,9 +114,6 @@ export class ClientAiEvaluationModelConfig {
@Field(() => String, { nullable: true })
providerLabel?: string;
- // False when the catalog declares the model but the instance holds no key
- // for its provider. The picker still shows it, so an operator can see what
- // configuring the provider would buy.
@Field(() => Boolean)
isAvailable: boolean;
@@ -153,7 +144,6 @@ export class ClientAiModelTierConfig {
@Field(() => AiModelTierEnum)
tier: AiModelTier;
- // The model this instance resolves the tier to when a workspace has no pin.
@Field(() => String)
modelId: ModelId;
}
@@ -161,15 +151,12 @@ export class ClientAiModelTierConfig {
@ObjectType()
export class AdminAiModelConfig {
@Field(() => String)
- // Composite model id (`provider/modelName`) used for toggles, defaults, and registry lookups.
+ // Composite `provider/modelName` id.
modelId: string;
@Field(() => String)
label: string;
- // What the model is for. An evaluation model answers typed questions and
- // cannot be chatted with, so the table has to say which is which rather than
- // list them side by side as interchangeable.
@Field(() => String)
kind: AiModelKind;
@@ -210,7 +197,7 @@ export class AdminAiModelConfig {
providerLabel?: string;
@Field(() => String, { nullable: true })
- // Bare SDK model name from the provider definition (`AiProviderModelConfig.name`), not the composite `modelId`.
+ // Bare SDK model name, not the composite modelId.
name?: string;
@Field(() => String, { nullable: true })
@@ -225,8 +212,6 @@ export class AdminAiModelTierDefault {
@Field(() => AiModelTierEnum)
tier: AiModelTier;
- // The model the tier resolves to on this instance; unset when no model is
- // available.
@Field(() => String, { nullable: true })
modelId?: string;
}
@@ -408,8 +393,7 @@ export class ClientConfig {
@Field(() => [PublicFeatureFlag])
publicFeatureFlags: PublicFeatureFlag[];
- // Always true now that cookie sessions are the only web auth path. Kept in
- // the schema because removing a field breaks the public API contract.
+ // Always true; kept because removing a field breaks the public API contract.
@Field(() => Boolean)
isCookieSessionEnabled: boolean;
diff --git a/packages/twenty-server/src/engine/core-modules/client-config/services/client-config.service.ts b/packages/twenty-server/src/engine/core-modules/client-config/services/client-config.service.ts
index 4546985940d..da9220da477 100644
--- a/packages/twenty-server/src/engine/core-modules/client-config/services/client-config.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/client-config/services/client-config.service.ts
@@ -37,8 +37,6 @@ export class ClientConfigService {
private maintenanceModeService: MaintenanceModeService,
) {}
- // A variant carries only the reading taken at its own effort, so until the
- // sync measures it the base model's reading is shown, flagged as such.
private resolveBenchmark(modelConfig: AiModelConfig | undefined): {
benchmark?: AiModelBenchmark;
isInherited: boolean;
@@ -158,8 +156,6 @@ export class ClientConfigService {
isDeprecated: modelConfig.isDeprecated,
}));
- // A tier with no model is left out; the client shows its "configure a
- // provider" state from the empty list rather than an error.
const aiModelTiers = AI_MODEL_TIERS.flatMap((tier) => {
const model = this.aiModelRegistryService.findDefaultModelForTier(tier);
diff --git a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/e2b.driver.ts b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/e2b.driver.ts
index fe25b6100f4..e93ce0d73f8 100644
--- a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/e2b.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/e2b.driver.ts
@@ -88,7 +88,6 @@ export class E2BDriver implements CodeInterpreterDriver {
}
try {
- // A reused sandbox already has the scripts from its first run.
if (!isReused) {
try {
await uploadDirectoryToSandbox(
diff --git a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/local.driver.ts b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/local.driver.ts
index 3e4cc99f627..433051e14c7 100644
--- a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/local.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/local.driver.ts
@@ -86,8 +86,7 @@ const buildEnvSetup = (env?: Record<string, string>): string => {
return `import os\n${assignments}\n\n`;
};
-// WARNING: This driver is UNSAFE and can be used for development only.
-// It executes arbitrary Python code on the server without any sandboxing.
+// UNSAFE: executes arbitrary Python on the server without sandboxing; development only.
export class LocalDriver implements CodeInterpreterDriver {
private readonly sessions = new Map<string, LocalSession>();
@@ -112,8 +111,6 @@ export class LocalDriver implements CodeInterpreterDriver {
return this.executeEphemeral(code, files, context, callbacks);
}
- // Persistent path: reuse a per-session process + work dir so state survives
- // between calls (variables, imports, files).
private async executeInSession(
sessionId: string,
code: string,
@@ -127,8 +124,7 @@ export class LocalDriver implements CodeInterpreterDriver {
context?.actorKey,
);
- // /home/user/output is cleared at the start of every call (matching the E2B
- // behavior and the tool contract).
+ // Cleared on every call to match E2B behavior and the tool contract.
await fs.rm(session.outputDir, { recursive: true, force: true });
await fs.mkdir(session.outputDir, { recursive: true });
@@ -154,9 +150,6 @@ export class LocalDriver implements CodeInterpreterDriver {
try {
response = await this.runInSession(session, submission, timeoutMs);
} catch (error) {
- // A timeout or a dead kernel: kill the (possibly wedged) process so the
- // next call recreates a clean one. The 'exit' handler reclaims the work
- // dir.
session.hasExited = true;
if (this.sessions.get(sessionId) === session) {
this.sessions.delete(sessionId);
@@ -187,8 +180,6 @@ export class LocalDriver implements CodeInterpreterDriver {
};
}
- // Ephemeral path (no session): fresh work dir + process per call, cleaned up
- // afterwards. State does NOT persist between calls here.
private async executeEphemeral(
code: string,
files: InputFile[] | undefined,
@@ -257,7 +248,6 @@ export class LocalDriver implements CodeInterpreterDriver {
scriptsDir: string,
outputDir: string,
): string {
- // Rewrite E2B-style paths to local paths for compatibility
return code
.replace(/\/home\/user\/scripts\//g, `${scriptsDir}/`)
.replace(/\/home\/user\/scripts/g, scriptsDir)
@@ -426,8 +416,6 @@ export class LocalDriver implements CodeInterpreterDriver {
}
session.pending?.reject(new Error('Python kernel process exited'));
session.pending = undefined;
- // The kernel self-terminates (idle watchdog) or dies on its own; reclaim
- // its work dir here so it doesn't leak.
void fs.rm(workDir, { recursive: true, force: true }).catch(() => {});
};
diff --git a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/__tests__/get-or-create-session-sandbox.util.spec.ts b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/__tests__/get-or-create-session-sandbox.util.spec.ts
index 1095c685960..178faac650e 100644
--- a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/__tests__/get-or-create-session-sandbox.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/__tests__/get-or-create-session-sandbox.util.spec.ts
@@ -19,7 +19,6 @@ const idleTimeoutMs = 300_000;
// The resolver keeps the sandbox alive for the larger of the two.
const aliveTimeoutMs = 600_000;
-// Sandbox.list() returns a paginator; emit the tagged sandboxes as a single page.
const paginatorOf = (items: ListedSandbox[]) => {
let fetched = false;
@@ -198,8 +197,7 @@ describe('getOrCreateSessionSandbox', () => {
it('never reuses a sandbox whose metadata does not exactly match the session', async () => {
const created = buildFakeSandbox();
const { api, mock } = buildSandboxApi({
- // A sandbox from a different session/tenant that a loose server-side match
- // could surface — it must be ignored, never connected to or reaped.
+ // Another session's sandbox surfaced by a loose server-side match must be ignored.
list: jest.fn(() =>
paginatorOf([listedSandbox('sbx-foreign', 'workspace-2:thread-9')]),
),
diff --git a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/get-or-create-session-sandbox.util.ts b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/get-or-create-session-sandbox.util.ts
index 265bbbc6994..a429dfa01a4 100644
--- a/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/get-or-create-session-sandbox.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/code-interpreter/drivers/utils/get-or-create-session-sandbox.util.ts
@@ -36,8 +36,7 @@ const listSandboxesForSession = async (
sandboxes.push(...(await paginator.nextItems()));
}
- // Re-check the tag client-side so a loose server-side match can never reuse
- // another tenant's sandbox.
+ // A loose server-side tag match must never reuse another tenant's sandbox.
return sandboxes.filter(
(sandbox) => sandbox.metadata?.[SESSION_SANDBOX_METADATA_KEY] === sessionId,
);
@@ -62,7 +61,6 @@ const connectAndKeepAlive = async (
return sandbox;
} catch {
- // Couldn't refresh the timeout — kill it instead of leaking a running sandbox.
await sandbox.kill().catch(() => undefined);
return undefined;
@@ -105,8 +103,6 @@ export const getOrCreateSessionSandbox = async ({
sandbox: Sandbox;
isReused: boolean;
}> => {
- // The sandbox must outlive a single execution and the idle window before it
- // auto-pauses, so take the larger of the two.
const aliveTimeoutMs = Math.max(timeoutMs, idleTimeoutMs);
const sessionSandboxes = await listSandboxesForSession(
diff --git a/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts b/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts
index ce7ffa8fc96..9189dce3e16 100644
--- a/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts
@@ -64,8 +64,6 @@ export class CompanyEnrichmentResolver {
]);
if (enrichmentResult.outcome === 'matched') {
- // Two independent bars on the same enrichment: a company worth a demo and
- // a company worth credits are not necessarily the same company.
await this.onboardingService.setOnboardingBookCallPendingIfQualified({
userId: user.id,
workspaceId: workspace.id,
diff --git a/packages/twenty-server/src/engine/core-modules/dns-manager/services/dns-manager.service.ts b/packages/twenty-server/src/engine/core-modules/dns-manager/services/dns-manager.service.ts
index 5f8ef2fb3e5..487a02956e9 100644
--- a/packages/twenty-server/src/engine/core-modules/dns-manager/services/dns-manager.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/dns-manager/services/dns-manager.service.ts
@@ -222,7 +222,6 @@ export class DnsManagerService {
return customHostnames.result[0];
}
- // should never happen. error 5xx
const hostnameCount = customHostnames.result.length;
const domainName = hostname;
@@ -249,7 +248,6 @@ export class DnsManagerService {
const { ssl, verification_errors, created_at } = customHostname;
return {
- // wait 10s before starting the real check
redirection:
created_at &&
new Date().getTime() - new Date(created_at).getTime() < 1000 * 10
diff --git a/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/parse-relative-url.util.ts b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/parse-relative-url.util.ts
index a4625aadb62..78d62b83ab5 100644
--- a/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/parse-relative-url.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/domain/domain-server-config/utils/parse-relative-url.util.ts
@@ -1,8 +1,4 @@
-// A redirect location coming from the front can carry a query string and a
-// tab anchor (e.g. /object/company/<recordId>#<tabId>). Assigning the whole
-// string to URL.pathname percent-encodes '?' and '#' into the path, so split
-// it into parts the URL API can reassemble. Parsing against a fixed base also
-// drops any host smuggled into the value, keeping redirects on our domain.
+// URL.pathname would percent-encode '?' and '#'; parsing against a fixed base also drops any smuggled host.
export const parseRelativeUrl = (relativeUrl: string) => {
const { pathname, searchParams, hash } = new URL(
relativeUrl,
diff --git a/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts b/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts
index 5229b6a0ffc..1fa0e91d3e0 100644
--- a/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts
@@ -109,8 +109,7 @@ export class WorkspaceDomainsService {
this.domainServerConfigService.getSubdomainAndDomainFromUrl(origin);
if (!this.twentyConfigService.get('IS_MULTIWORKSPACE_ENABLED')) {
- // Single-workspace: workspace is always the default. Still resolve a
- // matching public domain so the route trigger can scope by application.
+ // Still resolve the public domain so route triggers can scope by application.
const publicDomain = isDefined(domain)
? await this.publicDomainRepository.findOne({ where: { domain } })
: null;
diff --git a/packages/twenty-server/src/engine/core-modules/dpa/__tests__/subprocessors-json.spec.ts b/packages/twenty-server/src/engine/core-modules/dpa/__tests__/subprocessors-json.spec.ts
index 3dc9acb7d53..398944a5107 100644
--- a/packages/twenty-server/src/engine/core-modules/dpa/__tests__/subprocessors-json.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/dpa/__tests__/subprocessors-json.spec.ts
@@ -20,10 +20,7 @@ describe('subprocessors.json integrity', () => {
expect(typeof subprocessor.processesPii).toBe('boolean');
- // A sub-processor that handles PII must declare where it does so (Annex C
- // relies on it). Non-PII providers (e.g. optional AI backends) may list
- // none, and the trust-center sync action owns this data, so the location
- // requirement is enforced only for PII processors.
+ // Only PII processors must declare locations (Annex C relies on them).
if (subprocessor.processesPii) {
expect(subprocessor.processingLocations.length).toBeGreaterThan(0);
}
diff --git a/packages/twenty-server/src/engine/core-modules/dpa/config/dpa-region-config.constant.ts b/packages/twenty-server/src/engine/core-modules/dpa/config/dpa-region-config.constant.ts
index fc9723e9b5b..87e3c371082 100644
--- a/packages/twenty-server/src/engine/core-modules/dpa/config/dpa-region-config.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/dpa/config/dpa-region-config.constant.ts
@@ -7,8 +7,7 @@ const DPA_COMMON_VALUES = {
PROCESSOR_ENTITY: 'Twenty.com PBC',
PROCESSOR_LEGAL_FORM:
'a public benefit corporation under the laws of Delaware, USA',
- // Registered office is the Delaware registered agent; the SF notices
- // address is kept distinct so the two are not conflated under one label.
+ // The Delaware registered office and the SF notices address must stay distinct.
PROCESSOR_ADDRESS:
'c/o National Registered Agents, Inc., 1209 Orange Street, Wilmington, Delaware 19801, USA. For notices: 2261 Market Street #5275, San Francisco, California 94114, USA',
EU_AFFILIATE_ENTITY: 'Twenty.com SAS',
diff --git a/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template-version.constant.ts b/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template-version.constant.ts
index bb77e3a86f4..741592eeb8e 100644
--- a/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template-version.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template-version.constant.ts
@@ -1,6 +1,4 @@
-// Bump BOTH values whenever the rendered legal text changes — i.e. when the
-// verbatim template OR the resolved merge-field values (entities, addresses,
-// governing law, …) change — so a version always maps to one exact agreement.
+// Bump both whenever the rendered legal text changes (template or merge-field values).
export const DPA_TEMPLATE_VERSION = '2026-08';
export const DPA_LAST_UPDATED_LABEL = 'August 2026';
diff --git a/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template.constant.ts b/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template.constant.ts
index fc83a22fb86..0148551bc86 100644
--- a/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/dpa/constants/dpa-template.constant.ts
@@ -1,6 +1,5 @@
-// Generated from the source DPA template (Twenty DPA — Universal Template.docx).
-// Legal wording changes must be reviewed and accompanied by a template-version bump.
-// Merge fields use {{DOUBLE_BRACES}} and are resolved at render time.
+// Generated from Twenty DPA Universal Template.docx; wording changes need legal review and a template-version bump.
+// {{DOUBLE_BRACES}} merge fields are resolved at render time.
import { type DpaTemplateBlock } from 'src/engine/core-modules/dpa/types/dpa.type';
diff --git a/packages/twenty-server/src/engine/core-modules/dpa/utils/__tests__/resolve-dpa.util.spec.ts b/packages/twenty-server/src/engine/core-modules/dpa/utils/__tests__/resolve-dpa.util.spec.ts
index 8d2f8604dad..fbdc16239f6 100644
--- a/packages/twenty-server/src/engine/core-modules/dpa/utils/__tests__/resolve-dpa.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/dpa/utils/__tests__/resolve-dpa.util.spec.ts
@@ -261,8 +261,7 @@ describe('resolveDpa', () => {
expect(text).toContain('ANNEX C – List of Sub-Processors');
expect(text).toContain('set out in Annex C');
- // Derive the expected entries from the synced data rather than hardcoding
- // vendor locations, which the trust-center sync action overwrites.
+ // Derived from synced data because the trust-center sync overwrites vendor locations.
for (const subprocessor of subprocessors) {
const vendorSuffix = subprocessor.vendorUrl
? ` (${subprocessor.vendorUrl})`
diff --git a/packages/twenty-server/src/engine/core-modules/dpa/utils/resolve-dpa.util.ts b/packages/twenty-server/src/engine/core-modules/dpa/utils/resolve-dpa.util.ts
index 1041cba59bd..640273f64ef 100644
--- a/packages/twenty-server/src/engine/core-modules/dpa/utils/resolve-dpa.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/dpa/utils/resolve-dpa.util.ts
@@ -91,7 +91,6 @@ const buildExecutionBlocks = (
return blocks;
};
-// Pure: no I/O or clock access — everything time-dependent is passed in via context.
export const resolveDpa = (context: DpaResolveContext): ResolvedDpa => {
const config = getDpaRegionConfig(context.region);
diff --git a/packages/twenty-server/src/engine/core-modules/email/utils/sanitize-outbound-email-html.util.ts b/packages/twenty-server/src/engine/core-modules/email/utils/sanitize-outbound-email-html.util.ts
index df0960cbaec..2472eda635b 100644
--- a/packages/twenty-server/src/engine/core-modules/email/utils/sanitize-outbound-email-html.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/email/utils/sanitize-outbound-email-html.util.ts
@@ -134,10 +134,7 @@ export const sanitizeOutboundEmailHtml = async (
}),
});
- // DOMPurify intentionally removes document types and comments. Restore the
- // inert doctype so email clients stay in standards mode; conditional comments
- // remain stripped because preserving arbitrary commented markup would create
- // a sanitizer bypass for raw HTML blocks and legacy bodies.
+ // Restore the doctype DOMPurify strips (standards mode); conditional comments stay stripped to avoid a sanitizer bypass.
return preamble.doctype === undefined
? sanitizedHtml
: `${preamble.doctype}${sanitizedHtml}`;
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant.ts
index 1461df619ed..780216df724 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/constants/resend-workspace-tag-name.constant.ts
@@ -1,3 +1,2 @@
-// Attached to every send and echoed back in Resend webhook payloads, so
-// outbound events can be attributed to a workspace without provider state.
+// Echoed back in Resend webhook payloads, so events can be attributed to a workspace.
export const RESEND_WORKSPACE_TAG_NAME = 'workspace_id';
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service.ts
index 4dae42daaaf..bbdc34ea474 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/services/resend-driver.service.ts
@@ -39,8 +39,7 @@ export class ResendDriver implements EmailingDomainDriverInterface {
private readonly unsubscribeContentService: UnsubscribeContentService,
) {}
- // Resend has no per-workspace resources: domains are account-level and
- // workspace attribution travels on each send as a tag.
+ // Resend domains are account-level; workspace attribution travels on each send as a tag.
async provisionWorkspace(workspaceId: string): Promise<void> {
this.logger.log(
`No Resend resources to provision for workspace ${workspaceId}`,
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util.ts
index 8b4e64122dc..0bab593cfe2 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/drivers/resend/utils/map-resend-sending-status.util.ts
@@ -6,10 +6,7 @@ import { EmailingDomainStatus } from 'src/engine/core-modules/emailing-domain/dr
const SENDING_RECORD_LABELS = ['SPF', 'DKIM'];
-// A domain with receiving enabled reports partially_verified while its MX
-// record is pending even though sending is fully set up, so outbound
-// readiness is derived from the sending records rather than the aggregate
-// domain status.
+// Receiving-enabled domains report partially_verified while MX is pending, so readiness comes from the sending records.
export const mapResendSendingStatus = (
domain: ResendDomain,
): EmailingDomainStatus => {
diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts
index dad128f6d31..8e3d3bbe1e9 100644
--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/services/emailing-domain.service.ts
@@ -30,8 +30,7 @@ export class EmailingDomainService {
constructor(
@InjectWorkspaceScopedRepository(EmailingDomainEntity)
private readonly emailingDomainRepository: WorkspaceScopedRepository<EmailingDomainEntity>,
- // Domain is globally unique across workspaces, so existence checks need
- // an unscoped repository
+ // Domain is globally unique, so existence checks need an unscoped repository.
// eslint-disable-next-line twenty/prefer-workspace-scoped-repository
@InjectRepository(EmailingDomainEntity)
private readonly globalEmailingDomainRepository: Repository<EmailingDomainEntity>,
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant.ts
index 77f4c5fe59c..ab53a46f7f5 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-refresh-interval.constant.ts
@@ -1,7 +1,4 @@
/* @license Enterprise */
-// Model resolution reads the entitlement synchronously, so seats are counted on
-// this cadence instead: an instance that crosses the threshold keeps resolving
-// its custom models for at most this long. Well under the daily seat report,
-// and one COUNT per hour per process is far cheaper than one per inference.
+// Model resolution reads the entitlement synchronously, so seats are recounted on this cadence rather than per inference.
export const CUSTOM_AI_PROVIDER_ACCESS_REFRESH_INTERVAL_MS = 60 * 60 * 1000;
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant.ts
index f442f99f179..05730ecc9aa 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/custom-ai-provider-access-retry-interval.constant.ts
@@ -1,7 +1,4 @@
/* @license Enterprise */
-// A count that failed leaves a verdict that may be wrong in either direction, so
-// it is retried far sooner than a successful one is refreshed. Still an interval
-// rather than an immediate retry: a database that stays down would otherwise put
-// a count back on the path of every single model resolution.
+// Sooner than a refresh since the verdict may be wrong, but not immediate so a down database stays off the resolution path.
export const CUSTOM_AI_PROVIDER_ACCESS_RETRY_INTERVAL_MS = 60 * 1000;
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.resolver.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.resolver.ts
index 86f9dc71b40..c2aa2150cab 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.resolver.ts
@@ -21,8 +21,6 @@ import { BillingDisabledGuard } from 'src/engine/guards/billing-disabled.guard';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
-// Server-binding rejections that should surface as an activation failure with
-// their own user-facing message (rather than being silently swallowed).
const SERVER_BINDING_REJECTION_CODES: EnterpriseExceptionCode[] = [
EnterpriseExceptionCode.ENTERPRISE_KEY_BOUND_TO_ANOTHER_SERVER,
EnterpriseExceptionCode.ENTERPRISE_MISSING_SERVER_ID,
@@ -52,9 +50,6 @@ const SERVER_BINDING_REJECTION_CODES: EnterpriseExceptionCode[] = [
export class EnterpriseResolver {
constructor(private readonly enterprisePlanService: EnterprisePlanService) {}
- // Turn a server-binding rejection from the last refresh into a user-facing
- // error, so activation and manual refresh surface the real reason instead of
- // silently failing.
private throwIfServerBindingRejected(): void {
const rejectionCode =
this.enterprisePlanService.getLastRefreshRejectionCode();
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/custom-ai-provider-access.service.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/custom-ai-provider-access.service.ts
index 29db9c3d8b1..66f4e531b4b 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/services/custom-ai-provider-access.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/custom-ai-provider-access.service.ts
@@ -21,8 +21,7 @@ export type CustomAiProviderAccess = {
export class CustomAiProviderAccessService {
private readonly logger = new Logger(CustomAiProviderAccessService.name);
- // Assumed granted until the first count returns, so a cold process never drops
- // an entitled instance's custom models while the query is still in flight.
+ // Assumed granted so a cold process never drops an entitled instance's custom models while counting.
private hasAccess = true;
private lastRefreshStartedAt: number | null = null;
private didLastRefreshFail = false;
@@ -33,8 +32,7 @@ export class CustomAiProviderAccessService {
) {}
async computeAccess(): Promise<CustomAiProviderAccess> {
- // Stamped before the first await so concurrent synchronous readers cannot
- // each start their own count.
+ // Stamped before the first await so concurrent synchronous readers cannot each start a count.
this.lastRefreshStartedAt = Date.now();
try {
@@ -59,16 +57,11 @@ export class CustomAiProviderAccessService {
}
}
- // Callers on the inference path resolve models synchronously and must not wait
- // on a seat count, so they get the last verdict and only start a refresh once
- // it has aged out — whoever reads next picks the new one up.
+ // The inference path cannot wait on a seat count, so it reads the last verdict and refreshes in the background once stale.
getCachedHasAccess(): boolean {
if (this.isVerdictStale()) {
- // computeAccess stamps the clock before its first await, so a second
- // synchronous caller cannot start a competing count.
this.computeAccess().catch((error) => {
- // A count that fails must never disable AI: the previous verdict stands
- // until a later refresh succeeds.
+ // A failed count must never disable AI: the previous verdict stands.
this.logger.warn(
`Could not refresh custom AI provider access: ${
error instanceof Error ? error.message : 'Unknown error'
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
index 4dbd1818439..3b48e3af776 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
@@ -334,8 +334,6 @@ export class EnterprisePlanService implements OnModuleInit {
errorData.code ===
EnterprisePlanService.ENTERPRISE_VALIDITY_TOKEN_RATE_LIMITED_CODE
) {
- // Rate limited: the existing token stays valid, surface the reason so
- // callers (e.g. the manual refresh button) can tell the user.
throw new EnterpriseException(
'Validity token refresh rate limit exceeded',
EnterpriseExceptionCode.ENTERPRISE_VALIDITY_TOKEN_RATE_LIMITED,
@@ -346,10 +344,7 @@ export class EnterprisePlanService implements OnModuleInit {
this.lastRefreshRejectionCode = errorData.code;
}
- // Only a key claimed by a different server means this instance is
- // definitively displaced, so revoke its stored license. Other
- // rejections (missing SERVER_ID, dev-needs-prod, dev-slot-taken) are
- // recoverable: the existing token simply expires without reissue.
+ // Only a key bound to another server is definitive; other rejections are recoverable and the token just expires.
if (
errorData.code ===
EnterprisePlanService.ENTERPRISE_KEY_BOUND_TO_ANOTHER_SERVER_CODE
@@ -387,8 +382,7 @@ export class EnterprisePlanService implements OnModuleInit {
}
}
- // Self-hosted pricing is per user: a user who belongs to several workspaces
- // on the same instance only counts as one seat.
+ // Self-hosted pricing is per user, so a user in several workspaces counts as one seat.
async getBillableSeatCount(): Promise<number> {
const result = await this.userWorkspaceRepository
.createQueryBuilder('userWorkspace')
@@ -720,8 +714,7 @@ export class EnterprisePlanService implements OnModuleInit {
}
}
- // In development and Jest integration tests, tries both keys so production keys
- // work locally
+ // Development and tests try both keys so production keys also work locally.
private getPublicKeysToTry(): string[] {
const nodeEnv = this.twentyConfigService.get('NODE_ENV');
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util.ts b/packages/twenty-server/src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util.ts
index 96323a41d4a..89af586266b 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/utils/has-custom-ai-provider-access.util.ts
@@ -8,9 +8,7 @@ type HasCustomAiProviderAccessArgs = {
seatCount: number;
};
-// Cloud runs a single instance whose seat count spans every customer, so the
-// threshold would always trip; there the plan is enforced per workspace by
-// billing entitlements instead.
+// Cloud's seat count spans every customer, so there billing entitlements enforce the plan per workspace.
export const hasCustomAiProviderAccess = ({
isBillingEnabled,
hasValidEnterprisePlan,
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
index 015080eb193..0297e75f0b5 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
@@ -204,9 +204,7 @@ describe('LocalDriver', () => {
const second = await stat(path.join(storagePath, filePath));
- // Same length, so only the identity distinguishes them: a rewrite in
- // place would keep the inode and leave a promotion unable to tell the
- // two versions apart.
+ // Same length, so only the inode tells them apart; a rewrite in place would keep it.
expect(second.size).toBe(first.size);
expect(second.ino).not.toBe(first.ino);
@@ -359,8 +357,6 @@ describe('LocalDriver', () => {
code: FileStorageExceptionCode.PRECONDITION_FAILED,
});
- // A failed promotion must not strand the object under the private name
- // it was claimed with, where nothing would ever look for it again.
await expect(readdir(folderPath)).resolves.toEqual(['file.txt']);
await expect(
readFile(path.join(folderPath, 'file.txt'), 'utf-8'),
@@ -374,8 +370,7 @@ describe('LocalDriver', () => {
await mkdir(folderPath, { recursive: true });
await writeFile(path.join(folderPath, 'file.txt'), 'original');
- // A non-empty directory in the destination's place makes the final
- // rename fail after the source has already been claimed.
+ // A non-empty directory at the destination makes the final rename fail after the claim.
const blockedDestination = path.join(
storagePath,
'workspace',
@@ -409,8 +404,7 @@ describe('LocalDriver', () => {
const storagePath = await createTempDirectory('local-driver-storage-');
await mkdir(path.join(storagePath, 'workspace'), { recursive: true });
- // A regular file where a directory is expected makes stat fail with
- // ENOTDIR, which root cannot bypass the way it bypasses mode bits.
+ // stat fails with ENOTDIR here, which root cannot bypass the way it bypasses mode bits.
await writeFile(path.join(storagePath, 'workspace', 'blocker'), 'x');
const driver = new LocalDriver({ storagePath });
@@ -427,8 +421,7 @@ describe('LocalDriver', () => {
it('should write and promote a filename at the validation limit', async () => {
const storagePath = await createTempDirectory('local-driver-storage-');
const driver = new LocalDriver({ storagePath });
- // MAX_SEGMENT_LENGTH is the filesystem's own limit, so any suffix the
- // driver adds to the filename for its temporary names would not fit.
+ // MAX_SEGMENT_LENGTH is the filesystem limit, so no temporary suffix could fit.
const filename = `${'a'.repeat(251)}.txt`;
await driver.writeFileStream({
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
index 8cf1955741e..61aa97169ff 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
@@ -27,9 +27,8 @@ export interface LocalDriverOptions {
storagePath: string;
}
-// Local storage has no ETag, so identity comes from the stat fields that a
-// rewrite changes. Enough to catch a swap between an inspection and a move,
-// which is all callers use it for.
+// Local storage has no ETag, so identity comes from the stat fields a rewrite changes; only enough to catch a swap
+// between an inspection and a move.
const buildStatChecksum = (stats: Stats): string =>
`${stats.ino}-${stats.size}-${stats.mtimeMs}`;
@@ -134,8 +133,6 @@ export class LocalDriver implements StorageDriver {
}
}
- // Resolves the on-disk path for a write, creating the parent folder and
- // enforcing storage containment + symlink rejection.
private async resolveWritableRealPathOrThrow(
filePath: string,
): Promise<string> {
@@ -188,19 +185,14 @@ export class LocalDriver implements StorageDriver {
params.filePath,
);
- // Writing through to the destination would mutate the object other callers
- // are already reading, in place and under a stable inode. Promotion
- // identifies the version it validated by inode, so publishing each write as
- // a new one is what keeps that identity meaningful. The temporary name
- // does not carry the original filename: path validation allows filenames
- // up to the filesystem's own limit, so appending to one could not fit.
+ // Publish each write as a new inode: promotion identifies the validated version by inode.
+ // The temporary name omits the filename, which may already be at the filesystem length limit.
const partialFilePath = join(dirname(realFilePath), `.${v4()}.part`);
try {
await pipeline(params.stream, createWriteStream(partialFilePath));
await fs.rename(partialFilePath, realFilePath);
} catch (error) {
- // Remove the partial file so a failed upload can be retried cleanly
await fs.rm(partialFilePath, { force: true });
throw error;
@@ -358,12 +350,7 @@ export class LocalDriver implements StorageDriver {
}
}
- // Checking the source and then renaming it leaves a window in which a client
- // still holding an upload target can publish over the path, so the rename
- // would promote bytes that were never inspected. Claiming the source under a
- // private name first makes the checked object and the moved object the same
- // one: whatever a concurrent upload publishes afterwards lands on the
- // original path and is no longer reachable from here.
+ // Claim the source under a private name first so a concurrent upload cannot get promoted uninspected.
private async movePreconditionedOnChecksum({
fromPath,
toPath,
@@ -385,11 +372,7 @@ export class LocalDriver implements StorageDriver {
await this.renameOrThrow({ fromPath: claimedPath, toPath });
} catch (error) {
- // Put it back so the caller's retry and the cleanup sweep still find it
- // at the path they know: the claim name is private to this call and
- // nothing would look for it again. A concurrent upload may have
- // published there in the meantime, but that path is bound for deletion
- // either way.
+ // Restore it so the caller's retry and the cleanup sweep still find it; the claim name is private.
await fs.rename(claimedPath, fromPath).catch(() => {
this.logger.error(
`Could not restore "${path.basename(fromPath)}" after a failed promotion`,
@@ -446,8 +429,6 @@ export class LocalDriver implements StorageDriver {
return null;
}
- // Local storage has no external endpoint to upload to: the caller falls
- // back to the server-side streaming upload endpoint.
async getPresignedUploadUrl(): Promise<string | null> {
return null;
}
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts
index 341d42837e3..3b19cf5d7be 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts
@@ -209,8 +209,7 @@ export class S3Driver implements StorageDriver {
stream: Readable;
mimeType: string | undefined;
}): Promise<void> {
- // Upload streams the body with bounded memory (multipart under the hood),
- // unlike PutObjectCommand which requires the whole payload upfront.
+ // Upload streams with bounded memory; PutObjectCommand needs the whole payload upfront.
const upload = new Upload({
client: this.s3Client,
params: {
@@ -341,8 +340,7 @@ export class S3Driver implements StorageDriver {
}),
);
- // Backends without CopySourceIfMatch support get an unconditional copy,
- // so this is their only check that the object is still the inspected one.
+ // Backends without CopySourceIfMatch get an unconditional copy, so this is their only check.
if (
isDefined(params.ifMatchChecksum) &&
head.ETag !== params.ifMatchChecksum
@@ -384,9 +382,7 @@ export class S3Driver implements StorageDriver {
}
}
- // Some S3-compatible backends (e.g. OVHcloud) reject CopySourceIfMatch
- // with 501, so fall back to an unconditional copy rather than failing
- // every upload completion on them.
+ // Some S3-compatible backends (e.g. OVHcloud) reject CopySourceIfMatch with 501.
private async copyObjectIfMatch({
fromKey,
toKey,
@@ -591,8 +587,7 @@ export class S3Driver implements StorageDriver {
ContentLength: params.contentLength,
});
- // Content-Type and Content-Length are part of the signature so the client
- // cannot upload a payload of a different type or size than declared.
+ // Signed so the client cannot upload a different type or size than declared.
return getSignedUrl(this.presignClient, command, {
expiresIn: params.expiresInSeconds ?? 900,
signableHeaders: new Set(['content-type', 'content-length']),
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
index b034eb3365d..362e7b568b7 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
@@ -518,9 +518,7 @@ export class FileStorageService {
return file;
}
- // Creates the file record ahead of a direct client upload. The bytes are
- // not in storage yet: the record stays PENDING until the upload is
- // confirmed (completeFileUpload) or reaped by the cleanup cron.
+ // Stays PENDING until completeFileUpload confirms it or the cleanup cron reaps it.
async createPendingFile({
fileFolder,
applicationUniversalIdentifier,
@@ -792,9 +790,7 @@ export class FileStorageService {
});
}
- // Removes only the stored object. deleteFile also drops any row sitting at
- // that path, which is wrong once the row is gone or belongs to a later
- // upload that reused the same resource path.
+ // Unlike deleteFile, leaves the row alone: it may be gone or belong to a later upload at the same path.
async deleteFileObject(params: ResourceIdentifier): Promise<void> {
const driver = this.fileStorageDriverFactory.getCurrentDriver();
const { onStorageFilePath } =
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/types/file-storage-metadata.type.ts b/packages/twenty-server/src/engine/core-modules/file-storage/types/file-storage-metadata.type.ts
index 7d291795cf3..67b2afaaa33 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/types/file-storage-metadata.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/types/file-storage-metadata.type.ts
@@ -1,3 +1,2 @@
-// checksum is whatever the backend can offer as a version identity (an S3
-// ETag); backends that have none omit it and callers lose the precondition.
+// checksum is the backend's version identity (an S3 ETag); without it callers lose the precondition.
export type FileStorageMetadata = { size: number; checksum?: string };
diff --git a/packages/twenty-server/src/engine/core-modules/file/controllers/file.controller.ts b/packages/twenty-server/src/engine/core-modules/file/controllers/file.controller.ts
index 105a889c59a..fd545d3957e 100644
--- a/packages/twenty-server/src/engine/core-modules/file/controllers/file.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/controllers/file.controller.ts
@@ -57,10 +57,7 @@ export class FileController {
private readonly serverFileStorageService: ServerFileStorageService,
) {}
- // Serves application registration assets (logo, gallery images) by their
- // public folder path. These are instance-global marketplace resources, also
- // displayed on the public OAuth authorize page, hence no auth token, unlike
- // the workspace-scoped /file/:folder/:id.
+ // Instance-global marketplace assets, also shown on the public OAuth authorize page, hence no auth.
@Get(
`${ApiPath.Files}/application-registrations/:applicationRegistrationId/*path`,
)
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/max-sanitizable-svg-size.constant.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/max-sanitizable-svg-size.constant.ts
index 8eca45c1d24..e6b88dac246 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/max-sanitizable-svg-size.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/max-sanitizable-svg-size.constant.ts
@@ -1,5 +1,2 @@
-// DOMPurify needs the whole SVG as a string plus a JSDOM tree, so the peak
-// heap is a large multiple of the file. Anything bigger is refused rather
-// than sanitized: node's max string length would throw well below the
-// direct upload cap anyway.
+// DOMPurify's peak heap is a large multiple of the SVG, so bigger files are refused rather than sanitized.
export const MAX_SANITIZABLE_SVG_BYTES = 3 * 1024 * 1024;
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant.ts
index 5abb67ceab0..8b8198605b6 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant.ts
@@ -1,5 +1,2 @@
-// Direct uploads land under this prefix and are only moved to their final
-// path once completeFileUpload has validated them. A presigned PUT URL stays
-// usable until it expires, so a client allowed to write straight to the final
-// path could swap the bytes after they were checked.
+// A presigned PUT stays usable until expiry, so uploads land here and move only once completeFileUpload validates them.
export const PENDING_UPLOAD_PATH_PREFIX = '.pending';
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload.service.create-file-upload.spec.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload.service.create-file-upload.spec.ts
index 1a04734588b..148f56413a1 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload.service.create-file-upload.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload.service.create-file-upload.spec.ts
@@ -41,8 +41,7 @@ describe('FileUploadService.createFileUpload', () => {
);
it('should not refuse an SVG within the limit', async () => {
- // Reaching a collaborator means the guard let it through, which is what
- // this asserts: the empty mocks make that surface as a TypeError.
+ // Passing the size guard reaches a collaborator, which the empty mocks surface as a TypeError.
await expect(
createUpload('logo.svg', MAX_SANITIZABLE_SVG_BYTES),
).rejects.not.toMatchObject({
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
index c3167c1464a..80df6a539a5 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
@@ -87,10 +87,7 @@ export class FileUploadCompletionService {
}),
};
- // Only the quarantined object is ever evidence of this upload. Falling
- // back to the final path would let an object left there by a previous
- // upload of the same resource path complete an upload that never
- // delivered any bytes.
+ // Never fall back to the final path: a previous upload's object there would complete an upload that sent nothing.
const metadata =
await this.fileStorageService.getFileMetadata(pendingLocation);
@@ -129,10 +126,7 @@ export class FileUploadCompletionService {
metadata,
});
- // The presigned PUT stays usable until it expires, so the quarantined
- // object can still be overwritten between the sniff above and this move.
- // Promoting only the version that was inspected is what makes the
- // recorded mimeType describe the bytes that end up at the final path.
+ // The presigned PUT can still overwrite quarantine after the sniff, so only the inspected version is promoted.
await this.fileStorageService.move({
from: pendingLocation,
to: storageLocation,
@@ -148,12 +142,7 @@ export class FileUploadCompletionService {
mimeType,
});
- // The cleanup cron claims a stale PENDING row by deleting it, then deletes
- // its objects, so losing the row here means it won. The promoting copy may
- // have landed after its sweep and be orphaned; it is deliberately left
- // there rather than rolled back, because this path cannot prove the object
- // is still the one it wrote, and deleting a later upload's bytes is far
- // worse than leaking one object.
+ // Losing the row means the cleanup cron reaped it; leak the promoted object rather than risk deleting a later upload.
if (affected === 0) {
this.logger.warn(
`File ${file.id} was reaped while completing; the object promoted to "${file.path}" may be orphaned`,
@@ -266,8 +255,7 @@ export class FileUploadCompletionService {
file = await streamToBuffer(stream, MAX_SANITIZABLE_SVG_BYTES);
} catch (error) {
if (error instanceof StreamSizeExceededError) {
- // Deliberately does not quote `size`: storage understated it, so
- // repeating it here would contradict the failure being reported.
+ // Storage understated `size`, so quoting it would contradict this failure.
throw buildSvgTooLargeException(
`content exceeds the ${MAX_SANITIZABLE_SVG_BYTES} byte limit`,
);
@@ -292,14 +280,11 @@ export class FileUploadCompletionService {
mimeType,
});
- // Rewriting the object gives it a new version identity, so the checksum
- // read before sanitizing would no longer match on the promoting copy.
+ // Sanitizing rewrites the object, so the checksum read before no longer matches.
const sanitizedMetadata =
await this.fileStorageService.getFileMetadata(storageLocation);
- // Returning no identity here would silently downgrade that copy to an
- // unconditional one, so a backend that reported one before the rewrite
- // has to report one after it.
+ // A missing identity would silently downgrade the promoting copy to an unconditional one.
if (
!isDefined(sanitizedMetadata) ||
(isDefined(metadata.checksum) && !isDefined(sanitizedMetadata.checksum))
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts
index f0f580c52e1..033a9e030e7 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts
@@ -64,8 +64,7 @@ export class FileUploadTargetService {
resourcePath,
});
- // The prefix is added after the final path has passed validation, so a
- // path close to the limit would only fail once the client tried to write.
+ // The prefix lengthens the path, so near-limit paths would otherwise fail only when the client writes.
const pendingPathValidation = validateFilePath({
resourcePath: pendingResourcePath,
fileFolder,
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts
index 17e40196297..bf906ca4f6e 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts
@@ -51,9 +51,7 @@ export const DIRECT_UPLOAD_FILE_FOLDERS = [
FileFolder.CorePicture,
] as const;
-// A tarball leaves quarantine through completeAppTarballUpload only, behind
-// the marketplace-apps permission: the generic completion, open to any member
-// allowed to upload files, must not persist bytes in that folder.
+// These folders leave quarantine only through their dedicated, permission-gated completions, never the generic one.
export const DEDICATED_COMPLETION_FILE_FOLDERS = [
FileFolder.AppTarball,
FileFolder.CorePicture,
@@ -111,9 +109,7 @@ export class FileUploadService {
const { ext } = buildFileInfo(filename);
- // Completion refuses to sanitize an SVG this big, so reject before the
- // client transfers it. The declared extension is a client claim, which
- // only makes this a shortcut: the sniffed check at completion decides.
+ // Completion refuses SVGs this big; the declared extension is only a hint, the sniffed check at completion decides.
if (ext.toLowerCase() === 'svg' && size > MAX_SANITIZABLE_SVG_BYTES) {
throw buildSvgTooLargeException(
`declared size ${size} exceeds the ${MAX_SANITIZABLE_SVG_BYTES} byte limit`,
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
index 18b7cd86a07..f93a4f8ed3e 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
@@ -72,10 +72,7 @@ export class PendingFileCleanupService {
continue;
}
- // Claim the row atomically: delete it only while it is still PENDING.
- // If completeFileUpload promoted it to UPLOADED between the fetch above
- // and here, the delete affects no rows and the now-live file (and its
- // object) are left untouched.
+ // Delete only while still PENDING, so a file completeFileUpload just promoted is left untouched.
const { affected } = await this.fileRepository.delete({
id: file.id,
status: FILE_STATUS.PENDING,
@@ -107,9 +104,7 @@ export class PendingFileCleanupService {
return deletedCount;
}
- // The row has already been removed, so this only tidies the (possibly
- // partial, possibly absent) storage object. A failure here leaks bytes but
- // never data, so it is logged rather than retried.
+ // The row is already gone, so a failure here only leaks bytes and is logged rather than retried.
private async deleteStorageObject(file: FileEntity): Promise<void> {
if (!isDefined(file.workspaceId)) {
return;
@@ -136,14 +131,8 @@ export class PendingFileCleanupService {
fileFolder: fileFolder as FileFolder,
};
- // Normally the object is still in quarantine, but a crash between the move
- // and the row update leaves it at its final path with the row PENDING.
- //
- // Quarantine goes first and the two are not concurrent: while a
- // quarantined object still exists, a completion racing this cleanup can
- // move it into the final path after that path has been deleted, orphaning
- // an object no later run will look for. Both still run regardless of the
- // other's outcome, since the row is already gone.
+ // A crash between move and row update leaves the object at its final path, so both are deleted.
+ // Quarantine goes first: a racing completion could otherwise move it into an already-cleaned final path.
const failures: unknown[] = [];
for (const pathToDelete of [
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/__tests__/build-pending-upload-resource-path.util.spec.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/__tests__/build-pending-upload-resource-path.util.spec.ts
index 3c78a3e59f8..b6d9b705fb4 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/__tests__/build-pending-upload-resource-path.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/__tests__/build-pending-upload-resource-path.util.spec.ts
@@ -15,8 +15,7 @@ describe('buildPendingUploadResourcePath', () => {
).toBe(`.pending/${fileId}/field-universal-identifier/document.pdf`);
});
- // The presigned PUT targets the quarantine path, so it has to survive the
- // same storage validation as the final path for every folder shape.
+ // The presigned PUT targets the quarantine path, so it must pass the same validation for every folder shape.
it.each([
{ fileFolder: FileFolder.FilesField, resourcePath: 'field-uid/file.png' },
{ fileFolder: FileFolder.Workflow, resourcePath: 'attachment.pdf' },
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util.ts
index 247b33c7b1a..7e78a67e02a 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util.ts
@@ -1,7 +1,6 @@
import { PENDING_UPLOAD_PATH_PREFIX } from 'src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant';
-// The final resource path is kept verbatim under the prefix so that path and
-// extension validation behave identically for both locations.
+// Kept verbatim so path and extension validation behave identically in quarantine.
export const buildPendingUploadResourcePath = ({
fileId,
resourcePath,
diff --git a/packages/twenty-server/src/engine/core-modules/file/interfaces/file-folder.interface.ts b/packages/twenty-server/src/engine/core-modules/file/interfaces/file-folder.interface.ts
index 7d49225da4e..1987dc271f8 100644
--- a/packages/twenty-server/src/engine/core-modules/file/interfaces/file-folder.interface.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/interfaces/file-folder.interface.ts
@@ -22,9 +22,7 @@ export const IMMUTABLE_FILE_CACHE_CONTROL = 'private, max-age=86400, immutable';
export const PUBLIC_ASSET_CACHE_CONTROL = 'public, max-age=3600';
-// Responses embedding a short-lived presigned URL must never be stored:
-// a cached copy either 403s once the signature expires or leaks a live
-// presigned URL to clients that never authenticated.
+// A cached copy would 403 once the signature expires or leak a live presigned URL.
export const PRESIGNED_URL_NO_STORE_CACHE_CONTROL = 'private, no-store';
export const fileFolderConfigs: Record<FileFolder, FileFolderConfig> = {
diff --git a/packages/twenty-server/src/engine/core-modules/file/services/file.service.ts b/packages/twenty-server/src/engine/core-modules/file/services/file.service.ts
index 16053ff7744..fd56b327cf7 100644
--- a/packages/twenty-server/src/engine/core-modules/file/services/file.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/services/file.service.ts
@@ -231,11 +231,7 @@ export class FileService {
});
if (isDefined(presignedUrl)) {
- // The storage provider serves presigned downloads directly and handles
- // Range requests without proxying the file through the server. It can
- // only echo the response-* overrides set above, so this path carries no
- // X-Content-Type-Options: nosniff; the headers it does carry pin the
- // type sniffed at upload and attach anything not inline-safe.
+ // Presigned downloads bypass the server, so no nosniff; the response-* overrides pin the sniffed type and disposition.
return { type: 'redirect', presignedUrl };
}
diff --git a/packages/twenty-server/src/engine/core-modules/i18n/i18n.service.ts b/packages/twenty-server/src/engine/core-modules/i18n/i18n.service.ts
index c4988dd1017..6b21fac62a0 100644
--- a/packages/twenty-server/src/engine/core-modules/i18n/i18n.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/i18n/i18n.service.ts
@@ -51,10 +51,7 @@ export class I18nService implements OnModuleInit {
{} as Record<keyof typeof APP_LOCALES, I18n>;
async loadTranslations() {
- // The global i18n singleton backs server-side t`…` calls and has no
- // compiled catalog, so it needs a runtime message compiler. Since lingui
- // 5.9 it also throws unless a locale is activated, so activate the source
- // locale (t`…` then renders the English source text via the compiler).
+ // The global singleton backs server-side t`` with no compiled catalog, so it needs a runtime compiler; since lingui 5.9 it also throws unless a locale is active.
i18n.setMessagesCompiler(compileMessage);
i18n.load(SOURCE_LOCALE, enMessages);
i18n.activate(SOURCE_LOCALE);
diff --git a/packages/twenty-server/src/engine/core-modules/impersonation/services/impersonation.service.ts b/packages/twenty-server/src/engine/core-modules/impersonation/services/impersonation.service.ts
index 0f998d9bca0..a98414e196a 100644
--- a/packages/twenty-server/src/engine/core-modules/impersonation/services/impersonation.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/impersonation/services/impersonation.service.ts
@@ -97,8 +97,7 @@ export class ImpersonationService {
);
}
- // Hands the impersonator back the session parked when impersonation started.
- // Nothing is minted on the strength of the impersonated user's cookie.
+ // Restores the parked session; never mints one from the impersonated user's cookie.
async stopImpersonation({
impersonationContext,
workspaceId,
@@ -167,8 +166,7 @@ export class ImpersonationService {
return { canRestoreImpersonatorSession };
}
- // The parked token is evidence of nothing on its own, so it is re-resolved
- // and checked against the impersonator the impersonation session names.
+ // The parked token proves nothing alone, so it is re-checked against the impersonator.
private async restoreImpersonatorSession(
request: Request,
impersonatorUserWorkspaceId: string,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts
index 27bd41fb104..18dedbcc64d 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local/services/local-child-process-runner.service.ts
@@ -10,8 +10,7 @@ import { getLocalSdkLayerPath } from 'src/engine/core-modules/logic-function/log
import { HANDLER_NAME_REGEX } from 'src/engine/metadata-modules/logic-function/constants/handler.contant';
export class LocalChildProcessRunnerService {
- // Symlinks everything from the deps layer except twenty-client-sdk,
- // which comes from the SDK layer (workspace-specific generated client).
+ // twenty-client-sdk comes from the SDK layer (workspace-specific generated client), not the deps layer.
async assembleNodeModules({
sourceTemporaryDir,
flatApplication,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index ef210c1ee0e..819e1f6408e 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -153,8 +153,7 @@ export class LogicFunctionExecutorService {
logicFunctionId,
});
- // Checked before the shared workspace throttle so a flood from a stopped
- // application cannot exhaust the token bucket of the other applications.
+ // Before the shared workspace throttle so a stopped app's flood cannot drain other apps' token bucket.
await this.assertApplicationNotStopped(flatApplication);
await this.throttleExecution(workspaceId);
@@ -443,8 +442,7 @@ export class LogicFunctionExecutorService {
userWorkspaceId?: string;
workspaceDeletionRequestTimestamp?: string;
}) {
- // Two tokens so a handler can choose per call which access it acts with,
- // rather than the whole run being locked to one of them.
+ // Two tokens so a handler can choose per call which access it acts with.
const hasTriggeringPerson = isDefined(userId) && isDefined(userWorkspaceId);
const [applicationAccessToken, delegatedAccessToken] = await Promise.all([
@@ -490,8 +488,7 @@ export class LogicFunctionExecutorService {
...serverVariables,
...workspaceVariables,
[DEFAULT_API_URL_NAME]: baseUrl ?? '',
- // Falls back to the application when nobody triggered the run, so a cron
- // schedule or an install hook keeps working without asking for anything.
+ // Falls back to the application so cron schedules and install hooks work with nobody triggering.
[DEFAULT_APP_ACCESS_TOKEN_NAME]: (
delegatedAccessToken ?? applicationAccessToken
).token,
@@ -651,11 +648,7 @@ export class LogicFunctionExecutorService {
functionName: flatLogicFunction.name,
});
- // Billing-exempt apps (first-party maintenance apps whose per-record
- // triggers fire during mailbox/calendar import) do not consume the
- // workspace's credits for the execution itself. Explicit chargeCredits
- // calls and AI token usage from within the function are billed separately
- // and stay untouched.
+ // Billing-exempt apps skip the invocation charge; their explicit chargeCredits and AI usage are still billed.
const { invocationCreditsMicro, durationCreditsMicro, billedDurationMs } =
computeLogicFunctionExecutionCreditsMicro({
durationMs: result.billedDurationMs,
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
index b401c503c3c..0f5c5c1a645 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
@@ -448,7 +448,6 @@ export class BullMQDriver
);
}
- // This ensures only one waiting job can be queued for a specific option.id
if (options?.id && !options?.allowDuplicatedPrefixes) {
const waitingJobIds = await this.getWaitingJobIds(queueName);
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.explorer.ts b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.explorer.ts
index 67703de1f50..fc1a8b78512 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.explorer.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue.explorer.ts
@@ -65,9 +65,7 @@ export class MessageQueueExplorer implements OnModuleInit {
const groupedProcessors = this.groupProcessorsByQueueName(processors);
- // Filter out empty entries: an explicit empty env value is parsed as ['']
- // by the shared ARRAY transformer, which would otherwise turn an empty
- // allowlist (meaning "all queues") into "no queues"
+ // The ARRAY transformer parses an empty env value as [''], which would turn "all queues" into "no queues".
const enabledQueues = this.twentyConfigService
.get('WORKER_ENABLED_QUEUES')
.filter((queueName) => queueName.length > 0);
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
index 5ce31595fb9..9598973d516 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
@@ -124,10 +124,7 @@ export class OnboardingService {
userId: string;
workspaceId: string;
}): Promise<OnboardingStatus | null> {
- // We always read the workspace directly from the database here (bypassing
- // the per-instance core entity cache) so that onboardingStatus reflects the
- // freshest activationStatus right after activateWorkspace, even when a
- // sibling server instance still has a stale cached workspace.
+ // Bypasses the core entity cache, which a sibling instance may hold stale right after activateWorkspace.
const workspace = await this.workspaceRepository.findOne({
where: { id: workspaceId },
});
@@ -421,8 +418,7 @@ export class OnboardingService {
queryRunner,
);
case OnboardingStatus.INVITE_TEAM:
- // User-scoped on purpose: the workspace-scoped flag would pull every
- // other member of the workspace back to the invite screen.
+ // User-scoped: the workspace-scoped flag would pull every other member back to the invite screen.
return this.setOnboardingInviteTeamPending(
{
userId,
@@ -928,10 +924,7 @@ export class OnboardingService {
workspaceId: string;
employeeCount: number | null;
}) {
- // Reading the tiers throws on its own when the configured value is not a
- // parseable JSON object, so it sits inside the guard with the grant: a
- // reward nobody has configured correctly must not cost anyone their
- // onboarding.
+ // Reading the tiers throws on malformed config, so it stays guarded: a broken reward must not break onboarding.
try {
const { amountMicro, malformedTierKeys } =
getOnboardingEnrichmentCreditRewardMicro({
@@ -942,8 +935,7 @@ export class OnboardingService {
});
if (malformedTierKeys.length > 0) {
- // Dropping a malformed tier silently would under-pay every workspace
- // that should have matched it, with nothing to notice it by.
+ // Otherwise a dropped tier would silently under-pay every workspace that should have matched it.
this.exceptionHandlerService.captureExceptions([
new Error(
`Ignored malformed ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS entries: ${malformedTierKeys.join(', ')}`,
@@ -960,10 +952,7 @@ export class OnboardingService {
amountMicro,
type: BillingCreditGrantType.ONBOARDING_REWARD,
reason: 'Onboarding reward: enrichment-qualified workspace',
- // The only gate on the reward, deliberately: it is keyed on the
- // workspace rather than the enriching user so that a re-run of the
- // enrichment, or a second member qualifying later, replays instead of
- // topping up a balance the workspace already received.
+ // Keyed on the workspace, not the user, so re-runs and later members replay instead of topping up.
idempotencyKey: `${ONBOARDING_REWARD_IDEMPOTENCY_KEY_PREFIXES.enrichmentQualification}:${workspaceId}`,
});
} catch (error) {
@@ -1131,8 +1120,7 @@ export class OnboardingService {
throw new Error('Transaction entity manager has no query runner');
}
- // Claiming the offer is the single-winner gate: a concurrent enrichment
- // loses the insert and must not resurrect a step the user already skipped.
+ // Single-winner gate: a concurrent enrichment must not resurrect a step the user already skipped.
const hasClaimedBookCallOffer =
await this.userVarsService.setIfNotExists(
{
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type.ts b/packages/twenty-server/src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type.ts
index 0364cfa4fc0..ae6780020d0 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type.ts
@@ -1,7 +1,3 @@
-// A band of enriched company data and what a workspace landing in it is worth.
-// Conditions are additive over time: a qualification score will join
-// minEmployeeCount here, and a tier missing the newer field keeps matching on
-// the conditions it does carry.
export type OnboardingEnrichmentCreditRewardTier = {
minEmployeeCount: number;
amountMicro: number;
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util.ts b/packages/twenty-server/src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util.ts
index b55fc003587..250260fae5e 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util.ts
@@ -3,8 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type OnboardingEnrichmentCreditRewardTier } from 'src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type';
-// Tiers are hand-authored config, so a malformed entry must drop out rather
-// than coerce into a threshold of zero and pay every matched workspace.
+// Hand-authored config: a malformed tier must drop out rather than coerce to a zero threshold that pays everyone.
const isUsableTier = (tier: OnboardingEnrichmentCreditRewardTier): boolean =>
isNumber(tier?.minEmployeeCount) &&
tier.minEmployeeCount >= 0 &&
@@ -24,9 +23,7 @@ export const getOnboardingEnrichmentCreditRewardMicro = ({
const entries = Object.entries(tiers);
- // Reported whatever the employee count, so a mistyped tier surfaces on the
- // first enrichment after the config change rather than waiting for a
- // workspace that would have matched it.
+ // Reported regardless of match so a mistyped tier surfaces on the first enrichment.
const malformedTierKeys = entries
.filter(([, tier]) => !isUsableTier(tier))
.map(([key]) => key);
@@ -35,8 +32,7 @@ export const getOnboardingEnrichmentCreditRewardMicro = ({
return { amountMicro: null, malformedTierKeys };
}
- // Tiers are keyed for legibility, not ordered, so every one is measured and
- // the most generous match is the one owed.
+ // Tiers are keyed, not ordered, so the most generous match wins.
const matchedAmounts = entries
.filter(
([, tier]) =>
diff --git a/packages/twenty-server/src/engine/core-modules/open-api/utils/__tests__/generate-random-field-value.util.spec.ts b/packages/twenty-server/src/engine/core-modules/open-api/utils/__tests__/generate-random-field-value.util.spec.ts
index f06a6dd376d..17deb36c73c 100644
--- a/packages/twenty-server/src/engine/core-modules/open-api/utils/__tests__/generate-random-field-value.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/open-api/utils/__tests__/generate-random-field-value.util.spec.ts
@@ -9,8 +9,7 @@ const buildField = (name: string, type: FieldMetadataType) => ({
});
describe('generateRandomFieldValue', () => {
- // The document is diffed against main's in CI, so two generations of the same
- // field have to agree or every operation reads as changed.
+ // CI diffs the document against main's, so two generations of a field must agree.
it.each([
FieldMetadataType.UUID,
FieldMetadataType.TEXT,
diff --git a/packages/twenty-server/src/engine/core-modules/open-api/utils/generate-random-field-value.util.ts b/packages/twenty-server/src/engine/core-modules/open-api/utils/generate-random-field-value.util.ts
index 646cf282f4a..a2fc2b3f5b9 100644
--- a/packages/twenty-server/src/engine/core-modules/open-api/utils/generate-random-field-value.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/open-api/utils/generate-random-field-value.util.ts
@@ -16,8 +16,7 @@ type ExampleField = Pick<
// Its own instance so seeding cannot disturb the shared faker other callers use.
const faker = new Faker({ locale: en });
-// CI diffs this document against the one main generates, so an example may only
-// depend on the field it describes. Field ids are per-workspace, hence the name.
+// CI diffs this document against main's, so seed from the field name and type (ids are per-workspace).
const seedForField = (field: ExampleField) => {
let seed = 0;
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.ts b/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.ts
index b4ea4310f29..6db4373c215 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/constants/open-when-detached-object-universal-identifiers.constant.ts
@@ -2,9 +2,7 @@
import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-// Notes and tasks were readable by every member before they inherited from
-// their targets, so one attached to nothing stays that way instead of falling
-// back to its creator only
+// Notes and tasks were open to every member before inheriting from targets, so detached ones stay open.
export const OPEN_WHEN_DETACHED_OBJECT_UNIVERSAL_IDENTIFIERS: string[] = [
STANDARD_OBJECTS.note.universalIdentifier,
STANDARD_OBJECTS.task.universalIdentifier,
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.ts
index ee29e2a553f..f5203ade587 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/services/record-access-policy.service.ts
@@ -68,9 +68,7 @@ export class RecordAccessPolicyService {
private readonly recordShareStorageService: RecordShareStorageService,
) {}
- // A subject receives the records a query would return it: its role must read
- // the object and the row-level filter must hold on the event snapshot before
- // the share gate of the object is consulted.
+ // Mirrors the query gate: role read, then the row-level filter on the event snapshot, then the share gate.
buildEventRecordAccessGate({
workspaceId,
objectMetadata,
@@ -408,8 +406,7 @@ export class RecordAccessPolicyService {
),
),
);
- // A row trashed along with the record still attaches it, as in the
- // query gate; rows trashed before any of these records cannot
+ // Rows trashed along with the record still attach it, as in the query gate; rows trashed earlier do not.
const trashedChildRows = await childRepository
.createQueryBuilder()
.select(['id', parent.childJoinColumnName, 'deletedAt'])
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts
index dc34eacfcc7..503c8d76325 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/services/record-share-storage.service.ts
@@ -27,8 +27,7 @@ type RecordShareRepository = WorkspaceRepository<RecordShare>;
export class RecordShareStorageService {
constructor(private readonly workspaceOrmManager: WorkspaceOrmManager) {}
- // Authorization and grant changes must share the caller's transaction.
- // OWNER and APPLICATION grants are managed by their respective producers.
+ // Must share the caller's transaction; OWNER and APPLICATION grants are managed by their producers.
async setManualShare({
workspaceId,
share,
@@ -112,15 +111,13 @@ export class RecordShareStorageService {
if (recordIds.length === 0) {
return;
}
- // History transactions can span core and workspace tables and must reuse
- // their existing connection rather than open a separate ORM transaction.
+ // History transactions span core and workspace tables, so they must reuse their connection.
await manager.query(
`DELETE FROM ${escapeIdentifier(getWorkspaceSchemaName(workspaceId))}.${escapeIdentifier(RECORD_SHARE_OBJECT_METADATA_NAME)} WHERE "objectMetadataId" = $1 AND "recordId" = ANY($2::uuid[])`,
[objectMetadataId, recordIds],
);
}
- // Each criterion is ANDed, and a row matching any of them is deleted.
async deleteMatching({
workspaceId,
criteria,
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/services/record-sharing.service.ts b/packages/twenty-server/src/engine/core-modules/record-share/services/record-sharing.service.ts
index 6c164722b73..6f25d660a0b 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/services/record-sharing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/services/record-sharing.service.ts
@@ -225,8 +225,7 @@ export class RecordSharingService {
),
args.authContext,
);
- // A writer may revoke the grant that allowed their own access. The saved
- // mutation must still succeed, returning a redacted state after revocation.
+ // A writer may revoke their own access; the mutation must still succeed with a redacted state.
const permissions = await this.getPermissions(args);
if (!permissions.canRead) {
return {
diff --git a/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts b/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts
index e59f1bbb9de..d33a23b990b 100644
--- a/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/record-share/utils/build-inherited-readability-condition.util.ts
@@ -74,8 +74,7 @@ export const buildInheritedReadabilityCondition = ({
const parameters: ObjectLiteral = {};
const quotedTableAlias = escapeIdentifier(tableAlias);
- // The share rows on the record itself, its creator's among them, grant
- // access on their own, as they do on a PRIVATE record
+ // The record's own share rows, its creator's included, grant access on their own, as on a PRIVATE record.
const ownRecordShareCondition = buildRecordShareCondition({
tableAlias,
recordShareTableExpression,
diff --git a/packages/twenty-server/src/engine/core-modules/search/services/search.service.ts b/packages/twenty-server/src/engine/core-modules/search/services/search.service.ts
index 268d7fe3e83..e42a5eaab93 100644
--- a/packages/twenty-server/src/engine/core-modules/search/services/search.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/search/services/search.service.ts
@@ -204,8 +204,7 @@ export class SearchService {
});
}
- // The simple text search configuration does not segment continuous CJK text,
- // so substring matching is needed when the full-text search misses.
+ // The simple text search config does not segment CJK, so fall back to substring matching.
async buildSearchQueryAndGetRecordsWithFallback<
Entity extends ObjectLiteral,
>({
@@ -375,7 +374,7 @@ export class SearchService {
.addOrderBy('id', 'ASC', 'NULLS FIRST')
.setParameter('searchTerms', searchTerms)
.setParameter('searchTermsOr', searchTermsOr)
- .take(limit + 1) // We take one more to check if hasNextPage is true
+ .take(limit + 1)
.getRawMany<ObjectRecord & { tsRank: number; tsRankCD: number }>();
}
diff --git a/packages/twenty-server/src/engine/core-modules/secret-encryption/secret-encryption.service.ts b/packages/twenty-server/src/engine/core-modules/secret-encryption/secret-encryption.service.ts
index 9ffc4cc9957..6be9eafc48b 100644
--- a/packages/twenty-server/src/engine/core-modules/secret-encryption/secret-encryption.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/secret-encryption/secret-encryption.service.ts
@@ -30,9 +30,7 @@ export class SecretEncryptionService {
private readonly environmentConfigDriver: EnvironmentConfigDriver,
) {}
- // Legacy CTR pair (`encrypt` / `decrypt`) is intentionally left unbranded.
- // Its callers predate the enc:v2 envelope and never went through the
- // branded API; retrofitting them is tracked as a separate follow-up.
+ // TODO: migrate legacy CTR callers to the branded enc:v2 envelope.
public encrypt(value: string): string {
if (!isDefined(value)) {
return value;
@@ -45,9 +43,8 @@ export class SecretEncryptionService {
return encryptAesCtr({ plaintext: value, rawKey: primary });
}
- // Legacy CTR has no integrity tag, so a wrong key produces an arbitrary
- // byte sequence rather than throwing. Rotation of these rows requires
- // migrating the consumer to the versioned envelope first.
+ // CTR has no integrity tag, so a wrong key yields garbage instead of throwing:
+ // migrate a caller to enc:v2 before rotating the key its rows use.
public decrypt(value: string): string {
if (!isDefined(value)) {
return value;
@@ -75,8 +72,6 @@ export class SecretEncryptionService {
}
public maskDecryptedValue(decryptedValue: string, mask: string): string {
- // Visible-char count caps at 5 and at one-tenth of the secret length, so
- // short secrets reveal nothing and longer secrets reveal a stable prefix.
const visibleCharsCount = Math.min(
5,
Math.floor(decryptedValue.length / 10),
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.ts
index c4686f51637..d173aef9b62 100644
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/secure-http-client.service.ts
@@ -32,11 +32,8 @@ export class SecureHttpClientService {
constructor(private readonly twentyConfigService: TwentyConfigService) {}
- // Returns an SSRF-protected HTTP client for external requests.
- // Protection is enforced at the connection level via custom agents
- // that validate resolved IPs, which covers redirects automatically.
- // When context is provided, outbound requests are logged with
- // workspace/user info for GuardDuty correlation.
+ // SSRF protection is enforced at connection level by validating resolved IPs, which also covers redirects.
+ // With a context, outbound requests are logged with workspace/user info for GuardDuty correlation.
getHttpClient(
config?: SecureHttpClientConfig,
context?: OutboundRequestContext,
@@ -102,8 +99,7 @@ export class SecureHttpClientService {
return client;
}
- // Returns a plain HTTP client for requests to trusted internal URLs
- // (e.g., the server's own API endpoints). Not SSRF-protected.
+ // Not SSRF-protected: trusted internal URLs only.
getInternalHttpClient(config?: CreateAxiosDefaults): AxiosInstance {
return axios.create(config);
}
@@ -116,8 +112,7 @@ export class SecureHttpClientService {
return buildAxiosFetch(this.getHttpClient()) as typeof globalThis.fetch;
}
- // For libraries that own their HTTP stack and only accept an agent
- // (openid-client). Undefined means no restriction.
+ // For libraries that only accept an agent (openid-client); undefined means no restriction.
getSsrfSafeAgent(url: URL): http.Agent | undefined {
const allowedInternalHosts = this.getAllowedInternalHosts();
@@ -142,8 +137,7 @@ export class SecureHttpClientService {
}
private getAllowedInternalHosts(): string[] {
- // OUTBOUND_HTTP_SAFE_MODE_ENABLED is deprecated but still honoured so
- // self-hosted setups that turned it off keep working after upgrading.
+ // Deprecated but still honoured so self-hosted setups that disabled it keep working.
if (
this.twentyConfigService.get('OUTBOUND_HTTP_SAFE_MODE_ENABLED') === false
) {
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.ts
index 6823fa25242..16e258c7466 100644
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/__tests__/create-ssrf-safe-agent.util.spec.ts
@@ -10,7 +10,6 @@ const createMockSocket = (): Socket & { destroy: jest.Mock } => {
return Object.assign(emitter, {
destroy: jest.fn(),
- // Minimal Socket stubs to avoid type errors
connecting: false,
writable: true,
}) as unknown as Socket & { destroy: jest.Mock };
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.ts
index 364272b55b9..b4de697b4cf 100644
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/create-ssrf-safe-agent.util.ts
@@ -7,9 +7,7 @@ import { getIsBlockedIp } from 'src/engine/core-modules/secure-http-client/utils
type IsBlockedIp = ReturnType<typeof getIsBlockedIp>;
-// Checks whether a hostname is a blocked IP literal.
-// Returns false for domain names — those are validated after DNS
-// resolution in the socket 'lookup' event handler.
+// Domain names are validated after DNS resolution, in the socket 'lookup' handler.
const isHostnameBlockedIp = (
hostname: string,
isBlockedIp: IsBlockedIp,
@@ -27,14 +25,12 @@ const validateHost = (host: string | undefined, isBlockedIp: IsBlockedIp) => {
}
};
-// Validates a resolved IP and destroys the socket if it's blocked.
-// Fails closed: if the IP cannot be parsed, the socket is destroyed.
+// Fails closed: an unparseable IP destroys the socket.
const attachLookupValidation = (
duplex: Duplex,
isBlockedIp: IsBlockedIp,
): Socket => {
- // createConnection returns a net.Socket at runtime; the Duplex
- // return type in @types/node is overly broad.
+ // @types/node types this as Duplex, but it is a net.Socket at runtime.
const socket = duplex as Socket;
socket.on('lookup', (error: Error | null, address: string) => {
@@ -62,10 +58,7 @@ const attachLookupValidation = (
return socket;
};
-// Agents that block connections to private IPs. Validation happens at
-// the connection level (createConnection + socket 'lookup' event),
-// which means every connection is checked — including those created
-// by automatic redirect following.
+// Validated per connection, so connections opened by redirect following are checked too.
class SsrfSafeHttpAgent extends http.Agent {
constructor(private readonly allowedInternalHosts: string[]) {
super();
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util.ts
index 55f7ff6e052..84129c962a3 100644
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/get-is-blocked-ip.util.ts
@@ -2,8 +2,7 @@ import { isAllowedInternalHost } from 'src/engine/core-modules/secure-http-clien
import { isLinkLocalIp } from 'src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util';
import { isPrivateIp } from 'src/engine/core-modules/secure-http-client/utils/is-private-ip.util';
-// An allowlisted host may reach private networks but never the link-local
-// range, so a DNS change cannot turn it into a path to the metadata service.
+// Allowlisted hosts never reach link-local, so a DNS change cannot expose the metadata service.
export const getIsBlockedIp = (
host: string | undefined,
allowedInternalHosts: string[],
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util.ts
index 608fa5b546b..4803a2d4f0a 100644
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/is-link-local-ip.util.ts
@@ -2,8 +2,7 @@ import { BlockList } from 'net';
import { matchesIpRanges } from 'src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util';
-// Cloud metadata services (169.254.169.254, ECS/EKS task credentials) live in
-// the link-local range, so it is never opened by the internal host allowlist.
+// Cloud metadata services live here, so the internal host allowlist never opens this range.
const LINK_LOCAL_RANGES = new BlockList();
LINK_LOCAL_RANGES.addSubnet('169.254.0.0', 16);
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util.ts
index 4e46f8b40bc..f1b8ecf5602 100644
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/matches-ip-ranges.util.ts
@@ -4,8 +4,7 @@ const fromLong = (ipl: number): string => {
return `${ipl >>> 24}.${(ipl >> 16) & 255}.${(ipl >> 8) & 255}.${ipl & 255}`;
};
-// Parses IPv4 in any encoding (dotted decimal, octal, hex, bare integer)
-// into a 32-bit unsigned integer. Returns -1 for invalid input.
+// Every IPv4 encoding (octal, hex, bare integer) must normalize, or it slips past the range check. -1 means invalid.
const normalizeToLong = (addr: string): number => {
const parts = addr.split('.').map((part) => {
if (part.startsWith('0x') || part.startsWith('0X')) {
@@ -47,9 +46,6 @@ const normalizeToLong = (addr: string): number => {
return val >>> 0;
};
-// Extracts the embedded IPv4 from an IPv4-mapped IPv6 address in hex
-// notation (e.g. ::ffff:a9fe:a9fe → 169.254.169.254). Returns null
-// if the address is not in this form.
const HEX_MAPPED_RE = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
const extractIpv4FromHexMappedIpv6 = (addr: string): string | null => {
@@ -65,8 +61,6 @@ const extractIpv4FromHexMappedIpv6 = (addr: string): string | null => {
return `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;
};
-// Extracts the embedded IPv4 from an IPv4-mapped IPv6 address in
-// dotted-decimal notation (e.g. ::ffff:127.0.0.1 → 127.0.0.1).
const DOTTED_MAPPED_RE = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i;
const extractIpv4FromDottedMappedIpv6 = (addr: string): string | null => {
@@ -76,26 +70,23 @@ const extractIpv4FromDottedMappedIpv6 = (addr: string): string | null => {
};
export const matchesIpRanges = (ranges: BlockList, addr: string): boolean => {
- // IPv4-mapped IPv6 in hex form — the form Node.js URL parser produces.
+ // The form Node's URL parser produces.
const hexMappedIpv4 = extractIpv4FromHexMappedIpv6(addr);
if (hexMappedIpv4 !== null) {
return ranges.check(hexMappedIpv4);
}
- // IPv4-mapped IPv6 in dotted-decimal form (::ffff:D.D.D.D)
const dottedMappedIpv4 = extractIpv4FromDottedMappedIpv6(addr);
if (dottedMappedIpv4 !== null) {
return ranges.check(dottedMappedIpv4);
}
- // Pure IPv6 (any address containing a colon that isn't IPv4-mapped)
if (addr.includes(':')) {
return ranges.check(addr, 'ipv6');
}
- // IPv4 in any encoding (standard, octal, hex, bare integer)
const ipl = normalizeToLong(addr);
if (ipl < 0) {
diff --git a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util.ts b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util.ts
index 9eb40bf067e..3c0f5b10aeb 100644
--- a/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/secure-http-client/utils/normalize-allowed-internal-host.util.ts
@@ -1,5 +1,4 @@
-// Operators paste whatever they have at hand (a bare host, host:port or the
-// full issuer URL); connections are matched on the hostname alone.
+// Operators paste a bare host, host:port or full issuer URL; connections match on the hostname alone.
export const normalizeAllowedInternalHost = (entry: string): string => {
const trimmed = entry.trim();
diff --git a/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts b/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts
index f57b4b015d2..ffbf60793cf 100644
--- a/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/sso/services/sso.service.ts
@@ -35,11 +35,8 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent
export class SsoService {
private readonly featureLookUpKey = BillingEntitlementKey.SSO;
- // openid-client resolves this hook on whichever object issues the request:
- // the Issuer class for discovery, the issuer instance for JWKS and the
- // client instance for token and userinfo calls, so it is set on all three.
- // It deep-merges what the hook returns with its own per-request options
- // (method, headers, body), so only the agent needs to be returned.
+ // openid-client resolves this hook on the Issuer class, issuer and client instances, so all three get it.
+ // It deep-merges the result with its own per-request options, so only the agent is returned.
private readonly oidcHttpOptions = (url: URL) => ({
agent: this.secureHttpClientService.getSsrfSafeAgent(url),
});
@@ -73,8 +70,7 @@ export class SsoService {
try {
return await Issuer.discover(issuerUrl);
} catch (error) {
- // Surfaced so a blocked private-network issuer is diagnosable at setup;
- // at login the failure would only show as a redirect.
+ // Surfaced so a blocked private-network issuer is diagnosable at setup; at login it only shows as a redirect.
const reason = error instanceof Error ? error.message : String(error);
throw new SsoException(
diff --git a/packages/twenty-server/src/engine/core-modules/sso/workspace-sso-identity-provider.entity.ts b/packages/twenty-server/src/engine/core-modules/sso/workspace-sso-identity-provider.entity.ts
index cfb58c27ee8..0d6cbdd579d 100644
--- a/packages/twenty-server/src/engine/core-modules/sso/workspace-sso-identity-provider.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/sso/workspace-sso-identity-provider.entity.ts
@@ -72,14 +72,12 @@ export class WorkspaceSsoIdentityProviderEntity extends WorkspaceRelatedEntity {
@Column()
issuer: string;
- // OIDC
@Column({ nullable: true })
clientID?: string;
@Column({ nullable: true })
clientSecret?: string;
- // SAML
@Column({ nullable: true })
ssoURL?: string;
diff --git a/packages/twenty-server/src/engine/core-modules/target/services/message-calendar-target-readiness.service.ts b/packages/twenty-server/src/engine/core-modules/target/services/message-calendar-target-readiness.service.ts
index 228fe948315..49a47a9902f 100644
--- a/packages/twenty-server/src/engine/core-modules/target/services/message-calendar-target-readiness.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/target/services/message-calendar-target-readiness.service.ts
@@ -32,8 +32,7 @@ export class MessageCalendarTargetReadinessService {
}
async isReady(workspaceId: string): Promise<boolean> {
- // During workspace upgrades the target objects may not exist yet;
- // retain legacy reads until metadata sync creates both junctions.
+ // During upgrades the target objects may not exist yet, so keep legacy reads until metadata sync creates them.
const { flatObjectMetadataMaps } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
'flatObjectMetadataMaps',
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts
index 2e34a2d1408..5d90868ff91 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/__tests__/database-tool.provider.spec.ts
@@ -97,9 +97,7 @@ describe('DatabaseToolProvider', () => {
}),
} as unknown as WorkspaceManyOrAllFlatEntityMapsCacheService;
- // Returns the messageId so the label util falls back to the English source,
- // mirroring the runtime behavior when no translation exists for the locale.
- // getI18nInstance resolves verb descriptors to their English source message.
+ // Echo the messageId so labels fall back to the English source, as at runtime without a translation.
const i18nService = {
translateMessage: jest.fn(
({ messageId }: { messageId: string }) => messageId,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts
index e5a22a41e1b..c5d12c131a7 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/database-tool.provider.ts
@@ -56,10 +56,7 @@ export class DatabaseToolProvider implements ToolProvider {
return true;
}
- // Database CRUD tools emit `executionRef.kind === 'database_crud'` descriptors
- // and are dispatched inline by ToolExecutorService. The static-tool path is
- // unreachable for this provider; this method exists only to satisfy the
- // interface.
+ // Unreachable: database CRUD descriptors are dispatched inline by ToolExecutorService.
async executeStaticTool(
toolName: string,
_args: Record<string, unknown>,
@@ -467,8 +464,7 @@ export class DatabaseToolProvider implements ToolProvider {
}
}
- // Every record operation but group_by answers with recordReferences, which
- // the records widget turns into links; group_by answers with aggregates.
+ // group_by answers with aggregates, not the recordReferences the records widget links.
return descriptors.map((descriptor) =>
descriptor.operation === 'group_by'
? descriptor
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
index 0a33fb6d7c3..77c25a8e8af 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
@@ -30,10 +30,7 @@ export class LogicFunctionToolProvider implements ToolProvider {
return true;
}
- // Logic function tools emit `executionRef.kind === 'logic_function'`
- // descriptors and are dispatched inline by ToolExecutorService. The
- // static-tool path is unreachable for this provider; this method exists
- // only to satisfy the interface.
+ // Unreachable: logic function descriptors are dispatched inline by ToolExecutorService.
async executeStaticTool(
toolName: string,
_args: Record<string, unknown>,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts
index 851c823b45c..2f1a2ca61f2 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/resolvers/tool-index.resolver.ts
@@ -94,8 +94,7 @@ export class ToolIndexResolver {
});
}
- // Resolves the inputSchema for a single tool on demand (avoids computing
- // schemas for every tool in the workspace when listing the tool index).
+ // On demand, so listing the tool index does not compute every tool's schema.
@Query(() => graphqlTypeJson, { nullable: true })
@UseGuards(NoPermissionGuard)
async getToolInputSchema(
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
index 4cbf7ad95e0..708a3c8ae7c 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-executor.service.ts
@@ -319,9 +319,7 @@ export class ToolExecutorService {
);
}
- // Defense-in-depth: catalog and by-name lookups already filter by
- // `isAvailable`, but re-verify at dispatch so the gate is enforced in
- // one place regardless of how the descriptor reached us.
+ // Defense-in-depth: re-verify at dispatch whatever path the descriptor came from.
if (!(await provider.isAvailable(context))) {
return {
success: false,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
index 1fe667c3874..d6e6c9aee48 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/services/tool-registry.service.ts
@@ -381,8 +381,7 @@ export class ToolRegistryService {
);
}
- // Eager loading tools by categories (MCP, workflow agent).
- // These paths need full schemas, so generate with includeSchemas: true.
+ // MCP and the workflow agent need full schemas.
async getToolsByCategories(
context: ToolProviderContext,
options: ToolRetrievalOptions = {},
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/tool-provider.module.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/tool-provider.module.ts
index af9d43ceb92..526c32fe7bd 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/tool-provider.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/tool-provider.module.ts
@@ -43,15 +43,8 @@ import { EmailingModule } from 'src/modules/emailing/emailing.module';
import { ToolIndexResolver } from './resolvers/tool-index.resolver';
import { ToolRegistryService } from './services/tool-registry.service';
-// NOTE: This module does NOT import WorkflowToolsModule or DashboardToolsModule
-// directly: their service graphs transitively reach AiAgentExecutionModule which
-// forwardRef's back into ToolProviderModule. Those two @Global() modules provide
-// a service token that their respective providers consume via @Optional()
-// @Inject, breaking the cycle.
-//
-// Webhook and NavigationMenuItem do NOT have that cycle, so we import their
-// entity modules directly and the providers inject the services the normal way
-// (same pattern as views/objects/metadata).
+// Workflow and Dashboard tools modules reach AiAgentExecutionModule, which forwardRefs back here,
+// so their @Global() modules provide tokens consumed via @Optional() @Inject instead of being imported.
@Module({
imports: [
@@ -94,10 +87,7 @@ import { ToolRegistryService } from './services/tool-registry.service';
WebhookToolProvider,
WorkflowToolProvider,
{
- // TOOL_PROVIDERS contains only providers implementing ToolProvider
- // (registry tools with descriptors). The native tool binder is a
- // parallel concept and is exported for surfaces that bind SDK-native
- // tools directly into their model ToolSet.
+ // Only ToolProvider implementations; the native tool binder is exported separately.
provide: TOOL_PROVIDERS,
useFactory: (
actionProvider: ActionToolProvider,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/types/tool-index-entry.type.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/types/tool-index-entry.type.ts
index 3c6ce4ae7a4..f9b9a84e6c7 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/types/tool-index-entry.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/types/tool-index-entry.type.ts
@@ -11,8 +11,7 @@ export type ToolIndexEntry = {
objectName?: string;
operation?: string;
icon?: string;
- // Built-in widget that renders this tool's calls in the AI chat.
widgetName?: ToolWidgetName;
- // App-supplied front component that renders this tool's calls instead.
+ // App-supplied front component that renders this tool's calls instead of widgetName.
frontComponentId?: string;
};
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-required-tool-auth-context.util.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-required-tool-auth-context.util.ts
index 1cc59742e0a..f73eb9ed51c 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-required-tool-auth-context.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-required-tool-auth-context.util.ts
@@ -26,9 +26,7 @@ export const buildRequiredToolAuthContext = async ({
);
}
- // The identity triple arrives as separate fields, so validate that the
- // userWorkspace actually binds this user to this workspace, exactly like
- // token-based auth does, before building an auth context from it.
+ // The identity arrives as separate fields, so verify the userWorkspace binds this user to this workspace, as token auth does.
const userWorkspace = await userWorkspaceRepository.findOne({
where: {
id: context.userWorkspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.ts
index ac6d2d5f7c9..862e1fb94eb 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/execute-tool-from-tool-set.util.ts
@@ -3,10 +3,7 @@ import { type ToolCategory } from 'twenty-shared/ai';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
-// Invokes a tool from a factory-generated ToolSet by name. Used by providers
-// whose tools are produced as opaque AI-SDK ToolSet closures (view, metadata,
-// workflow, dashboard, view-field) and which therefore cannot dispatch by
-// executionRef alone.
+// For providers whose tools are opaque AI-SDK ToolSet closures and so cannot dispatch by executionRef.
export const executeToolFromToolSet = async (
toolSet: ToolSet,
toolName: string,
@@ -21,8 +18,7 @@ export const executeToolFromToolSet = async (
);
}
- // ToolSet widens execute to a union no argument satisfies; these tools are
- // dispatched by name and take no per-tool context.
+ // ToolSet widens execute to a union no argument satisfies; these tools take no per-tool context.
const execute = tool.execute as ToolExecuteFunction<
Record<string, unknown>,
ToolOutput,
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/with-resolved-tool-auth-context.util.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/with-resolved-tool-auth-context.util.ts
index 23d447f06fc..3a660de9feb 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/with-resolved-tool-auth-context.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/with-resolved-tool-auth-context.util.ts
@@ -5,12 +5,7 @@ import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/
import { type ToolAuthContextDependencies } from 'src/engine/core-modules/tool-provider/types/tool-auth-context-dependencies.type';
import { buildRequiredToolAuthContext } from 'src/engine/core-modules/tool-provider/utils/build-required-tool-auth-context.util';
-// Tools are dispatched from queue workers (AI chat, workflows) as well as
-// HTTP requests; only the latter get an async-local auth context from
-// WorkspaceAuthContextMiddleware. Establish it around the dispatch so any
-// tool code relying on getWorkspaceAuthContext() works on every transport.
-// Without a resolvable identity the dispatch runs outside any auth context,
-// as before.
+// Queue workers get no async-local auth context from WorkspaceAuthContextMiddleware, so establish one around the dispatch.
export const withResolvedToolAuthContext = async <T>(
{
context,
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
index f5c9838d409..6366c377f0f 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/email-tool/email-composer.service.ts
@@ -298,8 +298,8 @@ export class EmailComposerService {
return attachments;
}
- // Resolve parent's root thread id (Gmail/MS native or stored) + RFC 5322 §3.6.4
- // References chain so replies thread on both Twenty and recipient mail clients.
+ // Parent's root thread id (provider-native or stored) and RFC 5322 §3.6.4 References chain, so replies thread
+ // on both Twenty and recipient mail clients.
private async getParentThreadContext(
workspaceId: string,
inReplyTo: string,
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index 547006cfbeb..1a219a8fb57 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -581,10 +581,7 @@ export class ConfigVariables {
isHiddenInAdminPanel: true,
type: ConfigVariableType.ENUM,
options: Object.values(DpaRegion),
- // Deployment-fixed: must mirror where data actually lives. Allowing a
- // runtime DB/admin override could advertise a hosting location that does
- // not match where data resides, so this is only configurable via
- // environment variable.
+ // Env-only: a runtime override could advertise a hosting location that does not match where data lives.
isEnvOnly: true,
})
@IsOptional()
@@ -1877,7 +1874,7 @@ export class ConfigVariables {
type: ConfigVariableType.NUMBER,
})
@CastToPositiveNumber()
- INVITATION_SENDING_BY_WORKSPACE_THROTTLE_TTL_IN_MS = 604_800_000; // 7 days
+ INVITATION_SENDING_BY_WORKSPACE_THROTTLE_TTL_IN_MS = 604_800_000;
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.RATE_LIMITING,
@@ -1895,7 +1892,7 @@ export class ConfigVariables {
type: ConfigVariableType.NUMBER,
})
@CastToPositiveNumber()
- INVITATION_SENDING_BY_EMAIL_THROTTLE_TTL_IN_MS = 604_800_000; // 7 days
+ INVITATION_SENDING_BY_EMAIL_THROTTLE_TTL_IN_MS = 604_800_000;
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.RATE_LIMITING,
@@ -2189,7 +2186,7 @@ export class ConfigVariables {
type: ConfigVariableType.NUMBER,
})
@CastToPositiveNumber()
- WORKFLOW_EXEC_HARD_THROTTLE_TTL = 3_600_000; // 1 hour;
+ WORKFLOW_EXEC_HARD_THROTTLE_TTL = 3_600_000;
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.CAPTCHA_CONFIG,
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/utils/parse-config-duration.util.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/utils/parse-config-duration.util.ts
index 90057072a2d..69fa840bfc0 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/utils/parse-config-duration.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/utils/parse-config-duration.util.ts
@@ -1,8 +1,6 @@
import ms from 'ms';
-// Parsed by the same library the consumers call, so the accepted units cannot
-// drift from them: "1M" and "1Month" look interchangeable but ms reads them as
-// one minute and as nothing at all.
+// Same library as the consumers so units cannot drift: ms reads "1M" as a minute and "1Month" as nothing.
export const parseConfigDuration = (duration: unknown): number | undefined => {
if (typeof duration !== 'string') {
return undefined;
diff --git a/packages/twenty-server/src/engine/core-modules/upgrade/utils/is-upgrade-workspace-cursor-valid-for-segment.util.ts b/packages/twenty-server/src/engine/core-modules/upgrade/utils/is-upgrade-workspace-cursor-valid-for-segment.util.ts
index 467c511d680..75d6231d50b 100644
--- a/packages/twenty-server/src/engine/core-modules/upgrade/utils/is-upgrade-workspace-cursor-valid-for-segment.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/upgrade/utils/is-upgrade-workspace-cursor-valid-for-segment.util.ts
@@ -31,8 +31,7 @@ export const isUpgradeWorkspaceCursorValidForSegment = ({
precedingInstanceSegmentStartCursor--;
}
- // Later instance commands can already be globally complete without a
- // workspace-specific cursor when the workspace was provisioned later.
+ // A workspace provisioned later has no cursor for instance commands that were already globally complete.
return (
cursorPosition >= precedingInstanceSegmentStartCursor &&
cursorPosition < startCursor
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
index 4e13286e38b..6a8a8f8a53b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
@@ -12,15 +12,12 @@ export enum UsageOperationType {
CALL_RECORDING = 'CALL_RECORDING',
EMAIL_SEND = 'EMAIL_SEND',
MESSAGE_CAMPAIGN_SEND = 'MESSAGE_CAMPAIGN_SEND',
- // Raised by the query runner and read back by the API rate limit, so it is
- // out of twenty-shared's USAGE_OPERATION_TYPES: an app billing under it
- // would spend the workspace's request budget.
+ // Out of twenty-shared's USAGE_OPERATION_TYPES: the API rate limit reads it, so an app billing under it would spend the request budget.
API_REQUEST = 'API_REQUEST',
WEBHOOK_CALL = 'WEBHOOK_CALL',
STORAGE_FILE = 'STORAGE_FILE',
RECORD_WRITE = 'RECORD_WRITE',
- // Platform-raised, once per billing period. Also out of
- // USAGE_OPERATION_TYPES: an app declares the amount, it never charges this.
+ // Platform-raised once per billing period; also out of USAGE_OPERATION_TYPES since apps only declare the amount.
SUBSCRIPTION = 'SUBSCRIPTION',
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
index 7cbca7f9584..13e3d3fe1fb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
@@ -66,9 +66,7 @@ type GroupByField = (typeof ALLOWED_GROUP_BY_FIELDS)[number];
const BREAKDOWN_QUERY_LIMIT = 50;
-// Scopes a declared operation name to the application that declared it. Both
-// halves of the comparison are built here so the SQL and the array it is
-// matched against cannot spell the pair differently.
+// Scopes a declared operation to its application; both sides of the comparison use it so they cannot spell the pair differently.
const DECLARED_OPERATION_KEY_SEPARATOR = ':';
@Injectable()
@@ -90,8 +88,7 @@ export class UsageAnalyticsService {
}): Promise<UsageConsumptionRow[]> {
const periodClause = buildUsagePeriodClause(periodAnchor);
- // The filtered keys are grouped again so the shape matches the
- // consumption_by_scope projection, which is only picked on a full key match.
+ // Grouped again so the shape matches the consumption_by_scope projection, which is picked only on a full key match.
return this.clickHouseService.selectOrThrow<UsageConsumptionRow>(
`SELECT operationType, userWorkspaceId, apiKeyId, applicationId, agentId,
workflowId, logicFunctionId,
@@ -168,8 +165,7 @@ export class UsageAnalyticsService {
workspaceId: string;
periodStart: Date;
}): Promise<number> {
- // Both keys are pinned, so the grouping only exists to match the
- // billing_by_workspace_period projection; it still returns a single row.
+ // The grouping only exists to match the billing_by_workspace_period projection; it still returns one row.
const rows = await this.clickHouseService.selectOrThrow<{
total: string | number | null;
}>(
@@ -250,15 +246,8 @@ export class UsageAnalyticsService {
});
}
- // Apps pick their operation type from a closed platform enum, so unrelated
- // apps merge under whichever one they picked. Grouping on the application
- // and on the operation it declared answers "what did this app charge me
- // for" without disturbing the operation-type breakdown, which still
- // accounts for every credit.
- //
- // Contexts the app never declared collapse here rather than in the
- // resolver, so a row is a displayed slice and the limit truncates the same
- // way it does for every other breakdown.
+ // Apps share a closed operation-type enum, so grouping on the app and its declared operation shows what each app charged.
+ // Undeclared contexts collapse here rather than in the resolver, so the limit truncates displayed slices.
async getUsageByApplication({
workspaceId,
periodStart,
@@ -329,10 +318,7 @@ export class UsageAnalyticsService {
}));
}
- // Which recurring charges an application has already been billed for in a
- // period. The usage row is itself the record of the charge, so re-running the
- // cron re-reads it instead of needing separate bookkeeping. Compared with >=
- // rather than = so a truncated timestamp cannot miss the current period.
+ // The usage row is the record of the charge; >= so a truncated timestamp cannot miss the current period.
async getChargedRecurringKeys({
workspaceId,
periodStart,
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
index 5e567723594..53d7ea059f5 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
@@ -153,10 +153,7 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {
);
}
- // Every recorded row funnels through here, so the credit invariant holds for
- // any caller rather than each one clamping its own arithmetic. The event is
- // still recorded, at zero credits, so the activity stays visible in the
- // breakdown.
+ // Every row funnels through here so the credit invariant holds for all callers; the event still records at zero credits.
private withDefaults(input: RecordUsageInput): UsageEvent {
const creditsUsedMicro = input.creditsUsedMicro ?? 0;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts b/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
index f3b05c36b12..fd40b44b758 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
@@ -76,8 +76,7 @@ export class UsageResolver {
'flatApplicationMaps',
]);
- // Per application, not workspace-wide: two apps may use the same operation
- // name, and only the one that declared it should keep it as its own slice.
+ // Per application: two apps may declare the same operation name.
const declaredOperationsByApplicationId = Object.fromEntries(
Object.entries(flatApplicationMaps.byId).map(
([applicationId, application]) => [
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-recurring-charge-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-recurring-charge-key.util.ts
index f7fed9564bf..3a8b535c08f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/build-recurring-charge-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-recurring-charge-key.util.ts
@@ -1,8 +1,4 @@
-// Identifies one recurring charge within a billing period, as the usage row
-// that records it: the application and the charge name it was raised under.
-// Both the ClickHouse read of what a period already carries and the check for
-// what is still due go through this, so the two cannot drift apart and start
-// re-charging every workspace daily.
+// Shared by the ClickHouse read and the due check so they cannot drift and re-charge every workspace daily.
export const buildRecurringChargeKey = ({
applicationId,
chargeKey,
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
index 4cca1ef8626..926fdd35cd9 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
@@ -11,13 +11,8 @@ type ConsolidateUsageByApplicationParams = {
flatApplicationMaps: FlatApplicationCacheMaps;
};
-// Operations an app declared in its manifest get their own slice under the app
-// name; anything it charged without declaring arrives already folded into a
-// single app-level slice, so undeclared context strings never reach a screen.
-// Uninstalled apps are looked up too, otherwise their spend would drop out of
-// the pie while still counting towards the bill. Keying on the label also
-// merges two apps sharing a display name, which would otherwise collide as one
-// chart id.
+// Uninstalled apps are looked up too, or their spend would drop out of the pie while still billed.
+// Keying on the label merges apps sharing a display name, which would otherwise collide as one chart id.
export const consolidateUsageByApplication = ({
items,
flatApplicationMaps,
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-secure-cookie-name.constant.ts b/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-secure-cookie-name.constant.ts
index b77cbecf980..251e2c8ab34 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-secure-cookie-name.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-secure-cookie-name.constant.ts
@@ -1,3 +1,2 @@
-// __Host- enforces Secure, Path=/ and no Domain attribute at the browser
-// level, so the cookie can never be widened to sibling subdomains.
+// __Host- forces Secure, Path=/ and no Domain, so the cookie can never widen to sibling subdomains.
export const USER_SESSION_SECURE_COOKIE_NAME = '__Host-twenty-session';
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-token-prefix.constant.ts b/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-token-prefix.constant.ts
index bd57b7990c2..818f8be3b8d 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-token-prefix.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/constants/user-session-token-prefix.constant.ts
@@ -1,3 +1,2 @@
-// Makes opaque session tokens self-describing so the bearer-token dispatcher
-// can route them without attempting JWT verification first.
+// Lets the bearer-token dispatcher route session tokens without attempting JWT verification first.
export const USER_SESSION_TOKEN_PREFIX = 'sess_';
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/crons/jobs/user-session-cleanup.cron.job.ts b/packages/twenty-server/src/engine/core-modules/user-session/crons/jobs/user-session-cleanup.cron.job.ts
index 8fe09aa0e07..21f0f5dba00 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/crons/jobs/user-session-cleanup.cron.job.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/crons/jobs/user-session-cleanup.cron.job.ts
@@ -11,8 +11,7 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
import { USER_SESSION_CLEANUP_CRON_PATTERN } from 'src/engine/core-modules/user-session/constants/user-session-cleanup-cron-pattern.constant';
import { UserSessionEntity } from 'src/engine/core-modules/user-session/user-session.entity';
-// Rows outlive their usability so the sessions UI and audits can still show
-// recently ended sessions.
+// Kept after ending so the sessions UI and audits can still show recent sessions.
const ENDED_SESSION_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
const DELETE_BATCH_SIZE = 10000;
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session-cookie.service.ts b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session-cookie.service.ts
index 6a288d87ee2..fcee1d1feb5 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session-cookie.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session-cookie.service.ts
@@ -125,8 +125,7 @@ export class UserSessionCookieService {
clearSessionCookie(response: Response): void {
const { options } = this.resolveCookieSettings();
- // Both names, so an instance that switched to https drops the cookie it
- // issued under the old one.
+ // Both names, so an instance that switched to https drops the cookie issued under the old one.
response.clearCookie(USER_SESSION_SECURE_COOKIE_NAME, options);
response.clearCookie(USER_SESSION_COOKIE_NAME, options);
}
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts
index 7e21daaa795..df5f84e617a 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/services/user-session.service.ts
@@ -81,8 +81,7 @@ export class UserSessionService {
throw new Error('Cannot issue a user session without an HTTP response');
}
- // Cannot live in the CSRF middleware, which cannot know a request is about
- // to issue a cookie.
+ // Not in the CSRF middleware, which cannot know a request is about to issue a cookie.
if (!this.isRequestAllowedToReceiveSessionCookie(request)) {
this.logger.warn(
`Refused to issue a session cookie to origin ${request.headers.origin}`,
@@ -132,8 +131,7 @@ export class UserSessionService {
}
}
- // Create the replacement before touching the presented session. If the
- // insert fails, the browser keeps its last working credential.
+ // Create the replacement first so a failed insert leaves the browser its working credential.
const { sessionToken, session } = await this.createSession(sessionInput);
this.userSessionCookieService.attachSessionTokenToResponse(
@@ -147,9 +145,7 @@ export class UserSessionService {
}
if (sessionInput.isImpersonating === true) {
- // The one sign-in that must not revoke what it replaces: parking the
- // impersonator's session lets stopImpersonation hand back the credential
- // they already held.
+ // Parked rather than revoked, so stopImpersonation can hand the impersonator's credential back.
this.userSessionCookieService.attachImpersonatorSessionTokenToResponse(
response,
presentedSessionToken,
@@ -164,8 +160,7 @@ export class UserSessionService {
UserSessionRevokedReason.Superseded,
);
} catch (error) {
- // The replacement session and cookie are already valid. A cleanup
- // failure must not turn that successful handoff into another logout.
+ // The handoff already succeeded; a cleanup failure must not turn it into another logout.
this.logger.error(
`Failed to revoke the superseded session: ${
error instanceof Error ? error.message : String(error)
@@ -183,8 +178,7 @@ export class UserSessionService {
}
}
- // No Origin means no browser to plant a cookie in, so scripted sign-ins keep
- // working. Browsers always send one on the unsafe requests these arrive as.
+ // No Origin means no browser to plant a cookie in; browsers always send one on these unsafe requests.
private isRequestAllowedToReceiveSessionCookie(request: Request): boolean {
const origin = request.headers.origin;
@@ -397,9 +391,7 @@ export class UserSessionService {
};
}
- // A revocation racing the write above may have had its cache delete land
- // first, resurrecting the session for a full TTL. Re-checking afterwards
- // closes it: anything committing later deletes what we just wrote.
+ // A racing revocation's cache delete may land first and resurrect the session for a TTL; re-checking closes that.
private async assertNotRevokedAfterCaching(
sessionId: string,
tokenHash: string,
@@ -424,10 +416,8 @@ export class UserSessionService {
});
}
- // Scoped to one workspace: a session belongs to the workspace its exchange
- // selected, and the same person's membership of another workspace is not that
- // workspace's business. Sessions with no workspace are the workspace-agnostic
- // ones minted on the default subdomain, which belong to no workspace's list.
+ // A session belongs to the workspace its exchange selected, so other workspaces' sessions stay out;
+ // workspace-agnostic ones belong to no list.
async findActiveSessionsForUserWorkspace({
userId,
workspaceId,
@@ -490,8 +480,7 @@ export class UserSessionService {
return await this.revokeSessionEntity(session, reason);
}
- // workspaceId narrows this to one workspace, which is what the settings panel
- // wants. Account-wide callers (password change) leave it out on purpose.
+ // Account-wide callers (password change) omit workspaceId on purpose.
async revokeAllSessionsForUser({
userId,
workspaceId,
@@ -503,9 +492,7 @@ export class UserSessionService {
reason: UserSessionRevokedReason;
exceptSessionId?: string;
}): Promise<number> {
- // Applying the predicate in the UPDATE rather than to ids read beforehand
- // narrows but does not close the window: a sign-in committing after this
- // statement's snapshot survives, which would need a generation counter.
+ // Narrows but does not close the race: a sign-in committing after this snapshot survives.
const revokingQuery = this.userSessionRepository
.createQueryBuilder()
.update(UserSessionEntity)
@@ -592,8 +579,7 @@ export class UserSessionService {
return;
}
- // Outside the catch: a storage failure here leaves a usable refresh token
- // behind, so it must surface rather than report success.
+ // Outside the catch: a storage failure leaves a usable refresh token behind, so it must surface.
await this.appTokenRepository.update(
{
id: payload.jti,
@@ -650,8 +636,7 @@ export class UserSessionService {
return ms(this.twentyConfigService.get('SESSION_IDLE_TIMEOUT'));
}
- // Must stay well inside the idle timeout, or a continuously active user goes
- // idle between two touches.
+ // Must stay well inside the idle timeout, or a continuously active user goes idle between touches.
private getTouchIntervalMs(): number {
return Math.min(
USER_SESSION_MAX_TOUCH_INTERVAL_MS,
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/types/cached-user-session.type.ts b/packages/twenty-server/src/engine/core-modules/user-session/types/cached-user-session.type.ts
index e6144ca5252..b94b8c473f2 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/types/cached-user-session.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/types/cached-user-session.type.ts
@@ -1,7 +1,5 @@
import { type AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
-// Cached under the token hash in Redis; dates as ISO strings so the payload
-// survives JSON serialization.
export type CachedUserSession = {
sessionId: string;
userId: string;
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.ts b/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.ts
index 4d3421b229b..dbb0b2518e7 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/user-session.entity.ts
@@ -51,8 +51,7 @@ export class UserSessionEntity {
@Column({ type: 'uuid', nullable: true })
workspaceId: string | null;
- // Removing someone from a workspace deletes the membership, not the
- // workspace, so without the cascade a dead session lingers until expiry.
+ // Removing a member deletes the membership, not the workspace, so without the cascade sessions linger until expiry.
@ManyToOne(() => UserWorkspaceEntity, {
onDelete: 'CASCADE',
})
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.ts b/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.ts
index 32f4049b7b7..54652ba926c 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/user-session.resolver.ts
@@ -49,8 +49,7 @@ export class UserSessionResolver {
| undefined,
@Context() context: { req: Request },
): Promise<UserSessionDTO[]> {
- // Workspace-agnostic sessions are admitted and have no workspace to
- // scope to. Nothing is in scope rather than everything.
+ // Workspace-agnostic sessions have no workspace to scope to: nothing is in scope rather than everything.
if (!isDefined(workspace)) {
return [];
}
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.ts
index 6dc52440109..1d3c4c127fb 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/apply-credentialed-cors.util.ts
@@ -20,10 +20,7 @@ const toComparableOrigin = (value: string): string | undefined => {
}
};
-// The browser reports a rejected credentialed wildcard response only in its
-// own console, leaving nothing server-side for the operator to act on
-// (#24037). Warn once per origin on cross-origin browser preflights that will
-// be answered with the wildcard.
+// Browsers report a rejected credentialed wildcard only in their console (#24037), so warn once per origin.
export const warnOnceOnDisallowedBrowserPreflight = ({
request,
twentyConfigService,
@@ -77,17 +74,14 @@ export const warnOnceOnDisallowedBrowserPreflight = ({
);
};
-// Shared between the production bootstrap and the integration test harness so
-// the CORS behavior under test is the deployed one.
+// Shared with the integration test harness so the CORS behavior under test is the deployed one.
export const applyCredentialedCors = (
app: INestApplication,
twentyConfigService: TwentyConfigService,
): void => {
const warnedOrigins = new Set<string>();
- // The cors package only emits Vary: Origin when it reflects one, so wildcard
- // and reflected responses would share a cache entry and a credentialed
- // request could be served the wildcard, which browsers reject.
+ // cors only emits Vary: Origin when reflecting, so wildcard and reflected responses would share a cache entry.
app.use((request: Request, response: Response, next: NextFunction) => {
response.vary('Origin');
warnOnceOnDisallowedBrowserPreflight({
@@ -99,10 +93,7 @@ export const applyCredentialedCors = (
});
app.enableCors({
- // Resolved per request rather than once at boot: the origins derive from
- // config the admin panel can change, and a snapshot would drift from the
- // CSRF guard, which resolves them per request and would then disagree with
- // CORS about the same origin.
+ // Per request: the admin panel can change the origins, and a boot snapshot would disagree with the CSRF guard.
origin: (
origin: string | undefined,
callback: (error: Error | null, allow?: boolean | string) => void,
@@ -119,8 +110,7 @@ export const applyCredentialedCors = (
return callback(null, '*');
},
credentials: true,
- // Expose WWW-Authenticate so browser-based MCP clients can read the
- // resource_metadata pointer on 401. Required by MCP authorization spec.
+ // Browser-based MCP clients must read the resource_metadata pointer on 401 (MCP authorization spec).
exposedHeaders: ['WWW-Authenticate'],
});
};
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-user-session-token-from-request.util.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-user-session-token-from-request.util.ts
index 0c4e333163c..b48b353e3c4 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-user-session-token-from-request.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/extract-user-session-token-from-request.util.ts
@@ -28,9 +28,7 @@ const readCookieValue = (
return undefined;
};
-// The plain name is only read on deployments that cannot set a __Host- cookie
-// at all (plain http). Accepting it on an https deployment would let a
-// sibling subdomain toss a session in and fixate the visitor.
+// Plain name only on plain http: on https a sibling subdomain could plant one and fixate the visitor.
export const extractUserSessionTokenFromRequestCookie = (
request: Request,
{
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/is-request-origin-allowed.util.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/is-request-origin-allowed.util.ts
index c0786eac709..28ee191c19c 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/utils/is-request-origin-allowed.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/is-request-origin-allowed.util.ts
@@ -24,9 +24,7 @@ export const isRequestOriginAllowed = ({
}): boolean => {
const normalizedOrigin = origin.toLowerCase();
- // Compared through URL rather than as strings: browsers omit :443 and :80
- // from Origin while Host keeps whatever port the client spelled, so a genuine
- // same-origin POST would otherwise 403 on the port alone.
+ // Via URL: browsers omit :443/:80 from Origin while Host keeps the port the client spelled.
const comparableOrigin = toComparableOrigin(normalizedOrigin);
const comparableRequestOrigin = toComparableOrigin(
getRequestBaseUrl(request),
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/utils/resolve-allowed-credentialed-origins.util.ts b/packages/twenty-server/src/engine/core-modules/user-session/utils/resolve-allowed-credentialed-origins.util.ts
index 4e191cf3ed5..821e03e35c6 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/utils/resolve-allowed-credentialed-origins.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/utils/resolve-allowed-credentialed-origins.util.ts
@@ -3,8 +3,7 @@ import { isNonEmptyString } from '@sniptt/guards';
import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
import { type TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-// Opaque schemes (file:, data:) serialise to the literal "null" origin, which
-// would otherwise allowlist every sandboxed document that sends Origin: null.
+// Opaque schemes (file:, data:) serialise to "null", which would allowlist every sandboxed document.
const toOrigin = (url: string): string | undefined => {
try {
const parsedUrl = new URL(url);
@@ -19,8 +18,7 @@ const toOrigin = (url: string): string | undefined => {
}
};
-// URL canonicalises [::ffff:127.0.0.1] to [::ffff:7f00:1], so only the hex
-// spelling reaches here. All of 127.0.0.0/8 is loopback.
+// URL canonicalises [::ffff:127.0.0.1] to hex, so only that spelling reaches here; all of 127.0.0.0/8 is loopback.
const IPV4_LOOPBACK_REGEX = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const IPV4_MAPPED_HEX_REGEX = /^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/;
@@ -68,9 +66,7 @@ export const resolveAllowedCredentialedOrigins = (
.split(',')
.map((allowedOrigin) => allowedOrigin.trim());
- // SERVER_URL defaults to http://localhost:3000, so a deployment that never
- // set it would hand any local page on that port a credentialed origin.
- // Explicit entries are still honoured, so dev setups keep working.
+ // SERVER_URL defaults to http://localhost:3000, which would hand any local page on that port a credentialed origin.
const isProduction =
twentyConfigService.get('NODE_ENV') === NodeEnvironment.PRODUCTION;
diff --git a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
index 95508a128a3..3ac91a38dbf 100644
--- a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
@@ -359,13 +359,10 @@ export class UserWorkspaceService {
softDelete?: boolean;
}): Promise<void> {
if (softDelete) {
- // roleTarget has no deletedAt column, so its rows cannot be soft deleted.
- // Access stays gated by the soft-deleted userWorkspace.
+ // roleTarget has no deletedAt column, so its rows stay and access is gated by the soft-deleted userWorkspace.
await this.userWorkspaceRepository.softDelete({ id: userWorkspaceId });
} else {
- // The delete sets the creator of this member's workflows to null, which
- // makes them workspace-visible in core, so their runs' grants have to
- // follow or nobody could read those runs.
+ // The delete nulls the creator of this member's workflows, making them workspace-visible, so their runs' grants must follow.
const createdCoreWorkflowIds =
await this.workflowRunRecordShareService.findCoreWorkflowIdsCreatedBy({
workspaceId,
@@ -397,8 +394,7 @@ export class UserWorkspaceService {
},
});
- // HIDDEN workspaces are never advertised in the root-domain picker, even to
- // their own members — they must sign in from the workspace URL directly.
+ // HIDDEN workspaces are never advertised in the root-domain picker, even to members: they sign in from the workspace URL.
const alreadyMemberWorkspaces = user
? user.userWorkspaces
.map(({ workspace }) => ({ workspace }))
@@ -429,8 +425,7 @@ export class UserWorkspaceService {
const workspacesFromApprovedAccessDomainIds =
workspacesFromApprovedAccessDomain.map(({ workspace }) => workspace.id);
- // HIDDEN removes the picker convenience only; invited users can still join
- // through the direct invitation link, which carries its own token.
+ // HIDDEN only removes the picker; invitation links carry their own token.
const workspacesFromInvitations = (
await this.workspaceInvitationService.findInvitationsByEmail(email)
)
diff --git a/packages/twenty-server/src/engine/core-modules/user/services/user.service.ts b/packages/twenty-server/src/engine/core-modules/user/services/user.service.ts
index 11da342cfd9..f60b8378c54 100644
--- a/packages/twenty-server/src/engine/core-modules/user/services/user.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/user/services/user.service.ts
@@ -404,8 +404,7 @@ export class UserService {
workspaceId,
});
- // Runs after the membership is gone so a failed removal keeps the history
- // and threads created during the removal are still cleaned up.
+ // After the membership is gone, so a failed removal keeps the history and threads created meanwhile are cleaned.
await this.agentChatThreadRepository.delete(workspaceId, {
workspaceMemberId: workspaceMember.id,
});
diff --git a/packages/twenty-server/src/engine/core-modules/user/user.resolver.ts b/packages/twenty-server/src/engine/core-modules/user/user.resolver.ts
index ee33a4dc5d1..9a8b010a74e 100644
--- a/packages/twenty-server/src/engine/core-modules/user/user.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/user/user.resolver.ts
@@ -472,8 +472,7 @@ export class UserResolver {
const workspaceMemberToDeleteIsAuthenticatedUser =
workspaceMemberToDelete.userId === userId;
- // Removing oneself deletes the account when it is the last workspace, so it
- // is the person's to do rather than an application's.
+ // Removing oneself may delete the account, so only the person can do it, not an application.
if (workspaceMemberToDeleteIsAuthenticatedUser && !isUserSession) {
throw buildUserSessionRequiredError();
}
@@ -710,8 +709,7 @@ export class UserResolver {
return user.userWorkspaces;
}
- // Same rows as workspaces under the entity's own field name, so guarding only
- // one of the two leaves the other answering.
+ // Same rows as the workspaces field under the entity's own name, so guarding only one leaves the other answering.
@ResolveField(() => [UserWorkspaceEntity], {
name: 'userWorkspaces',
nullable: false,
diff --git a/packages/twenty-server/src/engine/core-modules/user/utils/assert-workspace-member-update-values-are-valid.util.ts b/packages/twenty-server/src/engine/core-modules/user/utils/assert-workspace-member-update-values-are-valid.util.ts
index 5bd4f361a38..534353ac204 100644
--- a/packages/twenty-server/src/engine/core-modules/user/utils/assert-workspace-member-update-values-are-valid.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/user/utils/assert-workspace-member-update-values-are-valid.util.ts
@@ -3,8 +3,7 @@ import { UI_SCALE_VALUES } from 'twenty-shared/constants';
import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
-// Enum-like TEXT fields whose values would otherwise be persisted unchecked,
-// then cast to a client-side union.
+// Enum-like TEXT fields would otherwise persist unchecked and then be cast to a client-side union.
const WORKSPACE_MEMBER_FIELD_ALLOWED_VALUES: Record<
string,
ReadonlySet<string>
diff --git a/packages/twenty-server/src/engine/core-modules/well-known/utils/build-api-catalog.util.ts b/packages/twenty-server/src/engine/core-modules/well-known/utils/build-api-catalog.util.ts
index f0ed135fe33..fe2ead18d51 100644
--- a/packages/twenty-server/src/engine/core-modules/well-known/utils/build-api-catalog.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/well-known/utils/build-api-catalog.util.ts
@@ -4,8 +4,7 @@ import { ApiPath } from 'twenty-shared/types';
const API_DOCS_URL = `${DOCUMENTATION_BASE_URL}/developers/extend/api`;
const MCP_DOCS_URL = `${DOCUMENTATION_BASE_URL}/user-guide/ai/capabilities/mcp`;
-// service-desc points at each host's live OpenAPI, which is generated per
-// workspace and so includes that workspace's custom objects.
+// Points at each host's live OpenAPI, generated per workspace with its custom objects.
export const buildApiCatalog = (baseUrl: string) => ({
linkset: [
{
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts
index 55b693086b8..9f3be74365e 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/core-workflow-access.module.ts
@@ -6,8 +6,7 @@ import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workfl
import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
-// The rule is reached from the command menu as well as from the workflow API,
-// and those two modules already depend on each other, so it lives on its own.
+// Own module: the command menu and the workflow API both need it and already depend on each other.
@Module({
imports: [TypeOrmModule.forFeature([WorkflowEntity, WorkflowVersionEntity])],
providers: [
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.ts b/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.ts
index 1854b0067a8..14737808617 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/dtos/core-workflow.dto.ts
@@ -37,8 +37,7 @@ export class CoreWorkflowDTO {
@Field(() => WorkflowVisibility, { nullable: false })
visibility: WorkflowVisibility;
- // the reader's own id never leaves the server; the client only needs to know
- // whether this reader is allowed to change who sees the workflow
+ // Exposed instead of the owner id, since the reader's own id never leaves the server.
@Field(() => Boolean, { nullable: false })
canChangeVisibility: boolean;
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts
index 596e2ccce23..100d72222bd 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/entities/workflow.entity.ts
@@ -54,9 +54,7 @@ export class WorkflowEntity extends SyncableEntity {
@Column({ type: 'uuid', nullable: true })
lastPublishedCoreWorkflowVersionId: string | null;
- // Enforced where ids are resolved rather than at each endpoint, so a workflow
- // private to someone else stops resolving at all and its versions and steps
- // are unreachable too. See CoreWorkflowIdResolutionService.
+ // Enforced where ids resolve (CoreWorkflowIdResolutionService), so a private workflow's versions and steps are unreachable too.
@WasIntroducedInUpgrade({
upgradeCommandName: ADD_WORKFLOW_VISIBILITY_UPGRADE_COMMAND_NAME,
})
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
index 014243e9d19..c433ee47278 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-access.service.ts
@@ -15,9 +15,8 @@ import {
WorkflowQueryValidationExceptionCode,
} from 'src/modules/workflow/common/exceptions/workflow-query-validation.exception';
-// A workflow's versions carry its whole definition, so reaching one by id has
-// to answer to the same rule as reaching the workflow. Both asserts live here
-// so a private workflow has one deny to audit rather than one per entry point.
+// Versions carry the whole definition, so they answer to the workflow's rule; both asserts live here so a private
+// workflow has one deny to audit.
@Injectable()
export class CoreWorkflowAccessService {
constructor(
@@ -51,8 +50,7 @@ export class CoreWorkflowAccessService {
`Core workflow '${inaccessibleCoreWorkflow.id}' is private to another member`,
WorkflowQueryValidationExceptionCode.FORBIDDEN,
{
- // the same message a missing workflow gets, so a private one does not
- // announce that it exists
+ // Same message as a missing workflow, so a private one does not announce that it exists.
userFriendlyMessage: msg`Workflow not found`,
},
);
@@ -95,8 +93,7 @@ export class CoreWorkflowAccessService {
});
}
- // The legacy resolvers are keyed by the workspace mirror's ids rather than
- // the core ones, so they need the same rule reached from the other side.
+ // Legacy resolvers use the workspace mirror's ids, so the same rule is reached from that side.
async assertWorkspaceWorkflowVersionsAreAccessibleOrThrow({
workspaceId,
userWorkspaceId,
@@ -156,8 +153,7 @@ export class CoreWorkflowAccessService {
});
}
- // The command menu lists every member's manual triggers in one read, so the
- // rule has to come back as a filter rather than a deny.
+ // The command menu lists every member's manual triggers in one read, so the rule comes back as a filter.
async findInaccessibleWorkspaceWorkflowVersionIds({
workspaceId,
userWorkspaceId,
@@ -267,8 +263,7 @@ export class CoreWorkflowAccessService {
},
});
- // An id nobody owns keeps behaving exactly as it did before, so an unknown
- // or already deleted workflow is still a no-op rather than a refusal.
+ // Unknown or deleted ids stay a no-op rather than a refusal.
return coreWorkflows.filter(
(coreWorkflow) =>
coreWorkflow.visibility === WorkflowVisibility.PRIVATE &&
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts
index e2a68110a2b..956c85f4a9f 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-id-resolution.service.ts
@@ -54,8 +54,7 @@ export class CoreWorkflowIdResolutionService {
return resolved;
}
- // Everything that reaches a workflow by id comes through here, so this is
- // where a workflow private to someone else stops being resolvable at all.
+ // Every by-id access goes through here, so this is where a private workflow stops resolving.
async resolveWorkspaceVersionIdIfCoreVersionExists({
workspaceId,
userWorkspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
index 5b4c9783144..4e21cd6bdc5 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-lifecycle.workspace-service.ts
@@ -124,8 +124,7 @@ export class CoreWorkflowLifecycleWorkspaceService {
userWorkspaceId: string | undefined;
coreWorkflowVersionId: string;
}): Promise<boolean> {
- // this one reads the version straight from the repository rather than
- // through the id resolver, so it needs the rule applied by hand
+ // Reads the version from the repository, not the id resolver, so the rule is applied by hand.
await this.coreWorkflowAccessService.assertCoreWorkflowVersionsAreAccessibleOrThrow(
{
workspaceId,
@@ -226,9 +225,7 @@ export class CoreWorkflowLifecycleWorkspaceService {
let previousResolved: ResolvedCoreVersion | undefined;
- // The workspace side keeps its transaction, locks and checks. The core side
- // is collected here and applied by the migration runner once that
- // transaction has committed, then reverted if it did not.
+ // The core side is applied by the migration runner after this transaction commits, and reverted if it does not.
const pendingCoreStatuses = new Map<string, WorkflowVersionStatus>();
const triggersToRestore: TriggerToRestore[] = [];
const statusesToRestore = new Map<string, WorkflowVersionStatus>();
@@ -632,9 +629,7 @@ export class CoreWorkflowLifecycleWorkspaceService {
return currentlyActiveCoreVersion?.id ?? null;
}
- // The core half of this write is collected and applied by the migration runner
- // after the transaction, because the runner owns its own transaction and the
- // events the surfaces listen to are derived from its actions.
+ // Applied after the transaction: the runner owns its own, and the surfaces' events derive from its actions.
private async writeVersionStatusInTransaction({
transactionScope,
coreWorkflowVersionId,
@@ -780,8 +775,7 @@ export class CoreWorkflowLifecycleWorkspaceService {
);
}
- // The trigger work committed with the mirror transaction, so leaving it
- // would arm an automation on a version that is no longer active.
+ // The trigger work committed with the mirror transaction, so leaving it would arm an inactive version.
for (const { resolved, action } of [
...triggersToRestore,
].reverse()) {
@@ -801,8 +795,7 @@ export class CoreWorkflowLifecycleWorkspaceService {
);
}, buildSystemAuthContext(workspaceId));
- // The forward disable dropped the cron cache entry after its commit, so a
- // re-armed cron version would stay invisible to the scheduler without this.
+ // The forward disable dropped the cron cache entry after commit, so a re-armed version needs it rewritten.
for (const { resolved, action } of triggersToRestore) {
if (action === 'enable') {
await this.writeCronTriggerCacheEntryAfterCommit({ resolved });
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.ts
index 2f527fc4b09..16f93734a64 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-list.service.ts
@@ -55,8 +55,7 @@ type CoreWorkflowCursor = {
id: string;
};
-// sorting and the keyset comparison stay on the raw columns so a btree index
-// can serve them; only the cursor value is rendered to text
+// sort and keyset-compare on raw columns so a btree index serves them; only the cursor value is rendered to text
const SORT_COLUMN_BY_FIELD: Record<
CoreWorkflowOrderByField,
{ column: string; cursorExpression: string; nullable: boolean; cast: string }
@@ -76,8 +75,7 @@ const SORT_COLUMN_BY_FIELD: Record<
},
};
-// Every raw query binds the reader as $2, right after the workspace, so the
-// filter parameters keep starting at $3 in both the page and the count.
+// every raw query binds the reader right after the workspace so filter parameters start at $3 in both page and count queries
const READER_PARAMETER = '$2';
const VISIBILITY_PREDICATE = buildCoreWorkflowVisibilitySqlPredicate({
tableAlias: 'c',
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
index adf15dbe3d1..0860a6779ee 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts
@@ -767,8 +767,7 @@ export class CoreWorkflowMutationWorkspaceService {
flatEntityMaps: flatWorkflowVersionMaps,
});
- // The mirror goes first: the other order committed the core delete before the
- // assert could veto it, which destroyed the version's triggers and steps.
+ // mirror first so the assert can veto before the core delete commits
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
await this.workspaceOrmManager.runInWorkspaceTransaction(
async (transactionScope) => {
@@ -891,7 +890,6 @@ export class CoreWorkflowMutationWorkspaceService {
}, buildSystemAuthContext(workspaceId));
}
- // Owning a workflow means being a person, so this one keeps a strict reader
async updateWorkflowVisibility({
workspaceId,
userWorkspaceId,
@@ -909,12 +907,8 @@ export class CoreWorkflowMutationWorkspaceService {
},
);
- // Workflows that predate this column have no owner, and the first member to
- // set a visibility claims one. The ownership test is the UPDATE's own WHERE
- // rather than a preceding read, so two members claiming at the same moment
- // cannot both pass it and have the later write silently take the workflow.
- // A workspace-visible workflow is already editable and deletable by every
- // member, so claiming one grants no access the claimer did not have.
+ // ownership is checked in the UPDATE's WHERE, not a prior read, so two concurrent claims of an ownerless workflow cannot both win;
+ // a workspace-visible workflow is already editable by every member, so claiming one grants no new access
const claimResult =
await this.workflowRunRecordShareService.updateAccessThenSyncRuns({
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts
index 58decac8ca6..d4f717cad56 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-version-write.service.ts
@@ -176,9 +176,7 @@ export class CoreWorkflowVersionWriteService {
steps,
});
- // The runner cannot compare the previous content inside its UPDATE to catch
- // two people editing the same draft, so the comparison and the write it
- // guards are serialized on this lock.
+ // the runner cannot compare previous content inside its UPDATE, so concurrent draft edits serialize on this lock
await this.withCoreWorkflowVersionEditLock(
coreWorkflowVersionId,
async () => {
@@ -285,8 +283,7 @@ export class CoreWorkflowVersionWriteService {
try {
await queryRunner.connect();
- // Transaction scoped, so the lock is released by the commit below and by
- // any failure that rolls back, including a connection that dies holding it.
+ // xact-scoped lock so commit, rollback or a dropped connection all release it
await queryRunner.startTransaction();
const [lockResult] = (await queryRunner.query(
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts
index ac8d99b897b..7529a75dae7 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-core-sync.service.ts
@@ -178,8 +178,7 @@ export class WorkflowCoreSyncService {
[];
const flatWorkflowsToUpdate: UniversalFlatWorkflow[] = [];
- // The cache decides which rows exist, so a stale map would send a persisted
- // id down the create branch and hit the primary key. The table decides.
+ // read the table, not the cache: a stale map would send a persisted id to create and hit the primary key
const persistedCoreWorkflowIds = new Set(
(
await this.coreWorkflowRepository.find(workspaceId, {
@@ -350,9 +349,7 @@ export class WorkflowCoreSyncService {
);
}, buildSystemAuthContext(workspaceId));
- // The locks above only cover the workspace rows, so the core writes they
- // decided on run once that transaction has committed, through the runner
- // like every other core write.
+ // the locks above only cover workspace rows, so core writes go through the runner after commit
await this.applyReconciledCoreWorkflowUpdates(
workspaceId,
coreWorkflowUpdates,
@@ -458,8 +455,7 @@ export class WorkflowCoreSyncService {
}, buildSystemAuthContext(workspaceId));
}
- // coreWorkflowId is a writable column on the workspace record, so a caller
- // can point it at a core row owned by another workspace.
+ // coreWorkflowId is caller-writable, so it may point at another workspace's core row
private async resolveWorkspaceWorkflowIdByOwnedCoreWorkflowId(
workspaceId: string,
workflows: WorkflowWorkspaceEntity[],
@@ -506,10 +502,7 @@ export class WorkflowCoreSyncService {
(_, index) => !isDefined(resolvedFlatWorkflows[index]),
);
- // The dual-write listener deletes the same rows when the workspace mirror is
- // soft-deleted, so an id that is gone from both the cache and the table is an
- // idempotent no-op. An id still in the table is a stale cache and must fail
- // rather than leave an orphan that still reads and still broadcasts.
+ // gone from the table means the dual-write listener already deleted it; still there means a stale cache, so fail rather than orphan it
if (missingCoreWorkflowIds.length > 0) {
const stillPersisted = await this.coreWorkflowRepository.find(
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
index 80776a66079..484f2f46559 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-run-record-share.service.ts
@@ -33,10 +33,7 @@ type CoreWorkflowAccess = {
creatorWorkspaceMemberId: string | null;
};
-// A run carries its workflow's inputs and outputs, so it is exactly as private
-// as its core workflow. Its grants are derived from that workflow rather than
-// set by hand, which is why the whole derived set is replaced: a visibility
-// change or a new creator must also take away what the old state granted.
+// runs carry their workflow's data, so their grants are derived from it and replaced wholesale to revoke what the old state granted
@Injectable()
export class WorkflowRunRecordShareService {
constructor(
@@ -50,8 +47,7 @@ export class WorkflowRunRecordShareService {
private readonly cacheLockService: CacheLockService,
) {}
- // Held across both steps so that a run created meanwhile cannot be granted
- // from the state this change replaces.
+ // lock held across both steps so a run created meanwhile is not granted from the replaced state
async updateAccessThenSyncRuns<TResult>({
workspaceId,
coreWorkflowId,
@@ -205,15 +201,11 @@ export class WorkflowRunRecordShareService {
workspaceId,
transactionScope,
criteria: [
- // Grants written on the run's own behalf rather than by a
- // person sharing it: the ones derived here, and the creator
- // role an application's create writes, which would otherwise
- // keep everyone holding that role reading a private
- // workflow's runs.
+ // grants written on the run's own behalf: those derived here, and the APPLICATION creator-role
+ // grant, which would otherwise let that role read a private workflow's runs
{ ...recordScope, sourceId: In(batch) },
{ ...recordScope, rowCause: RecordShareRowCause.APPLICATION },
- // Whatever wrote it, a grant to everyone on a run means
- // workspace-visible, which only the core workflow decides.
+ // a grant to everyone means workspace-visible, which only the core workflow decides
{
...recordScope,
principalType: RecordSharePrincipalType.EVERYONE,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
index a6a6aa1ca67..d02d0a899cb 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/workflow-version-core-sync.service.ts
@@ -171,8 +171,7 @@ export class WorkflowVersionCoreSyncService {
{ workspaceId, flatMapsKeys: ['flatWorkflowVersionMaps'] },
);
- // The table decides create vs update: a stale map would send a persisted id
- // down the create branch and into the primary key.
+ // read the table, not the cache: a stale map would send a persisted id to create and hit the primary key
const persistedCoreVersionIds = new Set(
(
await this.coreWorkflowVersionRepository.find(workspaceId, {
@@ -354,10 +353,7 @@ export class WorkflowVersionCoreSyncService {
(_, index) => !isDefined(resolvedFlatVersions[index]),
);
- // The dual-write listener deletes the same ids when the mirror is soft
- // deleted, so an id gone from both the cache and the table is an idempotent
- // no-op. An id still in the table is a stale cache and must fail rather than
- // leave an orphan that still reads and still broadcasts.
+ // gone from the table means the dual-write listener already deleted it; still there means a stale cache, so fail rather than orphan it
if (missingCoreWorkflowVersionIds.length > 0) {
const stillPersisted = await this.coreWorkflowVersionRepository.find(
workspaceId,
@@ -553,9 +549,7 @@ export class WorkflowVersionCoreSyncService {
);
}
- // The conflict target is the primary key alone, so without the workspaceId
- // predicate a core row owned by another workspace would have its triggers
- // and steps overwritten.
+ // the conflict target is the primary key alone, so the workspaceId predicate keeps another workspace's row from being overwritten
const mirroredRows = await transactionScope.executeRawQuery(
`INSERT INTO core."workflowVersion"
("id", "workspaceId", "workflowId", "triggers", "steps", "status", "universalIdentifier", "applicationId", "coreWorkflowId"${hasWorkspaceVersionMapping ? ', "workspaceWorkflowVersionId"' : ''})
@@ -599,10 +593,7 @@ export class WorkflowVersionCoreSyncService {
);
}
- // This writer stays on raw SQL because it runs inside a transaction its
- // caller owns and relies on the locks taken above, so the flat entity maps
- // have to be refreshed by hand or the next migration write diffs against a
- // cache that no longer matches the table.
+ // raw SQL inside the caller's transaction bypasses the runner, so flat entity maps must be invalidated by hand
transactionScope.afterCommit(async () => {
await this.flatEntityMapsCacheService.invalidateFlatEntityMaps({
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-workflow-run-record-shares.util.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-workflow-run-record-shares.util.spec.ts
index 67fd0643f93..963d0ef2ebb 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-workflow-run-record-shares.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/build-workflow-run-record-shares.util.spec.ts
@@ -67,8 +67,6 @@ describe('buildWorkflowRunRecordShares', () => {
]);
});
- // A private workflow whose creator can no longer be resolved has nobody to
- // grant, and core shows such a workflow to nobody either.
it('grants nothing for a private workflow without a resolvable creator', () => {
expect(
buildWorkflowRunRecordShares({
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util.ts
index f11968a595c..09d770d3568 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-sql-predicate.util.ts
@@ -2,8 +2,7 @@ import { WorkflowVisibility } from 'twenty-shared/types';
import { canChangeCoreWorkflowVisibilitySqlPredicate } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util';
-// The list query is raw SQL on a keyset index, so it needs the same rule as a
-// fragment rather than a FindOptionsWhere.
+// SQL twin of buildCoreWorkflowVisibilityWhere for the raw keyset list query; keep them in sync
export const buildCoreWorkflowVisibilitySqlPredicate = ({
tableAlias,
userWorkspaceIdParameter,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util.ts
index bf1a8bf4961..b76ca44e366 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-core-workflow-visibility-where.util.ts
@@ -4,18 +4,8 @@ import { IsNull, type FindOptionsWhere } from 'typeorm';
import { type WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
-// A workflow is readable when the whole workspace can see it, when the reader
-// is the person who made it, or when nobody owns it. That last branch matters:
-// the owner FK is ON DELETE SET NULL, so a workflow whose creator left the
-// workspace would otherwise be visible to no one and editable by no one while
-// still running.
-//
-// The reader is absent for an API key, which authenticates a workspace rather
-// than a person: it reaches everything the workspace shares and nobody's
-// private workflow.
-//
-// The clauses are OR-ed by TypeORM, so any extra condition has to be repeated
-// in each of them.
+// ownerless workflows stay visible because the owner FK is ON DELETE SET NULL; userWorkspaceId is undefined for API keys,
+// which see shared workflows but nobody's private one. TypeORM ORs these clauses, so extra conditions go in each.
export const buildCoreWorkflowVisibilityWhere = ({
userWorkspaceId,
...where
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util.ts
index 84b2e91cac2..0ef26199d65 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/build-workflow-run-record-shares.util.ts
@@ -8,9 +8,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type RecordShareInput } from 'src/engine/core-modules/record-share/types/record-share-input.type';
-// The rule matches buildCoreWorkflowVisibilitySqlPredicate: everyone reads the
-// runs of a workspace-visible or ownerless workflow, and the creator always
-// reads their own.
+// must agree with buildCoreWorkflowVisibilitySqlPredicate
export const buildWorkflowRunRecordShares = ({
objectMetadataId,
workflowRunIds,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util.ts
index 930cbd1c11c..028fb9d2e23 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-select-expression.util.ts
@@ -1,9 +1,7 @@
import { canChangeCoreWorkflowVisibilitySqlPredicate } from 'src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util';
-// Selecting the predicate is not the same as filtering on it: an owned
-// workflow read by an API key gives `false OR NULL`, which is NULL, and
-// canChangeVisibility is a non-nullable GraphQL field. A WHERE clause treats
-// that NULL as false already, a projection does not.
+// An owned workflow read by an API key yields `false OR NULL`: WHERE treats that NULL as false, a projection
+// does not, and canChangeVisibility is non-nullable
export const canChangeCoreWorkflowVisibilitySelectExpression = (parameters: {
tableAlias: string;
userWorkspaceIdParameter: string;
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util.ts
index 49f87dc911e..c22a8c94ade 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility-sql-predicate.util.ts
@@ -1,6 +1,4 @@
-// The caller binds its own parameter for the reader, which is null for an API
-// key — hence the explicit IS NULL rather than a coalesce, which would read a
-// null reader as matching a null owner.
+// explicit IS NULL: a coalesce would match an API key's null reader against a null owner
export const canChangeCoreWorkflowVisibilitySqlPredicate = ({
tableAlias,
userWorkspaceIdParameter,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util.ts
index c9e8535d5c7..b745c59dca9 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/can-change-core-workflow-visibility.util.ts
@@ -1,8 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
-// Whether the reader may hand this workflow to the workspace or keep it to
-// themselves: they made it, or nobody did. The read rule in this directory has
-// to agree with this about an ownerless workflow.
+// the creator, or anyone when nobody made it; the visibility read rules in this directory must agree about ownerless workflows
export const canChangeCoreWorkflowVisibility = ({
createdByUserWorkspaceId,
userWorkspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/workflow-run-record-share.module.ts b/packages/twenty-server/src/engine/core-modules/workflow/workflow-run-record-share.module.ts
index 13e31a29936..b08dca99c83 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/workflow-run-record-share.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/workflow-run-record-share.module.ts
@@ -9,8 +9,7 @@ import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
-// Run creation, workflow visibility changes and member removal all rewrite run
-// grants, and those modules already depend on each other, so it lives on its own.
+// Its own module because its callers (run creation, visibility changes, member removal) already depend on each other
@Module({
imports: [
TypeOrmModule.forFeature([WorkflowEntity, UserWorkspaceEntity]),
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
index 392f6340ee1..70ac65ba64b 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/services/workspace.service.ts
@@ -111,10 +111,7 @@ import { WorkspaceManagerService } from 'src/engine/workspace-manager/workspace-
import { DEFAULT_FEATURE_FLAGS } from 'src/engine/workspace-manager/workspace-migration/constant/default-feature-flags';
import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
-// A workspace stuck in ONGOING_CREATION for longer than this is treated as a
-// crashed activation (the process died before the catch block could reset it to
-// PENDING_CREATION) and may be retried. It is far longer than a real activation
-// takes, so a genuinely in-progress activation is never reclaimed.
+// far longer than a real activation, so an older ONGOING_CREATION is a crashed attempt that may be reclaimed
const WORKSPACE_ACTIVATION_STALE_LOCK_TIMEOUT_MS = 5 * 60 * 1000;
const WORKSPACE_APPLICATION_UNINSTALL_RETRY_LIMIT = 3;
@@ -195,9 +192,7 @@ export class WorkspaceService {
private readonly applicationUninstallService: ApplicationUninstallService,
) {}
- // Pins are stored as given, so a stale or mistyped id must be refused here
- // rather than silently falling back to the tier default at run time. A pin
- // that is already stored is left alone so the others stay editable.
+ // reject unknown new pins now rather than silently falling back at run time; stored pins stay so the form remains editable
private validateAiModelIdByTier({
aiModelIdByTier,
storedAiModelIdByTier,
@@ -247,10 +242,7 @@ export class WorkspaceService {
}
}
- // Same contract as a tier pin: stored as given, so an id that names nothing
- // this instance can run must be refused here rather than stored and silently
- // ignored at run time. A pin already stored is left alone so the rest of the
- // form stays editable after an administrator withdraws the model.
+ // same contract as validateAiModelIdByTier
private validateAiEvaluationModelId({
aiEvaluationModelId,
storedAiEvaluationModelId,
@@ -484,13 +476,8 @@ export class WorkspaceService {
}
async activateWorkspace(user: AuthContextUser, workspace: WorkspaceEntity) {
- // Acquire the activation lock by atomically moving the workspace to
- // ONGOING_CREATION. First try the normal case (PENDING_CREATION). If nothing
- // matches, the workspace may be stuck in ONGOING_CREATION from a prior
- // attempt that was killed before the catch block could reset it — reclaim it,
- // but only once the lock is stale, so a genuinely concurrent activation is
- // never interrupted. Postgres row locking serializes concurrent reclaims, and
- // repository.update bumps updatedAt, so a reclaimed lock is immediately fresh.
+ // a workspace stuck in ONGOING_CREATION is reclaimed only once its lock is stale, so a live activation is never interrupted;
+ // row locking serializes reclaims and update bumps updatedAt, so a reclaimed lock is immediately fresh again
let activationLockResult = await this.workspaceRepository.update(
{
id: workspace.id,
@@ -513,10 +500,7 @@ export class WorkspaceService {
}
if ((activationLockResult.affected ?? 0) === 0) {
- // Activation is idempotent for the terminal state: if a prior attempt
- // already completed (e.g. the client lost the response and retried),
- // return the active workspace instead of failing. Otherwise another
- // activation is genuinely in progress and must not be interrupted.
+ // a client retrying after a lost response gets the already-active workspace
const existingWorkspace = await this.workspaceRepository.findOneBy({
id: workspace.id,
});
@@ -919,8 +903,7 @@ export class WorkspaceService {
}
}
- // FieldMetadataEntity has a self-referencing FK (relationTargetFieldMetadataId)
- // Related fields must be deleted together to avoid constraint violations
+ // relationTargetFieldMetadataId is a self-referencing FK, so related fields must share a chunk
private async getFieldMetadataIdChunks(
workspaceId: string,
): Promise<string[][]> {
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-discoverability.type.ts b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-discoverability.type.ts
index 844c4e7c47b..01fbda24eea 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-discoverability.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/types/workspace-discoverability.type.ts
@@ -1,9 +1,6 @@
-// Ordered privacy levels controlling how a workspace surfaces in the
-// root-domain (app.twenty.com) sign-in picker. Each level hides strictly more
-// than the previous one:
-// - PUBLIC: discoverable by anyone whose email domain matches an approved access domain
-// - MEMBERS_AND_INVITEES: hidden from email-domain discovery, still shown to members and invited users
-// - HIDDEN: never listed in the picker; members and invited users sign in from the workspace URL directly
+// Visibility in the root-domain sign-in picker, each level hiding strictly more than the previous:
+// PUBLIC is discoverable by approved access email domain, MEMBERS_AND_INVITEES is shown only to members and invitees,
+// HIDDEN is never listed and members and invitees sign in from the workspace URL.
export enum WorkspaceDiscoverability {
PUBLIC = 'PUBLIC',
MEMBERS_AND_INVITEES = 'MEMBERS_AND_INVITEES',
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
index e8567dd5fe8..c553fadd64b 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.entity.ts
@@ -359,15 +359,13 @@ export class WorkspaceEntity {
@Column({ type: 'boolean', nullable: false, default: true })
isAutoModelSelectionEnabled: boolean;
- // Only read while isAutoModelSelectionEnabled is false; kept when the toggle
- // goes back on so switching off again restores the previous pins.
+ // only read while auto selection is off; kept when it is re-enabled so turning it off again restores the pins
@Field(() => GraphQLJSON, { nullable: false })
@Column({ type: 'jsonb', nullable: false, default: {} })
aiModelIdByTier: Partial<Record<AiModelTier, string>>;
- // Which evaluation model a Classify step lands on when it names none. Null
- // means whichever the instance offers, so a workspace that never chooses
- // still runs and picks up an evaluation provider the day one is configured.
+ // model a Classify step uses when it names none; null means whatever the instance offers, so a workspace
+ // picks up an evaluation provider once one is configured
@Field(() => String, { nullable: true })
@Column({ type: 'text', nullable: true })
aiEvaluationModelId: string | null;
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
index 355df0088d7..8cc9cbf6a08 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
@@ -145,9 +145,7 @@ export class WorkspaceResolver {
NoPermissionGuard,
)
async activateWorkspace(
- // Deprecated: the workspace name is set at creation. This argument is kept
- // for backward compatibility (removing it would be a breaking schema change)
- // but is ignored.
+ // ignored, kept only because removing it would break the schema
@Args('data') _data: ActivateWorkspaceInput,
@AuthUser() user: AuthContextUser,
@AuthWorkspace() workspace: WorkspaceEntity,
diff --git a/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts b/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts
index 55979841bc8..df66df9f286 100644
--- a/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts
+++ b/packages/twenty-server/src/engine/guards/__tests__/run-guarded-query.test-util.ts
@@ -24,10 +24,7 @@ import supertest from 'supertest';
import { UnhandledExceptionFilter } from 'src/filters/unhandled-exception.filter';
-// Runs one query through a real Nest + Yoga app so a guard's refusal takes the
-// same path as in production: the root module mirrors the real one, so an
-// exception no typed filter claims lands in the catch-all filter. The module
-// classes are built per call because the resolver's guard is the parameter.
+// real Nest + Yoga app so a guard refusal reaches the catch-all filter as in production
export const runGuardedQuery = async ({
guard,
request,
@@ -81,8 +78,6 @@ export const runGuardedQuery = async ({
return result;
};
-// Same for a REST route: the request fields are set by a middleware standing in
-// for authentication, and a refusal goes through the catch-all filter.
export const runGuardedRestRequest = async ({
guard,
request,
diff --git a/packages/twenty-server/src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util.ts b/packages/twenty-server/src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util.ts
index f187d413102..aae2a9cd057 100644
--- a/packages/twenty-server/src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util.ts
+++ b/packages/twenty-server/src/engine/guards/utils/get-request-or-throw-when-unauthenticated.util.ts
@@ -17,10 +17,7 @@ const hasAuthenticatedPrincipal = (request: {
isDefined(request.apiKey) ||
isDefined(request.application);
-// A refusal reports FORBIDDEN, which clients read as a permission problem and
-// never recover from, so a request nothing authenticated has to say
-// UNAUTHENTICATED instead. GraphQL only, since the catch-all filter turns a
-// GraphQL error thrown on the REST path into a 500.
+// clients never recover from FORBIDDEN, so say UNAUTHENTICATED; GraphQL only, the REST catch-all would turn it into a 500
export const getRequestOrThrowWhenUnauthenticated = (
context: ExecutionContext,
) => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
index a258d75cca5..b6f289e0283 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
@@ -102,8 +102,7 @@ const buildAnswerText = ({
})
.join('\n\n');
-// The chat renderer, the admin panel and the seeded runs all read this result
-// shape.
+// result shape is read by the chat renderer, the admin panel and seeded runs
export const ASK_QUESTIONS_PAUSING_TOOL = definePausingTool<
AskQuestionsToolInput,
AskQuestionsToolOutput
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
index ba9460c842e..826e10d9d3d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
@@ -9,8 +9,6 @@ import { PROPOSE_EMAIL_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-ag
import { REQUEST_FORM_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/request-form.pausing-tool';
import { type PausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type';
-// Tools whose call ends the turn until a person submits its output through
-// answerToolCall.
export const PAUSING_TOOLS: ReadonlyMap<string, PausingTool> = new Map([
[ASK_QUESTIONS_TOOL_NAME, ASK_QUESTIONS_PAUSING_TOOL],
[PROPOSE_EMAIL_TOOL_NAME, PROPOSE_EMAIL_PAUSING_TOOL],
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool.ts
index 29efe7610d5..cb3a00728d5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool.ts
@@ -49,8 +49,6 @@ const DECISION_TOOLS = {
saveDraft: { toolName: 'draft_email', status: 'drafted' },
} as const;
-// Sending or drafting runs the regular email tools as the person who
-// approved, so their connected accounts and permissions decide what happens.
export const PROPOSE_EMAIL_PAUSING_TOOL = definePausingTool<
ProposedEmail,
ProposeEmailToolOutput
@@ -58,8 +56,7 @@ export const PROPOSE_EMAIL_PAUSING_TOOL = definePausingTool<
inputSchema: proposeEmailInputSchema,
outputSchema: () => proposeEmailOutputSchema,
complete: async ({ output: { decision, email }, input, context }) => {
- // The person may edit what is sent, not which account sends it: the card
- // offers no choice of account, so one in the answer is not theirs to pick.
+ // the card offers no account choice, so the answer may not override the sending account
const finalEmail = {
...(email ?? input),
connectedAccountId: input.connectedAccountId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type.ts
index 2b00c7ec680..326cb67b7c0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type.ts
@@ -1,7 +1,6 @@
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
-// Tools run as the person who answered, with their permissions, never as the
-// agent that asked.
+// tools run with the answering person's permissions, never the agent's
export type PausingToolCompletionContext = {
executeTool: (args: {
toolName: string;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts
index 15606617a7f..92ee713d78a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts
@@ -5,12 +5,8 @@ import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/a
export type PausingToolDefinition<TInput, TOutput> = {
inputSchema: z.ZodType<TInput>;
- // The output a person may submit depends on what the call asked, so the
- // schema is built from the call's input.
outputSchema: (input: TInput) => z.ZodType<TOutput>;
- // Runs once the person's output is accepted, and only then: whatever the
- // call does on the person's behalf happens here, and the tool result says
- // what came of it.
+ // runs only after the output is accepted, so side effects on the person's behalf belong here
complete: (args: {
output: TOutput;
input: TInput;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type.ts
index 2eeb8fbe2c0..9ed114f4c33 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type.ts
@@ -1,7 +1,6 @@
import { type PausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type';
-// A definition with its input and output types bound per call, so tools with
-// different inputs can share one map keyed by tool name.
+// type-erased so tools with different inputs can share one map
export type PausingTool = {
isAwaitingOutput: (toolOutput: unknown) => boolean;
parseCall: (toolInput: unknown) => PausingToolCall | null;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util.ts
index a6bf8f0affb..e4de4f791f7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util.ts
@@ -1,7 +1,6 @@
import { escapeHtml } from 'src/engine/core-modules/emailing-domain/utils/escape-html.util';
-// The approval card edits a plain-text body, while the email tools read a
-// string body as HTML, where line breaks would otherwise collapse.
+// email tools read a string body as HTML, where the card's plain-text line breaks would collapse
export const convertPlainTextToEmailHtml = (text: string): string =>
text
.split(/\n\s*\n/)
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util.ts
index ad60c18179f..a4d4903fc3f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util.ts
@@ -11,8 +11,6 @@ export type AwaitingPausingToolPart = {
isAnswerable: boolean;
};
-// A step can call several pausing tools at once, and each waits on its own
-// answer.
export const findAwaitingPausingToolParts = (
parts: ExtendedUIMessagePart[],
): AwaitingPausingToolPart[] =>
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts
index 72377a89e30..f277ca2b8fe 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/skip-awaiting-tool-parts.util.ts
@@ -4,8 +4,6 @@ import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution
import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
-// Closes the calls a message still waits on once nothing will answer them, so
-// the model and the conversation both show they went unanswered.
export const skipAwaitingToolParts = async ({
messagePartRepository,
messageId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index 37d72c0887f..3233b58a93b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -95,10 +95,7 @@ const EMPTY_USAGE: LanguageModelUsage = {
},
};
-// Agent execution uses registry tools plus native model tools. The caller
-// supplies the base system prompt describing its execution context (workflow
-// step, programmatic run). Workflow registry tools are intentionally excluded
-// to avoid circular dependencies and recursive workflow execution.
+// workflow registry tools are excluded to avoid circular dependencies and recursive workflow execution
@Injectable()
export class AgentAsyncExecutorService {
private readonly logger = new Logger(AgentAsyncExecutorService.name);
@@ -145,8 +142,7 @@ export class AgentAsyncExecutorService {
return {};
}
- // Workflow agent nodes run a scoped task: pre-load the full schemas of the
- // few explicitly-granted objects so the model skips the learn_tools round trip.
+ // preloading the few granted object schemas saves the model a learn_tools round trip
private async buildPreloadedRegistryTools({
agent,
agentRoleId,
@@ -186,10 +182,8 @@ export class AgentAsyncExecutorService {
});
}
- // Open-ended agents (runAgent / Slack) need broad object access, which would
- // make pre-loading ship every schema. Expose a compact catalog plus the
- // learn_tools / execute_tool meta-tools instead, using composed role
- // permissions rather than explicit grants only.
+ // open-ended agents have broad access, so preloading would ship every schema: expose a compact catalog plus
+ // learn_tools / execute_tool instead, scoped by composed role permissions rather than explicit grants only
private async buildLazyRegistryTools({
agent,
agentRoleId,
@@ -239,9 +233,7 @@ export class AgentAsyncExecutorService {
!excludedToolNames.has(entry.name),
);
- // Restrict the meta-tools to the shown catalog. Enforced at call time, so a
- // tool that appears after the catalog was built still can't be reached,
- // preserving the recursion guard.
+ // meta-tools are limited to the shown catalog, checked at call time so a tool added later stays unreachable (recursion guard)
const allowedToolNames = new Set(catalog.map((entry) => entry.name));
const isToolAllowed = (toolName: string): boolean =>
allowedToolNames.has(toolName);
@@ -278,11 +270,8 @@ export class AgentAsyncExecutorService {
}: {
agent: AgentEntity | null;
messages: RunAgentMessage[];
- // A conversation being continued, with its tool calls and results, which
- // plain run messages cannot carry.
+ // a continued conversation, with the tool calls and results plain run messages cannot carry
priorModelMessages?: ModelMessage[];
- // Tools whose call ends the execution so that the caller can wait for
- // something outside it, such as a person answering.
pausingTools?: ToolSet;
baseSystemPrompt: string;
actorContext?: ActorMetadata;
@@ -356,8 +345,6 @@ export class AgentAsyncExecutorService {
let registryTools: ToolSet = {};
- // Registry tools are scoped exclusively by the agent permission-tab
- // role. No role means no registry tools.
if (isDefined(agentRoleId)) {
if (toolLoadingStrategy === 'lazy') {
const lazyToolset = await this.buildLazyRegistryTools({
@@ -524,7 +511,6 @@ export class AgentAsyncExecutorService {
offeredToolNames,
});
- // An execution stopped on a pausing tool has no final answer to structure.
if (isDefined(agentSchema) && !endsOnPausingTool) {
const structuredResult = await generateText({
instructions: STRUCTURED_OUTPUT_SYSTEM_PROMPT,
@@ -600,8 +586,7 @@ export class AgentAsyncExecutorService {
cacheCreationTokens,
nativeWebSearchCallCount,
hasNoMoreAvailableCredits,
- // An execution out of credits fails even if it asked something, so it
- // must not be left waiting for an answer.
+ // out of credits fails the execution even if it asked something, so it is never left waiting for an answer
isPaused: endsOnPausingTool && !hasNoMoreAvailableCredits,
steps: executionSteps,
modelId: resolvedModelId,
@@ -621,8 +606,7 @@ export class AgentAsyncExecutorService {
resolvedModelId ??
agent?.modelId ??
AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID;
- // Nothing was generated when execution failed before a model resolved,
- // and pricing an unresolved id would throw over the original error.
+ // pricing an unresolved model id would throw over the original error
const costInDollars = isDefined(resolvedModelId)
? this.aiBillingService.calculateStepsCost(
resolvedModelId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/finalize-dangling-tool-parts.roundtrip.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/finalize-dangling-tool-parts.roundtrip.spec.ts
index 2c37d74c01c..a39f328a905 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/finalize-dangling-tool-parts.roundtrip.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/finalize-dangling-tool-parts.roundtrip.spec.ts
@@ -70,8 +70,7 @@ const unresolvedToolCallIds = async (
return [...pending];
};
-// convertToModelMessages drops the `input` field when a tool part's input is
-// nullish, so every reconstructed tool-call must carry a defined input.
+// convertToModelMessages drops a nullish `input`, so every reconstructed tool-call must carry one
const toolCallInputs = async (messages: UIMessage[]): Promise<unknown[]> => {
const modelMessages = await convertToModelMessages(messages);
const inputs: unknown[] = [];
@@ -151,8 +150,7 @@ describe('finalizeDanglingToolParts round-trip', () => {
);
});
- // A tool call that failed input validation: persisted as output-error with
- // a null input (issue #21695).
+ // failed input validation: persisted as output-error with a null input (#21695)
const validationErroredPart: ExtendedUIMessagePart = {
type: 'tool-execute_tool',
toolCallId: 'validation_failed_1',
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts
index 217000ff9a4..df06f5ad2e8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts
@@ -1,13 +1,11 @@
import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';
-// Not the SDK's hasToolCall: its stop condition may return a promise, and this
-// check is also read synchronously once the run returns, to report the pause.
+// not the SDK's hasToolCall, whose stop condition may be async: this is also read synchronously after the run
export const endsOnPausingToolCall = ({
steps,
offeredToolNames,
}: {
steps: { toolCalls: { toolName: string }[] }[];
- // Narrows the pause to the pausing tools a run was actually given.
offeredToolNames?: string[];
}): boolean =>
steps[steps.length - 1]?.toolCalls.some(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util.ts
index ef4913eb864..4ab584cdeb0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util.ts
@@ -2,9 +2,6 @@ import { type StepResult, type ToolSet } from 'ai';
import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
-// An agent run outside chat keeps no stream to persist, only the SDK's step
-// results. Rebuilding the parts a chat stream would have produced lets that
-// run be stored and read back as an ordinary conversation.
export const mapAiStepsToUiMessageParts = (
steps: Pick<StepResult<ToolSet>, 'content'>[],
): ExtendedUIMessagePart[] => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util.ts
index 2db30328783..1beab38f5a8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util.ts
@@ -4,8 +4,7 @@ import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-module
import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';
import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts';
-// A stored message is replayed to a model later, so a dangling tool part must
-// be finalized before it is stored, whichever path records the message.
+// stored messages are replayed to a model, so dangling tool parts are finalized first
export const mapUIMessagePartsToPersistedDBParts = (
uiMessageParts: ExtendedUIMessagePart[],
messageId: string,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartToUIMessagePart.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartToUIMessagePart.ts
index 79a8e6abe19..b1b72587324 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartToUIMessagePart.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartToUIMessagePart.ts
@@ -5,8 +5,7 @@ import {
import { AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
-// A parallel mapping for GraphQL DTOs exists in the frontend at:
-// packages/twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
+// keep in sync with twenty-front/src/modules/ai/utils/mapDBPartToUIMessagePart.ts
export const mapDBPartToUIMessagePart = (
part: AgentMessagePartWorkspaceEntity,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts.ts
index 9d76aab2eca..73e9b947441 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts.ts
@@ -70,8 +70,7 @@ export const mapUIMessagePartsToDBParts = (
state: part.data.state,
};
case 'data-code-execution':
- // Code execution parts are streamed during execution but don't need
- // to be persisted - the final result is captured in the tool part
+ // streamed only: the final result is captured in the tool part
return null;
case 'data-thread-title':
// Thread title is a transient notification for the client
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-monitor/resolvers/agent-turn.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-monitor/resolvers/agent-turn.resolver.ts
index 4e921a44660..75b0234b1c1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-monitor/resolvers/agent-turn.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-monitor/resolvers/agent-turn.resolver.ts
@@ -116,8 +116,7 @@ export class AgentTurnResolver {
@AuthWorkspaceMemberId() workspaceMemberId: string,
@AuthUserWorkspaceId() userWorkspaceId: string,
): Promise<AgentTurnWorkspaceEntity> {
- // Defense in depth: the job also re-fetches the agent through a
- // workspace-scoped repository.
+ // defense in depth: the job also re-fetches the agent workspace-scoped
await this.agentService.findOneAgentById({
id: agentId,
workspaceId: workspace.id,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/entities/agent.entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/entities/agent.entity.ts
index dc50bc9b90c..15ccb7cf1b5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/entities/agent.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/entities/agent.entity.ts
@@ -50,7 +50,7 @@ export class AgentEntity
})
modelId: ModelId;
- // Should not be nullable
+ // TODO: make non-nullable
@Column({ nullable: true, type: 'jsonb', default: { type: 'text' } })
responseFormat: JsonbProperty<AgentResponseFormat>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
index fcd798588d5..0e66f290f7b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
@@ -76,9 +76,7 @@ export class AiBillingService {
};
}
- // Evaluation models are looked up first: they price like a language model
- // but live in their own registry, and getEffectiveModelConfig would throw on
- // an id it has never registered.
+ // evaluation models first: getEffectiveModelConfig throws on ids outside its registry
private getCostConfig(modelId: ModelId): AiModelCostConfig {
return (
this.aiModelRegistryService.getEvaluationModelConfig(modelId) ??
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/types/billing-token-usage.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/types/billing-token-usage.type.ts
index f9530be3538..56553fc39e7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/types/billing-token-usage.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/types/billing-token-usage.type.ts
@@ -1,6 +1,4 @@
-// What billing reads out of a model call, whichever kind of model made it.
-// LanguageModelUsage satisfies it structurally; an evaluation model reports
-// token counts and nothing else, so the details are optional.
+// evaluation models report only token counts, so the details are optional
export type BillingTokenUsage = {
inputTokens?: number;
outputTokens?: number;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/utils/compute-cost-breakdown.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/utils/compute-cost-breakdown.util.ts
index 4590db8767e..a6f2b042d91 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/utils/compute-cost-breakdown.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/utils/compute-cost-breakdown.util.ts
@@ -29,16 +29,8 @@ const safeNumber = (value: number | undefined): number => {
return Number.isFinite(result) ? result : 0;
};
-// Input token semantics (all providers we use):
-// `inputTokens` is the FULL prompt size and already includes cached and
-// cache-creation tokens. The @ai-sdk/anthropic provider reports
-// inputTokens = noCache + cacheRead + cacheCreation, and OpenAI-style
-// providers include cached tokens (and never report cache-creation tokens).
-// So the uncached, full-rate portion is always inputTokens minus cached
-// minus cache-creation, and the full input size is just inputTokens.
-// Output token semantics still differ by model family:
-// Anthropic: outputTokens excludes reasoning (thinking) tokens
-// OpenAI/xAI/Groq/Google: outputTokens includes reasoning tokens
+// every provider we use counts cached and cache-creation tokens inside inputTokens
+// Anthropic's outputTokens excludes reasoning tokens; OpenAI/xAI/Groq/Google include them
export const computeCostBreakdown = (
model: AiModelCostConfig,
usage: TokenUsageInput,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/__mocks__/agent-chat-thread-target-flat-entity-maps.mock.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/__mocks__/agent-chat-thread-target-flat-entity-maps.mock.ts
index 83310ff8b86..b4ac74520e7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/__mocks__/agent-chat-thread-target-flat-entity-maps.mock.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/__mocks__/agent-chat-thread-target-flat-entity-maps.mock.ts
@@ -23,8 +23,7 @@ for (const flatFieldMetadata of Object.values(
]);
}
-// The standard application computes its objects with empty fieldIds, which the
-// workspace cache fills in, and the target's legs are found through them.
+// standard objects come with empty fieldIds that the workspace cache fills in
export const AGENT_CHAT_THREAD_TARGET_FLAT_ENTITY_MAPS_MOCK: Pick<
AllFlatEntityMaps,
'flatObjectMetadataMaps' | 'flatFieldMetadataMaps'
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module.ts
index 5c23f103805..8ae6b0f554a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module.ts
@@ -6,8 +6,7 @@ import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/a
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
-// Separate from AiChatModule so the record API's query hooks avoid its tool and
-// workflow dependencies
+// separate from AiChatModule so the record API's query hooks avoid its tool and workflow dependencies
@Module({
imports: [AgentHistoryModule, WorkspaceCacheModule],
providers: [
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
index 14fd961f90c..06648333acf 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
@@ -61,22 +61,17 @@ import { getChatModelId } from 'src/engine/metadata-modules/ai/ai-models/utils/g
export { STREAM_AGENT_CHAT_JOB_NAME, type StreamAgentChatJobData };
-// Derive assistantMessageId deterministically from streamId so assistant-message
-// persistence is idempotent per stream: a retried job for the stream is skipped,
-// while each distinct resume in a turn persists its own message.
+// assistantMessageId derives from streamId, so a retried job skips persistence while each resume persists its own message
const ASSISTANT_MESSAGE_ID_NAMESPACE = '0b9c2a3d-4e5f-4a1b-8c2d-3e4f5a6b7c8d';
@Processor({ queueName: MessageQueue.aiStreamQueue, scope: Scope.REQUEST })
export class StreamAgentChatJob {
private readonly logger = new Logger(StreamAgentChatJob.name);
- // The processor is REQUEST-scoped, so this is per job. A publish failure
- // after the stream already classified its outcome reaches the catch in
- // handle(), which would otherwise count the same turn a second time.
+ // keeps the catch in handle() from counting a turn the stream already classified
private hasRecordedTurnOutcome = false;
- // Set once the turn has paused on a person, which is what the queue waits
- // on: a queued message drained now would bypass the answer it is waiting for.
+ // set once the turn pauses on a person: a queued message drained then would bypass the pending answer
private isAwaitingInput = false;
constructor(
@@ -270,10 +265,7 @@ export class StreamAgentChatJob {
}
}
- // The turn-started counter fires before the model is resolved downstream, so
- // resolve it here too: auto-select ids such as `default-fast-model` would
- // otherwise label the start of a turn differently from its outcome, and every
- // per-model rate is computed across the two.
+ // resolve auto-select ids here so turn-start and outcome metrics carry the same model label
private resolveTurnModelId(
requestedModelId: string | undefined,
workspace: WorkspaceEntity | null,
@@ -422,9 +414,7 @@ export class StreamAgentChatJob {
return persistChain;
};
- // onEnd fires before the uiStream is fully drained. We use this
- // promise to coordinate: the IIFE waits for DB persist to complete
- // before publishing message-persisted (after all chunks).
+ // onEnd fires before the uiStream drains, so message-persisted waits on this
let resolveStreamFinished: () => void;
const streamFinishedPromise = new Promise<void>((res) => {
resolveStreamFinished = res;
@@ -607,8 +597,7 @@ export class StreamAgentChatJob {
}
})();
- // Publish all chunks first, then signal completion. This guarantees
- // message-persisted arrives after every stream-chunk on the client.
+ // message-persisted must reach the client after every stream-chunk
void (async () => {
try {
for await (const chunk of publishStream) {
@@ -777,8 +766,7 @@ export class StreamAgentChatJob {
}
}
- // Returns null when the stream errored: that turn is accounted for by the
- // catch in handle(), and counting it here too would double it.
+ // null on stream error: the catch in handle() already counts that turn
private async persistStreamFinish({
assistantMessageId,
streamId,
@@ -823,8 +811,7 @@ export class StreamAgentChatJob {
);
const awaitingParts = findAwaitingPausingToolParts(responseMessage.parts);
- // Without an answerable call nothing can resume the turn, so it fails and
- // can be retried rather than wait forever.
+ // without an answerable call nothing can resume the turn, so fail rather than wait forever
const isAwaitingAnswer =
awaitingParts.length > 0 &&
awaitingParts.every(({ isAnswerable }) => isAnswerable);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/listeners/agent-chat-thread-lifecycle.listener.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/listeners/agent-chat-thread-lifecycle.listener.ts
index 9d180ea42a5..886b481cb20 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/listeners/agent-chat-thread-lifecycle.listener.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/listeners/agent-chat-thread-lifecycle.listener.ts
@@ -9,8 +9,8 @@ import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
-// Destroys reach here from both the record API and the chat mutations, and a
-// destroy hook only sees the selected columns of a row that is already gone
+// a listener rather than a destroy hook: destroys come from both the record API and chat mutations,
+// and a destroy hook only sees the selected columns of a row that is already gone
@Injectable()
export class AgentChatThreadLifecycleListener {
constructor(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts
index e97fb710e94..27b279ac32b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts
@@ -72,8 +72,7 @@ export class AgentChatActorService {
AiExceptionCode.MESSAGE_NOT_FOUND,
);
}
- // Only pre-attribution messages inherit the original participant. Never use
- // a worker's caller or the participant whose preceding turn drained the queue.
+ // only pre-attribution messages inherit the thread's member; never the worker's caller or the participant whose turn drained the queue
let userWorkspaceId = message.senderUserWorkspaceId;
if (!isDefined(userWorkspaceId)) {
const thread = await this.threads.findOneOrFail(workspaceId, {
@@ -157,8 +156,7 @@ export class AgentChatActorService {
return { authContext, rolePermissionConfig, roleId };
}
- // The call belongs to the turn that made it, so it is resolved from the
- // application context that turn was sent from and not from another one.
+ // resolved from the application context of the turn that made the call
async authorizeToolCallResolution({
workspaceId,
threadId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
index c02ebf14ce0..1fc3312e528 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
@@ -199,8 +199,7 @@ export class AgentChatSharingService {
}): Promise<TResult> {
const authContext = await this.getAuthContext(args);
const objectMetadata = await this.getThreadObjectMetadata(args.workspaceId);
- // Preload the workspace context before reserving a core connection. Sharing
- // changes and domain writes then serialize on the same grant/record locks.
+ // preloaded before reserving a core connection; sharing changes and domain writes then serialize on the same grant/record locks
return this.workspaceOrmManager.executeInWorkspaceContext(
() =>
this.threadRepository.query(args.workspaceId, async (context) => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
index 55fe1ec57c5..56feee1c379 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
@@ -596,8 +596,7 @@ export class AgentChatStreamingService {
select: ['id', 'deletedAt', 'pendingQuestionMessageId'],
});
- // Queued messages wait behind a pending tool call: they are the
- // conversation after the answer, not a replacement for it.
+ // queued messages wait behind a pending tool call: they follow the answer rather than replace it
if (
!threadStatus ||
threadStatus.deletedAt ||
@@ -631,8 +630,7 @@ export class AgentChatStreamingService {
userWorkspaceId = sender.userWorkspaceId;
break;
} catch (error) {
- // A rolling upgrade can temporarily leave a worker with an older access
- // policy. Preserve the request until a worker can authorize it.
+ // during a rolling upgrade a worker may run an older access policy, so keep the request for another worker
if (
error instanceof AiException &&
error.code === AiExceptionCode.THREAD_NOT_FOUND
@@ -766,11 +764,9 @@ export class AgentChatStreamingService {
}
}
- // A message sent while the agent waits on a person moves the conversation
- // past its pending calls, which are closed as skipped so the model sees why
- // they went unanswered. Clearing the marker is the claim, and an answer
- // holding the stream keeps it. A workflow run's calls gate the run, so a
- // chat message never closes them.
+ // a message sent while the agent waits on a person closes its pending calls as skipped, so the model sees why
+ // clearing the marker is the claim, which an answer holding the stream keeps
+ // workflow-run calls gate the run, so a chat message never closes them
private async settlePendingToolCallsBeforeSending({
thread,
workspaceId,
@@ -853,8 +849,7 @@ export class AgentChatStreamingService {
where: { id: threadId },
})
: undefined;
- // A hidden row without parts is an interrupted seed attempt: it carries no context and
- // would otherwise reach the model as an empty user message.
+ // a hidden row without parts is an interrupted seed and would reach the model as an empty message
const filteredMessages = allMessages.filter(
(message) =>
message.status !== AgentMessageStatus.QUEUED &&
@@ -887,8 +882,7 @@ export class AgentChatStreamingService {
return part;
}),
),
- // The hidden context seed gets no createdAt so injectMessageTimestamps skips it: its
- // insert time is meaningless and later than the first real message it sorts before.
+ // no createdAt so injectMessageTimestamps skips the seed, whose insert time postdates the first real message
...(message.isHidden
? {}
: {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
index a4f894e1d36..e1c893f3433 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service.ts
@@ -61,8 +61,7 @@ export class AgentChatThreadLifecycleService {
);
}
- // Awaited by the soft delete paths so the stream is stopped before they
- // respond
+ // awaited so the stream stops before the soft delete responds
async stopDeletedThreads({
workspaceId,
threadIds,
@@ -88,8 +87,7 @@ export class AgentChatThreadLifecycleService {
}
}
- // A run's conversation is the record of what its agent step did, so the
- // record API may read it but not edit, delete or destroy it
+ // a run's conversation records what its agent step did, so the record API may only read it
async assertThreadIsNotWorkflowRunThread({
workspaceId,
threadId,
@@ -109,8 +107,7 @@ export class AgentChatThreadLifecycleService {
}
}
- // The owner field is not writable through the record API. Owned and
- // workflow-run threads are skipped so an upsert cannot reassign them
+ // owned and workflow-run threads are skipped so an upsert cannot reassign them
async assignCreatedThreadsToCreator({
authContext,
threadIds,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service.ts
index 06a4af539ba..59ecd0a7c18 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service.ts
@@ -17,8 +17,7 @@ import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/a
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-// Chat history writes skip record events, so record subscribers only hear of
-// them from here
+// chat history writes skip record events, so subscribers only hear of them from here
@Injectable()
export class AgentChatThreadRecordEventService {
constructor(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-target.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-target.service.ts
index c8c8ca63d9e..f52688f7683 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-target.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-target.service.ts
@@ -30,10 +30,7 @@ export class AgentChatThreadTargetService {
private readonly workspaceCacheService: WorkspaceCacheService,
) {}
- // The link is written as the member, as the record API would write it. It
- // inherits its readability from the conversation, so the ORM refuses it
- // unless the member can edit that conversation. A chat turn runs in a queue
- // worker, outside the request that sent it, so it passes its sender's context.
+ // chat turns run in a queue worker, so the sender's context is passed to write the link as them
async attachThreadToRecord({
workspaceId,
threadId,
@@ -63,8 +60,7 @@ export class AgentChatThreadTargetService {
AGENT_CHAT_THREAD_TARGET_OBJECT_METADATA_NAME,
);
- // As on noteTarget, only the standard legs carry a unique index, so a
- // link to a custom object is deduplicated by looking for it first.
+ // only standard legs have a unique index, so custom-object links are deduplicated by lookup
if (await repository.existsBy(link)) {
return;
}
@@ -91,8 +87,7 @@ export class AgentChatThreadTargetService {
throw error;
});
- // Not-found rather than forbidden, so a member cannot probe for records
- // outside their grants.
+ // not-found rather than forbidden so members cannot probe for records outside their grants
if (!isDefined(record)) {
throw new AiException(
'Record not found',
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
index 534d5b32687..1aeb9a92463 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
@@ -579,8 +579,7 @@ export class AgentChatService {
return savedTurnId;
}
- // A tool call id is only unique within the conversation that made it, so
- // the part is looked up through its message's thread.
+ // tool call ids are only unique within a conversation
async findToolPart({
threadId,
toolCallId,
@@ -645,9 +644,7 @@ export class AgentChatService {
);
}
- // The answer and, once no call of the message still waits, the
- // conversation no longer waiting on it are written together, so an answer
- // never strands a conversation waiting on calls that are all answered.
+ // written together so an answer never strands a conversation waiting on answered calls
async recordToolCallAnswer({
threadId,
messageId,
@@ -681,8 +678,6 @@ export class AgentChatService {
);
}
- // Calls nothing can answer anymore are closed, so the conversation no longer
- // waits on them.
async closePendingToolCalls({
threadId,
messageId,
@@ -705,7 +700,6 @@ export class AgentChatService {
});
}
- // Sending to a soft deleted conversation brings it back to the list
async restoreThread({
threadId,
workspaceMemberId,
@@ -753,8 +747,7 @@ export class AgentChatService {
const threadAfter = { ...thread, updatedAt: new Date().toISOString() };
- // Conversations are listed by most recent change, so a message moves its
- // conversation to the top when it is sent, not only once the turn ends.
+ // conversations sort by last change, so bump on send rather than at turn end
await this.threadRepository.update(
workspaceId,
{ id: threadId },
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
index 7f5c556c099..88aff960b17 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
@@ -263,7 +263,6 @@ export class ChatExecutionService {
registeredModel.modelId,
);
- // Native and action search may both be bound here; the model picks at runtime.
const nativeCapabilities = getNativeModelCapabilities(
registeredModel.sdkPackage,
);
@@ -272,9 +271,6 @@ export class ChatExecutionService {
twitterSearch: nativeCapabilities?.twitterSearch === true,
});
- // Tools the model can call directly: preloaded registry tools (already
- // serialized by the hydrator) plus SDK-native tools (opaque, never
- // serialized). execute_tool routes discovered tools through the registry.
const directTools: ToolSet = {
...preloadedTools,
...nativeTools,
@@ -300,9 +296,7 @@ export class ChatExecutionService {
modelId: registeredModel.modelId,
});
- // Judged on the conversation rather than on setup still running: once setup
- // completes, the member's onboarding carries on in this same conversation,
- // and it is not one to file under their records.
+ // judged on the conversation, not setup status: onboarding continues here after setup completes
const canAttachConversationToRecords =
!isWorkspaceSetupConversation &&
(await this.featureFlagService.isFeatureEnabled(
@@ -330,8 +324,6 @@ export class ChatExecutionService {
const isToolAllowed = (toolName: string) =>
!AI_CHAT_EXCLUDED_TOOL_NAMES.has(toolName);
- // ToolSet is constant for the entire conversation — no mutation.
- // learn_tools returns schemas as text; execute_tool dispatches via the registry.
const activeTools: ToolSet = {
...directTools,
[ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({
@@ -390,8 +382,7 @@ export class ChatExecutionService {
const uploadedFiles = collectUploadedFileReferences(messages);
- // Skills the user tagged with / are inlined into the prompt so the model
- // does not spend a round trip calling load_skills for them.
+ // inline tagged skills to save the model a load_skills round trip
const referencedSkills = await this.skillService.findFlatSkillsByIds(
collectReferencedSkillIds(messages),
workspace.id,
@@ -560,8 +551,6 @@ export class ChatExecutionService {
userWorkspaceId,
);
- // billNativeWebSearchUsage short-circuits when count <= 0, so calling
- // unconditionally is safe regardless of whether native search fired.
void this.aiBillingService.billNativeWebSearchUsage(
countNativeWebSearchCallsFromSteps(steps),
workspace.id,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
index c0901466d2b..afcb0ffcaa8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
@@ -253,8 +253,7 @@ export class WorkspaceSetupChatService {
userLocale: string | null;
workspaceId: string;
}): Promise<string> {
- // The workspace member locale is what the UI is translated with, while the user
- // one stays at its signup default, so the assistant must follow the member locale.
+ // follow the member locale the UI uses; the user locale stays at its signup default
const workspaceMemberLocale = await this.findWorkspaceMemberLocale({
userId,
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/attach-conversation-to-record.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/attach-conversation-to-record.tool.ts
index a3b8eca815d..0acb1016dd4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/attach-conversation-to-record.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/attach-conversation-to-record.tool.ts
@@ -52,8 +52,7 @@ export const createAttachConversationToRecordTool = ({
const failureMessage = `Failed to attach this conversation to the ${objectNameSingular} record`;
try {
- // Resolved at call time, as registry tools are, so access withdrawn
- // since the turn began is honored.
+ // resolved at call time so access withdrawn mid-turn is honored
const { workspaceId, threadId, authContext } =
await (toolContext.resolveExecutionContext?.() ?? toolContext);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts
index 3f3566e56c4..94437d5da7e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool.ts
@@ -16,8 +16,7 @@ const requestFormFieldSchema = workflowFormFieldSchema.pick({
settings: true,
});
-// A form step issues this call with every field of its form, so a recorded
-// call is read without the limits an agent is held to.
+// form steps issue this call with every field, so recorded calls skip the agent's limits
export const requestFormCallSchema = z.object({
fields: z.array(requestFormFieldSchema),
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts
index 169e1987853..f51ec787b3d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-turn-outcome.type.ts
@@ -1,5 +1,4 @@
-// Every started turn resolves to exactly one of these so that
-// started = completed + cancelled + failed holds on the dashboards.
+// exactly one per started turn so started = completed + cancelled + failed on dashboards
export type AgentChatTurnOutcome =
| { kind: 'completed'; outcome: 'answered' | 'awaiting_user' }
| { kind: 'cancelled'; reason: 'user_cancelled' | 'superseded' }
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-agent-chat-thread-target-join-column-name.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-agent-chat-thread-target-join-column-name.util.spec.ts
index ab9612cfd33..713a916675b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-agent-chat-thread-target-join-column-name.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-agent-chat-thread-target-join-column-name.util.spec.ts
@@ -29,8 +29,6 @@ const findStandardObject = (nameSingular: keyof typeof STANDARD_OBJECTS) => {
const targetFlatObjectMetadata = findStandardObject('agentChatThreadTarget');
-// Adds a field to agentChatThreadTarget the way a side effect would: the field
-// itself, and its id on the object.
const withTargetField = (
flatFieldMetadata: FlatFieldMetadata,
): {
@@ -101,8 +99,6 @@ describe('findAgentChatThreadTargetJoinColumnName', () => {
).toBe('targetPetId');
});
- // Like notes, chats only attach to person, company, opportunity and custom
- // objects.
it('finds no leg for a standard object chats do not attach to', () => {
expect(
findAgentChatThreadTargetJoinColumnName({
@@ -113,8 +109,6 @@ describe('findAgentChatThreadTargetJoinColumnName', () => {
).toBeUndefined();
});
- // Only the target's own morph attaches a chat to a record, not any other
- // morph relation the target may carry to the same object.
it('ignores a relation to the object outside the target morph', () => {
const taskObjectMetadataId = findStandardObject('task').id;
@@ -138,8 +132,7 @@ describe('findAgentChatThreadTargetJoinColumnName', () => {
).toBeUndefined();
});
- // Its upgrade command provisions the target, so a workspace can briefly run
- // this code without it.
+ // an upgrade command provisions the target, so a workspace can briefly lack it
it('finds no leg in a workspace without the chat target', () => {
const { [targetFlatObjectMetadata.universalIdentifier]: _target, ...rest } =
flatObjectMetadataMaps.byUniversalIdentifier;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-update-event.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-update-event.util.ts
index 9d9c9293515..119fe55d05e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-update-event.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-update-event.util.ts
@@ -32,8 +32,7 @@ export const buildAgentChatThreadUpdateEvent = ({
flatFieldMetadataMaps,
);
- // The generic diff leaves updatedAt out, but a sent message changes nothing
- // else and conversation lists are ordered by it
+ // the generic diff omits updatedAt, yet a sent message changes only that and lists sort by it
if (
Object.keys(diff).length === 0 &&
!fastDeepEqual(threadBefore.updatedAt, threadAfter.updatedAt)
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts
index eeb4a705f85..43804d5562a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util.ts
@@ -11,9 +11,7 @@ export const classifyAgentChatTurnOutcome = ({
isAwaitingUserAnswer: boolean;
outOfCredits: boolean;
}): AgentChatTurnOutcome => {
- // Asking the user a question is how a turn is meant to end when the request is
- // ambiguous, and stopWhen ends the stream on it — so it is a completed turn
- // waiting on an answer, not an abandoned one.
+ // stopWhen ends the stream on a question, so this is a completed turn, not an abandoned one
if (isAwaitingUserAnswer) {
return { kind: 'completed', outcome: 'awaiting_user' };
}
@@ -32,11 +30,8 @@ export const classifyAgentChatTurnOutcome = ({
};
};
-// Losing the stream claim says the turn's result may never have reached the
-// user, which is worth recording over "completed". It says nothing about a
-// failure that already happened, so those keep their own phase — otherwise a
-// turn that ran out of credits during a claim handover is filed as a plain
-// cancellation and the billing signal disappears.
+// a lost stream claim overrides completion, but failures keep their phase so an out-of-credits turn
+// during a claim handover keeps its billing signal
export const resolveSupersededTurnOutcome = (
outcome: AgentChatTurnOutcome,
): AgentChatTurnOutcome =>
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util.ts
index a4a50dd24c1..54247eecd6f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/collect-referenced-skill-ids.util.ts
@@ -1,9 +1,7 @@
import { type ExtendedUIMessage } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
-// Matches the [[skill:<uuid>:<label>]] references the composer inserts when a
-// user picks a skill from the / menu. Only the id prefix is matched so a label
-// containing brackets cannot break the lookup.
+// matches only the id prefix of [[skill:<uuid>:<label>]] so brackets in a label cannot break it
const SKILL_REFERENCE_REGEX =
/\[\[skill:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}):/g;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-agent-chat-thread-target-join-column-name.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-agent-chat-thread-target-join-column-name.util.ts
index b54c076dc3a..da467253884 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-agent-chat-thread-target-join-column-name.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-agent-chat-thread-target-join-column-name.util.ts
@@ -8,10 +8,8 @@ import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/
import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
-// A thread reaches its record through the target's morph leg for that object,
-// the same way noteTarget does. No leg means the object cannot hold chats: it
-// is a standard object other than person, company and opportunity, or the
-// workspace has no agentChatThreadTarget yet.
+// A thread reaches its record through the target's morph leg for that object; no leg means it cannot hold chats
+// (standard objects other than person, company and opportunity, or no agentChatThreadTarget yet)
export const findAgentChatThreadTargetJoinColumnName = ({
flatObjectMetadataMaps,
flatFieldMetadataMaps,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-thread.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-thread.util.ts
index 6f61b6af523..b17c6d16ad3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-thread.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-thread.util.ts
@@ -17,8 +17,7 @@ export const lockAgentChatThread = async ({
objectMetadataId: string;
threadId: string;
}): Promise<AgentChatThreadWorkspaceEntity> => {
- // Match generic sharing's lock order so concurrent revocations and domain
- // writes cannot authorize against different grant/record snapshots.
+ // generic sharing's lock order, so revocations and writes cannot authorize against different snapshots
await manager.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [
buildRecordShareLockKey({
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts
index 147cf7b1cd4..bded4e09997 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts
@@ -27,8 +27,7 @@ export const updateAgentChatThreadUsage = async ({
usage: ThreadUsageUpdate;
}): Promise<{ affected: number }> =>
repository.query(workspaceId, async ({ manager, table }) => {
- // Keep arithmetic in PostgreSQL and ownership in the same UPDATE. DTO numbers
- // must never be read back and added to exact NUMERIC totals in JavaScript.
+ // sum in Postgres: JS numbers must never be added to exact NUMERIC totals
const rows = await manager.query<{ id: string }[]>(
`
WITH updated AS (
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/native-evaluation.runner.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/native-evaluation.runner.ts
index 2a851ce6600..d0f056c53d1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/native-evaluation.runner.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/native-evaluation.runner.ts
@@ -12,10 +12,7 @@ import { type AiEvaluationRequest } from 'src/engine/metadata-modules/ai/ai-eval
import { type AiEvaluationRunnerOutput } from 'src/engine/metadata-modules/ai/ai-evaluation/types/ai-evaluation-result.type';
import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
-// Runs the questions on a model built for them, through the SDK's evaluate()
-// rather than the provider's doEvaluate directly: it validates the answers
-// against the questions asked, so an off-menu option or a distribution that
-// does not sum to one is rejected before a workflow can branch on it.
+// evaluate() rather than doEvaluate validates answers, so invalid ones are rejected before a workflow branches on them
@Injectable()
export class NativeEvaluationRunner {
constructor(
@@ -49,8 +46,7 @@ export class NativeEvaluationRunner {
model: registeredModel.model,
state,
questions,
- // The workflow step owns retries, so a failure surfaces to it instead of
- // being spent silently here.
+ // the workflow step owns retries
maxRetries: 0,
...(isDefined(abortSignal) && { abortSignal }),
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/types/ai-evaluation-request.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/types/ai-evaluation-request.type.ts
index 2f9108c5a49..6ddde8e57ec 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/types/ai-evaluation-request.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/types/ai-evaluation-request.type.ts
@@ -5,8 +5,7 @@ import {
export type AiEvaluationRequest = {
workspaceId: string;
- // Attributes the spend to the member who triggered the run, and is the
- // spender the quota check is made against.
+ // spend attribution and quota check target
userWorkspaceId?: string | null;
state: AiEvaluationModelInput;
questions: Record<string, AiEvaluationModelQuestion>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-supported.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-supported.util.ts
index cddff7df8a9..4e0e8397416 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-supported.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-supported.util.ts
@@ -7,8 +7,6 @@ import {
import { type AiEvaluationModelConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model-config.type';
import { type AiEvaluationModelQuestion } from 'src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model.type';
-// A choice menu and a score rubric are capped differently, so each question
-// type is measured against the limit that applies to it.
const getCriteriaLimit = ({
question,
modelConfig,
@@ -34,8 +32,6 @@ const getCriteriaLimit = ({
}
};
-// Capabilities are declared in the catalog rather than inferred, so a request a
-// model cannot serve is refused before any network call is made.
export const assertEvaluationQuestionsAreSupported = ({
questions,
modelConfig,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-well-formed.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-well-formed.util.ts
index 33c7c0d22ff..9d0432ef145 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-well-formed.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/utils/assert-evaluation-questions-are-well-formed.util.ts
@@ -49,8 +49,7 @@ export const assertEvaluationQuestionsAreWellFormed = (
);
}
- // A one-level rubric has nothing to grade between, and the spec floors it
- // at two because a score is a position on that ladder.
+ // the spec floors a score rubric at two levels
if (question.type === 'score' && question.criteria.length < 2) {
throw new AiException(
`Score question "${questionId}" needs at least two levels`,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts
index f34168135e0..de4aa1d83f2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository.ts
@@ -218,8 +218,7 @@ export class AgentHistoryRepository<TRecord extends { id: string }> {
conflictPaths: string[],
) {
return this.run(workspaceId, async (repository, context) => {
- // Workspace upsert selects before inserting. Serialize concurrent stream
- // checkpoints for the same identity so both cannot take the insert path.
+ // workspace upsert selects before inserting, so serialize concurrent checkpoints per identity
const valuesByField: ObjectLiteral = values;
const identity = [...conflictPaths]
.sort()
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts
index 547021142e0..d7d5e4d5d75 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts
@@ -115,7 +115,6 @@ export class AgentHistoryWorkspaceStorageService {
await runner.connect();
await runner.startTransaction('REPEATABLE READ');
await runner.query('SET TRANSACTION READ ONLY');
- // Unprovisioned workspaces have no history tables to include in reports.
const provisioned: { workspaceId: string }[] = await runner.query(
`SELECT id AS "workspaceId" FROM unnest($1::uuid[], $2::text[]) AS candidate(id, table_name) WHERE to_regclass(table_name) IS NOT NULL
AND EXISTS (SELECT 1 FROM core."keyValuePair" state WHERE state."workspaceId" = candidate.id
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-evaluation-models-json.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-evaluation-models-json.spec.ts
index 028fa0a7e1a..4241c7138bf 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-evaluation-models-json.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-evaluation-models-json.spec.ts
@@ -3,10 +3,7 @@ import { z } from 'zod';
import defaultAiEvaluationModels from 'src/engine/metadata-modules/ai/ai-models/ai-evaluation-models.json';
import { aiProviderModelConfigSchema } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema';
-// Hand-maintained, unlike ai-models.json: models.dev has no notion of an
-// evaluation model, so the daily sync can neither add these nor keep them. The
-// sync folds this file into the catalog, which is why it carries what a model
-// is and never how it is reached — routes and credentials live in the spec.
+// hand-maintained: models.dev has no evaluation models, so the daily sync cannot add or keep them
const evaluationVendorsSchema = z.record(
z.string(),
z.object({ models: z.array(aiProviderModelConfigSchema).nonempty() }),
@@ -32,8 +29,7 @@ describe('ai-evaluation-models.json integrity', () => {
it('should price every model, free output included', () => {
Object.values(vendors).forEach((vendor) => {
vendor.models.forEach((model) => {
- // An omitted price bills nothing while the provider still charges, so
- // free output has to say so with an explicit 0.
+ // an omitted price bills nothing while the provider still charges
expect(model.inputCostPerMillionTokens).toBeDefined();
expect(model.outputCostPerMillionTokens).toBeDefined();
});
@@ -49,8 +45,7 @@ describe('ai-evaluation-models.json integrity', () => {
});
});
- // Where a self-hosted instance processes and retains data depends on its own
- // provider accounts, so the shipped catalog states neither on its behalf.
+ // residency and retention depend on each self-hosted instance's own provider accounts
it('should not assert data residency or zero data retention', () => {
Object.values(vendors).forEach((vendor) => {
vendor.models.forEach((model) => {
@@ -60,8 +55,7 @@ describe('ai-evaluation-models.json integrity', () => {
});
});
- // Routes belong to ai-self-host-spec.json; a credential here would be
- // committed to the repository and ignored by the pipeline besides.
+ // routes belong to ai-self-host-spec.json, and a credential here would be committed
it('should carry no routing or credentials', () => {
Object.values(defaultAiEvaluationModels).forEach((vendor) => {
expect(Object.keys(vendor)).toEqual(['models']);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-model-benchmarks-json.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-model-benchmarks-json.spec.ts
index 7a0156cc365..a0436d7ef99 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-model-benchmarks-json.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-model-benchmarks-json.spec.ts
@@ -52,8 +52,7 @@ describe('ai-model-benchmarks.json integrity', () => {
});
it('should agree with the benchmark merged into the catalog', () => {
- // The overlay is empty until the sync runs with an API key configured, so
- // this checks the two artifacts cannot drift rather than pinning a count.
+ // the overlay is empty until the sync runs with an API key, so check drift rather than a count
SCORED_CATALOG_MODELS.forEach((model) => {
const entry = OVERLAY_MODELS[model.name];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-provider-model-config.schema.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-provider-model-config.schema.spec.ts
index 2df66ee0dd7..4225707bf04 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-provider-model-config.schema.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-provider-model-config.schema.spec.ts
@@ -37,8 +37,7 @@ describe('aiProviderModelConfigSchema', () => {
});
it('rejects a reading filed under another effort than it was measured at', () => {
- // The registry hands a variant the reading under its own key, so this
- // would give the low-effort variant a high-effort figure.
+ // the registry keys readings by effort, so this would give the low variant a high figure
expect(
issuePaths(
modelWith({
@@ -125,8 +124,7 @@ describe('aiProviderModelConfigSchema', () => {
).toEqual(['supportedQuestionTypes']);
});
- // Free output has to say so with an explicit 0, or the model bills nothing
- // while the provider still charges.
+ // free output needs an explicit 0: an omitted price bills nothing while the provider still charges
it('rejects an evaluation model that omits a token cost', () => {
expect(
issuePaths({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts
index f717d71157b..27551a3af5a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts
@@ -55,9 +55,7 @@ describe('ai-providers.json integrity', () => {
});
});
- // An evaluation model answers questions against a state it is handed whole,
- // so it has no window to size and no output to cap; what it does have is the
- // set of question types it can answer.
+ // evaluation models get the whole state at once, so there is no window to size
it('should declare the question types of every evaluation model, and no window', () => {
Object.values(PROVIDERS).forEach((config) => {
(config.models ?? [])
@@ -111,8 +109,7 @@ describe('ai-providers.json integrity', () => {
});
});
- // Where a self-hosted instance processes and retains data depends on its own
- // provider accounts, so the shipped catalog states neither on its behalf.
+ // residency and retention depend on each self-hosted instance's own provider accounts
it('should not assert data residency or zero data retention', () => {
Object.values(PROVIDERS).forEach((config) => {
expect(config.dataResidency).toBeUndefined();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/constants/ai-sdk-package-efforts.const.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/constants/ai-sdk-package-efforts.const.ts
index c69a31a76cc..9914693d1cc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/constants/ai-sdk-package-efforts.const.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/constants/ai-sdk-package-efforts.const.ts
@@ -31,10 +31,7 @@ type XaiEffort = NonNullable<
XaiLanguageModelResponsesOptions['reasoningEffort']
>;
-// What each SDK package can put on the wire, pinned to the SDK's own option
-// type where it has one; the OpenAI Responses model types it as a plain string.
-// A model's catalog entry lists what the model takes; only the intersection is
-// offered, so a level the SDK would reject is never forwarded.
+// intersected with each model's catalog efforts so a level the SDK would reject is never forwarded
export const AI_SDK_PACKAGE_EFFORTS: Partial<
Record<AiSdkPackage, readonly AiModelEffort[]>
> = {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service.ts
index 1ac5ef5923f..d5684399aea 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-preferences.service.ts
@@ -40,8 +40,7 @@ export class AiModelPreferencesService {
);
}
- // The chosen model moves to the front of the chain; the rest of the chain is
- // kept so an instance losing that provider's key still resolves the tier.
+ // the chosen model moves to the front; the rest of the chain stays so losing that provider's key still resolves the tier
async setDefaultModel(tier: AiModelTier, modelId: string): Promise<void> {
const current = this.getDefaultModelIdsForTier(tier);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts
index 677f4b15a21..351529fb053 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts
@@ -79,15 +79,12 @@ export class AiModelRegistryService {
private readonly logger = new Logger(AiModelRegistryService.name);
private modelRegistry: Map<string, RegisteredAiModel> = new Map();
private modelConfigCache: Map<string, AiModelConfig> = new Map();
- // Kept out of modelRegistry and modelConfigCache so transcription models can
- // never surface in the chat model picker or reach token costing.
+ // separate so transcription models never reach the chat picker or token costing
private transcriptionRegistry: Map<string, RegisteredAiTranscriptionModel> =
new Map();
private transcriptionConfigCache: Map<string, AiTranscriptionModelConfig> =
new Map();
- // Kept apart for the same reason as transcription: an evaluation model has no
- // context window and cannot answer a chat turn, so it must never surface in
- // the model picker or reach language-model costing.
+ // separate for the same reason: evaluation models cannot answer a chat turn
private evaluationRegistry: Map<string, RegisteredAiEvaluationModel> =
new Map();
private evaluationConfigCache: Map<string, AiEvaluationModelConfig> =
@@ -107,12 +104,8 @@ export class AiModelRegistryService {
private readonly customAiProviderAccessService: CustomAiProviderAccessService,
) {}
- // The registry is rebuilt lazily whenever the LLM-group config hash changes,
- // so any mutation to an LLM-tagged config variable is picked up automatically
- // on the next read — no explicit refresh from callers needed. Seats are not
- // part of that hash, so the custom-provider entitlement is compared alongside
- // it: an instance that grows past the threshold loses its custom models on the
- // next read rather than waiting for an unrelated config change.
+ // rebuilt lazily when the LLM config hash changes; seats are not in that hash, so the custom-provider entitlement
+ // is compared too and an instance past the threshold loses its custom models on the next read
private ensureFresh(): void {
const configHash = this.configGroupHashService.computeHash(
ConfigVariablesGroup.LLM,
@@ -223,8 +216,7 @@ export class AiModelRegistryService {
}
private registerSupportedVariants(): void {
- // The client catalog must resolve every selectable effort before a pin is
- // saved, not only variants that have already been used by the server.
+ // the client must resolve every selectable effort before a pin is saved
for (const modelConfig of Array.from(this.modelConfigCache.values())) {
for (const effort of getAvailableEfforts(modelConfig)) {
this.registerVariant(`${modelConfig.modelId}@${effort}`);
@@ -232,8 +224,6 @@ export class AiModelRegistryService {
}
}
- // Any effort the catalog declares for a model is reachable by id, whether it
- // sits in a chain, a workspace pin or an agent. An undeclared one never is.
private registerVariant(variantId: string): void {
const variant = this.resolveConfiguredVariant(variantId);
@@ -248,8 +238,7 @@ export class AiModelRegistryService {
modelId: variantId,
label: `${baseConfig.label} (${AI_MODEL_EFFORT_LABELS[effort]})`,
effort,
- // A reading describes the effort it was taken at, so the variant gets
- // the one taken at its effort or none, never the base model's ceiling.
+ // a reading is only valid at its own effort, never inherit the base model's
benchmark: baseConfig.benchmarkByEffort?.[effort],
});
@@ -309,8 +298,7 @@ export class AiModelRegistryService {
modelDef: AiProviderModelConfig;
sdkInstance: AiSdkProviderInstance | undefined;
}): void {
- // An omitted price bills nothing while the provider still charges, so the
- // model is refused rather than run for free. An explicit 0 is allowed.
+ // an omitted price would bill nothing while the provider charges; an explicit 0 is allowed
if (!isDefined(modelDef.costPerMinute)) {
this.logger.error(
`Skipping transcription model "${compositeId}": costPerMinute is required`,
@@ -366,8 +354,6 @@ export class AiModelRegistryService {
return Array.from(this.transcriptionRegistry.values());
}
- // Registration order follows the provider config, so the first entry is the
- // one an operator listed first.
getDefaultTranscriptionModel(): RegisteredAiTranscriptionModel | undefined {
return this.getAvailableTranscriptionModels().find(
(model) =>
@@ -383,9 +369,7 @@ export class AiModelRegistryService {
return this.transcriptionConfigCache.get(modelId);
}
- // Deliberately the same rule as getDefaultTranscriptionModel: a registry
- // holding only deprecated models would otherwise advertise cloud dictation
- // that every request without an explicit model id then fails to resolve.
+ // same rule as getDefaultTranscriptionModel, or a deprecated-only registry would advertise unresolvable dictation
hasTranscriptionModel(): boolean {
return isDefined(this.getDefaultTranscriptionModel());
}
@@ -405,9 +389,8 @@ export class AiModelRegistryService {
}): void {
const { supportedQuestionTypes } = modelDef;
- // The schema already requires these, but a custom provider merged in at
- // runtime reaches here too, and a model with no declared question types
- // would accept every node and fail at the provider instead.
+ // custom providers merged at runtime bypass the schema, and a model without question types would accept
+ // every node and fail at the provider
if (!isNonEmptyArray(supportedQuestionTypes)) {
this.logger.error(
`Skipping evaluation model "${compositeId}": supportedQuestionTypes is required`,
@@ -471,11 +454,8 @@ export class AiModelRegistryService {
return Array.from(this.evaluationRegistry.values());
}
- // Registration order follows the provider config, so the first entry is the
- // one an operator listed first. Admin-disabled models are skipped the way
- // getFirstAvailableModelFromList skips them for language tiers: withdrawing
- // the only evaluation model has to send unpinned steps to the language
- // fallback, not keep running them on the model that was withdrawn.
+ // first in provider config order; skips admin-disabled models so withdrawing the only one sends unpinned
+ // steps to the language fallback
getDefaultEvaluationModel(): RegisteredAiEvaluationModel | undefined {
return this.getAvailableEvaluationModels().find(
(model) =>
@@ -515,8 +495,7 @@ export class AiModelRegistryService {
modelFamily:
modelDef.modelFamily ??
inferModelFamily(providerConfig.name ?? '', modelDef.name),
- // The provider value is only a fallback: one Bedrock provider serves both
- // eu.* and global.* models, which do not route to the same place.
+ // one Bedrock provider serves both eu.* and global.* models, so the model value wins
dataResidency: modelDef.dataResidency ?? providerConfig.dataResidency,
zeroDataRetention: modelDef.zeroDataRetention,
inputCostPerMillionTokens: modelDef.inputCostPerMillionTokens ?? 0,
@@ -576,12 +555,7 @@ export class AiModelRegistryService {
return undefined;
}
- // A rung whose chain names nothing available borrows the nearest rung's
- // chain, so an instance with two models lands on the neighbouring tier
- // rather than on whatever the catalog happens to list first. The last
- // resort is any model the admin still allows, a current one before a
- // deprecated one: a chain that names only disabled models must not hand a
- // disabled one to the client.
+ // borrow the nearest tier's chain before falling back to any allowed model, never a disabled one
findDefaultModelForTier(tier: AiModelTier): RegisteredAiModel | undefined {
for (const candidateTier of getAiModelTiersByDistance(tier)) {
const model = this.getFirstAvailableModelFromList(
@@ -615,9 +589,7 @@ export class AiModelRegistryService {
return model;
}
- // A pin only applies while the pinned model still resolves and is not
- // disabled, so a workspace never loses a tier because a provider key went
- // away or an admin disabled the model after it was pinned.
+ // a pin applies only while its model resolves and is enabled, so a tier never goes dark
private resolveModelForTier(
tier: AiModelTier,
workspaceSettings?: WorkspaceAiModelSettings,
@@ -691,9 +663,7 @@ export class AiModelRegistryService {
);
}
- // A model that disappeared because the instance outgrew the complimentary
- // threshold looks exactly like a typo from the caller's side, so the reason is
- // spelled out rather than leaving an operator to guess at a missing model.
+ // a model dropped past the complimentary threshold would otherwise look like a typo
private buildModelNotFoundMessage(modelId: string): string {
const message = `Model with ID ${modelId} not found`;
@@ -746,9 +716,7 @@ export class AiModelRegistryService {
);
}
- // Catalog membership rather than registration: an instance can name a
- // model before it holds the provider key, and a key added later makes the
- // stored id work without touching the agent.
+ // catalog membership, not registration: a provider key added later makes the stored id work
validateModelAvailability(modelId: string): void {
if (!this.isModelAdminAllowed(modelId)) {
throw new AiException(
@@ -800,9 +768,7 @@ export class AiModelRegistryService {
});
}
- // Evaluation models are cached apart from language models so nothing that
- // resolves a chat or an agent can reach them, which also keeps them out of
- // getAllModelsWithStatus. The admin panel lists both, so it asks separately.
+ // evaluation models are cached apart, so the admin panel asks for them separately
getAllEvaluationModelsWithStatus(): Array<{
modelConfig: AiEvaluationModelConfig;
isAvailable: boolean;
@@ -853,8 +819,7 @@ export class AiModelRegistryService {
}
}
- // Enabling and disabling reaches every kind, unlike a tier default, which
- // only a language model can serve.
+ // covers every model kind, unlike tier defaults which only language models serve
private validateModelIsKnown(modelId: string): void {
this.ensureFresh();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service.ts
index f96a2f02e65..1586469cc62 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/default-ai-catalog.service.ts
@@ -47,9 +47,7 @@ export class DefaultAiCatalogService implements OnModuleInit {
this.reportSkippedEntries(catalogPath, skipped);
}
- // A stored catalog carries the credentials, labels and prices of one
- // deployment, not the efforts and benchmarks the sync measures, so it
- // lists the models and the built-in catalog describes the ones it knows.
+ // stored catalogs lack the efforts and benchmarks the sync measures, so inherit them from the built-in one
this.catalog = inheritCatalogReadings({
catalog: this.builtInCatalog,
providers: normalizeAiProviders(providers),
@@ -60,9 +58,7 @@ export class DefaultAiCatalogService implements OnModuleInit {
this.logger.error(`Failed to load AI catalog from storage: ${message}`);
this.exceptionHandlerService.captureExceptions([error]);
- // The stored catalog lists exactly the routes this deployment serves,
- // while the built-in one can name routes it must not, such as ones
- // outside its data residency, so an unreadable file serves nothing.
+ // serve nothing rather than the built-in catalog, which may name routes this deployment must not serve (data residency)
this.catalog = {};
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.ts
index f3ff86f1b72..82f15fcf71d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/provider-config.service.ts
@@ -26,12 +26,10 @@ export class ProviderConfigService {
includeCustomProviders = true,
}: { includeCustomProviders?: boolean } = {}): AiProvidersConfig {
const rawCatalog = this.defaultAiCatalogService.getDefaultAiCatalog();
- // Only resolve {{VAR}} templates in the committed catalog — never in
- // user-supplied custom providers, to prevent config variable exfiltration.
+ // never resolve {{VAR}} templates in custom providers, to prevent config variable exfiltration
const catalog = this.resolveTemplates(rawCatalog);
- // Dropping the custom entries rather than filtering the merged map also
- // restores a catalog provider that a custom entry of the same name shadows.
+ // dropping custom entries, rather than filtering the merged map, also restores catalog providers a same-named custom entry shadowed
if (!includeCustomProviders) {
return catalog;
}
@@ -73,9 +71,7 @@ export class ProviderConfigService {
return value;
}
- // Registered config variables first (supports admin panel / DB overrides),
- // then fall back to process.env for vars not in ConfigVariables
- // (e.g. when CI replaces the catalog with custom provider entries).
+ // falls back to process.env for vars outside ConfigVariables (e.g. CI-replaced catalogs)
try {
const resolved = this.twentyConfigService.get(
varName as keyof ConfigVariables,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/sdk-provider-factory.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/sdk-provider-factory.service.ts
index 935b5171a21..67e26c76dc6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/sdk-provider-factory.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/sdk-provider-factory.service.ts
@@ -37,12 +37,8 @@ import { getEvaluationModelFactory } from 'src/engine/metadata-modules/ai/ai-mod
import { getTranscriptionModelFactory } from 'src/engine/metadata-modules/ai/ai-models/utils/get-transcription-model-factory.util';
export type AiSdkProviderInstance = {
- // Absent on providers that serve no language model at all, such as an
- // evaluation-only provider.
createModel?: (modelId: string) => LanguageModel;
- // Absent on providers with no speech-to-text API.
createTranscriptionModel?: (modelId: string) => TranscriptionModel;
- // Absent on providers with no evaluation API.
createEvaluationModel?: (modelId: string) => AiEvaluationModel;
rawProvider: unknown;
sdkPackage: AiSdkPackage;
@@ -236,8 +232,7 @@ export class SdkProviderFactoryService {
);
}
- // Evaluation-only: the provider serves no language model, so the instance
- // carries no createModel and the registry skips its models for chat.
+ // evaluation-only provider: no createModel, so the registry skips it for chat
private buildTypeSafeAiProvider(
config: AiProviderConfig,
): AiSdkProviderInstance {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model-config.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model-config.type.ts
index 51c90351921..3a7c3067c48 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model-config.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model-config.type.ts
@@ -4,13 +4,9 @@ import {
type DataResidency,
} from 'twenty-shared/ai';
-// Evaluation models answer typed questions instead of emitting text, so they
-// carry no context window, no max output and no effort ladder. They are billed
-// on input tokens like a language model, which is why the cost fields match.
+// billed on tokens like a language model, hence the matching cost fields
export type AiEvaluationModelConfig = {
modelId: string;
- // The provider key and the bare SDK model name the composite id is built
- // from, kept here so a reader does not have to split the id back apart.
providerName: string;
name: string;
sdkPackage: AiSdkPackage;
@@ -19,11 +15,7 @@ export type AiEvaluationModelConfig = {
inputCostPerMillionTokens: number;
outputCostPerMillionTokens: number;
supportedQuestionTypes: AiEvaluationQuestionType[];
- // Providers cap how many options one choice question may carry; a node that
- // exceeds it is rejected before any network call.
maxCriteriaPerQuestion?: number;
- // A score rubric is capped far lower than a choice menu, so it is declared
- // separately rather than sharing the option cap.
maxScoreLevels?: number;
medianLatencyMs?: number;
dataResidency?: DataResidency;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model.type.ts
index 7dbf5e1eaff..9470449f657 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model.type.ts
@@ -4,22 +4,17 @@ import {
type Experimental_EvaluationQuestion,
} from 'ai';
-// Local names for the AI SDK's evaluation spec. These are aliases, not a
-// restatement: the SDK owns the shape, so a spec change breaks the build here
-// instead of drifting silently. The prefix the SDK uses while the API is
-// experimental is kept out of the engine's own code.
+// aliases, not copies: an SDK spec change breaks the build here; they keep the experimental prefix out of engine code
export type AiEvaluationModel = Experimental_EvaluationModel;
export type AiEvaluationModelQuestion = Experimental_EvaluationQuestion;
-// Distributes over the question union, so this is the union of every answer
-// shape rather than one of them.
+// distributes over the question union, so this is every answer shape, not one
export type AiEvaluationModelAnswer =
Experimental_EvaluationAnswer<Experimental_EvaluationQuestion>;
-// The SDK exports the call and result shapes only through the model, so they
-// are read back off it.
+// the SDK only exports these through the model
export type AiEvaluationModelCallOptions = Parameters<
AiEvaluationModel['doEvaluate']
>[0];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema.ts
index 992320cf69b..47b2728aba3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema.ts
@@ -2,17 +2,12 @@ import { z } from 'zod';
import { AI_MODEL_EFFORTS } from 'twenty-shared/ai';
-// One publisher's reading of a model, taken on one date. An index is only
-// meaningful against models scored the same way, so whoever fills this must use
-// the same publisher throughout rather than filling gaps from a second. The
-// generated catalog uses Artificial Analysis.
+// indexes are only comparable from one publisher, so never fill gaps from a second (we use Artificial Analysis)
export const aiModelBenchmarkSchema = z.object({
intelligenceIndex: z.number().optional(),
outputTokensPerSecond: z.number().positive().optional(),
costPerTask: z.number().positive().optional(),
- // The publisher scores a model once per reasoning effort, so a reading is
- // only comparable with others taken at the same effort. Unset when the
- // publisher's row names none.
+ // readings are only comparable at the same effort
effort: z.enum(AI_MODEL_EFFORTS).optional(),
measuredAt: z.string().date(),
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts
index 92077d86c75..3fa4be4b444 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts
@@ -8,7 +8,7 @@ import { type LongContextCost } from 'src/engine/metadata-modules/ai/ai-models/t
import { type ModelFamily } from 'src/engine/metadata-modules/ai/ai-models/types/model-family.enum';
export type AiModelConfig = {
- // Composite model id (`provider/modelName`) used in the registry and GraphQL; same shape as SDK routing when applicable.
+ // `provider/modelName`
modelId: string;
sdkPackage: AiSdkPackage;
label: string;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-cost-config.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-cost-config.type.ts
index 1d40c625709..3c23987edee 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-cost-config.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-cost-config.type.ts
@@ -1,8 +1,6 @@
import { type LongContextCost } from 'src/engine/metadata-modules/ai/ai-models/types/long-context-cost.type';
import { type ModelFamily } from 'src/engine/metadata-modules/ai/ai-models/types/model-family.enum';
-// What costing needs from a model, whatever kind it is. Both AiModelConfig and
-// AiEvaluationModelConfig satisfy it, so token billing has one implementation.
export type AiModelCostConfig = {
modelId: string;
modelFamily?: ModelFamily;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-tier.enum.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-tier.enum.ts
index bbf3dfbe5cb..ab9cd62474a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-tier.enum.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-tier.enum.ts
@@ -2,8 +2,7 @@ import { registerEnumType } from '@nestjs/graphql';
import { type AiModelTier as SharedAiModelTier } from 'twenty-shared/ai';
-// GraphQL needs a runtime enum. Keys equal values so the GraphQL names are the
-// twenty-shared tier literals and the client can use one type on both sides.
+// GraphQL needs a runtime enum; keys equal values so GraphQL names match the twenty-shared tier literals
export enum AiModelTier {
extraFast = 'extraFast',
fast = 'fast',
@@ -14,7 +13,6 @@ export enum AiModelTier {
registerEnumType(AiModelTier, { name: 'AiModelTier' });
-// The enum object itself must satisfy the shared record, so a tier added on
-// one side without the other fails to compile.
+// fails to compile when a tier is added on only one side
const _assertTierValuesMatchShared: Record<SharedAiModelTier, AiModelTier> =
AiModelTier;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts
index 545b978be5d..360179f890a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts
@@ -29,22 +29,15 @@ export const aiProviderModelConfigSchema = z
maxOutputTokens: z.number().int().positive().optional(),
modalities: z.array(z.string()).optional(),
supportsReasoning: z.boolean().optional(),
- // In the provider's own vocabulary; a model without a list runs at the
- // provider default only.
+ // unset means the provider default only
efforts: z.array(z.enum(AI_MODEL_EFFORTS)).nonempty().optional(),
- // Contractual per route rather than published anywhere, so an operator
- // declares them and undefined means unasserted, not false. One Bedrock
- // provider serves both eu.* and global.* models, hence per model.
+ // contractual per route, so undefined means unasserted rather than false; per model since one Bedrock provider serves eu.* and global.*
dataResidency: z.enum(DATA_RESIDENCY_KEYS).optional(),
zeroDataRetention: z.boolean().optional(),
benchmark: aiModelBenchmarkSchema.optional(),
- // Keyed by effort so a pinned variant carries the reading taken at its own
- // effort instead of the base model's ceiling.
benchmarkByEffort: z
.partialRecord(z.enum(AI_MODEL_EFFORTS), aiModelBenchmarkSchema)
.optional(),
- // Evaluation models only. A question type the provider cannot answer is
- // rejected before any I/O rather than failing mid-run.
supportedQuestionTypes: z
.array(z.enum(AI_EVALUATION_QUESTION_TYPES))
.nonempty()
@@ -58,8 +51,7 @@ export const aiProviderModelConfigSchema = z
(model) =>
model.kind !== 'transcription' || model.costPerMinute !== undefined,
{
- // An omitted price bills nothing while the provider still charges, so a
- // free model has to say so with an explicit 0.
+ // an omitted price bills nothing while the provider still charges, so a free model states 0
message: 'costPerMinute is required for transcription models',
path: ['costPerMinute'],
},
@@ -76,8 +68,6 @@ export const aiProviderModelConfigSchema = z
(model) =>
model.kind === 'evaluation' || model.supportedQuestionTypes === undefined,
{
- // Declared on a language model it would advertise a capability nothing
- // reads, and the model would never reach the evaluation registry.
message: 'supportedQuestionTypes is only valid on evaluation models',
path: ['supportedQuestionTypes'],
},
@@ -88,17 +78,14 @@ export const aiProviderModelConfigSchema = z
(model.inputCostPerMillionTokens !== undefined &&
model.outputCostPerMillionTokens !== undefined),
{
- // Same rule as transcription: an omitted price bills nothing while the
- // provider still charges. Jev's free output has to say so with a 0.
+ // same rule as transcription models: an omitted price bills nothing, so free output states 0
message:
'inputCostPerMillionTokens and outputCostPerMillionTokens are required for evaluation models',
path: ['inputCostPerMillionTokens'],
},
)
.superRefine((model, context) => {
- // A variant reads this map by its own effort, so a reading filed under
- // another effort's key, or under an effort no variant can pin, would hand
- // it a figure measured elsewhere.
+ // a variant reads this map by its own effort, so a misfiled reading would hand it a foreign figure
for (const [effort, reading] of Object.entries(
model.benchmarkByEffort ?? {},
)) {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts
index 745e40de43d..352422430cc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts
@@ -1,7 +1,6 @@
import { type AiSdkPackage, type DataResidency } from 'twenty-shared/ai';
-// Separate from AiModelConfig so computeCostBreakdown is never reachable with a
-// model that has no token semantics.
+// separate so computeCostBreakdown never sees a model without token semantics
export type AiTranscriptionModelConfig = {
modelId: string;
sdkPackage: AiSdkPackage;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts
index d8e921d72d2..8732b045337 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts
@@ -1,15 +1,12 @@
import { type ModelsDevCost } from './models-dev-cost.type';
export type ModelsDevModel = {
- // Model id as returned by models.dev (may match the record key in `ModelsDevProvider.models`).
id: string;
name: string;
family?: string;
status?: 'deprecated' | 'beta';
reasoning?: boolean;
tool_call?: boolean;
- // Providers that price long context separately nest a second set of rates
- // under `context_over_200k`, in the same shape.
cost?: ModelsDevCost & { context_over_200k?: ModelsDevCost };
limit?: { context?: number; output?: number };
modalities?: { input?: string[]; output?: string[] };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/workspace-ai-model-settings.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/workspace-ai-model-settings.type.ts
index 578febf202f..e305b38dc54 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/workspace-ai-model-settings.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/workspace-ai-model-settings.type.ts
@@ -1,7 +1,5 @@
import { type AiModelTier } from 'twenty-shared/ai';
-// The subset of a workspace that decides which concrete model a tier resolves
-// to. Pins are ignored while automatic selection is on.
export type WorkspaceAiModelSettings = {
isAutoModelSelectionEnabled: boolean;
aiModelIdByTier: Partial<Record<AiModelTier, string>>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/build-ai-telemetry.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/build-ai-telemetry.util.ts
index 2c2f521e6a0..cda0a56a3d6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/build-ai-telemetry.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/build-ai-telemetry.util.ts
@@ -18,8 +18,7 @@ type AiTelemetryCallOptions = {
runtimeContext: Record<string, string>;
};
-// Identifiers travel as runtime context and are opted into telemetry one by
-// one, which is how a telemetry integration receives per-call attributes.
+// telemetry integrations only receive per-call attributes opted in from runtime context
export const buildAiTelemetry = ({
functionId,
...identifiers
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-ai-model-tiers-by-distance.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-ai-model-tiers-by-distance.util.ts
index 52f21d90d73..2abfe143bb5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-ai-model-tiers-by-distance.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-ai-model-tiers-by-distance.util.ts
@@ -1,8 +1,6 @@
import { AI_MODEL_TIERS, type AiModelTier } from 'twenty-shared/ai';
-// The tier itself first, then its neighbours by distance, the lower rung
-// before the higher one at equal distance so a missing rung borrows the
-// cheaper side of the ladder.
+// lower rung first at equal distance so a missing rung borrows the cheaper side
export const getAiModelTiersByDistance = (tier: AiModelTier): AiModelTier[] => {
const tierIndex = AI_MODEL_TIERS.indexOf(tier);
const distanceOf = (candidate: AiModelTier) =>
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util.ts
index 7da5aabeffa..ab01dba5f3b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util.ts
@@ -2,7 +2,6 @@ import { AUTO_SELECT_MODEL_ID_BY_TIER } from 'twenty-shared/ai';
import { type WorkspaceAiModelSettings } from 'src/engine/metadata-modules/ai/ai-models/types/workspace-ai-model-settings.type';
-// A chat turn that names no model runs on the workspace chat tier.
export const getChatModelId = ({
requestedModelId,
workspace,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-evaluation-model-factory.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-evaluation-model-factory.util.ts
index d61148e0ed0..851625d16f6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-evaluation-model-factory.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/get-evaluation-model-factory.util.ts
@@ -4,9 +4,7 @@ type EvaluationCapableProvider = {
evaluationModel: (modelId: string) => AiEvaluationModel;
};
-// Duck-typed rather than keyed by npm package: any provider exposing the SDK's
-// evaluation factory qualifies, so a gateway proxying several evaluation models
-// needs no entry here.
+// duck-typed so a gateway proxying evaluation models needs no entry here
const hasEvaluationFactory = (
provider: unknown,
): provider is EvaluationCapableProvider =>
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/load-default-model-preferences.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/load-default-model-preferences.util.ts
index 29560c9f264..cc1f735b0e5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/load-default-model-preferences.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/load-default-model-preferences.util.ts
@@ -1,15 +1,8 @@
-// TODO: derive default model preferences dynamically from the catalog
-// instead of hardcoding model IDs that become stale as models evolve
-//
-// Each tier is resolved by taking the first model that is actually available,
-// meaning the one whose provider the instance holds a key for. A chain is
-// therefore a preference order across providers, not a shortlist: every
-// supported provider needs an entry, or an instance configured with only that
-// provider resolves the tier to nothing.
+// TODO: derive default model preferences from the catalog instead of hardcoding ids
+// each tier takes the first model whose provider has a key, so every supported provider needs an entry or a single-provider instance resolves the tier to nothing
import { type AiModelTier } from 'twenty-shared/ai';
-// Efforts are pinned so a tier runs at the effort its benchmark was measured
-// at, and so one model family can back neighbouring tiers at different speeds.
+// efforts match the benchmarked effort and let one family back neighbouring tiers
export const DEFAULT_MODELS_BY_TIER: Record<AiModelTier, string[]> = {
extraFast: [
'openai/gpt-5.6-luna@low',
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/merge-custom-providers-into-catalog.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/merge-custom-providers-into-catalog.util.ts
index e4cb18f4d7f..1f58a126de2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/merge-custom-providers-into-catalog.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/merge-custom-providers-into-catalog.util.ts
@@ -4,8 +4,7 @@ import { type AiProviderConfig } from 'src/engine/metadata-modules/ai/ai-models/
import { type AiProviderModelConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.type';
import { type AiProvidersConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-providers-config.type';
-// A custom reading completes the catalog's rather than replacing it, so one
-// effort or one metric set by hand keeps the others the sync measured.
+// a hand-set effort or metric keeps the others the sync measured
const mergeDefined = <TValue extends Record<string, unknown>>({
catalogValue,
customValue,
@@ -17,19 +16,14 @@ const mergeDefined = <TValue extends Record<string, unknown>>({
? { ...catalogValue, ...customValue }
: (customValue ?? catalogValue);
-// Publishers and routes spell one model differently (`claude-haiku-4-5`,
-// `claude_haiku_4.5`, `claude-haiku-4-5-v1:0`), so names are compared with
-// separators and a trailing deployment version dropped.
+// publishers and routes spell one model differently: `claude-haiku-4-5`, `claude_haiku_4.5`, `claude-haiku-4-5-v1:0`
const normalizeModelName = (modelName: string): string =>
modelName
.toLowerCase()
.replace(/-v\d+(?::\d+)?$/, '')
.replace(/[\s.\-_]/g, '');
-// Bedrock and Azure prefix a model with the region and vendor that serve it
-// (`eu.anthropic.claude-opus-4-7`). Dropping leading dot-separated segments
-// one at a time lets a route fall back to the model it serves, while a name
-// such as `gpt-4.1` still matches itself first.
+// Bedrock and Azure prefix region and vendor (`eu.anthropic.claude-opus-4-7`), yet `gpt-4.1` must match itself first
const routeCandidates = (modelName: string): string[] => {
const segments = modelName.split('.');
@@ -75,10 +69,7 @@ const mergeModels = ({
: customModel;
});
-// A provider the catalog does not know (a gateway, Bedrock, Azure) serves
-// models the catalog does know under another route. Its prices are its own,
-// so only what describes the model itself carries over: the efforts it takes
-// and the readings measured for it.
+// a route's prices are its own, so only efforts and readings carry over from the catalog model
const withReadingsFromAnyProvider = ({
catalog,
customModels,
@@ -107,10 +98,7 @@ const withReadingsFromAnyProvider = ({
});
};
-// A provider written before the catalog carried efforts and benchmarks would
-// strip both from every model it lists, and the tier chains could no longer
-// name an effort on it. A model the catalog knows keeps the catalog fields the
-// entry does not set itself; the entry still decides which models exist.
+// providers written before the catalog carried efforts and benchmarks would otherwise strip them
export const inheritCatalogReadings = ({
catalog,
providers,
@@ -145,8 +133,6 @@ export const inheritCatalogReadings = ({
return result;
};
-// A custom entry replaces the catalog provider of the same name; providers it
-// does not name stay as the catalog has them.
export const mergeCustomProvidersIntoCatalog = ({
catalog,
custom,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/parse-stored-ai-catalog.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/parse-stored-ai-catalog.util.ts
index a338447455b..0be60d20524 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/parse-stored-ai-catalog.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/utils/parse-stored-ai-catalog.util.ts
@@ -14,7 +14,7 @@ export type SkippedStoredAiCatalogEntry = {
const storedCatalogSchema = z.record(z.string(), z.unknown());
-// Models are read one by one below, so a provider is read without them first.
+// the provider is read without its models, which are validated one by one below
const storedProviderSchema = aiProviderConfigSchema.extend({
models: z.array(z.unknown()).optional(),
});
@@ -46,9 +46,7 @@ const describeModelEntry = ({
: `${providerKey}.models[${index}]`;
};
-// The stored catalog ships with every deploy and can be newer than the server
-// reading it, so an entry this version cannot read is dropped on its own
-// rather than taking every other provider down with it.
+// the stored catalog can be newer than this server, so unreadable entries are dropped individually
export const parseStoredAiCatalog = (
raw: unknown,
): {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts
index d224bae56e0..b92e1b95b5c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/ai-tool-call-answer.module.ts
@@ -14,8 +14,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workflow-runner.module';
-// Answering a paused call can resume a chat or a workflow run, so this sits
-// above both.
+// sits above chat and workflow since an answer can resume either
@Module({
imports: [
AgentHistoryModule,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto.ts
index 031a80503c8..6dd0b99eecd 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/dtos/answer-tool-call-result.dto.ts
@@ -2,8 +2,7 @@ import { Field, ObjectType } from '@nestjs/graphql';
@ObjectType('AnswerToolCallResult')
export class AnswerToolCallResultDTO {
- // Only a chat conversation resumes as a stream, once its last call is
- // answered; a workflow run resumes in its own executor.
+ // set only when a chat's last pending call is answered; workflow runs resume in their own executor
@Field(() => String, { nullable: true })
streamId: string | null;
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver.ts
index 3ba953837d2..26fec40acd0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/resolvers/tool-call-answer.resolver.ts
@@ -28,9 +28,7 @@ import { AnswerToolCallInput } from 'src/engine/metadata-modules/ai/ai-tool-call
import { ToolCallAnswerService } from 'src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service';
import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
-// Served on /graphql: the permission an answer needs depends on whether the
-// call waits in a chat or in a workflow run, so it is checked per call rather
-// than by a class guard.
+// permission depends on whether the call waits in a chat or a workflow run, so no class guard
@CoreResolver()
@UsePipes(ResolverValidationPipe)
@UseGuards(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
index b11732bbea2..e91d8a02727 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-tool-call-answer/services/tool-call-answer.service.ts
@@ -55,11 +55,7 @@ type AnswerToolCallOutcome = {
turnId: string | null;
};
-// Every pause for a person is a pausing tool call in a conversation, a chat or
-// a workflow run's, and each is answered here. An answer takes the
-// conversation's stream claim, and only while the conversation still waits on
-// the message that paused, so each call is answered once and only the last
-// answer resumes what waits on them.
+// an answer takes the stream claim only while the conversation still waits, so each call is answered once
@Injectable()
export class ToolCallAnswerService {
constructor(
@@ -223,8 +219,7 @@ export class ToolCallAnswerService {
throw error;
}
- // The answer is recorded and cannot be given again, so from here a
- // failure fails the turn or the run, which can then be retried.
+ // the answer is recorded and cannot be resubmitted, so failures fail the turn or run for retry
try {
const answerMessage = await this.agentChatService.addMessage({
threadId,
@@ -238,8 +233,7 @@ export class ToolCallAnswerService {
await this.publishToolCallResolved({ threadId, toolCallId, workspaceId });
- // A run resumes in its own executor, and a conversation still waiting
- // on other calls resumes with the last of their answers.
+ // runs resume in their own executor, and only the last answer resumes a chat
if (isDefined(step) || !isLastAnswer) {
await this.agentChatStreamingService.releaseStreamClaim(
threadId,
@@ -371,8 +365,6 @@ export class ToolCallAnswerService {
});
}
- // The same permission that lets someone run a workflow, on a run they can
- // read.
private async assertCanAnswerForWorkflowRun({
userWorkspaceId,
workspaceId,
@@ -413,8 +405,6 @@ export class ToolCallAnswerService {
}
}
- // Built only when a pausing tool runs another tool, and as the person who
- // answered: their role and connected accounts decide what it may do.
private buildCompletionContext({
workspaceId,
userWorkspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-workspace-stats/services/ai-workspace-stats.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-workspace-stats/services/ai-workspace-stats.service.ts
index a03f617b924..3c0b0002c5f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-workspace-stats/services/ai-workspace-stats.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-workspace-stats/services/ai-workspace-stats.service.ts
@@ -28,9 +28,7 @@ export class AiWorkspaceStatsService {
workspaceId,
flatMapsKeys: ['flatSkillMaps'],
}),
- // Count the full tool catalog the user can see (built-in tools + custom
- // logic-function tools), matching the Tools tab rather than only the
- // custom subset. The catalog is role-scoped, like the tab.
+ // the full role-scoped catalog, to match the Tools tab
this.toolRegistryService.buildToolIndex(workspaceId, roleId),
]);
diff --git a/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/services/application-translation-catalog.service.ts b/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/services/application-translation-catalog.service.ts
index 4855431e157..1088e144c2f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/services/application-translation-catalog.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/services/application-translation-catalog.service.ts
@@ -72,8 +72,6 @@ export class ApplicationTranslationCatalogService {
};
}
- // Batched on purpose: one flat-maps read and one fetch per distinct
- // application, however many entities the caller is resolving.
async getCatalogs({
applicationIds,
locale,
@@ -129,10 +127,7 @@ export class ApplicationTranslationCatalogService {
return { standardApplicationId, catalogByApplicationId };
}
- // The single-entity context. GraphQL resolves labels in per-entity
- // ResolveFields, so it passes its request dataloaders to coalesce the N
- // calls one page produces; REST resolves a whole page in one call and has
- // nothing to coalesce, so it passes none. Same resolution either way.
+ // GraphQL passes dataloaders to coalesce per-entity ResolveFields; REST resolves a page at once and passes none
async buildEffectiveEntityI18nContext({
applicationId,
loaders,
@@ -209,8 +204,6 @@ export class ApplicationTranslationCatalogService {
});
}
- // The one place the context shape is built, so the loader-backed and
- // batched sources cannot drift apart.
private toI18nContextResolver({
applicationAuthorIdentifiers: {
standardApplicationId,
@@ -242,9 +235,6 @@ export class ApplicationTranslationCatalogService {
});
}
- // The common case: merge every resolved translatable property back onto the
- // entity it came from. Callers that present several metadata names in one
- // payload use getI18nContextByApplicationId directly instead.
async resolveTranslatablePropertiesForEntities<
TEntity extends { applicationId?: string | null },
>({
diff --git a/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-registration-id-by-application-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-registration-id-by-application-id.util.ts
index a7359a38122..9d68405560c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-registration-id-by-application-id.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-registration-id-by-application-id.util.ts
@@ -7,8 +7,7 @@ type ApplicationRegistrationLookup = {
>;
};
-// The standard application is skipped: its strings live in the server's own
-// lingui catalog, not in applicationTranslation.
+// skips the standard application, whose strings live in the server's lingui catalog
export const resolveRegistrationIdByApplicationId = ({
applicationIds,
flatApplicationMaps,
diff --git a/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-translatable-properties.util.ts b/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-translatable-properties.util.ts
index 35c05e640dc..4b3c9081dd9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-translatable-properties.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/application-translation-catalog/utils/resolve-translatable-properties.util.ts
@@ -11,9 +11,7 @@ export const resolveTranslatableProperties = ({
i18nContext,
}: {
metadataName: TranslatableMetadataName;
- // The registry decides which properties to read, so the entity is indexed by
- // name: callers range from TypeORM classes to plain DTOs, some without an
- // overrides column at all.
+ // indexed by registry property name: callers range from TypeORM classes to plain DTOs, some without an overrides column
entity: Record<string, unknown>;
i18nContext: EffectiveEntityI18nContext;
}): Record<string, string> =>
diff --git a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.ts
index 3e6666cb12c..f4200864528 100644
--- a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.resolver.ts
@@ -202,9 +202,7 @@ export class CommandMenuItemResolver {
return await this.commandMenuItemService.delete(id, workspace.id);
}
- // Activating a manual trigger writes a workspace-wide menu item, so the
- // command menu announces a private workflow by name unless the list answers
- // to the same rule as the workflow itself.
+ // manual trigger items are workspace-wide and would otherwise leak private workflow names
private async withoutInaccessibleWorkflowItems({
commandMenuItems,
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts
index cbfb2cfb82a..f6749719eca 100644
--- a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/command-menu-item.service.ts
@@ -493,9 +493,7 @@ export class CommandMenuItemService {
i18nContext,
});
- // shortLabel and icon are nullable columns, and resolveEffectiveEntityProperty
- // answers "what string should this be", flattening an absent value to ''.
- // Handing that straight back would turn every null into an empty string.
+ // resolveEffectiveEntityProperty flattens null to '', which these nullable columns must not get
const resolvedValue = isNonEmptyString(effectiveValue)
? effectiveValue
: undefined;
@@ -519,8 +517,7 @@ export class CommandMenuItemService {
commandMenuItem,
resolvedValue,
objectMetadata,
- // The navigated-to object may belong to a different application than the
- // command menu item pointing at it.
+ // the target object may belong to another application than the item
objectMetadataI18nContext:
await this.applicationTranslationCatalogService.buildEffectiveEntityI18nContext(
{
diff --git a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/dtos/command-menu-item.dto.ts b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/dtos/command-menu-item.dto.ts
index e5a2fccc40c..2fed8e74f9d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/dtos/command-menu-item.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/dtos/command-menu-item.dto.ts
@@ -124,9 +124,7 @@ export class CommandMenuItemDTO {
@HideField()
workspaceId: string;
- // Kept out of the schema but needed by the field resolvers: without it they
- // cannot tell a standard label from one a workspace renamed, and would match
- // the workspace's own copy against the standard catalog.
+ // field resolvers need it to tell a standard label from a workspace-renamed one
@HideField()
overrides?: AuthoredOverrides<CommandMenuItemOverrides> | null;
diff --git a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/utils/interpolate-navigation-command-menu-item-field.util.ts b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/utils/interpolate-navigation-command-menu-item-field.util.ts
index b76ec05087a..86ed1116b79 100644
--- a/packages/twenty-server/src/engine/metadata-modules/command-menu-item/utils/interpolate-navigation-command-menu-item-field.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/command-menu-item/utils/interpolate-navigation-command-menu-item-field.util.ts
@@ -10,10 +10,7 @@ import {
} from 'src/engine/metadata-modules/command-menu-item/utils/build-navigation-placeholder-values.util';
import { type EffectiveEntityI18nContext } from 'src/engine/metadata-modules/overrides/types/effective-entity-i18n-context.type';
-// NAVIGATION items are the only ones whose placeholders the server can fill:
-// they carry their target object as a foreign key. Every other availability
-// type is rendered against whichever object page the user is on, so its
-// placeholders travel untouched and are filled by the client.
+// only NAVIGATION items carry their target object, so the server fills theirs; other placeholders are filled by the client
export const interpolateNavigationCommandMenuItemField = ({
commandMenuItem,
resolvedValue,
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/controllers/field-metadata.controller.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/controllers/field-metadata.controller.ts
index 570efb69f02..d29d21e1da9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/controllers/field-metadata.controller.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/controllers/field-metadata.controller.ts
@@ -92,8 +92,7 @@ export class FieldMetadataController {
private readonly applicationTranslationCatalogService: ApplicationTranslationCatalogService,
) {}
- // REST returns the same labels the app renders: resolved for the caller's
- // locale, through the one resolver the GraphQL read path uses.
+ // same locale-resolved labels as the GraphQL read path
private async toPresentedFieldDtos({
fields,
derivedFieldMetadataIds,
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-filter.input.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-filter.input.ts
index 7258d981c96..76f19d04961 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-filter.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-filter.input.ts
@@ -39,9 +39,7 @@ export const FIELD_FILTER_COLUMN_BY_FILTER_FIELD: Record<
isActive: { column: 'isActive', type: 'boolean' },
isSystem: { column: 'isSystem', type: 'boolean' },
isUIEditable: { column: 'isUIEditable', type: 'boolean' },
- // The legacy isUIReadOnly column is no longer written since the 2.13
- // rename, so the deprecated filter runs inverted against isUIEditable,
- // consistent with how the field itself is resolved.
+ // isUIReadOnly is no longer written since 2.13, so filter inverted on isUIEditable
isUIReadOnly: {
column: 'isUIEditable',
type: 'boolean',
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-metadata.dto.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-metadata.dto.ts
index 7ef03c5c787..ee3ad2c60e4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-metadata.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/dtos/field-metadata.dto.ts
@@ -97,8 +97,7 @@ export class FieldMetadataDTO<T extends FieldMetadataType = FieldMetadataType> {
@Field(() => MetadataWritability, { nullable: true })
writability?: MetadataWritability;
- // Deprecated alias kept for one release: stays exposed (and filterable via
- // FieldFilter) so external API consumers are not broken.
+ // deprecated alias kept for one release so external API consumers do not break
@IsBoolean()
@IsOptional()
@Field({
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.entity.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.entity.ts
index f05aac9f5fb..86b010287de 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.entity.ts
@@ -44,8 +44,7 @@ import { SyncableEntity } from 'src/engine/workspace-manager/types/syncable-enti
import { type AuthoredOverrides } from 'src/engine/metadata-modules/overrides/types/authored-overrides.type';
import { JsonbProperty } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/jsonb-property.type';
-// Reference case for the type tests in types/__tests__/field-metadata-entity.test-type.ts:
-// modifying relations or properties may require updating their expectations for typecheck to pass.
+// changes here may require updating types/__tests__/field-metadata-entity.test-type.ts
@Entity('fieldMetadata')
@Index('IDX_FIELD_METADATA_APPLICATION_ID', ['applicationId'])
@Check(
@@ -165,21 +164,14 @@ export class FieldMetadataEntity<
})
writability: MetadataWritability;
- // Superseded by isUIEditable. Intentionally NOT @WasRemovedInUpgrade: dropping
- // it in 2.13 would break the previous release's pods mid rolling-deploy, since
- // they still SELECT it. The WasRemovedInUpgrade<T> type is kept so callers may
- // omit it; the decorator + physical drop are deferred (core-team-issues#2542).
+ // superseded by isUIEditable; no @WasRemovedInUpgrade yet: previous-release pods still SELECT it mid rolling deploy (core-team-issues#2542)
@Column({ type: 'boolean', default: false })
isUIReadOnly: WasRemovedInUpgrade<boolean>;
@Column({ nullable: true, default: true, type: 'boolean' })
isNullable: boolean | null;
- // Derived at flat-entity cache build time from the existence of a
- // single-field UNIQUE IndexMetadata covering this field — never persisted
- // on this entity. Kept on the type so flat-entity consumers continue to
- // read field.isUnique without per-call derivation; the PG column was
- // dropped by 1798300000000-drop-field-metadata-is-unique-column.ts.
+ // not persisted: derived from single-field UNIQUE IndexMetadata when the flat cache is built
isUnique: boolean | null;
isSearchable: boolean;
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.resolver.ts
index 25f4a5e574c..d5b5952eebd 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/field-metadata.resolver.ts
@@ -54,8 +54,7 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
-// Keep @Parent() structurally typed so ResolverValidationPipe does not validate
-// FieldMetadataDTO date decorators on already-loaded parent records.
+// structural type so ResolverValidationPipe skips FieldMetadataDTO decorators on loaded parents
type FieldMetadataStandardOverrideParent = Pick<
FieldMetadataDTO,
'label' | 'description' | 'icon' | 'overrides' | 'applicationId'
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/from-field-metadata-entity-to-field-metadata-dto.util.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/from-field-metadata-entity-to-field-metadata-dto.util.ts
index d4bd0b364f5..af33f11bf18 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/from-field-metadata-entity-to-field-metadata-dto.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/from-field-metadata-entity-to-field-metadata-dto.util.ts
@@ -17,11 +17,7 @@ const resolveEffectiveEntityIsActive = (entity: {
return typeof overrideValue === 'boolean' ? overrideValue : entity.isActive;
};
-// isUnique is derived from IndexMetadata rather than stored on the field
-// entity; callers that need an accurate value (e.g. the REST controller)
-// pass the precomputed Set<fieldMetadataId>. Callers in pure-entity
-// contexts that don't care about uniqueness can omit it.
-
+// isUnique lives in IndexMetadata, so callers needing it pass the precomputed field id set
export const fromFieldMetadataEntityToFieldMetadataDto = (
entity: FieldMetadataEntity,
derivedFieldMetadataIds?: DerivedFieldMetadataIds,
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/get-join-column-name-for-relation-field.util.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/get-join-column-name-for-relation-field.util.ts
index 7e7ffa0d2e0..f0b8ec9a0d6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/get-join-column-name-for-relation-field.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/get-join-column-name-for-relation-field.util.ts
@@ -5,8 +5,7 @@ import { computeMorphOrRelationFieldJoinColumnName } from 'src/engine/metadata-m
import { isFieldMetadataSettingsOfType } from 'src/engine/metadata-modules/field-metadata/utils/is-field-metadata-settings-of-type.util';
import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
-// The ORM derives relation columns from the field name, so fall back to it
-// when settings carry no explicit join column.
+// the ORM derives relation columns from the field name when no join column is set
export const getJoinColumnNameForRelationField = (
flatFieldMetadata: OrmFlatFieldMetadata,
): string => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/is-audit-loggable-field-type.util.ts b/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/is-audit-loggable-field-type.util.ts
index c1dff4a836d..f4740df1f2f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/is-audit-loggable-field-type.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/field-metadata/utils/is-audit-loggable-field-type.util.ts
@@ -1,7 +1,6 @@
import { FieldMetadataType } from 'twenty-shared/types';
-// Position values render blank in the timeline, so a position field is created
-// non audit logged rather than being filtered out again at write time.
+// position values render blank in the timeline, so these fields are created non audit logged instead of filtered at write time
const NON_AUDIT_LOGGABLE_FIELD_TYPES: FieldMetadataType[] = [
FieldMetadataType.POSITION,
];
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
index 6d3bcd77a93..0c3794a28c7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
@@ -82,12 +82,8 @@ export const ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME = {
toStringify: false,
universalProperty: undefined,
},
- // isUnique is derived from IndexMetadata at cache build time and is
- // not a column on the fieldMetadata table. It stays in
- // propertiesToCompare so per-type validators see the proposed
- // change (e.g. rejecting unique on FILES), but the field-metadata
- // runner drops it before issuing the SQL UPDATE — the actual state
- // change rides on the side-effect index create/delete.
+ // not a column: compared so validators see the change, but the runner drops it before the UPDATE; the
+ // actual change rides on the side-effect index create/delete
isUnique: {
toCompare: true,
toStringify: false,
@@ -2218,8 +2214,6 @@ export type MetadataEntityOverridablePropertyName<T extends AllMetadataName> =
(typeof ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME)[T]
>;
-// Which properties are translatable is owned by twenty-shared, because the
-// application SDK extracts against the same list at build time and the two
-// silently drifted when each side kept its own copy.
+// owned by twenty-shared because the application SDK extracts against the same list at build time
export type MetadataEntityTranslatablePropertyName<T extends AllMetadataName> =
T extends TranslatableMetadataName ? TranslatablePropertyName<T> : never;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts
index 795b1a69396..6e8008a92a9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts
@@ -39,7 +39,7 @@ type ManyToOneRelationValue<
? {
metadataName: TTargetMetadataName;
foreignKey: FK;
- // Should not be nullable, in the best of the world relation should always describe an inverse property
+ // TODO: make non-nullable once every relation describes an inverse property
inverseOneToManyProperty:
| keyof (typeof ALL_ONE_TO_MANY_METADATA_RELATIONS)[TTargetMetadataName]
| null;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-translatable-properties-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-translatable-properties-by-metadata-name.constant.ts
index f10233d6781..73f1c43e4df 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-translatable-properties-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-translatable-properties-by-metadata-name.constant.ts
@@ -1,8 +1,7 @@
import { TRANSLATABLE_PROPERTIES_BY_METADATA_NAME } from 'twenty-shared/i18n';
import { type AllMetadataName } from 'twenty-shared/metadata';
-// Widened from the shared literal so it can be indexed by any metadata name;
-// entities with no translatable properties are simply absent.
+// widened from the shared literal so any metadata name can index it
export const ALL_TRANSLATABLE_PROPERTIES_BY_METADATA_NAME: Partial<
Record<AllMetadataName, readonly string[]>
> = TRANSLATABLE_PROPERTIES_BY_METADATA_NAME;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts
index 3c36f4599ca..4e56ea947cb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type.ts
@@ -20,12 +20,10 @@ export const ORM_FLAT_FIELD_METADATA_KEYS = [
'relationTargetFieldMetadataId',
'relationTargetObjectMetadataId',
'morphId',
- // Read by the shared query runners (merge, create, group-by support gates)
- // and REST/direct-execution paths that also consume this projection.
+ // read by the shared query runners and REST/direct-execution paths
'isActive',
'isSystem',
- // Read by the timeline write path, which drops non-audited fields from the
- // event diff before an activity row is built.
+ // read by the timeline write path to drop non-audited fields
'isAuditLogged',
] as const satisfies readonly (keyof FlatFieldMetadata)[];
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util.ts
index 226995a5e5e..76cc468b403 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/build-field-maps-from-flat-object-metadata.util.ts
@@ -13,10 +13,7 @@ export type FieldMapsForObject = {
fieldIdByJoinColumnName: Record<string, string>;
};
-// Flat metadata snapshots are immutable and cached per workspace metadata
-// version, so the maps derived from a given (fieldMaps, objectMetadata) pair can
-// be memoized by identity: several helpers rebuild them per request otherwise
-// (order parsing, cursor encoding per record, cursor conditions per key).
+// flat snapshots are immutable per metadata version, so derived maps can be memoized by identity
const fieldMapsCache = new WeakMap<
FlatEntityMaps<OrmFlatFieldMetadata>,
WeakMap<FlatObjectMetadata, FieldMapsForObject>
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/compute-flat-field-to-update-and-related-flat-field-to-update.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/compute-flat-field-to-update-and-related-flat-field-to-update.util.ts
index 0aeb05182f2..68be045a1b2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/compute-flat-field-to-update-and-related-flat-field-to-update.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/compute-flat-field-to-update-and-related-flat-field-to-update.util.ts
@@ -37,8 +37,7 @@ type ComputeFlatFieldToUpdateAndRelatedFlatFieldToUpdateArgs = {
isSystemBuild: boolean;
workspaceCustomApplicationUniversalIdentifier: string;
} & Pick<AllFlatEntityMaps, 'flatFieldMetadataMaps'>;
-// Note: Standard override is way too complex we should land a smoother implemenentation once we standardize
-// them across every flat entities
+// TODO: simplify once standard overrides are standardized across flat entities
export const computeFlatFieldToUpdateAndRelatedFlatFieldToUpdate = ({
fromFlatFieldMetadata,
rawUpdateFieldInput,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/get-default-flat-field-metadata-from-create-field-input.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/get-default-flat-field-metadata-from-create-field-input.util.ts
index 8571598fcc4..d72fb4bd93b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/get-default-flat-field-metadata-from-create-field-input.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/get-default-flat-field-metadata-from-create-field-input.util.ts
@@ -64,8 +64,7 @@ export const getDefaultFlatFieldMetadata = ({
: resolvedDefaultValue,
createdAt,
updatedAt: createdAt,
- // isUIReadOnly is the deprecated alias of isUIEditable (inverted
- // polarity), kept for one release; isUIEditable wins when both are set.
+ // isUIReadOnly is the deprecated inverted alias; isUIEditable wins when both are set
isUIEditable:
createFieldInput.isUIEditable ??
(isDefined(createFieldInput.isUIReadOnly)
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-junction-target-settings.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-junction-target-settings.util.ts
index b6b22e4c970..1484f72a4f1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-junction-target-settings.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/validators/utils/validate-junction-target-settings.util.ts
@@ -112,9 +112,7 @@ export const validateJunctionTargetSettings = ({
];
}
- // The frontend mirrors the direction and source-group checks in
- // isValidJunctionTargetField after resolving GraphQL relation groups. These
- // representations use different identifiers, so update both together.
+ // mirrored by the frontend's isValidJunctionTargetField; update both together
const sourceFieldUniversalIdentifier =
universalFlatFieldMetadata.relationTargetFieldMetadataUniversalIdentifier;
const sourceField = isDefined(sourceFieldUniversalIdentifier)
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-skill/utils/from-create-skill-input-to-flat-skill-to-create.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-skill/utils/from-create-skill-input-to-flat-skill-to-create.util.ts
index a91c449a40b..67c1c660fe7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-skill/utils/from-create-skill-input-to-flat-skill-to-create.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-skill/utils/from-create-skill-input-to-flat-skill-to-create.util.ts
@@ -20,7 +20,7 @@ export const fromCreateSkillInputToUniversalFlatSkillToCreate = ({
['name', 'label', 'icon', 'description'],
);
- // Content is markdown - only trim, don't collapse whitespace (preserve newlines)
+ // markdown: trim only, inner whitespace is meaningful
const content = createSkillInput.content.trim();
const id = createSkillInput.id ?? v4();
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/__tests__/ingest-app-messages.input.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/__tests__/ingest-app-messages.input.spec.ts
index 4ef99a16073..aa943512e96 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/__tests__/ingest-app-messages.input.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/__tests__/ingest-app-messages.input.spec.ts
@@ -29,8 +29,7 @@ const anInput = (receivedAt: unknown) => ({
const validationErrors = (receivedAt: unknown) =>
validate(plainToInstance(IngestAppMessagesInput, anInput(receivedAt)));
-// `receivedAt` is the one field whose wire representation is not the type the
-// validator checks, so it is the one that can silently reject every call.
+// receivedAt's wire type differs from what the validator checks, so it can silently reject every call
describe('IngestAppMessagesInput receivedAt', () => {
it('accepts what the GraphQL DateTime scalar produces', async () => {
const fromTheScalar = GraphQLISODateTime.parseValue(
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
index a21b209f588..d69e56a73c8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
@@ -31,9 +31,7 @@ export class CreateAppMessageChannelInput {
@MaxLength(255)
displayName?: string;
- // Deliberately required: a default here would decide, silently and for
- // every app, whether one member's conversations are readable by the whole
- // workspace. The app author knows which its provider's messages are.
+ // required: a default would silently decide for every app whether conversations are workspace-readable
@Field(() => MessageChannelVisibility)
@IsEnum(MessageChannelVisibility)
@IsNotEmpty()
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input.ts
index d48ebb7b8ee..7e641341527 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input.ts
@@ -18,16 +18,13 @@ import { MessageParticipantRole } from 'twenty-shared/types';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
-// Only registered here: the role is stored as a SELECT on messageParticipant,
-// so app ingestion is the first surface to expose it as a GraphQL enum.
+// the role is a SELECT on messageParticipant, so this is the first surface exposing it as a GraphQL enum
registerEnumType(MessageParticipantRole, { name: 'MessageParticipantRole' });
-// One request stays inside a single transaction and one logic-function
-// timeout, so a provider backfill has to page rather than send everything.
+// one request runs in a single transaction and logic-function timeout, so provider backfills must page
export const INGEST_APP_MESSAGES_MAX_BATCH_SIZE = 100;
-// Comfortably above a long plain-text conversation message, well below what
-// would threaten the row or the transaction at full batch size.
+// above a long plain-text message, well below what would strain a full batch's transaction
export const MAX_APP_MESSAGE_TEXT_LENGTH = 262_144;
@InputType('AppMessageParticipantInput')
@@ -49,18 +46,13 @@ export class AppMessageParticipantInput {
@MaxLength(255)
displayName?: string;
- // Nothing can derive a Person from a handle that is not an email address,
- // so a caller that already knows who this is says so here. Without it the
- // participant stays unlinked and the thread never reaches a record page.
+ // a non-email handle cannot be matched to a Person, so the caller links it here or the thread reaches no record page
@Field(() => UUIDScalarType, { nullable: true })
@IsOptional()
@IsUUID()
personId?: string;
- // Attribution only. Thread targets — what puts a conversation on a record
- // page — are built from personId alone, exactly as they are for email, so a
- // participant linked only to a workspace member is stored and shows in the
- // thread but pulls the conversation onto nothing.
+ // attribution only: thread targets come from personId alone, as for email
@Field(() => UUIDScalarType, { nullable: true })
@IsOptional()
@IsUUID()
@@ -69,16 +61,13 @@ export class AppMessageParticipantInput {
@InputType('AppMessageInput')
export class AppMessageInput {
- // The provider's own id for this message. Re-ingesting the same externalId
- // updates nothing and creates nothing, so redelivered webhooks are safe.
+ // re-ingesting the same externalId is a no-op, so redelivered webhooks are safe
@Field()
@IsString()
@IsNotEmpty()
@MaxLength(512)
externalId: string;
- // The provider's own id for the conversation. Messages sharing one land in
- // the same Message Thread.
@Field()
@IsString()
@IsNotEmpty()
@@ -91,18 +80,13 @@ export class AppMessageInput {
@MaxLength(998)
subject?: string;
- // Bounded like every other string here. One call is already 100 messages in
- // a single workspace transaction, and unlike email import nothing upstream
- // caps this, so an unbounded body would make the batch limit meaningless.
+ // unlike email import, nothing upstream caps this
@Field()
@IsString()
@MaxLength(MAX_APP_MESSAGE_TEXT_LENGTH)
text: string;
- // GraphQL's DateTime scalar already hands the pipe a Date, so `@IsDate`
- // passes without this. It is here so the contract does not depend on that:
- // a timestamp scalar mode, or any non-GraphQL caller, would otherwise fail
- // validation on a value the field is meant to accept.
+ // GraphQL's DateTime scalar already yields a Date; this covers other scalar modes and non-GraphQL callers
@Field(() => Date)
@Type(() => Date)
@IsDate()
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output.ts
index 6dd74a1e702..f0164ef179e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output.ts
@@ -7,8 +7,7 @@ export class IngestedAppMessageDTO {
@Field()
externalId: string;
- // Stable across re-ingestion of the same externalId, so it is safe to hang
- // timeline activities or app records off it.
+ // stable across re-ingestion, so safe to hang timeline activities or app records off
@Field(() => UUIDScalarType)
messageId: string;
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
index fb1038bf42e..618237e3231 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
@@ -59,10 +59,8 @@ registerEnumType(MessageChannelPendingGroupEmailsAction, {
['webhookSubscriptionExternalId'],
{ where: '"webhookSubscriptionExternalId" IS NOT NULL' },
)
-// An app creates its channel from a connect hook, which a provider can retry
-// or run concurrently. The create path reads before it writes, so only the
-// database can actually stop a second row appearing for one handle. Scoped to
-// APP so it makes no claim about the email rows already in this table.
+// connect hooks can retry or run concurrently and the create path reads before writing, so only the DB stops duplicates;
+// scoped to APP so it makes no claim about existing email rows
@Index(
'IDX_MESSAGE_CHANNEL_APP_CONNECTED_ACCOUNT_HANDLE_UNIQUE',
['workspaceId', 'connectedAccountId', 'handle'],
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/__tests__/message-channel.resolver.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/__tests__/message-channel.resolver.spec.ts
index bce5658b9ac..f1ac2faedf6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/__tests__/message-channel.resolver.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/__tests__/message-channel.resolver.spec.ts
@@ -54,10 +54,6 @@ describe('MessageChannelResolver connectedAccount', () => {
};
};
- // Before this branch existed the decorator threw for a run with no user —
- // telling an app that "API keys are not supported", which is not even the
- // right diagnosis — so a cron, webhook or install hook could not read the
- // connection behind a channel its own application owns.
it('resolves an app-owned connection for a run with nobody behind it', async () => {
const { resolver, applicationMessageChannelsService } = buildResolver({
reachableConnectedAccount: { id: CONNECTED_ACCOUNT_ID },
@@ -84,9 +80,6 @@ describe('MessageChannelResolver connectedAccount', () => {
});
});
- // Reachability is the app-facing predicate's answer, not this resolver's:
- // it already refuses a connection owned by another application, and one
- // that is private to a different member than the caller.
it('returns null when the predicate says the caller cannot reach it', async () => {
const { resolver } = buildResolver({ reachableConnectedAccount: null });
@@ -100,8 +93,6 @@ describe('MessageChannelResolver connectedAccount', () => {
).toBeNull();
});
- // The user behind an APPLICATION_ACCESS token still has to be honoured, so
- // it is forwarded rather than dropped once an application is present.
it('forwards the request user when a member triggered the run', async () => {
const { resolver, applicationMessageChannelsService } = buildResolver({
reachableConnectedAccount: { id: CONNECTED_ACCOUNT_ID },
@@ -124,10 +115,7 @@ describe('MessageChannelResolver connectedAccount', () => {
);
});
- // An APPLICATION_ACCESS token can carry a user, and such a request can be
- // handed an EMAIL channel. Claiming those here sent the member's own mailbox
- // through a predicate that only matches APP connections, so a connection
- // they are entitled to see came back null.
+ // the app predicate only matches APP connections, so email channels must stay on user ownership
it('leaves an email channel on user ownership even in an application context', async () => {
const {
resolver,
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
index 3592f890cb1..d284197cdbc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
@@ -90,12 +90,8 @@ export class MessageChannelResolver {
return buildPublicConnectedAccount(account);
}
- // An app channel's connection belongs to the application, not to a member,
- // so there is no userWorkspaceId to resolve it through on a cron, webhook
- // or install hook. Reachability is delegated rather than re-derived: the
- // same predicate the app-facing channel API gates on also decides this,
- // including the boundary that stops one member reaching another's private
- // connection through the app.
+ // app connections have no member owner, so reachability is delegated to the app-facing predicate, which also
+ // stops one member reaching another's private connection through the app
if (
isDefined(application) &&
messageChannel.type === MessageChannelType.APP
@@ -171,11 +167,7 @@ export class MessageChannelResolver {
applicationId: application?.id,
});
- // An app channel's settings belong to the app that created it: its
- // visibility is the app's statement about how private its provider's
- // messages are, and the mailbox fields on this input (folder import
- // policy, group-email exclusions, contact auto-creation) have no meaning
- // for it. Mutations go through updateAppMessageChannel instead.
+ // app channel settings belong to the creating app and go through updateAppMessageChannel
if (messageChannel.type === MessageChannelType.APP) {
throw new MessageChannelException(
`Message channel ${input.id} is owned by an application and cannot be updated through this endpoint`,
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
index 658c8edefa0..9a53463cbe7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
@@ -29,12 +29,8 @@ import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/worksp
type ApplicationScope = {
applicationId: string;
workspaceId: string;
- // The user behind the call, when there is one. An APPLICATION_ACCESS token
- // carries them whenever a person triggered the run, and owning the app is
- // not the same as being allowed to administer another person's private
- // connection — so the channel API has to honour the same boundary the
- // connection API does. Null for cron, webhooks and install hooks, which act
- // as the application itself.
+ // the person who triggered the run, since owning the app does not grant access to another member's private connection;
+ // null for cron, webhooks and install hooks
requestUserWorkspaceId: string | null;
};
@@ -52,8 +48,7 @@ type UpdateArgs = ApplicationScope & {
isSyncEnabled?: boolean;
};
-// The scalar subset an app may change. Narrower than Partial<MessageChannelEntity>,
-// which carries the relations TypeORM's update() cannot take.
+// TypeORM's update() cannot take the relations Partial<MessageChannelEntity> carries
type UpdatableChannelFields = Partial<
Pick<MessageChannelEntity, 'displayName' | 'visibility' | 'isSyncEnabled'>
>;
@@ -63,8 +58,7 @@ export type OwnedMessageChannel = {
connectedAccount: ConnectedAccountEntity;
};
-// A name that is only whitespace is no name: stored as null so the UI falls
-// back to the handle, rather than rendering a blank row.
+// null rather than blank so the UI falls back to the handle
const normalizeDisplayName = (displayName?: string | null): string | null => {
const trimmedDisplayName = displayName?.trim();
@@ -152,9 +146,7 @@ export class ApplicationMessageChannelsService {
type: MessageChannelType.APP,
visibility,
isSyncEnabled: true,
- // Inert for an app channel: it is excluded from the polling crons, which
- // are the only writers of these fields. Mirrors EMAIL_GROUP, the other
- // push-delivered channel, so the sync-status UI reads it as healthy.
+ // inert since app channels skip the polling crons; mirrors EMAIL_GROUP so the UI reads healthy
syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
syncStatus: MessageChannelSyncStatus.ACTIVE,
isContactAutoCreationEnabled: false,
@@ -232,10 +224,7 @@ export class ApplicationMessageChannelsService {
return messageChannel;
}
- // Resolving the channel through the app's own connections is what stops one
- // app from reading or mutating another app's channels: the connected account
- // carries the applicationId, the channel does not. Public because ingestion
- // gates on the same check, and there must be exactly one of it.
+ // only the connected account carries applicationId, so resolving through it is what isolates apps
async findOwnedOrThrow({
applicationId,
workspaceId,
@@ -255,10 +244,7 @@ export class ApplicationMessageChannelsService {
})
: null;
- // Missing and not-reachable answer identically, and neither names the
- // connection. Letting the two differ would tell a caller holding a channel
- // id that the channel exists and whose connection backs it — the same
- // probe ownershipViolation() exists to prevent one step earlier.
+ // missing and unreachable answer identically so callers cannot probe for channels
if (!isDefined(messageChannel) || !isDefined(connectedAccount)) {
throw new MessageChannelException(
`Message channel ${id} not found`,
@@ -266,17 +252,10 @@ export class ApplicationMessageChannelsService {
);
}
- // The account comes back with the channel because the gate has already
- // loaded it: ingestion needs the same row, and re-reading it would be a
- // second round trip for a value we are holding.
return { messageChannel, connectedAccount };
}
- // Two boundaries, not one: the connection must belong to this application,
- // AND the caller must be allowed to see it. Checking only the first would
- // let any user of an app administer another user's private connection —
- // including flipping its channel to SHARE_EVERYTHING, which publishes that
- // person's messages to the whole workspace.
+ // ownership alone would let any app user flip another member's private channel to SHARE_EVERYTHING
private async assertOwnsConnectedAccount(
args: ApplicationScope & { connectedAccountId: string },
): Promise<void> {
@@ -285,10 +264,7 @@ export class ApplicationMessageChannelsService {
}
}
- // Public because the shared MessageChannelResolver resolves an app channel's
- // connectedAccount field through it: the app-facing reachability rule —
- // owned by this application, and not another member's private connection —
- // must have exactly one implementation.
+ // public so MessageChannelResolver shares the single reachability rule
async findReachableConnectedAccount({
applicationId,
workspaceId,
@@ -344,8 +320,7 @@ export class ApplicationMessageChannelsService {
.map((connectedAccount) => connectedAccount.id);
}
- // Deliberately indistinguishable from "not found": whether a connection id
- // exists is not something one app should be able to probe for another.
+ // indistinguishable from not found so one app cannot probe another's connection ids
private ownershipViolation(connectedAccountId: string) {
return new MessageChannelException(
`Connection ${connectedAccountId} not found`,
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts
index 37df9966612..26f439b8d91 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts
@@ -21,16 +21,8 @@ import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system
import { MessagingSaveMessagesAndEnqueueContactCreationService } from 'src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service';
import { type MessageWithParticipants } from 'src/modules/messaging/message-import-manager/types/message.type';
-// A full batch is 100 messages in one transaction, so the hold has to outlast
-// that comfortably: a lease that expires mid-save would let the next delivery
-// in and reintroduce exactly the duplicate this prevents. Waiting up to the
-// same order of time is better than failing a webhook that would have
-// succeeded a second later.
-//
-// The wait deliberately outlasts the lease. `withLock` does not renew, so a
-// holder that dies leaves the key behind until Redis expires it; a window
-// shorter than the lease would make every waiter give up just before the
-// lock became free, turning one crash into a batch of avoidable failures.
+// the lease must outlast a full batch save, or the next delivery gets in and duplicates
+// withLock does not renew, so waiters must outlast the lease left behind by a crashed holder
const INGESTION_LOCK_TTL_MS = 60_000;
const INGESTION_LOCK_RETRY_INTERVAL_MS = 500;
@@ -44,9 +36,7 @@ const INGESTION_LOCK_OPTIONS = {
type IngestArgs = {
applicationId: string;
workspaceId: string;
- // Ingestion resolves the channel through the same gate the channel API
- // uses, so a run triggered by one member cannot write into another
- // member's private channel.
+ // same gate as the channel API so one member's run cannot write into another's private channel
requestUserWorkspaceId: string | null;
messageChannelId: string;
messages: AppMessageInput[];
@@ -95,20 +85,13 @@ export class ApplicationMessageIngestionService {
}),
);
- // The save path decides what to insert by reading first and writing after,
- // and no unique index backs headerMessageId — so two deliveries of the same
- // provider message, arriving together, would both see nothing and both
- // insert, handing the app two different Twenty ids for one message. A
- // provider redelivers constantly, so this is the common case, not the edge.
- // Serialising per channel is the narrowest scope that closes it: dedup
- // never spans channels, and one channel's deliveries are naturally
- // sequential, so contention is a redelivery racing its original.
+ // save reads before writing and headerMessageId has no unique index, so concurrent redeliveries would duplicate
+ // locked per channel, the narrowest scope since dedup never spans channels
const savedMessages = await this.cacheLockService.withLock(
() =>
this.saveMessagesService.saveMessagesAndEnqueueContactCreation(
messagesToSave,
- // The save path only reads folder and contact-creation settings off
- // the channel, both inert here, plus its id.
+ // the save path only reads inert settings and the id off the channel
messageChannel,
connectedAccount,
workspaceId,
@@ -129,9 +112,7 @@ export class ApplicationMessageIngestionService {
messageExternalIdToMessageThreadIdMap,
} = savedMessages;
- // Dropping a row here would report success while returning fewer messages
- // than were sent, leaving the app with nothing to retry against — the
- // silent version of the "did not persist" failure above.
+ // never drop a row: the app would see success with nothing to retry
return {
messages: messagesToSave.map((message) => {
const messageId = messageExternalIdsAndIdsMap.get(message.externalId);
@@ -173,8 +154,6 @@ export class ApplicationMessageIngestionService {
subject: message.subject ?? null,
text: message.text,
receivedAt: message.receivedAt,
- // Apps ingest what the provider already delivered; there is no
- // provider-side draft to mirror.
isDraft: false,
externalId: message.externalId,
messageThreadExternalId: message.threadExternalId,
@@ -193,9 +172,7 @@ export class ApplicationMessageIngestionService {
};
}
- // A participant pointing at a record that is not there, or belongs to
- // another workspace, would insert a dangling link that quietly never
- // renders. Checked up front so the app gets told, rather than at the FK.
+ // checked up front so the app gets an error rather than a dangling link that never renders
private async assertReferencedIdentitiesExist({
messages,
workspaceId,
@@ -271,9 +248,7 @@ export class ApplicationMessageIngestionService {
}
}
- // Direction, the thread's sender column and the timeline preview all read
- // the FROM participant, so a message without exactly one is rejected rather
- // than silently rendering as an empty conversation.
+ // direction, thread sender and timeline preview all read the single FROM participant
private assertEachMessageHasOneSender(messages: AppMessageInput[]): void {
for (const message of messages) {
const senderCount = message.participants.filter(
@@ -289,8 +264,7 @@ export class ApplicationMessageIngestionService {
}
}
- // Two entries sharing an externalId would race each other inside the save
- // transaction, which keys its accumulator on exactly that value.
+ // the save transaction keys its accumulator on externalId
private assertExternalIdsAreUnique(messages: AppMessageInput[]): void {
const externalIds = new Set<string>();
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-header-message-id.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-header-message-id.util.spec.ts
index ff6e20117ae..b4d862419cd 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-header-message-id.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-header-message-id.util.spec.ts
@@ -22,10 +22,8 @@ describe('buildAppMessageHeaderMessageId', () => {
);
});
- // The collision that matters: providers commonly scope message ids per
- // conversation or per account, so two members can legitimately both send
- // "1". Merging those would discard one body and attach the other member's
- // channel to it.
+ // providers scope ids per conversation or account, so two members can both send "1"; merging them would
+ // discard one body and attach the other member's channel to it
it('separates two members whose provider reuses the same external id', () => {
expect(
buildAppMessageHeaderMessageId({
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/resolve-app-message-direction.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/resolve-app-message-direction.util.spec.ts
index 1422b8f58d8..cb92e1fa5cd 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/resolve-app-message-direction.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/resolve-app-message-direction.util.spec.ts
@@ -42,9 +42,6 @@ describe('resolveAppMessageDirection', () => {
).toBe(MessageDirection.INCOMING);
});
- // A provider that spells one account differently across its profile and
- // message payloads would otherwise mark everything the owner sent as
- // incoming — the same reason the email path normalises its handles.
it('still recognises the channel owner when the casing differs', () => {
expect(
resolveAppMessageDirection({
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util.ts
index f9e155e9e28..cb1f8a2d54c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util.ts
@@ -1,7 +1,4 @@
-// Scoped to the channel because that is the scope dedup works at: two channels
-// never share a headerMessageId, so serialising them against each other would
-// only add contention. Workspace-qualified so one workspace's ingestion cannot
-// stall another's.
+// per channel because dedup never spans channels; workspace-qualified so one workspace's ingestion cannot stall another's
export const buildAppIngestionLockKey = ({
workspaceId,
messageChannelId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util.ts
index 1a0475f81b8..5aaed9fac56 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util.ts
@@ -1,18 +1,5 @@
-// The save path dedupes on headerMessageId across every channel in the
-// workspace, which is what makes one email addressed to two synced mailboxes a
-// single Message with two channel associations. That is only sound when the id
-// is globally unique, as an RFC822 Message-ID is.
-//
-// A provider's own message id usually is not: plenty scope it per conversation
-// or per account, so Alice's message "1" and Bob's unrelated message "1" would
-// dedupe onto one row — discarding one body and attaching the other member's
-// channel to it. Scoping to the channel makes a collision impossible without
-// asking apps to guarantee a namespace they do not control.
-//
-// The cost is that two members in the same provider conversation get one
-// Message each rather than a shared one. Deliberate: convergence is a nicety,
-// and the alternative failure is one member's content surfacing under
-// another's sharing policy.
+// the save path dedupes on headerMessageId workspace-wide, but provider ids are often only unique per conversation or account
+// scoped to the channel: members in one provider conversation get separate Messages rather than one crossing sharing policies
export const buildAppMessageHeaderMessageId = ({
applicationId,
messageChannelId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util.ts
index 6ac7cd39a92..1034b4cd4e5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util.ts
@@ -2,9 +2,6 @@ import { MessageParticipantRole } from 'twenty-shared/types';
import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';
-// Derived rather than taken from the app: direction is a property of who sent
-// the message relative to this channel, which the server already knows, and
-// an app that got it backwards would mislabel every thread it ingests.
export const resolveAppMessageDirection = ({
participants,
channelHandle,
@@ -16,12 +13,7 @@ export const resolveAppMessageDirection = ({
(participant) => participant.role === MessageParticipantRole.FROM,
);
- // Compared case-insensitively, as the email path already normalises its
- // handles. A provider that spells the same account differently in its
- // profile API and its message payloads would otherwise mark every message
- // the channel owner sent as incoming. Two distinct handles differing only
- // in case would collide here, but one of them would have to be the
- // channel's own, which is the far smaller risk of the two.
+ // case-insensitive like the email path: a provider casing the account differently across APIs would make every sent message incoming
return sender?.handle.toLowerCase() === channelHandle.toLowerCase()
? MessageDirection.OUTGOING
: MessageDirection.INCOMING;
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts
index 7563c583d72..a9fadb80069 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/object-metadata/services/object-system-side-effects-on-delete-side-effect-handler.service.ts
@@ -225,11 +225,7 @@ export class ObjectSystemSideEffectsOnDeleteSideEffectHandlerService extends Met
),
);
- // Dropping a column drops every physical index on it, so an index on a
- // deleted field must go whatever its flags or owner. Join-column indexes
- // backfilled before isSystemSideEffect existed are still flagged false,
- // and skipping them left field-less indexMetadata rows whose name then
- // collided when the field was recreated.
+ // dropping a column drops its physical indexes, so delete their metadata whatever the flags or owner
const isEngineOwnedIndexOfObject =
belongsToObject && flatIndexMetadata.isSystemSideEffect;
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/utils/compute-system-view-to-create.util.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/utils/compute-system-view-to-create.util.ts
index 2c80679d304..dd1293ab4dc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/utils/compute-system-view-to-create.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-side-effect/handlers/utils/compute-system-view-to-create.util.ts
@@ -16,8 +16,7 @@ type SystemViewObjectMetadata = Pick<
'universalIdentifier' | 'labelSingular'
>;
-// The INDEX view name is a template resolved at display time; the record-page
-// view name is materialized at creation.
+// the INDEX name is a display-time template; the record-page name is materialized at creation
const SYSTEM_VIEW_PROPERTIES_BY_VIEW_KEY = {
[SYSTEM_VIEW_KEYS.INDEX]: {
type: ViewType.TABLE,
@@ -61,8 +60,7 @@ export const computeSystemViewToCreate = ({
viewKey,
}),
name: computeName(objectMetadata),
- // Only INDEX is a persisted key; FIELDS_WIDGET exists solely in the
- // universal identifier derivation.
+ // FIELDS_WIDGET exists only in the universal identifier derivation
key: viewKey === SYSTEM_VIEW_KEYS.INDEX ? ViewKey.INDEX : null,
icon,
type,
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translation-override.input.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translation-override.input.ts
index 1adc6687a0c..7d9b420d4f4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translation-override.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translation-override.input.ts
@@ -3,8 +3,7 @@ import { Field, InputType } from '@nestjs/graphql';
import { APP_LOCALES } from 'twenty-shared/translations';
import { IsIn, IsNotEmpty, IsOptional, IsString } from 'class-validator';
-// One translated value for one property in one locale. A null or empty value
-// removes the stored translation, reverting that locale to shipped-or-source.
+// a null or empty value removes the stored translation
@InputType()
export class MetadataTranslationOverrideInput {
@IsIn(Object.keys(APP_LOCALES))
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translations.input.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translations.input.ts
index 8fe4a8b1b0b..1d1c9e3f79c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translations.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-translation/dtos/metadata-translations.input.ts
@@ -5,8 +5,6 @@ import { IsIn, IsOptional, IsUUID } from 'class-validator';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
-// Scopes to one entity: all locales for the translations panel, or a single
-// locale when the caller only needs the viewer's resolution.
@InputType()
export class MetadataTranslationsInput {
@IsUUID()
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-translation/services/metadata-translation.service.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-translation/services/metadata-translation.service.ts
index 68675271aa7..0a67860f6df 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-translation/services/metadata-translation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-translation/services/metadata-translation.service.ts
@@ -32,8 +32,6 @@ type TranslatableEntity = {
entity: TranslatableFlatEntity;
};
-// The registry decides which property to read, so this is where a dynamic
-// name meets the concrete entity type.
const readStringProperty = (
entity: TranslatableFlatEntity,
property: string,
diff --git a/packages/twenty-server/src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.resolver.ts
index 723cc4f2540..69ebbe598e4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.resolver.ts
@@ -74,9 +74,7 @@ export class NavigationMenuItemResolver {
return resolveEffectiveEntityProperty({
metadataName: 'navigationMenuItem',
baseValue: navigationMenuItem.name,
- // navigationMenuItem is not an overridable entity: a workspace renaming a
- // folder edits the row itself, so there is no standard value left to
- // translate and no override to arbitrate against.
+ // not overridable: renaming a folder edits the row itself
overrides: undefined,
property: 'name',
i18nContext:
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-fraction-threshold.constant.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-fraction-threshold.constant.ts
index d9e2c92ad0d..aa8bdd79b13 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-fraction-threshold.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-fraction-threshold.constant.ts
@@ -1,3 +1,2 @@
-// A field is hinted as "mostly empty" when at least this fraction of records
-// leave it empty, per Postgres planner statistics (pg_stats)
+// a field is hinted mostly empty when at least this fraction of records leave it empty, per pg_stats planner statistics
export const MOSTLY_EMPTY_FRACTION_THRESHOLD = 0.95;
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-minimum-row-count.constant.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-minimum-row-count.constant.ts
index a8db2d9dbff..76f38049738 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-minimum-row-count.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/mostly-empty-minimum-row-count.constant.ts
@@ -1,3 +1,2 @@
-// Below this approximate record count the emptiness signal is meaningless and
-// young workspaces would get flooded with hints
+// below this the signal is meaningless and young workspaces would be flooded with hints
export const MOSTLY_EMPTY_MINIMUM_ROW_COUNT = 100;
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/optional-default-relations-object-standard-ids.constant.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/optional-default-relations-object-standard-ids.constant.ts
index 1786fe5cfbe..cd8f723bfee 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/optional-default-relations-object-standard-ids.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/constants/optional-default-relations-object-standard-ids.constant.ts
@@ -1,10 +1,7 @@
import { type STANDARD_OBJECTS } from 'twenty-shared/metadata';
-// Historical upgrade commands read DEFAULT_RELATIONS_OBJECTS_STANDARD_IDS and
-// skip any workspace missing one of those objects, so a relation object added
-// after them cannot join that list. Its own upgrade command provisions it, so a
-// workspace can lack it until that runs: object creation mints the pair only
-// when the object exists, and the command backfills objects created before.
+// historical upgrade commands skip workspaces missing any DEFAULT_RELATIONS_OBJECTS_STANDARD_IDS object, so later
+// relation objects go here: a workspace lacks them until their own upgrade command provisions them
export const OPTIONAL_DEFAULT_RELATIONS_OBJECTS_STANDARD_IDS = [
'agentChatThreadTarget',
] as const satisfies (keyof typeof STANDARD_OBJECTS)[];
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/controllers/object-metadata.controller.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/controllers/object-metadata.controller.ts
index b6aeb4cd038..f28d9bd7659 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/controllers/object-metadata.controller.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/controllers/object-metadata.controller.ts
@@ -310,10 +310,7 @@ export class ObjectMetadataController {
return grouped;
}
- // REST returns the same labels the app renders: resolved for the caller's
- // locale, through the one resolver the GraphQL read path uses. Objects and
- // every field across them resolve in one call each, so a page costs a fixed
- // number of catalog reads rather than one per row.
+ // labels resolve for the caller's locale via the GraphQL read path's resolver, one call per kind so a page costs a fixed number of catalog reads
private async toObjectWithFieldsDtos({
objects,
fieldsByObjectId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-filter.input.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-filter.input.ts
index 5fc14ffad57..40478e85145 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-filter.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-filter.input.ts
@@ -52,9 +52,7 @@ export const OBJECT_FILTER_COLUMN_BY_FILTER_FIELD: Record<
isSystem: { column: 'isSystem', type: 'boolean' },
isUICreatable: { column: 'isUICreatable', type: 'boolean' },
isUIEditable: { column: 'isUIEditable', type: 'boolean' },
- // The legacy isUIReadOnly column is no longer written since the 2.13
- // rename, so the deprecated filter runs inverted against isUIEditable,
- // consistent with how the field itself is resolved.
+ // isUIReadOnly is no longer written since 2.13, so filter inverted on isUIEditable
isUIReadOnly: {
column: 'isUIEditable',
type: 'boolean',
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-metadata.dto.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-metadata.dto.ts
index 13a248aa676..3413a494c69 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-metadata.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/dtos/object-metadata.dto.ts
@@ -70,8 +70,7 @@ export class ObjectMetadataDTO {
@Field()
isUICreatable: boolean;
- // Deprecated alias kept for one release: stays exposed (and filterable via
- // ObjectFilter) so external API consumers are not broken.
+ // Deprecated alias kept for one release so external API consumers are not broken
@Field({
deprecationReason: 'Use isUIEditable',
})
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/mostly-empty-fields.service.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/mostly-empty-fields.service.ts
index da80c5799da..e308de4a59c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/mostly-empty-fields.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/mostly-empty-fields.service.ts
@@ -12,10 +12,7 @@ import { computeMostlyEmptyFieldMetadataIds } from 'src/engine/metadata-modules/
import { computeObjectTargetTable } from 'src/engine/utils/compute-object-target-table.util';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
-// Detects fields that are empty in almost all records of an object, reading
-// Postgres planner statistics (pg_class / pg_stats) instead of scanning the
-// table: cost is a catalog lookup regardless of table size, at the price of
-// approximate results — acceptable for a settings-page hint
+// Reads Postgres planner statistics instead of scanning: approximate, but constant cost whatever the table size
@Injectable()
export class MostlyEmptyFieldsService {
constructor(
@@ -60,10 +57,7 @@ export class MostlyEmptyFieldsService {
return [];
}
- // Per-column emptiness: null fraction plus the sampled frequency of the
- // column type's empty sentinel — '' for text columns (NOT NULL DEFAULT ''),
- // '{}' for arrays, '{}'/'[]' for json. Sentinels are matched per physical
- // column type so a text value that happens to be '{}' does not count
+ // Empty sentinels are matched per physical column type so a text value of '{}' does not count as empty
const columnStatisticsRows: {
column_name: string;
empty_fraction: number;
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-metadata.entity.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-metadata.entity.ts
index 37765fafbfd..24a32aafb2e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-metadata.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-metadata.entity.ts
@@ -137,10 +137,7 @@ export class ObjectMetadataEntity
@Column({ default: true })
isUIEditable: boolean;
- // Superseded by isUIEditable. Intentionally NOT @WasRemovedInUpgrade: dropping
- // it in 2.13 would break the previous release's pods mid rolling-deploy, since
- // they still SELECT it. The WasRemovedInUpgrade<T> type is kept so callers may
- // omit it; the decorator + physical drop are deferred (core-team-issues#2542).
+ // Superseded by isUIEditable; not @WasRemovedInUpgrade yet as previous-release pods still SELECT it mid rolling deploy (core-team-issues#2542)
@Column({ type: 'boolean', default: false })
isUIReadOnly: WasRemovedInUpgrade<boolean>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-record-count.service.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-record-count.service.ts
index 974d5ddddbf..35c1376567d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-record-count.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/object-record-count.service.ts
@@ -17,8 +17,7 @@ export class ObjectRecordCountService {
private readonly workspaceManyOrAllFlatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
) {}
- // reltuples is the planner's row estimate, refreshed by autovacuum's
- // ANALYZE; never-analyzed tables report -1, clamped to 0 here
+ // Never-analyzed tables report reltuples as -1
async getApproximateRecordCountByTableName(
workspaceId: string,
): Promise<Map<string, number>> {
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/build-system-relation-flat-field-metadatas-for-object.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/build-system-relation-flat-field-metadatas-for-object.util.spec.ts
index 9b09dfca478..e3ca125b0c0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/build-system-relation-flat-field-metadatas-for-object.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/build-system-relation-flat-field-metadatas-for-object.util.spec.ts
@@ -44,8 +44,7 @@ const DEFAULT_TARGETS = {
};
describe('buildSystemRelationFlatFieldMetadatasForObject', () => {
- // The 2-38 backfill calls this with the four default targets only, so their
- // output must not change because a later target exists.
+ // The committed 2-38 backfill passes only the default targets, so their output must not change when later targets exist
it('mints exactly the default pairs when the chat target is not passed', () => {
const bundles = buildSystemRelationFlatFieldMetadatasForObject({
sourceFlatObjectMetadata: petFlatObjectMetadata,
@@ -90,7 +89,6 @@ describe('buildSystemRelationFlatFieldMetadatasForObject', () => {
]);
});
- // The 2-43 backfill passes the chat target alone to mint only its pair.
it('mints the chat pair on the same morph as the standard legs', () => {
const bundles = buildSystemRelationFlatFieldMetadatasForObject({
sourceFlatObjectMetadata: petFlatObjectMetadata,
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/resolve-system-relation-target-flat-object-metadatas.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/resolve-system-relation-target-flat-object-metadatas.util.spec.ts
index f96eb218b24..50fa8f0de55 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/resolve-system-relation-target-flat-object-metadatas.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/__tests__/resolve-system-relation-target-flat-object-metadatas.util.spec.ts
@@ -43,8 +43,6 @@ describe('resolveSystemRelationTargetFlatObjectMetadatas', () => {
expect(missingDefaultRelationObjectNameSingulars).toEqual([]);
});
- // Its upgrade command provisions the chat target and backfills the objects
- // created before it ran, so creating an object meanwhile must still work.
it('leaves out the chat target without reporting it while it is not provisioned', () => {
const {
standardTargetFlatObjectMetadataByNameSingular,
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/build-system-relation-flat-field-metadatas-for-object.util.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/build-system-relation-flat-field-metadatas-for-object.util.ts
index 93fe4b049af..2a55378f2fe 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/build-system-relation-flat-field-metadatas-for-object.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/build-system-relation-flat-field-metadatas-for-object.util.ts
@@ -24,8 +24,7 @@ type DefaultRelationStandardObjectNameSingular =
type OptionalDefaultRelationStandardObjectNameSingular =
(typeof OPTIONAL_DEFAULT_RELATIONS_OBJECTS_STANDARD_IDS)[number];
-// A pair is minted per target passed: object creation insists on the default
-// targets itself, while a backfill passes only the target it provisions.
+// A pair is built per target passed: object creation passes the defaults, a backfill only the target it provisions
export type StandardTargetFlatObjectMetadataByNameSingular = Partial<
Record<
| DefaultRelationStandardObjectNameSingular
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-mostly-empty-field-metadata-ids.util.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-mostly-empty-field-metadata-ids.util.ts
index f1a3bd11028..a2d812bac9e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-mostly-empty-field-metadata-ids.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-mostly-empty-field-metadata-ids.util.ts
@@ -49,8 +49,7 @@ export const computeMostlyEmptyFieldMetadataIds = ({
return false;
}
- // A column missing from statistics (e.g. added after the last ANALYZE)
- // means we don't know, and not knowing means no hint
+ // A column missing from statistics (e.g. added after the last ANALYZE) yields no hint
return columnNames.every((columnName) => {
const emptyFraction = emptyFractionByColumnName.get(columnName);
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-system-morph-target-field-label.util.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-system-morph-target-field-label.util.ts
index b5482702fef..7564675bcd2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-system-morph-target-field-label.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/compute-system-morph-target-field-label.util.ts
@@ -4,9 +4,7 @@ import { capitalize, isDefined } from 'twenty-shared/utils';
import { i18nLabel } from 'src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util';
-// Morph siblings render as one column labelled by whichever sibling survives
-// dedup, so a group with a shared label must keep it for every sibling,
-// including the ones added or renamed along with a custom object.
+// Morph siblings render as one column labelled by the dedup survivor, so a shared label must apply to every sibling
const SHARED_LABEL_BY_MORPH_ID: Record<string, string> = {
[STANDARD_OBJECTS.attachment.morphIds.targetMorphId.morphId]: i18nLabel(
msg({ message: `Attached to`, context: 'fieldMetadata.label' }),
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/get-emptiness-column-names-for-field.util.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/get-emptiness-column-names-for-field.util.ts
index 7ef221bba38..2d075a41845 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/get-emptiness-column-names-for-field.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/get-emptiness-column-names-for-field.util.ts
@@ -7,9 +7,7 @@ import { assertUnreachable, isDefined } from 'twenty-shared/utils';
import { computeCompositeColumnName } from 'src/engine/metadata-modules/field-metadata/utils/compute-column-name.util';
import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';
-// Composite properties that carry workspace defaults (currency codes, phone
-// country/calling codes): a stamped default would mask emptiness of the value
-// users actually fill in
+// A stamped workspace default would mask emptiness of the value users actually fill in
const DEFAULT_BEARING_COMPOSITE_PROPERTIES: Partial<
Record<FieldMetadataType, string[]>
> = {
@@ -39,9 +37,6 @@ const getCompositeEmptinessColumnNames = (
);
};
-// Returns the physical columns whose emptiness determines whether the field is
-// empty, or null for types where emptiness is not meaningful (relations,
-// booleans, system-managed types)
export const getEmptinessColumnNamesForField = (
flatFieldMetadata: Pick<FlatFieldMetadata, 'name' | 'type'>,
): string[] | null => {
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/resolve-system-relation-target-flat-object-metadatas.util.ts b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/resolve-system-relation-target-flat-object-metadatas.util.ts
index 3b2f824bec1..ad5290f5f51 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/resolve-system-relation-target-flat-object-metadatas.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/resolve-system-relation-target-flat-object-metadatas.util.ts
@@ -11,9 +11,7 @@ import { type StandardTargetFlatObjectMetadataByNameSingular } from 'src/engine/
type DefaultRelationStandardObjectNameSingular =
(typeof DEFAULT_RELATIONS_OBJECTS_STANDARD_IDS)[number];
-// A default relation object must exist for an object to be created, but an
-// optional one is provisioned by its own upgrade command, which also backfills
-// the objects created before it ran, so its absence must not block creation.
+// An optional target is provisioned and backfilled by its own upgrade command, so its absence must not block creation
export const resolveSystemRelationTargetFlatObjectMetadatas = ({
flatObjectMetadataMaps,
}: Pick<AllFlatEntityMaps, 'flatObjectMetadataMaps'>): {
diff --git a/packages/twenty-server/src/engine/metadata-modules/object-permission/field-permission/field-permission.service.ts b/packages/twenty-server/src/engine/metadata-modules/object-permission/field-permission/field-permission.service.ts
index 74b58ab6508..11e701828b8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/object-permission/field-permission/field-permission.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/object-permission/field-permission/field-permission.service.ts
@@ -222,8 +222,7 @@ export class FieldPermissionService {
: current.canUpdateFieldValue;
if (!isDefined(effectiveCanRead) && !isDefined(effectiveCanUpdate)) {
- // The mirror pass only owns rows it could have written itself, so a row
- // another application declared is left alone rather than silently dropped
+ // The mirror pass only owns rows it could have written itself; another application's row is left alone
const isForeignMirroredRow =
mirroredFieldKeys.has(key) &&
!inputFieldKeys.has(key) &&
@@ -509,8 +508,7 @@ export class FieldPermissionService {
continue;
}
- // A cleared source row is dropped from desiredMap by the bothNull gate above,
- // so the mirror has to be told to clear explicitly or it survives as an orphan
+ // The bothNull gate drops a cleared source row from desiredMap, so the mirror must be cleared explicitly or it orphans
const sourceIsCleared =
!isDefined(fieldPermission.canReadFieldValue) &&
!isDefined(fieldPermission.canUpdateFieldValue);
diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout-tab/constants/standard-page-layout-tab-titles.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout-tab/constants/standard-page-layout-tab-titles.ts
index 02ebe2032f4..630684b6d65 100644
--- a/packages/twenty-server/src/engine/metadata-modules/page-layout-tab/constants/standard-page-layout-tab-titles.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout-tab/constants/standard-page-layout-tab-titles.ts
@@ -1,9 +1,6 @@
import { msg } from '@lingui/core/macro';
-// This file exists solely for Lingui string extraction.
-// The strings defined here correspond to standard page layout tab titles
-// so they appear in the .po catalogs and can be translated at resolve time
-// via generateMessageId hash lookups.
+// Exists solely so Lingui extracts these into the .po catalogs for resolve-time translation
export const getStandardPageLayoutTabTitles = () => [
msg({ message: `Home`, context: 'pageLayoutTab.title' }),
msg({ message: `Timeline`, context: 'pageLayoutTab.title' }),
diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/constants/standard-page-layout-widget-titles.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/constants/standard-page-layout-widget-titles.ts
index 143b3619466..b91aff72864 100644
--- a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/constants/standard-page-layout-widget-titles.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/constants/standard-page-layout-widget-titles.ts
@@ -1,9 +1,6 @@
import { msg } from '@lingui/core/macro';
-// This file exists solely for Lingui string extraction.
-// The strings defined here correspond to standard page layout widget titles
-// so they appear in the .po catalogs and can be translated at resolve time
-// via generateMessageId hash lookups.
+// Exists solely so Lingui extracts these into the .po catalogs for resolve-time translation
export const getStandardPageLayoutWidgetTitles = () => [
msg({ message: `Fields`, context: 'pageLayoutWidget.title' }),
msg({ message: `Timeline`, context: 'pageLayoutWidget.title' }),
diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/validate-field-configuration-nested-relation.util.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/validate-field-configuration-nested-relation.util.ts
index 3b223a29bc1..e9f69fdb01a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/validate-field-configuration-nested-relation.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout-widget/utils/validate-field-configuration-nested-relation.util.ts
@@ -34,8 +34,7 @@ const buildNestedRelationValidationException = ({
);
};
-// Junction relation fields also carry ONE_TO_MANY metadata but are rendered
-// through a dedicated junction path, so they are not valid nested hops.
+// Junction fields are also ONE_TO_MANY but render through a dedicated junction path, so they are not valid nested hops
const isPlainOneToManyRelationFlatFieldMetadata = (
field: FlatFieldMetadata,
): boolean =>
@@ -43,9 +42,7 @@ const isPlainOneToManyRelationFlatFieldMetadata = (
field.settings.relationType === RelationType.ONE_TO_MANY &&
!isNonEmptyString(field.settings.junctionTargetFieldId);
-// The first hop can also be many-to-one: the widget then scopes the terminal
-// view directly by the single intermediate record the current record points
-// at, instead of traversing the relation.
+// A many-to-one first hop scopes the terminal view by the single record it points at
const isPlainRelationFlatFieldMetadata = (field: FlatFieldMetadata): boolean =>
isFlatFieldMetadataOfType(field, FieldMetadataType.RELATION) &&
(field.settings.relationType === RelationType.ONE_TO_MANY ||
@@ -87,8 +84,7 @@ export const validateFieldConfigurationNestedRelationOrThrow = ({
widgetTitle,
});
- // A nested widget lists the second hop through an embedded view, so any
- // inline display mode would render the first hop's relation field instead.
+ // Inline display modes would render the first hop's relation field instead of the nested view
if (fieldDisplayMode !== FieldDisplayMode.TABLE) {
throw invalidNestedRelation(
`nestedRelationFieldMetadataId requires fieldDisplayMode "${FieldDisplayMode.TABLE}", got "${fieldDisplayMode}".`,
diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout/constants/standard-page-layout-names.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout/constants/standard-page-layout-names.ts
index 2eefa0ef449..779dae2f31e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/page-layout/constants/standard-page-layout-names.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout/constants/standard-page-layout-names.ts
@@ -1,9 +1,6 @@
import { msg } from '@lingui/core/macro';
-// This file exists solely for Lingui string extraction.
-// The strings defined here correspond to standard page layout names
-// so they appear in the .po catalogs and can be translated at resolve time
-// via generateMessageId hash lookups.
+// Exists solely so Lingui extracts these into the .po catalogs for resolve-time translation
export const getStandardPageLayoutNames = () => [
msg({ message: `Default Blocklist Layout`, context: 'pageLayout.name' }),
msg({
diff --git a/packages/twenty-server/src/engine/metadata-modules/page-layout/resolvers/page-layout.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/page-layout/resolvers/page-layout.resolver.ts
index b5d90df9d62..a5535adc84b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/page-layout/resolvers/page-layout.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/page-layout/resolvers/page-layout.resolver.ts
@@ -85,9 +85,7 @@ export class PageLayoutResolver {
return resolveEffectiveEntityProperty({
metadataName: 'pageLayout',
baseValue: pageLayout.name,
- // pageLayout is not an overridable entity: a workspace renaming a layout
- // edits the row itself, so there is no standard value left to translate
- // and no override to arbitrate against.
+ // pageLayout is not overridable: a rename edits the row itself
overrides: undefined,
property: 'name',
i18nContext,
diff --git a/packages/twenty-server/src/engine/metadata-modules/pagination/types/metadata-filter-column.type.ts b/packages/twenty-server/src/engine/metadata-modules/pagination/types/metadata-filter-column.type.ts
index 63eaf0dc40c..5ca59754240 100644
--- a/packages/twenty-server/src/engine/metadata-modules/pagination/types/metadata-filter-column.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/pagination/types/metadata-filter-column.type.ts
@@ -1,6 +1,4 @@
-// invertBooleanValues supports deprecated boolean aliases whose backing
-// column has the opposite meaning (isUIReadOnly filters run against
-// isUIEditable, since the legacy column is no longer written).
+// invertBooleanValues: deprecated aliases like isUIReadOnly filter against the opposite isUIEditable column
export type MetadataFilterColumn =
| { column: string; type: 'uuid' }
| { column: string; type: 'boolean'; invertBooleanValues?: true };
diff --git a/packages/twenty-server/src/engine/metadata-modules/pagination/utils/apply-metadata-filter-to-query-builder.util.ts b/packages/twenty-server/src/engine/metadata-modules/pagination/utils/apply-metadata-filter-to-query-builder.util.ts
index 60398500844..d5cd3b3c873 100644
--- a/packages/twenty-server/src/engine/metadata-modules/pagination/utils/apply-metadata-filter-to-query-builder.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/pagination/utils/apply-metadata-filter-to-query-builder.util.ts
@@ -114,10 +114,6 @@ const applyComparisonToQueryBuilder = ({
}
};
-// Translates a nestjs-query style filter ({ and, or, field: { eq, in, ... } })
-// into TypeORM query builder conditions. Top-level field conditions, `and`
-// entries and separate comparisons on one field are combined with AND; `or`
-// groups are bracketed and combined with OR.
export const applyMetadataFilterToQueryBuilder = <
TFilter extends MetadataFilterShape<TFilter>,
>({
diff --git a/packages/twenty-server/src/engine/metadata-modules/pagination/utils/normalize-metadata-filter-comparison.util.ts b/packages/twenty-server/src/engine/metadata-modules/pagination/utils/normalize-metadata-filter-comparison.util.ts
index c4a9b91a0ea..4066476f2c8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/pagination/utils/normalize-metadata-filter-comparison.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/pagination/utils/normalize-metadata-filter-comparison.util.ts
@@ -77,9 +77,7 @@ export const normalizeMetadataFilterComparison = ({
);
}
- // Postgres compares uuid columns canonically, but the in-memory matcher
- // compares raw strings, so operands are lowercased to keep both paths
- // agreeing on differently-cased but equal ids.
+ // Postgres compares uuids case-insensitively but the in-memory matcher compares raw strings
return lowercaseComparisonOperands(normalizedComparison);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts b/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts
index e3edbeb5fda..0188e8299fb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/permissions/permissions.service.ts
@@ -274,8 +274,7 @@ export class PermissionsService {
);
}
- // Naming an application that no longer exists is not the same as declaring
- // no role, and must not fall back to the full permissions of the user.
+ // A deleted application must not fall back to the user's full permissions
private async findApplicationDefaultRoleIdOrThrow({
applicationId,
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/role/role.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/role/role.resolver.ts
index bf178accc51..89f8f415987 100644
--- a/packages/twenty-server/src/engine/metadata-modules/role/role.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/role/role.resolver.ts
@@ -222,8 +222,7 @@ export class RoleResolver {
return deletedRole.id;
}
- // API-key callers have no user workspace; lockout protection only applies to
- // human actors, so they resolve to no acting roles.
+ // Lockout protection only applies to human actors; API-key callers have no user workspace
private async getActingRoleIds({
workspaceId,
actingUserWorkspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts b/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts
index b2058e03a42..9febf2cc74b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/role/services/workspace-roles-permissions-cache.service.ts
@@ -274,8 +274,7 @@ export class WorkspaceRolesPermissionsCacheService extends WorkspaceCacheProvide
private getRolePermissionFlagUniversalIdentifier(
rolePermissionFlag: RolePermissionFlagEntity,
): string {
- // The `permissionFlag` relation is stripped during upgrades until the 2.6.0
- // cursor (@WasIntroducedInUpgrade), so fall back to the legacy `flag` column.
+ // The permissionFlag relation is stripped until the 2.6.0 upgrade cursor, so fall back to the legacy flag column
return (
rolePermissionFlag.permissionFlag?.universalIdentifier ??
SystemPermissionFlag[rolePermissionFlag.flag as PermissionFlagType]
diff --git a/packages/twenty-server/src/engine/metadata-modules/role/tools/types/role-tool-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/role/tools/types/role-tool-context.type.ts
index e9fe17ee823..fa672cf09ac 100644
--- a/packages/twenty-server/src/engine/metadata-modules/role/tools/types/role-tool-context.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/role/tools/types/role-tool-context.type.ts
@@ -1,5 +1,3 @@
-// Caller identity forwarded to the services, which enforce the caller-aware
-// rules (self role change, lockout protection).
export type RoleToolContext = {
workspaceId: string;
callerRoleIds: string[];
diff --git a/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-summary.util.ts b/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-summary.util.ts
index 9a696813321..4f9e174219c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-summary.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-summary.util.ts
@@ -8,8 +8,7 @@ type ObjectPermissionFields = {
canDestroyObjectRecords?: boolean | null;
};
-// Narrows to the permission booleans the model needs, dropping restrictedFields
-// and the nested row-level predicate arrays that would bloat the tool output.
+// Drops restrictedFields and row-level predicates that would bloat the tool output
export const toObjectPermissionSummary = (
objectPermission: ObjectPermissionFields,
) => ({
diff --git a/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-tool-error-message.util.ts b/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-tool-error-message.util.ts
index 09b9e1b2a8a..acd001ca94a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-tool-error-message.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/role/tools/utils/to-role-tool-error-message.util.ts
@@ -1,9 +1,7 @@
import { formatValidationErrors } from 'src/engine/core-modules/tool-provider/utils/format-validation-errors.util';
import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
-// Role writes run through the workspace migration pipeline, whose exception
-// carries a generic message and the actionable per-entity errors in its report.
-// Expand it so the model gets something it can correct.
+// Migration pipeline exceptions carry a generic message; the actionable per-entity errors are in the report
export const toRoleToolErrorMessage = (error: unknown): string => {
if (error instanceof WorkspaceMigrationBuilderException) {
return formatValidationErrors(error);
diff --git a/packages/twenty-server/src/engine/metadata-modules/role/utils/validate-role-mutation-does-not-lock-out-actor.util.ts b/packages/twenty-server/src/engine/metadata-modules/role/utils/validate-role-mutation-does-not-lock-out-actor.util.ts
index b66010a7466..58def8d15b3 100644
--- a/packages/twenty-server/src/engine/metadata-modules/role/utils/validate-role-mutation-does-not-lock-out-actor.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/role/utils/validate-role-mutation-does-not-lock-out-actor.util.ts
@@ -9,8 +9,7 @@ import {
PermissionsExceptionMessage,
} from 'src/engine/metadata-modules/permissions/permissions.exception';
-// Non-editable system roles are rejected downstream with ROLE_NOT_EDITABLE,
-// which is the more accurate error there; lockout only concerns editable roles.
+// Non-editable roles are left to the more accurate downstream ROLE_NOT_EDITABLE error
export const validateRoleDeletionDoesNotLockOutActorOrThrow = ({
flatRole,
actingRoleIds,
@@ -28,8 +27,6 @@ export const validateRoleDeletionDoesNotLockOutActorOrThrow = ({
);
};
-// Revoking settings access from a role the actor holds would lock them out of
-// role management, unless the role keeps an explicit ROLES permission flag.
export const validateRoleUpdateDoesNotLockOutActorOrThrow = ({
flatRole,
canUpdateAllSettingsUpdate,
diff --git a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts
index eb34e4d5ad5..1140a8eddc0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts
@@ -122,10 +122,7 @@ export class RowLevelPermissionPredicateGroupService {
}
public async deleteAllRowLevelPermissionPredicateGroups(workspaceId: string) {
- // Callers reconcile a whole fleet, so most workspaces have nothing to
- // delete. Checking first keeps that a read, and lets callers ask on every
- // pass instead of only on the revoke transition, which is what makes the
- // cleanup recover if a previous attempt failed after the revoke committed.
+ // Checking first keeps the common no-op a read and lets cleanup retry on every pass after a failed attempt
const hasPredicateGroups =
(await this.rowLevelPermissionPredicateGroupRepository.count(
workspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/utils/validate-row-level-permission-rule-ownership.util.ts b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/utils/validate-row-level-permission-rule-ownership.util.ts
index 52d967cd39e..a60963f2e5a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/utils/validate-row-level-permission-rule-ownership.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/utils/validate-row-level-permission-rule-ownership.util.ts
@@ -16,11 +16,8 @@ import {
import { type FlatRowLevelPermissionPredicateGroup } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate-group.type';
import { type FlatRowLevelPermissionPredicate } from 'src/engine/metadata-modules/row-level-permission-predicate/types/flat-row-level-permission-predicate.type';
-// Supplied ids are resolved workspace-wide further down, and the migration
-// validators only compare an update against its own stored row, so a predicate
-// or group id belonging to another role or object would be silently rewritten
-// in place, and a field from another object would build a filter that never
-// matches. Scope everything to the requested role and object upfront.
+// Ids resolve workspace-wide downstream and migration validators only compare an update to its own row, so another
+// role's or object's ids would be silently rewritten and another object's field would build a never-matching filter
export const validateRowLevelPermissionRuleOwnershipOrThrow = ({
roleId,
objectMetadataId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
index 60f485fe178..d9b1a10468d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/skill/skill.resolver.ts
@@ -22,8 +22,7 @@ import { SkillService } from 'src/engine/metadata-modules/skill/skill.service';
import { WorkspaceMigrationGraphqlApiExceptionInterceptor } from 'src/engine/workspace-manager/workspace-migration/interceptors/workspace-migration-graphql-api-exception.interceptor';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
-// Reads are open to chat users so the composer can list skills; mutations
-// stay behind AI settings.
+// Reads only need the AI flag so the chat composer can list skills; mutations need AI_SETTINGS
@UseGuards(
AuthPrincipalGuard({
userSession: {
diff --git a/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/constants/standard-timeline-activity-type-definitions.constant.ts b/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/constants/standard-timeline-activity-type-definitions.constant.ts
index aa98bb681bf..090c834eabb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/constants/standard-timeline-activity-type-definitions.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/constants/standard-timeline-activity-type-definitions.constant.ts
@@ -32,8 +32,7 @@ export type StandardTimelineActivityTypeDefinition =
happensAtFieldUniversalIdentifier?: string;
};
-// Standard wildcard emitters supply platform fallbacks when no object-specific
-// type owns the slot. Application manifests require an object on every emitter.
+// Wildcard emitters are standard-only fallbacks; application manifests require an object on every emitter
const STANDARD_TIMELINE_ACTIVITY_TYPE_DEFINITION_SOURCES: StandardTimelineActivityTypeDefinitionSource[] =
[
{
@@ -301,8 +300,7 @@ const STANDARD_TIMELINE_ACTIVITY_TYPE_DEFINITION_SOURCES: StandardTimelineActivi
},
];
-// The normalized properties keep the committed 2.34 workspace command stable;
-// current builders and app declarations read the nested emit contract.
+// Normalized properties keep the committed 2.34 upgrade command stable
export const STANDARD_TIMELINE_ACTIVITY_TYPE_DEFINITIONS: StandardTimelineActivityTypeDefinition[] =
STANDARD_TIMELINE_ACTIVITY_TYPE_DEFINITION_SOURCES.map((definition) => ({
...definition,
diff --git a/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/entities/timeline-activity-type.entity.ts b/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/entities/timeline-activity-type.entity.ts
index 22049b17fbc..10cae748e1c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/entities/timeline-activity-type.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/timeline-activity-type/entities/timeline-activity-type.entity.ts
@@ -57,8 +57,7 @@ export class TimelineActivityTypeEntity
@Column({ nullable: false, type: 'varchar' })
label: string;
- // The verb used by automatic audit writers to resolve a type. Null leaves
- // the type available only to explicit writers addressing its identifier.
+ // The verb automatic audit writers resolve the type by; null leaves it to explicit writers addressing its identifier
@Column({ nullable: true, type: 'varchar' })
action: TimelineActivityAction | null;
@@ -76,14 +75,11 @@ export class TimelineActivityTypeEntity
upgradeCommandName:
REFACTOR_TIMELINE_ACTIVITY_TYPE_RENDERING_UPGRADE_COMMAND_NAME,
})
- // Native renderers reserve identifiers in this namespace so snapshots use
- // the same live-first resolution path as application front components.
+ // Native renderers reserve identifiers here so snapshots resolve live-first like application front components
@Column({ nullable: true, type: 'uuid' })
frontComponentUniversalIdentifier: string | null;
- // The object whose records this entry is about, as a soft reference rather
- // than a relation: it is resolved through the flat maps at write time to pick
- // the type for an event, and null means any object.
+ // Soft reference resolved through the flat maps at write time; null means any object
@Column({ nullable: true, type: 'uuid' })
objectUniversalIdentifier: string | null;
@@ -99,9 +95,7 @@ export class TimelineActivityTypeEntity
@Column({ nullable: true, type: 'uuid', array: true })
triggerFieldUniversalIdentifiers: string[] | null;
- // The source object field carrying the moment linked activities anchor at
- // (an email's receivedAt, a calendar event's startsAt). Null keeps the
- // event write time.
+ // Source field holding the moment linked activities anchor at (email receivedAt, event startsAt); null keeps the write time
@WasIntroducedInUpgrade({
upgradeCommandName:
ADD_TIMELINE_ACTIVITY_HAPPENS_AT_FIELD_UPGRADE_COMMAND_NAME,
diff --git a/packages/twenty-server/src/engine/metadata-modules/user-role/user-role.service.ts b/packages/twenty-server/src/engine/metadata-modules/user-role/user-role.service.ts
index 8238b143cea..e143d67e029 100644
--- a/packages/twenty-server/src/engine/metadata-modules/user-role/user-role.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/user-role/user-role.service.ts
@@ -34,9 +34,6 @@ export class UserRoleService {
private readonly roleValidationService: RoleValidationService,
) {}
- // Resolves a workspace member to its user workspace and assigns the role,
- // enforcing the self-role-change and assignability rules for every surface
- // (GraphQL, AI tools, future REST/CLI).
public async assignRoleToWorkspaceMember({
workspaceId,
workspaceMemberId,
@@ -70,8 +67,7 @@ export class UserRoleService {
);
}
- // Checked before role validation so a self-assignment fails with the
- // self-role error even when the supplied role does not exist.
+ // Before role validation so a self-assignment reports the self-role error even for an unknown role
this.validateNotSelfAssignmentOrThrow({
userWorkspaceIds: [userWorkspace.id],
actingUserWorkspaceId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/view-filter/controllers/view-filter.controller.ts b/packages/twenty-server/src/engine/metadata-modules/view-filter/controllers/view-filter.controller.ts
index 8c6eea4c2c3..2e76d4ff209 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view-filter/controllers/view-filter.controller.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view-filter/controllers/view-filter.controller.ts
@@ -73,8 +73,6 @@ export class ViewFilterController {
) {
const page = await this.viewFilterService.findManyPaginated({
workspaceId: workspace.id,
- // An empty viewId means "no filter", matching the sibling view
- // controllers, rather than filtering on the empty string.
viewId: viewId === '' ? undefined : viewId,
pagination: parseMetadataRestPagination(request),
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/view-permissions/utils/resolve-view-child-entity-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/view-permissions/utils/resolve-view-child-entity-id.util.ts
index 15c0bb6cfce..e169dd077a9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view-permissions/utils/resolve-view-child-entity-id.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view-permissions/utils/resolve-view-child-entity-id.util.ts
@@ -1,8 +1,6 @@
import { isNonEmptyString } from '@sniptt/guards';
-// The top-level id is the authoritative one where a mutation takes it: its
-// input extends a partial create input that also carries an optional id, and
-// only the argument routes the mutation.
+// The input also carries an optional id from the create input, but only the top-level argument routes the mutation
export const resolveViewChildEntityId = ({
args,
params,
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/constants/index-view-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/view/constants/index-view-name.constant.ts
index 2ea07c78dee..989b35b4711 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/constants/index-view-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/constants/index-view-name.constant.ts
@@ -2,8 +2,6 @@ import { msg } from '@lingui/core/macro';
import { i18nLabel } from 'src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util';
-// Source message every INDEX view is minted with; the object label is
-// substituted at read time.
export const INDEX_VIEW_NAME = i18nLabel(
msg({ message: `All {objectLabelPlural}`, context: 'view.name' }),
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/dtos/inputs/update-view.input.ts b/packages/twenty-server/src/engine/metadata-modules/view/dtos/inputs/update-view.input.ts
index 846ed4a2ca0..ff204730356 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/dtos/inputs/update-view.input.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/dtos/inputs/update-view.input.ts
@@ -25,8 +25,7 @@ import { KANBAN_COLUMN_MAX_WIDTH } from 'src/engine/metadata-modules/view/consta
import { KANBAN_COLUMN_MIN_WIDTH } from 'src/engine/metadata-modules/view/constants/kanban-column-min-width.constant';
import { VIEW_OPEN_RECORD_IN_DEPRECATION } from 'src/engine/metadata-modules/view/constants/view-open-record-in-deprecation.constant';
-// TODO: this should be refactored like for view-field.input.ts
-// This is a temporary fix as we were extending the CreateViewInput class which was adding default values for the non filled fields
+// TODO: refactor like view-field.input.ts; extending CreateViewInput added defaults for unset fields
@InputType()
export class UpdateViewInput {
@IsUUID()
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/entities/view.entity.ts b/packages/twenty-server/src/engine/metadata-modules/view/entities/view.entity.ts
index 96516b42343..69fea2107f1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/entities/view.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/entities/view.entity.ts
@@ -61,7 +61,7 @@ export type ViewOverrides = {
groupLoadLimit?: number;
};
-// We could refactor this type to be dynamic to view type
+// TODO: make this type dynamic to the view type
@Entity({ name: 'view', schema: 'core' })
@Index('IDX_VIEW_APPLICATION_ID', ['applicationId'])
@Index('IDX_VIEW_OBJECT_METADATA_ID_WORKSPACE_ID', [
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/resolvers/view.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/view/resolvers/view.resolver.ts
index c4bb80c1e35..c4c7a5738b5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/resolvers/view.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/resolvers/view.resolver.ts
@@ -99,9 +99,7 @@ export class ViewResolver {
});
}
- // The object label is resolved against the object's own application, which is
- // not necessarily the view's -- a workspace-custom view can point at a
- // standard object.
+ // A workspace-custom view can point at a standard object, so the label resolves against the object's application
private async resolveObjectLabelPlaceholderValues({
view,
context,
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/build-view-name-object-labels.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/build-view-name-object-labels.util.spec.ts
index c1a4883fa2c..09b58c1ec00 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/build-view-name-object-labels.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/build-view-name-object-labels.util.spec.ts
@@ -15,8 +15,6 @@ const i18nContext = {
};
describe('buildViewNameObjectLabels', () => {
- // Capitalization rides along: the value carries the casing because a
- // placeholder can start a label.
it('resolves only the placeholder the name carries', () => {
expect(
buildViewNameObjectLabels({
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/resolve-view-name.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/resolve-view-name.util.spec.ts
index f779a978dff..711efe264e8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/resolve-view-name.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/utils/__tests__/resolve-view-name.util.spec.ts
@@ -71,8 +71,6 @@ describe('resolveViewName', () => {
).toBe('All {objectLabelPlural}');
});
- // A view owned by the workspace-custom application is user copy: it must come
- // back verbatim rather than being matched against the standard catalog.
it('returns a workspace-custom view name untranslated', () => {
expect(
resolveViewName({
@@ -99,8 +97,7 @@ describe('resolveViewName', () => {
});
it('resolves an installed application view name from that application catalog', () => {
- // generateMessageId('All rockets', 'view.name') — catalogs are keyed with
- // the metadataName.property context since S5.
+ // generateMessageId('All rockets', 'view.name')
const catalog = { '1FxLDo': 'Toutes les fusees' };
expect(
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/utils/build-view-name-object-labels.util.ts b/packages/twenty-server/src/engine/metadata-modules/view/utils/build-view-name-object-labels.util.ts
index 67e935a7033..2998e34c504 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/utils/build-view-name-object-labels.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/utils/build-view-name-object-labels.util.ts
@@ -15,8 +15,7 @@ type ViewNameObjectMetadata = {
overrides?: AuthoredOverrides<ObjectMetadataOverrides> | null;
};
-// Each placeholder resolved costs a catalog lookup, so only the ones the name
-// actually carries are resolved.
+// Each resolved placeholder costs a catalog lookup
export const buildViewNameObjectLabels = ({
viewName,
objectMetadata,
diff --git a/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts b/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts
index fe8d7682376..aae1871afd0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/webhook/jobs/call-webhook-jobs.job.ts
@@ -38,10 +38,7 @@ export class CallWebhookJobsJob {
async handle(
workspaceEventBatch: WorkspaceEventBatchForWebhook<ObjectRecordEvent>,
): Promise<void> {
- // If you change that function, double check it does not break Zapier
- // trigger in packages/twenty-zapier/src/triggers/trigger_record.ts
- // Also change the openApi schema for webhooks
- // packages/twenty-server/src/engine/core-modules/open-api/utils/computeWebhooks.utils.ts
+ // Keep in sync with packages/twenty-zapier/src/triggers/trigger_record.ts and computeWebhooks.utils.ts
const { flatWebhookMaps, flatObjectMetadataMaps } =
await this.workspaceCacheService.getOrRecompute(
diff --git a/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.spec.ts b/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.spec.ts
index a0eb4d2a31e..182c5cba32c 100644
--- a/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.spec.ts
+++ b/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.spec.ts
@@ -221,8 +221,6 @@ describe('CookieSessionCsrfMiddleware', () => {
expect(response.status).toHaveBeenCalledWith(403);
});
- // The middleware guards every route, so callers that never hold a session
- // cookie must pass without needing a per-route exclusion.
describe('callers that carry no session cookie', () => {
it('should allow a third-party webhook POST sending no Origin', () => {
const request = buildRequest({
diff --git a/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.ts b/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.ts
index 31b4445792f..91aee3118af 100644
--- a/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.ts
+++ b/packages/twenty-server/src/engine/middlewares/cookie-session-csrf.middleware.ts
@@ -11,10 +11,7 @@ import { isRequestOriginAllowed } from 'src/engine/core-modules/user-session/uti
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
-// Only guards requests that would authenticate through the session cookie,
-// since Bearer headers are never attached cross-site. SameSite=Lax already
-// blocks cross-site POSTs; checking Origin closes the sibling-subdomain gap,
-// which is same-site and so not covered by Lax.
+// Origin covers the same-site sibling-subdomain gap SameSite=Lax leaves; Bearer headers are never sent cross-site
@Injectable()
export class CookieSessionCsrfMiddleware implements NestMiddleware {
constructor(
@@ -28,8 +25,7 @@ export class CookieSessionCsrfMiddleware implements NestMiddleware {
return next();
}
- // Any other Authorization scheme still falls through to cookie auth, so it
- // must not skip the check.
+ // Other Authorization schemes still fall through to cookie auth, so they must not skip the check
if (
isNonEmptyString(this.jwtWrapperService.extractJwtFromRequest()(request))
) {
@@ -46,9 +42,7 @@ export class CookieSessionCsrfMiddleware implements NestMiddleware {
const origin = request.headers.origin;
- // Fails closed on a missing Origin: browsers send it on every unsafe
- // request, so its absence is either a non-browser client, which belongs on
- // a Bearer token, or a stripped header we cannot tell from a forgery.
+ // Fail closed: browsers always send Origin on unsafe requests, so its absence can't be told from a forgery
if (
isNonEmptyString(origin) &&
isRequestOriginAllowed({
diff --git a/packages/twenty-server/src/engine/middlewares/middleware.service.ts b/packages/twenty-server/src/engine/middlewares/middleware.service.ts
index 94b13f229c6..415ade0ed11 100644
--- a/packages/twenty-server/src/engine/middlewares/middleware.service.ts
+++ b/packages/twenty-server/src/engine/middlewares/middleware.service.ts
@@ -165,10 +165,7 @@ export class MiddlewareService {
try {
data = await this.accessTokenService.validateTokenByRequest(request);
} catch (error) {
- // Clearing is a response side effect, never a reason to swallow: letting
- // the request continue unauthenticated builds the schema without the
- // workspace, so the client gets "Cannot query field" instead of an auth
- // error and never learns its session was revoked.
+ // Never swallow: continuing unauthenticated yields "Cannot query field" instead of an auth error
this.clearDeadSessionCookie(request, error);
throw error;
diff --git a/packages/twenty-server/src/engine/subscriptions/event-stream.resolver.ts b/packages/twenty-server/src/engine/subscriptions/event-stream.resolver.ts
index 3e4482adfac..9a1c2f8fadf 100644
--- a/packages/twenty-server/src/engine/subscriptions/event-stream.resolver.ts
+++ b/packages/twenty-server/src/engine/subscriptions/event-stream.resolver.ts
@@ -150,8 +150,7 @@ export class EventStreamResolver {
},
);
- // Events are published once per workspace, so the locale can only be
- // applied here, where the subscriber is known.
+ // Events are published once per workspace, so the locale is applied per subscriber here
iterator = mapAsyncIterator(rawIterator, async (payload) => ({
...payload,
metadataEvents:
diff --git a/packages/twenty-server/src/engine/subscriptions/metadata-event/metadata-event-publisher.ts b/packages/twenty-server/src/engine/subscriptions/metadata-event/metadata-event-publisher.ts
index 4339e806fd5..c50c2687e53 100644
--- a/packages/twenty-server/src/engine/subscriptions/metadata-event/metadata-event-publisher.ts
+++ b/packages/twenty-server/src/engine/subscriptions/metadata-event/metadata-event-publisher.ts
@@ -72,10 +72,8 @@ export class MetadataEventPublisher {
});
}
- // An unowned private workflow stays workspace-wide on purpose: the read path
- // opens it to everyone once its creator has left the workspace. A version
- // whose parent is already gone is the opposite case and fails closed, since
- // the parent is deleted before its versions are published.
+ // Unowned private workflows stay workspace-wide on purpose, as the read path opens them once the creator leaves;
+ // versions whose parent is gone fail closed, since a parent is deleted before its versions are published
private async resolveRecipientUserWorkspaceIdsByRecordId({
metadataName,
workspaceId,
diff --git a/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/__tests__/resolve-metadata-event-record.util.spec.ts b/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/__tests__/resolve-metadata-event-record.util.spec.ts
index c4421914ec6..340d17f5ef2 100644
--- a/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/__tests__/resolve-metadata-event-record.util.spec.ts
+++ b/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/__tests__/resolve-metadata-event-record.util.spec.ts
@@ -43,8 +43,6 @@ describe('resolveMetadataEventRecord', () => {
expect(resolved.isPinned).toBe(true);
});
- // The whole point of resolving at delivery: an override is workspace-authored
- // text, so it wins over the catalog rather than being hashed against it.
it('should prefer an override over the translated base value', () => {
const resolved = resolveMetadataEventRecord({
metadataName: 'pageLayoutTab',
@@ -87,9 +85,7 @@ describe('resolveMetadataEventRecord', () => {
expect(resolved.name).toBe('My custom view');
});
- // Regression: delivery strips `overrides`, so anything it does not apply is
- // lost. The publisher used to apply every overridable property, not just the
- // translatable ones.
+ // Delivery strips `overrides`, so any it does not apply is lost
it('should apply an override on a non-translatable property', () => {
const resolved = resolveMetadataEventRecord({
metadataName: 'pageLayoutTab',
@@ -132,9 +128,6 @@ describe('resolveMetadataEventRecord', () => {
expect(resolved).not.toHaveProperty('overrides');
});
- // viewField is the one overridable entity with nothing translatable. Its
- // overrides used to be flattened by the publisher instead, which meant two
- // mechanisms resolving the same thing for different entities.
it('should apply overrides for an entity that has nothing translatable', () => {
const resolved = resolveMetadataEventRecord({
metadataName: 'viewField',
diff --git a/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/interpolate-navigation-command-menu-item-event.util.ts b/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/interpolate-navigation-command-menu-item-event.util.ts
index c9fbb1a5592..cf2cb3d58ff 100644
--- a/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/interpolate-navigation-command-menu-item-event.util.ts
+++ b/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/interpolate-navigation-command-menu-item-event.util.ts
@@ -16,9 +16,7 @@ type InterpolatableCommandMenuItemRecord = Record<string, unknown> & {
const INTERPOLATED_FIELDS = ['label', 'shortLabel', 'icon'] as const;
-// NAVIGATION items are the only ones whose placeholders name another entity,
-// and the label that fills them is the target object's -- which is locale
-// dependent, so this runs at delivery on already-resolved values.
+// Runs at delivery because the target object label filling the placeholders is locale dependent
export const interpolateNavigationCommandMenuItemEvent = ({
record,
flatObjectMetadataMaps,
diff --git a/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/resolve-metadata-event-record.util.ts b/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/resolve-metadata-event-record.util.ts
index 877b5c2a638..d53c6ef3c3e 100644
--- a/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/resolve-metadata-event-record.util.ts
+++ b/packages/twenty-server/src/engine/subscriptions/metadata-event/utils/resolve-metadata-event-record.util.ts
@@ -32,9 +32,7 @@ export const resolveMetadataEventRecord = ({
const resolved: Record<string, unknown> = { ...baseRecord };
- // Overridable-but-not-translatable properties are not all strings --
- // pageLayoutTab.position is a number, commandMenuItem.isPinned a boolean --
- // so they pass through as they are rather than through the resolver.
+ // Non-translatable overridable properties may be numbers or booleans, so they bypass the resolver
for (const property of overridableProperties) {
if (
property === TRANSLATIONS_OVERRIDE_KEY ||
diff --git a/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts b/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts
index 5e91563954a..368e0226125 100644
--- a/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts
+++ b/packages/twenty-server/src/engine/subscriptions/object-record-event/object-record-event-publisher.ts
@@ -421,9 +421,7 @@ export class ObjectRecordEventPublisher {
});
}
- // The cache keeps soft-deleted applications, so absence is not enough.
- // An application that has gone away is not one declaring no role: falling
- // back to the user alone would widen a stream that is already open.
+ // The cache keeps soft-deleted applications; a gone one must not fall back to the user alone and widen the stream
const application = findActiveFlatApplicationById(
permissionsContext.flatApplicationMaps,
applicationId,
diff --git a/packages/twenty-server/src/engine/subscriptions/utils/create-subscription-authorization.ts b/packages/twenty-server/src/engine/subscriptions/utils/create-subscription-authorization.ts
index 9e5db8e55fb..24c645e103b 100644
--- a/packages/twenty-server/src/engine/subscriptions/utils/create-subscription-authorization.ts
+++ b/packages/twenty-server/src/engine/subscriptions/utils/create-subscription-authorization.ts
@@ -1,7 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
-// Share in-flight checks and short-lived successes per subscription. A failed
-// check remains terminal so a buffered event cannot outlive a revoked grant.
+// A failed check stays terminal so a buffered event cannot outlive a revoked grant
export const createSubscriptionAuthorization = ({
check,
maxAgeMs,
diff --git a/packages/twenty-server/src/engine/subscriptions/utils/with-async-iterator-authorization.ts b/packages/twenty-server/src/engine/subscriptions/utils/with-async-iterator-authorization.ts
index 0b62a1cb991..c9085c5bb4f 100644
--- a/packages/twenty-server/src/engine/subscriptions/utils/with-async-iterator-authorization.ts
+++ b/packages/twenty-server/src/engine/subscriptions/utils/with-async-iterator-authorization.ts
@@ -1,5 +1,4 @@
-// Authorize after waiting for the next event: a grant may be revoked while
-// next() is blocked, including when the underlying transport buffered data.
+// Authorize after next() resolves: a grant may be revoked while it is blocked
export const withAsyncIteratorAuthorization = <TValue>({
iterator,
authorize,
diff --git a/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.ts b/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.ts
index 3f9a68da541..1f6597f80ac 100644
--- a/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.ts
+++ b/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.ts
@@ -10,14 +10,8 @@ export type WorkspaceBroadcastEvent = {
after?: Record<string, unknown>;
diff?: Record<string, unknown>;
};
- // Restricts delivery to streams whose authContext.userWorkspaceId is in this
- // list. Omit for workspace-wide events (shared metadata like views, objects,
- // fields). Set for user-scoped entities so other users in the same
- // workspace don't receive them.
+ // Set for user-scoped entities so other users in the workspace don't receive them
recipientUserWorkspaceIds?: string[];
- // Restricts delivery to streams whose user holds this settings permission
- // flag. Metadata events are workspace-wide by default; entities whose
- // existence is itself gated (workflows) set this so the channel cannot
- // leak them to users who cannot read them.
+ // Set when an entity's existence is itself gated (workflows) so the channel cannot leak it
requiredPermissionFlag?: PermissionFlagType;
};
diff --git a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts
index af445631788..0ba4d76bea3 100644
--- a/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/datasource/workspace-data-source.service.ts
@@ -25,9 +25,7 @@ import {
} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-// node-postgres parses a `date` column into a JS Date (which serializes with a
-// time component). Workspace DATE fields are date-only, so parse them as the raw
-// 'YYYY-MM-DD' string Postgres returns, matching the v1 TypeORM datasource.
+// Workspace DATE fields are date-only: keep Postgres's raw 'YYYY-MM-DD' instead of a JS Date, like the v1 datasource
const DATE_ONLY_POOL_TYPES: PoolConfig['types'] = {
getTypeParser: ((oid: number, format?: unknown) =>
oid === types.builtins.DATE
diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/types/query-builder.type.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/types/query-builder.type.ts
index 0dfe2b87baf..b84ceabc06c 100644
--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/types/query-builder.type.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/types/query-builder.type.ts
@@ -30,8 +30,7 @@ export const isWhereFactoryLike = (
condition !== null &&
typeof (condition as WhereFactoryLike).whereFactory === 'function';
-// Compares prototype depth, not identity: an object literal built in another
-// realm, such as an integration test file, has its own Object.prototype.
+// Compares prototype depth, not identity: an object from another realm (e.g. a test file) has its own Object.prototype
export const isObjectWhereLike = (
condition: unknown,
): condition is ObjectWhereLike => {
diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/utils/apply-mutation-criteria.util.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/utils/apply-mutation-criteria.util.ts
index 2d4f844eb47..f8a5409cc15 100644
--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/utils/apply-mutation-criteria.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/utils/apply-mutation-criteria.util.ts
@@ -16,8 +16,7 @@ export type MutationCriteria =
| ObjectWhereLike
| ObjectWhereLike[];
-// A where object with no key filters nothing, so the mutation would reach
-// every row of the table.
+// An empty where object would make the mutation reach every row
const assertWhereObjectFilters = (whereObject: ObjectWhereLike): void => {
if (Object.keys(whereObject).length === 0) {
throw new TwentyOrmException(
diff --git a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts
index d65e7d4eba2..622a551102b 100644
--- a/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/query-builder/workspace-select-query-builder.ts
@@ -774,8 +774,7 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {
);
}
- // Row-level permission predicates are injected on the select path only, so an
- // EXISTS rendered here would filter the related table with no predicate at all.
+ // Row-level permission predicates are injected on the select path only, so an EXISTS here would be unfiltered
if (this.existsFilterClauses.length > 0) {
throw new TwentyOrmException(
`A mutation cannot carry a relation filter; rewrite the filter as an "id IN (subquery)" predicate first`,
@@ -847,8 +846,7 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {
return this;
}
- // Dropping a condition it cannot read would widen the query, and a
- // delete to every row.
+ // Dropping an unreadable condition would widen the query, or make a delete hit every row
if (typeof condition !== 'string') {
throw new TwentyOrmException(
'A where condition must be a SQL string, a where object or a where factory',
@@ -949,10 +947,7 @@ export class WorkspaceSelectQueryBuilder implements WhereExpressionLike {
return { sql: conditions.join(' AND '), parameters };
}
- // Registers a correlated EXISTS on a relation and returns the token to place
- // in a where clause; the caller writes the related table's condition on the
- // nested builder, whose alias names that table. Unlike a join, an EXISTS never
- // duplicates root rows, so this is how a to-many relation gets filtered.
+ // EXISTS rather than a join so filtering a to-many relation never duplicates root rows
addRelationExistsFilter({
relationFieldName,
applyWhere,
diff --git a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
index 4f2f25cc441..04a816c23d8 100644
--- a/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/repository/workspace-repository.ts
@@ -129,11 +129,8 @@ type WorkspaceRepositoryOptions<TEntity extends ObjectLiteral> = {
executor: QueryExecutor;
objectRecordsPermissions: ObjectsPermissions;
shouldBypassPermissionChecks: boolean;
- // Suppresses the CREATED/UPDATED/DELETED database events this repository
- // would otherwise emit, and with them the snapshot SELECT that reads every
- // written row back to build the event payload. Only for bulk system writes
- // whose rows no subscriber cares about (campaign materialisation, backfills):
- // webhooks, workflow triggers and timeline activities will NOT fire.
+ // Suppresses database events and their snapshot SELECT, for bulk system writes only: webhooks, workflow triggers
+ // and timeline activities will NOT fire
shouldSkipEventEmission: boolean;
tableShapeByObjectMetadataId: (
objectMetadataId: string,
@@ -202,8 +199,7 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
);
}
- // TypeORM drops undefined properties before it validates or writes anything;
- // strip them here so they neither throw on an unknown field nor bind as NULL
+ // Strip undefined like TypeORM does, so they neither throw as unknown fields nor bind as NULL
private formatWriteData(
data: Partial<ObjectRecord>,
): Record<string, unknown> {
@@ -225,8 +221,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
this.applyRowLevelPermissionPredicates(queryBuilder, kind);
}
- // Capability reads use the same validators and SQL predicates as a mutation,
- // without performing a no-op write or emitting record events.
async findRecordIdsAllowedForOperation({
recordIds,
operationType,
@@ -1460,11 +1454,8 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
.withDeleted();
}
- // Re-parenting a child, or creating one under a parent, is a write on that
- // parent: the destination must grant the caller at least READ_WRITE. The
- // records inheriting through a row are checked on the row before and after
- // the write, whatever the write is, since creating, changing, deleting or
- // restoring the row changes what they expose
+ // Re-parenting or creating under a parent is a write on that parent, so the destination must grant READ_WRITE
+ // Inheriting records are checked before and after any write, since creating, changing, deleting or restoring the row changes what they expose
private async validateInheritedParentsAreWritableOrThrow({
writtenRecords,
affectedRecords,
@@ -2128,8 +2119,6 @@ export class WorkspaceRepository<TEntity extends ObjectLiteral = ObjectRecord> {
});
}
- // Records of an object whose readability keeps them out of the API are never
- // readable here, whatever the caller's role or grants
isReadDeniedByReadability(): boolean {
const subject = this.resolveRowAccessPolicySubject();
diff --git a/packages/twenty-server/src/engine/twenty-orm/upgrade-aware/upgrade-aware-repository.proxy.ts b/packages/twenty-server/src/engine/twenty-orm/upgrade-aware/upgrade-aware-repository.proxy.ts
index 2a1c6638f17..2bac6c0fa43 100644
--- a/packages/twenty-server/src/engine/twenty-orm/upgrade-aware/upgrade-aware-repository.proxy.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/upgrade-aware/upgrade-aware-repository.proxy.ts
@@ -164,8 +164,7 @@ const stripUnavailableSelect = (
return options;
};
-// A skipped update never reaches the driver, so the counts TypeORM would have
-// filled in have to be stated rather than left undefined: no rows matched.
+// A skipped update never reaches the driver, so state the no-match counts TypeORM would have filled in
const buildSkippedUpdateResult = (): UpdateResult => {
const updateResult = new UpdateResult();
@@ -371,8 +370,7 @@ const handleRepositoryMethodCall = <Entity extends object>({
args[1],
);
- // Nothing the caller asked to write exists at this cursor, and TypeORM
- // rejects an empty value set, so report the no-op instead of running it.
+ // TypeORM rejects an empty value set, so report the no-op instead
if (
updateValues !== args[1] &&
Object.keys(updateValues as Record<string, unknown>).length === 0
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-result.util.spec.ts b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-result.util.spec.ts
index 24c83451927..fae4f9aed72 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-result.util.spec.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/__tests__/format-result.util.spec.ts
@@ -125,9 +125,7 @@ describe('formatResult', () => {
expect(firstInvocationMetadataLookupCount).toBeGreaterThan(0);
expect(firstInvocationMetadataLookupCount).toBeLessThanOrEqual(4);
- // Field maps derived from a metadata snapshot are memoized by object
- // identity, so a second invocation only re-runs the lookups when it receives
- // fresh snapshot objects
+ // Field maps are memoized by snapshot identity, so only fresh snapshot objects re-run the lookups
const rebuiltFlatFieldMetadataMaps = buildFlatEntityMaps([
companyNameFieldMetadata,
companyPeopleFieldMetadata,
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts
index b39cf79365e..e495f020972 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/build-row-access-policy.util.ts
@@ -22,8 +22,7 @@ export const buildRowAccessPolicy = ({
}
const context = { subject, environment };
- // Inherited write access must respect the parent's writability as well as
- // its grants; otherwise a child can become writable through a SYSTEM parent.
+ // Inherited writes also need the parent's writability, or a child could become writable through a SYSTEM parent
if (
target.operationType !== 'select' &&
!isMetadataWritePermitted({
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/build-row-level-permission-record-filter.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/build-row-level-permission-record-filter.util.ts
index 6caa70b899d..3695a603756 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/build-row-level-permission-record-filter.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/build-row-level-permission-record-filter.util.ts
@@ -143,10 +143,7 @@ const buildRecordFilterForRole = ({
workspaceMember,
});
- // A predicate bound to a workspace member value the acting principal does
- // not carry (no member, unset field, incompatible value) cannot be
- // satisfied. Dropping it would lift the restriction instead of applying
- // it, so it is kept as a branch that never matches.
+ // Dropping an unsatisfiable predicate would lift the restriction, so it becomes a never-matching branch
if (!isDefined(workspaceMemberBoundValue)) {
unsatisfiableRecordFilterIds.add(predicate.id);
}
@@ -260,8 +257,7 @@ const buildRecordFilterForRole = ({
return false;
};
- // The role filter ANDs the branches that sit outside any group, so one of
- // them being unsatisfiable leaves the role with nothing to match.
+ // Ungrouped branches are ANDed, so one unsatisfiable branch leaves the role nothing to match
const isRoleFilterUnsatisfiable =
recordFilters.some(
(recordFilter) =>
@@ -303,9 +299,7 @@ type BuildRowLevelPermissionRecordFilterArgs = Omit<
roleIds: string[];
};
-// Each role compiles on its own and the results are ANDed. Merging the raw
-// predicates first would be wrong: compilation honours only the first
-// parentless group, so one role's restrictions would vanish and widen access.
+// Roles compile separately, then AND: compilation honours only the first parentless group, so merging would widen access
export const buildRowLevelPermissionRecordFilter = ({
roleIds,
...buildRecordFilterForRoleArgs
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/compute-permission-intersection.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/compute-permission-intersection.util.ts
index e93cff1d4fa..a00cc9e65be 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/compute-permission-intersection.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/compute-permission-intersection.util.ts
@@ -4,9 +4,7 @@ import {
type RowLevelPermissionPredicate,
} from 'twenty-shared/types';
-// An intersection has no combined predicate tree to expose, since each role
-// compiles separately. Keeping a field constrained by one role alone would
-// let that role's rule cancel another role's deny in the insert guard.
+// Keeping a field constrained by one role alone would let it cancel another role's deny in the insert guard
const intersectRowLevelPermissionPredicates = (
rowLevelPermissionPredicatesPerRole: RowLevelPermissionPredicate[][],
): RowLevelPermissionPredicate[] => {
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/get-objects-permissions-from-role-permission-config.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/get-objects-permissions-from-role-permission-config.util.ts
index ecf069c81e0..43fc1abe994 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/get-objects-permissions-from-role-permission-config.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/get-objects-permissions-from-role-permission-config.util.ts
@@ -33,8 +33,7 @@ export const getObjectsPermissionsFromRolePermissionConfig = ({
return computePermissionIntersection(permissionsPerRole);
}
- // Multi-role union is unimplemented and every producer emits one role, so
- // taking the first is exact rather than lossy.
+ // Multi-role union is unimplemented and every producer emits one role, so taking the first is exact
if ('unionOf' in rolePermissionConfig) {
const roleId = rolePermissionConfig.unionOf[0];
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/resolve-role-ids-for-user.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/resolve-role-ids-for-user.util.ts
index b2925b9f6bd..159ee007e2f 100644
--- a/packages/twenty-server/src/engine/twenty-orm/utils/resolve-role-ids-for-user.util.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/resolve-role-ids-for-user.util.ts
@@ -1,7 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
-// An application acting for a user stays within that person's role and within
-// the role it declared, so permissions are the intersection of both.
+// An application acting for a user is bounded by both the user's role and its own
export const resolveRoleIdsForUser = ({
userRoleId,
applicationRoleId,
diff --git a/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/__tests__/workspace-scoped-repository.spec.ts b/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/__tests__/workspace-scoped-repository.spec.ts
index c0718f11ab7..7939887a4bf 100644
--- a/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/__tests__/workspace-scoped-repository.spec.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/__tests__/workspace-scoped-repository.spec.ts
@@ -43,8 +43,7 @@ describe('WorkspaceScopedRepository', () => {
});
describe('workspaceId guard', () => {
- // TypeORM drops `undefined` values from WHERE/criteria, so a
- // missing workspaceId would otherwise produce an unscoped query.
+ // TypeORM drops undefined from WHERE, so a missing workspaceId would run unscoped
const unscopedCalls: [string, () => unknown][] = [
['findOne', () => scoped.findOne(undefined as never, { where: {} })],
[
diff --git a/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts b/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts
index 8b2ae20750f..cf70d0ced65 100644
--- a/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts
+++ b/packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository.ts
@@ -186,9 +186,7 @@ export class WorkspaceScopedRepository<T extends WorkspaceScopedEntity> {
);
}
- // DELETE ... RETURNING hands back raw driver output, which skips the
- // hydration a find would do, so column transformers have to be applied by
- // hand: a bigint column would otherwise read back as a string.
+ // DELETE ... RETURNING skips hydration, so column transformers are applied by hand (a bigint would read as a string)
private hydrateRawRow(row: Record<string, unknown>): DeepPartial<T> {
const { driver } = this.repository.manager.connection;
@@ -211,13 +209,8 @@ export class WorkspaceScopedRepository<T extends WorkspaceScopedEntity> {
);
}
- // save / saveMany / softRemove / recover / remove are intentionally absent.
- // TypeORM's entity-based methods use only the primary key in the WHERE
- // clause, so stamping workspaceId on the entity object does not add an
- // AND workspace_id = ? guard to the SQL. A leaked entity id could act on a
- // row from a different workspace and silently reassign its workspaceId.
- // The criteria-based methods either cannot target an existing row or
- // always carry workspaceId in the WHERE clause.
+ // save/softRemove/recover/remove are intentionally absent: entity-based methods filter on the primary key only,
+ // so a leaked id could act on, and reassign, another workspace's row
insert(
workspaceId: string,
@@ -329,8 +322,7 @@ export class WorkspaceScopedRepository<T extends WorkspaceScopedEntity> {
);
}
- // TypeORM drops `undefined` values from WHERE, which would emit an
- // unscoped query.
+ // TypeORM drops undefined from WHERE, which would emit an unscoped query
private assertWorkspaceId(workspaceId: string): void {
if (
workspaceId === undefined ||
@@ -380,9 +372,7 @@ export class WorkspaceScopedRepository<T extends WorkspaceScopedEntity> {
return { workspaceId, ...clause } as FindOptionsWhere<T>;
}
- // ON CONFLICT matches on the conflict target alone. When that target does
- // not contain workspaceId, a row from another workspace can satisfy it and
- // the DO UPDATE would overwrite that row and reassign its workspaceId.
+ // ON CONFLICT matches on the target alone, so without workspaceId DO UPDATE could overwrite another workspace's row
private async assertConflictTargetsBelongToWorkspace(
workspaceId: string,
entity: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T>[],
diff --git a/packages/twenty-server/src/engine/workspace-cache/services/workspace-cache.service.ts b/packages/twenty-server/src/engine/workspace-cache/services/workspace-cache.service.ts
index 36094606644..d22cbe5e0b0 100644
--- a/packages/twenty-server/src/engine/workspace-cache/services/workspace-cache.service.ts
+++ b/packages/twenty-server/src/engine/workspace-cache/services/workspace-cache.service.ts
@@ -52,19 +52,19 @@ import {
} from 'src/engine/workspace-cache/utils/serialize-cache-blob.util';
import { sweepLocalCache } from 'src/engine/workspace-cache/utils/sweep-local-cache.util';
-const LOCAL_TTL_MS = 100; // 100ms
-const MEMOIZER_TTL_MS = 10_000; // 10 seconds
-const STALE_VERSION_TTL_MS = 5_000; // 5 seconds
-const MAX_LOCAL_STALE_VERSIONS = 5; // 5 stale versions
+const LOCAL_TTL_MS = 100;
+const MEMOIZER_TTL_MS = 10_000;
+const STALE_VERSION_TTL_MS = 5_000;
+const MAX_LOCAL_STALE_VERSIONS = 5;
// Sized against 4 GiB pods (--max-old-space-size=3500): 7,500 sat at the heap ceiling.
const MAX_LOCAL_CACHE_ENTRIES = 6_000;
const MIN_EVICT_KEYS = 100;
-const LOCAL_ENTRY_TTL_MS = 30 * 60 * 1000; // 30 minutes idle
+const LOCAL_ENTRY_TTL_MS = 30 * 60 * 1000;
const LOCAL_CACHE_SWEEP_INTERVAL_MS = 60 * 1000;
const PACKING_INTERVAL_MS = 500;
const PACKING_PONDERATION_BUDGET = 64;
const MIN_IDLE_BEFORE_PACKING_MS = 60 * 1000;
-// Per-provider entry caps, keyed by local cache key prefix (ORM graphs are ~5 MB each).
+// Per-cache-key entry caps; ORM graphs are ~5 MB each
const MAX_LOCAL_ENTRIES_BY_KEY_NAME = new Map<string, number>([
['ORMEntityMetadatas', 128],
['flatFieldMetadataMaps', 256],
@@ -317,8 +317,7 @@ export class WorkspaceCacheService implements OnModuleInit, OnModuleDestroy {
strategy: 'mint',
});
- // Clear memoizer again after recomputation to evict any stale entries
- // cached by concurrent getOrRecompute calls during the flush window.
+ // Clear again to evict entries concurrent getOrRecompute calls cached during the flush window
await this.memoizer.clearKeys(`${workspaceId}-`);
},
);
@@ -482,7 +481,6 @@ export class WorkspaceCacheService implements OnModuleInit, OnModuleDestroy {
return { redisEntries, missingInRedis };
}
- // Interleave data and hash keys for atomic fetch: [data1, hash1, data2, hash2, ...]
const allKeys = cacheKeyNames.flatMap((keyName) => {
const baseKey = this.buildCacheKey(workspaceId, keyName);
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts
index 8dc194e5c47..1441ed0e1e5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts
@@ -64,8 +64,6 @@ export const APPLE_AGENT_CHAT_CONVERSATION_SEEDS: AgentChatConversationSeed[] =
},
];
-// Conversations paused on, or already past, a question, an email or a form for Tim's
-// team to decide on.
export const AGENT_CHAT_PENDING_INPUT_THREAD_DATA_SEED_IDS = {
PENDING_QUESTIONS: '20202020-0000-4000-8000-000000000015',
PENDING_EMAIL_APPROVAL: '20202020-0000-4000-8000-000000000016',
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-calendar-target-data-seeds.constant.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-calendar-target-data-seeds.constant.ts
index 15aa931e4bc..064fb5c7546 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-calendar-target-data-seeds.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-calendar-target-data-seeds.constant.ts
@@ -6,8 +6,7 @@ import { type MessageParticipantDataSeed } from 'src/engine/workspace-manager/de
import { OPPORTUNITY_DATA_SEEDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/opportunity-data-seeds.constant';
import { PERSON_DATA_SEEDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/person-data-seeds.constant';
-// Raw seeds bypass participant reconciliation, so seeded timelines need the
-// person, company, and point-of-contact opportunity targets it would create.
+// Raw seeds bypass participant reconciliation, so the targets it would create are seeded here
type TargetColumnsDataSeed = {
targetPersonId: string | null;
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-campaign-data-seeds.constant.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-campaign-data-seeds.constant.ts
index aa2828ff4cc..d8ee6e25ac6 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-campaign-data-seeds.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/constants/message-campaign-data-seeds.constant.ts
@@ -122,8 +122,7 @@ const createEmailBodyTemplate = ({
],
});
-// The sender is the seeded email group on the workspace's verified domain, so
-// the draft can actually be sent from a freshly seeded workspace.
+// Sends from the seeded email group on the verified domain so the draft is sendable on a fresh workspace
export const getMessageCampaignDataSeeds = (
workspaceId: string,
): MessageCampaignDataSeed[] => {
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
index a9f5166f39c..7385ef21085 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
@@ -200,9 +200,8 @@ type ConversationToSeed = {
askedBy: Member;
prompt: string;
intro: string;
- // Calls made in the same step, each waiting on its own answer.
calls: SeededToolCall[];
- // Answers the first call, in a conversation that made only one.
+ // Only answers the first call
answer?: {
response: Record<string, unknown>;
reply: string;
@@ -310,9 +309,6 @@ const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [
},
];
-// Seeds Tim's conversations that wait on a question, an email or a form, or have
-// just been answered, so each card and each answered state renders without
-// calling a model.
@Injectable()
export class DevSeederAgentChatPendingInputWorkspaceService {
constructor(
@@ -368,7 +364,7 @@ export class DevSeederAgentChatPendingInputWorkspaceService {
...call,
pausingToolCall,
pendingOutput: await call.buildPendingOutput(),
- // The first call keeps the id it had when conversations made one.
+ // The first call keeps its original seed id
toolCallId: `call_${seedId(callIndex === 0 ? 'toolCall' : `toolCall${callIndex}`).replace(/-/g, '')}`,
};
}),
@@ -406,8 +402,7 @@ export class DevSeederAgentChatPendingInputWorkspaceService {
? await firstCall.pausingToolCall.complete({
output: conversation.answer.response,
context: {
- // Seeds never send anything: the email reads as sent, as it would
- // once the person's own send_email succeeded.
+ // Seeds never send anything; the email reads as sent
executeTool: async () => ({
success: true,
message: 'Email sent successfully',
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service.ts
index 81eeed0e199..789c05bd0b3 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service.ts
@@ -141,13 +141,11 @@ const getRecordSeedsBatches = (
attachmentSeeds: RecordSeedConfig['recordSeeds'],
_featureFlags?: Record<FeatureFlagKey, boolean>,
): RecordSeedConfig[][] => {
- // Participants are generated randomly, so they are built once and the
- // derived target junction seeds are computed from the same arrays.
+ // Participants are random, so the derived target seeds must come from the same arrays
const messageParticipantSeeds = getMessageParticipantDataSeeds(workspaceId);
const calendarEventParticipantSeeds =
getCalendarEventParticipantDataSeeds(workspaceId);
- // Batch 1: No dependencies
const batch1: RecordSeedConfig[] = [
{
tableName: 'workspaceMember',
@@ -171,7 +169,6 @@ const getRecordSeedsBatches = (
},
];
- // Batch 2: Depends on workspaceMember
const batch2: RecordSeedConfig[] = [
{
tableName: 'company',
@@ -185,7 +182,6 @@ const getRecordSeedsBatches = (
},
];
- // Batch 3: Depends on company
const batch3: RecordSeedConfig[] = [
{
tableName: 'person',
@@ -199,7 +195,6 @@ const getRecordSeedsBatches = (
},
];
- // Batch 4: Depends on person/company/messageList or independent
const batch4: RecordSeedConfig[] = [
{
tableName: 'opportunity',
@@ -248,7 +243,6 @@ const getRecordSeedsBatches = (
},
];
- // Batch 5: Depends on batch 4 entities
const batch5: RecordSeedConfig[] = [
{
tableName: 'noteTarget',
@@ -277,7 +271,6 @@ const getRecordSeedsBatches = (
},
];
- // Batch 6: Depends on batch 5 entities
const batch6: RecordSeedConfig[] = [
{
tableName: 'messageChannelMessageAssociation',
@@ -431,8 +424,6 @@ export class DevSeederDataService {
featureFlags,
);
- // Process batches sequentially (respecting dependencies)
- // but entities within each batch in parallel
for (const batch of batches) {
await Promise.all(
batch.map(async (recordSeedsConfig) => {
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
index 7dab5a62cd6..62412b2ed2e 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
@@ -201,9 +201,6 @@ type SeededWorkflow = {
step: WorkflowAction;
};
-// Seeds workflow runs waiting on a person, and runs whose wait is over, so
-// the run view, the paused conversations and every kind of card can be tried
-// without calling a model.
@Injectable()
export class DevSeederWorkflowPendingInputWorkspaceService {
constructor(
@@ -382,8 +379,6 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
}
}
- // Parks the run's step the way the executor parks a step that waits on a
- // person, once its conversation is recorded.
private async seedPausedRun({
workspaceId,
workflowRunId,
@@ -431,8 +426,6 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
});
}
- // Records the answer in the form's conversation as answering it would,
- // without resuming the run.
private async recordFormAnswer({
workspaceId,
workflowRunId,
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/timeline-activity-seeder.service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/timeline-activity-seeder.service.ts
index 9f7c722c6b8..df9085a90f5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/timeline-activity-seeder.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/timeline-activity-seeder.service.ts
@@ -57,11 +57,12 @@ type TimelineActivitySeedData = Pick<
| 'targetCompanyId'
| 'targetOpportunityId'
> & {
- timelineActivityTypeSnapshot: string; // JSON stringified for raw insertion
- properties: string; // JSON stringified for raw insertion
- createdAt: string; // ISO string for raw insertion
- updatedAt: string; // ISO string for raw insertion
- happensAt: string; // ISO string for raw insertion
+ // serialized (JSON or ISO strings) for raw insertion
+ timelineActivityTypeSnapshot: string;
+ properties: string;
+ createdAt: string;
+ updatedAt: string;
+ happensAt: string;
};
type ActivityTargetInfo = {
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/__tests__/standard-metadata-label-catalog.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/__tests__/standard-metadata-label-catalog.spec.ts
index 9d4f4704152..129b0507bd0 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/__tests__/standard-metadata-label-catalog.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/__tests__/standard-metadata-label-catalog.spec.ts
@@ -13,13 +13,7 @@ import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/wo
import { AUTHORED_STANDARD_METADATA_MESSAGE_IDS } from 'src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util';
import { STANDARD_TIMELINE_ACTIVITY_TYPE_DEFINITIONS } from 'src/engine/metadata-modules/timeline-activity-type/constants/standard-timeline-activity-type-definitions.constant';
-// The read path resolves every standard metadata label through
-// generateMessageId(value, `${metadataName}.${property}`), while authoring
-// repeats that context as a literal on each msg site -- lingui extraction
-// cannot evaluate a call. This spec is what pins the two together: it mints
-// the standard application and asserts the compiled catalog holds an entry at
-// the exact id the read path will compute. A missing or misspelled context on
-// any authoring site fails here instead of silently untranslating.
+// Pins each authored msg context to the generateMessageId context the read path computes: extraction cannot evaluate a call
describe('standard metadata labels reach the catalog under their context', () => {
const { allFlatEntityMaps } =
computeTwentyStandardApplicationAllFlatEntityMaps({
@@ -59,8 +53,7 @@ describe('standard metadata labels reach the catalog under their context', () =>
continue;
}
- // FIELDS_WIDGET views back the record-page fields widget; their name is
- // engine plumbing and never displayed.
+ // FIELDS_WIDGET view names are never displayed
if (
metadataName === 'view' &&
(flatEntity as Record<string, unknown>).type === 'FIELDS_WIDGET'
@@ -77,8 +70,6 @@ describe('standard metadata labels reach the catalog under their context', () =>
continue;
}
- // A value that is nothing but placeholders ({objectLabelPlural} as a
- // whole short label) has no words to translate.
if (value.replace(/\{\w+\}/g, '').trim() === '') {
continue;
}
@@ -86,12 +77,7 @@ describe('standard metadata labels reach the catalog under their context', () =>
const context = getMetadataLabelContext(metadataName, property);
const messageId = generateMessageId(value, context);
- // Translation catalogs are generated after source changes, by the
- // i18n pipeline, and are not committed alongside them. The source
- // descriptor still proves that the label uses the exact context
- // expected by the read path before that pipeline catches up: labels
- // authored through i18nLabel register their macro-computed id, and
- // timeline labels expose it on their definition.
+ // Catalogs are regenerated by the i18n pipeline after merge, so an authored descriptor id also proves the context
const sourceMessageId =
metadataName === 'timelineActivityType' && property === 'label'
? timelineActivityTypeMessageIdByLabel.get(value)
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-command-menu-item-placeholders.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-command-menu-item-placeholders.spec.ts
index 18e495d10bf..eba63e56f06 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-command-menu-item-placeholders.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-command-menu-item-placeholders.spec.ts
@@ -22,9 +22,7 @@ const AUTHORED_METADATA_LABELS = [
];
describe('authored metadata label placeholders', () => {
- // Lingui drops ICU arguments it is not given, so a placeholder outside the
- // closed vocabulary would be silently erased from the translated label
- // instead of reaching whoever can fill it.
+ // Lingui silently drops ICU arguments it is not given, so an undeclared placeholder vanishes from translated labels
it('only uses names the placeholder vocabulary declares', () => {
const usedNames = new Set(
AUTHORED_METADATA_LABELS.flatMap((label) =>
@@ -32,8 +30,7 @@ describe('authored metadata label placeholders', () => {
),
);
- // Guards the assertion below against passing vacuously if the authored
- // labels stopped carrying placeholders at all.
+ // Guards against the check below passing vacuously
expect(usedNames.size).toBeGreaterThan(0);
expect(
[...usedNames].filter(
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
index 9e9f1526bd4..d072dc6cbd0 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
@@ -1110,8 +1110,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
'numberOfSelectedRecords == 1 and noneDefined(selectedRecords, "deletedAt") and objectPermissions.canUpdateObjectRecords and featureFlags.IS_MESSAGE_CAMPAIGN_ENABLED',
- // A sent campaign is the one people re-run, so the button is only pinned
- // there; drafts keep it in the menu.
+ // Pinned only on sent campaigns, the ones people re-run; drafts keep it in the menu
conditionalPinnedExpression:
'everyEquals(selectedRecords, "status", "SENT")',
availabilityObjectMetadataUniversalIdentifier:
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/workspace-creation-only-widget-types.constant.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/workspace-creation-only-widget-types.constant.ts
index 13008bc7895..5fa99386618 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/workspace-creation-only-widget-types.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/workspace-creation-only-widget-types.constant.ts
@@ -1,12 +1,9 @@
import { WidgetType } from 'twenty-shared/types';
-// Upgrade commands build from the standard definitions, sometimes at steps that
-// run before a later upgrade adds these types to the widget type enum, so only
-// workspace creation, on a fully upgraded database, creates their widgets. A
-// type leaves this list once every version before the one adding it to the enum
-// has left TWENTY_CROSS_UPGRADE_SUPPORTED_VERSIONS.
+// Upgrade steps can run before the widget type enum holds these; drop one once every version before it
+// has left TWENTY_CROSS_UPGRADE_SUPPORTED_VERSIONS
export const WORKSPACE_CREATION_ONLY_WIDGET_TYPES: WidgetType[] = [
- // Added to the enum in 2.44
+ // Both added to the enum in 2.44
WidgetType.CHAT_THREADS,
WidgetType.CHAT,
];
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-chat-thread-target-standard-metadata.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-chat-thread-target-standard-metadata.spec.ts
index c3499f3b855..8990b6f8933 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-chat-thread-target-standard-metadata.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-chat-thread-target-standard-metadata.spec.ts
@@ -28,9 +28,7 @@ const findIndex = (
.universalIdentifier
];
-// Postgres only uses a composite btree for a predicate that matches its leading
-// columns, so which columns an index carries and in what order is part of the
-// contract the read and write paths depend on, not an implementation detail.
+// Postgres uses a composite btree only for predicates matching its leading columns, so column order is contract
const getIndexedFieldUniversalIdentifiers = (
indexName: keyof typeof STANDARD_OBJECTS.agentChatThreadTarget.indexes,
) =>
@@ -68,9 +66,8 @@ const LEGS = [
] as const;
describe('agent chat thread target workspace metadata', () => {
- // One morph id makes the legs a single polymorphic target, which is what the
- // default-relation tooling extends for custom objects. CASCADE is the only
- // thing that removes a destroyed record's links.
+ // One shared morphId is what default-relation tooling extends to custom objects;
+ // CASCADE is the only thing that removes a destroyed record's links
it.each(LEGS)(
'attaches to a $objectName through its own leg of the target morph',
({ objectName, leg, joinColumnName }) => {
@@ -111,7 +108,6 @@ describe('agent chat thread target workspace metadata', () => {
},
);
- // A second attach of the same thread to the same record must not add a row.
it.each(LEGS)(
'keeps one live link per thread and $objectName',
({ leg, uniqueIndexName }) => {
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts
index 3046b589ea4..1f2ac443195 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts
@@ -89,8 +89,6 @@ describe('agent history workspace metadata', () => {
).toMatchObject({ isUnique: false });
},
);
- // Conversations are shareable records and their record links inherit from
- // them; the rest of the history is written and read by the platform only.
const SHARED_ACCESS_POLICY_BY_OBJECT_NAME: Partial<
Record<
(typeof OBJECT_NAMES)[number],
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-message-standard-metadata.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-message-standard-metadata.spec.ts
index 6fc24292d71..b7301142e76 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-message-standard-metadata.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-message-standard-metadata.spec.ts
@@ -38,8 +38,7 @@ describe('Message standard record page build', () => {
expect(pageLayout?.objectMetadataId).toBe(messageObjectMetadata?.id);
});
- // message is not audit logged and exposes no timelineActivities relation, so
- // a timeline tab would be filtered out of every render it appears in.
+ // message is not audit logged, so a timeline tab would always be filtered out
it('lays the message record page out as a single home tab', () => {
expect(Object.keys(MESSAGE_RECORD_PAGE.tabs)).toEqual(['home']);
@@ -115,8 +114,6 @@ describe('Message standard record page build', () => {
);
});
- // without it the body renders as one clamped line, which is what made the
- // record page look empty of content
it('displays the message text over multiple rows', () => {
const textField =
allFlatEntityMaps.flatFieldMetadataMaps.byUniversalIdentifier[
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
index 51dde9eec60..bc0be47612a 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts
@@ -87,8 +87,7 @@ describe('Standard object readability', () => {
),
);
- // Its grants follow the core workflow's visibility, since the workspace
- // workflow record is not where that visibility lives.
+ // workflowRun grants follow the core workflow's visibility, which does not live on the workspace workflow record
it('declares workflowRun PRIVATE and leaves workflow and workflowVersion OPEN', () => {
expect(findStandardFlatObjectMetadata('workflowRun')).toMatchObject({
readability: MetadataReadability.PRIVATE,
@@ -111,8 +110,7 @@ describe('Standard object readability', () => {
},
);
- // A link inheriting from its record, as noteTarget does, would tell everyone
- // who can read the record which private conversations are filed under it.
+ // Inheriting from the record would reveal which private conversations are filed under it
it('resolves its thread as the only parent of an agentChatThreadTarget', () => {
expect(
resolveParents('agentChatThreadTarget').map((parent) =>
@@ -178,8 +176,6 @@ describe('Standard object readability', () => {
});
});
- // A member's chat has no run, so it reads only through its own grants, as a
- // PRIVATE thread did; a run's conversation reads as its run does.
it('resolves its workflow run as the only parent of an agentChatThread', () => {
expect(
resolveParents('agentChatThread').map((parent) =>
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.ts
index 20dff98c4db..86884397ae4 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-writability.spec.ts
@@ -7,10 +7,8 @@ const WORKSPACE_ID = '20202020-1111-4111-8111-111111111111';
const TWENTY_STANDARD_APPLICATION_ID = '20202020-2222-4222-8222-222222222222';
const NOW = '2024-01-01T00:00:00.000Z';
-// Records of these objects are only ever written by the platform itself:
-// sync bookkeeping rows, campaign sending state and workflow trigger
-// registrations. timelineActivity stays OPEN because merging records
-// reparents its rows under the caller.
+// Only the platform writes these (sync bookkeeping, campaign sending state, trigger registrations).
+// timelineActivity stays OPEN because merging records reparents its rows under the caller
const SYSTEM_WRITABILITY_STANDARD_OBJECT_NAMES = [
'agentMessage',
'agentMessagePart',
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/workspace-creation-only-widget-types.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/workspace-creation-only-widget-types.spec.ts
index 8e92269b873..f2aa5a375eb 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/workspace-creation-only-widget-types.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/workspace-creation-only-widget-types.spec.ts
@@ -15,9 +15,6 @@ const COMPANY_CONVERSATIONS_TAB =
STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS.companyRecordPage.tabs
.conversations;
-// Upgrades from before 2.31 backfill record pages from these definitions while
-// the widget type enum does not hold CHAT_THREADS yet: a single such widget in
-// them fails the whole upgrade.
describe('widget types only workspace creation builds', () => {
it('should leave chat threads widgets, and the tab they fill, out of what upgrade commands build', () => {
const allFlatEntityMaps = computeStandardFlatEntityMaps();
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts
index 7183b718dd5..37024d23a2e 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts
@@ -64,9 +64,7 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (
icon: 'IconId',
isSystem: true,
isUIEditable: false,
- // A workflow run's conversation has no owner: it is read through the
- // run. The column goes away with the owner contract step
- // (twentyhq/core-team-issues#2925).
+ // Null for workflow run conversations, read through the run; the column goes away with the owner contract step (twentyhq/core-team-issues#2925)
isNullable: true,
},
}),
@@ -519,9 +517,7 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (
),
icon: 'IconUsers',
isUIEditable: false,
- // Stays optional for a workflow run's conversation, which is read
- // through its run rather than owned. Every other thread gets an owner
- // with the owner contract step (twentyhq/core-team-issues#2925).
+ // Stays nullable for workflow run conversations, read through the run; other threads get an owner with the owner contract step (twentyhq/core-team-issues#2925)
isNullable: true,
targetObjectName: 'workspaceMember',
targetFieldName: 'agentChatThreads',
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-message-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-message-standard-flat-field-metadata.util.ts
index 9f3d41668a4..0dd382859a7 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-message-standard-flat-field-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-message-standard-flat-field-metadata.util.ts
@@ -293,9 +293,7 @@ export const buildMessageStandardFlatFieldMetadatas = ({
icon: 'IconMessage',
isNullable: true,
isUIEditable: false,
- // an email body is a block of prose, so it needs the same multi-line
- // display as calendarEvent.description rather than the single clamped
- // line a TEXT field falls back to
+ // An email body is prose, so it needs multi-line display like calendarEvent.description
settings: { displayedMaxRows: 99 },
},
standardObjectMetadataRelatedEntityIds,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util.ts
index 160782151f9..69edecc0b7e 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/i18n-label.util.ts
@@ -1,10 +1,7 @@
import { type MessageDescriptor } from '@lingui/core';
import { isNonEmptyString } from '@sniptt/guards';
-// Translation catalogs are regenerated by the i18n pipeline after source
-// changes land, so the catalog-pinning spec accepts an authored descriptor id
-// in place of a catalog entry; every standard metadata label authoring site
-// funnels through i18nLabel, which records the macro-computed ids here.
+// Lets the catalog-pinning spec accept authored ids before the i18n pipeline regenerates catalogs
export const AUTHORED_STANDARD_METADATA_MESSAGE_IDS = new Set<string>();
export const i18nLabel = (descriptor: MessageDescriptor): string => {
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
index 52684b9ac7e..7d5a824e97f 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts
@@ -53,9 +53,7 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isAuditLogged: false,
isUIEditable: true,
isUICreatable: false,
- // A conversation outside a workflow run has no parent and is read only
- // through its own grants, as a PRIVATE record is. One held by a run's
- // agent step is read by whoever reads the run.
+ // Read by whoever reads its workflow run; with no run it reads only through its own grants, like a PRIVATE record
readability: MetadataReadability.INHERITED,
readabilityParentFieldMetadataNames: ['workflowRun'],
writability: MetadataWritability.OPEN,
@@ -100,10 +98,8 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isAuditLogged: false,
isUIEditable: false,
isUICreatable: false,
- // A link is exactly as private as the conversation it files, as a
- // messageThreadTarget is for its thread, so it inherits from the thread
- // rather than from the record. It stays writable because merging
- // records re-points its legs under the caller, as for noteTarget.
+ // Inherits from the thread, not the record, so a link stays as private as the conversation. It stays
+ // writable because record merges re-point its legs under the caller, as for noteTarget
readability: MetadataReadability.INHERITED,
readabilityParentFieldMetadataNames: ['thread'],
labelIdentifierFieldMetadataName: 'id',
@@ -1647,9 +1643,7 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {
isSystem: true,
isAuditLogged: false,
isUICreatable: false,
- // A run carries its workflow's inputs and outputs, so it is exactly as
- // private as its core workflow; WorkflowRunRecordShareService writes
- // the grants.
+ // As private as its core workflow; WorkflowRunRecordShareService writes the grants
readability: MetadataReadability.PRIVATE,
labelIdentifierFieldMetadataName: 'name',
},
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-config/standard-message-list-page-layout.config.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-config/standard-message-list-page-layout.config.ts
index 01f4e41e2ab..9d947ed04f4 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-config/standard-message-list-page-layout.config.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-config/standard-message-list-page-layout.config.ts
@@ -30,8 +30,6 @@ const MEMBERS_WIDGET_PROPS = {
.universalIdentifier,
} as const;
-// Like the note and task pages, the members table sits under the fields in
-// the side panel and on mobile, and gets a tab of its own in full screen.
const MESSAGE_LIST_PAGE_TABS = {
home: {
universalIdentifier:
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-tab/build-standard-flat-page-layout-tab-metadata-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-tab/build-standard-flat-page-layout-tab-metadata-maps.util.ts
index e1d6e4756b4..f6c728ef77f 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-tab/build-standard-flat-page-layout-tab-metadata-maps.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-tab/build-standard-flat-page-layout-tab-metadata-maps.util.ts
@@ -34,7 +34,6 @@ export const buildStandardFlatPageLayoutTabMetadataMaps = ({
const tab = layout.tabs[tabTitle];
const tabWidgets = Object.values(tab.widgets);
- // A tab only excluded widgets fill would reach the page empty.
const isFilledOnlyWithExcludedWidgets =
isNonEmptyArray(tabWidgets) &&
tabWidgets.every(
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/build-standard-flat-page-layout-widget-metadata-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/build-standard-flat-page-layout-widget-metadata-maps.util.ts
index 118be38e9a8..720442a2810 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/build-standard-flat-page-layout-widget-metadata-maps.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/page-layout-widget/build-standard-flat-page-layout-widget-metadata-maps.util.ts
@@ -323,8 +323,7 @@ const buildFieldWidgetConfiguration = ({
fieldDisplayMode,
viewId: embeddedViewId,
},
- // The universal FIELD configuration carries the view universal identifier
- // under viewId, resolved to the workspace view id at migration time.
+ // viewId holds the view universal identifier until migration resolves it
universalConfiguration: {
configurationType: WidgetConfigurationType.FIELD,
fieldMetadataId: fieldUniversalIdentifier,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/compute-standard-person-view-filters.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/compute-standard-person-view-filters.util.ts
index b0f303d35a2..e0ca7eb8a8a 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/compute-standard-person-view-filters.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/compute-standard-person-view-filters.util.ts
@@ -10,9 +10,7 @@ export const computeStandardPersonViewFilters = (
args: Omit<CreateStandardViewFilterArgs<'person'>, 'context'>,
): Record<string, FlatViewFilter> => {
return {
- // Scopes the embedded members table to the people whose list membership
- // points at the list record page displaying it, the way the layout editor
- // seeds junction relation table widgets.
+ // Scopes the members table to people listed on the displayed list record, as the layout editor seeds junction widgets
messageListRecordPageMembersListMembershipsListIsCurrentRecord:
createStandardViewFilterFlatMetadata({
...args,
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/create-standard-view-filter-flat-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/create-standard-view-filter-flat-metadata.util.ts
index 8f856a449b9..477ca4af9c9 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/create-standard-view-filter-flat-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view-filter/create-standard-view-filter-flat-metadata.util.ts
@@ -11,9 +11,6 @@ import { type AllStandardObjectViewFilterName } from 'src/engine/workspace-manag
import { type AllStandardObjectViewName } from 'src/engine/workspace-manager/twenty-standard-application/types/all-standard-object-view-name.type';
import { type StandardBuilderArgs } from 'src/engine/workspace-manager/twenty-standard-application/types/metadata-standard-buillder-args.type';
-// A relation traversal filter applies the operand to a field of the related
-// records instead of the filtered field itself, e.g. people whose list
-// memberships point at the current list.
export type StandardViewFilterRelationTargetField = {
[TargetObjectName in AllStandardObjectName]: {
objectName: TargetObjectName;
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-person-views.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-person-views.util.ts
index 642d1e85159..d28952ffc92 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-person-views.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/view/compute-standard-person-views.util.ts
@@ -37,8 +37,7 @@ export const computeStandardPersonViews = (
icon: 'IconListDetails',
},
}),
- // Embedded by the members widget of the list record page, so it must stay
- // a TABLE_WIDGET view and never carry the INDEX key.
+ // Embedded by the list page members widget, so it must stay a TABLE_WIDGET view without the INDEX key
messageListRecordPageMembers: createStandardViewFlatMetadata({
...args,
objectName: 'person',
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts
index 9ad2b322e26..a27d73e6a5f 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts
@@ -117,11 +117,7 @@ const createEntityActionsBuilderTask = <T extends AllMetadataName>(
if (result.status === 'fail') {
orchestratorFailureReport[metadataName].push(...result.errors);
} else {
- // TS mapped-type invariance: writing into a generic key of a mapped
- // type widens the expected value to the intersection of all variants.
- // The runtime value is correctly typed as
- // MetadataUniversalWorkspaceMigrationActionsRecord<T>, but TS cannot
- // narrow OrchestratorActionsReport[T] on the assignment side.
+ // TS cannot narrow OrchestratorActionsReport[T] when assigning through a generic mapped-type key
orchestratorActionsReport[metadataName] =
result.actions as OrchestratorActionsReport[T];
}
@@ -170,12 +166,7 @@ export class WorkspaceMigrationBuildOrchestratorService {
workspaceMigrationWorkflowVersionActionsBuilderService: WorkspaceMigrationWorkflowVersionActionsBuilderService,
workspaceMigrationSettingsMenuItemActionsBuilderService: WorkspaceMigrationSettingsMenuItemActionsBuilderService,
) {
- // The order of this array defines the execution order of the per-entity
- // builders. Each builder may mutate `optimisticAllFlatEntityMaps`, so
- // subsequent builders see those mutations and downstream entities depend
- // on upstream ones being processed first. Do not reorder casually.
- // The constructor parameter order above is irrelevant: NestJS DI resolves
- // dependencies by type, not by position.
+ // Execution order: builders mutate optimisticAllFlatEntityMaps that downstream builders read, so do not reorder
this.entityActionsBuilderTasksInExecutionOrder = [
createEntityActionsBuilderTask(
ALL_METADATA_NAME.objectMetadata,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-flat-entity-maps.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-flat-entity-maps.service.ts
index 7c68a98a887..2ef929a0942 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-flat-entity-maps.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-flat-entity-maps.service.ts
@@ -124,8 +124,6 @@ export class WorkspaceMigrationFlatEntityMapsService {
);
}
- // The record matrix is the canonical form; the from/to mutation helper still
- // consumes arrays, so we flatten each bucket at this boundary only.
const flatEntityToCreate = Object.values(
flatEntityOperations.flatEntityToCreate,
);
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts
index d86914d583b..5ee8c6dc0bb 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts
@@ -3,8 +3,7 @@ import { type AllMetadataName } from 'twenty-shared/metadata';
import { type MetadataEntity } from 'src/engine/metadata-modules/flat-entity/types/metadata-entity.type';
import { type ExtractJsonbProperties } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/extract-jsonb-properties.type';
-// Not strictly typed: every jsonb property that may contain a serialized
-// relation has to be referenced here by hand.
+// Not strictly typed: every jsonb property holding a serialized relation must be listed by hand
export const ALL_JSONB_PROPERTIES_WITH_SERIALIZED_RELATION_BY_METADATA_NAME = {
fieldMetadata: {
settings: 'settings',
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
index 5682c1eb24a..573566f98b5 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
@@ -74,7 +74,6 @@ export const computeOrderedMigrationActions = (
...aggregatedOrchestratorActionsReport.fieldPermission.create,
...aggregatedOrchestratorActionsReport.fieldPermission.update,
- // Permission flag definitions and their role assignments.
...aggregatedOrchestratorActionsReport.rolePermissionFlag.delete,
...aggregatedOrchestratorActionsReport.permissionFlag.delete,
...aggregatedOrchestratorActionsReport.permissionFlag.create,
@@ -86,12 +85,8 @@ export const computeOrderedMigrationActions = (
...aggregatedOrchestratorActionsReport.skill.create,
...aggregatedOrchestratorActionsReport.skill.update,
- // Menu items hold a frontComponentId with onDelete: CASCADE, so one sync that
- // repoints an item onto a new component while removing the old one would lose
- // the row if the component went first: the update would then match nothing and
- // report success. Items the manifest drops go first, then the new components,
- // then the items repoint, and only then is a component nothing references left
- // deleted.
+ // Menu items CASCADE on frontComponentId, so a repointed item would be lost if its old component were deleted first:
+ // dropped items go first, then new components, then item repoints, and unreferenced components last
...aggregatedOrchestratorActionsReport.commandMenuItem.delete,
...aggregatedOrchestratorActionsReport.settingsMenuItem.delete,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.ts
index 4bf097a7562..189ae13a170 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/validate-index-where-clause.util.ts
@@ -1,5 +1,4 @@
-// Allowlist of safe WHERE clause patterns for partial indexes.
-// Any new pattern must be reviewed for SQL injection safety before being added.
+// Any new pattern must be reviewed for SQL injection before being allowlisted
const ALLOWED_INDEX_WHERE_CLAUSES = new Set([
'"deletedAt" IS NULL',
'"isHidden" = true AND "deletedAt" IS NULL',
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-index-metadata-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-index-metadata-validator.service.ts
index eb53e9a9f42..9abb3e5fa67 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-index-metadata-validator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-index-metadata-validator.service.ts
@@ -182,9 +182,7 @@ export class FlatIndexValidatorService {
(property) => property.isIncludedInUniqueConstraint,
);
- // Each MANY_TO_ONE relation, including one concrete member of a
- // morph group, owns one UUID join column that Postgres can
- // uniquely index. The inverse side has no join column.
+ // Only the MANY_TO_ONE side owns a join column Postgres can uniquely index
const isUnindexableRelation =
isMorphOrRelationUniversalFlatFieldMetadata(relatedFlatField) &&
relatedFlatField.universalSettings?.relationType !==
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/page-layout-widget/services/utils/from-universal-configuration-to-flat-page-layout-widget-configuration.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/page-layout-widget/services/utils/from-universal-configuration-to-flat-page-layout-widget-configuration.util.ts
index 1e83816b0e0..1e16b5dcfdb 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/page-layout-widget/services/utils/from-universal-configuration-to-flat-page-layout-widget-configuration.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/page-layout-widget/services/utils/from-universal-configuration-to-flat-page-layout-widget-configuration.util.ts
@@ -366,10 +366,7 @@ export const fromUniversalConfigurationToFlatPageLayoutWidgetConfiguration = ({
})
: undefined;
- // Standard views are not synced together with page layouts: an upgrade
- // step can create a widget before a later step creates the view it
- // embeds. The widget is then created without a view, which renders
- // empty until the view lands, instead of failing the whole migration.
+ // Standard views sync separately from page layouts, so a widget may precede its view and render empty until it lands
const flatView = isDefined(viewUniversalIdentifier)
? findFlatEntityByUniversalIdentifier({
flatEntityMaps: flatViewMaps,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts
index eb4021f0353..c4889da675b 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts
@@ -52,8 +52,7 @@ export const optimisticallyApplyCreateActionOnAllFlatEntityMaps = ({
flatEntity: flatAction.flatEntity,
flatEntityAndRelatedMapsToMutate: allFlatEntityMaps,
metadataName: flatAction.metadataName,
- // searchFieldMetadata is created before its parent object/fields, which
- // therefore aren't in the maps yet to back-link to.
+ // searchFieldMetadata is created before its parent object and fields
skipMissingRelatedEntities: true,
});
diff --git a/packages/twenty-server/src/filters/unhandled-exception.filter.ts b/packages/twenty-server/src/filters/unhandled-exception.filter.ts
index 1c20269301b..ae046e7bb51 100644
--- a/packages/twenty-server/src/filters/unhandled-exception.filter.ts
+++ b/packages/twenty-server/src/filters/unhandled-exception.filter.ts
@@ -7,9 +7,7 @@ import {
import { type Response } from 'express';
-// In case of exception in middleware run before the CORS middleware (eg: JSON Middleware that checks the request body),
-// the CORS headers are missing in the response.
-// This class add CORS headers to exception response to avoid misleading CORS error
+// Exceptions thrown before the CORS middleware (e.g. JSON body parsing) would otherwise lack CORS headers
@Catch()
export class UnhandledExceptionFilter implements ExceptionFilter {
// oxlint-disable-next-line typescript/no-explicit-any
@@ -22,9 +20,7 @@ export class UnhandledExceptionFilter implements ExceptionFilter {
}
// TODO: Check if needed, remove otherwise.
- // Only for a response the CORS middleware never reached. Overwriting a
- // reflected origin with the wildcard would make the browser reject a
- // credentialed request that hit an exception, hiding the real error.
+ // Only when the CORS middleware never ran: overwriting a reflected origin with * would make the browser reject a credentialed request
if (!response.getHeader('Access-Control-Allow-Origin')) {
response.header('Access-Control-Allow-Origin', '*');
response.header(
diff --git a/packages/twenty-server/src/main.ts b/packages/twenty-server/src/main.ts
index 39e6822455a..f5217e1a21a 100644
--- a/packages/twenty-server/src/main.ts
+++ b/packages/twenty-server/src/main.ts
@@ -71,7 +71,6 @@ const bootstrap = async () => {
app.use(session(getSessionStorageOptions(twentyConfigService)));
- // Apply class-validator container so that we can use injection in validators
useContainer(app.select(AppModule), { fallbackOnErrors: true });
app.useLogger(logger);
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/dtos/create-calendar-event-output.dto.ts b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/dtos/create-calendar-event-output.dto.ts
index 7563d907504..70999842bd3 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/dtos/create-calendar-event-output.dto.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/dtos/create-calendar-event-output.dto.ts
@@ -5,12 +5,10 @@ export class CreateCalendarEventOutputDTO {
@Field(() => Boolean)
success: boolean;
- // Stable cross-provider identifier; query the created event in Twenty by iCalUid.
@Field(() => String, { nullable: true })
iCalUid?: string;
- // Absent when the event reached the provider but persistence failed; the next
- // sync then recovers the record, so callers must handle it being unset.
+ // Unset when persistence failed after provider creation; the next sync recovers the record
@Field(() => String, { nullable: true })
calendarEventId?: string;
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/services/create-calendar-event.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/services/create-calendar-event.service.ts
index cafef6e830c..7b4ce7d8da8 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/services/create-calendar-event.service.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/services/create-calendar-event.service.ts
@@ -51,9 +51,7 @@ export class CreateCalendarEventService {
}
}
- // Persist the created event right away so it is immediately visible in Twenty.
- // The next provider sync reconciles it via its external id, so a persistence
- // failure here is non-fatal.
+ // Non-fatal on failure: the next provider sync reconciles the event via its external id
async persistCalendarEvent(
createdEvent: FetchedCalendarEvent,
data: ComposedCalendarEvent,
diff --git a/packages/twenty-server/src/modules/calendar/common/standard-objects/calendar-event.workspace-entity.ts b/packages/twenty-server/src/modules/calendar/common/standard-objects/calendar-event.workspace-entity.ts
index 8f1fc025762..a5864047633 100644
--- a/packages/twenty-server/src/modules/calendar/common/standard-objects/calendar-event.workspace-entity.ts
+++ b/packages/twenty-server/src/modules/calendar/common/standard-objects/calendar-event.workspace-entity.ts
@@ -26,7 +26,5 @@ export class CalendarEventWorkspaceEntity extends BaseWorkspaceEntity {
CalendarEventParticipantWorkspaceEntity[]
>;
calendarEventTargets: EntityRelation<CalendarEventTargetWorkspaceEntity[]>;
- // callRecordings reverse relation intentionally omitted from the TypeScript workspace
- // entity. It exists in standard metadata, but declaring a to-many relation here expands
- // recursive nested insert types and tips Person past TS's instantiation-depth limit.
+ // callRecordings is omitted: a to-many relation here tips Person past TS's instantiation-depth limit
}
diff --git a/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts
index 89d4216e3c4..9db87f311c0 100644
--- a/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts
+++ b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts
@@ -17,10 +17,7 @@ import { ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modu
import { GoogleApiRefreshAccessTokenService } from 'src/modules/connected-account/refresh-tokens-manager/drivers/google/services/google-api-refresh-tokens.service';
import { MicrosoftApiRefreshAccessTokenService } from 'src/modules/connected-account/refresh-tokens-manager/drivers/microsoft/services/microsoft-api-refresh-tokens.service';
-// Tokens flowing through this service can be in two states depending on
-// where they enter the pipeline. We model both shapes explicitly so the
-// type system can prevent the #20819 class of bug (mixing encrypted and
-// decrypted tokens in the same flow).
+// Encrypted and plaintext shapes are modeled separately so they cannot be mixed (#20819)
export type ConnectedAccountPlaintextTokens = {
accessToken: PlaintextString;
refreshToken: PlaintextString | null;
@@ -31,8 +28,6 @@ export type ConnectedAccountEncryptedTokens = {
refreshToken: EncryptedString | null;
};
-// Public return type of resolveTokens: always encrypted (either fresh from
-// the database or freshly re-encrypted after a refresh round-trip).
export type ConnectedAccountTokens = ConnectedAccountEncryptedTokens;
const CONNECTED_ACCOUNT_ACCESS_TOKEN_EXPIRATION = 1000 * 60 * 60;
diff --git a/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts b/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts
index 2051861c17a..8c077902108 100644
--- a/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts
+++ b/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts
@@ -65,9 +65,6 @@ export class ImapSmtpCalDavApiService {
handle: string;
userWorkspaceId: string;
workspaceId: string;
- // Caller (resolver) has already validated the input through
- // `ImapSmtpCaldavService.validateAndTestConnectionParameters`, which
- // produces fully plaintext passwords ready for re-encryption.
connectionParameters: PlaintextImapSmtpCaldavParams;
existingAccount?: ConnectedAccountEntity | null;
}): Promise<string> {
diff --git a/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts b/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts
index 2e0f79a502b..7ac93c55e12 100644
--- a/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts
+++ b/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts
@@ -214,9 +214,7 @@ export class CreateCompanyAndPersonService {
accountOwner,
);
} catch (error) {
- // Concurrent imports for the same workspace can insert the same company
- // domain or person email, and the loser hits the unique index. The
- // record it wanted exists either way.
+ // Concurrent imports can race on a unique company domain or person email; the record exists either way
if (isDuplicateEntryError(error)) {
continue;
}
@@ -340,10 +338,6 @@ export class CreateCompanyAndPersonService {
};
}
- // Stages per-personId name enrichments for existing People auto-created via
- // CALENDAR or EMAIL. Empty fields are filled from new sources (first
- // non-empty value wins across multiple contacts mapping to the same Person);
- // populated fields are never overwritten.
private computePeopleToEnrichNames(
uniqueContacts: Contact[],
shouldCreateOrRestorePeopleByHandleMap: Map<
@@ -365,8 +359,7 @@ export class CreateCompanyAndPersonService {
continue;
}
- // Soft-deleted matches are restored earlier in the same job, so the
- // enrichment UPDATE runs against an un-deleted row.
+ // Soft-deleted matches were already restored earlier in this job
const existingSource = existingPerson.createdBy?.source;
if (
diff --git a/packages/twenty-server/src/modules/dashboard/services/dashboard-duplication.service.ts b/packages/twenty-server/src/modules/dashboard/services/dashboard-duplication.service.ts
index 245a19ea992..ab28fa1b5eb 100644
--- a/packages/twenty-server/src/modules/dashboard/services/dashboard-duplication.service.ts
+++ b/packages/twenty-server/src/modules/dashboard/services/dashboard-duplication.service.ts
@@ -31,8 +31,7 @@ import {
} from 'src/modules/dashboard/exceptions/dashboard.exception';
import { DashboardWorkspaceEntity } from 'src/modules/dashboard/standard-objects/dashboard.workspace-entity';
-// A role-scoped read validates every column it selects, so reading the whole
-// row would refuse a duplication over a dashboard field it never copies
+// A role-scoped read validates every selected column, so reading the whole row would refuse over fields never copied
const DUPLICATION_SOURCE_COLUMNS: (keyof DashboardWorkspaceEntity)[] = [
'id',
'title',
@@ -110,8 +109,7 @@ export class DashboardDuplicationService {
);
}
- // The layout copy lives in the core schema, outside the dashboard
- // insert, so a caller who may not create dashboards is refused before it
+ // The layout copy lives outside the dashboard insert, so refuse before creating it
this.assertCanCreateDashboardOrThrow({
workspaceContext,
rolePermissionConfig,
@@ -189,8 +187,7 @@ export class DashboardDuplicationService {
}
}
- // The layout lives in the core schema, outside the dashboard insert, so a
- // refused or failed insert has to take the layout it was created for with it
+ // The layout lives in the core schema, outside the insert, so a refused or failed insert must remove it
private async createDuplicatedDashboardOrRollback({
originalDashboard,
newPageLayoutId,
diff --git a/packages/twenty-server/src/modules/emailing/resolvers/message-list.resolver.ts b/packages/twenty-server/src/modules/emailing/resolvers/message-list.resolver.ts
index 51f86727ee6..2a504661b73 100644
--- a/packages/twenty-server/src/modules/emailing/resolvers/message-list.resolver.ts
+++ b/packages/twenty-server/src/modules/emailing/resolvers/message-list.resolver.ts
@@ -20,8 +20,7 @@ import { DuplicatedMessageListDTO } from 'src/modules/emailing/dtos/duplicated-m
import { MessageListDuplicationService } from 'src/modules/emailing/services/message-list-duplication.service';
import { MessageListGraphqlApiExceptionFilter } from 'src/modules/emailing/utils/message-list-graphql-api-exception.filter';
-// Object permissions on the list and its memberships are checked by the
-// service, so no settings permission is required here.
+// The service checks object permissions, so no settings permission is required
@MetadataResolver()
@UseFilters(
MessageListGraphqlApiExceptionFilter,
diff --git a/packages/twenty-server/src/modules/emailing/services/message-list-duplication.service.ts b/packages/twenty-server/src/modules/emailing/services/message-list-duplication.service.ts
index 74e7fd2c700..c0a7ce93186 100644
--- a/packages/twenty-server/src/modules/emailing/services/message-list-duplication.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/message-list-duplication.service.ts
@@ -59,8 +59,7 @@ export class MessageListDuplicationService {
userWorkspaceId,
});
- // One transaction so a failed member insert never leaves a list copy
- // without its members.
+ // One transaction so a failed member insert never leaves a list copy without its members
return this.workspaceOrmManager.executeInWorkspaceContext(
() =>
this.workspaceOrmManager.runInWorkspaceTransaction((transactionScope) =>
@@ -75,8 +74,7 @@ export class MessageListDuplicationService {
);
}
- // messageList and messageListMember are system objects, for which the
- // repositories skip role permission checks, so the role is checked here.
+ // Repositories skip role checks on system objects, so the role is checked here
private async assertCanReadAndUpdateDuplicatedObjects({
workspaceId,
userWorkspaceId,
diff --git a/packages/twenty-server/src/modules/match-participant/listeners/participant-target-person.listener.ts b/packages/twenty-server/src/modules/match-participant/listeners/participant-target-person.listener.ts
index 40a391640ee..fc5116fc6da 100644
--- a/packages/twenty-server/src/modules/match-participant/listeners/participant-target-person.listener.ts
+++ b/packages/twenty-server/src/modules/match-participant/listeners/participant-target-person.listener.ts
@@ -40,8 +40,7 @@ export class ParticipantTargetPersonListener {
return;
}
- // Enrichment can attach a company long after participants were matched,
- // without changing an email address or causing another provider sync.
+ // Enrichment can attach a company long after matching, with no email change or provider sync
await this.messageQueueService.add<ReconcilePersonCompanyTargetsJobData>(
ReconcilePersonCompanyTargetsJob.name,
{ workspaceId: payload.workspaceId, personIds },
diff --git a/packages/twenty-server/src/modules/match-participant/match-participant.service.ts b/packages/twenty-server/src/modules/match-participant/match-participant.service.ts
index 02cdc534540..576b3eeed69 100644
--- a/packages/twenty-server/src/modules/match-participant/match-participant.service.ts
+++ b/packages/twenty-server/src/modules/match-participant/match-participant.service.ts
@@ -94,14 +94,11 @@ export class MatchParticipantService<
matchWith = 'workspaceMemberAndPerson',
transactionScope,
}: MatchParticipantsArgs<ParticipantWorkspaceEntity>) {
- // Desired targets derive from personId only, so a workspaceMemberOnly
- // rematch can never change them; skip the recompute in that case.
+ // Targets derive from personId only, so a workspaceMemberOnly rematch cannot change them
const shouldReconcileTargets = matchWith !== 'workspaceMemberOnly';
- // A source whose handles are not email addresses has no matching to do:
- // looking every handle up as an email would find nothing and write
- // personId back to null, erasing the identities the caller supplied. The
- // targets still have to be built, so reconcile and stop there.
+ // Sources with non-email handles only reconcile targets: matching them as emails would null out the
+ // caller-supplied personId
if (matchWith === 'targetsOnly') {
await this.participantTargetReconciliationService.reconcileParticipantTargets(
{
diff --git a/packages/twenty-server/src/modules/match-participant/participant-target-reconciliation.service.ts b/packages/twenty-server/src/modules/match-participant/participant-target-reconciliation.service.ts
index ba23141499c..b13313d6a1b 100644
--- a/packages/twenty-server/src/modules/match-participant/participant-target-reconciliation.service.ts
+++ b/packages/twenty-server/src/modules/match-participant/participant-target-reconciliation.service.ts
@@ -274,10 +274,8 @@ export class ParticipantTargetReconciliationService {
return;
}
- // Existing workspaces only gain the target junction objects once the
- // upgrade metadata sync has run; until then reconciliation must no-op so
- // message and calendar imports keep succeeding. The backfill that follows
- // the sync covers rows imported during that window.
+ // Target junction objects exist only after the upgrade metadata sync; no-op until then so imports keep
+ // succeeding, and the following backfill covers the gap
if (
!isDefined(getWorkspaceContext().objectIdByNameSingular[targetObjectName])
) {
@@ -316,8 +314,7 @@ export class ParticipantTargetReconciliationService {
existingTargets,
});
- // Targets per parent are unbounded, so write batches are re-chunked to
- // stay under the ORM's per-call record cap.
+ // Targets per parent are unbounded, so re-chunk under the ORM's per-call record cap
for (const targetsToCreateChunk of chunk(
operations.targetsToCreate,
QUERY_MAX_RECORDS,
@@ -394,8 +391,7 @@ export class ParticipantTargetReconciliationService {
where: { id: In(personIds) },
select: { id: true, companyId: true },
});
- // find() excludes soft-deleted people, so this set keeps desired targets
- // aligned with the backfill, which only joins live people.
+ // find() excludes soft-deleted people, matching the backfill which joins live people only
const livePersonIds = new Set(people.map(({ id }) => id));
const companyIdByPersonId = new Map(
people.map(({ id, companyId }) => [id, companyId]),
diff --git a/packages/twenty-server/src/modules/match-participant/utils/apply-manually-assigned-default.util.ts b/packages/twenty-server/src/modules/match-participant/utils/apply-manually-assigned-default.util.ts
index 457d5559e8f..572770e2275 100644
--- a/packages/twenty-server/src/modules/match-participant/utils/apply-manually-assigned-default.util.ts
+++ b/packages/twenty-server/src/modules/match-participant/utils/apply-manually-assigned-default.util.ts
@@ -1,8 +1,5 @@
-// API writes to target junctions are user attachments. The field default
-// covers plain inserts, but an upsert that matches an existing row (an
-// automatic row, or an exclusion tombstone being restored) only applies the
-// caller's input, so the manual provenance has to ride the input itself or
-// reconciliation will reap the row as obsolete automatic state.
+// API writes to target junctions are user attachments. An upsert matching an existing row only applies the input,
+// so manual provenance must ride it or reconciliation reaps the row as obsolete automatic state
export const applyManuallyAssignedDefault = <
TRecord extends { isManuallyAssigned?: boolean; [key: string]: unknown },
>(
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
index 6ed8f6d2c2f..1e8d1064ac3 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/aws-ses/utils/__tests__/parse-workspace-id-from-aws-ses-resource-arn.util.spec.ts
@@ -1,9 +1,7 @@
import { parseWorkspaceIdFromAwsSesResourceArn } from 'src/modules/messaging-webhooks/drivers/aws-ses/utils/parse-workspace-id-from-aws-ses-resource-arn.util';
describe('parseWorkspaceIdFromAwsSesResourceArn', () => {
- // Tenant ARNs have an AWS-assigned opaque id segment after the tenant name
- // that must be discarded; configuration-set and identity ARNs do not. A
- // single helper has to handle both shapes consistently.
+ // Tenant ARNs carry an opaque AWS id segment after the tenant name that must be discarded
it.each([
{
label: 'tenant ARN (drops the AWS-assigned tenant-id segment)',
@@ -29,10 +27,7 @@ describe('parseWorkspaceIdFromAwsSesResourceArn', () => {
).toBe('20202020-cb1b-4e35-b50f-2bbd09c3b1ee');
});
- // The prefix-check is the only guard preventing cross-tenant updates from
- // foreign SES resources hitting the same SNS topic; an empty workspaceId
- // (resource named exactly "twenty-workspace-") would otherwise produce a
- // catastrophic empty WHERE clause downstream.
+ // The prefix check alone stops foreign SES resources; an empty workspaceId would yield an empty WHERE downstream
it.each([
{
label: 'foreign prefix',
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts
index d882974774d..d7cdaf635a7 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/services/resend-webhook-driver.service.ts
@@ -101,8 +101,7 @@ export class ResendWebhookDriverService {
);
}
- // received_for carries the envelope recipients; to/cc cover mail
- // delivered through aliases or group expansion
+ // received_for has the envelope recipients; to/cc cover aliases and group expansion
const recipients = [
...(event.data?.received_for ?? []),
...(event.data?.to ?? []),
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type.ts
index d13215b146c..44138fb9fd1 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/types/resend-webhook-event-tags.type.ts
@@ -1,5 +1,4 @@
-// tags are documented as an object map but have historically also appeared
-// as { name, value } entries, so both shapes are accepted
+// Documented as an object map but historically also sent as { name, value } entries
export type ResendWebhookEventTags =
| Record<string, string>
| { name?: string; value?: string }[];
diff --git a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util.ts b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util.ts
index 53b31fd46da..e0afdb88e27 100644
--- a/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util.ts
+++ b/packages/twenty-server/src/modules/messaging-webhooks/drivers/resend/utils/verify-svix-signature.util.ts
@@ -4,9 +4,7 @@ import { isNonEmptyString } from '@sniptt/guards';
const SIGNING_SECRET_PREFIX = 'whsec_';
-// Svix signatures are an HMAC-SHA256 over `${id}.${timestamp}.${body}` keyed
-// with the base64 secret after `whsec_`, carried base64-encoded in the
-// space-separated `v1,<sig>` entries of the signature header.
+// Svix signs `${id}.${timestamp}.${body}` with HMAC-SHA256 keyed by the base64 secret after `whsec_`
export const verifySvixSignature = ({
signingSecret,
svixId,
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
index 067bae2da6b..7f0c7e9e846 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
@@ -135,10 +135,8 @@ export class ApplyMessagesVisibilityRestrictionsService {
}
}
- // The same bypass as above, resolved through the application that
- // owns the connection rather than the user who owns it. An email
- // connection carries no applicationId, so this can only ever match
- // a channel the calling application created.
+ // Same bypass as above, via the application owning the connection; email connections carry no
+ // applicationId, so this only matches channels the calling application created
if (isDefined(applicationId)) {
const connectedAccounts =
await this.connectedAccountRepository.find({
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
index 430e161219b..2050fbdd999 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
@@ -45,9 +45,7 @@ export class MessageFindManyPostQueryHook implements WorkspacePostQueryHookInsta
? authContext.user.id
: undefined;
- // An application reading its own channel has no user behind it, so without
- // this it falls through to the redaction branches and gets back
- // placeholders instead of the messages it just wrote.
+ // An application has no user behind it, so it would otherwise get redacted placeholders for its own messages
const applicationId = isApplicationAuthContext(authContext)
? authContext.application.id
: undefined;
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
index c02df4d3fcc..0cc3f11e573 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
@@ -45,9 +45,7 @@ export class MessageFindOnePostQueryHook implements WorkspacePostQueryHookInstan
? authContext.user.id
: undefined;
- // An application reading its own channel has no user behind it, so without
- // this it falls through to the redaction branches and gets back
- // placeholders instead of the messages it just wrote.
+ // An application has no user behind it, so it would otherwise get redacted placeholders for its own messages
const applicationId = isApplicationAuthContext(authContext)
? authContext.application.id
: undefined;
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service.ts
index a79267db346..38c135572c0 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/resend-inbound-email-message-source.service.ts
@@ -13,9 +13,7 @@ import { InboundEmailParserService } from 'src/modules/messaging/message-import-
import { type InboundEmailMessageSourceInterface } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source.interface';
import { type MessageWithParticipants } from 'src/modules/messaging/message-import-manager/types/message.type';
-// Resend stores received emails on their side; the reference is the received
-// email id from the email.received webhook, and the raw MIME is fetched
-// through a pre-signed download URL.
+// The reference is the email.received webhook's email id; the raw MIME is fetched through a pre-signed URL
@Injectable()
export class ResendInboundEmailMessageSourceService implements InboundEmailMessageSourceInterface {
constructor(
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/ses-s3-inbound-email-message-source.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/ses-s3-inbound-email-message-source.service.ts
index 0594365cdd5..52c5e0f3bf3 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/ses-s3-inbound-email-message-source.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/drivers/inbound-email/sources/ses-s3-inbound-email-message-source.service.ts
@@ -7,8 +7,7 @@ import { InboundEmailStorageService } from 'src/modules/messaging/message-import
import { type InboundEmailMessageSourceInterface } from 'src/modules/messaging/message-import-manager/drivers/inbound-email/sources/inbound-email-message-source.interface';
import { type MessageWithParticipants } from 'src/modules/messaging/message-import-manager/types/message.type';
-// SES receipt rules park the raw MIME message in S3; the reference is the S3
-// object key relayed through the inbound webhook notification.
+// SES receipt rules park the raw MIME in S3; the reference is the S3 object key
@Injectable()
export class SesS3InboundEmailMessageSourceService implements InboundEmailMessageSourceInterface {
constructor(
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
index 08f5bc48f34..0154e9b1a32 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
@@ -103,8 +103,7 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {
messageChannel.excludeGroupEmails &&
isGroupEmail(participant.handle);
- // Drafts are outgoing, so don't turn recipients of an
- // unsent email into CRM contacts.
+ // Drafts are outgoing, so recipients of an unsent email don't become contacts
const shouldCreateContact =
!message.isDraft &&
!!participant.handle &&
@@ -206,10 +205,7 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {
),
];
- // The matcher resolves a participant by looking its handle up as an email
- // address. On a channel whose handles are not email addresses that finds
- // nothing and writes personId back to null, discarding the identities the
- // caller supplied at save time, so those channels only reconcile targets.
+ // Matching non-email handles as emails would null out caller-supplied identities, so those channels only reconcile targets
await this.messageParticipantService.matchMessageParticipants({
participants: savedMessagesResult.savedMessageParticipants,
messageIds,
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/utils/__tests__/safe-parse-email-addresses.util.spec.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/utils/__tests__/safe-parse-email-addresses.util.spec.ts
index 5885e994355..8cb5fd7ff12 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/utils/__tests__/safe-parse-email-addresses.util.spec.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/utils/__tests__/safe-parse-email-addresses.util.spec.ts
@@ -2,8 +2,6 @@ import { safeParseEmailAddresses } from 'src/modules/messaging/message-import-ma
describe('safeParseEmailAddresses', () => {
it('should return every recipient from a multi-address header', () => {
- // Regression: previously only the first recipient survived, silently dropping
- // CCs/BCCs and additional TOs for any Gmail-synced message with >1 recipient.
expect(
safeParseEmailAddresses(
@@ -29,16 +27,14 @@ describe('safeParseEmailAddresses', () => {
});
it('should drop entries that parse without an address', () => {
- // addressparser yields entries with no `address` for tokens like a bare name —
- // those would produce participants with handle "" and break matching downstream.
+ // A bare name yields an entry with no address, which would become a participant with handle ""
expect(safeParseEmailAddresses('NoAddressHere, [email protected]')).toEqual([
{ address: '[email protected]', name: '' },
]);
});
it('should flatten RFC 5322 address groups into their members', () => {
- // Group members previously vanished: addressparser nests them under `group`
- // with no top-level address, so the filter dropped the whole entry.
+ // addressparser nests group members under `group` with no top-level address
expect(
safeParseEmailAddresses(
@@ -55,8 +51,7 @@ describe('safeParseEmailAddresses', () => {
});
it('should not split on commas inside quoted display names', () => {
- // RFC 5322 allows commas inside quoted strings — splitting on them would
- // produce a phantom recipient with a garbage address.
+ // RFC 5322 allows commas inside quoted strings
expect(
safeParseEmailAddresses('"Doe, John" <[email protected]>, [email protected]'),
).toEqual([
diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
index 9276d9e508c..b6c47035a0a 100644
--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
@@ -51,15 +51,7 @@ export class MessagingMessageParticipantService {
isDefined(participant.personId) ||
isDefined(participant.workspaceMemberId);
- // A caller that states who a participant is owns that row, so it is
- // matched on what cannot drift between deliveries: the message, the
- // handle and the role. Keying on displayName as well would make a
- // provider that renames someone — or simply omits the name on a later
- // delivery — insert a rival row instead, leaving the original behind
- // with its stale person link and the thread attached to both records.
- //
- // Callers that supply no identity keep the exact match, so the email
- // path, where the matcher fills these in afterwards, is unchanged.
+ // Caller-identified rows match on message, handle and role only: displayName can drift between deliveries
const findExisting = (participant: ParticipantWithMessageId) =>
existingParticipantsBasedOnMessageIds.find(
(existingParticipant) =>
@@ -70,8 +62,7 @@ export class MessagingMessageParticipantService {
existingParticipant.displayName === participant.displayName),
);
- // Paired once: the lookup is a scan of every existing row, and both
- // the insert list and the update list below need the same answer.
+ // Paired once: the lookup scans every existing row
const participantsWithExisting = participants.map((participant) => ({
participant,
existingParticipant: findExisting(participant),
@@ -98,11 +89,7 @@ export class MessagingMessageParticipantService {
};
});
- // A re-ingested participant whose caller now knows the person it
- // belongs to would otherwise keep its original, unlinked row forever.
- // Only callers that supply an identity can trigger this, so the email
- // path — which leaves both undefined and relies on the matcher — is
- // untouched.
+ // Without this a re-ingested participant would keep its original unlinked row forever
const identityUpdates = participantsWithExisting.flatMap(
({ participant, existingParticipant }) => {
if (
@@ -117,13 +104,7 @@ export class MessagingMessageParticipantService {
const workspaceMemberId =
participant.workspaceMemberId ??
existingParticipant.workspaceMemberId;
- // Carried along because the row is no longer matched on it: without
- // this a rename would be silently dropped on every later delivery.
- // An omitted name arrives as an empty string though, and this is
- // the only branch that writes the column back, so taking that
- // literally would erase whatever an earlier delivery supplied — a
- // caller adding a person link should not have to resend the rest
- // of the row to keep it.
+ // An omitted name arrives as '', which must not erase one an earlier delivery supplied
const displayName = isNonEmptyString(participant.displayName)
? participant.displayName
: existingParticipant.displayName;
@@ -145,9 +126,7 @@ export class MessagingMessageParticipantService {
},
);
- // One ingested batch is bounded by messages, not by participants, so
- // a conversation with many people in it can exceed what updateMany
- // accepts in a single call.
+ // Batches are bounded by messages, not participants, so they can exceed what updateMany accepts
for (const identityUpdatesChunk of chunk(
identityUpdates,
QUERY_MAX_RECORDS,
diff --git a/packages/twenty-server/src/modules/timeline/repositories/timeline-activity.repository.ts b/packages/twenty-server/src/modules/timeline/repositories/timeline-activity.repository.ts
index c25bc891bbd..1d2415e70f8 100644
--- a/packages/twenty-server/src/modules/timeline/repositories/timeline-activity.repository.ts
+++ b/packages/twenty-server/src/modules/timeline/repositories/timeline-activity.repository.ts
@@ -95,9 +95,7 @@ export class TimelineActivityRepository {
{ shouldBypassPermissionChecks: true },
);
- // Queue retries can replay an older source event after a newer one, so the
- // value is read from the source row at write time instead of trusting the
- // event snapshot: a replay then rewrites the current value, not a stale one.
+ // Queue retries can replay an older event, so read the value from the source row rather than the event snapshot
const sourceRecords = await sourceRepository.find({
select: ['id', happensAtFieldName],
where: { id: In(linkedRecordIds) },
@@ -193,8 +191,7 @@ export class TimelineActivityRepository {
const timelineActivityPropertyName =
this.getTimelineActivityPropertyName(objectSingularName);
- // Bucketed once so matching a payload stays constant time: the recent
- // window is scoped to this batch but is not capped in size.
+ // The recent window is not capped in size, so bucket it once for constant-time matching
const recentTimelineActivitiesByMergeKey = new Map<
string,
(typeof recentTimelineActivities)[number][]
@@ -372,9 +369,7 @@ export class TimelineActivityRepository {
createdAt: MoreThan(tenMinutesAgo),
};
- // The where clause is already scoped to this batch payloads and to the merge
- // window, so every candidate is fetched: taking a single row would let only
- // one payload of a multi record batch merge.
+ // Every candidate is needed: a single row would let only one payload of a multi-record batch merge
return await timelineActivityRepository.find({
where: {
...whereConditions,
diff --git a/packages/twenty-server/src/modules/timeline/services/timeline-activity-routing-plan.service.ts b/packages/twenty-server/src/modules/timeline/services/timeline-activity-routing-plan.service.ts
index e303d2d430c..38b2cbeadc6 100644
--- a/packages/twenty-server/src/modules/timeline/services/timeline-activity-routing-plan.service.ts
+++ b/packages/twenty-server/src/modules/timeline/services/timeline-activity-routing-plan.service.ts
@@ -42,8 +42,7 @@ type TimelineActivityRoutingPlan = {
resolveTimelineActivityType: TimelineActivityTypeResolver;
};
-// A routing plan holds that workspace's whole flat field metadata maps, so an
-// unbounded map grows with the number of workspaces a worker ever routes for.
+// Each plan holds a workspace's whole flat field metadata maps, so the cache must be bounded
const MAX_CACHED_WORKSPACES = 128;
@Injectable()
@@ -242,8 +241,7 @@ export class TimelineActivityRoutingPlanService {
})?.name,
)
.filter(isDefined) ?? null,
- // A field from another object would make the write path read a value
- // that is not the source record's own moment, so it is dropped here.
+ // A field from another object is not the source record's own moment
happensAtFieldName:
isDefined(happensAtFlatFieldMetadata) &&
happensAtFlatFieldMetadata.objectMetadataId ===
diff --git a/packages/twenty-server/src/modules/timeline/services/timeline-activity.service.ts b/packages/twenty-server/src/modules/timeline/services/timeline-activity.service.ts
index 3c96e2be36c..c3482474588 100644
--- a/packages/twenty-server/src/modules/timeline/services/timeline-activity.service.ts
+++ b/packages/twenty-server/src/modules/timeline/services/timeline-activity.service.ts
@@ -49,8 +49,7 @@ const hasNonEmptyDiff = (
): boolean =>
isDefined(properties.diff) && Object.keys(properties.diff).length > 0;
-// Only the diff is worth storing: the rest of an event payload is the record
-// itself, which the timeline reads live.
+// The rest of an event payload is the record itself, which the timeline reads live
const keepDiffOnly = (
properties: ObjectRecordBaseEvent['properties'],
): Pick<ObjectRecordBaseEvent['properties'], 'diff'> =>
@@ -145,8 +144,7 @@ export class TimelineActivityService {
const payloads = (
await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- // Resolved after the rule check so batches without rules, system
- // objects mostly, never pay the workspace member query.
+ // After the rule check so batches without rules skip the workspace member query
const enrichedEvents = await this.enrichEventsWithWorkspaceMemberId({
events: auditLoggedEvents,
});
@@ -178,9 +176,7 @@ export class TimelineActivityService {
await this.timelineActivityRepository.updateLinkedTimelineActivitiesHappensAt(
{
workspaceId,
- // The unfiltered events on purpose: this keeps an already written
- // row anchored to its source moment, so hiding the happensAt field
- // from the timeline must not strand linked rows at a stale time.
+ // Unfiltered on purpose: hiding happensAt from the timeline must not strand linked rows at a stale time
updates: buildLinkedTimelineActivityHappensAtSyncUpdates({
rules: sourceRules,
events,
@@ -460,8 +456,7 @@ export class TimelineActivityService {
},
);
- // The junction event is the semantic fact; this enrichment read can race
- // the transaction that created the linked record.
+ // The junction event is the fact; this enrichment read can race the transaction that created the linked record
return eventsWithJunctionRecord.map(({ event, target, sourceRecordId }) => {
const sourceRecord = sourceRecordsByRecordId.get(sourceRecordId);
diff --git a/packages/twenty-server/src/modules/timeline/utils/build-linked-timeline-activity-happens-at-sync-updates.util.ts b/packages/twenty-server/src/modules/timeline/utils/build-linked-timeline-activity-happens-at-sync-updates.util.ts
index 536d7f249d6..249c0f88254 100644
--- a/packages/twenty-server/src/modules/timeline/utils/build-linked-timeline-activity-happens-at-sync-updates.util.ts
+++ b/packages/twenty-server/src/modules/timeline/utils/build-linked-timeline-activity-happens-at-sync-updates.util.ts
@@ -13,11 +13,7 @@ export type LinkedTimelineActivityHappensAtSyncUpdate = {
linkedRecordIds: string[];
};
-// A linked activity is anchored at its source record's own moment (an email's
-// receivedAt, a calendar event's startsAt), so when that moment moves, e.g. a
-// meeting gets rescheduled, the already written activities must follow. Only
-// the changed record ids are collected here: the new value is read from the
-// source row at write time, not from the event snapshot.
+// Linked activities follow their source moment (e.g. a rescheduled meeting); the value is read at write time
export const buildLinkedTimelineActivityHappensAtSyncUpdates = ({
rules,
events,
diff --git a/packages/twenty-server/src/modules/timeline/utils/build-non-audit-logged-field-names-by-object-metadata-id.util.ts b/packages/twenty-server/src/modules/timeline/utils/build-non-audit-logged-field-names-by-object-metadata-id.util.ts
index cadca054228..e0098192dab 100644
--- a/packages/twenty-server/src/modules/timeline/utils/build-non-audit-logged-field-names-by-object-metadata-id.util.ts
+++ b/packages/twenty-server/src/modules/timeline/utils/build-non-audit-logged-field-names-by-object-metadata-id.util.ts
@@ -22,12 +22,8 @@ export const buildNonAuditLoggedFieldNamesByObjectMetadataId = (
continue;
}
- // A projection cached before the column existed carries no value at all, so
- // only an explicit false takes a field out of the timeline. The type rule
- // is not a fallback and deliberately outranks the stored flag: a position
- // diff renders blank whatever the row says, and every row predating the
- // backfill says true, whether because the pods are mid rolling deploy or
- // because run-instance-commands was invoked without --include-slow.
+ // A projection cached before the column existed has no value, so only an explicit false excludes.
+ // The type rule outranks the flag: every row predating the backfill says true.
const isAuditLogged =
flatFieldMetadata.isAuditLogged !== false &&
isAuditLoggableFieldType(flatFieldMetadata.type);
@@ -43,10 +39,7 @@ export const buildNonAuditLoggedFieldNamesByObjectMetadataId = (
nonAuditLoggedFieldNames.add(flatFieldMetadata.name);
- // computeUpdatedFieldsFromDiff appends a join column for the owning side of a
- // relation only, and spells it <name>Id even when settings.joinColumnName
- // diverges, so that is the only alias an event can carry. Excluding the
- // settings-aware spelling would miss the one the event actually has.
+ // computeUpdatedFieldsFromDiff always spells the join column <name>Id, even when settings.joinColumnName differs
if (
isMorphOrRelationFlatFieldMetadata(flatFieldMetadata) &&
flatFieldMetadata.settings?.relationType === RelationType.MANY_TO_ONE
diff --git a/packages/twenty-server/src/modules/timeline/utils/exclude-non-audit-logged-fields-from-events.util.ts b/packages/twenty-server/src/modules/timeline/utils/exclude-non-audit-logged-fields-from-events.util.ts
index 620d617b2be..a877be4ae12 100644
--- a/packages/twenty-server/src/modules/timeline/utils/exclude-non-audit-logged-fields-from-events.util.ts
+++ b/packages/twenty-server/src/modules/timeline/utils/exclude-non-audit-logged-fields-from-events.util.ts
@@ -13,10 +13,7 @@ const doesEventCarryFieldNames = ({
...(event.properties.updatedFields ?? []),
].some((fieldName) => fieldNames.has(fieldName));
-// A diff emptied by this filter yields no timeline activity at all: the rules
-// downstream drop updates that have nothing left to show. updatedFields is
-// filtered alongside it because the relation rules read that list instead of
-// the diff, and the two have to agree on what the event touched.
+// updatedFields is filtered too because the relation rules read it instead of the diff
export const excludeNonAuditLoggedFieldsFromEvents = ({
events,
nonAuditLoggedFieldNames,
diff --git a/packages/twenty-server/src/modules/timeline/utils/resolve-linked-record-cached-name.util.ts b/packages/twenty-server/src/modules/timeline/utils/resolve-linked-record-cached-name.util.ts
index 5b00a1d669b..c243648a882 100644
--- a/packages/twenty-server/src/modules/timeline/utils/resolve-linked-record-cached-name.util.ts
+++ b/packages/twenty-server/src/modules/timeline/utils/resolve-linked-record-cached-name.util.ts
@@ -5,8 +5,6 @@ import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/typ
import { type OrmFlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/orm-flat-field-metadata.type';
import { type TimelineActivityRule } from 'src/modules/timeline/types/timeline-activity-rule.type';
-// Shared so both event streams label a linked record the same way, including
-// composite label identifiers such as a person full name.
export const resolveLinkedRecordCachedName = ({
rule,
record,
diff --git a/packages/twenty-server/src/modules/timeline/utils/resolve-timeline-activity-happens-at.util.ts b/packages/twenty-server/src/modules/timeline/utils/resolve-timeline-activity-happens-at.util.ts
index 7ae1cfd863d..65c338614c1 100644
--- a/packages/twenty-server/src/modules/timeline/utils/resolve-timeline-activity-happens-at.util.ts
+++ b/packages/twenty-server/src/modules/timeline/utils/resolve-timeline-activity-happens-at.util.ts
@@ -41,10 +41,7 @@ export const parseLinkedTimelineActivityHappensAt = (
value: unknown,
): Date | undefined => parseTimestamp(value);
-// Synced records carry their own moment in time: an email happened when it was
-// received and a calendar event when it starts, not when a sync or a late
-// participant match wrote the row. The timeline activity type declares which
-// source field holds that moment; the rule resolves it to a field name.
+// Synced records anchor at their own moment (email received, event start), not when a sync wrote the row
export const resolveLinkedTimelineActivityHappensAt = ({
event,
ruleAction,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/__tests__/workflow-version-validation.exception.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/__tests__/workflow-version-validation.exception.spec.ts
index da8c56a9e95..2e8f5e06c70 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/__tests__/workflow-version-validation.exception.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/__tests__/workflow-version-validation.exception.spec.ts
@@ -12,7 +12,6 @@ const issue = (message: string): WorkflowValidationIssue => ({
message,
});
-// The toast renders the descriptor, so what it will say is what i18n._ returns.
const userMessageOf = (exception: WorkflowVersionValidationException): string =>
i18n._(exception.userFriendlyMessage);
@@ -45,8 +44,6 @@ describe('WorkflowVersionValidationException', () => {
expect(userMessageOf(exception)).toContain('has nothing to classify');
});
- // A step with a dozen broken fields would otherwise push the first thing to
- // fix off the end of the toast.
it('should show the first few reasons and count the rest', () => {
const exception = new WorkflowVersionValidationException(
WorkflowVersionValidationExceptionCode.MALFORMED_WORKFLOW_VERSION,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/workflow-version-validation.exception.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/workflow-version-validation.exception.ts
index ab70b84fb06..1271156f725 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/workflow-version-validation.exception.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/exceptions/workflow-version-validation.exception.ts
@@ -10,8 +10,7 @@ export enum WorkflowVersionValidationExceptionCode {
NON_ACTIVABLE_WORKFLOW_VERSION = 'NON_ACTIVABLE_WORKFLOW_VERSION',
}
-// A long list would fill the toast and bury the first thing to fix, and the
-// rest are still in the exception's own message for the logs.
+// More would bury the first thing to fix; the full list stays in the logged message
const MAX_ISSUES_SHOWN_TO_USER = 3;
const describeIssuesForUser = (issues: WorkflowValidationIssue[]): string => {
@@ -24,8 +23,7 @@ const describeIssuesForUser = (issues: WorkflowValidationIssue[]): string => {
return remaining > 0 ? `${shown} (+${remaining} more)` : shown;
};
-// The reasons are interpolated rather than summarised away: "malformed" alone
-// leaves someone hunting a field across every step of the workflow.
+// Reasons are interpolated: "malformed" alone leaves someone hunting a field across every step
const getWorkflowVersionValidationExceptionUserFriendlyMessage = (
code: WorkflowVersionValidationExceptionCode,
issues: WorkflowValidationIssue[],
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-classify-step.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-classify-step.util.spec.ts
index 09f0776412f..2554de0212d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-classify-step.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/__tests__/validate-workflow-classify-step.util.spec.ts
@@ -122,8 +122,7 @@ describe('validateWorkflowClassifyStep', () => {
).toEqual([]);
});
- // A dot would be read as structure by the variable resolver, so the answer
- // this step advertises could never be referenced.
+ // The variable resolver reads a dot as structure, so a dotted answer name could never be referenced
it('should refuse an answer name that is not a valid variable key', () => {
expect(
codesFor({
@@ -182,11 +181,7 @@ describe('validateWorkflowClassifyStep', () => {
).toEqual(['CLASSIFY_INCOMPLETE_QUESTION']);
});
- // A step should report every reason it cannot activate at once; otherwise an
- // author fixes one problem only to be told about the next.
- // An option keys its probability, so a dot in it advertises
- // {{step.answers.intent.probabilities.v1.2}}, which the resolver walks as two
- // keys. A space survives, because escapePathSegment brackets it.
+ // A dotted option advertises a probabilities path the resolver walks as two keys; escapePathSegment brackets spaces
it('should refuse a choice option whose name cannot be read back', () => {
expect(
codesFor({
@@ -225,8 +220,7 @@ describe('validateWorkflowClassifyStep', () => {
).toEqual([]);
});
- // Score probabilities are keyed by level index, so a label never becomes a
- // path segment and stays free text.
+ // Score probabilities are keyed by level index, so labels stay free text
it('should accept a score level label containing a dot', () => {
expect(
codesFor({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-classify-step.util.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-classify-step.util.ts
index 830b5f06bd1..e38264eab19 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-classify-step.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/utils/validate-workflow-classify-step.util.ts
@@ -9,8 +9,7 @@ import {
import { type WorkflowClassifyAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
-// A blank question reaches the provider as an empty instruction and fails the
-// run, so the gap is reported while the workflow can still be edited.
+// A blank question reaches the provider as an empty instruction and fails the run
const getQuestionProblem = (
question: WorkflowClassifyQuestion,
): string | undefined => {
@@ -42,9 +41,7 @@ const getQuestionProblem = (
return `has an unnamed option for "${question.name}"`;
}
- // Only for a choice: its options key the probability map, so an option named
- // this way advertises a variable the resolver reads as two keys. Score levels
- // are keyed by index, so their labels stay free.
+ // Choice options key the probability map, so a dotted option advertises a variable read as two keys
if (question.type === 'choice') {
const unreachableOption = question.criteria.find((criterion) =>
criterion.name.includes(CLASSIFY_OPTION_NAME_FORBIDDEN_CHARACTER),
@@ -55,8 +52,7 @@ const getQuestionProblem = (
}
}
- // Only for a choice: its options key a map, so a repeat drops one before the
- // model ever sees it. Score levels are positional and keep their count.
+ // Choice options key a map, so a repeat is dropped before the model sees it
if (question.type === 'choice') {
const optionNames = question.criteria.map((criterion) => criterion.name);
const duplicateName = optionNames.find(
@@ -112,15 +108,13 @@ export const validateWorkflowClassifyStep = (
});
}
- // An unnamed question is already reported above, and tracking the blank
- // would make a second one look like a duplicate of it.
+ // Already reported above; tracking the blank would flag a second one as a duplicate
if (!isNonEmptyString(question.name)) {
continue;
}
// Answers are keyed by name, so a repeat would overwrite the earlier one.
- // Checked whatever else is wrong with the question: a step gets every
- // reason it cannot activate in one pass, rather than one per fix.
+ // Checked even when the question has other problems, so a step gets every reason in one pass
if (seenNames.has(question.name)) {
issues.push({
severity: 'error',
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
index 43c99643f8f..550f2b47519 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service.ts
@@ -30,9 +30,8 @@ export class WorkflowVersionValidationWorkspaceService {
private readonly workflowMetadataReadService: WorkflowMetadataReadService,
) {}
- // Malformed content is rejected at the write chokepoint, but legacy versions
- // written before that gate can still hold some, so activation refuses both
- // the malformed and the non-activable codes.
+ // Legacy versions written before the write-time gate can still hold malformed content, so both malformed and
+ // non-activable issues are refused
async assertWorkflowVersionIsActivableOrThrow({
workspaceId,
trigger,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.ts
index 2f5597c3540..c9efd468248 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-input.type.ts
@@ -12,8 +12,7 @@ export type WorkflowActionInput = {
steps: WorkflowAction[];
context: Record<string, unknown>;
runInfo: WorkflowRunInfo;
- // Set only when the step resumes after its question was answered: the
- // conversation it continues and the log of its execution so far.
+ // Set only when the step resumes after its question was answered
resumedThreadId?: string;
previousStepLog?: WorkflowRunStepLog;
};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.ts
index 4e051a69024..f93e54f525a 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-executor-input.type.ts
@@ -4,8 +4,7 @@ export type WorkflowExecutorInput = {
workspaceId: string;
shouldComputeWorkflowRunStatus?: boolean;
executedStepsCount?: number;
- // Set only when stepIds is the one step resuming after its question was
- // answered, already claimed out of PENDING: the conversation it continues.
+ // The conversation the resumed step continues; set only when stepIds is that one step, already claimed out of PENDING
resumedThreadId?: string;
};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts
index f98220985ae..dd63ec02d75 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/is-user-facing-workflow-executor-error.util.spec.ts
@@ -67,11 +67,7 @@ describe('isUserFacingWorkflowExecutorError', () => {
expect(isUserFacingWorkflowExecutorError(error)).toBe(false);
});
- // No retry conjures a model, and reporting these as system errors buries the
- // real ones, so a misconfigured classification step is the author's to fix.
it.each([
- // What an instance with no provider configured at all raises, through
- // getDefaultModelForTier under the auto-select fallback.
AiExceptionCode.API_KEY_NOT_CONFIGURED,
AiExceptionCode.EVALUATION_MODEL_NOT_FOUND,
AiExceptionCode.EVALUATION_QUESTION_UNSUPPORTED,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.ts
index 289c4d139f4..c8bbbdd0c0b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/workflow-should-keep-running.util.spec.ts
@@ -100,8 +100,7 @@ describe('workflowShouldKeepRunning', () => {
expect(workflowShouldKeepRunning({ steps, stepInfos })).toBeTruthy();
});
- // The trigger is not a step, so nothing but the answered step's own
- // status can keep its run alive once a parallel branch has finished.
+ // The trigger is not a step, so only the answered step's own status can keep its run alive
it('an answered agent step right after the trigger waits for its resume while a parallel branch has finished', () => {
const steps = [
{ id: 'agent' } as WorkflowAction,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.ts
index 9001c60be40..e158c80a20c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.ts
@@ -20,8 +20,7 @@ export const buildStepInfosReset = ({
status: StepStatus.NOT_STARTED,
result: undefined,
error: undefined,
- // Step infos are merged on write, so a value left out here would keep
- // pointing the next iteration at the previous one's conversation.
+ // Step infos are merged on write, so an omitted value would keep the previous iteration's conversation
threadId: undefined,
history: [
...(stepInfo.history ?? []),
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util.ts
index 9b0364f9670..78fe2144eff 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/get-user-from-auth-context.util.ts
@@ -1,8 +1,7 @@
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
-// Spread into a logic function execution call: a run started by the platform
-// rather than by a person contributes nothing rather than null fields.
+// Spread into a logic function call: a platform-started run contributes nothing rather than null fields
export const getUserFromAuthContext = (
authContext: WorkspaceAuthContext,
): { userId?: string; userWorkspaceId?: string } =>
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts
index b495fda02ab..cc115be2ae8 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util.ts
@@ -18,11 +18,8 @@ const USER_FACING_STEP_EXECUTOR_EXCEPTION_CODES = [
WorkflowStepExecutorExceptionCode.STEP_NOT_FOUND,
];
-// A step asking for a model the instance does not serve, or asking it something
-// it cannot answer, is a configuration the author has to change: no retry will
-// produce a model, and reporting it as a system error buries real ones.
-// API_KEY_NOT_CONFIGURED is the one an instance with no provider at all raises,
-// from getDefaultModelForTier under the auto-select fallback.
+// Author misconfigurations: no retry produces a model, and reporting them as system errors buries real ones.
+// API_KEY_NOT_CONFIGURED is what an instance with no provider raises via getDefaultModelForTier.
const USER_FACING_AI_EXCEPTION_CODES = [
AiExceptionCode.API_KEY_NOT_CONFIGURED,
AiExceptionCode.EVALUATION_MODEL_NOT_FOUND,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index db57d8daaf3..121809ed74f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -100,8 +100,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const resolvedPrompt = resolveInput(prompt, context) as string;
- // The conversation is a record of the step, not part of its outcome, so a
- // failure to write it must not fail a step whose agent did its work.
+ // A record of the step, not its outcome, so a write failure must not fail the step
const recordConversation = (
executionResult: AgentExecutionResult,
): Promise<RecordedConversation | null> =>
@@ -171,9 +170,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const durationMs = Date.now() - startedAtMs;
- // A conversation only exists to be answered in: an execution that never
- // asks keeps its step log as its record, which saves a thread per
- // execution for agents running in loops or on busy triggers.
+ // Only executions that ask get a conversation, saving a thread per execution for looping agents
const recordedConversation =
isDefined(resumedThreadId) || executionResult.isPaused === true
? await recordConversation(executionResult)
@@ -195,8 +192,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
}
if (executionResult.isPaused === true) {
- // The conversation is where the question is answered, so without it the
- // run would wait for an answer nobody can give.
+ // Without the conversation nobody could answer, so the run would wait forever
if (recordedConversation?.isAwaitingAnswer !== true) {
return {
error: 'Agent asked a question that could not be recorded.',
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
index 9e78c59c837..78abf223094 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
@@ -38,11 +38,8 @@ export type RecordedConversation = {
isAwaitingAnswer: boolean;
};
-// A conversation is recorded only for an execution of a step that waits on a
-// person, a form or an agent that asks, and continued when that execution
-// resumes. Each gets its own, so a loop iteration or a retry never reads or
-// continues another one's messages. The conversation has no owner: it belongs
-// to the run and is readable by whoever can read the run.
+// One conversation per execution, so a loop iteration or retry never reads or continues another's messages.
+// It has no owner: it belongs to the run and is readable by whoever can read the run.
@Injectable()
export class WorkflowAgentConversationWorkspaceService {
constructor(
@@ -105,8 +102,7 @@ export class WorkflowAgentConversationWorkspaceService {
return { threadId, isAwaitingAnswer };
}
- // A form step asks for its fields the way an agent would, so it is answered
- // like any call that waits on a person. The call is named after the step.
+ // A form step is answered like any call that waits on a person
async recordFormRequest({
workspaceId,
workflowRunId,
@@ -153,8 +149,7 @@ export class WorkflowAgentConversationWorkspaceService {
);
}
- // Continues a conversation whose question has been answered: the answer is
- // already recorded as the last message, so only the agent's reply is added.
+ // The answer is already the last message, so only the agent's reply is added
async recordContinuation({
workspaceId,
threadId,
@@ -206,9 +201,7 @@ export class WorkflowAgentConversationWorkspaceService {
return convertToModelMessages(uiMessages);
}
- // A paused reply marks its conversation as waiting on its calls, all of
- // which have to be answerable: one call nobody can answer would keep the
- // step waiting forever on the others, so the step fails instead.
+ // One unanswerable call would keep the step waiting forever, so the step fails instead
private async recordReply({
workspaceId,
threadId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util.ts
index 5471b74b025..e2976a2790d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/merge-ai-agent-step-logs.util.ts
@@ -1,8 +1,7 @@
import { isDefined } from 'twenty-shared/utils';
import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
-// An agent that asked a question runs again once it is answered, and the
-// step's log has to account for every segment rather than the last one only.
+// An agent that asked a question runs again once answered, so its log spans several segments
export const mergeAiAgentStepLogs = ({
previousStepLog,
nextStepLog,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/__tests__/build-evaluation-questions.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/__tests__/build-evaluation-questions.util.spec.ts
index f2621af7e33..c0949bbecae 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/__tests__/build-evaluation-questions.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/__tests__/build-evaluation-questions.util.spec.ts
@@ -49,8 +49,7 @@ describe('buildEvaluationQuestions', () => {
});
});
- // The editor seeds every added level with description: '', so this is the
- // shape the UI actually sends, not an omitted field.
+ // The editor seeds every added level with description: ''
it('should fall back to the level label when the editor left the description empty', () => {
expect(
buildEvaluationQuestions([
@@ -115,8 +114,7 @@ describe('buildEvaluationQuestions', () => {
);
});
- // Options key a map, so a repeat would hand the model fewer choices than the
- // step declares rather than failing.
+ // A repeat would silently hand the model fewer choices than declared
it('should refuse a choice question listing the same option twice', () => {
expect(() =>
buildEvaluationQuestions([
@@ -139,8 +137,7 @@ describe('buildEvaluationQuestions', () => {
);
});
- // Score levels are positional and keep their count, so a repeated label
- // loses nothing.
+ // Score levels are positional, so a repeated label loses nothing
it('should allow a score question repeating a level label', () => {
expect(
buildEvaluationQuestions([
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/build-evaluation-questions.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/build-evaluation-questions.util.ts
index 584fadcc0cf..b463b63a7a1 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/build-evaluation-questions.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/classify/utils/build-evaluation-questions.util.ts
@@ -7,9 +7,7 @@ import {
} from 'src/engine/metadata-modules/ai/ai.exception';
import { type AiEvaluationModelQuestion } from 'src/engine/metadata-modules/ai/ai-models/types/ai-evaluation-model.type';
-// Options key an object, so a repeat would overwrite the earlier one and hand
-// the model fewer choices than the step declares — losing one silently, which
-// is worse than refusing to run.
+// Options key an object, so a repeat would silently drop a choice; refusing is better
const buildChoiceCriteria = (
question: WorkflowClassifyQuestion,
): Record<string, string | null> => {
@@ -40,10 +38,8 @@ const toEvaluationQuestion = (
criteria: buildChoiceCriteria(question),
};
case 'score':
- // A level's position is its score, so the editor's order is the rubric.
- // The label stands in when no description was written, since an unnamed
- // level tells the model nothing. The editor seeds description with an
- // empty string, so this cannot be a nullish fallback.
+ // A level's position is its score, so editor order is the rubric. The editor seeds description with '',
+ // so the name fallback cannot be nullish
return {
type: 'score',
instructions: question.instructions,
@@ -61,8 +57,7 @@ const toEvaluationQuestion = (
}
};
-// Keyed by the question's name rather than its id: the key is what downstream
-// steps reference, and a uuid would make every variable unreadable.
+// Keyed by name, not id: downstream steps reference the key, and a uuid would be unreadable
export const buildEvaluationQuestions = (
questions: WorkflowClassifyQuestion[],
): Record<string, AiEvaluationModelQuestion> => {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts
index 213fd2ed972..1702b899901 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/mail-sender/email-workflow-action.base.ts
@@ -100,11 +100,8 @@ export abstract class EmailWorkflowActionBase extends ToolBackedWorkflowAction<W
return { ...resolvedInput, connectedAccountId };
}
- // The sender configured on an email step is either a connected account id
- // (static pick) or a workspace member id (from a resolved workflow variable).
- // When it is a workspace member id, resolve that member's first connected
- // account; otherwise return it unchanged so the regular connected account
- // flow applies. Only meaningful inside workflow email actions.
+ // The sender is a connected account id or, from a workflow variable, a workspace member id; a member id resolves
+ // to that member's first connected account, anything else is returned unchanged
protected async resolveSenderConnectedAccountId(
senderId: string,
workspaceId: string,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts
index 64a7514f255..a3622610f1d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/jobs/run-workflow.job.ts
@@ -222,9 +222,7 @@ export class RunWorkflowJob {
});
}
- // An answered step stays PENDING until here, which keeps its run from
- // completing while the resume waits in the queue. Claiming it out of PENDING
- // is what makes a second resume of the same step do nothing.
+ // The step stays PENDING until claimed here, so its run can't complete while queued and a second resume no-ops
private async resumeAnsweredStep({
workflowRunId,
stepToResume: { stepId, threadId },
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index 925e3afa1a4..c42c77cb76c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
@@ -117,8 +117,7 @@ export class WorkflowRunWorkspaceService {
enqueuedAt: status === WorkflowRunStatus.ENQUEUED ? new Date() : null,
});
- // A run is a private record written by the system, so nobody reads it
- // until it carries its workflow's grants.
+ // A run is a private system-written record, so nobody reads it until it carries its workflow's grants
await this.workflowRunRecordShareService.syncRuns({
workspaceId,
workflowRunIds: [id],
@@ -207,9 +206,8 @@ export class WorkflowRunWorkspaceService {
await this.updateWorkflowRun({ workflowRunId, workspaceId, partialUpdate });
- // A run that ends can no longer consume an answer, so the calls its
- // conversations wait on are closed. This is housekeeping: the run is over
- // either way, and a failure here only leaves a call that looks waiting.
+ // An ended run cannot consume answers, so close the calls its conversations wait on.
+ // Best effort: a failure only leaves a call that looks waiting.
if (
Object.values(workflowRunToUpdate.state?.stepInfos ?? {}).some(
(stepInfo) => isDefined(stepInfo?.threadId),
@@ -281,9 +279,7 @@ export class WorkflowRunWorkspaceService {
await this.updateWorkflowRun({ workflowRunId, workspaceId, partialUpdate });
}
- // Built from the persisted step info rather than the executor's snapshot:
- // the attempt that just failed recorded its conversation while it ran, and
- // only the stored step info carries it into the history entry.
+ // Built from persisted step info: only it carries the failed attempt's conversation
@WithLock('workflowRunId')
async moveStepToRetry({
stepId,
@@ -373,9 +369,7 @@ export class WorkflowRunWorkspaceService {
});
}
- // Written from the state read under the lock rather than from the caller's
- // snapshot, or a step-info write that landed in between, such as an accepted
- // form submission, would be put back as it was.
+ // Written from the locked state, or a concurrent step-info write (e.g. a form submission) would be reverted
@WithLock('workflowRunId')
async markWorkflowRunAsStopping({
workflowRunId,
@@ -419,13 +413,9 @@ export class WorkflowRunWorkspaceService {
return true;
}
- // A step waiting on a person must move on exactly once. This shares the lock
- // every step-info write takes, so of two concurrent callers the second finds
- // the step no longer PENDING. A stop is refused too: endWorkflowRun turns a
- // pending step into FAILED, and a stop still waiting on another branch
- // leaves the run STOPPING with the step PENDING but nothing left to resume.
- // An expected conversation must still be the step's: a retry or another loop
- // iteration replaces it.
+ // Shares the step-info write lock so of two concurrent callers the second finds the step no longer PENDING.
+ // A stop is refused: endWorkflowRun fails a pending step, or leaves it PENDING with nothing to resume.
+ // expectedThreadId must still be the step's: a retry or another loop iteration replaces it.
@WithLock('workflowRunId')
async updateStepInfoIfPending({
stepId,
@@ -474,9 +464,7 @@ export class WorkflowRunWorkspaceService {
return true;
}
- // A run conversation names no step: it belongs to the step whose current
- // execution recorded it, so one replaced by a retry or a later loop
- // iteration belongs to no step anymore.
+ // A conversation replaced by a retry or a later loop iteration belongs to no step
async findStepAwaitingAnswer({
threadId,
workflowRunId,
@@ -674,8 +662,7 @@ export class WorkflowRunWorkspaceService {
workflowRunId: string;
workspaceId: string;
}): Promise<void> {
- // An answer holding a conversation's claim decides its calls: it closes
- // them itself once it finds the run over.
+ // An answer holding a conversation's claim closes its calls itself once it finds the run over
const waitingThreads = await this.threadRepository.find(workspaceId, {
where: {
workflowRunId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
index 50d8e7f9213..448b8317b90 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
@@ -93,9 +93,7 @@ export class WorkflowRunnerWorkspaceService {
);
}
- // Called once every call a step's conversation waits on is answered: a
- // form step completes with its answer, while an agent step stays PENDING
- // until the resume job claims it and continues its conversation.
+ // A form step completes with its answer; an agent step stays PENDING until the resume job claims it
async resumeAnsweredStep({
workspaceId,
workflowRunId,
@@ -217,8 +215,7 @@ export class WorkflowRunnerWorkspaceService {
}
}
- // Release the cached not-started slot only after the stop has been
- // persisted, so a persistence failure can't desync the throttle counter.
+ // Only after the stop is persisted, so a persistence failure can't desync the throttle counter
if (wasNotStarted) {
await this.workflowThrottlingWorkspaceService.decreaseWorkflowRunNotStartedCount(
workspaceId,
@@ -305,8 +302,7 @@ export class WorkflowRunnerWorkspaceService {
buildRunWorkflowJobOptions(workflowRunId),
);
} catch (error) {
- // The job couldn't be enqueued: revert to the previous failed state so
- // the run isn't left stuck as RUNNING without a worker job.
+ // Revert so the run isn't left RUNNING without a worker job
await this.workflowRunWorkspaceService.updateWorkflowRun({
workflowRunId,
workspaceId,
diff --git a/packages/twenty-server/src/modules/workspace-member/query-hooks/workspace-member-delete-one.post-query.hook.ts b/packages/twenty-server/src/modules/workspace-member/query-hooks/workspace-member-delete-one.post-query.hook.ts
index 07562ca46ae..41a86813a90 100644
--- a/packages/twenty-server/src/modules/workspace-member/query-hooks/workspace-member-delete-one.post-query.hook.ts
+++ b/packages/twenty-server/src/modules/workspace-member/query-hooks/workspace-member-delete-one.post-query.hook.ts
@@ -105,8 +105,7 @@ export class WorkspaceMemberDeleteOnePostQueryHook implements WorkspacePostQuery
workspaceId: workspace.id,
});
- // Runs after the membership is gone so a failed removal keeps the history
- // and threads created during the removal are still cleaned up.
+ // After the membership is gone, so a failed removal keeps the history and racing threads are cleaned too
await this.agentChatThreadRepository.delete(workspace.id, {
workspaceMemberId: workspaceMember.id,
});
diff --git a/packages/twenty-server/src/utils/__test__/get-field-metadata-entity.mock.ts b/packages/twenty-server/src/utils/__test__/get-field-metadata-entity.mock.ts
index 955e3cbdfaf..2c313fe1dcc 100644
--- a/packages/twenty-server/src/utils/__test__/get-field-metadata-entity.mock.ts
+++ b/packages/twenty-server/src/utils/__test__/get-field-metadata-entity.mock.ts
@@ -16,7 +16,7 @@ type GetMockFieldMetadataEntityOverride<
Pick<FieldMetadataEntity<T>, 'workspaceId' | 'objectMetadataId' | 'type'>
>;
-// Should be renamed to abstract
+// TODO: rename to abstract
export const getMockFieldMetadataEntity = <
T extends FieldMetadataType = FieldMetadataType.TEXT,
>(
diff --git a/packages/twenty-server/src/utils/get-request-base-url.util.ts b/packages/twenty-server/src/utils/get-request-base-url.util.ts
index fe033a11587..fd4332cb50d 100644
--- a/packages/twenty-server/src/utils/get-request-base-url.util.ts
+++ b/packages/twenty-server/src/utils/get-request-base-url.util.ts
@@ -1,5 +1,5 @@
import { type Request } from 'express';
-// Absolute origin the request arrived on (honors Express `trust proxy`).
+// Honors Express `trust proxy`
export const getRequestBaseUrl = (request: Request): string =>
`${request.protocol}://${request.get('host')}`;
diff --git a/packages/twenty-server/src/utils/stream-size-exceeded-error.ts b/packages/twenty-server/src/utils/stream-size-exceeded-error.ts
index 66dc569a82e..6e208f5e39e 100644
--- a/packages/twenty-server/src/utils/stream-size-exceeded-error.ts
+++ b/packages/twenty-server/src/utils/stream-size-exceeded-error.ts
@@ -1,5 +1,4 @@
-// Callers that cap a read need to tell "too big" apart from a storage failure
-// without matching on a message, so they can map it to their own domain error.
+// Lets callers tell "too big" from a storage failure without matching on a message
export class StreamSizeExceededError extends Error {
constructor(maxSizeBytes: number) {
super(`Stream exceeds maximum allowed size of ${maxSizeBytes} bytes`);
diff --git a/packages/twenty-server/test/integration/ai/suites/mcp-tool-catalog.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/mcp-tool-catalog.integration-spec.ts
index 1adf9b1ac89..c625b748097 100644
--- a/packages/twenty-server/test/integration/ai/suites/mcp-tool-catalog.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/mcp-tool-catalog.integration-spec.ts
@@ -52,11 +52,8 @@ const getToolCatalog = async (
const READ_ONLY_TOOL_NAME_PATTERN = /^(find_|list_|get_|search_)/;
-// Dispatch-layer failures come from execute_tool gating or the registry
-// (unknown or unavailable tool), not from the executed tool itself. Their
-// exact wording is pinned by the "should report unknown tools as dispatch
-// failures" control test below, so drift fails loudly instead of silently
-// weakening the catalog contract.
+// Dispatch failures come from execute_tool gating or the registry, not the tool itself; their exact wording is
+// pinned by the unknown-tools control test below, so drift fails loudly
const DISPATCH_FAILURE_MESSAGE_PATTERN =
/^Tool ".+" (not found|is not available)$/;
@@ -77,10 +74,7 @@ const isDispatchFailure = (result: {
);
};
-// Deliberate exceptions to the "every advertised category is dispatchable
-// through a read-only tool" contract. Currently none: every category the MCP
-// catalog advertises ships at least one read-only tool. Adding a category
-// here must be a conscious decision, not silent drift.
+// Adding a category here must be a conscious decision, not silent drift
const EXPECTED_CATEGORIES_WITHOUT_READ_ONLY_TOOLS: string[] = [];
const listMcpTools = async (
@@ -223,8 +217,7 @@ describe('MCP tool catalog (integration)', () => {
.slice(0, 3);
if (readOnlyCandidates.length === 0) {
- // A write-only category has nothing safe to dispatch in CI; it is
- // collected and checked against the deliberate exception list below.
+ // A write-only category has nothing safe to dispatch in CI
categoriesWithoutReadOnlyTool.push(category);
continue;
}
@@ -237,10 +230,7 @@ describe('MCP tool catalog (integration)', () => {
arguments: {},
});
- // Called with empty arguments, a resolved tool may legitimately
- // return a structured failure (isError true since the MCP layer
- // surfaces success: false); only a dispatch-layer failure means the
- // category is advertised but not actually wired up.
+ // A tool may return a structured failure on empty arguments; only a dispatch failure means it is unwired
if (!isDispatchFailure(result)) {
dispatched = true;
break;
@@ -253,8 +243,7 @@ describe('MCP tool catalog (integration)', () => {
});
}
- // Exact equality fails in both directions, so gaining or losing a
- // skipped category forces a deliberate update of the exception list.
+ // Exact equality so gaining or losing a skipped category forces updating the exception list
expect([...categoriesWithoutReadOnlyTool].sort()).toEqual(
EXPECTED_CATEGORIES_WITHOUT_READ_ONLY_TOOLS,
);
@@ -295,8 +284,7 @@ describe('MCP tool catalog (integration)', () => {
expect(allToolNames).not.toEqual(expect.arrayContaining(['create_role']));
- // The restricted role still sees record read tools, proving the empty
- // ROLE category is gating rather than a broken catalog.
+ // Proves the empty ROLE category is gating rather than a broken catalog
expect(catalog[ToolCategory.DATABASE_CRUD]?.length).toBeGreaterThan(0);
});
});
diff --git a/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts
index 302e75a1630..7b4ff0acea5 100644
--- a/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/ai/suites/mcp-tool-execution.integration-spec.ts
@@ -166,9 +166,7 @@ describe('MCP tool execution (integration)', () => {
format: 'uuid',
});
- // Morph relations must be exposed as `${name}Id` UUIDs (the join column),
- // not as the relation name typed as string — the data-arg-processor only
- // accepts the join-column form for write operations.
+ // Morph relations must be exposed as `${name}Id` UUIDs: the data-arg-processor only accepts that form for writes
expect(resolveProperty(properties?.targetCompanyId)).toMatchObject({
type: 'string',
format: 'uuid',
@@ -255,8 +253,6 @@ describe('MCP tool execution (integration)', () => {
createdCompanyBId = companyB.id;
- // Two targets on company A, one on company B — the grouped counts
- // we'll assert against later.
const targetCompanyIds = [
createdCompanyAId,
createdCompanyAId,
@@ -314,8 +310,6 @@ describe('MCP tool execution (integration)', () => {
expect(groupByItems).toBeDefined();
- // Each groupBy variant is { [columnName]: true }. Collect every column
- // the schema offers so we can assert on the morph-relation columns.
const groupByColumns = new Set<string>();
if (groupByItems?.anyOf) {
@@ -353,8 +347,6 @@ describe('MCP tool execution (integration)', () => {
{
groupBy: [{ targetCompanyId: true }],
aggregateOperation: 'COUNT',
- // Scope to the noteTargets we created so other seeded rows don't
- // leak into the counts.
noteId: { in: createdNoteIds },
},
);
diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
index 7fc6ad4bfad..2b46c136b65 100644
--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
@@ -139,9 +139,7 @@ describe('Admin credit grant and revoke (integration)', () => {
expect(grants[0].expiresAt).toBeNull();
});
- // Rounded up to a period end rather than the exact day: credits are spent and
- // settled a period at a time, so a deadline inside one would be invisible to
- // both the cached counter and the carry-forward.
+ // Credits settle a period at a time, so a mid-period deadline would be invisible to the counter and carry-forward
it('expires a time-boxed grant at the end of the period the requested day falls in', async () => {
const response = await grantCredits({
workspaceId,
@@ -156,9 +154,7 @@ describe('Admin credit grant and revoke (integration)', () => {
const [storedGrant] = await listCreditGrants(workspaceId);
- // Which period the thirtieth day lands in depends on when the suite runs,
- // so the boundary is derived the same way the server derives it rather
- // than listed.
+ // The boundary depends on when the suite runs, so derive it like the server does
const expectedExpiresAt = alignGrantExpiryToPeriodEnd({
requestedExpiresAt: addDays(new Date(), 30),
currentPeriodStart: PERIOD_START,
@@ -246,9 +242,7 @@ describe('Admin credit grant and revoke (integration)', () => {
expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
- // The panel only offers the three operator types, but the mutation is
- // reachable directly and these two are written by the period transition and
- // the onboarding jobs.
+ // The panel offers three operator types, but the mutation is reachable directly and jobs write these two
it.each([
BillingCreditGrantType.ROLLOVER,
BillingCreditGrantType.ONBOARDING_REWARD,
@@ -280,9 +274,7 @@ describe('Admin credit grant and revoke (integration)', () => {
expect(await listCreditGrants(workspaceId)).toHaveLength(0);
});
- // The admin panel keeps one operation id per open modal, so an Apollo retry
- // or a resubmit after a lost response must answer with the grant the first
- // attempt wrote rather than crediting the workspace a second time.
+ // The admin panel reuses one operation id per open modal, so a retry must not credit twice
it('answers a retried grant with the original instead of granting twice', async () => {
const clientOperationId = randomUUID();
const variables = {
@@ -304,9 +296,7 @@ describe('Admin credit grant and revoke (integration)', () => {
expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();
});
- // The refusal to time-box a grant with no billing period must not reach a
- // replay: the subscription that anchored the original deadline can be gone by
- // the time the client retries, and the operation already succeeded.
+ // The anchoring subscription can be gone by retry time, and the operation already succeeded
it('answers a retried time-boxed grant after the subscription is canceled', async () => {
const clientOperationId = randomUUID();
const variables = {
diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
index b3fffdb8f17..379e17e7581 100644
--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
@@ -19,9 +19,7 @@ import { type BillingUsageService } from 'src/engine/core-modules/billing/servic
const client = request(`http://localhost:${APP_PORT}`);
-// Whole calendar months, anchored so the period the transition opens is the
-// one running right now. The ledger filters on now(), so periods fixed in the
-// past would read as expired and assert nothing.
+// The ledger filters on now(), so periods fixed in the past would read as expired and assert nothing
const PERIOD_BOUNDARY = startOfMonth(new Date());
const CLOSING_PERIOD_START = subMonths(PERIOD_BOUNDARY, 1);
const CLOSING_PERIOD_END = PERIOD_BOUNDARY;
@@ -70,9 +68,7 @@ describe('Billing credit rollover (integration)', () => {
creditAmountMicro: ALLOWANCE_MICRO,
});
- // Usage is read from ClickHouse, whose inserts are asynchronous. Stubbing
- // the read keeps every expectation exact instead of racing ingestion; the
- // query itself has its own unit coverage.
+ // ClickHouse inserts are asynchronous, so the read is stubbed rather than racing ingestion
usageSpy = jest.spyOn(billingUsageService, 'getCreditsUsedBetweenOrNull');
});
@@ -99,8 +95,7 @@ describe('Billing credit rollover (integration)', () => {
revokedAt: null,
});
expect(new Date(grants[0].effectiveAt)).toEqual(CLOSING_PERIOD_END);
- // Successors carry no deadline: stamping the next period end would put the
- // balance back at the mercy of the transition after this one running.
+ // Stamping the next period end would expose the balance to the following transition
expect(grants[0].expiresAt).toBeNull();
});
@@ -145,8 +140,7 @@ describe('Billing credit rollover (integration)', () => {
expect(compensation).toBeDefined();
- // Its expiry was pulled back to the boundary, so the balance counts it
- // once through its carried-forward copy rather than twice.
+ // Pulled back to the boundary, so the balance counts it once through its carried-forward copy
expect(compensation?.expiresAt).toEqual(CLOSING_PERIOD_END);
expect(
grants.some(
@@ -182,7 +176,6 @@ describe('Billing credit rollover (integration)', () => {
).toBe(ALLOWANCE_MICRO);
});
- // A redelivery must not hand out the credits a second time.
it('is idempotent when Stripe redelivers the same invoice', async () => {
usageSpy.mockResolvedValue(300_000);
@@ -198,8 +191,7 @@ describe('Billing credit rollover (integration)', () => {
).toBe(afterFirst.reduce((total, grant) => total + grant.amountMicro, 0));
});
- // Returning normally would answer 200 and Stripe would never redeliver, so
- // the transition would be lost and the balance would expire unrolled.
+ // Returning normally would answer 200 and Stripe would never redeliver
it('fails the webhook when usage cannot be read so Stripe redelivers', async () => {
usageSpy.mockResolvedValue(null);
@@ -211,9 +203,7 @@ describe('Billing credit rollover (integration)', () => {
it('drops the allowance counter on the period transition', async () => {
usageSpy.mockResolvedValue(300_000);
- // The counter is keyed by the period the subscription is currently in,
- // which is the one the invoice is closing: Stripe moves the subscription
- // forward in a separate event.
+ // Stripe advances the subscription in a separate event, so the counter is keyed by the closing period
await warmAllowanceCounter(workspaceId, CLOSING_PERIOD_START, 120_000);
await postInvoiceFinalized().expect(200);
@@ -236,10 +226,7 @@ describe('Billing credit rollover (integration)', () => {
).toBeNull();
});
- // A subscription anchored on the 31st runs January 31 to February 28. Once
- // the subscription.updated webhook has moved the subscription on, calendar
- // arithmetic clamps February 28 back to January 28 and the closing period
- // swallows three days of the period before it.
+ // A 31st anchor runs Jan 31 to Feb 28; once advanced, calendar arithmetic clamps Feb 28 back to Jan 28 and swallows three days
describe('a month-end anchor whose subscription already advanced', () => {
const MONTH_END_BOUNDARY = new Date('2026-02-28T00:00:00.000Z');
const TRUE_CLOSING_PERIOD_START = new Date('2026-01-31T00:00:00.000Z');
@@ -253,8 +240,7 @@ describe('Billing credit rollover (integration)', () => {
periodEnd: MONTH_END_NEXT_PERIOD_END,
creditAmountMicro: ALLOWANCE_MICRO,
});
- // What the previous transition left behind: a grant closed at the instant
- // the period it belonged to ended.
+ // What the previous transition left: a grant closed at the end of its period
await insertCreditGrant({
workspaceId,
amountMicro: 100_000,
diff --git a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
index 234470014d8..370c483526f 100644
--- a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
+++ b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
@@ -6,11 +6,7 @@ import { type SubscriptionStatus } from 'src/engine/core-modules/billing/enums/b
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
-// The dev seeder gives every workspace a billingCustomer and an active
-// billingSubscription, but no subscription item, and no period. Rollover needs
-// the whole chain — subscription -> item -> product -> price with a
-// credit_amount — so these helpers finish the fixture and put the period where
-// the test wants it.
+// The dev seeder creates no subscription item or period; rollover needs subscription -> item -> product -> price
export const TEST_STRIPE_CUSTOMER_ID = 'cus_default0';
export const TEST_STRIPE_SUBSCRIPTION_ID = 'sub_default0';
@@ -33,8 +29,7 @@ export type CreditGrantRow = {
const query = async <T>(sql: string, params: unknown[] = []): Promise<T[]> =>
global.testDataSource.query(sql, params);
-// The billing seeds insert with orIgnore, so the customer and subscription
-// land on exactly one workspace and which one is not worth hardcoding.
+// Billing seeds insert with orIgnore, so which workspace holds them is not worth hardcoding
export const getSeededBillingWorkspaceId = async (): Promise<string> => {
const [row] = await query<{ workspaceId: string }>(
`SELECT "workspaceId" FROM core."billingSubscription" WHERE "stripeSubscriptionId" = $1`,
@@ -237,9 +232,7 @@ export const resetBillingCreditState = async (
}
};
-// Cancelling is what makes getCurrentBillingSubscription stop returning it, so
-// this is how a test reaches the no-subscription path without deleting rows the
-// rest of the suite shares.
+// Cancelling stops getCurrentBillingSubscription returning it without deleting rows the suite shares
export const setSubscriptionStatus = async (
workspaceId: string,
status: SubscriptionStatus,
diff --git a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util.ts b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util.ts
index 431b4c0e221..1ace65bc24c 100644
--- a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util.ts
+++ b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util.ts
@@ -1,6 +1,4 @@
-// Typed to what the handler actually reads rather than to Stripe.Invoice: the
-// payload crosses the wire as JSON, so the runtime shape is what matters, and
-// a full Stripe.Invoice fixture would be a few hundred lines of noise.
+// Typed to what the handler reads, not Stripe.Invoice: a full fixture would be hundreds of lines of noise.
export type MockStripeInvoiceFinalizedData = {
object: {
id: string;
@@ -27,10 +25,7 @@ export const createMockStripeInvoiceFinalizedData = ({
stripeSubscriptionId = 'sub_default0',
billingReason = 'subscription_cycle',
invoiceId = 'in_test_default',
- // Stripe raises a cycle invoice at the handover, which for an advance-stamped
- // one is the period it opens. The boundary is resolved off this rather than
- // off our own clock, so a fixture that leaves it out no longer models the
- // handover at all.
+ // The handler resolves the period boundary from the invoice's created time, not our clock.
createdAt = periodStart,
}: {
periodStart: Date;
@@ -47,8 +42,6 @@ export const createMockStripeInvoiceFinalizedData = ({
billing_reason: billingReason,
created: toUnixSeconds(createdAt),
customer: stripeCustomerId,
- // The invoice for a subscription_cycle bills the period it opens, so its
- // period_start is the instant the previous period closed.
period_start: toUnixSeconds(periodStart),
period_end: toUnixSeconds(periodEnd),
parent: {
diff --git a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts
index 75dbbb77728..1c907436f9b 100644
--- a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts
+++ b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts
@@ -24,8 +24,7 @@ const PASSWORD = 'radicale-password';
const authorizationHeader = `Basic ${Buffer.from(`${HANDLE}:${PASSWORD}`).toString('base64')}`;
-// A sync token the server no longer recognises, which drives the fallback from
-// an incremental sync-collection report to a full re-sync.
+// An unrecognised token forces the fallback from incremental sync to a full re-sync.
const buildStaleSyncCursor = (collectionUrl: string) =>
JSON.stringify({
syncTokens: { [collectionUrl]: 'stale-sync-token' },
@@ -83,8 +82,7 @@ describe('CalDAV calendar events import (integration)', () => {
};
beforeAll(async () => {
- // The CalDAV driver wraps its fetch in the SSRF guard, which rejects the
- // container's private address before the request is made.
+ // The SSRF guard would otherwise reject the container's private address.
await updateConfigVariable({
input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },
});
diff --git a/packages/twenty-server/test/integration/constants/test-ai-model-ids.constants.ts b/packages/twenty-server/test/integration/constants/test-ai-model-ids.constants.ts
index e5d83f57242..bd55e232c20 100644
--- a/packages/twenty-server/test/integration/constants/test-ai-model-ids.constants.ts
+++ b/packages/twenty-server/test/integration/constants/test-ai-model-ids.constants.ts
@@ -1,18 +1,11 @@
import { DEFAULT_MODELS_BY_TIER } from 'src/engine/metadata-modules/ai/ai-models/utils/load-default-model-preferences.util';
-// Any registered model can back an agent, so the suites read ids from the
-// default chains rather than naming them: those lists are refreshed against the
-// models.dev catalog on a daily automerge, and a hardcoded id broke every agent
-// suite the day it dropped out of the catalog.
+// Hardcoded ids break the suites whenever the daily models.dev refresh drops them from the catalog.
export const [TEST_AI_MODEL_ID, TEST_AI_OTHER_MODEL_ID] = [
DEFAULT_MODELS_BY_TIER.fast[0],
DEFAULT_MODELS_BY_TIER.smart[0],
];
-// Two distinct ids are load-bearing: the update suites assert a transition from
-// one model to another, and would pass without testing anything if both were
-// the same. Fail at import rather than let a future list shape silently empty
-// those assertions out.
if (TEST_AI_MODEL_ID === TEST_AI_OTHER_MODEL_ID) {
throw new Error(
'The agent integration suites need two distinct default models: one to create an agent with and one to update it to. The fast and smart chains now start with the same id.',
diff --git a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts
index 7a3d48b10a1..bf0bf905e64 100644
--- a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts
@@ -519,8 +519,7 @@ describe('Admin panel global chat threads (integration)', () => {
]);
});
- // A workflow run's conversation belongs to no member, and a null owner
- // must not null out a non-null field and fail the whole list.
+ // Workflow-run conversations belong to no member; a null owner must not fail the whole list on a non-null field.
it('lists a thread without an owner', async () => {
const ownerlessThreadId = randomUUID();
diff --git a/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
index 15cff978ac4..b3f432249c4 100644
--- a/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-tool-call.integration-spec.ts
@@ -31,16 +31,12 @@ const QUESTIONS = [
},
];
-// The model is not called here: the turn that asked is written as the stream
-// job persists it, and the resumed stream is only checked for being queued.
describe('Answering a chat tool call', () => {
const threadId = randomUUID();
let chat: AgentChatService;
let enqueueStream: jest.SpyInstance;
const spies: jest.SpyInstance[] = [];
- // One assistant message that calls ask_questions once per id, as a model
- // asking several things in one step does.
const pauseOnQuestions = async (...toolCallIds: string[]) => {
const userMessage = await chat.addMessage({
workspaceId,
@@ -71,7 +67,6 @@ describe('Answering a chat tool call', () => {
})) as never,
});
- // Written in the same update as the turn's totals.
await global.testDataSource.query(
`UPDATE "${schema}"."agentChatThread" SET "pendingQuestionMessageId" = $1 WHERE id = $2`,
[assistantMessageId, threadId],
diff --git a/packages/twenty-server/test/integration/graphql/suites/application-user-role-intersection.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/application-user-role-intersection.integration-spec.ts
index 8588e8269c6..cec769c3db6 100644
--- a/packages/twenty-server/test/integration/graphql/suites/application-user-role-intersection.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/application-user-role-intersection.integration-spec.ts
@@ -33,10 +33,7 @@ const COMPANY_UNIVERSAL_IDENTIFIER =
const COMPANY_NAME_FIELD_UNIVERSAL_IDENTIFIER =
STANDARD_OBJECTS.company.fields.name.universalIdentifier;
-// The application declares a role that is strictly narrower than the admin who
-// holds the token: it may read but not update, and only sees companies whose
-// name contains "Intersection Visible". The admin has neither bound, so every
-// assertion below fails if the application's role is dropped.
+// Strictly narrower than the admin, so every assertion fails if the application's role is dropped.
const buildApplicationManifest = (): Manifest =>
buildBaseManifest({
appId: TEST_APP_UNIVERSAL_IDENTIFIER,
@@ -157,8 +154,6 @@ describe('An application acting for a user is bound by both roles', () => {
await createCompany(VISIBLE_COMPANY_ID, VISIBLE_COMPANY_NAME);
await createCompany(HIDDEN_COMPANY_ID, HIDDEN_COMPANY_NAME);
- // Minted with the admin token, so it carries that admin's userId and
- // userWorkspaceId alongside the applicationId.
const tokenPair = await generateAppleAdminApplicationTokenPair({
applicationId,
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/cookie-session/cookie-session.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/cookie-session/cookie-session.integration-spec.ts
index 246a15783fe..3120dc36e54 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/cookie-session/cookie-session.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/cookie-session/cookie-session.integration-spec.ts
@@ -15,10 +15,7 @@ const buildAppleOrigin = (): string => {
return origin.origin;
};
-// The app listens on localhost while the seeded workspace resolves from the
-// apple subdomain. Without a matching Host the server sees a cross-origin
-// request and refuses to issue the cookie, which is the behaviour under test
-// everywhere except here.
+// Without a Host matching the apple subdomain the server sees a cross-origin request and refuses the cookie.
const asWorkspaceRequest = (
agent: request.Test,
originOverride?: string,
@@ -45,9 +42,7 @@ const SIGN_OUT_MUTATION = `
}
`;
-// A workspace object rather than currentUser: workspace types only exist in the
-// schema once a workspace is bound, so a request that is allowed to continue
-// unauthenticated fails with "Cannot query field" instead of an auth error.
+// Not currentUser: workspace types only exist once a workspace is bound, so a pass-through fails with "Cannot query field".
const FIND_COMPANIES_QUERY = `
query FindCompanies {
companies(first: 1) {
@@ -187,8 +182,6 @@ describe('Cookie sessions (integration)', () => {
expect(response.body.error).toBe('CSRF_ORIGIN_MISMATCH');
});
- // Mints its own session rather than consuming the shared one, so revoking it
- // cannot break the tests above whatever order they run in.
it('should stop authenticating the cookie once signed out', async () => {
const disposableSessionCookie = await signInAndGetSessionCookie();
@@ -243,8 +236,7 @@ describe('Cookie sessions (integration)', () => {
graphQLError.extensions?.code,
);
- // The client only signs out on an auth code. A missing workspace schema
- // surfaces as "Cannot query field", which it cannot act on.
+ // The client only signs out on an auth code.
expect(messages.join(' ')).not.toContain('Cannot query field');
expect(codes.some((code: string) => AUTH_ERROR_CODES.includes(code))).toBe(
true,
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts
index 5387e80cf38..a4a63c1e1e4 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-totp.integration-spec.ts
@@ -10,8 +10,7 @@ const MINIMUM_STEP_REMAINING_MS = 5_000;
const generateTokenAtEpoch = (secret: string, epochMs: number): string =>
authenticator.clone({ epoch: epochMs }).generate(secret);
-// A previous-step token generated right before a step boundary would already be
-// two steps old once the server validates it, so wait out the boundary first
+// A previous-step token minted right before a boundary would be two steps old when validated.
const waitUntilSafelyInsideTotpStep = async (): Promise<void> => {
const millisecondsRemainingInStep =
TOTP_STEP_DURATION_MS - (Date.now() % TOTP_STEP_DURATION_MS);
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-cookie-authentication.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-cookie-authentication.integration-spec.ts
index 45277c886c8..75765d1cae2 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-cookie-authentication.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-cookie-authentication.integration-spec.ts
@@ -36,8 +36,7 @@ describe('failing session cookie authentication (integration)', () => {
});
it('should reject a session token presented as a Bearer header', async () => {
- // Cookie-only by design: accepting sess_ tokens as Bearer would reopen
- // the XSS-exfiltration surface cookie sessions close.
+ // Accepting sess_ tokens as Bearer would reopen the XSS-exfiltration surface cookie sessions close.
const response = await makeMetadataApiRequest(
currentUserIdentityQueryFactory(),
sessionToken,
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-expiration.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-expiration.integration-spec.ts
index 08dd6b38095..466d2240caf 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-expiration.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/failing-session-expiration.integration-spec.ts
@@ -15,8 +15,7 @@ import { ALLOWED_ORIGIN } from 'test/integration/graphql/suites/auth/user-sessio
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
-// Sessions created here are never resolved before the row is tampered with,
-// so the read-through cache holds no entry and the checks hit the database.
+// Never resolved before tampering, so the read-through cache is empty and checks hit the database.
describe('failing session expiration (integration)', () => {
const signInAndTamper = async (
tamper: Partial<Pick<UserSessionEntity, 'expiresAt' | 'lastActiveAt'>>,
@@ -62,8 +61,7 @@ describe('failing session expiration (integration)', () => {
});
it('should reject a session past the idle timeout and clear the cookie', async () => {
- // 31 days idle exceeds the 30d SESSION_IDLE_TIMEOUT while the absolute
- // 180d lifetime is still far in the future.
+ // Past the 30d SESSION_IDLE_TIMEOUT but well within the 180d absolute lifetime.
const sessionCookieHeader = await signInAndTamper({
lastActiveAt: new Date(Date.now() - 31 * ONE_DAY_MS),
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-cookie-delivery.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-cookie-delivery.integration-spec.ts
index 3dd3abc658b..f84d769d125 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-cookie-delivery.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-cookie-delivery.integration-spec.ts
@@ -10,12 +10,8 @@ import { USER_SESSION_SECURE_COOKIE_NAME } from 'src/engine/core-modules/user-se
import { ALLOWED_ORIGIN } from 'test/integration/graphql/suites/auth/user-sessions/constants/session-origins.constants';
import { setupDatabaseConfigOverrideForSuite } from 'test/integration/graphql/suites/auth/user-sessions/utils/setup-database-config-override.util';
-// SameSite=None forces Secure (browsers reject the combination without it),
-// which is the one secure-deployment trigger reachable at runtime: SERVER_URL
-// stays plain http in .env.test. The production combination (https SERVER_URL
-// with the SameSite=Lax default) is covered by
-// secure-deployment/suites/secure-session-cookie.integration-spec.ts under a dedicated app
-// boot.
+// SameSite=None forces Secure, the only secure-deployment trigger reachable while SERVER_URL is http in .env.test.
+// The https production case is covered by secure-deployment/suites/secure-session-cookie.integration-spec.ts.
describe('successful session cookie delivery on a secure deployment (integration)', () => {
setupDatabaseConfigOverrideForSuite('AUTH_COOKIE_SAME_SITE', 'none');
@@ -39,8 +35,6 @@ describe('successful session cookie delivery on a secure deployment (integration
throw new Error('Expected a secure session cookie');
}
- // __Host- requires Secure, Path=/ and no Domain; browsers enforce the
- // prefix contract, so the snapshot pins host-only scoping.
expect(
normalizeSessionCookieForSnapshot(secureSessionCookie.rawCookie),
).toMatchSnapshot('secure-session-cookie');
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.ts
index b1e86f82478..530fc703550 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-creation.integration-spec.ts
@@ -42,13 +42,8 @@ describe('successful user session creation on auth exchanges (integration)', ()
firstSessionToken = sessionCookie.sessionToken;
firstSessionCookieHeader = sessionCookie.cookieHeader;
- // Pins name, sess_ prefix, attribute list and order in one place. The
- // absences matter as much as the presences: no Secure and no __Host-
- // (plain-http test deployment), and no Domain, which is what makes the
- // cookie host-only so browsers never send it to sibling workspace
- // subdomains. The secure boot pins its own shape in
- // secure-deployment/suites/secure-session-cookie.integration-spec.ts, so this snapshot
- // only applies to the insecure one.
+ // Insecure boot only (plain http: no Secure, no __Host-); secure-deployment/suites/secure-session-cookie.integration-spec.ts
+ // pins the secure shape. The absences matter: no Domain keeps the cookie host-only, off sibling workspace subdomains.
if (!IS_SECURE_DEPLOYMENT) {
expect(
normalizeSessionCookieForSnapshot(sessionCookie.rawCookie),
@@ -96,15 +91,12 @@ describe('successful user session creation on auth exchanges (integration)', ()
expect(session).toMatchObject({
userId: expect.any(String),
- // Bound to the workspace the GraphQL origin selected: the server-side
- // half of workspace scoping, alongside the host-only cookie.
workspaceId: SEED_APPLE_WORKSPACE_ID,
userWorkspaceId: expect.any(String),
isImpersonating: false,
revokedAt: null,
revokedReason: null,
- // expect.any(Date) would fail: the entity's Date comes from the app's
- // vm context, so it is not an instanceof the test context's Date.
+ // Not expect.any(Date): the entity's Date comes from the app's vm context.
lastActiveAt: expect.anything(),
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-workspace-binding.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-workspace-binding.integration-spec.ts
index 409dc357629..ff1b7c4dad1 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-workspace-binding.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-session-workspace-binding.integration-spec.ts
@@ -17,11 +17,8 @@ import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-s
import { UserSessionEntity } from 'src/engine/core-modules/user-session/user-session.entity';
import { hashUserSessionToken } from 'src/engine/core-modules/user-session/utils/hash-user-session-token.util';
-// Tim is seeded in both the apple and yc workspaces, which is what makes this
-// provable: same user, same credentials, two sessions, and each cookie can
-// only ever reach the workspace its exchange selected. No request-side input
-// (header, variable, origin) lets a session pivot to another workspace; the
-// context is rebuilt from the session row alone.
+// Tim is seeded in both apple and yc, so each session must reach only the workspace its exchange selected,
+// whatever the request sends: the context is rebuilt from the session row alone.
describe('successful session workspace binding (integration)', () => {
let appleSessionToken: string;
let ycSessionToken: string;
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-sign-out.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-sign-out.integration-spec.ts
index 3166386f5f7..3d96167692b 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-sign-out.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-sign-out.integration-spec.ts
@@ -54,8 +54,7 @@ describe('successful sign-out (integration)', () => {
UserSessionRevokedReason.UserSignOut,
);
- // Revocation invalidates the cache, so reuse fails immediately, not
- // after the cache TTL.
+ // Revocation invalidates the cache, so reuse fails before the cache TTL.
const reuseResponse = await postMetadataOperationWithHeaders(
currentUserIdentityQueryFactory(),
{
@@ -69,10 +68,7 @@ describe('successful sign-out (integration)', () => {
});
it('should not clear anything on a cookie-less sign-out, so a cross-site POST cannot log a visitor out', async () => {
- // What a cross-site forgery actually looks like server-side: SameSite=Lax
- // keeps the cookie off the request, and the attacker page's origin comes
- // along. CSRF does not apply (no cookie), so the mutation runs and must
- // still clear nothing.
+ // SameSite=Lax keeps the cookie off a cross-site request, so CSRF does not apply and the mutation runs.
const response = await postMetadataOperationWithHeaders(
signOutQueryFactory(),
{ originHeader: DISALLOWED_ORIGIN },
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-user-sessions-api.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-user-sessions-api.integration-spec.ts
index d1f43050203..6f1fc3a0689 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-user-sessions-api.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/successful-user-sessions-api.integration-spec.ts
@@ -43,8 +43,7 @@ describe('successful user sessions API (integration)', () => {
};
beforeAll(async () => {
- // Two devices: the "other" one signs in first so the second sign-in does
- // not supersede it (no cookie presented on either exchange).
+ // The other device signs in first so the second cookie-less sign-in does not supersede it.
const otherDeviceResponse = await signInWithCookieCapture({
originHeader: ALLOWED_ORIGIN,
});
@@ -112,7 +111,6 @@ describe('successful user sessions API (integration)', () => {
});
it('should revoke every other session but keep the presented one alive', async () => {
- // A fresh sign-in guarantees at least one other active session to revoke.
await signInWithCookieCapture({ originHeader: ALLOWED_ORIGIN });
const response = await postMetadataOperationWithHeaders(
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/workspace-scoped-user-sessions-api.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/workspace-scoped-user-sessions-api.integration-spec.ts
index b15de9ccc8e..39bff453634 100644
--- a/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/workspace-scoped-user-sessions-api.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/user-sessions/workspace-scoped-user-sessions-api.integration-spec.ts
@@ -14,10 +14,7 @@ import { ALLOWED_ORIGIN } from 'test/integration/graphql/suites/auth/user-sessio
type UserSessionApiEntry = { id: string; isCurrent: boolean };
-// Tim is seeded in both apple and yc, which is what makes this provable: one
-// person, two workspaces. Almost nothing in Twenty is account-wide, so a
-// workspace must not surface, or be able to revoke, the sessions this person
-// holds in another workspace.
+// Tim is seeded in both apple and yc, proving a workspace can neither list nor revoke his sessions in the other.
describe('workspace-scoped user sessions API (integration)', () => {
let appleCookieHeader: string;
let ycCookieHeader: string;
@@ -81,14 +78,12 @@ describe('workspace-scoped user sessions API (integration)', () => {
expect(response.body.errors).toBeDefined();
- // Still usable: the refusal has to be a no-op, not a silent revocation.
const ycSessionsAfter = await fetchSessions(ycCookieHeader);
expect(ycSessionsAfter.map((session) => session.id)).toContain(ycSessionId);
});
it('should leave other workspaces signed in when revoking all other devices', async () => {
- // A second apple sign-in guarantees there is something to revoke.
await signInTo('apple');
const response = await postMetadataOperationWithHeaders(
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-conversation-record-attachment.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-conversation-record-attachment.integration-spec.ts
index ac603c282ec..02f07fd636c 100644
--- a/packages/twenty-server/test/integration/graphql/suites/chat-conversation-record-attachment.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-conversation-record-attachment.integration-spec.ts
@@ -55,7 +55,6 @@ describe('Attaching a conversation to a record from a chat turn', () => {
await destroyAgentChatThread({ threadId });
});
- // Built from the same authorization ChatExecutionService gives the turn.
const buildTool = async () => {
const { authorization } = await actors.authorizeJob({
workspaceId,
@@ -76,7 +75,6 @@ describe('Attaching a conversation to a record from a chat turn', () => {
});
};
- // Read back through the record API, the way the record page lists them.
const listConversationIdsAttachedTo = async (recordId: string) => {
const response = await makeGraphqlApiRequest(
findManyOperationFactory({
diff --git a/packages/twenty-server/test/integration/graphql/suites/cursor-pagination-order-by.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/cursor-pagination-order-by.integration-spec.ts
index c876ce2a851..22b391faca8 100644
--- a/packages/twenty-server/test/integration/graphql/suites/cursor-pagination-order-by.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/cursor-pagination-order-by.integration-spec.ts
@@ -63,7 +63,6 @@ const paginateForward = async ({
let after: string | undefined = undefined;
let pages = 0;
- // Cap the loop far above the expected page count so a paging bug cannot hang the suite
for (let iteration = 0; iteration < 20; iteration++) {
const response: GraphqlResponse = await makeGraphqlApiRequest(
findManyOperationFactory({
@@ -184,7 +183,6 @@ describe('Cursor pagination exhaustiveness with orderBy (issue #24333)', () => {
expect(ids).toHaveLength(TOTAL_COUNT);
expect(new Set(ids).size).toBe(TOTAL_COUNT);
- // The NULL block sorts last: its records must all be there, at the end
expect(new Set(ids.slice(DATED_CLOSE_DATES.length))).toEqual(
new Set(nullCloseDateOpportunityIds),
);
@@ -216,8 +214,6 @@ describe('Cursor pagination exhaustiveness with orderBy (issue #24333)', () => {
});
it('should walk backward across the NULL boundary with before cursors', async () => {
- // Reach the last page forward, then walk back from its end cursor: the
- // backward scan re-crosses the null/non-null boundary in reverse
const forwardResponse = await makeGraphqlApiRequest(
findManyOperationFactory({
objectMetadataSingularName: 'opportunity',
@@ -240,7 +236,6 @@ describe('Cursor pagination exhaustiveness with orderBy (issue #24333)', () => {
startingBefore: forwardConnection.pageInfo.endCursor,
});
- // Everything before the last record, in the same order as the forward scan
expect(ids).toEqual(forwardIds.slice(0, -1));
});
@@ -276,8 +271,7 @@ describe('Cursor pagination exhaustiveness with orderBy (issue #24333)', () => {
expect(ids).toEqual(datedOpportunityIds.slice(2));
});
- // Canonical lowercase UUID strings sort the same way in JS and in Postgres,
- // so the expected order can be computed with a plain string sort
+ // Lowercase UUID strings sort the same in JS and Postgres, so a plain string sort gives the expected order.
it('should honor an explicit descending id ordering across pages', async () => {
const { ids } = await paginateForward({
orderBy: { id: 'DescNullsLast' },
@@ -342,7 +336,6 @@ describe('Cursor pagination with composite orderBy not in the selection set', ()
first: 2,
});
- // Global order must hold across pages: Alice..Eve
expect(ids).toEqual(personIds);
});
});
@@ -457,7 +450,6 @@ describe('Cursor pagination ordered by a nullable composite sub-field', () => {
expect(ids).toHaveLength(amountTotalCount);
expect(new Set(ids).size).toBe(amountTotalCount);
- // Non-null amounts keep their micros order across pages
expect(ids.slice(0, withAmountOpportunityIds.length)).toEqual(
withAmountOpportunityIds,
);
@@ -521,9 +513,8 @@ describe('Cursor pagination with duplicate sort values', () => {
});
});
-// Empty TEXT values are stored as SQL NULL (write-side normalization) and
-// presented as '' by the API: the scan's NULL block holds every empty row, and
-// cursors read the raw SQL values so the continuation follows the scan exactly
+// Empty TEXT values are stored as SQL NULL but returned as '' by the API: the scan's NULL block holds every empty row,
+// and cursors carry the raw SQL values so the continuation follows the scan.
describe('Cursor pagination ordered by a TEXT field with empty values', () => {
const namedCompanyIds = {
ALPHA: '20202020-eeee-4000-8000-000000000001',
@@ -549,7 +540,6 @@ describe('Cursor pagination ordered by a TEXT field with empty values', () => {
data: [
{ id: namedCompanyIds.ALPHA, name: 'Alpha Corp' },
{ id: namedCompanyIds.BETA, name: 'Beta Inc' },
- // One explicitly empty, the others without the field: both store NULL
{ id: emptyNameCompanyIds[0], name: '' },
...emptyNameCompanyIds.slice(1).map((id) => ({ id })),
],
diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts
index cae092965cb..900dc9e2212 100644
--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts
@@ -44,8 +44,7 @@ import { type RecordAccessPolicyService } from 'src/engine/core-modules/record-s
import { type WorkspaceEventBatch } from 'src/engine/workspace-event-emitter/types/workspace-event-batch.type';
import { computeEventName } from 'src/engine/workspace-event-emitter/utils/compute-event-name';
-// Avoid loading the migration runner's ESM file dependencies inside Jest. The
-// command below receives the real migration service from the running test app.
+// Avoids loading the migration runner's ESM dependencies in Jest; the command gets the real service from the test app.
jest.mock(
'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service',
() => ({ WorkspaceMigrationValidateBuildAndRunService: class {} }),
@@ -76,8 +75,6 @@ const readThread = async (
token,
);
};
-// Chats are renamed, soft deleted, restored and destroyed through the record
-// API like any other record
const updateThreadRecord = (
threadId: string,
data: Record<string, unknown>,
@@ -561,8 +558,7 @@ describe('Conversation sharing through the authenticated API', () => {
expect((await readThread(owner.threadId)).body.errors).toBeUndefined();
} finally {
await command.up(options);
- // The 2.43 command sets threads PRIVATE; later upgrades have moved them
- // on, so replay those to leave the workspace as other suites expect it.
+ // The 2.43 command resets threads to PRIVATE; replay later upgrades to restore the state other suites expect.
await getAppProviderByClassName<AddWorkflowRunToChatThreadsCommand>(
'AddWorkflowRunToChatThreadsCommand',
).up(options);
@@ -841,7 +837,6 @@ describe('Conversations through the record API', () => {
'Renamed through the record API',
);
- // Archive is soft delete now; the legacy column is no longer writable
const legacyArchive = await updateThreadRecord(threadId, {
archivedAt: new Date().toISOString(),
});
@@ -907,8 +902,6 @@ describe('Conversations through the record API', () => {
}
});
- // The application exposes its events through WorkspaceEventEmitter, so the
- // destroy batch is captured there, as delivered to its subscribers.
const waitForDestroyedThread = (threadId: string) => {
const workspaceEventEmitter =
getAppProviderByClassName<WorkspaceEventEmitter>('WorkspaceEventEmitter');
diff --git a/packages/twenty-server/test/integration/graphql/suites/order-by-relation-field.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/order-by-relation-field.integration-spec.ts
index 0976415a23d..76bc6ce999b 100644
--- a/packages/twenty-server/test/integration/graphql/suites/order-by-relation-field.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/order-by-relation-field.integration-spec.ts
@@ -234,7 +234,6 @@ describe('Order by relation field (e2e)', () => {
if (edge.node.company === null) {
seenNull = true;
} else if (seenNull) {
- // If we already saw a null, subsequent non-nulls mean order is wrong
throw new Error('Records with null company should appear at the end');
}
}
@@ -395,7 +394,6 @@ describe('Order by relation field (e2e)', () => {
expect(collectedIds).toHaveLength(TEST_PERSON_IDS.length);
expect(new Set(collectedIds).size).toBe(TEST_PERSON_IDS.length);
- // Company names must be globally non-decreasing across pages, nulls last
const companyNames = collectedCompanyNames.filter(
(name): name is string => name !== null,
);
@@ -501,12 +499,10 @@ describe('Order by relation field (e2e)', () => {
before = connection.pageInfo.startCursor;
}
- // Everything before the last record, in the same order as the forward scan
expect(backwardIds).toEqual(forwardIds.slice(0, -1));
});
- // Cursors read the relation orderBy values from the ordering join itself,
- // so pagination must not depend on the selection set (issue #24333)
+ // Regression for #24333: cursors must not depend on the selected fields.
it('should paginate exhaustively without the ordered relation field selected', async () => {
const collectedIds: string[] = [];
let after: string | undefined = undefined;
@@ -561,8 +557,7 @@ describe('Order by relation field (e2e)', () => {
after = connection.pageInfo.endCursor;
}
- // Companies sort Alpha < Beta < Gamma with id tie-breaks, then the
- // missing-relation block in id order: exactly the seeded id order
+ // The fixture ids are seeded in the expected sort order.
expect(collectedIds).toEqual(TEST_PERSON_IDS);
});
@@ -762,9 +757,7 @@ describe('Order by relation field (e2e)', () => {
});
it('should work with filter + relation orderBy + scalar orderBy with minimal fields selected', async () => {
- // This test reproduces a bug where TypeORM's DISTINCT subquery failed
- // when orderBy included columns not in the SELECT clause.
- // The bug manifested as: "column distinctAlias.person_position does not exist"
+ // Regression: TypeORM's DISTINCT subquery failed when orderBy used columns missing from SELECT.
const queryData = {
query: gql`
query People(
@@ -790,9 +783,8 @@ describe('Order by relation field (e2e)', () => {
}
`,
variables: {
- // Filter excludes one record - key to triggering the DISTINCT subquery path
+ // Excluding a record triggers the DISTINCT subquery path.
filter: { id: { neq: TEST_PERSON_IDS[0] } },
- // Multiple orderBy: relation field + scalar field (position not in SELECT)
orderBy: [
{ company: { name: 'DescNullsLast' } },
{ position: 'AscNullsFirst' },
@@ -803,7 +795,6 @@ describe('Order by relation field (e2e)', () => {
const response = await makeGraphqlApiRequest(queryData);
- // Should succeed without "column distinctAlias.person_position does not exist" error
expect(response.body.errors).toBeUndefined();
expect(response.body.data).toBeDefined();
expect(response.body.data.people).toBeDefined();
@@ -836,17 +827,13 @@ const COMPOSITE_TEST_OPPORTUNITY_IDS = [
'20202020-dddd-4000-8000-000000000006',
];
-// The web app sorts a relation column by the target's label identifier; for a
-// person target that is the FULL_NAME composite, sent as one orderBy entry per
-// property: [{ pointOfContact: { name: { firstName } } }, { ...lastName... }]
+// Mirrors how the web app sorts a relation column whose label identifier is a FULL_NAME composite.
describe('Order by a composite field through a relation (e2e)', () => {
const orderBy = [
{ pointOfContact: { name: { firstName: 'AscNullsLast' } } },
{ pointOfContact: { name: { lastName: 'AscNullsLast' } } },
];
- // Opportunities ordered by their contact's (firstName, lastName), the two
- // Adas separated by lastName, then the two without a contact in id order
const expectedOpportunityIds = COMPOSITE_TEST_OPPORTUNITY_IDS;
beforeAll(async () => {
@@ -1015,7 +1002,6 @@ describe('Order by a composite field through a relation (e2e)', () => {
before = connection.pageInfo.startCursor;
}
- // Everything before the last record, in forward order
expect(collectedIds).toEqual(expectedOpportunityIds.slice(0, -1));
});
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/timeline/timeline-activity-write-path.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/timeline/timeline-activity-write-path.integration-spec.ts
index f19cef49abe..129710149c1 100644
--- a/packages/twenty-server/test/integration/graphql/suites/timeline/timeline-activity-write-path.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/timeline/timeline-activity-write-path.integration-spec.ts
@@ -136,8 +136,7 @@ const FIND_MANY_TIMELINE_ACTIVITY_TYPES = gql`
}
`;
-// Mirrors the server resolver: several types share an action, and the one bound
-// to the event's object wins over the shared one.
+// Mirrors the server resolver: an object-bound type wins over a shared one for the same action.
const timelineActivityTypeIdByObjectAndAction = new Map<string, string>();
const buildKey = (
@@ -297,8 +296,7 @@ describe('timeline activity write path (integration)', () => {
afterAll(async () => {
if (isNonEmptyString(nonAuditLoggedFieldMetadataId)) {
- // A field has to be deactivated before it can be deleted, otherwise its
- // name stays taken and the next run cannot recreate it.
+ // Deleting without deactivating first leaves the name taken for the next run.
await updateOneFieldMetadata({
input: {
idToUpdate: nonAuditLoggedFieldMetadataId,
@@ -650,8 +648,6 @@ describe('timeline activity write path (integration)', () => {
expect(rowsWithoutTarget).toHaveLength(0);
});
- // The note rule only fans out on its trigger field, so editing the body
- // leaves the linked timelines alone.
it('should not write a linked entry when a non trigger field changes', async () => {
await updateRecord({
objectMetadataSingularName: 'note',
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/classify-workflow-activation.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/classify-workflow-activation.integration-spec.ts
index 081c242bde7..4d74edd6135 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/classify-workflow-activation.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/classify-workflow-activation.integration-spec.ts
@@ -3,8 +3,7 @@ import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/wo
const client = request(`http://localhost:${APP_PORT}`);
-// The settings schema requires uuids here, so these are fixed rather than
-// readable: a non-uuid would be refused for the wrong reason.
+// The settings schema requires uuids, and a non-uuid would be refused for the wrong reason.
const SECOND_QUESTION_ID = '0f7f5f2e-6f1e-4c1e-9a3e-2b7d9a1c4e81';
const BILLING_CRITERION_ID = '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d';
const SUPPORT_CRITERION_ID = '2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e';
@@ -193,8 +192,7 @@ describe('Classify step activation (e2e)', () => {
);
});
- // A dot would be read as structure by the variable resolver, so an answer
- // named this way could never be referenced downstream.
+ // The variable resolver reads a dot as structure, so the answer could never be referenced downstream.
it('should refuse an answer name that is not a valid variable key', async () => {
const response = await updateStep(
workflowVersionId,
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
index c5057a6028e..bad814b5f32 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
@@ -791,8 +791,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
name: 'Approve the discount',
});
- // The form's call is named after the step, in the conversation the step's
- // current execution recorded.
const getFormConversation = async (runId: string, stepId: string) => {
const threadId = (await getRun(runId)).state.stepInfos[stepId].threadId;
const [thread] = await global.testDataSource.query(
@@ -929,9 +927,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
});
});
- // Every iteration of a loop re-executes the same step in the same run, so
- // each records its own conversation and one iteration's answer never
- // stands for the next.
it('records a conversation for each iteration of a form inside a loop', async () => {
const afterLoop = emptyStep();
const form = approvalForm([]);
@@ -1034,8 +1029,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
});
});
- // A stop waiting on a step still running on another branch parks the run in
- // STOPPING with the form still PENDING; nothing would resume an answer.
+ // Nothing would resume an answer submitted to a run parked in STOPPING.
it('refuses a submission while its run is stopping', async () => {
const finalStep = emptyStep();
const form = formStep([finalStep.id]);
@@ -1145,7 +1139,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
.mockResolvedValueOnce(askingResult)
.mockResolvedValueOnce(replyingResult);
- // Each call the conversation waits on, and whether it still waits.
const getToolCalls = async (threadId: string) => {
const [thread] = await global.testDataSource.query(
`SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,
@@ -1187,8 +1180,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
const startAskingRun = async () => {
const finalStep = emptyStep();
const agent = agentStep([finalStep.id]);
- // A run reads through its workspace workflow record, which a
- // mirrorless fixture does not have.
+ // A run reads through its workspace workflow record, which a mirrorless fixture lacks.
const fixture = await createFixture({ steps: [agent, finalStep] });
const runId = await runFixture(fixture);
const run = await waitForStep(runId, agent.id, 'PENDING');
@@ -1367,8 +1359,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(waitingRun.status).toBe('RUNNING');
expect(waitingRun.state.stepInfos[agent.id].status).toBe('PENDING');
- // Had the first answer resumed the step, the second would find it no
- // longer waiting.
const second = await answer({ threadId, toolCallId: 'ask-2' });
expect(second.body.errors).toBeUndefined();
@@ -1429,8 +1419,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
getQueueToken(MessageQueue.workflowQueue),
);
- // Holds the resume back, so the run's fate can be decided while it is
- // still queued.
+ // Holds the resume back so the run's fate is decided while it is still queued.
const enqueue = jest.spyOn(queue, 'add').mockResolvedValueOnce(undefined);
const response = await answer({ threadId });
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
index 94e939ed144..7486f41ff7b 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
@@ -230,8 +230,7 @@ const createActiveManualWorkflow = async (name: string) => {
return { coreWorkflowId, workspaceWorkflowId, workspaceWorkflowVersionId };
};
-// The generic record API, which the run pages read, rather than
-// the core workflow API that #26243 already gates.
+// The record API the run pages read, not the core workflow API #26243 already gates.
const findRecordIds = async (
requester: (query: string, variables?: object) => request.Test,
objectNamePlural: 'workflowRuns',
@@ -267,9 +266,8 @@ describe('core workflow visibility (e2e)', () => {
let workflowsRoleId: string;
beforeAll(async () => {
- // The whole workflow API sits behind SettingsPermissionGuard(WORKFLOWS),
- // which the seeded Member role does not carry, so the second member has to
- // be someone who could reach the workflow if visibility allowed it.
+ // The workflow API requires the WORKFLOWS settings permission, which the seeded Member role lacks,
+ // so the second member gets it and only visibility can block them.
const memberRole = await findOneRoleByLabel({ label: 'Member' });
originalMemberRoleId = memberRole.id;
@@ -396,9 +394,8 @@ describe('core workflow visibility (e2e)', () => {
});
});
- // Workflows predating the visibility column have no owner, and so does one
- // whose creator left the workspace, since the owner FK is ON DELETE SET NULL.
- // Without a claim they would be unreachable by everyone while still running.
+ // Pre-visibility workflows and those whose creator left (owner FK is ON DELETE SET NULL) have no owner,
+ // and without a claim nobody could reach them while they still run.
describe('an ownerless workflow', () => {
let ownerlessWorkspaceWorkflowId: string;
let ownerlessCoreWorkflowId: string;
@@ -478,8 +475,7 @@ describe('core workflow visibility (e2e)', () => {
});
});
- // The claim is the UPDATE's own WHERE rather than a preceding read, so this
- // is what keeps two simultaneous claims from both passing.
+ // The claim is the UPDATE's own WHERE, which is what stops two simultaneous claims both passing.
it('refuses a second claim even though the workflow is still workspace-visible', async () => {
const secondClaim = await workflowGraphqlRequest(
UPDATE_VISIBILITY_MUTATION,
@@ -547,8 +543,6 @@ describe('core workflow visibility (e2e)', () => {
);
});
- // The versions carry the whole definition, so reaching one by id has to
- // answer to the same rule as reaching the workflow.
it('refuses its version to another member', async () => {
const response = await asOtherMember(CORE_WORKFLOW_VERSION_QUERY, {
workspaceWorkflowVersionId,
@@ -557,9 +551,7 @@ describe('core workflow visibility (e2e)', () => {
expect(response.body.data?.coreWorkflowVersion ?? null).toBeNull();
});
- // The builder resolver reads a version's content straight from its id to
- // compute a schema, so it hands out the whole definition unless it answers
- // to the same rule.
+ // This resolver reads version content straight from its id, bypassing the workflow lookup.
it('refuses to compute a step output schema from its version for another member', async () => {
const response = await asOtherMember(
COMPUTE_STEP_OUTPUT_SCHEMA_MUTATION,
@@ -575,9 +567,7 @@ describe('core workflow visibility (e2e)', () => {
expect(response.body.data?.computeStepOutputSchema ?? null).toBeNull();
});
- // The legacy resolver is keyed by the workspace mirror's ids and never
- // passes through CoreWorkflowIdResolutionService, so it needs the rule
- // reached from the other side or a held id still launches the workflow.
+ // The legacy resolver uses the mirror's ids and never goes through CoreWorkflowIdResolutionService.
it('refuses to run it from the legacy API for another member', async () => {
const response = await asOtherMember(LEGACY_RUN_MUTATION, {
input: { workflowVersionId: workspaceWorkflowVersionId },
@@ -587,9 +577,7 @@ describe('core workflow visibility (e2e)', () => {
expect(response.body.data?.runWorkflowVersion ?? null).toBeNull();
});
- // WorkflowTriggerResolver's AuthPrincipalGuard accepts API keys, so unlike
- // the core workflow API an API key does reach this mutation, and the rule
- // has to hold for a caller that is a workspace rather than a person.
+ // Unlike the core workflow API, WorkflowTriggerResolver's AuthPrincipalGuard accepts API keys.
it('refuses to activate it for an API key', async () => {
const response = await asApiKey(ACTIVATE_VERSION_MUTATION, {
workflowVersionId: workspaceWorkflowVersionId,
@@ -620,9 +608,7 @@ describe('core workflow visibility (e2e)', () => {
});
});
- // Activating a manual trigger writes a workspace-wide command menu item
- // carrying the workflow name, so the command menu is a second way to reach
- // the workflow and has to answer to the same rule.
+ // Activating a manual trigger writes a workspace-wide command menu item carrying the workflow name.
describe('a workflow with an active manual trigger', () => {
let manualWorkspaceWorkflowId: string;
let manualCoreWorkflowId: string;
@@ -694,8 +680,6 @@ describe('core workflow visibility (e2e)', () => {
});
});
- // A run holds the workflow's inputs and step outputs, so it has to be as
- // private as the workflow even when read through the generic record API.
describe('the runs of a workflow', () => {
let runsCoreWorkflowId: string;
let runsWorkspaceWorkflowId: string;
@@ -787,8 +771,7 @@ describe('core workflow visibility (e2e)', () => {
});
});
- // An agent step's conversation carries no grants of its own: it is read
- // through its run, so it follows the workflow's visibility like the run does.
+ // An agent step's conversation has no grants of its own: it is read through its run, so follows the workflow's visibility.
describe('the conversation an agent step records on a run', () => {
let conversationCoreWorkflowId: string;
let conversationWorkspaceWorkflowId: string;
@@ -997,8 +980,7 @@ describe('core workflow visibility (e2e)', () => {
});
});
- // Removing a member deletes their membership, and the database then clears
- // the creator of every workflow they created.
+ // Removing a member deletes the membership, which nulls the creator of every workflow they created.
describe('the runs of a private workflow whose creator is removed from the workspace', () => {
const removedUserId = randomUUID();
const removedUserWorkspaceId = randomUUID();
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
index 6724e77d743..1dc61fe3623 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
@@ -284,8 +284,7 @@ describe('Parallel branch leaf resume workflow (e2e)', () => {
},
};
- // Insert the run directly instead of going through runWorkflowVersion, so
- // no start job is enqueued and the manual handle below is the only driver.
+ // Inserted directly so no start job is enqueued and the manual handle is the only driver.
await global.testDataSource.query(
`INSERT INTO "${schema}"."workflowRun" (id, name, "workflowId", "workflowVersionId", "coreWorkflowId", "coreWorkflowVersionId", status, state, position, "enqueuedAt")
VALUES ($1, 'Parallel branch leaf resume run', $2, $3, $4, $5, 'ENQUEUED', $6, 0, now())`,
@@ -298,8 +297,7 @@ describe('Parallel branch leaf resume workflow (e2e)', () => {
JSON.stringify(state),
],
);
- // Runs are private, and a direct insert skips the grants that creating a
- // run writes, so the run would be unreadable through the record API.
+ // A direct insert skips the run's grants, leaving it unreadable through the record API.
await getAppProviderByClassName<WorkflowRunRecordShareService>(
'WorkflowRunRecordShareService',
).syncRuns({
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
index 7108939e8f4..d684b1dc2e0 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
@@ -202,7 +202,6 @@ describe('Quick Lead Workflow (e2e)', () => {
let createdPersonId: string | null = null;
afterAll(async () => {
- // Clean up created records in reverse order of creation
if (createdPersonId) {
await client
.post('/graphql')
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-tool-call.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-tool-call.util.ts
index f4c5997f47d..08c9d7d0e1e 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-tool-call.util.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-tool-call.util.ts
@@ -7,8 +7,6 @@ type ToolCallLocation =
| { workflowRunId: string; stepId: string }
| { threadId: string; toolCallId: string };
-// A form step's call is named after the step, in the conversation its current
-// execution recorded.
const findFormStepThreadId = async ({
workflowRunId,
stepId,
diff --git a/packages/twenty-server/test/integration/graphql/suites/workspace/custom-application-translation.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workspace/custom-application-translation.integration-spec.ts
index 2473d2334d6..59f97918d18 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workspace/custom-application-translation.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workspace/custom-application-translation.integration-spec.ts
@@ -78,9 +78,7 @@ describe('custom application translation resolve path', () => {
});
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.
+ // A fresh workspace ensures the catalog is read from the database, not a warm empty cache.
const uniqueEmail = `test-custom-translation-${randomUUID()}@example.com`;
const { data: signUpData } = await signUp({
diff --git a/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts
index 6056439db70..f3f149740b1 100644
--- a/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts
+++ b/packages/twenty-server/test/integration/imap/suites/imap-messages-import.integration-spec.ts
@@ -162,9 +162,7 @@ describe('IMAP messages import (integration)', () => {
expect(await findImportedMessageSubjects([subject])).toEqual([subject]);
}, 300000);
- // Servers that scope HIGHESTMODSEQ to the account rather than the mailbox hand
- // us a cursor MODSEQ higher than any message the folder will receive next.
- // Dovecot is compliant and cannot produce that state, so it is written directly.
+ // Servers scoping HIGHESTMODSEQ to the account leave a stored MODSEQ above the folder's next message; Dovecot can't, so it is written directly.
it('imports new mail when the stored MODSEQ is ahead of the mailbox', async () => {
await runMessageChannelSync(messageChannelId);
diff --git a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts
index 0adcae3d4b0..a1d98012cc3 100644
--- a/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/agent/successful-agent-creation.integration-spec.ts
@@ -210,9 +210,7 @@ describe('Agent creation should succeed', () => {
isCustom: true,
});
- // Delete the agent first so its role_target is removed; otherwise
- // deleting the role would refuse to orphan the agent (the workspace
- // default role isn't agent-assignable).
+ // Deleting the role first would refuse to orphan the agent, since the default role isn't agent-assignable.
await deleteOneAgent({
expectToFail: false,
input: { id: createdAgentId },
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/system-relation-index-deletion.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/system-relation-index-deletion.integration-spec.ts
index 6e0bf1e5afd..1e3730f8a28 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/system-relation-index-deletion.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/system-relation-index-deletion.integration-spec.ts
@@ -114,8 +114,7 @@ describe.each(['sync', 'uninstall'] as const)(
indexes.length,
);
- // Older backfills left these generated indexes unflagged and sometimes
- // owned by Twenty Standard rather than the application owning the field.
+ // Older backfills left these indexes unflagged and sometimes owned by Twenty Standard.
await globalThis.testDataSource.query(
`UPDATE core."indexMetadata" SET "isSystemSideEffect" = false,
"applicationId" = (
diff --git a/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.ts
index 8e432eb6142..e703d9e933f 100644
--- a/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/developers/webhooks.integration-spec.ts
@@ -330,8 +330,7 @@ describe('webhooksResolver (e2e)', () => {
expect(createPersonResponse.body.errors).toBeUndefined();
createdPersonId = createPersonResponse.body.data.createPerson.id;
- // Delivery crosses two BullMQ hops behind a fire-and-forget event
- // emit, so poll the receiver instead of guessing at the latency.
+ // Delivery crosses two BullMQ hops behind a fire-and-forget emit.
await expectEventually(
() => {
expect(receiver.receivedPayloads.length).toBe(1);
diff --git a/packages/twenty-server/test/integration/metadata/suites/field-metadata/morph-relation/morph-relation-cursor-pagination.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/field-metadata/morph-relation/morph-relation-cursor-pagination.integration-spec.ts
index 0871430654a..2adbeb632e2 100644
--- a/packages/twenty-server/test/integration/metadata/suites/field-metadata/morph-relation/morph-relation-cursor-pagination.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/field-metadata/morph-relation/morph-relation-cursor-pagination.integration-spec.ts
@@ -18,10 +18,7 @@ type MorphParentConnection = {
pageInfo: { hasNextPage: boolean; endCursor: string };
};
-// A MANY_TO_ONE morph relation materializes one relation field per target
-// (owner -> ownerMorphCursorPerson / ownerMorphCursorCompany), so ordering by
-// one leg must treat records attached to the other leg - and unattached ones -
-// as the NULL block of the scan.
+// Each morph target is its own relation field, so records on the other leg fall in the NULL block.
describe('morph relation cursor pagination', () => {
let parentObjectMetadataId = '';
let personObjectMetadataId = '';
@@ -229,8 +226,7 @@ describe('morph relation cursor pagination', () => {
);
});
- // Cursors read the morph leg's orderBy values from the ordering join itself,
- // so pagination must not depend on the selection set (issue #24333)
+ // Regression for #24333: cursors must not depend on the selected fields.
it('should paginate exhaustively when the ordered morph leg is not selected', async () => {
await collectAllPages('id');
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts
index b68f16b642e..6c0e8be3010 100644
--- a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-message-channels.integration-spec.ts
@@ -348,9 +348,7 @@ describe('app message channels API (e2e)', () => {
adminUserWorkspaceId = userWorkspace.id;
- // Minted with the admin token, so it carries that admin's userWorkspaceId
- // alongside the owning applicationId — the shape an app gets when a member
- // triggered the run, rather than a cron.
+ // Carries the admin's userWorkspaceId: the shape of a member-triggered run rather than a cron.
const tokenPair = await generateAppleAdminApplicationTokenPair({
applicationId: owningApplicationDbId,
});
@@ -385,8 +383,6 @@ describe('app message channels API (e2e)', () => {
userWorkspaceId: adminUserWorkspaceId,
});
- // Owned by the calling application, but private to a member who is not
- // the one behind the token.
await insertAppConnection({
id: foreignMemberConnectionId,
applicationId: owningApplicationDbId,
@@ -481,8 +477,7 @@ describe('app message channels API (e2e)', () => {
expect(channel).toMatchObject({
handle: CHANNEL_HANDLE,
- // Trimmed rather than stored as given, so the UI never renders a
- // padded label.
+ // Trimmed so the UI never renders a padded label.
displayName: 'Ada at LinkedIn',
type: MessageChannelType.APP,
visibility: MessageChannelVisibility.SHARE_EVERYTHING,
@@ -547,8 +542,7 @@ describe('app message channels API (e2e)', () => {
describe('appMessageChannels', () => {
it("lists the application's own channels and nothing else", async () => {
const channel = await createChannelOrThrow();
- // A channel that exists, is type APP, and lives in the same workspace —
- // so a list query that forgot to scope by application would return it.
+ // Same workspace and type APP, so a list query not scoped by application would return it.
const foreignChannel = await createChannelOrThrow({
connectedAccountId: otherAppConnectionId,
token: otherApplicationToken,
@@ -723,8 +717,7 @@ describe('app message channels API (e2e)', () => {
buildMessage({
externalId: 'sent-by-the-channel-owner',
threadExternalId,
- // Same account as the channel handle, spelled the way a provider
- // that upper-cases its profile API would return it.
+ // The channel's own handle, spelled the way a provider that upper-cases its profile API returns it.
senderHandle: CHANNEL_HANDLE.toUpperCase(),
}),
buildMessage({
diff --git a/packages/twenty-server/test/integration/metadata/suites/object-metadata/mostly-empty-field-metadata-ids.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/object-metadata/mostly-empty-field-metadata-ids.integration-spec.ts
index 7c0e8d771dd..72b9a3cfbab 100644
--- a/packages/twenty-server/test/integration/metadata/suites/object-metadata/mostly-empty-field-metadata-ids.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/object-metadata/mostly-empty-field-metadata-ids.integration-spec.ts
@@ -113,7 +113,6 @@ describe('mostlyEmptyFieldMetadataIds', () => {
});
it('should flag a never-filled field only while the record gate passes and the field stays empty', async () => {
- // Below the minimum record count nothing is flagged
await insertProbeRecords(50);
await analyzeProbeTable();
@@ -121,8 +120,7 @@ describe('mostlyEmptyFieldMetadataIds', () => {
await fetchMostlyEmptyFieldMetadataIds(testObjectMetadataId),
).toEqual([]);
- // Past the gate, the untouched custom text field is the only expected hit:
- // name is the label identifier and system fields are excluded
+ // Past the gate, only the untouched custom text field hits: name is the label identifier and system fields are excluded.
await insertProbeRecords(100);
await analyzeProbeTable();
@@ -130,7 +128,6 @@ describe('mostlyEmptyFieldMetadataIds', () => {
await fetchMostlyEmptyFieldMetadataIds(testObjectMetadataId),
).toEqual([probeNotesFieldMetadataId]);
- // Once the field is backfilled everywhere the hint disappears
await global.testDataSource.query(
`UPDATE "${testSchemaName}"."${TEST_TABLE_NAME}" SET "probeNotes" = 'filled'`,
);
diff --git a/packages/twenty-server/test/integration/metadata/suites/object-metadata/object-metadata-i18n.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/object-metadata/object-metadata-i18n.integration-spec.ts
index e2812a53835..b489f5099ae 100644
--- a/packages/twenty-server/test/integration/metadata/suites/object-metadata/object-metadata-i18n.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/object-metadata/object-metadata-i18n.integration-spec.ts
@@ -170,8 +170,7 @@ describe('object metadata i18n', () => {
'objects',
);
const person = items.find((item) => item.nameSingular === 'person');
- // A field only reachable through person proves the inlined fields were
- // regrouped onto the object they belong to, not merely onto some object.
+ // A person-only field proves fields were regrouped onto their own object.
const companyField = person?.fields.find(
(field) => field.name === 'company',
);
diff --git a/packages/twenty-server/test/integration/metadata/suites/object-metadata/rename-custom-object.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/object-metadata/rename-custom-object.integration-spec.ts
index 334296c6e8e..4dc6db7d795 100644
--- a/packages/twenty-server/test/integration/metadata/suites/object-metadata/rename-custom-object.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/object-metadata/rename-custom-object.integration-spec.ts
@@ -139,9 +139,7 @@ describe('Custom object renaming', () => {
const relationFieldMetadataId = relationFieldMetadata?.id;
expect(relationFieldMetadataId).not.toBeUndefined();
- // Reverse system relation fields carry the engine-derived label
- // (capitalized source object nameSingular), except attachment targets
- // which share their morph group label
+ // Attachment targets share their morph group label instead of the engine-derived one.
expect(relationFieldMetadata?.label).toBe(
relation === 'attachment'
? 'Attached to'
@@ -187,9 +185,6 @@ describe('Custom object renaming', () => {
expect(data.updateOneObject.labelSingular).toBe(HOUSE_LABEL_SINGULAR);
expect(data.updateOneObject.labelPlural).toBe(HOUSE_LABEL_PLURAL);
- // The reverse morph fields on the standard objects must be renamed in place
- // (name and engine-derived label follow the new object name) while keeping
- // their universal identifier stable, so the rename stays lossless.
const expectedReverseFieldName = `target${capitalize(HOUSE_NAME_SINGULAR)}`;
const expectedReverseFieldLabel = capitalize(HOUSE_NAME_SINGULAR);
const fields = await makeMetadataApiRequest(fieldsGraphqlOperation);
@@ -256,9 +251,7 @@ describe('Custom object renaming', () => {
const relationFieldMetadataId =
timelineActivityRelation.relationFieldMetadataId;
- // morphRelationsUpdatePayload is not an editable property, so it must be
- // rejected explicitly for engine-owned fields instead of silently creating
- // relation fields and indexes on them
+ // morphRelationsUpdatePayload isn't an editable property, so engine-owned fields must reject it rather than silently create relation fields and indexes.
const { errors } = await updateOneFieldMetadata({
expectToFail: true,
input: {
diff --git a/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.ts b/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.ts
index ee191589581..90cb2e258ea 100644
--- a/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.ts
+++ b/packages/twenty-server/test/integration/oauth/suites/oauth.integration-spec.ts
@@ -1032,8 +1032,7 @@ describe('OAuth (integration)', () => {
})
.expect(200);
- // 'read' alone, not the registration's full scope list, so the assertion
- // fails if the granted scope is ignored in favour of the declared one.
+ // 'read' alone, so the assertion fails if the declared scope is used instead of the granted one.
it('should record the authorization with the scopes the user granted', async () => {
await exchangeForTokens('read');
@@ -1078,8 +1077,7 @@ describe('OAuth (integration)', () => {
}).expect(200);
});
- // Deleting the row leaves a refresh token in the state every token minted
- // before this table existed is in.
+ // Deleting the row recreates the state of tokens minted before this table existed.
it('should backfill a refresh token that predates the authorization record without inventing a consent', async () => {
const { refreshToken } = await exchangeForTokens('read write');
diff --git a/packages/twenty-server/test/integration/rest/suites/rest-api-core-find-many.integration-spec.ts b/packages/twenty-server/test/integration/rest/suites/rest-api-core-find-many.integration-spec.ts
index 1f0144a9ef2..15d9960feff 100644
--- a/packages/twenty-server/test/integration/rest/suites/rest-api-core-find-many.integration-spec.ts
+++ b/packages/twenty-server/test/integration/rest/suites/rest-api-core-find-many.integration-spec.ts
@@ -212,19 +212,6 @@ describe('Core REST API Find Many endpoint', () => {
expect(filteredPeople.length).toBeGreaterThan(0);
});
- // TODO: Refacto-common - Uncomment this after https://github.com/twentyhq/core-team-issues/issues/1627
-
- // expect(response.body).toMatchInlineSnapshot(`
- // {
- // "error": "BadRequestException",
- // "messages": [
- // "field 'company' does not exist in 'person' object",
- // ],
- // "statusCode": 400,
- // }
- // `);
- // });
-
it('should support ordering Desc of results', async () => {
const descResponse = await makeRestApiRequest({
method: 'get',
@@ -300,41 +287,6 @@ describe('Core REST API Find Many endpoint', () => {
}).expect(400);
});
- // TODO: Uncomment this test when we support composite fields ordering in the rest api
-
- // const testPeople = [
- // {
- // id: TEST_PERSON_1_ID,
- // firstName: 'Alice',
- // lastName: 'Brown',
- // position: 0,
- // },
- // {
- // id: TEST_PERSON_2_ID,
- // firstName: 'Alice',
- // lastName: 'Smith',
- // position: 1,
- // },
- // {
- // id: TEST_PERSON_3_ID,
- // firstName: 'Bob',
- // lastName: 'Johnson',
- // position: 2,
- // },
- // {
- // id: TEST_PERSON_4_ID,
- // firstName: 'Bob',
- // lastName: 'Williams',
- // position: 3,
- // },
- // {
- // id: TEST_PERSON_5_ID,
- // firstName: 'Charlie',
- // lastName: 'Davis',
- // position: 4,
- // },
- // ];
-
it('should support depth 0 parameter', async () => {
const response = await makeRestApiRequest({
method: 'get',
@@ -408,8 +360,7 @@ describe('Core REST API Find Many endpoint', () => {
expect(new Set(ids).size).toBe(testPersonIds.length);
});
- // Cursors read relation orderBy values from the ordering join itself, so
- // continuation must not require any depth (issue #24333)
+ // Regression for #24333: continuation must not require any depth.
it('should continue past the first page at depth 0', async () => {
const ids: string[] = [];
let startingAfter: string | undefined = undefined;
diff --git a/packages/twenty-server/test/integration/secure-deployment/suites/secure-session-cookie.integration-spec.ts b/packages/twenty-server/test/integration/secure-deployment/suites/secure-session-cookie.integration-spec.ts
index 1f340d2f487..5c6fc8faa0f 100644
--- a/packages/twenty-server/test/integration/secure-deployment/suites/secure-session-cookie.integration-spec.ts
+++ b/packages/twenty-server/test/integration/secure-deployment/suites/secure-session-cookie.integration-spec.ts
@@ -19,12 +19,7 @@ import { IS_SECURE_DEPLOYMENT } from 'test/integration/graphql/suites/auth/user-
import { USER_SESSION_COOKIE_NAME } from 'src/engine/core-modules/user-session/constants/user-session-cookie-name.constant';
import { USER_SESSION_SECURE_COOKIE_NAME } from 'src/engine/core-modules/user-session/constants/user-session-secure-cookie-name.constant';
-// The secure/insecure cookie branch is decided by configuration, never by the
-// transport: isSecureDeployment() reads SERVER_URL, which is env-only. This
-// suite therefore needs the app booted with an https SERVER_URL, which
-// jest-integration-secure.config.ts guarantees; run it through
-// `nx run twenty-server:test:integration:secure`. It exercises the exact
-// production combination: __Host- name, Secure, and the SameSite=Lax default.
+// Needs an https SERVER_URL (env-only, read by isSecureDeployment()): run via `nx run twenty-server:test:integration:secure`.
describe('session cookie on a production-like secure deployment (integration)', () => {
let sessionToken: string;
@@ -58,8 +53,7 @@ describe('session cookie on a production-like secure deployment (integration)',
sessionToken = secureSessionCookie.sessionToken;
- // A literal rather than a snapshot: snapshots written by this dedicated
- // run would count as obsolete in the plain-http run.
+ // Not a snapshot: this dedicated run's snapshots would be obsolete in the plain-http run.
expect(
normalizeSessionCookieForSnapshot(secureSessionCookie.rawCookie),
).toBe(
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts
index 00fe4cbf2a0..b34c141e01e 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts
@@ -28,8 +28,7 @@ import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder
const WORKSPACE_ID = SEED_APPLE_WORKSPACE_ID;
const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
-// The link object 2.43 adds on top of agent history, as later suites see it:
-// its fields and the relations pointing at it, its indexes and its foreign keys.
+// The link object 2.43 adds on top of agent history.
const describeAgentChatThreadTarget = async (dataSource: DataSource) => ({
fields: await dataSource.query<{ objectName: string; fieldName: string }[]>(
`SELECT objectMetadata."nameSingular" AS "objectName", fieldMetadata.name AS "fieldName"
@@ -133,8 +132,7 @@ describe('versioned agent history upgrade (integration)', () => {
dataSource = owners.manager.connection;
const owner = await owners.findOneByOrFail({ workspaceId: WORKSPACE_ID });
- // Threads a workflow run owns arrived with 2.44 and have no member to own
- // them in the core tables 2.42 moves history back to.
+ // Run-owned threads arrived with 2.44 and have no member owner in the core tables 2.42 restores.
await dataSource.query(
`DELETE FROM "${SCHEMA}"."agentChatThread" WHERE "workflowRunId" IS NOT NULL`,
);
@@ -147,8 +145,7 @@ describe('versioned agent history upgrade (integration)', () => {
seededAgentChatThreadTarget =
await describeAgentChatThreadTarget(dataSource);
- // Objects later upgrades add on top of history hold a relation into it,
- // which the deleted thread object would take along and strand them without.
+ // Later objects relate into history and would be stranded when the thread object is deleted.
const historyObjectNames = AGENT_HISTORY_TABLES.map(({ name }) => name);
const laterObjectNames = (
await dataSource.query<{ nameSingular: string }[]>(
@@ -167,9 +164,7 @@ describe('versioned agent history upgrade (integration)', () => {
expect(laterObjectNames).toContain('agentChatThreadTarget');
- // Recreate a pre-upgrade workspace: history exists only in core, and none
- // of the five standard objects has been installed yet, nor the objects
- // later upgrades add on top of them.
+ // Recreate a pre-upgrade workspace: history only in core, no standard or later objects installed.
await dataSource.query(
'DELETE FROM core."objectMetadata" WHERE "workspaceId" = $1 AND "nameSingular" = ANY($2)',
[WORKSPACE_ID, [...historyObjectNames, ...laterObjectNames]],
@@ -189,8 +184,7 @@ describe('versioned agent history upgrade (integration)', () => {
for (const { name } of [...AGENT_HISTORY_TABLES].reverse()) {
await dataSource.query(`DROP TABLE "${SCHEMA}"."${name}" CASCADE`);
}
- // Pre-upgrade workspaces have no attachment side of the chat thread
- // relation either; the object deletion above only cascades its metadata.
+ // Pre-upgrade workspaces lack the attachment side too, and the deletion above only cascades its metadata.
await dataSource.query(
'DELETE FROM core."indexMetadata" WHERE "workspaceId" = $1 AND "universalIdentifier" = $2',
[
@@ -255,8 +249,7 @@ describe('versioned agent history upgrade (integration)', () => {
total: 1,
options: {},
});
- // The history objects were rebuilt as 2.42 leaves them; replay the later
- // upgrades that change them, in order, for the suites that follow.
+ // Replay the later upgrades on the rebuilt 2.42 objects, in order, for the suites that follow.
for (const laterCommand of [
getAppProviderByClassName<AddWorkflowRunToChatThreadsCommand>(
'AddWorkflowRunToChatThreadsCommand',
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-command-registration.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-command-registration.integration-spec.ts
index c33ea275497..a504c9e3b9b 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-command-registration.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-command-registration.integration-spec.ts
@@ -21,8 +21,7 @@ it('discovers sender expansion through the application upgrade runner', () => {
);
});
-// The move locks archivedAt again, so it has to run after the command that
-// opened it
+// The move locks archivedAt again, so it must run after the command that opened it.
it('runs the chat record model commands after archivedAt was opened', () => {
const registry = getAppProviderByClassName<UpgradeCommandRegistryService>(
'UpgradeCommandRegistryService',
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts
index 559c2acb548..bcacd619dcf 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts
@@ -72,8 +72,7 @@ describe('2-44 workspace command 1790607161319 - AddWorkflowRunToChatThreadsComm
};
};
- // What a workspace that has not run the command yet looks like: no run link
- // and threads PRIVATE, as 2.43 left them.
+ // Pre-upgrade state: no run link and threads PRIVATE, as 2.43 left them.
const setPreUpgradeState = async () => {
const migrationService =
getAppProviderByClassName<WorkspaceMigrationValidateBuildAndRunService>(
@@ -125,9 +124,7 @@ describe('2-44 workspace command 1790607161319 - AddWorkflowRunToChatThreadsComm
],
},
});
- // Run conversations only exist from 2.44 on; dropping their run link
- // would leave them ownerless and unlinked, which no earlier version can
- // hold (2.42's reverse copy, for one, requires an owner).
+ // Run conversations only exist from 2.44 on; no earlier version can hold them ownerless and unlinked.
await global.testDataSource.query(
`DELETE FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."agentChatThread" WHERE "workflowRunId" IS NOT NULL`,
);
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790751626421-move-agent-chat-threads-to-record-model.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790751626421-move-agent-chat-threads-to-record-model.integration-spec.ts
index 3e9c27c2766..3079cac3ff8 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790751626421-move-agent-chat-threads-to-record-model.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790751626421-move-agent-chat-threads-to-record-model.integration-spec.ts
@@ -102,7 +102,6 @@ describe('2-44 workspace command 1790751626421 - MoveAgentChatThreadsToRecordMod
const chatService =
getAppProviderByClassName<AgentChatService>('AgentChatService');
- // What a workspace that has not run the command yet looks like
await runCommand('down');
for (const threadId of threadIds) {
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts
index 6dcf9489de7..e2354baea4a 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790772993322-record-pending-form-conversations.integration-spec.ts
@@ -51,8 +51,7 @@ describe('2-44 workspace command 1790772993322 - RecordPendingFormConversationsC
return state?.stepInfos?.[formStepId]?.threadId;
};
- // A form step waiting since before this release: pending, with no
- // conversation recorded for it.
+ // A form step pending since before this release, with no recorded conversation.
const forgetFormConversation = () =>
inWorkspace(() =>
repository('workflowRun').update(workflowRun.id, {
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-5-instance-command-slow-1798000009000-encrypt-totp-secrets.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-5-instance-command-slow-1798000009000-encrypt-totp-secrets.integration-spec.ts
index 80a8729237d..1e607a28317 100644
--- a/packages/twenty-server/test/integration/upgrade/suites/2-5-instance-command-slow-1798000009000-encrypt-totp-secrets.integration-spec.ts
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-5-instance-command-slow-1798000009000-encrypt-totp-secrets.integration-spec.ts
@@ -69,9 +69,7 @@ const restoreCheckConstraint = async (
);
};
-// Stand-in for the real JwtWrapperService used by SimpleSecretEncryptionUtil.
-// Reproduces JwtWrapperService.generateAppSecret byte-for-byte so the legacy
-// CBC key derivation matches what production rows were sealed with.
+// Reproduces JwtWrapperService.generateAppSecret byte for byte so legacy CBC keys match production rows.
const buildJwtWrapperServiceStub = (appSecret: string): JwtWrapperService => {
return {
generateAppSecret: (
diff --git a/packages/twenty-server/test/integration/upgrade/utils/upgrade-sequence-runner-integration-test.util.ts b/packages/twenty-server/test/integration/upgrade/utils/upgrade-sequence-runner-integration-test.util.ts
index 2a25bec3d73..eed4b980a95 100644
--- a/packages/twenty-server/test/integration/upgrade/utils/upgrade-sequence-runner-integration-test.util.ts
+++ b/packages/twenty-server/test/integration/upgrade/utils/upgrade-sequence-runner-integration-test.util.ts
@@ -151,8 +151,7 @@ export const makeSlowInstance = (name: string, version?: string) =>
export const makeWorkspace = (name: string, version?: string) =>
makeStep('workspace', name, version) as WorkspaceUpgradeStep;
-// Steps the status service can resolve a version from: it reads the version
-// off the command name, not off the step's `version` field.
+// The status service reads the version off the command name, not the step's `version` field.
export const makeVersionedStep = (
kind: UpgradeStep['kind'],
{ version, label }: { version: string; label: string },
@@ -370,8 +369,7 @@ export const seedInstanceMigration = async (
attempt?: number;
},
) => {
- // Seeds must have past timestamps so the runner's NOW()-based records
- // always sort after them in createdAt order.
+ // Past timestamps so the runner's NOW()-based records always sort after the seeds.
const createdAt = new Date(
Date.now() - (1000000 - seedSequenceCounter * 1000),
).toISOString();
diff --git a/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts b/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts
index 52cd9ad24f5..59207de452e 100644
--- a/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts
+++ b/packages/twenty-server/test/integration/utils/connect-dovecot-imap-account.util.ts
@@ -15,8 +15,7 @@ export type DovecotImapAccount = {
messageChannelId: string;
};
-// The IMAP driver routes through the SSRF guard, which rejects the container's
-// private address before the connection is attempted.
+// The SSRF guard would otherwise reject the container's private address.
export const connectDovecotImapAccount = async ({
handle,
password,
diff --git a/packages/twenty-server/test/integration/utils/destroy-agent-chat-thread.util.ts b/packages/twenty-server/test/integration/utils/destroy-agent-chat-thread.util.ts
index 7817f31f243..605c1040e8e 100644
--- a/packages/twenty-server/test/integration/utils/destroy-agent-chat-thread.util.ts
+++ b/packages/twenty-server/test/integration/utils/destroy-agent-chat-thread.util.ts
@@ -3,8 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';
import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-// Chats are destroyed like any record; their grants stay behind, as for any
-// destroyed record, until a new chat reuses the id
+// Grants outlive the destroyed chat until a new chat reuses its id.
export const destroyAgentChatThread = async ({
threadId,
token = APPLE_JANE_ADMIN_ACCESS_TOKEN,
diff --git a/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts b/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts
index 1fe5040a3d3..19588bea870 100644
--- a/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts
+++ b/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts
@@ -3,8 +3,7 @@ import { isDefined } from 'twenty-shared/utils';
import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-// Mirrors the chat list query: deleted chats stay listed so they can be
-// restored, and workflow run conversations are left to their run
+// Mirrors the chat list: deleted chats stay listed for restore, run conversations are excluded.
export const listChatThreadIds = async (
token = APPLE_JANE_ADMIN_ACCESS_TOKEN,
): Promise<string[]> => {
diff --git a/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.ts b/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.ts
index d2796e692bb..459896fe729 100644
--- a/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.ts
+++ b/packages/twenty-server/test/integration/workflow-actions/create-calendar-event/drivers/caldav.integration-spec.ts
@@ -27,8 +27,7 @@ describe('CREATE_CALENDAR_EVENT workflow action on CalDAV (integration)', () =>
`http://${radicale.host}:${radicale.port}/${HANDLE}/${COLLECTION}/`;
beforeAll(async () => {
- // The CalDAV driver wraps its fetch in the SSRF guard, which rejects the
- // container's private address before the request is made.
+ // The SSRF guard would otherwise reject the container's private address.
await updateConfigVariable({
input: { key: 'OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS', value: ['*'] },
});
diff --git a/packages/twenty-shared/src/ai/constants/ai-evaluation-question-type.const.ts b/packages/twenty-shared/src/ai/constants/ai-evaluation-question-type.const.ts
index d23e20b806f..23c5e4c4cbc 100644
--- a/packages/twenty-shared/src/ai/constants/ai-evaluation-question-type.const.ts
+++ b/packages/twenty-shared/src/ai/constants/ai-evaluation-question-type.const.ts
@@ -1,6 +1,4 @@
-// The three decisions an evaluation model can be asked for. Mirrors the AI SDK
-// evaluation specification, restated here so the domain never depends on an
-// experimental provider type.
+// Restates the AI SDK evaluation spec so the domain never depends on an experimental provider type.
export const AI_EVALUATION_QUESTION_TYPES = [
'choice',
'score',
diff --git a/packages/twenty-shared/src/ai/constants/ai-model-effort.const.ts b/packages/twenty-shared/src/ai/constants/ai-model-effort.const.ts
index 61125bfd6c5..8dde98f31e4 100644
--- a/packages/twenty-shared/src/ai/constants/ai-model-effort.const.ts
+++ b/packages/twenty-shared/src/ai/constants/ai-model-effort.const.ts
@@ -1,6 +1,4 @@
-// Every effort level a supported provider accepts, in ascending order. A model
-// lists the subset it takes in the catalog, since the set differs per model even
-// within one provider.
+// Ascending; each model lists its own subset in the catalog since support differs even within a provider.
export const AI_MODEL_EFFORTS = [
'none',
'minimal',
diff --git a/packages/twenty-shared/src/ai/constants/ai-model-tier.const.ts b/packages/twenty-shared/src/ai/constants/ai-model-tier.const.ts
index a9932d3be5c..6e474f6f7b6 100644
--- a/packages/twenty-shared/src/ai/constants/ai-model-tier.const.ts
+++ b/packages/twenty-shared/src/ai/constants/ai-model-tier.const.ts
@@ -1,5 +1,4 @@
-// Ordered from fastest and cheapest to most capable. The order is what the
-// slider walks, so it must stay monotonic in both directions.
+// The slider walks this order, so it must stay monotonic from fastest and cheapest to most capable.
export const AI_MODEL_TIERS = [
'extraFast',
'fast',
diff --git a/packages/twenty-shared/src/ai/constants/auto-select-model-id-by-tier.const.ts b/packages/twenty-shared/src/ai/constants/auto-select-model-id-by-tier.const.ts
index 5fea9e7a357..594fb2578ee 100644
--- a/packages/twenty-shared/src/ai/constants/auto-select-model-id-by-tier.const.ts
+++ b/packages/twenty-shared/src/ai/constants/auto-select-model-id-by-tier.const.ts
@@ -1,8 +1,7 @@
import { type AiModelTier } from './ai-model-tier.const';
-// Stored in agent.modelId and sent by the chat client in place of a concrete
-// `provider/model` id. The fast and smart values predate tiers and live in
-// existing rows, so they keep their original spelling.
+// Stand-ins for a concrete `provider/model` id in agent.modelId and chat requests.
+// The fast and smart values predate tiers and live in stored rows, so they keep their original spelling.
export const AUTO_SELECT_MODEL_ID_BY_TIER = {
extraFast: 'default-extra-fast-model',
fast: 'default-fast-model',
diff --git a/packages/twenty-shared/src/ai/constants/auto-select-workspace-default-model-id.const.ts b/packages/twenty-shared/src/ai/constants/auto-select-workspace-default-model-id.const.ts
index 727db5c6422..415e7f430df 100644
--- a/packages/twenty-shared/src/ai/constants/auto-select-workspace-default-model-id.const.ts
+++ b/packages/twenty-shared/src/ai/constants/auto-select-workspace-default-model-id.const.ts
@@ -1,4 +1,2 @@
-// Stored on an agent that follows the workspace's agent tier instead of naming
-// one of its own, so changing the workspace setting moves every such agent.
export const AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID =
'workspace-default-model' as const;
diff --git a/packages/twenty-shared/src/ai/constants/default-ai-chat-model-tier.const.ts b/packages/twenty-shared/src/ai/constants/default-ai-chat-model-tier.const.ts
index 11c0473a782..d2abf652834 100644
--- a/packages/twenty-shared/src/ai/constants/default-ai-chat-model-tier.const.ts
+++ b/packages/twenty-shared/src/ai/constants/default-ai-chat-model-tier.const.ts
@@ -1,5 +1,3 @@
import { type AiModelTier } from './ai-model-tier.const';
-// Cheap and quick is the right default for most workspaces; the slider is one
-// click away for anyone who wants more.
export const DEFAULT_AI_CHAT_MODEL_TIER: AiModelTier = 'fast';
diff --git a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
index d3e3abe7943..85952be1e47 100644
--- a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
+++ b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
@@ -1,6 +1,4 @@
-// `chunk` is typed as Record<string, unknown> rather than UIMessageChunk
-// to avoid importing the `ai` package in twenty-shared. The frontend casts
-// it back to UIMessageChunk when feeding it into readUIMessageStream.
+// Not UIMessageChunk, to keep the `ai` package out of twenty-shared.
export type AgentChatSubscriptionEvent =
| { type: 'stream-chunk'; chunk: Record<string, unknown>; seq?: number }
| { type: 'message-persisted'; messageId: string }
diff --git a/packages/twenty-shared/src/ai/types/EmailApprovalResponse.ts b/packages/twenty-shared/src/ai/types/EmailApprovalResponse.ts
index 8699fcacbed..b76521eda98 100644
--- a/packages/twenty-shared/src/ai/types/EmailApprovalResponse.ts
+++ b/packages/twenty-shared/src/ai/types/EmailApprovalResponse.ts
@@ -1,8 +1,6 @@
import { type EmailApprovalDecision } from '@/ai/types/EmailApprovalDecision';
import { type ProposedEmail } from '@/ai/types/ProposedEmail';
-// The email is the one the person approved, edited or not; a discard needs
-// none.
export type EmailApprovalResponse = {
decision: EmailApprovalDecision;
email?: ProposedEmail;
diff --git a/packages/twenty-shared/src/ai/types/ProposedEmail.ts b/packages/twenty-shared/src/ai/types/ProposedEmail.ts
index 13691aaacec..8890b6f3b22 100644
--- a/packages/twenty-shared/src/ai/types/ProposedEmail.ts
+++ b/packages/twenty-shared/src/ai/types/ProposedEmail.ts
@@ -1,7 +1,6 @@
import { type EmailRecipients } from '@/workflow/types/EmailRecipients';
-// An email as an agent proposes it and as a person edits it before sending:
-// recipients are comma-separated, the body is plain text.
+// Recipients are comma-separated; the body is plain text.
export type ProposedEmail = {
recipients: Required<EmailRecipients>;
subject: string;
diff --git a/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts b/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts
index ab7423968f1..7537f24fcd1 100644
--- a/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts
+++ b/packages/twenty-shared/src/ai/types/RequestFormToolInput.ts
@@ -2,9 +2,7 @@ import type z from 'zod';
import { type workflowFormFieldSchema } from '@/workflow/schemas/form-action-settings-schema';
-// A workflow form step issues this call with its own fields, so a form step
-// and an agent asking for a form are answered the same way. Answers are keyed
-// by field name.
+// Workflow form steps issue this call too, so they and agent form requests are answered alike; answers are keyed by field name.
export type RequestFormField = Pick<
z.infer<typeof workflowFormFieldSchema>,
'name' | 'label' | 'type' | 'placeholder' | 'settings'
diff --git a/packages/twenty-shared/src/ai/types/ToolWidget.ts b/packages/twenty-shared/src/ai/types/ToolWidget.ts
index 89e02b5b685..b0c1b55b25c 100644
--- a/packages/twenty-shared/src/ai/types/ToolWidget.ts
+++ b/packages/twenty-shared/src/ai/types/ToolWidget.ts
@@ -1,6 +1,4 @@
-// A tool names the widget that renders its calls in the AI chat. The client
-// resolves the name it is given instead of switching on tool names, so a tool
-// can change its presentation without a front-end release.
+// Tools name their widget so a tool can change its presentation without a front-end release.
export const RECORDS_TOOL_WIDGET_NAME = 'records';
export const TOOL_WIDGET_NAMES = [RECORDS_TOOL_WIDGET_NAME] as const;
@@ -10,8 +8,6 @@ export type ToolWidgetName = (typeof TOOL_WIDGET_NAMES)[number];
export const isToolWidgetName = (value: string): value is ToolWidgetName =>
TOOL_WIDGET_NAMES.includes(value as ToolWidgetName);
-// Emitted by every record tool on its output, and rendered by the `records`
-// widget as links to the real record.
export type ToolRecordReference = {
objectNameSingular: string;
recordId: string;
diff --git a/packages/twenty-shared/src/ai/utils/infer-ai-sdk-package.util.ts b/packages/twenty-shared/src/ai/utils/infer-ai-sdk-package.util.ts
index 9ff979a4e18..72d830bc6ac 100644
--- a/packages/twenty-shared/src/ai/utils/infer-ai-sdk-package.util.ts
+++ b/packages/twenty-shared/src/ai/utils/infer-ai-sdk-package.util.ts
@@ -3,9 +3,7 @@ import {
type AiSdkPackage,
} from '../constants/ai-sdk-packages.const';
-// models.dev names a vendor the way the AI SDK names its package for most of
-// the ones we bundle, so a vendor we have a package for is served by it and
-// everything else goes through the compatible shim.
+// models.dev vendor ids match the AI SDK package names we bundle; anything else goes through the compatible shim.
export const inferAiSdkPackage = (providerId: string): AiSdkPackage =>
(AI_SDK_PACKAGES as readonly string[]).includes(`@ai-sdk/${providerId}`)
? (`@ai-sdk/${providerId}` as AiSdkPackage)
diff --git a/packages/twenty-shared/src/ai/utils/parse-ai-model-variant-id.util.ts b/packages/twenty-shared/src/ai/utils/parse-ai-model-variant-id.util.ts
index 8976592830c..5a33440563b 100644
--- a/packages/twenty-shared/src/ai/utils/parse-ai-model-variant-id.util.ts
+++ b/packages/twenty-shared/src/ai/utils/parse-ai-model-variant-id.util.ts
@@ -3,8 +3,7 @@ import { isAiModelEffort } from './is-ai-model-effort.util';
const EFFORT_SEPARATOR = '@';
-// Catalog model names never contain `@` (Bedrock ids use `:`), so the last one
-// delimits the effort. Any other suffix is part of the id itself.
+// Catalog model names never contain `@` (Bedrock ids use `:`), so the last `@` delimits the effort.
export const parseAiModelVariantId = (
modelId: string,
): { modelId: string; effort?: AiModelEffort } => {
diff --git a/packages/twenty-shared/src/application/appMessageChannelType.ts b/packages/twenty-shared/src/application/appMessageChannelType.ts
index 6b97cb1f89a..c4d7c0cc552 100644
--- a/packages/twenty-shared/src/application/appMessageChannelType.ts
+++ b/packages/twenty-shared/src/application/appMessageChannelType.ts
@@ -1,29 +1,15 @@
import { type MessageChannelVisibility } from '../types/MessageChannelVisibility';
-// One messaging channel an app owns, bound to one of its connections.
-// Returned from `listMessageChannels` and `createMessageChannel`.
-//
-// The shape lives in twenty-shared so this and the server-side
-// `MessageChannelDTO` projection always agree.
export type AppMessageChannel = {
id: string;
- // The account's identity on the provider, as the provider names it (a
- // LinkedIn member URN, a WhatsApp number). Opaque to Twenty: it is what
- // the app matches inbound payloads against, and what participant handles
- // on this channel are compared to when deciding message direction.
+ // Provider identity (LinkedIn URN, WhatsApp number) that inbound payloads and participant handles are matched against.
handle: string;
- // End-user label for the channel. Falls back to `handle` in the UI when null.
+ // Falls back to `handle` in the UI when null.
displayName: string | null;
- // How much of a message on this channel other workspace members may read:
- // 'METADATA' = participants and dates only.
- // 'SUBJECT' = the above plus the subject.
- // 'SHARE_EVERYTHING' = the above plus the body.
- // The owner of the underlying connection always reads their own messages
- // in full regardless of this value.
+ // What other members may read: METADATA = participants and dates, SUBJECT adds the subject, SHARE_EVERYTHING the body.
+ // The connection owner always reads their own messages in full.
visibility: MessageChannelVisibility;
- // The app connection whose credential this channel speaks through.
connectedAccountId: string;
- // False pauses the channel without deleting it: ingestion is rejected
- // while it is off, and existing messages stay readable.
+ // False rejects ingestion without deleting the channel; existing messages stay readable.
isSyncEnabled: boolean;
};
diff --git a/packages/twenty-shared/src/application/applicationBillingType.ts b/packages/twenty-shared/src/application/applicationBillingType.ts
index d42567bd1b8..613d79cdd68 100644
--- a/packages/twenty-shared/src/application/applicationBillingType.ts
+++ b/packages/twenty-shared/src/application/applicationBillingType.ts
@@ -9,8 +9,7 @@ export const isRecurringChargePeriod = (
): value is RecurringChargePeriod =>
RECURRING_CHARGE_PERIODS.includes(value as RecurringChargePeriod);
-// Omitted for a flat fee. WORKSPACE_MEMBER multiplies the amount by the number
-// of members in the workspace at the moment the period is charged.
+// Omitted for a flat fee; WORKSPACE_MEMBER multiplies by the member count when the period is charged.
export const RECURRING_CHARGE_UNITS = ['WORKSPACE_MEMBER'] as const;
export type RecurringChargeUnit = (typeof RECURRING_CHARGE_UNITS)[number];
@@ -27,12 +26,8 @@ export type RecurringCharge = {
label: string;
};
-// 1 USD = 1_000_000 micro-credits. Unlike a chargeCredits call, which the app
-// makes and the server validates per request, a recurring charge is raised by
-// the platform from a jsonb column, so these bound what the platform is willing
-// to debit on an app's behalf. PER_UNIT bounds the declared rate, which a
-// WORKSPACE_MEMBER charge multiplies by the member count, and PER_PERIOD bounds
-// the resulting total.
+// 1 USD = 1_000_000 micro-credits; these bound what the platform debits on an app's unvalidated declaration.
+// PER_UNIT bounds the declared rate (multiplied by member count for WORKSPACE_MEMBER), PER_PERIOD the total.
export const MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT = 100_000_000;
export const MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD = 1_000_000_000;
@@ -42,8 +37,7 @@ export const isRecurringChargeAmount = (value: unknown): value is number =>
value > 0 &&
value <= MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT;
-// The declaration reaches the raise path as untrusted jsonb, so its shape is
-// checked at runtime rather than trusted from the RecurringCharge type.
+// Reaches the raise path as untrusted jsonb, so its shape is checked at runtime.
export const isRecurringCharge = (value: unknown): value is RecurringCharge => {
if (typeof value !== 'object' || value === null) {
return false;
@@ -61,9 +55,7 @@ export const isRecurringCharge = (value: unknown): value is RecurringCharge => {
);
};
-// Keyed by a name the application chooses. Unlike operations, the platform
-// raises these itself once per billing period, so the app declares the amount
-// rather than calling chargeCredits.
+// Raised by the platform once per billing period, unlike operations the app charges via chargeCredits.
export type RecurringCharges = Partial<Record<string, RecurringCharge>>;
export type ApplicationBilling = {
diff --git a/packages/twenty-shared/src/application/creditAvailabilityType.ts b/packages/twenty-shared/src/application/creditAvailabilityType.ts
index 3f332f25c64..bf5f988d7f8 100644
--- a/packages/twenty-shared/src/application/creditAvailabilityType.ts
+++ b/packages/twenty-shared/src/application/creditAvailabilityType.ts
@@ -7,11 +7,7 @@ export const CREDIT_UNAVAILABLE_REASONS = [
export type CreditUnavailableReason =
(typeof CREDIT_UNAVAILABLE_REASONS)[number];
-// What an application is told about its workspace's ability to spend. Mirrors
-// the gate the platform already applies to AI, workflows and email, so an app
-// can make the same decision up front instead of discovering the refusal
-// through a downstream call it did not write. Carries no balance: an app learns
-// whether it may spend, not how much the workspace has or what it pays.
+// Mirrors the platform's AI, workflow and email spend gate; deliberately carries no balance.
export type CreditAvailability =
| { hasAvailableCredits: true }
| { hasAvailableCredits: false; reason: CreditUnavailableReason };
diff --git a/packages/twenty-shared/src/application/objectManifestType.ts b/packages/twenty-shared/src/application/objectManifestType.ts
index 20ea6b8ad1b..aff6160f848 100644
--- a/packages/twenty-shared/src/application/objectManifestType.ts
+++ b/packages/twenty-shared/src/application/objectManifestType.ts
@@ -14,9 +14,7 @@ export type ObjectManifest = SyncableEntityOptions & {
color?: string | null;
isLabelSyncedWithName?: boolean;
isSearchable?: boolean;
- // When false, the generic UI shows no affordance to create records of this object
isUICreatable?: boolean;
- // When false, records of this object are not editable through the generic UI
isUIEditable?: boolean;
writability?: MetadataWritability;
readability?: MetadataReadability;
diff --git a/packages/twenty-shared/src/application/toolTriggerSettingsType.ts b/packages/twenty-shared/src/application/toolTriggerSettingsType.ts
index d26177f5435..9a50dc5ad74 100644
--- a/packages/twenty-shared/src/application/toolTriggerSettingsType.ts
+++ b/packages/twenty-shared/src/application/toolTriggerSettingsType.ts
@@ -1,12 +1,8 @@
import { type InputJsonSchema } from '@/logic-function/input-json-schema.type';
-// Exposes a logic function as an AI tool (chat / MCP / function calling).
-// Uses standard JSON Schema -- the format LLMs natively understand.
-// inputSchema is optional in the developer-facing SDK; the manifest
-// builder fills it in by inferring from the handler source code when omitted.
+// inputSchema is optional in the SDK; the manifest builder infers it from the handler source.
export type ToolTriggerSettings = {
inputSchema?: InputJsonSchema;
- // Universal identifier of a front component that renders this tool's calls
- // in the AI chat. Resolved to a front component id when descriptors are built.
+ // Front component that renders this tool's calls in the AI chat; resolved to its id when descriptors are built.
frontComponentUniversalIdentifier?: string;
};
diff --git a/packages/twenty-shared/src/application/usageOperationTypesType.ts b/packages/twenty-shared/src/application/usageOperationTypesType.ts
index 702a6ee9e73..483f35bf444 100644
--- a/packages/twenty-shared/src/application/usageOperationTypesType.ts
+++ b/packages/twenty-shared/src/application/usageOperationTypesType.ts
@@ -1,8 +1,5 @@
-// The subset of the server's UsageOperationType an app may bill under, so a
-// manifest can name a category without importing server code. API_REQUEST,
-// STORAGE_FILE, RECORD_WRITE, SUBSCRIPTION and MESSAGE_CAMPAIGN_SEND are left
-// out on purpose: the platform raises all five itself, and API_REQUEST rows
-// feed the workspace's API rate limit.
+// The UsageOperationType subset an app may bill under; the omitted ones are raised by the platform itself,
+// and API_REQUEST rows feed the API rate limit.
export const USAGE_OPERATION_TYPES = [
'AI_CHAT_TOKEN',
'AI_WORKFLOW_TOKEN',
diff --git a/packages/twenty-shared/src/constants/PolledMessageChannelTypes.ts b/packages/twenty-shared/src/constants/PolledMessageChannelTypes.ts
index d5957a65730..79aa821d9f1 100644
--- a/packages/twenty-shared/src/constants/PolledMessageChannelTypes.ts
+++ b/packages/twenty-shared/src/constants/PolledMessageChannelTypes.ts
@@ -1,10 +1,4 @@
import { MessageChannelType } from '../types/MessageChannelType';
-// The email import pipeline polls providers on a cron. Only types whose
-// messages are fetched that way belong here: push-delivered channels
-// (EMAIL_GROUP, APP) would be scheduled forever against a driver that
-// cannot list their messages. SMS is declared on the enum but has no
-// driver, so it is left out too — listing the polled types rather than
-// excluding the others keeps a type out of the pipeline until someone
-// deliberately opts it in.
+// Only cron-polled types: push channels (EMAIL_GROUP, APP) and driverless SMS would be scheduled forever.
export const POLLED_MESSAGE_CHANNEL_TYPES = [MessageChannelType.EMAIL] as const;
diff --git a/packages/twenty-shared/src/i18n/__tests__/generate-message-id.spec.ts b/packages/twenty-shared/src/i18n/__tests__/generate-message-id.spec.ts
index 114b0dd00ee..40e439e1742 100644
--- a/packages/twenty-shared/src/i18n/__tests__/generate-message-id.spec.ts
+++ b/packages/twenty-shared/src/i18n/__tests__/generate-message-id.spec.ts
@@ -1,10 +1,7 @@
import { generateMessageId } from '@/i18n/generate-message-id';
-// These ids are not arbitrary: each pair below was lifted from the
-// `js-lingui-id` comments in twenty-server's committed en.po, so this suite
-// asserts our implementation still agrees with what the Lingui CLI actually
-// emits. If it goes red, every persisted metadata label has silently stopped
-// resolving against its catalog.
+// Pairs lifted from twenty-server's en.po `js-lingui-id` comments, pinning parity with the Lingui CLI.
+// A failure means persisted metadata labels no longer resolve against their catalog.
describe('generateMessageId', () => {
it.each([
['A company', 'kZR6+h'],
diff --git a/packages/twenty-shared/src/i18n/generate-message-id.ts b/packages/twenty-shared/src/i18n/generate-message-id.ts
index 55571a5c915..44cf5ca0b30 100644
--- a/packages/twenty-shared/src/i18n/generate-message-id.ts
+++ b/packages/twenty-shared/src/i18n/generate-message-id.ts
@@ -3,14 +3,11 @@ import { utf8ToBytes } from '@noble/hashes/utils';
import { isDefined } from '../utils/validation/isDefined';
-// Lingui's generated-id scheme (catalogs are emitted with `printLinguiId: true`).
-// Server, SDK and front-component runtime must produce byte-identical ids --
-// drift silently untranslates -- so there is exactly one implementation, in
-// pure JS so the sandboxed front-component worker can call it too.
+// Server, SDK and the sandboxed front-component worker must emit Lingui's ids byte for byte (drift silently untranslates),
+// so this is the single implementation, in pure JS.
const UNIT_SEPARATOR = String.fromCharCode(0x1f);
-// The same few thousand source strings recur across requests; the cap bounds
-// a workspace that mints unusual labels.
+// The cap bounds a workspace that mints unusual labels.
const MAX_CACHED_MESSAGE_IDS = 50_000;
const messageIdByCacheKey = new Map<string, string>();
diff --git a/packages/twenty-shared/src/i18n/get-metadata-label-context.ts b/packages/twenty-shared/src/i18n/get-metadata-label-context.ts
index 02c707cbd03..8ee8958a842 100644
--- a/packages/twenty-shared/src/i18n/get-metadata-label-context.ts
+++ b/packages/twenty-shared/src/i18n/get-metadata-label-context.ts
@@ -3,12 +3,8 @@ import {
type TranslatablePropertyName,
} from './translatable-properties-by-metadata-name';
-// Message context for a metadata label, e.g. 'fieldMetadata.label'. The same
-// English string can label different roles ('Company' is an object name and a
-// field label), and many languages need different words for them, so catalog
-// entries are keyed per role. Authoring sites repeat this rule as literal msg
-// contexts because lingui extraction cannot evaluate a call; the standard
-// catalog guard spec is what pins them to the ids the read path computes.
+// Keyed per role since many languages word the same English label differently ('Company' as object vs field).
+// Authoring sites repeat this as literal msg contexts (lingui cannot evaluate a call); the standard catalog guard spec pins them.
export const getMetadataLabelContext = <T extends TranslatableMetadataName>(
metadataName: T,
property: TranslatablePropertyName<T>,
diff --git a/packages/twenty-shared/src/i18n/interpolate-message-placeholders.ts b/packages/twenty-shared/src/i18n/interpolate-message-placeholders.ts
index 3cdbbaa2046..a83767b078e 100644
--- a/packages/twenty-shared/src/i18n/interpolate-message-placeholders.ts
+++ b/packages/twenty-shared/src/i18n/interpolate-message-placeholders.ts
@@ -2,9 +2,7 @@ import { isDefined } from '../utils/validation/isDefined';
const PLACEHOLDER_REGEX = /\{(\w+)\}/g;
-// Placeholders the caller cannot fill are left as written, so a message can be
-// translated by whoever owns the catalog and filled later by whoever owns the
-// values.
+// Unfillable placeholders are left as written so whoever owns the values can fill them later.
export const interpolateMessagePlaceholders = (
message: string,
values?: Record<string, string | number | undefined>,
diff --git a/packages/twenty-shared/src/i18n/metadata-label-placeholder.ts b/packages/twenty-shared/src/i18n/metadata-label-placeholder.ts
index e28b0b70f9d..d57331a36e6 100644
--- a/packages/twenty-shared/src/i18n/metadata-label-placeholder.ts
+++ b/packages/twenty-shared/src/i18n/metadata-label-placeholder.ts
@@ -1,8 +1,6 @@
import { capitalize } from '../utils/strings/capitalize';
import { isDefined } from '../utils/validation/isDefined';
-// The closed vocabulary metadata-label placeholders draw from -- adding a name
-// here is what makes it fillable, on the server and the client.
export const METADATA_LABEL_PLACEHOLDER_NAMES = [
'objectLabel',
'objectLabelSingular',
@@ -13,8 +11,7 @@ export const METADATA_LABEL_PLACEHOLDER_NAMES = [
export type MetadataLabelPlaceholderName =
(typeof METADATA_LABEL_PLACEHOLDER_NAMES)[number];
-// The subset an object metadata can fill. objectLabel is deliberately absent:
-// it follows the record selection, which only the client knows.
+// The subset an object metadata can fill; objectLabel is left out as it follows the record selection, which only the client knows.
export const OBJECT_METADATA_LABEL_PLACEHOLDER_NAMES = [
'objectLabelSingular',
'objectLabelPlural',
@@ -29,9 +26,7 @@ export const getMetadataLabelPlaceholder = (
name: MetadataLabelPlaceholderName,
): string => `{${name}}`;
-// Lingui drops ICU arguments it is not given, so translating with the
-// placeholders as their own values keeps them in the output for the side that
-// can actually resolve them.
+// Lingui drops ICU arguments it is not given, so pass placeholders through as their own values.
export const METADATA_LABEL_PLACEHOLDER_PASS_THROUGH: Record<
MetadataLabelPlaceholderName,
string
diff --git a/packages/twenty-shared/src/i18n/translatable-properties-by-metadata-name.ts b/packages/twenty-shared/src/i18n/translatable-properties-by-metadata-name.ts
index c21edca1790..325db385999 100644
--- a/packages/twenty-shared/src/i18n/translatable-properties-by-metadata-name.ts
+++ b/packages/twenty-shared/src/i18n/translatable-properties-by-metadata-name.ts
@@ -1,13 +1,6 @@
import { type AllMetadataName } from '@/metadata/types/AllMetadataName';
-// The single source of truth for which provider-owned metadata properties are
-// translatable. twenty-server resolves them against a catalog at request time
-// and derives MetadataEntityTranslatablePropertyName from this list; twenty-sdk
-// extracts them out of an application manifest at build time.
-//
-// The two used to keep separate lists and drifted: a property missing from one
-// side is a string that is either extracted and never read, or read and never
-// extracted, and both failure modes are silent.
+// Read by both twenty-server and twenty-sdk extraction: a property missing on either side fails silently.
export const TRANSLATABLE_PROPERTIES_BY_METADATA_NAME = {
objectMetadata: ['labelSingular', 'labelPlural', 'description'],
fieldMetadata: ['label', 'description'],
diff --git a/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts b/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts
index 7bcaae4727e..38fb39b48af 100644
--- a/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts
+++ b/packages/twenty-shared/src/logic-function/logic-function-execution-context.type.ts
@@ -2,8 +2,7 @@ export type LogicFunctionExecutionContext = {
retryCount: number;
maxRetries: number;
workspaceId: string;
- // Null when nobody triggered the run: cron, install hooks and
- // unauthenticated webhooks have no person behind them.
+ // Null for cron, install hooks and unauthenticated webhooks.
userWorkspaceId: string | null;
workspaceMemberId: string | null;
};
diff --git a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts
index 9b566e650e5..ed2aa74c678 100644
--- a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts
+++ b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts
@@ -4,22 +4,9 @@ import { getSystemRelationFieldUniversalIdentifier } from '@/application/determi
import { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from '@/metadata/constants/standard-object-universal-identifiers.constant';
import { buildStandardObjectSystemFields } from '@/metadata/utils/internal/build-standard-object-system-fields.util';
-// Important notice:
-// - Never ever mutate an existing universal identifier
-// - Deleting an existing universal identifier should be very rare
-// - System field universal identifiers (id, createdAt, updatedAt, deletedAt,
-// createdBy, updatedBy, position, searchVector) are deterministically derived
-// from the standard application universal identifier, the object universal
-// identifier and the field name (buildStandardObjectSystemFields). The name
-// field is a default field, not a system field, and keeps its hardcoded
-// universal identifier.
-// - System relation field universal identifiers are deterministically derived
-// from the object + the relation target object
-// (getSystemRelationFieldUniversalIdentifier).
-//
-// Fields live in their own const so that both STANDARD_OBJECTS' `fields` and
-// its INDEX view (buildStandardObjectIndexView) can read the same field
-// universal identifiers.
+// Never mutate an existing universal identifier, and delete one only rarely.
+// System field ids come from buildStandardObjectSystemFields and getSystemRelationFieldUniversalIdentifier;
+// name is a default field, not a system one, and keeps its hardcoded id.
export const STANDARD_OBJECT_FIELDS = {
agentChatThread: {
...buildStandardObjectBaseFields(
diff --git a/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.ts
index f274f7aca05..c74aafc0cd6 100644
--- a/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.ts
+++ b/packages/twenty-shared/src/metadata/constants/standard-object-universal-identifiers.constant.ts
@@ -1,9 +1,4 @@
-// Single source of truth for standard object universal identifiers: an object
-// identifier is referenced from its own STANDARD_OBJECTS entry, from its
-// STANDARD_OBJECT_FIELDS entry (system fields and INDEX view derivation), and
-// sometimes from another object's declaration (default relation builders need
-// both the host and the source object identifiers, and an object literal
-// cannot reference its sibling keys).
+// Separate from STANDARD_OBJECTS because an object literal cannot reference its sibling keys.
export const STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS = {
agentChatThread: 'fab0fff8-0c90-4116-9bb0-7dbc07392633',
agentChatThreadTarget: '9f2a5bf4-3a57-4e61-b561-eaf5a5b86973',
diff --git a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts
index c5beca88f85..c7f81ddf447 100644
--- a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts
+++ b/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts
@@ -3,22 +3,8 @@ import { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from '@/metadata/constants/stan
import { buildStandardObjectIndexView } from '@/metadata/utils/internal/build-standard-object-index-view.util';
import { buildStandardObjectRecordPageFieldsView } from '@/metadata/utils/internal/build-standard-object-record-page-fields-view.util';
-// Important notice:
-// - Never ever mutate an existing universal identifier
-// - Deleting an existing universal identifier should be very rare
-// - Field universal identifiers live in STANDARD_OBJECT_FIELDS (see
-// standard-object-fields.constant.ts), so both an object's `fields` and its
-// INDEX view can read the same values.
-// - INDEX view universal identifiers (the "All {objectLabelPlural}" table view
-// keyed on ViewKey.INDEX) and their view-field universal identifiers are
-// deterministically derived by buildStandardObjectIndexView
-// (getSystemViewUniversalIdentifier for the view,
-// getSystemViewFieldUniversalIdentifier for each view field).
-// - FIELDS_WIDGET record-page view universal identifiers (keyed on
-// SYSTEM_VIEW_KEYS.FIELDS_WIDGET), their view fields and their view field groups are
-// deterministically derived by buildStandardObjectRecordPageFieldsView; the group
-// names passed there MUST match the ones the server standard view-field-group
-// builders assign.
+// Never mutate an existing universal identifier, and delete one only rarely.
+// Group names passed to buildStandardObjectRecordPageFieldsView MUST match the server's standard view-field-group builders.
export const STANDARD_OBJECTS = {
attachment: {
universalIdentifier: STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.attachment,
diff --git a/packages/twenty-shared/src/metadata/constants/standard-page-layout-universal-identifiers.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-page-layout-universal-identifiers.constant.ts
index 8616f27369e..5b3625b2abf 100644
--- a/packages/twenty-shared/src/metadata/constants/standard-page-layout-universal-identifiers.constant.ts
+++ b/packages/twenty-shared/src/metadata/constants/standard-page-layout-universal-identifiers.constant.ts
@@ -1,13 +1,8 @@
import { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from '@/metadata/constants/standard-object-universal-identifiers.constant';
import { buildStandardObjectRecordPageLayout } from '@/metadata/utils/internal/build-standard-object-record-page-layout.util';
-// Never mutate an existing universal identifier
-// Deleting an existing universal identifier should be very rare
-// Record-page layout universal identifiers are deterministically derived by
-// buildStandardObjectRecordPageLayout (layout keyed on the object + the
-// name-free RECORD_PAGE discriminator, tabs on their title within the layout,
-// widgets on their title within their tab). The titles passed here MUST match
-// the ones the server standard page-layout configs assign.
+// Never mutate an existing universal identifier, and delete one only rarely.
+// buildStandardObjectRecordPageLayout derives ids from titles, which MUST match the server's standard page-layout configs.
export const STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS = {
myFirstDashboard: {
diff --git a/packages/twenty-shared/src/translations/utils/__tests__/getLocaleTextDirection.test.ts b/packages/twenty-shared/src/translations/utils/__tests__/getLocaleTextDirection.test.ts
index 75d780ea6f7..850329583d9 100644
--- a/packages/twenty-shared/src/translations/utils/__tests__/getLocaleTextDirection.test.ts
+++ b/packages/twenty-shared/src/translations/utils/__tests__/getLocaleTextDirection.test.ts
@@ -19,8 +19,7 @@ describe('getLocaleTextDirection', () => {
expect(getLocaleTextDirection('ar-EG')).toBe('rtl');
});
- // A locale it cannot place is laid out left to right rather than throwing:
- // the wrong direction is recoverable, a blank app is not.
+ // Falls back to left to right: a wrong direction is recoverable, a blank app is not.
it('falls back to ltr for an unknown locale', () => {
expect(getLocaleTextDirection('zz-ZZ')).toBe('ltr');
expect(getLocaleTextDirection('')).toBe('ltr');
diff --git a/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts b/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts
index eb0ca92e022..11486f34063 100644
--- a/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts
+++ b/packages/twenty-shared/src/translations/utils/getLocaleTextDirection.ts
@@ -1,8 +1,7 @@
import { type TextDirection } from '@/translations/types/TextDirection';
-// Scripts written right to left, by ISO 639-1 language subtag. Twenty ships
-// Arabic and Hebrew today; the rest are listed so that ticking one of them in
-// Crowdin does not silently lay the app out backwards.
+// RTL languages by ISO 639-1 subtag, beyond the shipped Arabic and Hebrew so enabling another in Crowdin
+// does not lay the app out backwards.
const RIGHT_TO_LEFT_LANGUAGES = [
'ar',
'dv',
diff --git a/packages/twenty-shared/src/types/AppPath.ts b/packages/twenty-shared/src/types/AppPath.ts
index d6329500e5d..a66ad88ccb3 100644
--- a/packages/twenty-shared/src/types/AppPath.ts
+++ b/packages/twenty-shared/src/types/AppPath.ts
@@ -1,12 +1,10 @@
export enum AppPath {
- // Not logged-in
Verify = '/verify',
VerifyEmail = '/verify-email',
SignInUp = '/welcome',
Invite = '/invite/:workspaceInviteHash',
ResetPassword = '/reset-password/:passwordResetToken',
- // Onboarding
WorkspaceActivation = '/workspace-activation',
CreateProfile = '/create/profile',
SyncEmails = '/sync/emails',
@@ -16,7 +14,6 @@ export enum AppPath {
PlanRequiredSuccess = '/plan-required/payment-success',
BookCall = '/book-call',
- // Onboarded
AiChat = '/chat/:threadId?',
Index = '/',
// Mobile only: the navigation menu is a page there rather than a drawer.
@@ -39,7 +36,6 @@ export enum AppPath {
// Deep link for twenty.com/dpa → in-app DPA generator (login-gated redirect).
Dpa = '/dpa',
- // 404 page not found
NotFoundWildcard = '*',
NotFound = '/not-found',
}
diff --git a/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.ts b/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.ts
index d957eff1a58..a613f502c0a 100644
--- a/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.ts
+++ b/packages/twenty-shared/src/types/page-layout/PageLayoutWidgetConfiguration.ts
@@ -102,8 +102,7 @@ export type FieldConfiguration = {
fieldMetadataId: string;
fieldDisplayMode: 'CARD' | 'EDITOR' | 'FIELD' | 'VIEW' | 'TABLE';
viewId?: string;
- // One-to-many relation field on the relation target object, to list records
- // two relation hops away (e.g. Company -> People -> Owned opportunities)
+ // One-to-many relation field on the target object, for records two hops away (e.g. Company -> People -> Owned opportunities).
nestedRelationFieldMetadataId?: string | null;
isUIEditable?: boolean;
};
diff --git a/packages/twenty-shared/src/utils/__tests__/evalFromContext.test.ts b/packages/twenty-shared/src/utils/__tests__/evalFromContext.test.ts
index ea4219ea310..5a15135fd6e 100644
--- a/packages/twenty-shared/src/utils/__tests__/evalFromContext.test.ts
+++ b/packages/twenty-shared/src/utils/__tests__/evalFromContext.test.ts
@@ -38,8 +38,6 @@ describe('evalFromContext', () => {
expect(evalFromContext('{{step.[key.with.dots]}}', context)).toBe('dotted');
});
- // A path ending in a number or a keyword read it as a value rather than a
- // key, so it never resolved; mid-path the same segment is an ordinary key
it('should reject a trailing bare number but index through it mid-path', () => {
expect(evalFromContext('{{list.[0]}}', context)).toBe('a');
expect(evalFromContext('{{list.[1].x}}', context)).toBe('x1');
@@ -48,8 +46,7 @@ describe('evalFromContext', () => {
expect(evalFromContext('{{list.0.length}}', context)).toBe(1);
});
- // Handlebars compiled each hop as `x != null ? x.key : x`, so walking through
- // a null yields that null rather than undefined
+ // Handlebars compiled each hop as `x != null ? x.key : x`.
it('should short-circuit to the nullish container it walks through', () => {
expect(evalFromContext('{{nested.child.whatever}}', context)).toBeNull();
});
@@ -66,8 +63,7 @@ describe('evalFromContext', () => {
expect(evalFromContext('{{list.length}}', context)).toBe(2);
});
- // The value is JSON round-tripped, which is what the Handlebars `json` helper
- // plus JSON.parse did, so these coercions are part of the contract
+ // The Handlebars `json` helper plus JSON.parse made these coercions part of the contract.
it('should JSON round-trip the resolved value', () => {
expect(evalFromContext('{{date}}', context)).toBe(
'2020-01-02T03:04:05.000Z',
@@ -99,8 +95,7 @@ describe('evalFromContext', () => {
expect(evalFromContext('not a token', context)).toBeUndefined();
});
- // `@root.` was a data lookup in Handlebars and compiled to a different guard
- // from a bare path, so these two families are pinned separately
+ // `@root.` compiled to a different guard than a bare path in Handlebars.
describe('context-prefixed paths', () => {
const prefixContext = {
zero: 0,
@@ -115,8 +110,6 @@ describe('evalFromContext', () => {
expect(evalFromContext('{{this.obj.p}}', prefixContext)).toBe(1);
});
- // The guard is a plain truthiness test, so NaN short-circuits like any other
- // falsy value and JSON round-trips to null
it('should short-circuit an @root path on NaN', () => {
expect(
evalFromContext('{{@root.notANumber.missing}}', { notANumber: NaN }),
@@ -143,9 +136,6 @@ describe('evalFromContext', () => {
});
});
- // A keyword read as a value rather than a key, which Handlebars only did
- // where a value was expected: the whole expression, or the last segment of a
- // path. Anywhere else it is an ordinary key, so `obj.true.length` resolves
it('should not resolve a trailing bare keyword segment', () => {
const keywordContext = { obj: { true: 'T', null: 'N' }, null: { x: 1 } };
diff --git a/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts b/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts
index a25778c358f..cf49dd2854b 100644
--- a/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts
+++ b/packages/twenty-shared/src/utils/email/__tests__/formatEmailAddress.test.ts
@@ -47,8 +47,7 @@ describe('formatEmailAddress', () => {
expect(reparsed).toHaveLength(2);
expect(reparsed[0]?.address).toBe('[email protected]');
- // addressparser collapses the escaped backslash: containment is the
- // contract here, not byte fidelity of exotic display names.
+ // addressparser collapses the escaped backslash, so only containment is asserted.
expect(reparsed[0]?.name).toBe('x"y');
expect(reparsed[1]).toEqual({ address: '[email protected]', name: '' });
});
diff --git a/packages/twenty-shared/src/utils/evalFromContext.ts b/packages/twenty-shared/src/utils/evalFromContext.ts
index 940bcae95aa..e830ef8e90f 100644
--- a/packages/twenty-shared/src/utils/evalFromContext.ts
+++ b/packages/twenty-shared/src/utils/evalFromContext.ts
@@ -2,20 +2,9 @@ import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from '@/utils/validation/isDefined';
-// Resolves a single `{{ path }}` token against a context object.
-//
-// This replaces a Handlebars `{{{ json <path> }}}` compile whose only purpose
-// was to read a value out of the context: Handlebars is CommonJS, so bundlers
-// cannot tree-shake it, and it reached every browser consumer of this package
-// through the utils barrel for what is a property lookup.
-//
-// The quirks below are Handlebars' own and are reproduced deliberately, because
-// workflows already in flight were authored against them:
-// - a bare numeric path segment never resolves (`arr.0`), only `arr.[0]` does
-// - only own properties resolve, so prototype access is denied
-// - extra space-separated params are ignored (they were helper params)
-// - the value is JSON round-tripped, so Dates become ISO strings, NaN and
-// Infinity become null, and functions or circular values become undefined
+// Resolves one `{{ path }}` token without Handlebars, which is CommonJS and cannot be tree-shaken from browser bundles.
+// Reproduces its `{{{ json <path> }}}` quirks on purpose since in-flight workflows rely on them: own properties only,
+// extra params ignored, values JSON round-tripped (Dates become ISO strings, NaN and functions drop).
const TOKEN_PATTERN = /^\{\{([^{}]*)\}\}$/;
const NUMBER_LITERAL_PATTERN = /^-?\d+(\.\d+)?$/;
const WHOLE_CONTEXT_PATHS = ['.', 'this', '@root'];
@@ -24,8 +13,6 @@ const KEYWORD_LITERALS = ['true', 'false', 'null', 'undefined'];
type PathSegment = { value: string; isLiteralSegment: boolean };
-// Reads the first space-separated token, treating `[...]` as atomic so that
-// `{{step.[key with space] extra}}` still yields `step.[key with space]`
const readFirstParam = (expression: string): string | undefined => {
let param = '';
@@ -96,8 +83,7 @@ const parsePathSegments = (path: string): PathSegment[] | undefined => {
continue;
}
- // An empty segment: a leading dot is not a path at all, while a repeated
- // dot mid-path truncates it, both matching how Handlebars parsed these
+ // A leading dot is not a path and a repeated dot truncates it, as in Handlebars.
if (segments.length === 0) {
return undefined;
}
@@ -105,7 +91,6 @@ const parsePathSegments = (path: string): PathSegment[] | undefined => {
return segments;
}
- // Anything other than a separator straight after `[...]`, such as `[a]b`
if (justClosedLiteralSegment) {
return undefined;
}
@@ -169,8 +154,7 @@ export const evalFromContext = (
return toJsonValue(context);
}
- // Stripped before the `@` guard below, so `@root.foo` stays a path rooted at
- // the context rather than being rejected as an unsupported data variable
+ // Stripped before the `@` guard so `@root.foo` is not rejected as a data variable.
const contextPrefix = CONTEXT_PREFIXES.find((prefix) =>
param.startsWith(prefix),
);
@@ -232,9 +216,7 @@ export const evalFromContext = (
return toJsonValue(context);
}
- // A number or a keyword read as a value rather than a key, so a path ending in
- // one never resolved. Mid-path they are ordinary keys: `arr.0` is undefined
- // but `arr.0.length` is not, and `[0]` works in either position
+ // Handlebars read a trailing number or keyword as a value, so it never resolved; mid-path it is a key.
if (
!lastSegment.isLiteralSegment &&
(NUMBER_LITERAL_PATTERN.test(lastSegment.value) ||
@@ -243,8 +225,7 @@ export const evalFromContext = (
return undefined;
}
- // A leading `[]` collapsed the whole path to the context in Handlebars, but
- // only for a bare path: under `@root.` it stayed an ordinary empty-string key
+ // Handlebars collapsed a leading `[]` to the context, except under `@root.`.
if (
contextPrefix !== '@root.' &&
firstSegment.isLiteralSegment &&
@@ -253,17 +234,13 @@ export const evalFromContext = (
return toJsonValue(context);
}
- // Handlebars guarded each hop, but with a different test depending on how the
- // path started: `x != null ? x.key : x` for a bare or `this.` path, and a
- // plain truthiness check for an `@root.` data lookup, so walking through 0 or
- // '' yields that value there rather than undefined
+ // Handlebars guarded `@root.` hops by truthiness and other paths by `!= null`.
const shortCircuitsOnFalsy = contextPrefix === '@root.';
let resolved: unknown = context;
for (const segment of segments) {
- // Mirrors the compiled guard exactly rather than enumerating falsy values,
- // which would miss NaN and anything else JavaScript counts as falsy
+ // Mirrors the compiled guard rather than enumerating falsy values, which would miss NaN.
const shortCircuits = shortCircuitsOnFalsy
? !resolved
: !isDefined(resolved);
diff --git a/packages/twenty-shared/src/utils/url/normalizeUrlOrigin.ts b/packages/twenty-shared/src/utils/url/normalizeUrlOrigin.ts
index 6f102eeffe4..4e50170f515 100644
--- a/packages/twenty-shared/src/utils/url/normalizeUrlOrigin.ts
+++ b/packages/twenty-shared/src/utils/url/normalizeUrlOrigin.ts
@@ -1,9 +1,7 @@
import { getUrlSafely } from '@/utils/getUrlSafely';
import { isDefined } from '@/utils/validation';
-// Lowercases the URL origin (scheme + host) and removes a trailing slash.
-// URL() already lowercases the origin and preserves percent-encoded sequences
-// in the path, query, and hash (e.g. %2F stays %2F, %2520 stays %2520).
+// Only strips a trailing slash: URL() already lowercases the origin and preserves percent-encoded sequences elsewhere.
export const normalizeUrlOrigin = (rawUrl: string) => {
const url = getUrlSafely(rawUrl);
diff --git a/packages/twenty-shared/src/utils/variable-resolver.ts b/packages/twenty-shared/src/utils/variable-resolver.ts
index b9006790b37..624789066d7 100644
--- a/packages/twenty-shared/src/utils/variable-resolver.ts
+++ b/packages/twenty-shared/src/utils/variable-resolver.ts
@@ -77,8 +77,7 @@ export const resolveStringTemplate = (
});
};
-// Returns the resolved value itself when the whole string is one variable, so
-// `{{step.amount}}` keeps its type instead of being stringified
+// A lone `{{step.amount}}` keeps its type instead of being stringified.
const resolveString = (
input: string,
context: Record<string, unknown>,
diff --git a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
index efc0688d745..ef2bc2269a2 100644
--- a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
@@ -6,8 +6,7 @@ export const workflowAiAgentActionSettingsSchema =
input: z.object({
agentId: z.string().optional(),
prompt: z.string().optional(),
- // Off by default: an agent that can ask pauses its run until someone
- // answers, which existing workflows were not built to expect.
+ // Off by default: asking pauses the run, which existing workflows were not built to expect.
canAskQuestions: z.boolean().optional(),
}),
});
diff --git a/packages/twenty-shared/src/workflow/schemas/classify-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/classify-action-settings-schema.ts
index 87c7a87f9fe..cfbe79b55cb 100644
--- a/packages/twenty-shared/src/workflow/schemas/classify-action-settings-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/classify-action-settings-schema.ts
@@ -4,16 +4,10 @@ import { AI_EVALUATION_QUESTION_TYPES } from '@/ai/constants/ai-evaluation-quest
import { baseWorkflowActionSettingsSchema } from './base-workflow-action-settings-schema';
-// An answer name is one segment of a variable path — {{stepId.answers.<name>}}.
-// A dot, brace or space in it would be read as structure by the variable
-// resolver, so the output the picker advertises would never resolve.
+// A dot, brace or space would be read as variable-path structure, so the answer would never resolve.
export const CLASSIFY_ANSWER_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
-// A choice option's name keys its probability, so it is a path segment too:
-// {{stepId.answers.<name>.probabilities.<option>}}. It stays free text because
-// the model reads it as the label it is, and a segment with spaces or brackets
-// survives the round trip through escapePathSegment. A dot does not: nothing
-// escapes it, so the resolver would walk it as two keys.
+// Option names are path segments too; escapePathSegment handles spaces and brackets but not dots.
export const CLASSIFY_OPTION_NAME_FORBIDDEN_CHARACTER = '.';
export const workflowClassifyCriterionSchema = z.object({
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts
index eb20772a936..602a7c3c9f6 100644
--- a/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts
@@ -6,8 +6,7 @@ export const workflowRunStateStepInfoSchema = z.object({
error: z.any().optional(),
status: workflowRunStepStatusSchema,
retryAttempt: z.number().optional(),
- // The conversation an agent step held on this execution, kept per history
- // entry so each loop iteration's conversation stays reachable.
+ // The agent step's conversation, kept per history entry so each loop iteration's one stays reachable.
threadId: z.string().optional(),
get history() {
return z
diff --git a/packages/twenty-shared/src/workflow/types/WorkflowClassifyQuestion.ts b/packages/twenty-shared/src/workflow/types/WorkflowClassifyQuestion.ts
index 9656f01697c..4c68db2e1d7 100644
--- a/packages/twenty-shared/src/workflow/types/WorkflowClassifyQuestion.ts
+++ b/packages/twenty-shared/src/workflow/types/WorkflowClassifyQuestion.ts
@@ -1,11 +1,8 @@
import { type AiEvaluationQuestionType } from '@/ai/constants/ai-evaluation-question-type.const';
-// A `choice` option or one `score` level. Score levels are ordered lowest
-// first, and their position is the score the model returns.
+// A `choice` option or one `score` level; score levels are ordered lowest first and their position is the score.
export type WorkflowClassifyCriterion = {
- // Positional meaning, stable identity: deleting a row shifts every later
- // criterion, and an editor keyed on position would leave the shifted rows
- // showing the values they held before.
+ // Deleting a row shifts later positions, so editors must key rows on id, not position.
id: string;
name: string;
description?: string;
diff --git a/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts b/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
index e6e8dcec096..5949dfd5aa6 100644
--- a/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
+++ b/packages/twenty-shared/src/workflow/validation/constants/non-activable-workflow-validation-issue-codes.constant.ts
@@ -1,7 +1,6 @@
import { type WorkflowValidationIssueCode } from '@/workflow/validation/types/WorkflowValidation';
-// Issues a well-formed draft may carry while being edited, but that keep it
-// from being activated because a run could not proceed through them.
+// Allowed in a draft being edited, but block activation since a run could not proceed through them.
export const NON_ACTIVABLE_WORKFLOW_VALIDATION_ISSUE_CODES: ReadonlySet<WorkflowValidationIssueCode> =
new Set([
'MISSING_TRIGGER',
diff --git a/packages/twenty-shared/vite.config.ts b/packages/twenty-shared/vite.config.ts
index d7daf0fc0ef..fdb1d9c3de5 100644
--- a/packages/twenty-shared/vite.config.ts
+++ b/packages/twenty-shared/vite.config.ts
@@ -49,9 +49,7 @@ export default defineConfig(() => {
external: [
...Object.keys((packageJson as any).dependencies || {}),
'typescript',
- // `twenty-shared/i18n` hashes message ids with node:crypto. Keep the
- // builtin external so rollup emits a plain import instead of trying
- // to bundle or polyfill it.
+ // TODO: i18n now hashes with @noble/hashes, so this node:crypto external looks removable.
'node:crypto',
],
output: [
diff --git a/packages/twenty-ui/src/utilities/responsive/hooks/useIsTouchDevice.ts b/packages/twenty-ui/src/utilities/responsive/hooks/useIsTouchDevice.ts
index fca52f3479a..8add15e2a43 100644
--- a/packages/twenty-ui/src/utilities/responsive/hooks/useIsTouchDevice.ts
+++ b/packages/twenty-ui/src/utilities/responsive/hooks/useIsTouchDevice.ts
@@ -1,8 +1,5 @@
import { TOUCH_DEVICE_MEDIA_QUERY } from '@ui/utilities/responsive/constants/TouchDeviceMediaQuery';
import { useMediaQuery } from '@ui/utilities/responsive/hooks/useMediaQuery';
-// Viewport width tells us how much room we have to lay things out, not how the
-// user points at them: a narrow window on a desktop still hovers, a tablet in
-// landscape never does. Interaction behaviour must branch on this, not on
-// useIsMobile.
+// Branch on hover capability, not useIsMobile: a narrow desktop window still hovers, a landscape tablet never does.
export const useIsTouchDevice = () => useMediaQuery(TOUCH_DEVICE_MEDIA_QUERY);
diff --git a/packages/twenty-utils/crowdin-normalizer/constants/__tests__/normalization-rules.constant.spec.ts b/packages/twenty-utils/crowdin-normalizer/constants/__tests__/normalization-rules.constant.spec.ts
index aa36e808490..aaf71588457 100644
--- a/packages/twenty-utils/crowdin-normalizer/constants/__tests__/normalization-rules.constant.spec.ts
+++ b/packages/twenty-utils/crowdin-normalizer/constants/__tests__/normalization-rules.constant.spec.ts
@@ -26,8 +26,6 @@ describe('NORMALIZATION_RULES', () => {
]);
});
- // Identifiers, links and code spans are an MDX concern; every other rule
- // reads an ICU catalog and belongs to PO.
it('runs every rule but the MDX-specific one against PO catalogs', () => {
const mdxOnly = NORMALIZATION_RULES.filter(
(rule) => !rule.formats.includes('po'),
diff --git a/packages/twenty-utils/crowdin-normalizer/normalize-crowdin-translations.ts b/packages/twenty-utils/crowdin-normalizer/normalize-crowdin-translations.ts
index a51f74945a0..d1495030da1 100644
--- a/packages/twenty-utils/crowdin-normalizer/normalize-crowdin-translations.ts
+++ b/packages/twenty-utils/crowdin-normalizer/normalize-crowdin-translations.ts
@@ -48,9 +48,7 @@ function parseProjectIdOrThrow(): number {
const CATALOG_FORMATS: CatalogFormat[] = ['po', 'mdx'];
-// Selecting by format rather than by name means a new rule protects every
-// project holding that format, instead of only the workflow someone remembered
-// to edit. --rules stays for narrowing a run to one rule by hand.
+// Selected by format so a new rule covers every project with that format, not just one workflow.
function selectRulesOrThrow(): NormalizationRule[] {
const requestedFormat = getArgumentValue('format');
const requestedNames = (getArgumentValue('rules') ?? '')
@@ -192,8 +190,7 @@ async function repairOne(
finding: NormalizationFinding,
): Promise<boolean> {
try {
- // An empty repair means the translation could not be salvaged: deleting it
- // without a replacement falls back to English until Crowdin retranslates.
+ // An empty fix means unsalvageable: deleting without a replacement falls back to English until Crowdin retranslates.
if (finding.fixedText !== '') {
await addTranslation(context, {
stringId: finding.stringId,
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/__tests__/escaped-every-character.rule.spec.ts b/packages/twenty-utils/crowdin-normalizer/rules/__tests__/escaped-every-character.rule.spec.ts
index 2d170e99865..c95a269bdf6 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/__tests__/escaped-every-character.rule.spec.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/__tests__/escaped-every-character.rule.spec.ts
@@ -16,8 +16,6 @@ describe('ESCAPED_EVERY_CHARACTER_RULE', () => {
},
);
- // A path or a regex carries a few backslashes among ordinary text, which is
- // the translator writing what the source asked for.
it.each([
'C:\\Users\\name\\file',
'Escape it as \\n to break the line',
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/__tests__/translated-identifier.rule.spec.ts b/packages/twenty-utils/crowdin-normalizer/rules/__tests__/translated-identifier.rule.spec.ts
index 14e3c3d765e..5dced149089 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/__tests__/translated-identifier.rule.spec.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/__tests__/translated-identifier.rule.spec.ts
@@ -15,8 +15,6 @@ describe('TRANSLATED_IDENTIFIER_RULE', () => {
);
});
- // A translation reorders spans to suit its own grammar, so position says
- // nothing about which source span belongs in which slot.
it('stands down on more than one span, where order cannot be trusted', () => {
const sourceText =
'The `twenty-app` keyword in your `package.json` `keywords` array';
@@ -27,9 +25,7 @@ describe('TRANSLATED_IDENTIFIER_RULE', () => {
expect(fix(translationText, sourceText)).toBe(translationText);
});
- // Backticks in the docs mark UI labels as often as symbols, and the reader
- // sees those labels translated in their own app, so restoring them would
- // un-translate correct work.
+ // Backticked UI labels are rightly translated, so restoring them would undo correct work.
it.each([
[
'Go to `Settings` in the left sidebar.',
@@ -87,8 +83,6 @@ describe('TRANSLATED_IDENTIFIER_RULE', () => {
},
);
- // Lining them up positionally is only sound when both sides hold the same
- // number; a translation that dropped or added one cannot be matched safely.
it('stands down when the counts do not line up', () => {
const sourceText = 'Use `a` and `b`.';
@@ -103,9 +97,6 @@ describe('TRANSLATED_IDENTIFIER_RULE', () => {
expect(detect(translationText, sourceText)).toBe(false);
});
- // Translated pages live under /<lang>/ and link to each other there, so a
- // locale-prefixed target is the translation being right, not wrong. Paths and
- // link targets are left to a human.
it('leaves link targets alone, including locale-prefixed ones', () => {
const sourceText = 'See [the guide](/user-guide/billing).';
const translationText = 'Vezi [ghidul](/ro/user-guide/billing).';
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/__tests__/wordless-translation.rule.spec.ts b/packages/twenty-utils/crowdin-normalizer/rules/__tests__/wordless-translation.rule.spec.ts
index cc716c4afa2..ac246dc8555 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/__tests__/wordless-translation.rule.spec.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/__tests__/wordless-translation.rule.spec.ts
@@ -17,8 +17,6 @@ describe('WORDLESS_TRANSLATION_RULE', () => {
expect(detect(' .,; ', 'Regenerate key')).toBe(true);
});
- // \w is ASCII-only in JavaScript, so a naive check would delete every
- // translation in a non-Latin script.
it.each([
['他們的值必須是唯一的', 'Chinese'],
['הערכים חייבים להיות ייחודיים', 'Hebrew'],
@@ -43,11 +41,8 @@ describe('WORDLESS_TRANSLATION_RULE', () => {
expect(detect('{count}', '{count}')).toBe(false);
});
- // Ignoring placeholder names would catch a translation left as a bare
- // {count}, but a dry run over ~200k strings found none of those and two
- // Finnish translations that legitimately render a connector word as a
- // symbol. Deleting a good translation is worse than keeping a thin one, so
- // the rule reads the whole string.
+ // A ~200k-string dry run found no bare {count} translations but two valid Finnish symbol renderings;
+ // deleting a good translation is worse than keeping a thin one, so the rule reads the whole string.
it('keeps a translation that renders a connector word as a symbol', () => {
expect(detect('{0} / {1}', '{0} of {1}')).toBe(false);
expect(detect(' /{intervalLabel}', ' per {intervalLabel}')).toBe(false);
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/corrupted-model-output.rule.ts b/packages/twenty-utils/crowdin-normalizer/rules/corrupted-model-output.rule.ts
index c002138149e..d0d47404f00 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/corrupted-model-output.rule.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/corrupted-model-output.rule.ts
@@ -1,8 +1,6 @@
import { type NormalizationRule } from '../types/normalization-rule.type';
-// Trailing characters the machine translator leaves behind once its response
-// envelope bleeds into the string. Only stripped when the source does not end
-// the same way, so legitimate quotes and brackets survive.
+// Machine-translator envelope residue; only stripped when the source does not end the same way.
const DEBRIS_CHARACTERS = new Set([
' ',
'\t',
@@ -15,8 +13,7 @@ const DEBRIS_CHARACTERS = new Set([
'"',
]);
-// Fragments of the translator's own JSON/markdown envelope. A salvaged prefix
-// carrying one of these was cut inside the envelope rather than after it.
+// A salvaged prefix carrying one of these was cut inside the envelope rather than after it.
const ENVELOPE_REGEX = /pluralForm|```|\\",\\"|\[/;
const ICU_ARGUMENT_REGEX = /\{\s*([A-Za-z0-9_]+)\s*[,}]/g;
@@ -102,9 +99,7 @@ function salvage(text: string, sourceText?: string): string {
const source = sourceText ?? '';
const cutText = cutAtUnmatchedBrace(text);
- // Balanced text has nothing to cut. Otherwise an unclosed '{' is all that is
- // left, with no clean tail to cut after, so the translation is dropped rather
- // than guessed at.
+ // An unclosed '{' with no clean tail is dropped rather than guessed at.
if (cutText === undefined) {
return hasBalancedBraces(text) ? text : '';
}
@@ -117,8 +112,6 @@ function salvage(text: string, sourceText?: string): string {
(!ENVELOPE_REGEX.test(salvagedText) || ENVELOPE_REGEX.test(source)) &&
icuShape(salvagedText) === icuShape(source);
- // An empty repair tells the runner to delete the translation rather than
- // replace it, so the locale falls back to English until Crowdin retranslates.
return isSalvageable ? salvagedText : '';
}
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/escaped-every-character.rule.ts b/packages/twenty-utils/crowdin-normalizer/rules/escaped-every-character.rule.ts
index 63906cc6e1b..a2a54c02be2 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/escaped-every-character.rule.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/escaped-every-character.rule.ts
@@ -1,13 +1,9 @@
import { type NormalizationRule } from '../types/normalization-rule.type';
-// \w is ASCII-only in JavaScript even under the u flag, and every message this
-// rule exists for is Arabic, Japanese or Hebrew.
+// \w is ASCII-only even under the u flag, and this rule targets Arabic, Japanese and Hebrew.
const ESCAPED_CHARACTER_REGEX = /\\([\p{L}\p{N}])/gu;
-// Enough of the message to rule out a Windows path or a regex, where a handful
-// of backslashes sit among ordinary text. The corruption escapes every
-// character it touches, so the ratio separates the two cleanly: `\ا\ل\إ` scores
-// 1, `C:\Users\name\file` scores 0.2.
+// The corruption escapes every character (`\ا\ل\إ` scores 1), a Windows path only a few (about 0.2).
const MINIMUM_ESCAPED_SHARE = 0.8;
const MINIMUM_ESCAPED_CHARACTERS = 3;
@@ -19,10 +15,7 @@ function unescapedCharacterCount(text: string): number {
return [...text.replaceAll('\\', '')].length;
}
-// An import once wrote the Arabic and Japanese UI with a backslash before every
-// letter - `\ا\ل\إ\ع\د\ا\د\ا\ت` for Settings, `\ダ\ー\ク` for Dark - which ships
-// to the reader verbatim. The letters are intact, so wordless-translation sees
-// a real translation and leaves it alone.
+// An import once escaped every letter of the Arabic and Japanese UI; wordless-translation misses it as the letters remain.
function hasEscapedEveryCharacter(text: string): boolean {
const escaped = escapedCharacterCount(text);
const unescaped = unescapedCharacterCount(text);
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/escaped-unicode.rule.ts b/packages/twenty-utils/crowdin-normalizer/rules/escaped-unicode.rule.ts
index eef6dd5d344..171a239bf34 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/escaped-unicode.rule.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/escaped-unicode.rule.ts
@@ -6,10 +6,7 @@ function escapesIn(text: string): string[] {
return [...text.matchAll(ESCAPED_UNICODE_REGEX)].map(([escape]) => escape);
}
-// A source that writes the escape itself - a code sample, a string about
-// escaping - means the translation is right to carry it through. Only an escape
-// the translator introduced is a decoding failure, and without the source there
-// is no way to tell the two apart, so the rule stands down as its peers do.
+// Only escapes the source lacks are decoding failures; without the source the rule stands down.
function hasEscapedUnicode(text: string, sourceText?: string): boolean {
if (sourceText === undefined) return false;
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/invented-argument.rule.ts b/packages/twenty-utils/crowdin-normalizer/rules/invented-argument.rule.ts
index 5e1059557a5..8445db4ad03 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/invented-argument.rule.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/invented-argument.rule.ts
@@ -2,9 +2,7 @@ import { type NormalizationRule } from '../types/normalization-rule.type';
const ARGUMENT_NAME_REGEX = /^\{\s*([A-Za-z0-9_]+)\s*[,}]/;
-// Arguments the message itself takes, ignoring plural and select case bodies:
-// a translation may add cases its locale needs, but never a new argument, which
-// the caller has no value for.
+// Ignores plural and select case bodies: a locale may add cases but never an argument the caller has no value for.
function topLevelArgumentNames(text: string): Set<string> {
const names = new Set<string>();
let depth = 0;
@@ -54,8 +52,7 @@ function repairInventedArgument(text: string, sourceText?: string): string {
const repairedText = inventedArgumentNames(text, source).reduce(
(accumulator, inventedName) => {
- // Only a difference in spelling can be repaired: the argument is the same
- // one, so restoring the source's casing makes it resolve again.
+ // Only a casing difference is repairable: it is the same argument.
const intendedName = sourceNames.find(
(name) =>
name.toLowerCase() === inventedName.toLowerCase() &&
@@ -69,8 +66,7 @@ function repairInventedArgument(text: string, sourceText?: string): string {
text,
);
- // An argument the source never had has no value to render, so an unrepaired
- // translation is dropped rather than shipped with a dangling placeholder.
+ // Dropped rather than shipped with a placeholder nothing can fill.
return inventedArgumentNames(repairedText, source).length > 0
? ''
: repairedText;
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/invented-markup.rule.ts b/packages/twenty-utils/crowdin-normalizer/rules/invented-markup.rule.ts
index 8bfab2defb8..39d2bbfec56 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/invented-markup.rule.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/invented-markup.rule.ts
@@ -1,14 +1,11 @@
import { type NormalizationRule } from '../types/normalization-rule.type';
-// Any markup tag, including Lingui's numbered ones (<0>), so a source carrying
-// tags of its own is left entirely alone.
+// Includes Lingui's numbered tags (<0>), so a source with tags of its own is left alone.
const TAG_PATTERN = '<\\/?[A-Za-z0-9][^<>]*>';
const TAG_REGEX = new RegExp(TAG_PATTERN);
const ALL_TAGS_REGEX = new RegExp(TAG_PATTERN, 'g');
-// The machine translator sometimes decorates a plain string with markup of its
-// own - RTL spans, bold around numbers, highlight spans - which the reader then
-// sees as literal tags.
+// The machine translator sometimes adds markup (RTL spans, bold numbers) the reader then sees as literal tags.
function hasInventedMarkup(text: string, sourceText?: string): boolean {
return (
sourceText !== undefined &&
@@ -17,8 +14,6 @@ function hasInventedMarkup(text: string, sourceText?: string): boolean {
);
}
-// Stripping everything leaves nothing to say, and the empty result drops the
-// translation rather than shipping a blank string.
function removeInventedMarkup(text: string): string {
return text.replace(ALL_TAGS_REGEX, '').trim();
}
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/translated-identifier.rule.ts b/packages/twenty-utils/crowdin-normalizer/rules/translated-identifier.rule.ts
index 50f552265f2..59c987f0738 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/translated-identifier.rule.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/translated-identifier.rule.ts
@@ -1,10 +1,6 @@
import { type NormalizationRule } from '../types/normalization-rule.type';
-// Backticks in the docs carry two different things: symbols the machine
-// resolves, and UI labels the reader sees translated in their own app. Only the
-// first kind is restored - a span shaped like an identifier, never one shaped
-// like prose - so `useEffect` and `SELECT` are put back while `Settings` and
-// `Data Model` stay in the reader's language.
+// Only identifier-shaped spans are restored; prose-shaped ones are UI labels the reader sees translated.
const INLINE_CODE_REGEX = /`[^`\n]+`/g;
function codeSpansIn(text: string): string[] {
@@ -13,10 +9,7 @@ function codeSpansIn(text: string): string[] {
);
}
-// Package, command and header names are hyphenated lowercase, and that is the
-// shape translators actually broke: the French docs ship `vingt-emails` and the
-// Japanese `20-emails` for `twenty-emails`, each inside an npx command nobody
-// can run. Nothing in the English source has this shape without being a symbol.
+// Translators broke hyphenated names (`vingt-emails` for `twenty-emails`); no English prose takes that shape.
const KEBAB_CASE_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)+$/;
function looksLikeIdentifier(span: string): boolean {
@@ -32,12 +25,7 @@ function looksLikeIdentifier(span: string): boolean {
);
}
-// Only a message carrying exactly one span on each side is repaired. Lining
-// spans up by position looked obvious and is wrong: a translation reorders them
-// to suit its own grammar, so "the `twenty-app` keyword in your `package.json`
-// `keywords` array" comes back with keywords and package.json swapped, and
-// restoring by position writes package.json over both. With one span there is
-// no order to get wrong.
+// Only single-span messages: translations reorder spans, so restoring by position overwrites the wrong one.
function restoreIdentifiers(text: string, sourceText?: string): string {
if (sourceText === undefined) return text;
diff --git a/packages/twenty-utils/crowdin-normalizer/rules/wordless-translation.rule.ts b/packages/twenty-utils/crowdin-normalizer/rules/wordless-translation.rule.ts
index 2b9e8dc53d0..f08921a580a 100644
--- a/packages/twenty-utils/crowdin-normalizer/rules/wordless-translation.rule.ts
+++ b/packages/twenty-utils/crowdin-normalizer/rules/wordless-translation.rule.ts
@@ -1,30 +1,20 @@
import { type NormalizationRule } from '../types/normalization-rule.type';
-// \w is ASCII-only in JavaScript, which would read every Chinese, Arabic or
-// Hebrew translation as wordless. Only the Unicode letter and number categories
-// hold across the scripts we translate into.
+// \w is ASCII-only; only the Unicode letter and number categories hold across our scripts.
const WORD_CHARACTER_REGEX = /[\p{L}\p{N}]/u;
function hasWordCharacter(text: string): boolean {
return WORD_CHARACTER_REGEX.test(text);
}
-// A translation carrying no letter or digit at all cannot be a rendering of a
-// source that carries them - it is a stray backslash, an escaped quote pair,
-// punctuation debris. A source with no words of its own, such as a lone
-// placeholder or a separator, is left alone: there a wordless translation is
-// the correct one.
+// A wordless source (a lone placeholder, a separator) legitimately has a wordless translation.
function isWordlessTranslation(text: string, sourceText?: string): boolean {
- // Rules run in sequence on each other's output, so an empty text means an
- // earlier rule already dropped this translation: firing again would only
- // report the same deletion twice.
+ // Rules chain, so empty text means an earlier rule already dropped this translation.
if (sourceText === undefined || text === '') return false;
return hasWordCharacter(sourceText) && !hasWordCharacter(text);
}
-// Debris holds nothing to rebuild the missing words from, so the translation is
-// dropped and the string falls back to English until Crowdin retranslates it.
function dropTranslation(): string {
return '';
}
diff --git a/packages/twenty-utils/crowdin-normalizer/types/normalization-rule.type.ts b/packages/twenty-utils/crowdin-normalizer/types/normalization-rule.type.ts
index 37d5f067563..f2cbf8c4121 100644
--- a/packages/twenty-utils/crowdin-normalizer/types/normalization-rule.type.ts
+++ b/packages/twenty-utils/crowdin-normalizer/types/normalization-rule.type.ts
@@ -1,17 +1,13 @@
-// Catalogs Crowdin holds for Twenty: Lingui PO for the app and website, MDX for
-// the docs. ICU braces mean something different in each, so rules declare which
-// they are safe to run against rather than being opted in per workflow.
+// ICU braces mean different things in PO and MDX, so rules declare which formats they are safe for.
export type CatalogFormat = 'po' | 'mdx';
export type NormalizationRule = {
name: string;
formats: CatalogFormat[];
detect: (text: string, sourceText?: string) => boolean;
- // Returning an empty string means the translation could not be salvaged and
- // should be deleted rather than replaced.
+ // An empty string deletes the translation rather than replacing it.
fix: (text: string, sourceText?: string) => string;
- // Set by rules that compare a translation against its source but select every
- // string rather than narrowing with sourceFilter.
+ // For rules that need the source but scan every string instead of using sourceFilter.
needsSourceText?: boolean;
sourceFilter?: (sourceText: string) => boolean;
};
diff --git a/packages/twenty-utils/crowdin-normalizer/utils/is-translation-already-present-error.util.ts b/packages/twenty-utils/crowdin-normalizer/utils/is-translation-already-present-error.util.ts
index e8a7e459fc9..02259a6a8e9 100644
--- a/packages/twenty-utils/crowdin-normalizer/utils/is-translation-already-present-error.util.ts
+++ b/packages/twenty-utils/crowdin-normalizer/utils/is-translation-already-present-error.util.ts
@@ -3,8 +3,7 @@ import { CrowdinApiError } from '../errors/crowdin-api.error';
const IDENTICAL_TRANSLATION_CODE = 'identicalTranslation';
const VALIDATION_ERROR_CODE = 'validationError';
-// validationError also covers unrelated refusals, so the wording has to narrow
-// it down to the one that means the text we wanted is already there.
+// validationError also covers unrelated refusals, so the wording narrows it down.
const DUPLICATE_TRANSLATION_REGEX = /duplicate translation/i;
type CrowdinErrorBody = {
diff --git a/packages/twenty-website/src/app/.well-known/api-catalog/route.ts b/packages/twenty-website/src/app/.well-known/api-catalog/route.ts
index 5b63a83bf9e..06f2ae08f6f 100644
--- a/packages/twenty-website/src/app/.well-known/api-catalog/route.ts
+++ b/packages/twenty-website/src/app/.well-known/api-catalog/route.ts
@@ -1,10 +1,6 @@
import { SITE_URLS } from '@/platform/site-urls';
-// Route handler (not a public/ file) so the RFC 9727 application/linkset+json
-// content type survives the site's global nosniff header.
-//
-// Twenty is multi-tenant, so anchors use a `{your-workspace-url}` placeholder
-// (a workspace host such as `mycompany.twenty.com` or a custom domain).
+// Route handler so the RFC 9727 application/linkset+json content type survives the global nosniff header.
const WORKSPACE = 'https://{your-workspace-url}';
diff --git a/packages/twenty-website/src/app/[locale]/layout.tsx b/packages/twenty-website/src/app/[locale]/layout.tsx
index 81433ce6f41..049353b1acf 100644
--- a/packages/twenty-website/src/app/[locale]/layout.tsx
+++ b/packages/twenty-website/src/app/[locale]/layout.tsx
@@ -13,8 +13,6 @@ import { resolveLocaleParam } from '@/platform/i18n/resolve-locale-param';
import { WEBSITE_LOCALE_LIST } from '@/platform/i18n/website-locale-list';
import { color, fontFamily, tokenCssVariables } from '@/tokens';
-// Host Grotesk and Azeret Mono are variable fonts, declared over their full
-// wght axis so the browser interpolates every weight the site asks for.
const hostGrotesk = localFont({
src: '../../fonts/host-grotesk-latin-variable.woff2',
weight: '300 800',
@@ -47,10 +45,7 @@ const vt323 = localFont({
display: 'swap',
});
-// Inter is twenty-front's product font; the app-preview/CRM mockups render in it
-// (exposed as --font-product so the preview surfaces can rebind to it). Pinned to
-// the exact classic Inter (v12, weights 400/500/600) twenty-front self-hosts, so
-// the mockups match the product pixel-for-pixel rather than Google's current Inter.
+// Pinned to the classic Inter v12 twenty-front self-hosts, so mockups match the product pixel for pixel.
const inter = localFont({
src: [
{
@@ -74,9 +69,6 @@ const inter = localFont({
});
const globalStyles = css`
- /* One root rule instead of per-component guards: motion collapses to
- instant for users who prefer reduced motion. State still applies;
- only the travel disappears. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
diff --git a/packages/twenty-website/src/platform/routing/static-website-routes.ts b/packages/twenty-website/src/platform/routing/static-website-routes.ts
index 99d966d14d8..18f027ca96d 100644
--- a/packages/twenty-website/src/platform/routing/static-website-routes.ts
+++ b/packages/twenty-website/src/platform/routing/static-website-routes.ts
@@ -94,8 +94,6 @@ export const STATIC_WEBSITE_ROUTES: readonly WebsiteRoute[] = [
title: msg`Find a Twenty Partner — Certified Open Source CRM Experts`,
},
{
- // The application form: noindex (a utility route, excluded from the
- // sitemap by getIndexedWebsiteRoutes), reachable from the partner CTAs.
changeFrequency: 'yearly',
description: msg`Apply to join the Twenty partner ecosystem and grow your practice with the #1 open source CRM.`,
id: 'partnersApply',
@@ -168,8 +166,7 @@ export const STATIC_WEBSITE_ROUTES: readonly WebsiteRoute[] = [
title: msg`Terms of Service | Twenty`,
},
{
- // Post-checkout license activation: noindex (a utility route reached only
- // with a Stripe ?session_id=, excluded from the sitemap).
+ // Reached only with a Stripe ?session_id=.
changeFrequency: 'yearly',
description: msg`Activate your Twenty Organization license after checkout and copy your key into your self-hosted instance.`,
id: 'enterpriseActivate',
@@ -179,8 +176,7 @@ export const STATIC_WEBSITE_ROUTES: readonly WebsiteRoute[] = [
title: msg`Organization Activation | Twenty`,
},
{
- // The interactive halftone generator: an internal dev tool, noindex and
- // excluded from the sitemap (getIndexedWebsiteRoutes). Mounted client-only.
+ // Internal dev tool, mounted client-only.
changeFrequency: 'monthly',
description: msg`Interactive halftone generator exported from Twenty.`,
id: 'halftone',
diff --git a/packages/twenty-website/src/platform/routing/website-route.ts b/packages/twenty-website/src/platform/routing/website-route.ts
index 23fef9400d7..da04c713165 100644
--- a/packages/twenty-website/src/platform/routing/website-route.ts
+++ b/packages/twenty-website/src/platform/routing/website-route.ts
@@ -29,8 +29,7 @@ export type WebsiteRouteFamilyId = never;
export type SitemapChangeFrequency =
MetadataRoute.Sitemap[number]['changeFrequency'];
-// A static page. Sitemap, robots, hreflang, and metadata derive from this
-// record, so a page's SEO surface lives in one place.
+// Sitemap, robots, hreflang and metadata all derive from this record.
export type WebsiteRoute = {
changeFrequency: SitemapChangeFrequency;
description: MessageDescriptor;
@@ -44,9 +43,7 @@ export type WebsiteRoute = {
title: MessageDescriptor;
};
-// One slug under a dynamic family, produced by the family's enumerator from
-// its content source (markdown, CMS). Strings are content, not catalog
-// messages — they arrive already written per entry.
+// Strings are content, not catalog messages: they arrive already written per entry.
export type WebsiteRouteFamilyEntry = {
description: string;
lastModified?: Date;
@@ -55,9 +52,7 @@ export type WebsiteRouteFamilyEntry = {
title: string;
};
-// A dynamic route family (e.g. /articles/[slug]). The enumerator is the
-// single source for generateStaticParams, the sitemap, and per-entry
-// metadata.
+// The enumerator feeds generateStaticParams, the sitemap and per-entry metadata.
export type WebsiteRouteFamily = {
basePath: string;
changeFrequency: SitemapChangeFrequency;
diff --git a/packages/twenty-website/src/platform/seo/serialize-json-ld.ts b/packages/twenty-website/src/platform/seo/serialize-json-ld.ts
index 55115213675..e1f87cf6962 100644
--- a/packages/twenty-website/src/platform/seo/serialize-json-ld.ts
+++ b/packages/twenty-website/src/platform/seo/serialize-json-ld.ts
@@ -1,8 +1,4 @@
-// JSON.stringify output is inlined into a <script> body, where the HTML parser
-// still scans for "</script" and "<!--" before any JSON parsing happens. Names
-// reaching this payload come from the marketplace and partners APIs, so they
-// could otherwise close the tag and inject markup. Escaping as JSON unicode
-// sequences parses back to the same string while staying inert in HTML.
+// Names come from the marketplace and partners APIs and could close the <script> tag, so escape to inert JSON unicode.
const HTML_SIGNIFICANT_CHARACTERS_PATTERN = /[<>&]/g;
const HTML_SIGNIFICANT_CHARACTER_ESCAPES: Record<string, string> = {
diff --git a/packages/twenty-website/src/platform/site-urls.ts b/packages/twenty-website/src/platform/site-urls.ts
index fc29d7fe37c..482c485f083 100644
--- a/packages/twenty-website/src/platform/site-urls.ts
+++ b/packages/twenty-website/src/platform/site-urls.ts
@@ -1,5 +1,4 @@
-// Every external destination the site links to, in one place. Sections and
-// data files never inline these.
+// Sections and data files never inline external URLs.
export const SITE_URLS: Record<
| 'appWelcome'
| 'calBooking'
diff --git a/packages/twenty-website/src/sections/compare/CompareCostTable.tsx b/packages/twenty-website/src/sections/compare/CompareCostTable.tsx
index 66e22ddd093..b6280172f61 100644
--- a/packages/twenty-website/src/sections/compare/CompareCostTable.tsx
+++ b/packages/twenty-website/src/sections/compare/CompareCostTable.tsx
@@ -21,8 +21,6 @@ const CheckMark = INFORMATIVE_MARKS.check;
const REPORT_INACCURACY_URL =
'https://github.com/twentyhq/twenty/issues/new/choose';
-// On narrow viewports the three-column grid scrolls horizontally instead of
-// squeezing the price cells.
const TableScroller = styled.div`
overflow-x: auto;
width: 100%;
diff --git a/packages/twenty-website/src/sections/compare/CompareReceipt.tsx b/packages/twenty-website/src/sections/compare/CompareReceipt.tsx
index 13eb0392013..7868ce63f71 100644
--- a/packages/twenty-website/src/sections/compare/CompareReceipt.tsx
+++ b/packages/twenty-website/src/sections/compare/CompareReceipt.tsx
@@ -53,8 +53,6 @@ const CardsGrid = styled.div`
}
`;
-// Mirrors the pricing page's PlanCard shell so both pages read as one
-// component family.
const CardShell = styled.div`
background-color: ${color('white')};
border: 1px solid transparent;
@@ -113,8 +111,6 @@ const priceSuffixClassName = css`
min-width: 0;
`;
-// Clones the billing toggle's discount badge so the savings chip is the
-// same component language as the pricing page's "-25%".
const SavingsBadge = styled.span`
align-items: center;
align-self: center;
diff --git a/packages/twenty-website/src/sections/compare/compare-data.ts b/packages/twenty-website/src/sections/compare/compare-data.ts
index 2bad2aa4de2..d1762580cc2 100644
--- a/packages/twenty-website/src/sections/compare/compare-data.ts
+++ b/packages/twenty-website/src/sections/compare/compare-data.ts
@@ -1,9 +1,8 @@
import { type MessageDescriptor } from '@lingui/core';
import { msg } from '@lingui/core/macro';
-// Competitor list prices, checked against each vendor's public pricing page
-// on 2026-07-30 (annual billing unless stated). Keep every price cell paired
-// with its source URL; re-verify before changing any number.
+// Checked against vendors' public pricing pages on 2026-07-30 (annual unless stated); keep each price paired
+// with its source URL and re-verify before changing.
export type CompareCompetitorCell = {
detail: MessageDescriptor;
diff --git a/packages/twenty-website/src/sections/pricing-plan-table/PlanTableContent.tsx b/packages/twenty-website/src/sections/pricing-plan-table/PlanTableContent.tsx
index 558d924b1b6..c136b31ea6a 100644
--- a/packages/twenty-website/src/sections/pricing-plan-table/PlanTableContent.tsx
+++ b/packages/twenty-website/src/sections/pricing-plan-table/PlanTableContent.tsx
@@ -135,8 +135,7 @@ const CtaRow = styled.div`
width: 100%;
`;
-// Enterprise inherits the Organization cell unless a row overrides it: the
-// tier is a superset, so unmarked rows read as "same as Organization".
+// Enterprise inherits the Organization cell unless a row overrides it.
function resolveCell(
row: PlanTableFeatureRowDataType,
columnId: PlanTableTierId,
diff --git a/packages/twenty-website/src/sections/pricing-plans/PlanCard.tsx b/packages/twenty-website/src/sections/pricing-plans/PlanCard.tsx
index f2e729bb9d8..5749f42a378 100644
--- a/packages/twenty-website/src/sections/pricing-plans/PlanCard.tsx
+++ b/packages/twenty-website/src/sections/pricing-plans/PlanCard.tsx
@@ -57,9 +57,7 @@ const CardHeaderInfo = styled.div`
}
`;
-// The title and price guard against long localized strings: they ellipsis
-// (or, for the price line, hold one line) on desktop where the two cards
-// share the row width. Ported from the old card.
+// Guards long localized strings where the two cards share the row on desktop.
const titleClassName = css`
overflow: hidden;
text-overflow: ellipsis;
diff --git a/packages/twenty-website/src/sections/pricing-plans/PricingBoard.tsx b/packages/twenty-website/src/sections/pricing-plans/PricingBoard.tsx
index bbf20bfafaa..0b5fecb1294 100644
--- a/packages/twenty-website/src/sections/pricing-plans/PricingBoard.tsx
+++ b/packages/twenty-website/src/sections/pricing-plans/PricingBoard.tsx
@@ -11,9 +11,7 @@ import { PLANS_DATA, type PlansBillingPeriod } from './plans-data';
import { SelfHostToggle } from './SelfHostToggle';
import { usePricingState } from '@/pricing-state';
-// The interactive island below the intro: the switcher and the cards.
-// It sits 32px under the intro (the hero's intro-to-CTA gap); the cards
-// hang 68px under the switcher (the hero's CTA-to-mockup measure).
+// Spacing echoes the hero: 32px intro-to-CTA, 68px CTA-to-mockup.
const Board = styled.div`
align-items: center;
display: flex;
@@ -45,8 +43,7 @@ const BillingToggleSlot = styled.div`
${mediaUp('md')} {
grid-column: 2;
- /* Nudged right of dead-centre so it does not read as left of the
- Selfhosting control that sits on the row's right. */
+ /* Nudged right so it does not read as left of the Selfhosting control. */
transform: translateX(${spacing(3)});
}
`;
diff --git a/packages/twenty-website/src/sections/pricing-plans/plans-data.ts b/packages/twenty-website/src/sections/pricing-plans/plans-data.ts
index 16697526322..1d5304ec8ef 100644
--- a/packages/twenty-website/src/sections/pricing-plans/plans-data.ts
+++ b/packages/twenty-website/src/sections/pricing-plans/plans-data.ts
@@ -19,8 +19,7 @@ type PlansTierCell = {
price: PlanPrice;
};
-// A CTA without href opens the contact modal (TalkToUsButton) instead of
-// navigating.
+// A CTA without href opens the contact modal instead of navigating.
type PlansTierCta = {
href?: string;
label: MessageDescriptor;
diff --git a/packages/twenty-website/src/sections/pricing-salesfarce/PricingSalesfarce.tsx b/packages/twenty-website/src/sections/pricing-salesfarce/PricingSalesfarce.tsx
index 0ec746d8cd2..4c0c4a40278 100644
--- a/packages/twenty-website/src/sections/pricing-salesfarce/PricingSalesfarce.tsx
+++ b/packages/twenty-website/src/sections/pricing-salesfarce/PricingSalesfarce.tsx
@@ -74,8 +74,6 @@ const CompareList = styled.ul`
padding: 0;
`;
-// The footer's hover-marker link affordance, so the list reads as the same
-// navigation language.
const HoverMarker = styled.span`
background-color: ${semanticColor.ink};
border-radius: 1px;