61b76b681ea672f924c9699f5d3426fbde8733b4
4848 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
61b76b681e |
fix: i18n missing hardcoded strings in settings (#21424)
## What Two user-visible strings in the Settings area were never wrapped with Lingui, so they were excluded from i18n extraction and shipped untranslated regardless of the selected language: - **"Remote"** — the type chip shown for remote objects in **Settings → Data Model** (`SettingsItemTypeTag`) - **"Done"** — the confirm button of the fields configuration group rename input (`FieldsConfigurationGroupRenameInput`) ## Changes - Wrap the `Chip` `label` with the `t` macro in `SettingsItemTypeTag.tsx` (the `placeholder` / `placeholderColorSeed` props are intentionally left as-is — they drive the avatar initial and color hash, not display text). - Wrap the `Button` `title` with the existing `t` from `useLingui()` in `FieldsConfigurationGroupRenameInput.tsx`. - Add the corresponding source entries to `en.po` so Crowdin can propagate the translations to all supported locales. Both follow i18n patterns already used throughout the codebase — these two were simply missed. ## Screenshots Both components rendered via Storybook (source `en` locale) after the change — the strings now resolve through Lingui's `t` macro without breaking rendering:  ## How to test 1. Switch the workspace language to a non-English locale. 2. Go to **Settings → Data Model** with a remote object present → the type chip reads "Remote" translated. 3. Rename a fields configuration group → the confirm button reads "Done" translated. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
f1c7aecadb |
fix(front): sanitize optimistic input when creating a record (#21076)
## Summary Closes #15800. Clicking **+ Add New** from a relation cell to create a **Task** or **Note** (e.g. from a custom object's Tasks/Notes section in the list view) throws: ``` Uncaught (in promise) Error: Should never occur, encountered unknown fields name in objectMetadataItem task ``` ### Root cause `useCreateOneRecord` computes a **sanitized** input (with `sanitizeRecordInput`, which strips fields that don't belong to the object) and sends it to the GraphQL mutation. But it still feeds the **raw** input to the optimistic cache computation: ```ts const sanitizedInput = { ...sanitizeRecordInput({ objectMetadataItem, recordInput }), id: idForCreation }; const optimisticRecordInput = computeOptimisticRecordFromInput({ ... recordInput: { ...computeOptimisticCreateRecordBaseRecordInput(objectMetadataItem), ...recordInput, // ← raw input, may contain fields unknown to the object id: idForCreation, }, ... }); // mutation uses the sanitized input: mutate({ variables: { input: sanitizedInput } }); ``` `computeOptimisticRecordFromInput` asserts that every input key maps to a field on the object and `throw`s otherwise. So when the create input carries a field the target object doesn't have (the relation-create path passes a `name`, but Task/Note use `title`), the optimistic step throws before the mutation ever runs. `useCreateManyRecords` does **not** have this problem — it already feeds the sanitized input to `computeOptimisticRecordFromInput`. ### Fix Feed the sanitized input to the optimistic computation in `useCreateOneRecord`, exactly as `useCreateManyRecords` does: ```ts recordInput: { ...computeOptimisticCreateRecordBaseRecordInput(objectMetadataItem), ...sanitizedInput, }, ``` This is safe and behavior-preserving for valid creates: `computeOptimisticRecordFromInput` only ever reads *known* fields (it iterates the object's field metadata); unknown input keys never contribute to the optimistic record — they only trip the invariant. Relations are resolved through their join columns, which sanitization keeps. ## Test plan - [x] `npx oxlint --type-aware` — passes on the changed files - [x] `npx oxfmt --check` — passes - [x] `tsc --noEmit` — no type errors in the changed files - [x] `npx jest computeOptimisticRecordFromInput` — passes, including a new case asserting that input which has been through `sanitizeRecordInput` no longer trips the "Should never occur, encountered unknown fields" invariant (the existing test already covers the raw input throwing) - [ ] Manual: from a custom object's Notes/Tasks relation, use **+ Add New** to create a Note/Task — no error, the record is created ### Note on test scope The crash only reproduces through the full relation-create flow with live metadata; at the hook level in jsdom the create resolves regardless, so a hook-level test would not guard the regression. The added test instead locks the underlying mechanism the fix relies on — that sanitized input is safe for `computeOptimisticRecordFromInput` — alongside the existing test that proves raw unknown fields throw. --------- Co-authored-by: Charles Bochet <charles@twenty.com> |
||
|
|
adba66caea |
fix(twenty-front): new layout fast-follows — settings drawer, loading & command menu (#21389)
Second batch of new-layout fast-follows (master: twentyhq/core-team-issues#2478). All changes verified live against a running workspace. ## Settings drawer & header - **twentyhq/core-team-issues#2489** — sidebar icons render as plain 16px icons, no background tiles. - **twentyhq/core-team-issues#2488** — Advanced toggle spans the full drawer width; yellow dot removed. - **twentyhq/core-team-issues#2497** — page title stays centered in the settings header (breadcrumb stays left). - **twentyhq/core-team-issues#2490** — Exit Settings control aligned to the workspace switcher (24px, matching padding/gap). - **twentyhq/core-team-issues#2499** — 2px vertical gap restored between collapsible drawer section items. - **twentyhq/core-team-issues#2491** — settings drawer rhythm now matches the main app (28px items, 2px gaps, 28px section headers). - **twentyhq/core-team-issues#2492** — Home/Chat tab switch no longer flickers: both tab subtrees stay mounted (a shared `NavigationDrawerTabbedContent` toggles visibility instead of remounting + flashing the chat skeleton). ## Loading states - **twentyhq/core-team-issues#2486** — metadata loading shows an empty body (no dense skeleton rows). - **twentyhq/core-team-issues#2487** — settings table keeps its layout while loading, with the shimmer localized to the first row's first cell. ## Command menu & navigation - **twentyhq/core-team-issues#2501** — navigation section header height matches the nav item rhythm (28px). - **twentyhq/core-team-issues#2502 (part 1)** — the page side-panel toggle stays as the dots glyph while the command menu is open, instead of morphing into a second close control. ## New-field flow - **twentyhq/core-team-issues#2494** — the new-field stepper moved from a breadcrumb dropdown into a centered secondary wizard bar (back chevron + Save on the configure step); breadcrumb stays clean and the object label is the centered title. ## Descoped (substantive bugs already fixed) - **twentyhq/core-team-issues#2500** — command-menu highlight right gutter: the menu-item base measures full-width, so it's likely a scrollbar gutter on the list, not the shared component. Left for a focused follow-up. - **twentyhq/core-team-issues#2502 part 2** — moving the command-menu close from left to right is cosmetic (the duplicate-control bug is fixed by part 1) and would touch the shared `SidePanelTopBar` used by search/AI panels. ## Verification typecheck (tsgo) + oxlint + oxfmt green for all changed files; each change DOM-measured / screenshotted in the running app. |
||
|
|
ca63904ac5 |
fix(security): bump @scalar/api-reference-react to clear unhead XSS (#21382)
Resolves [Dependabot Alert 630](https://github.com/twentyhq/twenty/security/dependabot/630). unhead@1.11.20 was pulled in transitively via @scalar/api-reference-react@0.4.42 (@unhead/vue@^1.11.11). The useHeadSafe XSS bypass (GHSA, alert https://github.com/twentyhq/twenty/issues/630) is only patched on the unhead 2.x line; the 1.x branch was never fixed and 1.11.20 is the latest 1.x release, so the existing semver range could not reach a patched version. Rather than a resolutions override, bump the direct dependency to a Scalar release that depends on @unhead/vue@^2.x, which resolves unhead to 2.1.15. - Upgrade @scalar/api-reference-react ^0.4.36 -> ^0.9.42 (0.9.43+ blocked by the 3-day npmMinimalAgeGate; the caret adopts them once aged). - Migrate RestPlayground configuration to the new Scalar API: - spec.content -> top-level content - authentication.http.bearer -> authentication.securitySchemes.bearerAuth (with preferredSecurityScheme), matching the server's OpenAPI scheme name. - Drop the ?inline query on the style.css import. It was added in https://github.com/twentyhq/twenty/pull/12099 to stop the old Scalar's global CSS reset from leaking; the new CSS scopes every reset to :where(.scalar-app), so importing it normally restores styling without re-introducing that leak. Proof: <img width="215" height="48" alt="image" src="https://github.com/user-attachments/assets/3a738fae-63bd-4e88-82c3-5dbe72d993ec" /> Co-authored-by: Félix Malfait <felix.malfait@gmail.com> |
||
|
|
ce2d77be2a |
feat(server): in-app server-level admin management (#19785) (#21321)
## Closes #19785 In-app management of **server-level admin rights** (`canAccessFullAdminPanel`, `canImpersonate`) so self-hosters no longer need raw SQL + a Redis flush + restart to grant access. > **Draft** — feature complete; `/code-review` + `/security-review` run and addressed. ### Background `AdminPanelGuard` / `ServerLevelImpersonateGuard` read `request.user.{canAccessFullAdminPanel,canImpersonate}`, hydrated each request from `CoreEntityCacheService.get('user', …)` (local 30-min + Redis no-TTL). The cache was only invalidated on soft-delete, so a raw `UPDATE core."user"` never took effect. The **first** signup auto-gets both flags; every subsequent admin previously needed raw SQL. ### UX - **Admin Panel → General → Administrators**: a read-only overview of every user with server-level access; each row links to that user's admin page. - **Find anyone** via the user search (Recent Users) — available to full admins and impersonators — then open their **admin user page**. - On the user page, an **"Administrator access"** card (gated on `canAccessFullAdminPanel`) has two toggles — *Full admin panel access* and *Impersonation* — that work for **any** user (a user with no access shows both off). Mirrors how **Impersonate** already works (find user → user page → act). Each change opens a confirm dialog with a **2FA code** field; the last full admin's toggle is disabled. ### Backend / security - **Cache fix** — invalidate the user entity cache on committed user updates (not just soft-delete) so privilege changes propagate (~100 ms, cluster-wide) with no restart. - `getServerAdmins` query + `updateServerAdminAccess` mutation (any `targetUserId`), gated on `canAccessFullAdminPanel`. - `NoImpersonationGuard` on both — an impersonated full-admin session can't be used to escalate an impersonator. - Fresh **2FA TOTP step-up** (enrolled+verified method **and** a fresh code; genuine 2FA errors surface; dev-skip on trusted `NODE_ENV`). - **Last-admin lockout** in a transaction with a pessimistic row lock (no TOCTOU). - **Email-to-all-admins + affected user** (rendered once per locale), structured log, audit event-log emit. - **Authorization**: the read-only `userLookupAdminPanel` + `adminPanelRecentUsers` lookups now accept `canAccessFullAdminPanel OR canImpersonate` (new `AdminPanelOrImpersonateGuard`), so a full admin without impersonate can still find users to manage. Workspace/impersonation queries stay impersonate-gated. ### Reviews - `/code-review` (max effort): 3 security findings (impersonation-escalation sink, lockout TOCTOU, step-up accepting PENDING 2FA) — **all fixed**. `/simplify`: applied. `/security-review`: **no high/medium vulnerabilities**. ### Follow-ups (not in this PR) - Unit tests for `AdminPanelServerAdminService` + a frontend test. - Point the self-host troubleshooting docs at the new UI. - OTP retry UX: `ConfirmationModal` closes on confirm, so a wrong code needs a reopen (kept to reuse the existing modal; no new pattern). ### Notes for reviewers - `generated-admin/graphql.ts` entries were hand-added to match codegen output (admin codegen needs a running server); re-run `nx graphql:generate twenty-front --configuration=admin` to confirm parity. - First-admin bootstrap (first signup) is unchanged. --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> |
||
|
|
6c65ae8257 |
perf(twenty-front): stop Sentry Replay from re-serializing record-table mutations on navigation (#21381)
## Problem
Navigating between record-index pages (e.g. People ↔ Companies) blocks
the main thread for seconds, on every navigation, for ~every user.
Profiling pointed at **Sentry Session Replay(rrweb)**, not app code.
## Root cause
Swapping one record table for another produces a large DOM mutation
batch. rrweb serializes that batch **synchronously on the main thread**
(`_isParentRemoved` / mutation processing).
The built-in `mutationLimit` safety valve doesn't help: it's a *count*
threshold (default 10000), but our cost is *per-mutation serialization*
on a wide/deep table DOM — the batch is expensive, not numerous, so it
slips under the limit.
## Fix
```ts
replayIntegration({
_experiments: {
ignoreMutations: ['[id^="row-virtual-index-"]'],
},
}),
```
- ignoreMutations tells rrweb to drop mutation batches originating from
the virtualized row containers (StyledVirtualizedRowContainer, ids
row-virtual-index-N) — the source of the
table-swap churn. The table still appears in replays (initial snapshot;
text is already masked by default), its live row updates just aren't
re-serialized.
## Test
Measured locally
```
┌────────────────────────────────────────────────────────────┬───────────┬───────────────┐
│ │ Baseline │ With fix │
├────────────────────────────────────────────────────────────┼───────────┼───────────────┤
│ Replay/rrweb total │ 4,112 ms │ 188 ms (−95%) │
├────────────────────────────────────────────────────────────┼───────────┼───────────────┤
│ _isParentRemoved │ 2,195 ms │ 6 ms │
├────────────────────────────────────────────────────────────┼───────────┼───────────────┤
```
## Tradeoff
ignoreMutations tells rrweb to skip mutation batches coming from the
virtualized record-table rows, so session replays won't reflect live
changes inside the table — rows scrolling, cells updating, inline edits
will appear "frozen" at the last full snapshot. The table still shows in
the replay (initial render), and **its text is masked by default anyway,
so in practice we lose little**: the surrounding UI, navigation, clicks,
and interactions are all still recorded. The cost we're removing
(multi-second main-thread freeze on every navigation, for ~all users)
**far outweighs not seeing table row churn in replays** imho.
(@FelixMalfait @charlesBochet)
Two caveats worth noting: _experiments.ignoreMutations is an
experimental Sentry API, and it's batch-coarse, if a mutation batch
contains any matching element, the whole batch is dropped, so an
unrelated change occasionally batched with table mutations could be
missed. During navigation these batches are almost entirely table
mutations, so collateral is minimal.
If it ever proves insufficient, the reliable fallback is
`data-sentry-block` on the record-table body (which turns the table into
a placeholder box in replays).
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
|
||
|
|
5f7638cdaf |
fix(front): surface widget render errors via ErrorBoundary onError (#21009)
## Summary
The page-layout widget `ErrorBoundary` in `WidgetCardShell` renders a
generic
"Invalid Configuration" fallback whenever a widget renderer throws.
Because
there is no `onError` handler, the underlying error is swallowed —
unrelated
widget types (fields, notes, front-component, etc.) all surface the same
chip
with no telemetry, which makes render failures hard to triage.
This adds an `onError` handler that forwards the caught error to
`console.error`
and to Sentry (when available) with the widget's `id`, `type`, and
`configurationType` as extra context. It reuses the same dynamic-import
Sentry
pattern already used by `AppErrorBoundary` and
`CommandMenuItemErrorBoundary`,
so it degrades gracefully to a console log when Sentry is not
configured. The
fallback UI is unchanged.
## Test plan
- [ ] `npx nx typecheck twenty-front` passes
- [ ] `npx nx lint:diff-with-main twenty-front` passes
- [ ] When a widget renderer throws, the "Invalid Configuration" chip
still
renders and the error now appears in the browser console / Sentry
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Charles Bochet <charles@twenty.com>
|
||
|
|
7894ae39f0 |
fix(front): reject backslash paths in isValidReturnToPath (open-redirect hardening) (#21287)
## Summary
`isValidReturnToPath` validates the post-login `returnTo` path and
already rejects protocol-relative `//` paths — but not the backslash
variant. Browsers normalize `\` to `/`, so `/\evil.com` resolves like
`//evil.com` (a protocol-relative, external URL) while still passing the
existing `//` check:
```ts
isValidReturnToPath("/\\evil.com"); // returns true today; should be false
```
This hardens the open-redirect guard by rejecting any path containing a
backslash, so a `returnTo` can only ever be a same-site absolute path.
## Changes
- `isValidReturnToPath`: reject paths containing `\`.
- Added tests for backslash-tricked paths.
Framed as defense-in-depth — the validator should reject this class
regardless of how each consumer performs the redirect.
---------
Co-authored-by: Charles Bochet <charles@twenty.com>
|
||
|
|
9c66975520 |
isCustom deprecation for Objects and Fields (#21228)
## Context
`isCustom` was a legacy denormalized boolean on `ObjectMetadataEntity`
and `FieldMetadataEntity`.
Now that every metadata row carries `applicationId` (via
`SyncableEntity`), "is this custom" is fully derivable, and the stored
boolean was a redundant second source of truth that could drift.
The real meaning of `isCustom` is **"the owning application is not the
twenty-standard application"** — i.e. `!belongsToTwentyStandardApp`.
Note this is *not* "belongs to the workspace custom app" as I initially
thought: third-party-application
objects/fields are custom too.
The standard application has a globally stable `universalIdentifier`, so
the value derives with no per-workspace lookup.
## Changed
## `isCustom` checks — before → after
`isCustom` is no longer a stored column. The table below lists every
site that branched on it and how it resolves now. The unifying rule:
`isCustom ≡
!isTwentyStandardApplicationUniversalIdentifier(applicationUniversalIdentifier)`.
### Server — behavioural checks
| Location | Purpose | Before | Now |
|---|---|---|---|
| `utils/compute-object-target-table.util.ts` | Physical table name `_`
prefix | `computeTableName(nameSingular, objectMetadata.isCustom)` |
derives from `applicationUniversalIdentifier` (single source for all
table-name callers) |
| `twenty-orm/factories/entity-schema.factory.ts` +
`…/entity-schema-metadata.type.ts` | ORM table name (hot path) |
`object.isCustom` | `object.applicationId !== standardApplicationId`
(computed in `buildEntitySchemaMetadataMaps`) |
|
`twenty-orm/repository/workspace-{delete,soft-delete,update}-query-builder.ts`
| Table name for mutations | `computeTableName(nameSingular,
objectMetadata.isCustom)` | `computeObjectTargetTable(objectMetadata)` |
| `index-metadata/utils/generate-deterministic-index-name-v2.ts` | Index
name hash (must stay bit-identical) | `flatObjectMetadata.isCustom` |
derives from `applicationUniversalIdentifier` |
| `object-metadata/object-record-count.service.ts` | Table name for
record count | `computeTableName(nameSingular, isCustom)` |
`computeObjectTargetTable(flatObjectMetadata)` |
|
`workspace-manager/dev-seeder/data/services/dev-seeder-data.service.ts`
| Match seed config by table name | `computeTableName(item.nameSingular,
item.isCustom)` | `computeObjectTargetTable(item)` |
| `commands/workspace-export/workspace-export.service.ts` +
`…/utils/generate-workspace-schema-ddl.util.ts` | Export table name (raw
entity) | `objectMetadata.isCustom` |
`!isTwentyStandard…(objectMetadata.application?.universalIdentifier)` |
|
`flat-field-metadata/services/flat-field-metadata-type-validator.service.ts`
| Block users creating reserved field types |
`args.flatEntityToValidate.isCustom` |
`!args.flatEntityToValidate.isSystem` |
| `api/common/.../common-create-many-query-runner.service.ts` | Don't
let client overwrite system `createdBy` |
`createdByFieldMetadata.isCustom === false` |
`createdByFieldMetadata.isSystem === true` |
|
`field-metadata/utils/resolve-field-metadata-standard-override.util.ts`
| Skip i18n/overrides for custom fields | `if (fieldMetadata.isCustom)
return raw` | **removed** — falls through on
`isDefined(standardOverrides)` |
|
`object-metadata/utils/resolve-object-metadata-standard-override.util.ts`
| Skip i18n/overrides for custom objects | `if (objectMetadata.isCustom)
return raw` | **removed** — same fall-through |
|
`command-menu-item/utils/build-navigation-interpolation-context.util.ts`
| Override context for nav labels | passed `isCustom` into resolver |
dropped (resolver no longer needs it) |
| `api/common/.../data-arg-processor.service.ts` | `isCustom` for
record-position table name | `flatObjectMetadata.isCustom` | derives
from `applicationUniversalIdentifier` |
| `metadata-modules/minimal-metadata/minimal-metadata.service.ts` |
Minimal DTO + override context | `flatObjectMetadata.isCustom` | derives
from `applicationUniversalIdentifier` |
|
`commands/upgrade-version-command/1-23/…backfill-record-page-layouts.command.ts`
| Filter to custom objects | `objectMetadata.isCustom` |
`!isTwentyStandard…(applicationUniversalIdentifier)` |
### Server — DTO / API population
| Location | Before | Now |
|---|---|---|
|
`flat-object-metadata/utils/from-flat-object-metadata-to-object-metadata-dto.util.ts`
| passthrough `isCustom` | derives from `applicationUniversalIdentifier`
|
|
`flat-field-metadata/utils/from-flat-field-metadata-to-field-metadata-dto.util.ts`
| passthrough `isCustom` | derives from `applicationUniversalIdentifier`
|
|
`object-metadata/utils/from-object-metadata-entity-to-object-metadata-dto.util.ts`
(REST) | `entity.isCustom` | `entity.applicationId !==
standardApplicationId` |
|
`field-metadata/utils/from-field-metadata-entity-to-field-metadata-dto.util.ts`
(REST) | `entity.isCustom` | `entity.applicationId !==
standardApplicationId` |
| `dataloaders/dataloader.service.ts` | passed
`flatFieldMetadata.isCustom` into override resolver | dropped (resolver
no longer needs it) |
> REST controllers (`object-metadata.controller.ts`,
`field-metadata.controller.ts`) resolve `standardApplicationId` once per
request from the cached `flatApplicationMaps`.
### Frontend
| Location | Purpose | Before | Now |
|---|---|---|---|
| `settings/.../SettingsObjectFieldDisabledActionDropdown.tsx` | Whether
an inactive field is deletable | `isDeletable = isCustomField` |
`isDeletable = isCustomField && !isSystemField` |
### Unchanged (out of scope)
`isCustom` on `IndexMetadata` / `View` / `Skill` / `Agent` and their
guards still read the persisted column.
Breaking change is on the isCustom filter on field and object APIs, this
is never used in the FE and unlikely used by external consumers
|
||
|
|
02aa086866 |
fix(twenty-front): new layout fast-follows (#21360)
Fast-follows for the new layout / flat redesign (master: twentyhq/core-team-issues#2478). ## Changes - **Main navbar 48px** (twentyhq/core-team-issues#2479) — `SIDE_PANEL_TOP_BAR_HEIGHT` 40 → 48, so `PageCardHeader` matches the Figma target. The side panel top bar shares this constant and stays aligned. - **Content panel 12px radius** (twentyhq/core-team-issues#2480) — `PageCardLayout` card gets a full border + 12px radius and an 8px inset (`spacing[2]`) so it floats on the shell instead of square full-bleed. - **Square three-dots button** (twentyhq/core-team-issues#2481) — added a `square` option to `AnimatedButton`; the page-header side-panel toggle now renders a 24×24 square icon button instead of a 32×24 pill. - **Table checkbox sizing** (twentyhq/core-team-issues#2482) — restored `box-sizing: content-box` on the checkbox box. Its border is declared outside the label size, so the global `border-box` reset (#21349) was shrinking it (14px → 12px). Same fix pattern as #21349. - **Tertiary navbar background** (twentyhq/core-team-issues#2483) — left navbar / app shell use `background/tertiary` instead of the noisy surface (`DefaultLayout`, `UserOrMetadataLoader`). - **Skeleton loading** (twentyhq/core-team-issues#2484) — metadata + content loading now match the new layout: tertiary shell, 12px rounded content panel, 48px navbar, sparse bars, empty body (removed the dense full-width rows). Left-panel skeleton bars use `quaternary` so they stay visible on the tertiary shell. ## Verification - typecheck (tsgo) + oxlint + oxfmt pass for all changed files. - Verified live against a running workspace: measured navbar = 48px, three-dots = 24×24, checkbox box-sizing = content-box (14px), card radius = 12px, shell background = tertiary (no noisy image). Content-loading skeleton matches the target. |
||
|
|
c27c8c88b0 |
Fix various graphs bugs (#21311)
Some bugs fixed in this PR
1. From UI any field could be chosen to group the query by it, while for
instance, RAW_JSON type (eg workflowRun.state) is not supported by
PostgreSQL to group a query by. Fix: removed it from the "group by"
fields options in FE + in BE -->
2. The BE check existed (isFlatFieldMetadataSupportedInGroupBy) but the
signature was malformed: it expected`{ fieldMetadataType,
fieldMetadataName, fieldMetadataIsSystem }` while every caller passes a
flat field metadata object with type/name/isSystem. So the check is
mis-wired — at runtime the destructured props are undefined, making it
always return true (validation bypassed). Fixed this.
3. Group by does not work with Morph relations if their direction is
ONE_TO_MANY. Added that constraint.
4. Group by with morph relations were broken even for MANY_TO_ONE,
because a morph is stored as one field per target
(polymorphicOwnerRocket, polymorphicOwnerSurveyResult…), each with its
own join column, but the frontend collapsed them into a single
polymorphicOwner field — so the backend tried to resolve a non-existent
polymorphicOwnerId. Fix: Frontend: added a target picker so you choose
the specific morph target (then its sub-field), storing the real
per-target field id. Backend: fixed validate-relation-subfield to use
the per-target field's own relationTargetObjectMetadataId instead of the
multi-target resolver that returned null.
5. (improvement) When an error occured in the query, the graph showed
"No data". Updated it to "error". (screenshot 1)
6. When a field used as a filter on a graph is deleted, it is not
deleted as a graph filter (which is ok because it would involve parsing
all the graph's configuration json to find whether a field is
referenced; there is no foreign key), which prevented from further
modifying the graph's filters. Fixed this + add an indicator that the
filter is can/should be removed (see screenshot 2)
7. "Ambiguous column name" PG error occurs when ordering by "creation
date" of a related field, because both objects have createdAt field.
Fixed it by adding table alias as prefix.
8. (improvement) While working on #5 I did not understand why we could
directly do `"objectMetadataNameSingular"."columnName" `while I expected
that for custom objects it would have to be
`_objectMetadataNameSingular`. that's simply because we use an alias
from the beginning. To add clarity, within groupBy code I replaced
`objectMetadataNameSingular` with `objectAlias` everywhere it is indeed
inherited from us using objectAlias.
<img width="685" height="391" alt="Screenshot 2026-06-08 at 12 01 45"
src="https://github.com/user-attachments/assets/f2b15ca5-da39-4114-8188-69f58f3c4cbf"
/>
<img width="598" height="341" alt="Screenshot 2026-06-08 at 11 53 55"
src="https://github.com/user-attachments/assets/66372811-4a37-40d9-b43a-4af51f89b6e6"
/>
|
||
|
|
137fe45cf6 |
Deprecate dummy enterprise key 2/2 (#21328)
Following [1/2](https://github.com/twentyhq/twenty/pull/20890) Now that all usages of hasValidEnterpriseKey has been removed in prod and deployed, we can safely remove it altogether. --------- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> |
||
|
|
ba4ac6b70e |
fix(twenty-front): restore top-bar-title testid to unbreak merge queue (#21367)
## Problem The merge queue is broken. Every queued PR (#21357, #21361, #21364, #21366, …) fails on the same E2E assertion in `workflow-creation.spec.ts:36`: ``` Locator: getByTestId('top-bar-title').getByPlaceholder('Name') Error: element(s) not found ``` All other E2E tests pass, which pointed to a regression already on `main` rather than any individual PR. ## Root cause #21308 ("generalize the page primary/secondary bars (flat redesign)") switched `RecordShowPageHeader` from `PageHeader` to the new `PageCardHeader`. - The old `PageHeader` wrapped its title in `<StyledTitleContainer data-testid="top-bar-title">`. - The new `PageCardHeader` renders the breadcrumb slot **without** that `data-testid`. The editable record title cell (the `Name` input the test fills in) still renders fine inside `ObjectRecordShowPageBreadcrumb` — it just lost the `top-bar-title` wrapper that the E2E suite locates it by. The testid is also used by the `blank-workflow` fixture. ## Fix Restore `data-testid="top-bar-title"` on the record-show breadcrumb container, which wraps exactly what `PageHeader` previously did (the editable `Name` input and, after save, the record name text). Minimal and behavior-preserving; record-index and standalone pages use different header slots and were unaffected (their E2E tests passed throughout). |
||
|
|
7606dd75a8 |
Fix: pinned command-menu actions run with empty selection (#21366)
## Cause PR #21308 ("generalize the page primary/secondary bars") swapped the old `PageHeader` for the new `PageCardHeader` on the record-index, record-show, and standalone pages. The old header set `data-click-outside-id="page-action-container"` on its action container — an id that the record table/board/calendar click-outside listeners exclude so header clicks don't clear the current selection. The new `PageCardHeader` dropped that attribute. ## Implications With the attribute gone, clicking a pinned command-menu item registered as a click *outside* the table/board, which reset the selected records before the action read them. As a result, pinned actions and workflows triggered from the top bar ran with an empty selection. ## Fix Re-add `data-click-outside-id={PAGE_ACTION_CONTAINER_CLICK_OUTSIDE_ID}` to `PageCardHeader`'s action container. Since all three migrated headers route their buttons through this shared component, the single change covers every affected page. |
||
|
|
92502efacc |
Restore content-box sizing for components broken by the global border-box reset (#21361)
Since [#21315](https://github.com/twentyhq/twenty/pull/21315), the new twenty-ui's global border-box reset applies app-wide, shrinking legacy content-box components: most visibly, off-center checkboxes. [#21349](https://github.com/twentyhq/twenty/pull/21349) missed a few; this adds box-sizing: content-box to Checkbox, Radio, ColorSample, MenuItemHotKeys, Tag, ImageInput, and OnboardingModalCircularIcon. |
||
|
|
55cbd3bfbf |
perf(ai): lazy-load agent chat runtime so it doesn't fetch/diff threads until opened (#21331)
## Problem On workspaces with a sizeable AI chat history, the whole app was freezing during navigation, including Settings (one navigation click measured ~6.5s). ## Root cause `AgentChatProvider` is mounted app-wide in `AppRouterProviders`, so its effects run on every page. On every render it would: 1. auto-select the most recently active thread (`AgentChatThreadInitializationEffect`), 2. fetch that thread's **full message history** (`AgentChatMessagesFetchEffect`), 3. run `AgentChatStreamingPartsDiffSyncEffect` → `updateStreamingPartsWithDiff`, which loops over every message doing `isDeeplyEqual(existing, incoming)` + `structuredClone`. A large thread would produce multi-second freeze on every interaction, app-wide. (Confirmed via a Chrome CPU profile) ## Fix Don't run the agent-chat **message runtime** until the chat is actually opened. ## Note There is still room for improvement, opening AI chats would still be very slow. |
||
|
|
8a3e6e645a |
fix(ui): restore content-box sizing for components broken by the global border-box reset (#21349)
## Problem Since the `twenty-ui` → `twenty-ui-deprecated` / `twenty-new-ui` → `twenty-ui` rename (#21315), many deprecated components render with **compacted height** — e.g. dropdown menu items collapse from 32px to 16px, and chips from ~24px to 16px. ## Root cause The new `twenty-ui` (formerly `twenty-new-ui`) ships a global reset in `packages/twenty-ui/src/styles/base/reset.scss`: ```css *, *::before, *::after { box-sizing: border-box; } ``` This is bundled into `twenty-ui/style.css`, which the app imports in `index.tsx`. #21315 did not change the `import 'twenty-ui/style.css'` line, but it changed what `twenty-ui` resolves to (old → new), so this **global `border-box` reset now applies app-wide**. Several deprecated components were authored against the **content box**, e.g. `StyledMenuItemBase`: ```css height: calc(32px - 2 * var(--vertical-padding)); padding: var(--vertical-padding) var(--horizontal-padding); ``` With `content-box` the padding sits *outside* the declared height → 32px total. Under the new `border-box` reset the padding is folded *inside* → 16px total. (`Chip` uses `height: spacing[4]` + outside padding — same failure mode.) Verified in the running app: the collapsed menu item computes `box-sizing: border-box`, matched by the rule `*, ::before, ::after { box-sizing: border-box }`; `height` resolves to `calc(32px - 2 * 8px) = 16px`. ## Fix Add `box-sizing: content-box` to the affected deprecated components. A class selector outranks the universal `*` reset, so this restores their intended sizing **without touching the global reset** (which the new `twenty-ui` components rely on). Affected: `StyledMenuItemBase` (and its hoverable variant), `MenuItemSelect`, `MenuItemSuggestion`, `Chip`. |
||
|
|
bfefcd3755 |
feat(twenty-front): generalize the page primary/secondary bars (flat redesign) (#21308)
Replaces #21279 and #21282 with one clean PR from `main`. Generalizes the settings primary-bar / secondary-bar card chrome to the record index, record show and standalone pages via a shared `PageCardLayout` + `PageCardHeader` (the side panel sits as a sibling of the content card), and applies the new flat design direction: square corners on the card, side panel and loading skeletons. Iterating toward the new design (Figma node 102282-221623); the confirmed direction and the explicit "remove rounded corners" change are in, remaining designer specifics to follow. |
||
|
|
cd13457a4a |
fix(twenty-front): match loading skeleton menu width to the nav drawer (#21278)
## What On the very first load (full browser refresh), the navigation skeleton didn't match the real `NavigationDrawer` width: it rendered an 8px-wider panel (an 8px wrapper padding on top of the 220px animated container) and right-aligned 204/196px item rows, so the menu visibly shifted and resized once the app finished loading. This makes every navigation skeleton mirror the real drawer geometry: a single `NAVIGATION_DRAWER_CONSTRAINTS.default`-wide (220px), border-box panel with the drawer's own padding, left-aligned, and skeleton bars that fill the content width like the real nav items (`width: 100%`). The same fill-width fix is applied to the in-drawer section skeletons so every navigation skeleton matches the real menu width. ## Verification - `tsgo` typecheck, `oxlint`, and `oxfmt` all clean on the changed files. --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> |
||
|
|
c596a5e342 |
Rename twenty-ui to twenty-ui-deprecated and twenty-new-ui to twenty-ui to prepare package release (#21315)
## Description Promotes the next-gen UI library (formerly `twenty-new-ui`) to the name **`twenty-ui`** (v0.1.0, publishable) and renames the old package to **`twenty-ui-deprecated`**. Rewrites ~1,730 `twenty-ui` imports → `twenty-ui-deprecated`, updates all configs/CI/Docker/deps, and migrates twenty-front's `Toggle` to the new package (first consumer) as a drop-in. ## Next steps - Wire the `ui/v*` publish dispatch (`cd-deploy-tag.yaml` + `.yarnrc.yml`), then tag `ui/v0.1.0` to publish. - Continue migrating components from `twenty-ui-deprecated` → `twenty-ui`. |
||
|
|
13e8e26d1c |
security: bump uuid 9 → 11 (server, shared, front) (#21326)
Clears the `uuid` "missing buffer bounds check in v3/v5/v6" advisory — patched in **11.1.1**. Bumps `twenty-server`, `twenty-shared`, `twenty-front` from 9 → `^11.1.1`. ### Why 11 and not 13 uuid **11.1.x still ships a CommonJS build**, so jest loads it with **no config changes**. uuid went **ESM-only at v12+**, which would otherwise force `transformIgnorePatterns` workarounds across the jest projects (and broke server/integration/storybook CI on the earlier 13 attempt). 11.1.1 is the actual patched version, so this is the minimal fix. ### Changes - `uuid` → `^11.1.1` in the three workspaces (lockfile regenerated under hardened mode) - one test (`useCreateManyRecords.test.tsx`): pin the mocked `v4` to its string-returning overload — uuid's types declare a `Uint8Array` overload that `jest.mocked` resolves to (present in v11 too, unrelated to ESM). All usages are named imports, so no source migration. typecheck passes (server/shared/front); affected specs pass. **No jest config changes.** |
||
|
|
2151a414f5 | Remove IS_WORKFLOW_RUN_STEP_LOGS_ENABLED feature flag (#21323) | ||
|
|
e04eef0461 |
fix: wrong record count on deleted and normal records (#21292)
## Summary - Resolves #11977 - When looking into the deleted records from People tab (or any object list), the record detail header showing 0/(total records) instead of the correct position among deleted records only, e.g. 1/3 or 3/7. So, this PR makes the count match what users see in the deleted-records list. - Also normal records showing `0/N` in the header when opened from a list view (e.g. `0/48` -> `2/48`). ## Approach I tried to keep the change small and avoid extra server requests: - when a user came from a deleted-records view, we tell our existing queries to include soft-deleted records. - for the position number, we use the record list the user already had open (from the index view they came from) instead of apollo cache, which didn’t include records, especially deleted ones, but also normal records. - normal list behavior is not changed on the server side. ## Test plan - Open people/company, delete a record - Use the side menu -> “see deleted records” - open a deleted record’s details - confirm the header showing the correct position and total (e.g. 1/2, not 0/100) - for normal list: open People (normal list, not deleted) -> click a record -> open full page -> confirm header shows correct position and total (e.g. `2/48`, not `0/48`) ## Screenshots ### Before: <img width="1513" height="309" alt="Screenshot 2026-06-07 135204" src="https://github.com/user-attachments/assets/4754f1a7-8315-4a7a-815f-dda977b09331" /> <img width="1514" height="261" alt="Screenshot 2026-06-07 141735" src="https://github.com/user-attachments/assets/dd5b1834-5d84-49fe-8d20-633428d73502" /> ### After: <img width="1511" height="224" alt="Screenshot 2026-06-07 134946" src="https://github.com/user-attachments/assets/9450af7d-84b9-40bb-95e9-5a8665cc0923" /> <img width="1514" height="288" alt="Screenshot 2026-06-07 135045" src="https://github.com/user-attachments/assets/029ae632-ad7e-451e-8170-a4e4e71ac6f9" /> <img width="1512" height="229" alt="Screenshot 2026-06-07 141642" src="https://github.com/user-attachments/assets/576f4cad-a9e9-4380-aa67-e5f0e976a193" /> --------- Signed-off-by: Parship Chowdhury <parshipchowdhury@gmail.com> Co-authored-by: Charles Bochet <charles@twenty.com> |
||
|
|
dfb3da1f8d |
feat(emailing-domain): add LOG driver for local development (#21286)
## What Adds a `LOG` driver to the emailing-domain feature, selected via a new `EMAILING_DOMAIN_DRIVER` config variable (defaults to `AWS_SES`, so production behavior is unchanged). The LOG driver: - resolves domains to `VERIFIED` instantly (no DNS / SES setup) - logs each `sendEmail` and returns a synthetic `messageId` instead of calling SES It also dev-seeds a pre-verified domain per workspace (`<workspaceId>.dev.twenty.local`) so the feature works out of the box. ## Why The emailing-domain feature currently ships only the AWS SES driver, so the verify → send flow can't be exercised locally (or in CI) without real AWS credentials. This unblocks local development and review of anything built on emailing domains. ## Usage ``` EMAILING_DOMAIN_DRIVER=LOG ``` The seeded `*.dev.twenty.local` domain is already verified; sends are logged (`[log-driver] sendEmail ...`). --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> |
||
|
|
4f87ea5a9a |
fix: firefox blank import validation screen and center toggles (#21266)
## Summary Resolves #20182 and also centered toggles (e.g. under ICP) vertically in validation cells. ## Screencasts In Firefox: Before: https://github.com/user-attachments/assets/cd837733-6f4c-4bd4-9b08-723f22a5c9ba After: https://github.com/user-attachments/assets/d180a2f3-ee40-46f9-8db2-ecd341878fc6 ## Screenshots Before: <img width="156" height="160" alt="Screenshot 2026-06-05 215835" src="https://github.com/user-attachments/assets/a228fea8-7f3d-43f1-88bd-d6e198f8cac0" /> After: <img width="191" height="148" alt="Screenshot 2026-06-05 215815" src="https://github.com/user-attachments/assets/a419bf29-9925-44f2-a6c7-c11af6401806" /> --------- Signed-off-by: Parship Chowdhury <parshipchowdhury@gmail.com> Co-authored-by: Charles Bochet <charles@twenty.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
79c9c75776 |
fix: use correct userWorkspaceId for navigation menu comparisons (#21299)
## What does this PR do? Fixes a bug where `NavigationMenuItem.userWorkspaceId` was being compared/set to `WorkspaceMember.id` instead of the correct `UserWorkspace.id`, causing the favorites functionality to not work correctly. Fixes #21291 ## Problem The `isFavorite` check in `ViewPickerOptionDropdown` and `createManyNavigationMenuItems` calls in multiple files were using `currentWorkspaceMemberId` (which is `WorkspaceMember.id` from the `workspace_*` schema) instead of the correct `UserWorkspace.id` (from the `core` schema). This caused: - `isFavorite` to always return `false` for user favorites - Navigation menu items to be created with incorrect `userWorkspaceId` ## Root Cause In `useNavigationMenuItemsData.ts`: - `currentWorkspaceMemberId` was derived from `currentWorkspaceMember?.id` (WorkspaceMember.id) - But `NavigationMenuItem.userWorkspaceId` expects a `UserWorkspace.id` - These are two different entities from different schemas (core vs workspace) ## Solution 1. Added `currentUserWorkspaceId` to the `useNavigationMenuItemsData` hook return type 2. `currentUserWorkspaceId` is derived from `currentWorkspaceMember?.userWorkspaceId` 3. Updated all comparisons and assignments to use `currentUserWorkspaceId` when dealing with `userWorkspaceId` ## Files Changed - `packages/twenty-front/src/modules/navigation-menu-item/display/hooks/useNavigationMenuItemsData.ts` - Added `currentUserWorkspaceId` to return type - `packages/twenty-front/src/modules/views/view-picker/components/ViewPickerOptionDropdown.tsx` - Fixed `isFavorite` check and `createManyNavigationMenuItems` call - `packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/components/AddToFavoritesSingleRecordCommand.tsx` - Fixed `createManyNavigationMenuItems` call - `packages/twenty-front/src/modules/navigation-menu-item/edit/hooks/useNavigationMenuItemEditController.ts` - Fixed `targetUserWorkspaceId` assignment ## Testing - No existing tests directly cover the `useNavigationMenuItemsData` hook - The fix is a simple type/field correction that should not affect other components - CI will verify TypeScript compilation and linting ## Checklist - [x] I have read the [CONTRIBUTING.md](https://github.com/twentyhq/twenty/blob/main/.github/CONTRIBUTING.md) file - [x] Changes are tested locally (TypeScript compilation) - [x] Commit message follows repository conventions - [x] PR is linked to the relevant issue (#21291) --------- Co-authored-by: Mani bharadwaj <Manibharadwaj@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
6bfbe036f6 |
fix(settings): gate APIs & Webhooks page on API_KEYS_AND_WEBHOOKS, not WORKSPACE (#21302)
## Summary The **APIs & Webhooks** settings page (`SettingsPath.ApiWebhooks`) is gated by the wrong permission flag. Its route sits in the `PermissionFlagType.WORKSPACE` group in `SettingsRoutes.tsx`, but everything else about the page is gated on `API_KEYS_AND_WEBHOOKS`: - The **nav item** is hidden behind `API_KEYS_AND_WEBHOOKS` (`useSettingsNavigationItems.tsx`). - All its **sub-routes** — new/detail API key, new/detail webhook, and the GraphQL & REST playgrounds — already live under the `API_KEYS_AND_WEBHOOKS` wrapper. So a role with **"API Keys & Webhooks"** enabled but **without "Workspace"** sees the nav item (and the **"Set up MCP"** button in *Settings → AI*, which links to `/settings/api-webhooks#mcp`), but on arrival `SettingsProtectedRouteWrapper` finds no `WORKSPACE` flag and redirects them to the **Profile** page. The entry points are visible; the destination is unreachable. ## Root cause The route was grouped under the `WORKSPACE` wrapper while its nav item and sub-pages are gated on `API_KEYS_AND_WEBHOOKS` — the page's route gate and its nav gate disagree. ## Changes - `SettingsRoutes.tsx` — move the `SettingsPath.ApiWebhooks` route out of the `WORKSPACE` group and into the existing `API_KEYS_AND_WEBHOOKS` group, alongside its own sub-routes. This is the same class of fix as #21239 (*gate the AI settings page on `AI_SETTINGS`, not the chat flag*). ## Test plan - [ ] Role with **only "API Keys & Webhooks"** (`API_KEYS_AND_WEBHOOKS`, no `WORKSPACE`): *Settings → APIs & Webhooks* is reachable; the nav item and the *Settings → AI* "Set up MCP" link both land on the page instead of redirecting to Profile. - [ ] Role with **"Workspace" but not "API Keys & Webhooks"**: the APIs & Webhooks nav item stays hidden and the route is not reachable (was previously reachable — now consistent with the nav). - [ ] Admin (both flags): unchanged. |
||
|
|
011afa6011 |
Allow kanban cross-column drag when sorting is enabled (#21025)
## Summary This PR allows kanban cards to be dragged across columns while sorting is enabled. Previously, any board drag while a sort was active opened the “Remove sorting?” modal. That makes sense for same-column reordering, because manual reorder conflicts with the active sort. But for cross-column moves, the user is changing the grouped field, not trying to manually reorder the destination column. With this change: - Same-column drag with sorting enabled still opens the existing remove-sorting modal. - Cross-column drag with sorting enabled updates only the group field. - The destination column keeps using the active sort to determine where the card appears. - Unsorted board drag behavior continues to update `position` as before. ## Why On sorted kanban boards, moving a card to another column is a valid workflow even though manual reordering is not. The previous guard blocked both cases because it only checked whether sorting was active, not whether the card stayed inside the same column. ## Implementation The drop behavior now distinguishes between: - sorted same-column drops, which remain blocked - sorted cross-column drops, which are allowed without a position update - unsorted drops, which keep the existing position-update behavior A small helper captures that decision and has focused unit coverage. ## Validation - Manually verified sorted cross-column drag persists after refresh. - Manually verified sorted same-column drag still opens the remove-sorting modal. - Manually verified unsorted same-column drag still reorders cards. - Manually verified unsorted cross-column drag still moves cards. - Ran focused Jest coverage for the sorted board drop decision. - Ran formatting and oxlint checks on touched frontend files. - Ran `twenty-front` typecheck. - Ran `twenty-front` production build. Co-authored-by: Félix Malfait <felix.malfait@gmail.com> Co-authored-by: Charles Bochet <charles@twenty.com> |
||
|
|
4658d44d8b |
fix(settings): ship borderless hero cover images (#21277)
## What The settings discovery hero images (AI, Applications, Page Layouts, Members, Data Model, APIs & Webhooks) baked the rounded border into the pixels — transparent rounded corners plus a 1px edge stroke. Rendered inside `Card rounded` — which already draws a 1px border + border-radius and clips children with `overflow: hidden` — this produced a doubled, slightly misaligned border. This replaces all 12 files (light + dark per section) with clean full-bleed exports (opaque square corners), so the border and rounding come entirely from CSS. ## Notes - Pure asset swap, no component changes. - The MCP section's `.svg` cover is untouched (no new export provided). Billing's unused cover is left as-is. ## Verification - Each new image confirmed 1388×300, opaque square corners (no baked border), correct light/dark variant. - `Card` (twenty-ui) provides `border` + `border-radius` + `overflow: hidden`, so the square images are clipped to the rounded card. |
||
|
|
91f2f08995 |
feat(server): unify workspace-event ingestion behind one EventSink pipeline (#21197)
## Why The five event-log streams (`workspaceEvent`, `pageview`, `objectEvent`, `usageEvent`, `applicationLog`) each wrote to ClickHouse through their own fire-and-forget writer (`AuditService`, `UsageEventWriterService`, and the `application-logs` driver), with the per-type knowledge (table names, normalization, access rules) spread across several modules. Three of them reimplemented the same ClickHouse insert, and the read side, the live stream, and the producers lived in different modules under two different names. This consolidates them into one `core-modules/event-logs/` subsystem (emit, write, live, read), with the per-type config in a single registry so adding an event type is roughly one file. The base Logs settings tab and free application logs shipped separately in #21180 (merged). This PR adds the unified backend, the registry, and the viewer's live mode and entitlement gating. ## Pipeline ```mermaid flowchart TB subgraph PROD["Producers"] A["auth, billing, impersonation,<br/>webhook, custom-domain"] U["usage listener"] F["logic-function executor (app logs)"] R["record CRUD (entity events)"] end EM["EventLogEmitterService<br/>createContext().insert* / dispatch()"] EQ(["entityEventsToDbQueue<br/>(existing, shared with timeline)"]) CIE["CreateEventLogFromInternalEvent"] SINK["WorkspaceEventSinkService.ingest()"] C1["ClickHouseEventSink"] C2["ConsoleEventSink"] LIVE["EventLogLiveService.publishWatched()<br/>(presence-gated)"] CH[("ClickHouse, 5 tables, async_insert")] CHAN(["WORKSPACE_EVENTS_CHANNEL"]) RS["EventLogsService (registry-driven read)"] LR["EventLogsLiveResolver"] UI["Settings > Logs"] A --> EM U --> EM F --> EM EM -->|direct| SINK R --> EQ --> CIE -->|ingest| SINK SINK --> C1 --> CH SINK --> C2 SINK --> LIVE -.->|if a viewer is watching| CHAN --> LR --> UI CH --> RS --> UI ``` ## What it does - Producers call `EventLogEmitterService.createContext().insert*()`, which builds a typed `WorkspaceEventEnvelope` and writes it through `WorkspaceEventSinkService` to the configured sinks (ClickHouse, Console) plus a presence-gated live fan-out. Record/CRUD events reach the same sink through the existing `entityEventsToDbQueue`. There is no dedicated queue; ClickHouse `async_insert` batches server-side. Writes are best-effort, as on main today. - `EVENT_LOG_TYPES[table]` is the per-type source of truth: the ClickHouse table, the required entitlement, the free-text filter column, and the row-to-GraphQL mapping. Read row shapes derive from the write rows. - Four modules along their dependency boundaries: `EventLogEmitterModule` (producer API), `EventLogIngestionModule` (sink layer), `EventLogLiveModule` (fan-out), and `EventLogsViewerModule` (the entitlement-gated GraphQL read, which is where billing/enterprise/permissions stay so producers stay light). - Logs viewer: per-table columns, filters (text, date, record), live mode, and an upgrade card that points to Billing on Cloud or the Admin Panel on self-hosted. Application logs are free on every plan; the other four require the `AUDIT_LOGS` entitlement (with a `NO_ENTITLEMENT` fallback to the upgrade card). - Renames `AuditService` to `EventLogEmitterService`, and the generic `Monitoring` event to a typed `Impersonation` event (`level` + `action`). - Removes `UsageEventWriterService`, the `application-logs` driver/module, and `AuditService`'s direct inserts. ## Durability Writes are best-effort, the same as main today (the old writers were fire-and-forget). A dedicated queue was tried mid-PR and removed: `async_insert` already batches server-side, so the queue only added durability, which isn't a requirement right now. The `EventSink` seam keeps a durable transport (e.g. a Redis-Streams buffer) easy to add later without touching producers. ## Out of scope S3 peer sink (seam only), Postgres or any second read path, `ReplicatedMergeTree`, ClickHouse table-schema changes, and the record-data `EVENT_STREAM_CHANNEL` (unchanged, separate concern). ## Testing Unit tests cover the registry definitions and row normalization, the entitlement gating, the envelope builders, and the producers. Integration tests cover the write paths (record create produces an `objectEvent`; the track mutation produces a `workspaceEvent`) and the read/query path across all five tables. Verified with typecheck, lint, a server boot, and GraphQL/SDK codegen. |
||
|
|
c3dd6b25a6 |
fix: use canonical oxlint rule id in lint-disable directives (#21253)
## What Many `oxlint-disable` / `eslint-disable` directives across the repo carry a corrupted rule id — `@typescripttypescript/<rule>` — most likely a find-and-replace accident that mangled the eslint-era `@typescript-eslint/` prefix. oxlint matches disable directives **loosely by rule name**, so these still suppress in practice (not a silent no-op), but the id is malformed and misleading. ## Change Replace them with the **canonical oxlint id** `typescript/<rule>` — matching the plugin name and rule keys declared in `.oxlintrc.json` — **127 files, 262 directives**: | rule | count | | --- | ----- | | `typescript/no-explicit-any` | 250 | | `typescript/ban-ts-comment` | 6 | | `typescript/no-misused-promises` | 4 | | `typescript/no-empty-object-type` | 2 | - `twenty-server`: 122 files - `twenty-front`: 5 files Comment-only — no code or runtime changes. ## Verification `oxlint --type-aware -c .oxlintrc.json` reports **0 warnings / 0 errors** for both `twenty-server` and `twenty-front`. Every changed line is exactly the id correction inside a disable directive (262 insertions / 262 deletions, no collateral edits). > Addresses the cubic review, which flagged that the canonical oxlint id is `typescript/...` (no `@`). Worth noting the original `@typescripttypescript/` was not actually a silent no-op — oxlint matches these directives loosely by rule name — but `typescript/` is the correct, config-aligned id. |
||
|
|
1b30983307 |
fix(settings): gate the AI settings page on AI_SETTINGS, not the chat flag (#21239)
## Summary Closes #21229. The two AI role permissions behaved **opposite to their labels**. The trap is that the flag's code name is the inverse of its UI label: | `PermissionFlagType` | UI label | Section | Means | |---|---|---|---| | `AI` | **"Ask AI"** | Actions | End-user: chat with AI | | `AI_SETTINGS` | **"AI"** | Member / settings | Admin: configure AI agents | Before this PR (on `main`): - `AI` ("Ask AI", chat) gated **both** the AI chat **and** the AI settings page. - `AI_SETTINGS` ("AI", configure agents) gated **nothing** the user could see. So a chat-only user could reach the whole AI **configuration** page, and toggling the "AI" settings permission did nothing — exactly the misalignment reported in #21229. ## Root cause `PermissionFlagType.AI` *reads* like "the AI permission", so it looks like the natural gate for the AI settings page — but it's actually the **chat** flag. The settings page (nav item + route) had been pointed at `AI` in #21072 to match the Overview stats query (`findWorkspaceAiStats`), which was itself mis-gated on `AI`. Both the stats query and the rest of the settings surface are admin/config features, so they belong on `AI_SETTINGS`. ## Changes All three move the **AI settings surface** from the chat flag (`AI`) to the settings flag (`AI_SETTINGS`); chat keeps following `AI`: - `useSettingsNavigationItems.tsx` — AI nav item → `AI_SETTINGS` - `SettingsRoutes.tsx` — AI settings route group → `AI_SETTINGS` - `ai-workspace-stats.resolver.ts` — `findWorkspaceAiStats` (settings-only, drives the Overview tab) → `AI_SETTINGS` After this: the "AI" permission controls the AI settings page + its Overview; the "Ask AI" permission controls the chat. Both toggles now match their labels. ## Test plan - [ ] Role with **only "Ask AI"** (`AI`): AI chat tabs/pane visible; **Settings → AI is hidden** and the route is not reachable. - [ ] Role with **only "AI"** (`AI_SETTINGS`): Settings → AI is visible, Overview stats load; chat nav is hidden. - [ ] Admin (both flags): everything works as before. ## Known follow-ups (out of scope — pre-existing, shared endpoints) These remain on `AI` because they're shared with non-settings surfaces and need either OR-gating or a resolver split, so a role with `AI_SETTINGS` but **not** `AI` still can't use them yet: - `getAiSystemPromptPreview` (Models/Prompts tabs) lives in the chat resolver, class-gated `AI`; NestJS guards are additive so it can't be cleanly method-overridden — it should be pulled into a settings resolver. - Agent reads `findManyAgents` / `findOneAgent` (agent create/edit forms) are class-gated `AI` and shared with the **Workflow** editor and **Roles** pages; these want a guard that accepts `AI ∨ AI_SETTINGS ∨ WORKFLOWS`. |
||
|
|
4e1cc2d831 |
fix: prevent workflow from disappearing after activation (#21231)
## Summary - Fixes a regression from #21176 where activating a workflow caused it to disappear until page refresh - Root cause: when a draft is activated (status DRAFT→ACTIVE), `useEffectiveDraftVersionId` incorrectly treated it as a discard because the cached version was no longer DRAFT, filtering it from the versions list - Fix: only set `lastDiscardedDraftId` when `deletedAt` is actually set on the cached version, not when the status simply changes ## Test plan - [x] Open a workflow with a DRAFT version - [x] Activate the workflow → verify it does NOT disappear - [x] Discard a draft → verify header does NOT flicker between DRAFT/ACTIVE |
||
|
|
c2ca90c255 |
feat(sdk): add runAgent() to run app agents from logic functions (#21157)
<img width="948" height="593" alt="image" src="https://github.com/user-attachments/assets/d990fa98-3cfd-469d-ab7f-0b2d4ccf3afc" /> <img width="1361" height="802" alt="image" src="https://github.com/user-attachments/assets/1091f598-49f3-4c16-92ea-1e1c200181e2" /> ## Add `runAgent()` to the Logic Function SDK Lets an app's logic function run one of its own AI agents server-side and get the result back synchronously — reusing the existing agent executor instead of a new bespoke transport. ### Backend - New **`runAgent` GraphQL mutation** (metadata schema) in `ai-agent-execution`, wrapping the existing `AgentAsyncExecutorService.executeAgent`. Scopes the agent lookup to the calling application and runs it under an application auth context. - New `@AuthApplication()` param decorator (mirrors `@AuthWorkspace()`) — first GraphQL resolver authenticated by an **application access token**. - Guarded by `WorkspaceAuthGuard` + `SettingsPermissionGuard(PermissionFlagType.AI)`: the app's role must grant the `AI` permission flag. ### SDK - `runAgent({ agentUniversalIdentifier, prompt })` posts the mutation to `/metadata` with the app token via a new runtime GraphQL transport. Returns `{ result, hasNoMoreAvailableCredits }`. - Refactored the connections helpers onto a shared `postAppEndpoint` util (removes duplicated transport logic). ### Frontend - App install permission modal now shows an explicit consent line — _"Run AI agents and bill AI credits to your workspace"_ — when the app's role requests the `AI` flag. ### Docs - Documented `runAgent` and its `AI` permission-flag requirement in _Skills & Agents_. - Fixed outdated role-permission examples in _Roles & Permissions_ (`permissionFlags` → `permissionFlagUniversalIdentifiers`, `PermissionFlag` → `SystemPermissionFlag`). ### Test plan - [x] SDK unit tests (`run-agent.spec.ts`) — request shape, GraphQL/HTTP error handling, missing env vars - [x] `twenty-server`, `twenty-front`, `twenty-shared` typecheck + lint - [ ] Manual: install an app granting the `AI` flag, call `runAgent()` from a logic function, confirm the agent runs and credits are billed --------- Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> |
||
|
|
41d5d80a65 |
Migrate Company and Person standard fields in preparation for the enrichment app (#21171)
# Migrate Company and Person standard fields in preparation for the
enrichment app
## Why
Our standard `Person`/`Company` objects accumulated fields that aren't
generic to every
business, while missing a more universal revenue field that essentially
every CRM ships.
This PR makes the **Standard application** hold a tighter, more
universal set of fields,
and sets the stage for a follow-up PR that introduces a **People Data
Labs enrichment app**
to populate them.
## What changes
### Standard fields
**Demoted (Standard → Workspace Custom application)** — not generic
enough to ship as standard:
| Object | Field | Type |
| ------- | ------------------------------ | -------- |
| Company | annualRecurringRevenue (ARR) | CURRENCY |
| Company | employees | NUMBER |
| Company | idealCustomerProfile (ICP) | BOOLEAN |
| Company | xLink (X/Twitter) | LINKS |
| Person | xLink (X/Twitter) | LINKS |
| Person | city | TEXT |
**Added (new generic Standard field)** — present in
Salesforce/HubSpot/Zoho, PDL-populatable:
| Object | Field | Type |
| ------- | ------------- |
-------------------------------------------------------- |
| Company | annualRevenue | CURRENCY (generic total revenue; replaces
the niche ARR) |
### Behavior by workspace
* **New workspaces:** demoted fields are gone; `annualRevenue` is
**active**.
* **Existing workspaces:** demoted fields are **preserved as active
custom fields, data intact**;
`annualRevenue` is created **inactive (opt-in)** with its column ready,
so a later activation
is a metadata-only toggle.
### Upgrade commands (v2.9)
Three idempotent, per-workspace commands, run in timestamp order:
1. **`upgrade:2-9:move-demoted-standard-fields-to-custom-application`**
(1799000040000) —
re-owns the 6 demoted fields to the workspace custom application
(`isCustom = true`,
new `applicationId` + fresh `universalIdentifier`), keeping their data
and active state.
2. **`upgrade:2-9:rename-conflicting-custom-fields`** (1799000045000) —
if a workspace already
has a *custom* field named `annualRevenue`, renames it to
`annualRevenueCustom`
(data preserved via column rename) so the standard field can be added.
Skips non-custom matches.
3. **`upgrade:2-9:add-inactive-generic-standard-fields`**
(1799000050000) — creates
`Company.annualRevenue` on existing workspaces as inactive, guarded to
skip workspaces
missing the target object or where the name is still taken.
**Failure model:** the workspace iterator isolates failures per
workspace (one workspace failing
never affects others); within a workspace the runner records per-command
status and resumes on the
next run, and every command is idempotent, so partial runs self-heal.
### Supporting changes
* **Field-option color palette:** widened the `TagColor` union
(`twenty-shared` `FieldMetadataOptions`
+ the field-metadata `options.input` DTO) from 10 colors to the full
theme palette, benefiting any
future SELECT/MULTI_SELECT field.
* **Dev seeder:**
* The default "Annual Recurring Revenue" dashboard widget now points at
the generic
`annualRevenue` field (renamed to "Annual Revenue").
* Removed the "Companies by Size (Stacked by City)" widget (relied on
the demoted `employees`).
* `employees` is dropped from company data seeds and re-added as a
**custom** field seed, so dev
workspaces still get an `employees` column matching the demoted
behavior.
### Cleanup
Front-end record types (`Company.ts`/`Person.ts`), the
`getDisplayNameFromParticipant` test mock,
metadata integration specs, the Zapier `crud_record` test, and the
regenerated
`get-standard-object-metadata-related-entity-ids` snapshot.
## ⚠️ Breaking change (intentional)
Removes standard fields `Company.annualRecurringRevenue`,
`Company.employees`,
`Company.idealCustomerProfile`, `Company.xLink`, `Person.xLink`, and
`Person.city` from the core
GraphQL schema (replaced by `Company.annualRevenue`).
This is why the breaking-changes check reports a large number of
removals — `graphql-inspector`
flags any removed object field plus its derived
aggregate/order-by/filter/update types.
**Mitigation:** the
`upgrade:2-9:move-demoted-standard-fields-to-custom-application` command
re-owns these fields as custom fields per workspace, preserving their
name and data, so existing
tenants keep working. New workspaces won't have them.
|
||
|
|
a3a44c8315 |
fix(front): settings skeleton, app-detail header & empty favorites (#21209)
Three small post-redesign UI fixes. Each is an independent commit, so they can be split into separate PRs if preferred. ## 1. Settings loading skeleton — match the rounded-card layout The redesign (#21131) moved settings chrome into a rounded card (`SettingsPageLayout`: bordered header with breadcrumb + centered title, optional secondary bar, 760px body), but `SettingsSkeletonLoader` still rendered the old flat `PageHeader` + `PageBody` — so pages painted as a full-width flat bar then snapped into the card. - `SettingsSkeletonLoader` now reproduces the card and **reuses the real `SettingsPageHeader` + `SettingsPageContainer`**, so the frame aligns by construction; the card CSS is replicated (not `SettingsPageLayout`) to avoid the layout's side effects (hotkeys, side panel, info banner). - It's **composed with `SettingsSectionSkeletonLoader`** so the loading body is identical whether or not chrome is present. Rule: no chrome on screen yet → full-page skeleton; chrome already on screen → body-only `SettingsSectionSkeletonLoader` (the admin Enterprise tab now uses it, matching its sibling tabs). A short comment on each component documents this. ## 2. Application detail header — pass a plain title `SettingsApplicationDetails` / `SettingsAvailableApplicationDetails` passed a custom `SettingsApplicationDetailTitle` (avatar + name + multi-line description, fixed width) into `SettingsPageLayout`'s **centered single-line title slot**, which broke the header. They now pass the app's display name like every other page. The available-app "unlisted" notice moves into the body as a reusable `InlineBanner`; the now-unused `SettingsApplicationDetailTitle` is removed. ## 3. Navigation — hide Favorites when empty Always rendering the Favorites section (#21087) left a stray "Favorites" title above Workspace for users with no favorites. It now renders only when at least one favorite exists (redundant per-child guards dropped). Note: the "+ add favorite" entry point therefore appears once you have ≥1 favorite; the first favorite is created from a record/view as before. ## Verification - `nx typecheck twenty-front` ✅ · `oxlint` + `oxfmt --check` on changed files ✅ - i18n catalogs intentionally untouched — handled by the repo's separate i18n pipeline. |
||
|
|
2ac515894b |
feat(settings): add Logs as a dedicated tab in General settings (#21180)
## What & why The audit-log viewer lived as a full-screen page reachable only via a "View Logs" button buried in the **Security** tab. This surfaces it as the **third tab in General settings** (`General | Security | Logs`), consistent with the other tabs. ## Changes - **Relocated** the event-logs module `pages/settings/security/event-logs/` → `modules/settings/event-logs/` and render it as tab content instead of a `FullScreenContainer` page. Dropped `SettingsPath.EventLogs`, its route, and the fullscreen handling in favor of the `general#logs` hash tab. - **Security tab:** removed the "View Logs" entry; kept the log-retention setting there. - **In-tab gating** (shown to users with the Security permission): Enterprise upgrade card when not entitled, a clear "ClickHouse not configured" placeholder otherwise (derived from client config), and the query is skipped when disabled. Replaces a bespoke error component that string-matched error messages with the shared `SettingsEmptyPlaceholder` / `SettingsEnterpriseFeatureGateCard`. - **Layout:** boxed content column with the table selector + filters grouped in a `Card` and the results table below, matching settings conventions. Kept the existing fixed filters (page/event name, member, period) rather than recreating the record-view filter chips (those are tightly coupled to record/view context). Frontend + `twenty-shared` only — no changes to the log query or data. ## Test plan - [x] `npx nx typecheck twenty-front` and `npx nx lint twenty-front` pass - [x] Settings → General shows three tabs; Logs is the third; breadcrumb stays "Workspace / General" - [x] With Enterprise + ClickHouse: table selector, filters, refresh, and the paginated table work - [x] Non-Enterprise: Enterprise upgrade card shown; no failing query fires - [ ] Enterprise without ClickHouse: shows the "ClickHouse not configured" placeholder - [ ] Security tab still shows the log-retention setting and the "View Logs" button is gone - [ ] A user without the Security permission sees neither the Security nor Logs tab |
||
|
|
ccffc4a1ea |
Fix axios related dependabot alerts generated against root yarn.lock (#21187)
Fixes the following Dependabot alerts: https://github.com/twentyhq/twenty/security/dependabot?q=is%3Aopen+package%3Aaxios+manifest%3Ayarn.lock+has%3Apatch Upgraded the referenced version in root yarn.lock. Creating a separate PR for the nested ones to keep the updates isolated (e.g. /seed-dependencies/yarn.lock). |
||
|
|
15eaabdbc1 |
fix(ai) - optimize crud tools (#21133)
- **Add delete many**, `delete_many_{object}` added alongside the
existing `delete_one_{object}`.
- **Uniformize naming**, crud module, type names, and MCP helper
constants renamed for consistency.
- **Optimize tool schema (learn phase)**
- `find_many(_companies)`: **7 158 → 2 700 tokens**
- `find_one(_company)`: **280 → 126 tokens**
- ....
- Main mechanism: `reused: 'ref'` (line 7 of
`to-tool-json-schema.util.ts`). Zod walks the schema tree, tracks which
Zod schema instances appear more than once, and emits each reused
instance exactly once in `$defs`, replacing all subsequent occurrences
with a `$ref`. Works because filter and value schemas are now extracted
as shared objects.
- **Optimize system prompt (tool catalog)**, DATABASE_CRUD section
restructured to list operation patterns (`find_many_{object}`, …) once +
objects once, instead of the full N×M cross-product of tool names.
- **Optimize execute_tool**, shared record-properties schema (same
`$defs` deduplication applies at call time); introduced `upsert_many`;
added `selectedFields` to `find_*` so the agent only fetches the fields
it needs.
|
||
|
|
d3a7ea0790 |
Fix: Not able to add multiple handles to Blocklist in settings/accounts (#21049)
Fixes: #21031 ### Root cause: This feature was never fully implemented even though the placeholder text suggested it was supported. It could only update one handle at a time. ### Fix Fixed the zod validation to validate each handle separately. Used `useCreateManyRecords` to update multiple handles at the same time. ### Before: <img width="2032" height="1162" alt="Screenshot 2026-05-29 at 3 25 12 PM" src="https://github.com/user-attachments/assets/ae6b6ae3-ed38-4410-801e-11f514773681" /> ### After: https://github.com/user-attachments/assets/69354129-422a-41de-baf7-fa5a28f01f3f --------- Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com> |
||
|
|
4b15b949f3 |
Provide additional logsobservability to workflow runs (per node) (#21142)
Surfaces per-step "Logs" tabs in the workflow run side panel so users can see what each step actually did (model + tokens + tool calls for AI, console output for serverless functions, request/response for HTTP, recipients/body for Email). <img width="546" height="501" alt="ai_agent_without_websearch" src="https://github.com/user-attachments/assets/c6ca3518-9489-4484-a570-3d0569ff3b03" /> ## Storage - New `stepLogs` JSONB column on the `workflowRun` workspace entity, typed as `Record<string, WorkflowRunStepLog>` (keyed by step id). - Schema lives in `twenty-shared`: `workflowRunStepLogSchema` with a discriminated `details.type` union for `AI_AGENT | CODE | HTTP_REQUEST | EMAIL` — frontends and backends consume the same Zod-inferred type. - Field is added to existing workspaces via a workspace upgrade command (`2-9 add-workflow-run-step-logs-field`); the standard-object metadata declares it for new workspaces. - Writes happen atomically per step in `WorkflowRunStepLogWorkspaceService.setStepLog` using `jsonb_set`. That lets concurrent steps in the same run write their own keys without contending with the existing lock around `workflowRun.state`. - Per-step payload is hard-capped at 256 KB; anything larger is dropped with a `logger.warn`, so a pathological tool call can never bloat a row. See below for more information. ## How logs are produced **Aalmost everything was already being collected; this PR mostly persists and renders it.** - **AI agent** — `AgentAsyncExecutorService` already tracked token usage, model id, native web-search count, and the AI SDK's `steps[]`. We map those into the log via `mapAiStepsToToolCallLogs` (`searchVector` stripped from record outputs, per-call input/output capped at 32/64 KB, max 200 tool calls per step). The only new measurement is a wall-clock `durationMs` taken around `executeAgent`, and we now fold native web-search cost into the displayed `totalCostInDollars` (it was already billed, just not shown). - **Code / serverless function** — reuses the `console.log` output the function runner already returns (`logsByLevel`); `build-code-step-log.util` only repackages it. - **HTTP request** — built from the action's existing input/output via `build-http-request-step-log.util`. No new signals collected. - **Email (send / draft)** — added `sanitizedHtmlBody` + `plainTextBody` to the existing tool outputs (a small additive change), then `build-email-step-log.util` consumes them. No additional AI inference or external calls are made for logging — the cost is a small CPU overhead per step plus the JSONB write. ## Security The log surface intentionally shows whatever the workflow touched, which made redaction and sanitization the main design concern. - **HTTP — secrets in headers**: existing `SENSITIVE_HEADER_NAMES` set (Authorization, Cookie, …) replaced with `[redacted]` in both request and response. - **HTTP — secrets in URLs**: `SENSITIVE_URL_PARAM_NAMES` (e.g. `api_key`, `token`, `access_token`) replaced in the query string via `URL`-based parsing. - **HTTP — secrets in bodies**: `SENSITIVE_BODY_KEY_REGEX` deep-walks JSON request/response bodies (object input or stringified JSON) and redacts matching keys. Applied to the `error` field too, since transport-layer errors sometimes embed structured payloads. - **Email — XSS risk in body preview**: tool outputs now expose a server-side `sanitizedHtmlBody`; the log builder prefers it over the raw user-authored `input.body`, with `plainTextBody` as a second fallback. The original raw body is only used if sanitization didn't happen (e.g. tool failed before composing). - **AI — internal/noisy data**: `searchVector` (Postgres tsvector strings) is stripped from record outputs returned by Twenty tools to avoid leaking internal full-text-search payloads. - **DB bloat / runaway agents**: 256 KB per-step cap + 32 KB / 64 KB per-tool-call input/output cap + 200 tool calls per step. <img width="547" height="307" alt="logic_function" src="https://github.com/user-attachments/assets/dd4a3d16-67f2-434b-95b3-bdcaf9ed053d" /> ## More details on Log size & truncation Logs are stored in `workflowRun.stepLogs` (JSONB), keyed by `stepId`. ### Per-step cap Each step's log is hard-capped at **256 KB** (`MAX_STEP_LOG_BYTES` in `WorkflowRunStepLogWorkspaceService.setStepLog`). For ~99% of workflows this is roomy — typical real-world sizes: - Code / serverless function: 1–20 KB - HTTP request: 5–70 KB - Email: 5–30 KB - AI agent (a handful of tool calls): 5–50 KB ### Two layers of bounding 1. **Per-field truncation** in each builder (before writing): - **Code**: ≤ 500 entries, ≤ 4 KB per message, ≤ 8 KB stack trace - **HTTP**: ≤ 32 KB per body (request + response), UTF-8 byte-aware - **Email**: ≤ 8 KB body preview, UTF-8 byte-aware - **AI agent**: ≤ 32 KB tool input, ≤ 64 KB tool output, ≤ 200 tool calls/step 2. **Global per-step safety net** at write time: if the assembled `stepLog` still exceeds 256 KB, the write is **dropped entirely** with a `logger.warn`. The workflow itself keeps running unaffected. ### What this means in practice - **Safe**: workflow execution, step results, downstream steps — never blocked by log size. - **Safe**: iterators (each iteration overwrites the previous log for that `stepId`, so they can't accumulate). - **Safe**: step retries (same `stepId` is overwritten, not appended). - **Possible**: an AI agent step with many large tool outputs (e.g., 50+ heavy `web_search` calls) can exceed 256 KB → the **entire** step's log is dropped, side panel shows "No logs were recorded for this step". The user has no explicit signal that the log was dropped due to size (only server-side warn). - **Possible** (theoretical): a workflow with hundreds of distinct steps could push the row toward Postgres's internal ~256 MB jsonb limit. Beyond that, individual `jsonb_set` writes would error and be swallowed by the action's try/catch — workflow still completes. ### Possible future hardening (not in this PR) - Replace "drop entire log" with a stub that preserves the summary card (cost, duration, status) and marks `truncated.reason = 'size_cap'`. - Surface size-drops in the UI (similar to the existing `<StyledTruncatedNotice>`). - Emit a metric so dropped logs are observable in dashboards. |
||
|
|
ac0368e876 |
fix: eliminate workflow editing flicker on active-to-draft transitions (#21176)
## Before https://github.com/user-attachments/assets/5108a9d8-2017-41d5-855c-98714cbd4237 ## After https://github.com/user-attachments/assets/0a78d1e1-354f-4f3f-8ec4-6f46517619e4 ## Summary - Fixes visual flickering/glitching in the workflow show page header and canvas when editing an active workflow or discarding a draft - Root cause: SSE events re-added discarded drafts to Apollo cache, and multiple hook instances had independent state causing version oscillation between DRAFT and ACTIVE - Rewrites `useWorkflowWithCurrentVersion` with a module-level `discardedDraftId` variable shared across all instances, Apollo cache seeding in mutation callbacks, and `lastValidResult` caching to prevent null renders ## Test plan - [x] Open a workflow show page with an ACTIVE workflow - [x] Drag a node to change position → verify no flicker, status shows DRAFT smoothly - [x] Discard the draft → verify header does NOT flicker between DRAFT/ACTIVE, position resets cleanly - [x] Click on manual trigger and edit settings → verify the edit works (draft created, settings saved) - [x] Repeat discard + edit cycle multiple times to confirm stability |
||
|
|
cc76b7bc50 |
Fix fields widget new field visibility (#21111)
Fixes https://github.com/twentyhq/twenty/issues/21043 ## Context Newly created fields were never added to FIELDS widgets, regardless of the "Set fields created in the future as visible" toggle. The widget's newFieldDefaultVisibility was null on widgets that never explicitly set it (it was never populated at creation), so the backend skipped them and no view field was created. ## Implementation Keep newFieldDefaultVisibility nullable with false (not visible) as the behavior when not provided. The FE now reflects that properly and shows "un-toggled" when it's null (iso with BE behavior). The fix also ensures the value is explicitly set to true wherever it should be: - Set newFieldDefaultVisibility: true at every FIELDS widget creation path (backend default record-page layout, frontend createDefaultFieldsWidget + useTemporaryFieldsConfiguration); - Added a 2-9 workspace upgrade command that backfills true onto existing standard FIELDS widgets where the value is null. |
||
|
|
e64e5662e5 |
fix(ai-chat): refresh JWT token on SSE reconnect to prevent login red… (#20176)
Closes #18928 ## Problem When a JWT access token expires while the AI chat is streaming a response, the SSE connection drops and `graphql-sse` calls the retry callback. The previous implementation would wait, then destroy the SSE client but never refreshed the token. On the next connection attempt the client reused the same expired token, eventually triggering an `UNAUTHENTICATED` error that redirected the user to the login screen. ## Solution Add proactive token renewal inside `useHandleSseClientConnectionRetry` before each reconnect attempt: - Uses a module-level `let renewalPromise` variable to deduplicate concurrent renewal requests , the exactpattern used in `ApolloFactory.ts` - Calls `renewToken` via `retryWithBackoff` against the `/metadata` endpoint - Writes the fresh token pair into the Jotai store ,the SSE client's `headers()` callback picks it up automatically on reconnect - If renewal fails -> falls back to destroying the SSE client as before ## Files changed - `packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts` ## Notes This addresses the two issues from the previous review: - No `useRef` using module-level variable instead - CI passing removed the `CombinedGraphQLErrors` import --------- Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com> |
||
|
|
1e336dbad1 |
feat: allow many-to-one relations as advanced filter leaves (#21147)
## What
Lets a many-to-one relation be selected as the **leaf** of an advanced
(nested) filter. Previously the nested-field submenu excluded relations,
so you could filter `Opportunities WHERE company.Name contains X` but
not `Opportunities WHERE company.accountOwner = me`.
## How it works
Selecting a relation leaf filters by its **foreign key** —
`company.accountOwnerId = X` — a single hop the backend already resolves
on the joined table (`{ company: { accountOwnerId: { in: [...] } } }`).
It is **not** a multi-hop traversal: filtering on a *scalar field of*
the related record (e.g. `company.accountOwner.name`) stays excluded,
since that needs a second join the backend caps at one hop.
Two changes:
- **`AdvancedFilterRelationTargetFieldSelectMenu`** — stop excluding
many-to-one relations from the nested-field submenu.
- **`ObjectFilterDropdownRecordSelect`** — resolve the record picker's
object from the *leaf* relation's target (e.g. WorkspaceMember,
including the "Me" pin) rather than the source relation's object. The
source-field fallback applies only when there is no leaf.
## Testing
- Added `turnRecordFilterIntoRecordGqlOperationFilter` unit cases
asserting a relation leaf (and `= me`) compiles to the FK form — 59/59.
- typecheck + lint green (twenty-front, twenty-shared).
Seeding an onboarding view that uses this filter will follow in a
separate PR.
|
||
|
|
120793f69f |
fix: block self-impersonation in admin panel (#21130)
## Issue - From Settings -> Admin Panel -> Workspace -> Members, impersonating the currently logged-in user still issued an impersonation login token. Token exchange produced invalid impersonation JWTs (`impersonatorUserWorkspaceId === impersonatedUserWorkspaceId`). JWT validation then failed with `User cannot impersonate themselves`, leaving the app in an endless loading state until cookies were cleared. - Closes #21086 ## Approach I was first thinking of to only hide the impersonate button for the logged-in user in the admin, since they can not click what isn’t shown (as I thought it was just a frontend issue). But that was not enough: - The `impersonate` mutation can still be called directly (GraphQL client, scripts, devtools). - Before this fix, the mutation could succeed and only fail later at JWT validation, which led to invalid tokens and a broken session. So the PR does both: - Frontend: hide/disable self-impersonation in the UI and avoid reloading on failed token exchange (UX). - Backend: reject self-impersonation in `ImpersonationService` and at token exchange (enforcement, fail fast before bad tokens). Hiding the button is the right product behavior; the backend change is what makes the rule real and safe. ## How to test Manual: - Log in as a user with admin impersonation. - Go to Settings -> Admin panel -> Workspace -> open your workspace -> members. - Confirm your row has no Impersonate button; other members still do. - Open Admin Panel -> User for yourself -> confirm no impersonate button. - Open Settings -> Members -> your own member profile -> confirm no Impersonate action. - Impersonate another member -> should work as before Automated: `npx jest impersonation.service.spec` ### Before: <img width="830" height="413" alt="Screenshot 2026-06-02 122224" src="https://github.com/user-attachments/assets/46f38a74-8bd6-4ffa-b749-500ce18314f1" /> ### After: <img width="795" height="369" alt="Screenshot 2026-06-02 122333" src="https://github.com/user-attachments/assets/62ece4a8-d38b-4f91-817f-792ff49b146b" /> --------- Signed-off-by: Parship Chowdhury <parshipchowdhury@gmail.com> Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com> |
||
|
|
c18f8d6cf7 |
Always show Favorites section and add favorites via the side panel (#21087)
## What & why The left-sidebar **Favorites** section was hidden whenever the user had no favorites, so it was effectively undiscoverable — and personal favorites could only be created via the record-level "Add to favorites" action or drag-drop. This PR: - **Always shows the Favorites section**, with an empty-state **"Add a favorite"** call-to-action. - Adds a **"+" on the Favorites header that opens the same "New menu item" side panel** the Workspace section already uses, so users can add personal **Objects, Views, Records, Links and Folders** directly from the sidebar. ## How Favorites and workspace navigation are the same `NavigationMenuItem` entity (a personal favorite simply has `userWorkspaceId` set). Rather than build a separate favorites-only flow, the shared add/edit side-panel subsystem is made **section-aware** (`NavigationMenuItemSection = 'workspace' | 'favorite'`): - a new `navigationMenuItemEditSectionState` atom records which section the panel is operating on; - a new `useNavigationMenuItemEditController` forks persistence — the **workspace** section stages changes in the draft (saved on layout-customization exit), while the **favorite** section creates/updates/deletes personal items **immediately** with `userWorkspaceId = current member`. This mirrors the existing `useHandleNavigationMenuItemDragAndDrop` fork. The existing add/edit hooks, pickers and title editors were rerouted through the controller and a section-aware items hook, so they work for both sections with no behavior change to the workspace flow. **Backend: no changes** — `canUserCreateNavigationMenuItem` already authorizes personal navigation menu items of every type for any authenticated user. ## Decisions & tradeoffs - **Folder button → unified "+":** the folder-only header button is replaced by the single "+" (Folder is one of the panel's options), matching the Workspace section. This removed the inline folder-create code path. - **Click-to-add only in v1:** dragging items from the panel directly into Favorites is deferred — those drag handles are disabled in the favorite section (the drag path is hardwired to workspace layout mode), with a defense-in-depth no-op in the drop handler. - **Persist-on-commit:** favorite title/URL edits hit the network once on blur/enter, never per keystroke. - **Personal color edits** change only the favorite's own color, never the shared object metadata (that remains a workspace-customization behavior). - The change touches ~37 files because it generalizes the shared subsystem rather than duplicating it; net diff is slightly negative (+605 / −636). ## Testing - `npx nx typecheck twenty-front` — passes - `npx nx lint twenty-front` (oxlint + oxfmt) — passes - `navigation-menu-item` unit tests — pass (incl. an updated `computeInsertIndexAndPosition` test covering personal items) - Manual end-to-end walkthrough still recommended before merge. |
||
|
|
431f6ae98f |
feat(settings): move settings chrome into a single rounded card (#21131)
## What Replaces `SubMenuTopBarContainer` with a settings-specific `SettingsPageLayout` that puts the whole page chrome — breadcrumb, centered title, actions, an optional secondary bar (tabs or wizard step), and the 760px body — inside **one rounded card**, with `SidePanelForDesktop` as a sibling. Title, tabs and body content share one centered vertical axis at every card width. Supersedes #21122. One PR, no feature flag. ## New components (`@/settings/components/layout/`) - **SettingsPageLayout** — owns the rounded card + side-panel sibling, `useCommandMenuHotKeys`, mobile command menu - **SettingsPageHeader** — breadcrumb · centered title · actions in a symmetric `1fr auto 1fr` grid (symmetric padding throughout) - **SettingsSecondaryBar** — the secondary row, bracketed by top + bottom borders - **SettingsTabBar** — centered tabs reusing `activeTabIdComponentState` + `TabListFromUrlOptionalEffect` for URL-hash sync (does not touch the shared `TabList`) - **SettingsWizardStepBar** — back arrow · "N. Label" · optional trailing slot ## Migrations - Bulk rename across ~80 call sites (`SubMenuTopBarContainer` → `SettingsPageLayout`); old component deleted. - 5 tab pages (AI, APIs & Webhooks, Applications, Members, Role) + the Data Model object-detail page render their tabs in `secondaryBar` (object-detail keeps "See records" / "New Field" in the header actions). - The 2 role object-level steps render the wizard step bar with working back navigation. - Accounts consolidated into **General / Emails / Calendars** tabs; standalone `SettingsAccountsEmails` / `SettingsAccountsCalendars` pages + routes + stories removed. `SettingsPath.AccountsEmails` / `AccountsCalendars` now resolve to `accounts#emails` / `accounts#calendars`, so existing `getSettingsPath()` links deep-link to the right tab via the existing hash sync — no call-site changes. ## Verification - `nx typecheck twenty-front` and `nx lint twenty-front` both clean. - Browser (logged-in workspace): title / tab / body / card centers align on a single axis at multiple widths — width-invariant, so alignment holds when the AI side panel (a sibling) shrinks the card. Rounded card with even gaps on all four sides; tab row bracketed by two 1px lines; no-tab pages render header → body with no lines; wizard back navigation works; `…/accounts#emails` opens the Emails tab. The shared `PageHeader` and `TabList` are untouched. The settings side panel itself isn't wired to open yet — that's a follow-up PR. |
||
|
|
2048efb75d |
fix(record-table): keep column header dropdown open after Move Left/Right (#21015)
Fixes #20999 ## Summary Fixes a UX issue where clicking **Move left** or **Move right** in the column header dropdown immediately closed the menu, forcing users to reopen it for every single move. ## Problem `handleColumnMoveLeft` and `handleColumnMoveRight` both called `closeDropdownAndToggleScroll()` unconditionally at the top of their handlers — before even checking `canMoveLeft` / `canMoveRight`. This immediately set the Jotai atom `isDropdownOpenComponentState` to `false`, unmounting the dropdown. Since move actions are **repeatable** — a user might want to shift a column several positions — they were forced into a frustrating loop: click header → click move → click header → click move → repeat for every step. ## Fix Removed the two `closeDropdownAndToggleScroll()` calls from the move handlers in `RecordTableColumnHeadDropdownMenu.tsx`. ```diff const handleColumnMoveLeft = () => { - closeDropdownAndToggleScroll(); - if (!canMoveLeft) return; moveTableColumn('left', recordField.fieldMetadataItemId); }; const handleColumnMoveRight = () => { - closeDropdownAndToggleScroll(); - if (!canMoveRight) return; moveTableColumn('right', recordField.fieldMetadataItemId); }; ``` All other handlers — **Filter, Sort, Hide** — are untouched and still close the dropdown correctly, since those are one-shot or navigation actions. ## Changes | File | Change | |---|---| | `RecordTableColumnHeadDropdownMenu.tsx` | Remove 2 `closeDropdownAndToggleScroll()` calls from move handlers | | `RecordTable.stories.tsx` | Add `HeaderMenuStaysOpenAfterMoveRight` regression story | ## Testing **Storybook interaction test** — `HeaderMenuStaysOpenAfterMoveRight`: clicks "Move right" then asserts the menu is still visible. **Manual checklist:** - [x] Move right → menu stays open - [x] Move right again → column moves again, menu still open - [x] Move left → menu stays open - [x] Move rightmost column → "Move right" disappears, menu stays open showing "Move left" - [x] Filter → menu closes *(unchanged)* - [x] Sort → menu closes *(unchanged)* - [x] Hide → menu closes *(unchanged)* - [x] Click outside → menu closes *(unchanged)* - [x] Escape → menu closes *(unchanged)* - [x] TypeScript: zero new errors (`tsc --noEmit`) --------- Co-authored-by: Félix Malfait <felix.malfait@gmail.com> Co-authored-by: Charles Bochet <charles@twenty.com> |
||
|
|
58907b733c |
feat(logic-function): add LIVE / PREBUILT execution modes (#20873)
## Summary
### Why
1. Sending the code to the lambda (~1Mb usually) is heavy on network and
results to a constant traffic of ~30Mb/s on AWS which results into TB of
network data every month
2. eval(1MB of code) is not that fast, it's heavy on memory and CPU on
lambda side
### High level
Adds two execution modes for logic functions, gated behind the new
`IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED` workspace feature flag (off
everywhere by default):
- **LIVE** (current behavior, preserved bit-for-bit): the compiled
bundle is read from object storage and shipped in every Lambda invoke
payload. Used for fast iteration in the workflow editor / Settings test
runs.
- **PREBUILT** (new): the bundle is installed onto the per-function
Lambda alongside the unified executor, and invocations carry only `{
params, env, handlerName }` — saving JSON payload egress and warm-start
`import()` cost on every call.
### Key design choices
- **Unified Lambda handler** (`constants/executor/index.mjs`) dispatches
at runtime: `event.code` present ? LIVE (write to `/tmp`, dynamic
import) : `import('./prebuilt-logic-function.mjs')`. Both code paths
always coexist on the deployment package, so the same Lambda can serve
either mode without redeploying.
- **Install runs inside the `validateBuildAndRun` migration pipeline**,
not at execute time. `Create/UpdateLogicFunctionActionHandlerService`
calls `driver.installPrebuiltBundle` when `executionMode` flips
LIVE?PREBUILT or `checksum` changes while PREBUILT, gated on
`isBuildUpToDate=true` and a fresh checksum.
- **Strict execute, no reconciliation**:
`LogicFunctionExecutorService.execute` resolves `effectiveExecutionMode`
(caller override > feature flag > entity column). For PREBUILT it asks
the driver `getInstalledBundleChecksum` (Lambda `twenty:bundle-checksum`
tag for AWS, sidecar file locally) and throws
`LOGIC_FUNCTION_PREBUILT_BUNDLE_NOT_INSTALLED` on mismatch.
- **Feature flag gates every side effect**: with the flag off the
executor forces LIVE, the action-handler install hooks bail before AWS,
and workflow activation does not flip the mode. Rollback is just turning
the flag off.
### Lifecycle
- New workflow CODE step ? `LIVE`, no install.
- Workflow activated ? build + activation flips `executionMode=PREBUILT`
? action-handler installs the bundle + sets the Lambda tag.
- Draft from active version ? duplicated logic function reset to `LIVE`.
- App install ? manifest converter sets `PREBUILT`, create-action
handler installs.
- Test runs (`executeOneFromSource`, workflow editor) pass
`executionMode=LIVE` explicitly.
### Observability
`[lambda-timing]` log lines now include `effectiveExecutionMode` and
`payloadBytes`; the action handler logs `install_duration_ms` for each
install.
## Test plan
- [x] `npx nx typecheck twenty-server` ? passes
- [x] `npx oxlint --type-aware` on all changed files ? 0 warnings, 0
errors
- [x] `npx nx test twenty-server` ? 588 suites / 5009 tests pass (no
regressions vs main)
- [x] New unit suite `flat-logic-function-validator.service.spec.ts` ?
9/9
- [x] Existing
`workflow-version-step-operations.workspace-service.spec.ts` ? 8/8
(verified the new token-based DI avoids a circular-import regression)
- [x] Snapshot for
`ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY` updated
to include `executionMode`
- [x] Integration suite `logic-function-execution.integration-spec.ts`
extended to assert `executionMode=LIVE` on newly-created functions and
continues to exercise the LIVE happy path
- [ ] Manual staging rollout: flip
`IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED` per workspace, observe
`[lambda-timing]` `payloadBytes` drop + `install_duration_ms`, then ramp
in prod.
|