Compare commits

..
467 Commits
Author SHA1 Message Date
Paul RastoinandGitHub 28e79de7b0 Fix workspace application fk command re-run (#17018)
# Introduction
The command is not idempotent, try to create an already existing FK
fails
- Always dropping the FK before recreating it in order to prevent this
- Removed the `remoteTable` and `remoteServer` from the command

We still have the `hasRunOnce` static var that will avoid re running it
if a workspace successfully passed the migration

Note: This is shared between both the upgrade command and the typeorm
migration

## Test
locally
```ts
atedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object person (20202020-e674-48e5-a542-72570eee7213) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object pet (custom) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object surveyResult (custom) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object rocket (custom) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] All objects already have updatedBy field for workspace 20202020-1c25-4d02-bf25-6aeccf7ea419
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [AddWorkspaceForeignKeysMigrationCommand] Successfully run AddWorkspaceForeignKeysMigrationCommand
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [UpgradeCommand] Upgrade for workspace 20202020-1c25-4d02-bf25-6aeccf7ea419 completed.
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [UpgradeCommand] Running command on workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db 2/2
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [UpgradeCommand] Upgrading workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db from=1.14.0 to=1.15.0 2/2
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [MigratePageLayoutWidgetConfigurationCommand] Starting migration of page layout widget configurations for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [MigratePageLayoutWidgetConfigurationCommand] Found 0 widget(s) needing migration out of 16 total
query: SELECT COUNT(1) AS "cnt" FROM "workspace_3ixj3i1a5avy16ptijtb3lae3"."note" "note" WHERE ( (("note"."position" = $1)) ) AND ( "note"."deletedAt" IS NULL ) -- PARAMETERS: ["NaN"]
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [FixNanPositionValuesInNotesCommand] Found 0 note(s) with NaN position values in workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [FixNanPositionValuesInNotesCommand] No NaN position values to fix
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Starting backfill of updatedBy field for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object note (20202020-0b00-45cd-b6f6-6cd806fc6804) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object task (20202020-1ba1-48ba-bc83-ef7e5990ed10) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object dashboard (20202020-3840-4b6d-9425-0c5188b05ca8) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object workflowRun (20202020-4e28-4e95-a9d7-6c00874f843c) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object workflow (20202020-62be-406c-b9ca-8caa50d51392) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object opportunity (20202020-9549-49dd-b2b2-883999db8938) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object company (20202020-b374-4779-a561-80086cb2e17f) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object attachment (20202020-bd3d-4c60-8dca-571c71d4447a) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object person (20202020-e674-48e5-a542-72570eee7213) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] Object surveyResult (custom) already has updatedBy field, skipping
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [BackfillUpdatedByFieldCommand] All objects already have updatedBy field for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [AddWorkspaceForeignKeysMigrationCommand] Skipping has already been run once AddWorkspaceForeignKeysMigrationCommand
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [UpgradeCommand] Upgrade for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db completed.
[Nest] 17395  - 01/08/2026, 3:04:18 PM     LOG [UpgradeCommand] Command completed!
```
2026-01-08 14:12:57 +00:00
0623bbbf9a i18n - docs translations (#17020)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 15:18:07 +01:00
MarieandGitHub f414f4799b Enable switching field to group records by on existing kanban view (#17015)
Fixes https://github.com/twentyhq/twenty/issues/16982 and
https://github.com/twentyhq/private-issues/issues/403

Re-introducing the feature to allow to switch field to group records by
on a kanban view


https://github.com/user-attachments/assets/a552d3f2-7900-4771-b512-98cb99cdd8de
2026-01-08 13:08:06 +00:00
Raphaël BosiandGitHub c207214f0b Fix chart sorting (#16996)
I introduced a bug in the chart sorting in this PR:
https://github.com/twentyhq/twenty/pull/16794
This PR fixes this.

The sorting on the first axis is already done by the group by for
FIELD_ASC and FIELD_DESC. It is sorted also for the second axis but in
each group.
For instance, if I create a graph that displays the amount of sales on
each day of the week grouped by vendor
I can have for:
Monday: Vendor B, Vendor C
Tuesday: Vendor A, Vendor B
Wednesday: Vendor A, Vendor C
...
Inside each day the order of the vendor is correct, but by looking at
only one day, I can't know the order of all the vendors.
That is why we always need to sort the second axis.
2026-01-08 12:46:56 +00:00
Don KendallandGitHub 8630efc3d7 feat: helm chart (#16808)
# Add Helm Chart

- Introduces a Twenty Helm chart with sensible defaults: internal
Postgres/Redis, auto DB creation/user, migrations, TLS via cert-manager,
and quickstart docs.

## Feedback requested
- Handling replicas > 1 with local storage (warn/force S3?).
- Defaults/guards for ephemeral pods + S3.
2026-01-08 12:45:46 +00:00
Raphaël BosiandGitHub 22573ccf03 [DASHBOARDS] Select title input upon tab or widget creation (#17010)
Video QA:


https://github.com/user-attachments/assets/334bbac8-03a5-4eb2-98b7-78bab7abfccf
2026-01-08 12:37:36 +00:00
nitinandGitHub 7fff8c8234 [Dashboards] Fix chart axis label behavior (#17011)
- Axis labels now respect `axisNameDisplay` config when chart has no
data (previously always showed both) - fixed for bar and line charts
- Horizontal bar charts now correctly map axis settings to visual
positions:
    - "X axis" setting → bottom axis (value)
    - "Y axis" setting → left axis (category)
    
video QA



https://github.com/user-attachments/assets/5bf32294-9a5e-4aa6-b3fd-0d4e33608d14
2026-01-08 12:34:39 +00:00
7a8f795dce i18n - docs translations (#17014)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 13:32:14 +01:00
b27f2ca146 fix(graph): fix toggle click and multiple dropdown issues (#16874)
Fixes #16843

## Summary

This PR fixes two bugs in graph settings:

1. **Multiple dropdowns opening simultaneously** 
2. **Toggle switches not clickable**

---

## Fix 1: Multiple dropdowns

**File:**
[ChartSettingItem.tsx](https://github.com/twentyhq/twenty/blob/main/packages/twenty-front/src/modules/command-menu/pages/page-layout/components/chart-settings/ChartSettingItem.tsx)

Added `closeAnyOpenDropdown()` before opening a new dropdown. This
follows the existing pattern used in:
-
[useCommandMenu.ts](https://github.com/twentyhq/twenty/blob/main/packages/twenty-front/src/modules/command-menu/hooks/useCommandMenu.ts)
-
[RecordBoardDragSelect.tsx](https://github.com/twentyhq/twenty/blob/main/packages/twenty-front/src/modules/object-record/record-board/components/RecordBoardDragSelect.tsx)
-
[useRecordGroupReorderConfirmationModal.ts](https://github.com/twentyhq/twenty/blob/main/packages/twenty-front/src/modules/object-record/record-group/hooks/useRecordGroupReorderConfirmationModal.ts)

---

## Fix 2: Toggle switches not clickable

**File:**
[MenuItemToggle.tsx](https://github.com/twentyhq/twenty/blob/main/packages/twenty-ui/src/navigation/menu/menu-item/components/MenuItemToggle.tsx)
(twenty-ui)

### Investigation

I traced the toggle click flow and compared working vs non-working
usages:
- 
[SettingsRolesList.tsx](https://github.com/twentyhq/twenty/blob/main/packages/twenty-front/src/modules/settings/roles/components/SettingsRolesList.tsx)
- toggles work (MenuItemToggle directly in Dropdown)
- 
[ObjectOptionsDropdownRecordGroupsContent.tsx](https://github.com/twentyhq/twenty/blob/main/packages/twenty-front/src/modules/object-record/object-options-dropdown/components/ObjectOptionsDropdownRecordGroupsContent.tsx)
- toggles work (MenuItemToggle in SelectableListItem)
- 
[ChartSettingItem.tsx](https://github.com/twentyhq/twenty/blob/main/packages/twenty-front/src/modules/command-menu/pages/page-layout/components/chart-settings/ChartSettingItem.tsx)
- toggles don't work (CommandMenuItemToggle in SelectableListItem)

The component structure and props were identical, so I examined the HTML
output.

### Root Cause

Found **nested `<label>` elements**:

```html
<!-- Before (problematic) -->
<label htmlFor="id123">           <!-- MenuItemToggle's outer label -->
  <div>...content...</div>
  <label>                         <!-- Toggle's internal label -->
    <input id="id123" type="checkbox">
  </label>
</label>
```

While `htmlFor` theoretically links to the checkbox, nested labels are
**invalid HTML** and can cause click propagation issues in certain
browser contexts (particularly when combined with React event handling
and `SelectableList` keyboard navigation).

### Solution
Changed `StyledToggleContainer` from `label` to `div`:

```diff
- const StyledToggleContainer = styled.label`
+ const StyledToggleContainer = styled.div`
```

The
[Toggle](https://github.com/twentyhq/twenty/blob/main/packages/twenty-ui/src/input/components/Toggle.tsx)
component already handles clicks via its internal label wrapper, so the
outer label was redundant.

Also removed unused `useId`, `htmlFor`, and `id` props that were only
needed for the label association.


## Testing

-  TypeScript checks pass on `twenty-ui`
-  TypeScript checks pass on `twenty-front`
- No breaking changes to
[MenuItemToggle](https://github.com/twentyhq/twenty/blob/main/packages/twenty-ui/src/navigation/menu/menu-item/components/MenuItemToggle.tsx)
API
- All existing usages of
[MenuItemToggle](https://github.com/twentyhq/twenty/blob/main/packages/twenty-ui/src/navigation/menu/menu-item/components/MenuItemToggle.tsx)
should continue working (and potentially work better)

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2026-01-08 12:05:32 +00:00
Aman RajandGitHub 7ce76277d2 Fix the crash of the app page when object view is configured to open only on record page. (#16977)
### Problem:
If the command menu page is kept opened while navigating to record show
page then the app crashes.

### Root cause

When navigatiing to a record show page while the command menu page is
kept opened, it tries to open the record show page with command menu
open, as its state were set to true , before navigating to a new page
along with the instance id of previous context which are used in the
current context while rendering the page. Hence, leading to an error
page.

### Changes

while navigation to a record show page the command menu open state is
set to false. This is to handle the navigation gracefully

Fixes: #16577
2026-01-08 11:51:07 +00:00
5864c69e45 i18n - translations (#17012)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 12:20:58 +01:00
e9b7ad21d2 Fix view picker small bugs (#16987)
This PR solves small bugs around the view picker.

- Couldn’t obtain optimistic update after a re-order of a view by drag
and drop, we needed to refresh the page
- Picking a new icon wouldn’t trigger optimistic update (same problem)
- Picking a new icon would change the view (difficult to understand
behavior)
- Picking a new icon would trigger left drawer collapse (z-index
problem)

Since core views are not being handled by object metadata items anymore,
and that all view logic is plugged on coreViewsState, this PR
implemented optimistic effect by upserting into this state.

Fixes https://github.com/twentyhq/twenty/issues/15422
Fixes https://github.com/twentyhq/twenty/issues/16986

# Before


https://github.com/user-attachments/assets/64099c21-df9f-4772-ab0d-9ea449aed761

# After


https://github.com/user-attachments/assets/f4e844b3-6530-4178-abdb-b7a10d2327b8

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2026-01-08 12:05:45 +01:00
Thomas TrompetteandGitHub 71fd05315c [IF/ELSE] Capitalize branch titles + remove ending separator (#17009)
Before : if - else if not capitalized, ending separator)
<img width="496" height="451" alt="Capture d’écran 2026-01-08 à 11 17
29"
src="https://github.com/user-attachments/assets/621e92f3-02ed-4e71-9893-576543922871"
/>

After
<img width="496" height="431" alt="Capture d’écran 2026-01-08 à 11 17
14"
src="https://github.com/user-attachments/assets/549c146c-00b0-4162-b395-ceb05baf34b1"
/>
2026-01-08 10:28:15 +00:00
0d9245b684 i18n - docs translations (#17008)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 11:26:54 +01:00
3e08f295d5 i18n - translations (#17007)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 10:50:39 +01:00
c82ac19657 i18n - translations (#17005)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 10:39:04 +01:00
WeikoandGitHub 66b2882ac4 BREAKING CHANGE: Removing remote integration feature (#17001)
## Context
The feature has not been maintained for more than a year and was never
officially launched.
This PR removes its code due to the upcoming refactoring of the
sync-metadata that will break its logic if not handled properly and it
would be too costly for the time being.

TODO:
- remove isRemote from object/field metadata
2026-01-08 09:14:51 +00:00
Raphaël BosiandGitHub 2e0eeda52e [DASHBOARDS] Fix dashboard duplication createdBy (#16999)
Fixes https://github.com/twentyhq/core-team-issues/issues/2032

## Before


https://github.com/user-attachments/assets/5804d3e7-1c03-4eb9-9203-64656438f5d1


## After


https://github.com/user-attachments/assets/9f96458c-d2a5-481a-b6b2-4d88f0daa98a
2026-01-08 09:13:43 +00:00
nitinandGitHub d653b0a168 Change bar chart tooltips interaction from bar to slice (#16938)
https://github.com/user-attachments/assets/90baca7e-2c32-448d-a458-e95ced00fdf4


https://github.com/user-attachments/assets/53dd5f8b-1c22-4600-b582-46ba594b966a




https://github.com/user-attachments/assets/0b0b15c1-3ff8-4059-bc10-969d49852545
2026-01-08 09:06:44 +00:00
e0107f67fd i18n - docs translations (#17004)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 09:57:58 +01:00
bb9f243fd0 i18n - docs translations (#17002)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-08 09:03:50 +01:00
0e49b67b7d i18n - docs translations (#17000)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-07 19:22:56 +01:00
EtienneandGitHub 615ef1abdc Fix kanban view when grouping select field has null value (#16998) 2026-01-07 17:55:54 +00:00
1f0fac195c i18n - docs translations (#16993)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-07 18:54:45 +01:00
Raphaël BosiandGitHub 7af98a9c15 Update updatedat field on dashboards after edition (#16964)
Closes https://github.com/twentyhq/core-team-issues/issues/1896
2026-01-07 17:14:24 +00:00
nitinandGitHub a19ed92429 fix: composite field matching in relation field orderBy with groupBy (#16992)
- Fix groupBy field matching for composite fields nested within relation
fields
- Add `nestedSubFieldName` comparison when the nested field is a
composite type (CURRENCY, FULL_NAME, ADDRESS, etc.)
2026-01-07 16:13:08 +00:00
e83e616fde fix: qs's arrayLimit bypass in its bracket notation allows DoS via memory exhaustion (#16886)
Resolves [Dependabot Alert
354](https://github.com/twentyhq/twenty/security/dependabot/354) and
[Dependabot Alert
355](https://github.com/twentyhq/twenty/security/dependabot/355).

Upgraded express by one minor version. Removed redundant type definition
in root `package.json` since we already have it in twenty-server's
`package.json`.

Upgraded body-parser patch version in serverless package.json.

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2026-01-07 15:58:12 +00:00
Thomas TrompetteandGitHub 6410157c5c Provide executed step output instead of result (#16991)
For huge workflows, after 20 steps, we stop the job and re-trigger a new
one.
But some of those workflows actually never stop.
See https://github.com/twentyhq/private-issues/issues/401 

Here is a first issue. We resuming the workflow, we were providing the
result instead of the output
2026-01-07 15:50:14 +00:00
Charles BochetandGitHub 9acf6ce1ad Add otel collector to reserved subdomains (#16988)
Ordered the RESERVED_SUBDOMAINS list by alphabetical order and added
'otel-collector'
2026-01-07 15:11:34 +00:00
370609a2e2 i18n - translations (#16989)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-07 16:21:49 +01:00
Raphaël BosiandGitHub 4faed25624 [PAGE LAYOUTS] Add widgets validation (#16635)
- Add widget validation
- Remove 'None' option for primary axis group by
- Fix error message parsing by passing the operation type in
`useMetadataErrorHandler`
2026-01-07 15:00:13 +00:00
701a713042 Updated the user guide with new article + updated old content (#16955)
- more details on rate at which messages are imported from Gmail
- Settings -> Release deprecated to Settings -> Updates => this leads to
updating the file title, file name and the navigation files
- Support & Documentation accessible via Settings and no longer the nav
bar
- updated features out of the lab
- no more integration page
- added a new article with step by step on how to notify a teammate of a
note to review

docs.json is updated only for the English part

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-07 14:17:13 +00:00
EtienneandGitHub 81afc8b9ca Fix memory crash when creating record in table view (#16984)
**Bug Fixed**
Creating a new record in the People table view caused a browser memory
crash ("Paused before potential out of memory crash").
**Root Cause**
In useResetVirtualizationBecauseDataChanged.ts, when creating a record,
a loop iterated from 0 to totalNumberOfRecordsToVirtualize (the total
database count).
**Fix Applied**
Changed the loop to only iterate through indices from actually loaded
pages

Fixes https://github.com/twentyhq/twenty/issues/16980
2026-01-07 14:06:32 +00:00
Rajdeep DasandGitHub a4daead678 Fix view field updates not persisting (#16672)
Fixes an issue where column width changes and other view field
modifications were not persisted, and a toast error was shown.

**Root Causes:**
1. Frontend was using client-generated IDs instead of database IDs for
updates
2. Backend cache was stale, causing `View field to update not found`
error

**Changes:**
- Use the existing database ID when updating view fields
- Exclude client-generated IDs when creating new view fields  
- Invalidate flat entity maps cache before/after view field operations
- Refresh both view and view field caches to prevent validation errors

Fixes #16417 
Closes #16381
2026-01-07 13:56:43 +00:00
Paul RastoinandGitHub 4ea4572924 Workspace creation prefill fix (#16983)
# Introduction
Fixing prefill in v2 workspace creation code flow
2026-01-07 13:51:21 +00:00
Abdul RahmanandGitHub 10de7acef3 If else node tests (#16916) 2026-01-07 10:37:37 +00:00
nitinandGitHub e6b5ae825c fix purple color palette (#16972)
before - 

<img width="490" height="181" alt="CleanShot 2026-01-06 at 23 20 50"
src="https://github.com/user-attachments/assets/939897c1-3a8d-4a38-a586-98667e69f011"
/>

now - 

<img width="494" height="170" alt="CleanShot 2026-01-06 at 23 20 03"
src="https://github.com/user-attachments/assets/634676c4-ea28-4ead-b3da-49ca75b57bd1"
/>
2026-01-07 09:30:41 +00:00
e4f8d804d5 fix(16819): Add NoteDeleteOnePostQueryHook for soft removing note targets (#16826)
Fixes [#16819](https://github.com/twentyhq/twenty/issues/16819)

Added a post-query hook (NoteDeleteOnePostQueryHook) that automatically
soft-deletes all associated noteTarget records when a note is deleted.

## Key changes:

Created `note-delete-one.post-query.hook.ts`
Uses `GlobalWorkspaceOrmManager` to access workspace entities correctly
Executes in the proper workspace context to ensure data isolation
Soft-deletes noteTarget records to maintain referential consistency

## Testing
1. Company notes
Create a Company
Create and attach a Note to the Company
Navigate to Company → Notes page (should display the note)
Delete the Note
Navigate to Company → Notes page (should no longer crash)
Restore the Note (should appear again)
Delete and destroy the Note permanently
Navigate to Company → Notes page (should still work, just empty)

2. Opportunity notes
Create an Opportunity
Create and attach a Note to the Opportunity
Navigate to Opportunity → Notes page (should display the note)
Delete the Note
Navigate to Opportunity → Notes page (should no longer crash)
Restore the Note (should appear again)
Delete and destroy the Note permanently
Navigate to Opportunity → Notes page (should still work, just empty)

### Expected behavior:

Company Notes page remains functional at all stages
No console errors
Deleted notes properly excluded from the view
Other notes on the same Company remain accessible
Additional Notes
This fix ensures data consistency by maintaining the relationship
between notes and their targets throughout the deletion lifecycle.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2026-01-07 08:30:08 +00:00
Félix MalfaitandGitHub 5f4b6e7ea4 Set default SMTP value to true (#16967)
As per title. Will make it easier for self-hosters. @Weiko fyi
2026-01-06 18:25:33 +00:00
a46619ec55 fix: enable save button when changing currency default value (#16864)
Closes #16792

## Problem

When editing a currency field’s default value (for example, changing
from **USD** to **UYU**), the **Save** button remained disabled.
However, if the format setting was changed first (**short → full →
short**), the Save button would then work correctly for currency
changes.

## Root Cause

The form was using **React Hook Form’s `values` mode**, which did not
properly track dirty state for the `defaultValue` and `settings` fields.

## Solution

Switched to the **`defaultValues` + `reset()`** pattern:

- Initialize the form with `defaultValues` (using placeholder values)
- Call `reset()` when `fieldMetadataItem` loads

This correctly tracks dirty state by comparing against the most recent
`reset` values.

## Note

A similar pattern is used in:
- `useWebhookForm`
- `useImapSmtpCaldavConnectionForm`

Those hooks call `reset()` via query callbacks. In this case, `reset()`
is called inside a `useEffect` because the data comes from synchronous
Recoil state rather than an async query.

Found two solutions to the problem, created commits for both. I feel the
useEffect pattern makes more sense here since it's cleaner in terms of
code.

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2026-01-06 18:02:43 +00:00
neo773andGitHub 971ddc0bb4 fix calendar save events transaction (#16763) 2026-01-06 17:56:03 +00:00
MarieandGitHub ceba0972cd Remove tests run on push on main (#16971)
Since tests are now run in the pre-merge queue with the latest main
version, they need not to be run again when merged into main, it would
be the exact same thing
2026-01-06 17:53:08 +00:00
Charles BochetandGitHub d53ec8f3c4 fix e2e tests (#16970)
As per title!
2026-01-06 18:52:15 +01:00
Thomas TrompetteandGitHub 6043edd53f Add metrics for completed and failed jobs (#16969)
Add a counter for completed and failed jobs
2026-01-06 18:51:54 +01:00
Thomas TrompetteandGitHub 2c5a7570fc Clean workflow run stoppage flag (#16950)
Flag has never been removed. Feature allows to stop a running workflow
run.
2026-01-06 17:05:46 +01:00
1113c20d89 Destroy core view (#16868)
Solution for #16526

---------

Co-authored-by: prastoin <paul@twenty.com>
2026-01-06 17:00:10 +01:00
MarieandGitHub 12189b378f Fix add related records to activity target after object renaming (#16953)
Fixes https://github.com/twentyhq/twenty/issues/16928 and
https://github.com/twentyhq/private-issues/issues/400

When an object is renamed, its corresponding relation field on
noteTarget and taskTarget are not renamed. This caused an issue as in
the FE, we used the related record object name to compute the field name
used in the payload.
This PR addresses it by, instead, finding the field name after
identifying it thanks to the object id.

To reproduce, you can rename an object then try to tie it to a note.
2026-01-06 16:26:26 +01:00
MarieandGitHub 13bc04047e [E2E tests] Fix run E2E tests before merge - attempt #3 (#16961) 2026-01-06 15:56:39 +01:00
Paul RastoinandGitHub 96f7f1cb0e Fix 1-15 upgrade commands bundle (#16957) 2026-01-06 14:13:40 +00:00
Thomas TrompetteandGitHub 48b0e2f11d Move run creation before opening side panel (#16956)
Fixes https://github.com/twentyhq/twenty/issues/16837

Current flow:
- create workflow run optimistically 
- open side panel => triggers query + event stream
- mutation that actually creates the run using the optimistic id

New flow
- create workflow run optimistically 
- mutation that actually creates the run using the optimistic id
- open side panel => triggers query + event stream
2026-01-06 14:06:07 +00:00
EtienneandGitHub 0c6f4021bf Fix - Update searchVector when labelIdentifier is updated (#16940)
Fixes https://github.com/twentyhq/twenty/issues/16891

In next PR, validation rules will be added in migration logic
2026-01-06 12:55:25 +00:00
Paul RastoinandGitHub bd9e5986d2 Clean orphan metadata (#16914)
# Introduction
Followup https://github.com/twentyhq/twenty/pull/16863

Important note: This is not an upgrade command and will have to be
manually run

In this pull request we're introducing a coding that will allow this
[migration](https://github.com/twentyhq/twenty/blob/clean-orphan-metadata/packages/twenty-server/src/database/typeorm/core/migrations/utils/1767002571103-addWorkspaceForeignKeys.util.ts#L3)
to pass, it enforces the `workspaceId` foreignKey on all metadata
entities. Allowing workspace deletion cascading of all its related
entities and avoiding orphan metadata entities to reoccur in the future

Also introduced a small migration that will set the workspaceId col type
to `uuid`, as it has been historically `varchar`
This migration is a requirement for the above command to work
successfully


## Note
Chunking by relations fields the orphan field deletion as would take way
too much time within a transac,

## Test
Tested on a prod extract locally ( both dry and not dry )
2026-01-06 13:36:53 +01:00
e51cf607c9 Fix if-else node drag-to-create (#16944)
Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2026-01-06 13:28:29 +01:00
EtienneandGitHub 3539f5cb7a Billing - Update alert when meter price is updated (#16952) 2026-01-06 12:25:28 +00:00
Thomas TrompetteandGitHub 35c7687ed8 Publish batch events for sse subscriptions (#16943)
- publish batch events to avoid multiple redis / graphql sse
publications
- add event to the endpoint output
2026-01-06 13:22:14 +01:00
f8ed339f24 i18n - translations (#16951)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-06 12:01:05 +01:00
c531cfe0a4 [DASHBOARDS] Manual and position-based sorting for chart widgets (#16794)
## Description

SELECT fields have a defined option order that users expect to see
reflected in charts.
This PR allows sorting by that position and also enables custom manual
ordering.

## Video QA

### Reordering on primary axis


https://github.com/user-attachments/assets/994f515e-19cb-4a5e-b745-e8c77e92ae0b


### Reordering on secondary axis


https://github.com/user-attachments/assets/444c16f2-1920-4dc4-8b42-312d520ab43b

Note: The colors in the graph will match the colors of the select
options, but this will be done in another PR

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Introduces new sort modes and UI for chart groupings, with full FE/BE
support and updated GraphQL schema.
> 
> - Extend `GraphOrderBy` with `FIELD_POSITION_ASC/DESC` and `MANUAL`;
add corresponding fields in configs: `primaryAxisManualSortOrder`,
`secondaryAxisManualSortOrder`, and `manualSortOrder` (pie)
> - New UI: dropdown options filtered by field type, icons, and a
draggable submenu (`ChartManualSortSubMenuContent`) to reorder select
options; integrates with widget edit flow
> - Sorting logic added/refactored: `sortChartData`,
`sortByManualOrder`, `sortBySelectOptionPosition`,
`sortLineChartSeries`, plus updates to bar/line/pie transformers to
honor new modes and manual orders
> - Default behaviors: select fields default to `FIELD_POSITION_ASC`;
query variable builders skip `orderBy` when using manual/position sorts
> - Update GraphQL generated types/fragments/queries and backend
DTOs/schemas to persist new fields; add tests for sorting utilities and
snapshots; add sorting icons in `twenty-ui`
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
78c9b56c0f. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2026-01-06 11:52:54 +01:00
Paul RastoinandGitHub 221a6262f0 Fix metadata relation field settings item type tag display (#16949)
# Introduction
followup https://github.com/twentyhq/twenty/pull/16880

Fixing the item tag type displayal of the relation field within an
object
Inferring the application id at field level instead of object level

## From
<img width="1162" height="1220" alt="image"
src="https://github.com/user-attachments/assets/28af2242-2786-4e17-b910-3fc26871bc04"
/>

## To
<img width="1162" height="1220" alt="image"
src="https://github.com/user-attachments/assets/63fb89a0-a853-4157-baa4-d0f758648c3e"
/>
2026-01-06 11:23:17 +01:00
32efaee1bf fix: Remove incorrect background logic from PageLayoutGridLayout (#16945)
Removes the background color logic that was incorrectly added to
PageLayoutGridLayout in PR #16870. Grid layouts are only used for
dashboards where widgets have their own background colors set in
WidgetCard.tsx, so the container background was causing visual
mismatches in padding/gap areas. The background logic remains correctly
applied in PageLayoutVerticalListViewer and PageLayoutVerticalListEditor
where widgets need to inherit the container background.

---------

Co-authored-by: Devessier <baptiste@devessier.fr>
2026-01-06 10:19:34 +00:00
de33d17809 Fix navigation memory after custom object rename (#16918)
This PR fixes an issue where exiting Settings after renaming a custom
object could redirect to a stale object URL and result in a `404`. When
a custom object name was updated, the memorized navigation URL was not
kept in sync, causing redirects to use the old object route.
The navigation state is now updated only when the memorized URL belongs
to the renamed object, ensuring redirects always point to the correct
route while preserving unrelated navigation context.

Fixes https://github.com/twentyhq/twenty/issues/11291

---------

Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2026-01-05 17:46:22 +00:00
e6908e4635 i18n - translations (#16942)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-05 18:21:22 +01:00
Thomas TrompetteandGitHub 7aa7292869 Add invalid step input error (#16941)
`INVALID_STEP_TYPE` is used even when the step type is not the error
cause.
Adding a new `INVALID_STEP_INPUT` exception code
2026-01-05 17:05:40 +00:00
18473e5c94 fix: use white background for widgets on mobile and in side panel (#16870)
Closes [2029](https://github.com/twentyhq/core-team-issues/issues/2029)

Widgets now use a white background on mobile and in the side panel,
while keeping gray in the side column. Background colors are set at the
parent container level (PageLayoutVerticalListViewer/Editor) so widgets
inherit the correct background, centralizing the background logic in the
container components.

Other variants (dashboard, record-page) specify their own background
color inside `WidgetCard.tsx` file, so we should not have any
regressions.

---------

Co-authored-by: Baptiste Devessier <baptiste@devessier.fr>
2026-01-05 17:39:50 +01:00
fd8b222b9b i18n - translations (#16939)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-05 17:01:42 +01:00
WeikoandGitHub e83b9c9eb6 Clarify non-implemented calendar layouts (#16937)
## Context
Some users are confused with the dropdown showing other calendar
layouts. We've decided to hide it for now since their implementation is
not planned yet.

Before
<img width="1292" height="845" alt="Screenshot 2026-01-05 at 15 06 36"
src="https://github.com/user-attachments/assets/e12e064a-1f58-454c-8933-b3ae2537378a"
/>

After
<img width="1301" height="839" alt="Screenshot 2026-01-05 at 15 00 15"
src="https://github.com/user-attachments/assets/f4a65fb1-ac2e-4068-b7da-1b7ef55b174c"
/>
2026-01-05 16:54:51 +01:00
martmullandGitHub 3b05375419 Fix authContext (#16936)
as title, add missing application from authContext build
2026-01-05 14:58:25 +01:00
MarieandGitHub 777ec99e67 [E2E tests] Fix run E2E tests before merge - attempt #2 (#16935)
Following [this PR](https://github.com/twentyhq/twenty/pull/16931), this
is another attempt to trigger E2E tests in merge queue.
2026-01-05 14:35:55 +01:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
dffe4c2152 build(deps): bump @ai-sdk/xai from 2.0.19 to 2.0.43 (#16927)
Bumps [@ai-sdk/xai](https://github.com/vercel/ai) from 2.0.19 to 2.0.43.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/vercel/ai/releases"><code>@​ai-sdk/xai</code>'s
releases</a>.</em></p>
<blockquote>
<h2><code>@​ai-sdk/xai</code><a
href="https://github.com/2"><code>@​2</code></a>.0.43</h2>
<h3>Patch Changes</h3>
<ul>
<li>4953414: fix: trigger new release for <code>@ai-v5</code>
dist-tag</li>
<li>Updated dependencies [4953414]
<ul>
<li><code>@​ai-sdk/openai-compatible</code><a
href="https://github.com/1"><code>@​1</code></a>.0.30</li>
<li><code>@​ai-sdk/provider</code><a
href="https://github.com/2"><code>@​2</code></a>.0.1</li>
<li><code>@​ai-sdk/provider-utils</code><a
href="https://github.com/3"><code>@​3</code></a>.0.20</li>
</ul>
</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/vercel/ai/commit/8792b307a75fef8850dd4f06883accca79f73ea9"><code>8792b30</code></a>
Version Packages (<a
href="https://redirect.github.com/vercel/ai/issues/11473">#11473</a>)</li>
<li><a
href="https://github.com/vercel/ai/commit/495341421eea27e82d06caaefa6aaa751dd753ec"><code>4953414</code></a>
docs: changeset</li>
<li><a
href="https://github.com/vercel/ai/commit/15e037c3fdf2a9f6120861a801d9e2c04d3d7f8b"><code>15e037c</code></a>
build: configure dist-tag for v5 maintenance releases</li>
<li><a
href="https://github.com/vercel/ai/commit/94bf6d8f05b73a59e25bb90dde5b1bffb55fc1ea"><code>94bf6d8</code></a>
Version Packages (<a
href="https://redirect.github.com/vercel/ai/issues/11419">#11419</a>)</li>
<li><a
href="https://github.com/vercel/ai/commit/4f0e5af98e704baaa91e86ca607552d341842fe9"><code>4f0e5af</code></a>
Backport: Fix bedrock ConverseStream undocumented
<code>/delta/stop_sequence</code> (<a
href="https://redirect.github.com/vercel/ai/issues/11">#11</a>...</li>
<li><a
href="https://github.com/vercel/ai/commit/ca0e6516ce63698d3df334e3ec5871893db3256b"><code>ca0e651</code></a>
Version Packages (<a
href="https://redirect.github.com/vercel/ai/issues/11332">#11332</a>)</li>
<li><a
href="https://github.com/vercel/ai/commit/e3de98182860ddab117f3a81ab186b7e3fb036e0"><code>e3de981</code></a>
Backport: feat (provider/gateway): add zero data retention provider
option (#...</li>
<li><a
href="https://github.com/vercel/ai/commit/34da517fe5b7bc15137575144dc4036a796074da"><code>34da517</code></a>
Version Packages (<a
href="https://redirect.github.com/vercel/ai/issues/11329">#11329</a>)</li>
<li><a
href="https://github.com/vercel/ai/commit/cbc2dba9f02bb5c23822a6be3576cea06243e2a8"><code>cbc2dba</code></a>
Backport: fix(provider/google): preserve nested empty object schemas and
desc...</li>
<li><a
href="https://github.com/vercel/ai/commit/2c285e3870dc7153f48b14eb0c33af7b3ebc186c"><code>2c285e3</code></a>
Version Packages (<a
href="https://redirect.github.com/vercel/ai/issues/11325">#11325</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/vercel/ai/compare/@ai-sdk/xai@2.0.19...@ai-sdk/xai@2.0.43">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@ai-sdk/xai&package-manager=npm_and_yarn&previous-version=2.0.19&new-version=2.0.43)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-05 13:19:55 +01:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>Abdullah
2b60e41374 build(deps-dev): bump @typescript-eslint/parser from 8.39.0 to 8.51.0 (#16926)
Bumps
[@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser)
from 8.39.0 to 8.51.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/typescript-eslint/typescript-eslint/releases"><code>@​typescript-eslint/parser</code>'s
releases</a>.</em></p>
<blockquote>
<h2>v8.51.0</h2>
<h2>8.51.0 (2025-12-29)</h2>
<h3>🚀 Features</h3>
<ul>
<li><strong>eslint-plugin:</strong> expose rule name via RuleModule
interface (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11719">#11719</a>)</li>
<li><strong>eslint-plugin:</strong> [no-useless-default-assignment] fix
some cases to optional syntax (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11871">#11871</a>)</li>
<li><strong>eslint-plugin:</strong> add namespace to plugin meta (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11885">#11885</a>)</li>
<li><strong>tsconfig-utils:</strong> more informative error on parsing
failures (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11888">#11888</a>)</li>
</ul>
<h3>🩹 Fixes</h3>
<ul>
<li><strong>eslint-plugin:</strong> fix crash and false positives in
<code>no-useless-default-assignment</code> (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11845">#11845</a>)</li>
<li><strong>eslint-plugin:</strong> remove fixable from
no-dynamic-delete rule (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11876">#11876</a>)</li>
<li><strong>eslint-plugin:</strong> bump ts-api-utils to 2.2.0 (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11881">#11881</a>)</li>
<li><strong>eslint-plugin:</strong> [prefer-optional-chain] handle
MemberExpression in final chain position (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11835">#11835</a>)</li>
</ul>
<h3>❤️ Thank You</h3>
<ul>
<li>Josh Goldberg </li>
<li>Kirk Waiblinger <a
href="https://github.com/kirkwaiblinger"><code>@​kirkwaiblinger</code></a></li>
<li>mdm317</li>
<li>Ulrich Stark</li>
<li>Yannick Decat <a
href="https://github.com/mho22"><code>@​mho22</code></a></li>
<li>Yukihiro Hasegawa <a
href="https://github.com/y-hsgw"><code>@​y-hsgw</code></a></li>
</ul>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>v8.50.1</h2>
<h2>8.50.1 (2025-12-22)</h2>
<h3>🩹 Fixes</h3>
<ul>
<li><strong>eslint-plugin:</strong> [method-signature-style] ignore
methods that return <code>this</code> (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11813">#11813</a>)</li>
<li><strong>eslint-plugin:</strong> [no-unnecessary-type-assertion]
correct handling of undefined vs. void (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11826">#11826</a>)</li>
</ul>
<h3>❤️ Thank You</h3>
<ul>
<li>Josh Goldberg </li>
<li>Tamashoo <a
href="https://github.com/Tamashoo"><code>@​Tamashoo</code></a></li>
</ul>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>v8.50.0</h2>
<h2>8.50.0 (2025-12-15)</h2>
<h3>🚀 Features</h3>
<ul>
<li><strong>eslint-plugin:</strong> [no-useless-default-assignment] add
rule (<a
href="https://redirect.github.com/typescript-eslint/typescript-eslint/pull/11720">#11720</a>)</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md"><code>@​typescript-eslint/parser</code>'s
changelog</a>.</em></p>
<blockquote>
<h2>8.51.0 (2025-12-29)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.50.1 (2025-12-22)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.50.0 (2025-12-15)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.49.0 (2025-12-08)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.48.1 (2025-12-02)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.48.0 (2025-11-24)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.47.0 (2025-11-17)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.46.4 (2025-11-10)</h2>
<p>This was a version bump only for parser to align it with other
projects, there were no code changes.</p>
<p>You can read about our <a
href="https://typescript-eslint.io/users/versioning">versioning
strategy</a> and <a
href="https://typescript-eslint.io/users/releases">releases</a> on our
website.</p>
<h2>8.46.3 (2025-11-03)</h2>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/e4c57f5996a9a3aed8a8c2b02712a9ce37db4928"><code>e4c57f5</code></a>
chore(release): publish 8.51.0</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/d520b88990e1b20674dcfa3db3b0461c1d6d9aa2"><code>d520b88</code></a>
chore(release): publish 8.50.1</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/c62e85874f0e482156a54b6744fe90a6f270012a"><code>c62e858</code></a>
chore(release): publish 8.50.0</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/864595a44b56beb9870bf0f41d59cf7f8f48276a"><code>864595a</code></a>
chore(release): publish 8.49.0</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/32b7e891bd60ae993e85018ceefa2a0c07590688"><code>32b7e89</code></a>
chore(deps): update dependency <code>@​vitest/eslint-plugin</code> to
v1.5.1 (<a
href="https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser/issues/11816">#11816</a>)</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/8fe34456f75c1d1e8a4dc518306d5ab93422efec"><code>8fe3445</code></a>
chore(release): publish 8.48.1</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/6fb1551634b2ff11718e579098f69e041a2ff92c"><code>6fb1551</code></a>
chore(release): publish 8.48.0</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/a4dc42ac541139f0da344550bce7accd8f3d366a"><code>a4dc42a</code></a>
chore: migrate to nx 22 (<a
href="https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser/issues/11780">#11780</a>)</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/28cf8032c2492bb3c55dd7dd145249f2246034ad"><code>28cf803</code></a>
chore(release): publish 8.47.0</li>
<li><a
href="https://github.com/typescript-eslint/typescript-eslint/commit/843f144797c0a94272cdb002c00c5639cf0797c6"><code>843f144</code></a>
chore(release): publish 8.46.4</li>
<li>Additional commits viewable in <a
href="https://github.com/typescript-eslint/typescript-eslint/commits/v8.51.0/packages/parser">compare
view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by [GitHub Actions](<a
href="https://www.npmjs.com/~GitHub">https://www.npmjs.com/~GitHub</a>
Actions), a new releaser for <code>@​typescript-eslint/parser</code>
since your current version.</p>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@typescript-eslint/parser&package-manager=npm_and_yarn&previous-version=8.39.0&new-version=8.51.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Abdullah <125115953+mabdullahabaid@users.noreply.github.com>
2026-01-05 17:19:08 +05:00
MarieandGitHub 890d258482 [E2E tests] Fix run E2E tests before merge (#16931)
I have set a
[rule](https://github.com/twentyhq/twenty/settings/rules/11470513) to
require `ci-e2e-status-check` to pass before merging. The problem is,
before merging, ci-e2e-tests are skipped (as we only want them to run
right before merging), so ci-e2e-status-check evaluates to `passed`,
which is re-used by the merge queue, even though we have a trigger for
e2e-tests in the merging queue phase.
The attempt to fix this is to give a different name to
`ci-e2e-status-check` in the merge queue phase (now being named
`ci-e2e-merge-queue-check`), and it is this status we should require in
the rule.
2026-01-05 13:11:59 +01:00
fe5c90ed42 feat: Add drag-to-create node with placeholder preview in workflow diagram (#16873)
Closes #14951

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2026-01-05 13:09:09 +01:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
cc7fd99879 build(deps): bump @nestjs/schedule from 6.0.1 to 6.1.0 (#16925)
Bumps [@nestjs/schedule](https://github.com/nestjs/schedule) from 6.0.1
to 6.1.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/nestjs/schedule/releases"><code>@​nestjs/schedule</code>'s
releases</a>.</em></p>
<blockquote>
<h2>Release 6.1.0</h2>
<h2>What's Changed</h2>
<ul>
<li>feat(module): add forRootAsync method to allow async module
registration by <a
href="https://github.com/daanhegger"><code>@​daanhegger</code></a> in <a
href="https://redirect.github.com/nestjs/schedule/pull/2142">nestjs/schedule#2142</a></li>
<li>fix(deps): update dependency cron to v4.3.5 by <a
href="https://github.com/renovate"><code>@​renovate</code></a>[bot] in
<a
href="https://redirect.github.com/nestjs/schedule/pull/2133">nestjs/schedule#2133</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a
href="https://github.com/daanhegger"><code>@​daanhegger</code></a> made
their first contribution in <a
href="https://redirect.github.com/nestjs/schedule/pull/2142">nestjs/schedule#2142</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/nestjs/schedule/compare/6.0.1...6.1.0">https://github.com/nestjs/schedule/compare/6.0.1...6.1.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/nestjs/schedule/commit/76b802bb5b2bf8c5325bbda8883039e7cd2fa9ab"><code>76b802b</code></a>
chore(): release v6.1.0</li>
<li><a
href="https://github.com/nestjs/schedule/commit/4973da5cd2a727e8bb8e55021742234f675c98bb"><code>4973da5</code></a>
Merge pull request <a
href="https://redirect.github.com/nestjs/schedule/issues/2124">#2124</a>
from nestjs/renovate/cimg-node-24.x</li>
<li><a
href="https://github.com/nestjs/schedule/commit/dca5b7c6b6f74e5e3299dae77253f0e34431ba09"><code>dca5b7c</code></a>
Merge pull request <a
href="https://redirect.github.com/nestjs/schedule/issues/2133">#2133</a>
from nestjs/renovate/cron-4.x</li>
<li><a
href="https://github.com/nestjs/schedule/commit/7c00b0b9ebb5e49c9707bd6c98bc428851a20c65"><code>7c00b0b</code></a>
Merge pull request <a
href="https://redirect.github.com/nestjs/schedule/issues/2142">#2142</a>
from daanhegger/add-async-for-root</li>
<li><a
href="https://github.com/nestjs/schedule/commit/8ee5a5a3e0908539604d2d02d8b9d8e5457f44df"><code>8ee5a5a</code></a>
chore(deps): update commitlint monorepo to v20.2.0 (<a
href="https://redirect.github.com/nestjs/schedule/issues/2151">#2151</a>)</li>
<li><a
href="https://github.com/nestjs/schedule/commit/b911f17b9ae5f95b3ef2567b3988e28471abc436"><code>b911f17</code></a>
fix(deps): update dependency cron to v4.3.5</li>
<li><a
href="https://github.com/nestjs/schedule/commit/56ed37295b97ce3bf75e64875d842d7f27cf306d"><code>56ed372</code></a>
chore(deps): update dependency prettier to v3.7.4 (<a
href="https://redirect.github.com/nestjs/schedule/issues/2150">#2150</a>)</li>
<li><a
href="https://github.com/nestjs/schedule/commit/52f5c45eb5d4e1dbfae656993fd6de96442e8f1a"><code>52f5c45</code></a>
chore(deps): update dependency typescript-eslint to v8.48.1 (<a
href="https://redirect.github.com/nestjs/schedule/issues/2149">#2149</a>)</li>
<li><a
href="https://github.com/nestjs/schedule/commit/7fa5d15c2ad6a60a593fb8e598275ff0575ad8b4"><code>7fa5d15</code></a>
chore(deps): update dependency ts-jest to v29.4.6 (<a
href="https://redirect.github.com/nestjs/schedule/issues/2148">#2148</a>)</li>
<li><a
href="https://github.com/nestjs/schedule/commit/056a618ea1aa165c1d9936f5eb7a01247aa11692"><code>056a618</code></a>
chore(deps): update dependency prettier to v3.7.3 (<a
href="https://redirect.github.com/nestjs/schedule/issues/2147">#2147</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/nestjs/schedule/compare/6.0.1...6.1.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@nestjs/schedule&package-manager=npm_and_yarn&previous-version=6.0.1&new-version=6.1.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-05 16:41:27 +05:00
nitinandGitHub 4b34add51c Fix command menu input click outside listener blocking other elements (#16934)
click outside listeners for `CommandMenuItemNumberInput` and
`CommandMenuItemTextInput` were always active, even when the input
wasn't focused. This blocked clicks on other elements like toggles in
chart settings.

fixed by only enabling click outside listener when input is actually
focused
2026-01-05 11:10:54 +00:00
0238bb3f45 fix: show pen button for field widgets by default on mobile (#16871)
Closes [2021](https://github.com/twentyhq/core-team-issues/issues/2021)

Field widgets now show the pen button by default on mobile devices.
Previously, the button was only visible on hover, which doesn't work on
touch devices. The button remains hidden on desktop until hover,
preserving the existing desktop behavior.

Co-authored-by: Baptiste Devessier <baptiste@devessier.fr>
2026-01-05 11:43:09 +01:00
EtienneandGitHub f069efe361 Fix - Enable access to all options (#16933)
Before

https://github.com/user-attachments/assets/52271c96-b732-474b-9dac-a724a4955737


After

https://github.com/user-attachments/assets/c50a9b1d-988a-448d-950c-0197e325d987

Needed to QA [this](https://github.com/twentyhq/twenty/pull/16803)
2026-01-05 11:41:17 +01:00
Baptiste DevessierandGitHub 30b3dd1d6f Fix Field widget glitches (#16866)
## LinkedIn + Boolean bugs


https://github.com/user-attachments/assets/6520ed94-5f60-404c-a43e-50b175510cab

## Hide Pen button for boolean fields (& rating)


https://github.com/user-attachments/assets/89a6ca35-8797-4621-adf4-59d2dc7d4625

Closes https://github.com/twentyhq/core-team-issues/issues/2024
2026-01-05 11:23:31 +01:00
32c0728301 i18n - translations (#16932)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-05 11:21:41 +01:00
Félix MalfaitandGitHub 0173e40a20 feat: Serverless Functions as AI Tools (#16919)
## Summary

This PR enables serverless functions to be exposed as AI tools, allowing
them to be used by AI agents.

### Changes

- Added new `SERVERLESS_FUNCTION` tool category
- Added `toolDescription`, `toolInputSchema`, and `toolOutputSchema`
fields to serverless functions
- Created database migration for the new schema columns
- Added tool index query and resolver for fetching available tools
- Added Settings AI page tabs (Skills, Tools, Settings) with new tools
table
- Added utility to convert tool schema to JSON schema format
- Updated frontend to display tools in the settings page

### Implementation Details

- Serverless functions can now define tool metadata (description,
input/output schemas)
- These functions are automatically registered in the tool registry
- The tool index endpoint allows querying available tools with their
schemas
- Settings page now has a dedicated Tools tab showing all available
tools
2026-01-05 11:13:06 +01:00
c0d71f7f96 i18n - translations (#16929)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-05 10:22:50 +01:00
Paul RastoinandGitHub a6415db775 Refactor workspace migration and validation error types and centralize runner optimistic rendering (#16920)
# Introduction

In this PR we're:
- Refactoring the workspace migration action type introducing grain over
metadata and operation type ( for example operation `create` and
metadata `field` )
- Thanks to above point we can now factorize the runner optimistic
rendering out of each runner actions-handler file using the existing
into the generic one ( -3200 lines of code here )
- Still thanks to action type refactor we're able to dynamically compose
the response error type only send data when there's here. No more static
counter and static summary error message. This way we won't have to re
run snapshot every time we add a new entity to the engine ( huge
snapshot diff here )

## Noticeable points:
- We introduce an index update action to avoid any complex typing for
not having one or a tuple of actions instead. Now the drop and insert
logic is directly inferred from the update action handler instead of
being two action ( delete index and create index )

## TODO
- [x] Define base actions types
- [x] Migrate all actions to action type and metadata name pattern (
base actions )
- [x] Refactor flat entity validation type to embed metadata name
- [x] Refactor optimistic rendering within runner
- [x] Refactor legacy cache invalidation switch
- [x] Refactor response error format ( dynamic counter again + no empty
entries )
- [x] Try factorizing and removing redundant nor unused type declaration
in metadata actions type intermediary files
- [x] Adapt front to new response error format

## Remarks
- ~~Should create an issue for generic replace flat entity in related
flat entity maps~~ overkill
- Should create an issue for oneToMany foreignKey being nullable not
always cascade delete optimistic rendering edge case to either docs or
fix it in delete flat entity and related entity ( re-code the pg
cascading behavior )
- We could also factorize the builder to only implement validators and
not the intermediary file
2026-01-05 10:17:16 +01:00
Paul RastoinandGitHub 9b38254256 Refactor runner dynamic cache invalidation (#16913)
# Introduction
closes https://github.com/twentyhq/core-team-issues/issues/1792
Refactoring the cache to invalidate to be more precise and prevent any
corrupted cache occurrences

## Next
The load dependency cache from the workspace migration, that's not
optimal it should be smart enough to infer it from the actions
themselves. For the moment their definition isn't granular enough and
inferring such info would be very dirty
2026-01-03 02:51:07 +01:00
Paul RastoinandGitHub 42c9ae1ebc Centralize metadata relations constant + simplification (#16901)
# Introduction
As we introduced a new grain on relation extraction thanks to low level
`SyncableEntity` and `WorkspaceRelatedEntity` we're able to strictly
typesafe extract metadata entity

The new constant centralizes both many to one and one to many constants
metadata entity constants in a more strictly typesafe way. Remains only
the flatEntityForeignKey aggregator which has to be chosen manually
across all available targeted flat entity ids properties
2026-01-02 16:49:06 +01:00
3cab1bf80b i18n - translations (#16909)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-02 15:36:03 +01:00
Félix MalfaitandGitHub 21ff42074d feat: implement skills system for AI agents (#16865)
## Summary
This PR introduces a Skills system for AI agents, inspired by the [Agent
Skills specification](https://agentskills.io/specification).

## Changes

### Backend
- **SkillEntity**: New database entity with migration for storing skills
- **V2 Sync Mechanism**: Implemented FlatSkill, builders, validators,
and action handlers following the v2 flat entity pattern
- **Standard Skills**: Pre-defined skills (workflow-building,
data-manipulation, dashboard-building, metadata-building, research,
code-interpreter, xlsx, pdf, docx, pptx)
- **GraphQL API**: CRUD operations for skills with proper guards and
permissions
- **Workspace Cache**: Integrated skills into the workspace cache system

### Frontend  
- **Skills Table**: Searchable table in AI settings showing all skills
- **Skill Form**: Create/edit page with Label (primary), Description,
and Content (markdown editor)
- **API Name**: Following existing patterns, name is derived from label
with advanced settings toggle for custom API names
- **Standard vs Custom**: Standard skills are read-only, custom skills
can be edited/deleted

## Key Design Decisions
- Skills are stored in the database (Salesforce-like approach) rather
than files
- Name is derived from Label by default (isLabelSyncedWithName pattern)
- Skills reference functions/files via @ mentions in markdown content
rather than explicit relations
- Standard skills are synced from code, custom skills are created via UI

## Screenshots
Skills table and form UI follow existing settings patterns.

## Testing
- [x] Lint passes
- [x] Typecheck passes
- [ ] CI tests
2026-01-02 14:22:01 +00:00
2a3fd788ae i18n - translations (#16908)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-02 14:24:15 +01:00
EtienneandGitHub 300738e8cb Fix database event emission (#16759)
Fixes https://github.com/twentyhq/private-issues/issues/395


When calling `removeUserFromWorkspaceAndPotentiallyDeleteWorkspace` from
`user.service`,
```
        await workspaceMemberRepository.delete({
          userId: userWorkspace.userId,
        });
```
related database event is not emitted.

Same issue with update has been fixed
[here](https://github.com/twentyhq/twenty/pull/13287/changes)

The database event is not emitted because `await
eventSelectQueryBuilder.getOne()` in `workspace-delete-query-builder`
returns `null`. This happens because the `selectQueryBuilder` has no
entity—the database request is sent and the raw result is not `null`,
but the entity is `null`, causing the final result to be null.

It can be fixed the same way update has been fixed, updating the
`workspace-entity-manager`
- Pros : consistant with update but we should not forget to fix
softDelete and restore
- Cons : `workspace-entity-manager` is a copy of typeORM logic +
permission injection. Should it be more ?
 
Alternatively (as featured in this PR), it can be fixed by updating
computeEventSelectQueryBuilder, inspired by TypeORM's logic in
typeorm/query-builder/QueryBuilder.js at line 67.
- Pros : it fit with typeORM logic + It fixes all repository operations
2026-01-02 14:23:47 +01:00
EtienneandGitHub ecd41fc9cb Reduce complexity on groupBy query (#16803)
fixes https://github.com/twentyhq/core-team-issues/issues/2009
2026-01-02 14:19:40 +01:00
Paul RastoinandGitHub 98a9ae2a0e Migrate view filter group to v2 (#16876)
## Introduction
On the side hanlded PR with a // agents on another repo
Made several iterations to fix behavior and direction
Find below auto-generated PR description

closes https://github.com/twentyhq/core-team-issues/issues/2037

Created generic tooling for entity circular dep checking, will be useful
for permissions validation too @Weiko


## Migrate `viewFilterGroup` entity to v2 flat architecture

### Summary
Migrates the `viewFilterGroup` entity from v1 to the v2 flat entity
architecture, following the established patterns for other v2 entities
like `viewFilter`, `view`, and `viewField`.

### Changes

**Types & Constants**
- Added `FlatViewFilterGroup` and `FlatViewFilterGroupMaps` types
- Added editable properties constant for `viewFilterGroup`
- Registered `viewFilterGroup` in `ALL_METADATA_NAME`,
`ALL_METADATA_RELATION_PROPERTIES`,
`ALL_METADATA_MANY_TO_ONE_RELATIONS`, and related constants

**Cache Service**
- Created `WorkspaceFlatViewFilterGroupMapCacheService` with proper
relation loading for `viewFilters` and `childViewFilterGroups`
- Updated `WorkspaceFlatViewMapCacheService` to load `viewFilterGroups`
relation

**Builder & Validator**
- Created `WorkspaceMigrationV2ViewFilterGroupActionsBuilderService`
- Created `FlatViewFilterGroupValidatorService` with creation, update,
and deletion validation
- Integrated validation into the orchestrator service (runs before
`viewFilter` validation)

**Action Handlers**
- Created create, update, and delete action handlers for
`viewFilterGroup`

**Service Migration**
- Rewrote `ViewFilterGroupService` to use v2 migration pattern with
`WorkspaceMigrationValidateBuildAndRunService`
- Created utility functions for transforming DTOs to flat entities

**Database Migration**
- Added migration to make `parentViewFilterGroupId` foreign key
deferrable (handles self-referential parent/child insertions)

**ViewFilter Integration**
- Added `viewFilterGroupId` validation in
`FlatViewFilterValidatorService`
- Updated `viewFilter` many-to-one relations to include
`viewFilterGroup`

**Tests**
- Added integration tests for successful creation, update, deletion, and
destruction
- Added failing test cases for non-existent entities and invalid
references
- Added failing test for `viewFilter` creation with non-existent
`viewFilterGroupId`

### Breaking Changes
None - existing API contracts are preserved.
2026-01-02 14:16:01 +01:00
0adbe439d5 i18n - translations (#16895)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-01 15:35:33 +01:00
29de8ffba6 i18n - translations (#16894)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-01-01 15:20:55 +01:00
Paul RastoinandGitHub 1d9eb07ee0 Relation field metadata strict validation (#16890)
# Introduction

Now validating relation related object and field foreignkey integrity
2026-01-01 15:09:48 +01:00
Abdul RahmanandGitHub dff5e3cd7b feat: Add If/Else node (#16833)
Closes [#1265](https://github.com/twentyhq/core-team-issues/issues/1265)
2026-01-01 14:05:56 +00:00
Félix MalfaitandGitHub 5d5fd5fca5 fix: cache storybook-static folder to prevent EEXIST errors in tests (#16892)
## Problem

The `front-sb-test` jobs were sometimes failing with:
```
Error: EEXIST: file already exists, mkdir './storybook-static/images/icons/android'
```

## Root Cause

1. `front-sb-build` builds storybook and saves NX cache (but NOT
`storybook-static/` folder)
2. `front-sb-test` restores NX cache - NX thinks build is done, but
`storybook-static/` doesn't exist
3. `storybook:serve:static` depends on `storybook:build`, so NX re-runs
the build
4. Race condition in Storybook's file copy causes EEXIST error

The `storybook-static` folder was **never** included in the cache paths
- I verified this by checking git history back to when the save-cache
action was created.

## Solution

Add `storybook-static` to the `additional-paths` for both save and
restore cache steps. This ensures the built storybook is properly cached
and restored, eliminating the need for a rebuild during tests.
2026-01-01 14:24:43 +01:00
1d124a7a77 Enabled RLS seed dev (#16884)
And remove IS_GLOBAL_WORKSPACE_DATASOURCE_ENABLED

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Removes deprecated feature flag and enables RLS predicates in dev**
> 
> - Deletes `IS_GLOBAL_WORKSPACE_DATASOURCE_ENABLED` from server enum
and frontend generated GraphQL types
> - Updates dev seeder to enable
`IS_ROW_LEVEL_PERMISSION_PREDICATES_ENABLED` instead of the removed flag
> - Adjusts tests and mocked `GlobalWorkspaceDataSource` defaults to
drop the removed flag
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
7f4d5a401a. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2026-01-01 13:55:46 +01:00
Félix MalfaitandGitHub b521f53d24 fix: add NODE_OPTIONS to storybook build to prevent OOM errors (#16889)
## Description

The CI was failing with 'JavaScript heap out of memory' errors during
storybook builds:

```
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
```

The build was consuming ~6.4GB of memory before crashing.

## Solution

This inlines `NODE_OPTIONS='--max-old-space-size=10240'` directly in the
storybook build command, following the same pattern used for other
memory-intensive builds in the codebase (e.g., `front-build` job in CI).

## Notes

- The `project.json` had an `env` option with `NODE_OPTIONS`, but it
used underscores (`max_old_space_size`) instead of hyphens
(`max-old-space-size`), and the `env` option may not be reliably passed
through the `nx:run-commands` executor to subprocesses.
- Inlining the env variable in the command is more reliable and matches
the pattern used elsewhere in the codebase.
2026-01-01 09:34:12 +01:00
BOHEUSandGitHub daca127aa6 Update Mailchimp synchronizer README (#16885)
Leftover nitpick from #16875
2025-12-31 22:49:37 +01:00
9a5c2e4cea i18n - translations (#16882)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-31 16:34:31 +01:00
BOHEUSandGitHub 54332746a5 Disabling data import to actor type fields (#16867)
Fix for #15314
2025-12-31 16:31:54 +01:00
23f6acb43c i18n - translations (#16881)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-31 16:21:00 +01:00
15b21570ae Row level permissions - POC 1 (#16599)
## Context
This PR adds the core structure for RLS implementation:
- RLS data model
- RLS service layer
- RLS WorkspaceMigration and Syncable Entity + cache + Validations
- RLS resolver layer
- ORM layer with RLS Predicate to ORM WHERE clause conversion with
workspaceMember record transposition

Tests are missing though

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Establishes core row-level permissions infrastructure and enforcement
across the stack.
> 
> - Backend: new `rowLevelPermissionPredicate` and
`rowLevelPermissionPredicateGroup` entities, TypeORM migration, feature
flag `IS_ROW_LEVEL_PERMISSION_PREDICATES_ENABLED`, flat-entity
maps/cache wiring, services and GraphQL resolvers for CRUD, and
inclusion of `workspaceMember` in auth context
> - ORM: applies row-level permission predicates to SELECT, DELETE, and
SOFT DELETE query builders; propagates context through
GlobalWorkspaceOrmManager/EntityManager
> - GraphQL: generated schema/types/queries/mutations for
creating/updating/deleting/fetching predicates and groups
> - Frontend: settings page adds a gated "Record-level" section
(placeholder) and metadata error handler labels for new entities
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
fe955cc458. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2025-12-31 16:15:17 +01:00
888a50c3be feat: batch updating (#16384)
#16383 

## Scope & Context
**Context**:
Added a **Bulk Update** feature to allow users to modify multiple
records simultaneously. This addresses the need for efficient data
management when dealing with large datasets.

**Scope**:
Enabling a "Bulk Update" flow that can be triggered for a filtered list
of records (e.g., current view). The feature guides the user through
selecting fields to modify, inputting new values, and executing the
update with real-time progress feedback.

## Current behavior
Currently, users must open and update records one by one.
To change the "Status" of 10 different opportunities, the user has to
navigate to each record detail page or use the inline cell editor 10
separate times. This is repetitive and time-consuming.

## Expected behavior
Users can trigger "Update Records" from the command menu or action bar.
1. **Choose Fields**: A step where users select which properties they
want to modify (e.g., check "Status" and "Assignee").
2. **Input Values**: Users provide the new values for the selected
fields.
3. **Execution**: Upon confirmation, the system updates all matching
records in the background.
4. **Feedback**: A progress indicator shows the number of processed
records, and a toast notification confirms completion.

*Key interactions:*
- Users can clear a field's value (set to null) by selecting the field
but leaving the input empty.
- The operation supports cancelling midway.


https://github.com/user-attachments/assets/c87366a3-246e-4615-9941-0bf63d70df86

## Technical inputs
**Core Functionality**:
- **Incremental Batch Processing**: Updates are performed in small
batches (using `useIncrementalUpdateManyRecords` to handle large
datasets without timing out or freezing the UI.
- **Global Feedback**: Integrated with the Snackbar system to notify
users of success or errors across the application.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Introduces localization keys and generated messages to support the new
bulk update workflow.
> 
> - New strings for command menu selection info: `{totalCount} selected`
> - Footer actions for bulk update: `Apply`, `Cancel` in
`UpdateMultipleRecordsFooter`
> - Toasts in `UpdateMultipleRecordsContainer`: `Successfully updated
{count} records`, `Failed to update records. Please try again.`
> - Action labels: `Update`, `Update records` in
`DefaultRecordActionsConfig` and command menu hook
> - Adds/updates entries across multiple locale `.po` files and
regenerates `af-ZA` messages
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
b1dce4c599. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Samuel Arbibe <samuelarbibe@Samuels-MacBook-Pro.local>
Co-authored-by: Félix Malfait <felix@twenty.com>
2025-12-31 15:02:27 +00:00
BOHEUSandGitHub 145790840d Update twenty-sdk to newest version in apps (#16875) 2025-12-31 15:41:42 +01:00
Paul RastoinandGitHub d6acef24d4 Fix timeline activities display (#16880)
Fixes https://github.com/twentyhq/twenty/issues/16809

# Introduction
Front was expected timeline activities field to be relation and not
morph relation

Also fixed the new v2 workspace creation that had a bug in the
createStandardRelation util ( it's not in production yet so everything's
fine )
2025-12-31 13:42:56 +00:00
Abdul RahmanandGitHub 229916def2 Fix: Change opportunity kanban view aggregate operation from MIN to SUM (#16879)
Closes #16806
2025-12-31 12:58:20 +00:00
Félix MalfaitandGitHub 73d2027391 fix: centralize lint:changed configuration in nx.json (#16877)
## Summary

The `lint:changed` command was not using the correct ESLint config for
`twenty-server`, causing it to use the root `eslint.config.mjs` instead
of the package-specific one. This PR fixes the issue and renames the
command to `lint:diff-with-main` for clarity.

## Problem

- `twenty-front` correctly specified `--config
packages/twenty-front/eslint.config.mjs`
- `twenty-server` just called `npx eslint` without specifying a config
- This meant `twenty-server` was missing important rules like:
  - `@typescript-eslint/no-explicit-any: 'error'`
  - `@stylistic/*` rules (linebreak-style, padding, etc.)
  - `import/order` with NestJS patterns
- Custom workspace rules (`@nx/workspace-inject-workspace-repository`,
etc.)

## Solution

1. **Renamed** `lint:changed` to `lint:diff-with-main` to be explicit
about what the command does
2. **Centralized** the configuration in `nx.json` targetDefaults:
- Uses `{projectRoot}` interpolation for paths (resolved by Nx at
runtime)
   - Each package automatically uses its own ESLint config
- Packages can override specific options (e.g., file extension pattern)
3. **Simplified** `project.json` files by inheriting from defaults

## Usage

```bash
# Lint only files changed vs main branch
npx nx lint:diff-with-main twenty-front
npx nx lint:diff-with-main twenty-server

# Auto-fix files changed vs main
npx nx lint:diff-with-main twenty-front --configuration=fix
```

## Changes

- **nx.json**: Added `lint:diff-with-main` target default with
configurable pattern
- **twenty-front/project.json**: Simplified to inherit from defaults
- **twenty-server/project.json**: Overrides pattern to include `.json`
files
- **CLAUDE.md** and **.cursor/rules**: Updated documentation
2025-12-31 13:47:20 +01:00
Paul RastoinandGitHub eeb91d9a96 [DO_NOT_RELEASE_MAIN_UNTIL_MERGED] Prevent migration failure due to workspace orphan metadata rows (#16863)
# Introduction
The `AddWorkspaceForeignKeys1767002571103` migration would fail when
released in production right now, as `foreignKey` be applicable as
there's a lof of orphan entries in database

As a workaround in order not to block any patch release we're
fallbacking the migration using save point and an upgrade command that
will attempt to apply the `foreignKey` on every workspace upgrade until
it succeed

We should keep in mind that any new fresh self installation will have
the foreignKey double checked that it would not implies regression on
workspace deletion using the integration tests

## Cleaning upgrade command
We won't implement the cleaning command in this PR yet either will I as
discussed with @Weiko someone else might be taking the subject starting
next week

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Strengthens workspace data integrity and makes the FK migration
resilient.
> 
> - Adds `upgrade:1-16:add-workspace-foreign-keys-migration` command to
apply `workspaceId` FKs once per run; wires into
`V1_16_UpgradeVersionCommandModule` and 1.16 upgrade sequence
> - Refactors migration `1767002571103` to use
`addWorkspaceForeignKeysQueries` util and wrap in a savepoint,
swallowing errors to avoid blocking releases
> - Extracts FK DDL into
`utils/1767002571103-addWorkspaceForeignKeys.util` for reuse by command
and migration
> - Removes duplicate `workspaceId` columns from entities (e.g.,
`cronTrigger`, `databaseEventTrigger`, `indexMetadata`,
`objectMetadata`, `roleTarget`, `role`, `serverlessFunction`) relying on
`SyncableEntity`; keeps indexes/relations
> - Marks legacy delete paths as deprecated; temporarily extends
`WorkspaceManagerService.delete` to also delete `serverlessFunction` by
`workspaceId`
> - Updates wiring to inject `ServerlessFunctionEntity` repository in
`workspace-manager` module/service and corresponding unit test
> - Extends integration tests and adds GraphQL helpers to create
serverless functions and triggers; verifies cascade deletion of related
metadata on workspace removal
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
6805bf5d1b32828b4bb1e9f130bfe6e478f66aee. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2025-12-31 11:52:21 +00:00
Félix MalfaitandGitHub f8fa709abf refactor: Migrate CRUD services to use Common API (#16869)
This PR migrates the workflow CRUD services to use the Common API
(CommonQueryRunners) instead of directly accessing TwentyORM.

## Changes

- Created CommonApiContextBuilderService to build context for Common API
- Migrated CreateRecordService to use CommonCreateOneQueryRunnerService
- Migrated UpdateRecordService to use CommonUpdateOneQueryRunnerService
- Migrated DeleteRecordService to use CommonDeleteOneQueryRunnerService
- Migrated FindRecordsService to use CommonFindManyQueryRunnerService
- Migrated UpsertRecordService to use Common API with upsert flag
- Removed unused get-selected-columns-from-restricted-fields.util.ts
- Updated module dependencies

## Benefits

- Consistent permission checking via Common API
- Query hooks (before/after execution)
- Automatic input transformation
- Same behavior as REST/GraphQL APIs
- Reduced code duplication
2025-12-31 10:24:50 +01:00
Félix MalfaitandGitHub 009e7e05f2 feat(workflow): use authContext in CRUD services for Common API migration (#16857)
## Summary

This PR migrates workflow CRUD operations to properly use the Common API
layer's authentication context, addressing the issues from the reverted
PR #15875.

The original PR was reverted because the Common API required passing
either a User or an API Key for authentication, which was problematic
for workflows. Since then, the "Application" concept was introduced in
the Common API layer, allowing for token injection in serverless
functions.

This PR leverages the "Twenty Standard Application" concept for
non-manual workflow triggers, providing a clean authentication path
without the issues of user impersonation.

## Changes

### Core Infrastructure
- **RecordCrudExecutionContext**: Replace `workspaceId` with full
`authContext`
- **WorkflowExecutionContext**: Add `authContext` field to carry
authentication info
- **ToolGeneratorContext/ToolSpecification**: Add optional `authContext`
support for tool generation

### Authentication Flow
- **WorkflowExecutionContextService**: Build appropriate auth context
based on trigger type:
- **Manual triggers**: Use user's workspace auth context with their role
permissions
- **Non-manual triggers**: Use Twenty Standard Application auth context
(bypasses permission checks or uses default serverless function role)
- **ApplicationService**: Add `findTwentyStandardApplicationOrThrow`
method to retrieve the system application
- **UserWorkspaceService**: Make relations configurable in
`getUserWorkspaceForUserOrThrow` to load only what's needed

### CRUD Services Migration
All 5 record CRUD services now receive `authContext` instead of
`workspaceId`:
- `CreateRecordService`
- `UpdateRecordService`
- `DeleteRecordService`
- `FindRecordsService`
- `UpsertRecordService`

### Workflow Actions
All record CRUD workflow actions pass `executionContext.authContext` to
the services:
- `CreateRecordWorkflowAction`
- `UpdateRecordWorkflowAction`
- `DeleteRecordWorkflowAction`
- `FindRecordsWorkflowAction`
- `UpsertRecordWorkflowAction`

### AI Agent Integration
- AI agent workflow action passes auth context to agent executor
- Tool provider and MCP protocol service support auth context
propagation

## Benefits
-  Proper authentication for workflow CRUD operations via Common API
-  Non-manual triggers use system application context (no user
impersonation issues)
-  Manual triggers preserve user permissions correctly
-  Foundation for better permission handling in automated workflows
-  Cleaner separation between user-initiated and system-initiated
operations

## Related
- Reverted PR: #15875
2025-12-30 21:36:15 +01:00
Abdullah.andGitHub 62e496f65d Do not display border bottom for last widget of tab (#16856)
Closes [2030](https://github.com/twentyhq/core-team-issues/issues/2030).

Determines if a widget is the last visible widget in its parent tab. The
hook:
- Finds the tab containing the widget
- Filters widgets based on visibility rules (respects conditionalDisplay
and edit mode)
- Returns true if the current widget is the last in the filtered list
- Updated `WidgetCard`: Added isLastWidget prop to conditionally apply
border-bottom for the side-column variant
- Updated `WidgetRenderer`: Integrates the hook and passes isLastWidget
to WidgetCard
2025-12-31 01:28:59 +05:00
656a32be73 fix(twenty-front): properly manage focus stack in useInlineCell hook (#16309)
The useInlineCell hook was only managing the dropdown focus state
(activeDropdownFocusIdState/previousDropdownFocusIdState) but not the
focus stack (focusStackState). Since the hotkey system checks
currentFocusIdSelector which reads from focusStackState, closing an
inline cell in the side panel would leave the focus stack in an
incorrect state, causing hotkeys to not work properly.

This fix adds proper focus stack management:
- openInlineCell: pushes the inline cell to the focus stack
- closeInlineCell: removes the inline cell from the focus stack

Fixes #16224

### Tests Added
- Added unit tests for
[useInlineCell](cci:1://file:///Users/apple/WebstormProjects/twenty/packages/twenty-front/src/modules/object-record/record-inline-cell/hooks/useInlineCell.ts:15:0-83:2)
hook to verify focus stack management
- Tests cover: opening inline cell, closing inline cell, and full
open/close cycles
- Tests ensure `focusStackState` and `activeDropdownFocusIdState` are
properly synchronized

---------

Co-authored-by: Joker <apple@Apples-MacBook-Pro.local>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-12-30 19:57:59 +00:00
Félix MalfaitandGitHub fb41b116a4 Add Quick Lead workflow integration tests (#16862)
## Description

This PR adds integration tests for the Quick Lead workflow, including a
complete end-to-end test with full workflow execution.

### Key Changes

1. **Enabled SyncDriver for integration tests** - Jobs are now processed
synchronously in tests
   - Modified `create-app.ts` to use `SyncDriver` instead of `BullMQ`
- Added `MessageQueueExplorer` to discover and register workflow job
handlers
   - This enables complete workflow execution in integration tests

2. **Added integration tests for Quick Lead workflow**:
   - Verify workflow exists and is active
- Verify workflow version has correct structure (MANUAL trigger, FORM
step, CREATE_RECORD steps)
- Test workflow triggering creates workflow run with correct initial
state
   - Test stop workflow run on a running workflow
- **Full end-to-end test**: trigger → submit form → verify Company and
Person records created

### Test Coverage

The complete end-to-end test verifies:
- Workflow triggers and is in RUNNING status (waiting on FORM step)
- Form submission with test data succeeds
- Workflow completes successfully with all steps in SUCCESS status
- Company record is created with correct name and domain
- Person record is created with correct name and email
- Records are properly cleaned up after test

### How to Run Tests

```bash
npx nx run twenty-server:test:integration -- --testPathPattern="quick-lead-workflow"
```

Or with database reset:

```bash
npx nx run twenty-server:test:integration:with-db-reset -- --testPathPattern="quick-lead-workflow"
```
2025-12-30 18:02:04 +01:00
a2872b02ed Deleted at improvement (#16732)
Disable Deactivate option for all standard fields

#16706 

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Prevents deactivation UI for standard system fields on the field edit
page.
> 
> - Introduces `canFieldBeDeactivated` to flag standard fields
(`createdAt`, `createdBy`, `deletedAt`, `updatedAt`)
> - Hides the "Danger zone" (deactivate/activate/delete controls) when
`!isLabelIdentifier && !readonly && !canFieldBeDeactivated`
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
b309815700. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-12-30 16:52:17 +00:00
61addf8b62 fix(email threads): linkify Email body so that URL links are properly formatted (#16415)
Closes #16396

Added [linkify-react](https://www.npmjs.com/package/linkify-react) and
[linkifyjs](https://www.npmjs.com/package/linkifyjs?activeTab=versions)
to dependancies.
Both are widely used libraries with millions of weekly downloads. 
Both of them have 0 dependancies on other packages, so should be safe to
use.

### Before
URLs were shown as plain text

<img width="395" height="699" alt="Screenshot 2025-12-09 at 12 25 03 PM"
src="https://github.com/user-attachments/assets/772e6d03-8c48-45a1-985c-f775bbd3465c"
/>


### After
URLs are shown as link and are clickable now.

<img width="367" height="641" alt="Screenshot 2025-12-09 at 2 50 29 PM"
src="https://github.com/user-attachments/assets/d15bf23a-7cae-4cd4-b9da-e99706c7db38"
/>

<img width="376" height="656" alt="Screenshot 2025-12-09 at 2 50 46 PM"
src="https://github.com/user-attachments/assets/ba112a65-7550-47e3-b42f-83b94c08bfa6"
/>

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-12-30 16:49:31 +00:00
MarieandGitHub 64d75d0b79 Fix E2E tests + Skip chromatic (#16838)
- Always skip chromatic job (we dont check the outcome)
- Fix workflow creation test
- Run E2E tests before merge (to enable through repo rulesets)
2025-12-30 15:57:38 +00:00
Paul RastoinandGitHub 1128331cc1 Fix field item type tag (#16860)
# Introduction
This has been fixed on main already 1 hour ago, this PR now only passes
the field application id instead of the object applicationId that could
be different for example when creating a custom field on a standard
object

For the moment not introducing any logic around application integrity
directly and still relying on the isCustom and standardId definition
This will have to be refactored once we deprecate the standardId
2025-12-30 15:02:07 +00:00
Baptiste DevessierandGitHub aac70c679f Field widget fix dropdowns (#16855)
## Before


https://github.com/user-attachments/assets/a78f6561-a519-455e-a838-c4e138fb336f

## After


https://github.com/user-attachments/assets/ec704406-b16b-491a-8a88-8aa6fe25254b

Closes https://github.com/twentyhq/core-team-issues/issues/2023
2025-12-30 14:43:58 +00:00
WeikoandGitHub ab95437065 Create query runner context from request context instead of schema builder internal context (#16858)
## Context
This PR refactors how authentication context is handled in the GraphQL
resolver layer. Previously, the auth context was baked into the schema
builder context at schema creation time. Now, the auth context is
extracted from the request at query execution time, enabling better
schema caching.

## Implementation
- Removed user-specific data from schema cache key: The schema cache key
no longer includes userId and apiKeyId, allowing the same schema to be
shared across all users in a workspace
- Cache key simplified from
${workspaceId}-${userId}-${apiKeyId}-${url}-${cacheVersion} to
${workspaceId}-${url}-${cacheVersion}
- Removed authContext from WorkspaceSchemaBuilderContext: The schema
builder context is now purely about object/field metadata, not about who
is accessing it
- Created createQueryRunnerContext utility: A new helper that combines
the schema builder context with the auth context from the actual request
- Updated all resolver factories: All 15 resolver factories now use
createQueryRunnerContext to build the full context needed by query
runners at execution time

## Benefits
- Improved cache efficiency: GraphQL schemas are now cached per
workspace rather than per user, significantly reducing memory usage and
schema regeneration
- Cleaner separation of concerns: Schema building (metadata-driven) is
now separate from query execution (auth-driven)
- Fresh auth context: Auth context is always retrieved from the current
request, ensuring it reflects the latest state
- Reduced complexity: Simplified the schema creation path by removing
unnecessary auth checks

## Next steps
- Introduce a hash in redis and expose it in the req object so the yoga
patch can access the hash and use it during its own cache key
computation. This way we will be able to invalidate the local cache in
yoga graphql schema generation without restarting pods.
2025-12-30 15:16:57 +01:00
Paul RastoinandGitHub e3ffdb0c2b [BREAKING_CHANGE_NESTED_WORKSPACE]Refactor FlatEntity typing in aim of introducing UniversalFlatEntity (#16701)
# Introduction
Added a `WorkspaceRelated` and `AllNonWorkspaceRelatedEntity` to
simplify the `FlatEntityFrom` that now do not expect a string literal to
omit and itself builds the related many to one entities foreign key
aggregators

We now have the type grain over relation to syncable or just workspace
related entities

Added a migrations that sets the fk on missing entities

## Next
In upcoming PR we will be able to introduce such below type
```ts
import { type CastRecordTypeOrmDatePropertiesToString } from 'src/engine/metadata-modules/flat-entity/types/cast-record-typeorm-date-properties-to-string.type';
import { type ExtractEntityManyToOneEntityRelationProperties } from 'src/engine/metadata-modules/flat-entity/types/extract-entity-many-to-one-entity-relation-properties.type';
import { type ExtractEntityOneToManyEntityRelationProperties } from 'src/engine/metadata-modules/flat-entity/types/extract-entity-one-to-many-entity-relation-properties.type';
import { type ExtractEntityRelatedEntityProperties } from 'src/engine/metadata-modules/flat-entity/types/extract-entity-related-entity-properties.type';
import { type RemoveSuffix } from 'src/engine/workspace-manager/workspace-migration-v2/workspace-migration-builder-v2/types/remove-suffix.type';
import { type SyncableEntity } from 'src/engine/workspace-manager/workspace-sync/types/syncable-entity.interface';

export type UniversalFlatEntityFrom<TEntity extends SyncableEntity> = Omit<
  TEntity,
  | `${ExtractEntityManyToOneEntityRelationProperties<TEntity> & string}Id`
  | ExtractEntityRelatedEntityProperties<TEntity>
  | 'application'
  | 'workspaceId'
  | 'applicationId'
  | keyof CastRecordTypeOrmDatePropertiesToString<TEntity>
> &
  CastRecordTypeOrmDatePropertiesToString<TEntity> & {
    [P in ExtractEntityManyToOneEntityRelationProperties<TEntity> &
      string as `${RemoveSuffix<P, 's'>}UniversalIdentifier`]: string;
  } & {
    [P in ExtractEntityOneToManyEntityRelationProperties<
      TEntity,
      SyncableEntity
    > &
      string as `${RemoveSuffix<P, 's'>}UniversalIdentifiers`]: string[];
  };

```
2025-12-30 13:47:02 +00:00
720348c583 Add upgrade commands to backfill updatedBy field and view fields (#16845)
---
prastoin edit
## Introduction
As we're deprecating the sync metadata we cannot rely on it anymore in
order to create the new standard updatedBy field
In this PR we introduce a command that will backfill the dynamic field
on both workspace standard and custom objects, for standard object it
will create a standard fields ( twenty-standard app scoped ) and for
custom one it will create a custom field ( worksapce-custom-app scoped )

## Testing method
Checkout `1.14.0` `yarn` and `npx nx database:reset twenty-server`
checkout PR and `yarn` `npx nx build twenty-server` and `yarn
database:migrate:prod` finally running the command

#### Before
<img width="2244" height="1464" alt="image"
src="https://github.com/user-attachments/assets/2fb866cd-13b8-4152-99b8-1fcc813b1d46"
/>

#### After
<img width="2244" height="1464" alt="image"
src="https://github.com/user-attachments/assets/b836ac06-c7b8-4add-bee1-bc1963418f29"
/>


#### Logs
```ts
[Nest] 20678  - 12/30/2025, 1:47:35 PM     LOG [BackfillUpdatedByFieldCommand] Found 12 objects that need updatedBy field
[EntityBuilder fieldMetadata] matrix computation: 3.994ms
[EntityBuilder fieldMetadata] creation validation: 1.822ms
[EntityBuilder fieldMetadata] deletion validation: 0.016ms
[EntityBuilder fieldMetadata] update validation: 0.009ms
[EntityBuilder fieldMetadata] entity processing: 6.098ms
[EntityBuilder fieldMetadata] validateAndBuild: 10.217ms
[EntityBuilder index] matrix computation: 0.857ms
[EntityBuilder index] creation validation: 0.003ms
[EntityBuilder index] deletion validation: 0.017ms
[EntityBuilder index] update validation: 0.008ms
[EntityBuilder index] entity processing: 4.721ms
[EntityBuilder index] validateAndBuild: 5.632ms
[Runner] Initial cache retrieval: 0.07ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 7.69ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 10.531ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 5.354ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 6.134ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 2.507ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 3.745ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.113ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 1.585ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.223ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.221ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 5.375ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 5.943ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.363ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 1.997ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 2.03ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.982ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 0.88ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.977ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 9.638ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 11.297ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.581ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.248ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 0.847ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 1.732ms
[Runner] Transaction execution: 82.555ms
[Runner] Cache invalidation flatFieldMetadataMaps,flatIndexMaps,flatObjectMetadataMaps: 89.247ms
[Runner] Total execution: 171.963ms
[Nest] 20678  - 12/30/2025, 1:47:35 PM     LOG [BackfillUpdatedByFieldCommand] Successfully backfilled updatedBy field for 12 objects in workspace 20202020-1c25-4d02-bf25-6aeccf7ea419
[Nest] 20678  - 12/30/2025, 1:47:35 PM     LOG [BackfillUpdatedByFieldCommand] Running command on workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db 2/2
[Nest] 20678  - 12/30/2025, 1:47:35 PM     LOG [BackfillUpdatedByFieldCommand] Starting backfill of updatedBy field for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db
[Nest] 20678  - 12/30/2025, 1:47:35 PM     LOG [BackfillUpdatedByFieldCommand] Found 10 objects that need updatedBy field
[EntityBuilder fieldMetadata] matrix computation: 3.224ms
[EntityBuilder fieldMetadata] creation validation: 0.969ms
[EntityBuilder fieldMetadata] deletion validation: 0.014ms
[EntityBuilder fieldMetadata] update validation: 0.002ms
[EntityBuilder fieldMetadata] entity processing: 5.149ms
[EntityBuilder fieldMetadata] validateAndBuild: 8.472ms
[EntityBuilder index] matrix computation: 0.785ms
[EntityBuilder index] creation validation: 0.002ms
[EntityBuilder index] deletion validation: 0.014ms
[EntityBuilder index] update validation: 0.002ms
[EntityBuilder index] entity processing: 3.818ms
[EntityBuilder index] validateAndBuild: 4.637ms
[Runner] Initial cache retrieval: 0.05ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 2.964ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 3.902ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.502ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.039ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 2.673ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 3.403ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.143ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.123ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 2.033ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.954ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.826ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.903ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.495ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.106ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 14.014ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 14.373ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 1.669ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 2.48ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForMetadata: 0.62ms
[BaseWorkspaceMigrationRunnerActionHandlerService] create_field executeForWorkspaceSchema: 1.048ms
[Runner] Transaction execution: 73.222ms
[Runner] Cache invalidation flatFieldMetadataMaps,flatIndexMaps,flatObjectMetadataMaps: 37.703ms
[Runner] Total execution: 111.071ms
```
---

---------

Co-authored-by: prastoin <paul@twenty.com>
2025-12-30 14:05:26 +01:00
Harshit SinghandGitHub a0491e4755 fix: images are not included in PDF exports (#16076)
## Description

- This PR address issue https://github.com/twentyhq/twenty/issues/15998
- The issue was that images are stored as signed urls and the backend
signed these with JWT
- BlockNote `resolveFileUrl` uses a public CORS proxy that couldn’t
access authenticated/signed URLs



## Visual Appearance



https://github.com/user-attachments/assets/12936451-d91d-4371-bcf7-8a2c2bb68e9c
2025-12-30 11:29:30 +01:00
a2827494a1 Support actor filtering in workflows (#16783)
Fixes https://github.com/twentyhq/twenty/issues/15782

Find records
<img width="422" height="423" alt="Capture d’écran 2025-12-23 à 16 23
49"
src="https://github.com/user-attachments/assets/5856de06-d608-46f6-97a6-8f382f355a44"
/>

Filters
<img width="422" height="271" alt="Capture d’écran 2025-12-23 à 16 23
32"
src="https://github.com/user-attachments/assets/fcc10b6e-f1ec-497a-8593-d599164d4e4b"
/>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Adds full support for filtering on `ACTOR` composite fields across UI
and server.
> 
> - Front-end: handles `ACTOR` in advanced filters and workflow filters;
`source` uses multi-select options from `FieldActorSource`,
`workspaceMemberId` uses `FormSingleRecordPicker`, others default to
text
> - Updates operand mapping for `ACTOR` (`source`→`SELECT`,
`workspaceMemberId`→`RELATION`, else `TEXT`)
> - Server: adds `ACTOR` evaluation with subfield-specific logic
(delegates to select/relation/text evaluators)
> - Simplifies `AdvancedFilterFieldSelectMenu` by removing
workflow-specific field filtering
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
7a8164cd2d. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2025-12-30 09:34:08 +00:00
d39f105a03 i18n - translations (#16849)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-30 10:21:48 +01:00
MarieandGitHub 19c9f957b1 Improve userFriendlyMessage devX (#16815)
Two challenges with error messages
- always provide a useful/meaningful error message for the end user
instead of the generic one. eg: show "Wrong password" and not "An error
occured"
- avoid technical details unless error regards a technical feature. eg:
show "An error occured" and not "Invalid post-hook payload."; but do
show "Invalid issuer URL." as it occurs while configuring SSO

What this PR does
- Make userFriendlyMessage mandatory for widely used
GraphqlQueryRunnerException and CommonQueryRunnerException, so that
developers are forced to ask themselves what the error message should
be, and as it contains very wide error codes (eg: "Bad request") which
should not be mapped to just one default message
- Keep userFriendlyMessage optional for service-specific exceptions (eg:
workflowStepExecutorException), but convert the error code to
userFriendlyMessage mapper to a switch case function with a typecheck
ensuring that all codes are mapped to a message. These default messages
are still overridable where they are thrown.
2025-12-30 09:08:43 +00:00
7522ff6675 i18n - translations (#16848)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-30 10:03:15 +01:00
418377b867 i18n - translations (#16847)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-30 09:51:57 +01:00
Félix MalfaitandGitHub 4f1f0eb177 Redesign Object/Field tables (#16844)
Redesign the data model pages for more clarity / better distinction
between fields and relations
2025-12-30 09:49:55 +01:00
8d130908c2 Allow user to update profile picture (#16812)
Fixes [#16805](https://github.com/twentyhq/twenty/issues/16805)

User was not able to update his own profile picture it showed permisson
error while doing so.

Updated permission so that user is able to edit profile picture

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Ensures profile picture uploads succeed only with appropriate
permissions and clearer errors.
> 
> - Tightens `UploadProfilePicturePermissionGuard` to handle missing
`workspace`, allow during workspace creation, and permit uploads when
user has `WORKSPACE_MEMBERS` or `PROFILE_INFORMATION` settings;
otherwise throws a `PermissionsException` with a user-friendly message
> - In `user-workspace.resolver.ts`, validates the upload result and
throws an error if no files were returned
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
3766bac15e. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2025-12-30 09:46:10 +01:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>Abdullah
3096769616 build(deps): bump @monaco-editor/react from 4.6.0 to 4.7.0 (#16829)
Bumps
[@monaco-editor/react](https://github.com/suren-atoyan/monaco-react)
from 4.6.0 to 4.7.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/suren-atoyan/monaco-react/releases"><code>@​monaco-editor/react</code>'s
releases</a>.</em></p>
<blockquote>
<h2>v4.7.0</h2>
<ul>
<li>package: update <code>@monaco-editor/loader</code> to the latest
(<code>v1.5.0</code>) version (this uses <code>monaco-editor</code>
<code>v0.52.2</code>)</li>
<li>package: inherit all changes from <code>v4.7.0-rc.0</code></li>
</ul>
<h2>v4.7.0-rc.0</h2>
<ul>
<li>package: add support for react/react-dom <code>v19</code> as a peer
dependency</li>
<li>playground: update playground's React version to 19</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/suren-atoyan/monaco-react/blob/master/CHANGELOG.md"><code>@​monaco-editor/react</code>'s
changelog</a>.</em></p>
<blockquote>
<h2>4.7.0</h2>
<ul>
<li>package: update <code>@​monaco-editor/loader</code> to the latest
(v1.5.0) version (this uses monaco-editor v0.52.2)</li>
<li>package: inherit all changes from v4.7.0-rc.0</li>
</ul>
<h2>4.7.0-rc.0</h2>
<ul>
<li>package: add support for react/react-dom v19 as a peer
dependency</li>
<li>playground: update playground's React version to 19</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/eb120e66378471315620fe5339b73ba003f199ad"><code>eb120e6</code></a>
update package to 4.7.0 version</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/cdd070c9f080caf4a9a7b13c2c34fa4e10edc9bf"><code>cdd070c</code></a>
update snapshots</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/55a063e45d2f2672884b77059ac97850758764ae"><code>55a063e</code></a>
update <code>@​monaco-editor/loader</code> to the latest (v1.5.0)
version</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/52e8c75616e09730b7b1a0b5822385212a082ce8"><code>52e8c75</code></a>
update package to 4.7.0-rc.o version</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/e72be4edc1b4492eae9f7d85671ee61a43a6aee8"><code>e72be4e</code></a>
add react 19 to peerDependencies</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/642be903a9dd21d6fe639ab5c92c234dad77c813"><code>642be90</code></a>
update playground's react version to 19</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/ceee344fbe26285dabb0fe90985fe18ec867211c"><code>ceee344</code></a>
Add Monaco-React AI Bot in Readme (<a
href="https://redirect.github.com/suren-atoyan/monaco-react/issues/655">#655</a>)</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/f7cac39fbad0f062dc66458831aaf57a7126dd40"><code>f7cac39</code></a>
add electron blog post link</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/ea601cf9f6fe9f2cc0c6271d6a9cde9a332b6dc0"><code>ea601cf</code></a>
add tea constitution file</li>
<li><a
href="https://github.com/suren-atoyan/monaco-react/commit/3327f3c368cb6d56c02f2df8a9d45177ce6f52e9"><code>3327f3c</code></a>
add GitHub sponsor button</li>
<li>See full diff in <a
href="https://github.com/suren-atoyan/monaco-react/compare/v4.6.0...v4.7.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@monaco-editor/react&package-manager=npm_and_yarn&previous-version=4.6.0&new-version=4.7.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Abdullah <125115953+mabdullahabaid@users.noreply.github.com>
2025-12-29 20:01:05 +01:00
Félix MalfaitandGitHub 3a673f99ba Disable updated By 2 (#16840)
Prepare for release, will re-enable them
2025-12-29 18:57:17 +01:00
e5e5ae8e1d fix: guard against invalid date and undefined links field value (#16039)
closes https://github.com/twentyhq/twenty/issues/15854

- Add `isValid()` check in `formatDateISOStringToDateTime` before
calling `formatInTimeZone`
- Add `isDefined()` guard in `getFieldLinkDefinedLinks` (mirrors
`phonesUtils` pattern)

before:


https://github.com/user-attachments/assets/1eb89fa4-70b6-4794-8860-0a42522598b5



https://github.com/user-attachments/assets/781c7d37-c435-4832-98d4-8e6925b51e10



after:


https://github.com/user-attachments/assets/b1c22d25-4e8e-45c3-af98-be1684a5962e



https://github.com/user-attachments/assets/ce084a9d-03b8-4f88-8522-a32cb1b7cf2f

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-12-29 17:03:24 +00:00
Félix MalfaitandGitHub b56dcd8c22 Temporarily disable updatedBy (#16839)
To avoid breaking workflows during release
2025-12-29 17:06:16 +01:00
ba7a060195 i18n - translations (#16836)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-29 16:01:01 +01:00
4135a6473a [BREAKING_CHANGE_DASHBOARDS][DASHBOARD_CACHE_FLUSH_REQUIRED] Refactor page layout widget configuration type (#16671)
# Introduction
In this pull-request we're refactoring the page layout widget
configuration entity to be containing its discriminated key simplifying
underlying code and maintainability
- Made the configuration and title non nullable
- Introduced a generic predicate for the `widgetConfigurationType`
- Upgraded command to remove `graphType` and insert new
`configurationType` to existing entries
- Migrated frontend to new type system

---------

Co-authored-by: bosiraphael <raphael.bosi@gmail.com>
Co-authored-by: Raphaël Bosi <71827178+bosiraphael@users.noreply.github.com>
2025-12-29 15:46:59 +01:00
2b9728230a Correctly separate widgets in side-column mode. (#16804)
Had to close the other PR since I messed up re-basing somehow:
https://github.com/twentyhq/twenty/pull/16668/files.

Moved changes to this new PR in order to resolve comments from the
previous PR and also match the field-design to that on Figma.

---------

Co-authored-by: Baptiste Devessier <baptiste@devessier.fr>
2025-12-29 15:00:33 +01:00
Abdullah.andGitHub bee58fd03d feat: use side-column variant for all widgets on mobile and side panel (#16822)
Closes [1957](https://github.com/twentyhq/core-team-issues/issues/1957).

`getWidgetCardVariant` now returns `side-panel` for mobile and right
drawer instead of returning `record-page`.

Added stories to WidgetRenderer.stories.tsx because WidgetRenderer is
where getWidgetCardVariant is called and the variant is applied. These
stories test the actual behavior (mobile/side panel triggering
side-column variant) rather than just visual appearance, following the
existing pattern of individual behavior-testing stories in this file.
2025-12-29 14:02:52 +01:00
MarieandGitHub bb18f78f1b [Fix] Fix NaN position in notes resulting in not being able to create notes (#16818)
Following [discord
thread](https://discord.com/channels/1130383047699738754/1453910755387899996/1453910755387899996),
reproductible on twenty-eng


https://github.com/user-attachments/assets/ae7f363d-87e1-44fa-8fe2-ee78412d62a7

Records positions are computed at record creation, depending on the
position arg from the request, being equal to `last`, `first`, or not
present.
When being equal to last, as it is done when creating a note from the
product, the position is calculated using `.maximum()` function which
uses postgres' MAX function. If there is a `NaN` value among the list,
the MAX will return `NaN` too. So if for some reason there is a NaN
somewhere in the position column, all subsequent records being created
with last position argument will be created with NaN value. Until [this
PR](https://github.com/twentyhq/twenty/pull/16630), where we introduced
a validation on position at record creation which throws when NaN is
trying to be introduced as a position, this was going silent. (fyi
@etiennejouan , not on you at all but for info)

Looking into twenty-eng workspace, I found note records with NaN
position dating back to august 2025, making it hard to understand and
debug why they were introduced with NaN position. So I did not find the
real root cause, but I suggest to
- update record-position.service to fix the issue for subsequent records
that go through this service (which is what is currently broken)
- run a command to fix the existing records with NaN position for Notes,
as it is where the issue happened for both the user reporting the issue
on discord, and us on twenty-eng. So hopefully the problem was limited
to Notes
2025-12-29 13:55:20 +01:00
ee0e2ed854 i18n - translations (#16832)
Created by Github action

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-29 11:01:07 +01:00
343b74666f i18n - translations (#16831)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-29 10:22:32 +01:00
01e0502fcf feat: add updatedBy field to track last record modifier (#16807)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> Implements last-modifier tracking and unified actor injection.
> 
> - New `ActorFromAuthContextService` replaces createdBy-only logic;
pre-query hooks now inject both `createdBy` and `updatedBy` on create
and `updatedBy` on update
> - Add `updatedBy` standard field to core/custom objects (e.g.,
`person`, `company`, `task`, `note`, `attachment`, `dashboard`,
`workflow`, `workflowRun`) with IDs, metadata builders, and ORM entity
fields
> - Record CRUD: `create` now sets both `createdBy` and `updatedBy`;
`update` sets `updatedBy`; workflow actions use a shared workflow actor
builder; REST base handler uses the new actor service
> - Seeder data and snapshots updated to include `updatedBy`; GraphQL
result formatting adds defaults/handling for empty composite fields
(incl. actor)
> - Frontend `useUpdateOneRecord` upserts returned record into the local
store after mutation
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
1f283778e9. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
Co-authored-by: Félix Malfait <felix@twenty.com>
2025-12-29 09:05:17 +00:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>Abdullah
0da5cf29de Bump eslint from 9.32.0 to 9.39.2 (#16736)
Bumps [eslint](https://github.com/eslint/eslint) from 9.32.0 to 9.39.2.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/eslint/eslint/releases">eslint's
releases</a>.</em></p>
<blockquote>
<h2>v9.39.2</h2>
<h2>Bug Fixes</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/57058331946568164449c5caabe2cf206e4fb5d9"><code>5705833</code></a>
fix: warn when <code>eslint-env</code> configuration comments are found
(<a
href="https://redirect.github.com/eslint/eslint/issues/20381">#20381</a>)
(sethamus)</li>
</ul>
<h2>Build Related</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/506f1549a64aa65bdddc75c71cb62f0ab94b5a23"><code>506f154</code></a>
build: add .scss files entry to knip (<a
href="https://redirect.github.com/eslint/eslint/issues/20391">#20391</a>)
(Milos Djermanovic)</li>
</ul>
<h2>Chores</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/7ca0af7f9f89dd4a01736dae01931c45d528171b"><code>7ca0af7</code></a>
chore: upgrade to <code>@eslint/js@9.39.2</code> (<a
href="https://redirect.github.com/eslint/eslint/issues/20394">#20394</a>)
(Francesco Trotta)</li>
<li><a
href="https://github.com/eslint/eslint/commit/c43ce24ff0ce073ec4ad691cd5a50171dfe6cf1e"><code>c43ce24</code></a>
chore: package.json update for <code>@​eslint/js</code> release
(Jenkins)</li>
<li><a
href="https://github.com/eslint/eslint/commit/4c9858e47bb9146cf20f546a562bc58a9ee3dae1"><code>4c9858e</code></a>
ci: add <code>v9.x-dev</code> branch (<a
href="https://redirect.github.com/eslint/eslint/issues/20382">#20382</a>)
(Milos Djermanovic)</li>
</ul>
<h2>v9.39.1</h2>
<h2>Bug Fixes</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/650753ee3976784343ceb40170619dab1aa9fe0d"><code>650753e</code></a>
fix: Only pass node to JS lang visitor methods (<a
href="https://redirect.github.com/eslint/eslint/issues/20283">#20283</a>)
(Nicholas C. Zakas)</li>
</ul>
<h2>Documentation</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/51b51f4f1ce82ef63264c4e45d9ef579bcd73f8e"><code>51b51f4</code></a>
docs: add a section on when to use extends vs cascading (<a
href="https://redirect.github.com/eslint/eslint/issues/20268">#20268</a>)
(Tanuj Kanti)</li>
<li><a
href="https://github.com/eslint/eslint/commit/b44d42699dcd1729b7ecb50ca70e4c1c17f551f1"><code>b44d426</code></a>
docs: Update README (GitHub Actions Bot)</li>
</ul>
<h2>Chores</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/92db329211c8da5ce8340a4d4c05ce9c12845381"><code>92db329</code></a>
chore: update <code>@eslint/js</code> version to 9.39.1 (<a
href="https://redirect.github.com/eslint/eslint/issues/20284">#20284</a>)
(Francesco Trotta)</li>
<li><a
href="https://github.com/eslint/eslint/commit/c7ebefc9eaf99b76b30b0d3cf9960807a47367c4"><code>c7ebefc</code></a>
chore: package.json update for <code>@​eslint/js</code> release
(Jenkins)</li>
<li><a
href="https://github.com/eslint/eslint/commit/61778f6ca33c0f63962a91d6a75a4fa5db9f47d2"><code>61778f6</code></a>
chore: update eslint-config-eslint dependency <code>@​eslint/js</code>
to ^9.39.0 (<a
href="https://redirect.github.com/eslint/eslint/issues/20275">#20275</a>)
(renovate[bot])</li>
<li><a
href="https://github.com/eslint/eslint/commit/d9ca2fcd9ad63331bfd329a69534e1ff04f231e8"><code>d9ca2fc</code></a>
ci: Add rangeStrategy to eslint group in renovate config (<a
href="https://redirect.github.com/eslint/eslint/issues/20266">#20266</a>)
(唯然)</li>
<li><a
href="https://github.com/eslint/eslint/commit/009e5076ff5a4bd845f55e17676e3bb88f47c280"><code>009e507</code></a>
test: fix version tests for ESLint v10 (<a
href="https://redirect.github.com/eslint/eslint/issues/20274">#20274</a>)
(Milos Djermanovic)</li>
</ul>
<h2>v9.39.0</h2>
<h2>Features</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/cc57d87a3f119e9d39c55e044e526ae067fa31ce"><code>cc57d87</code></a>
feat: update error loc to key in <code>no-dupe-class-members</code> (<a
href="https://redirect.github.com/eslint/eslint/issues/20259">#20259</a>)
(Tanuj Kanti)</li>
<li><a
href="https://github.com/eslint/eslint/commit/126552fcf35da3ddcefa527db06dabc54c04041c"><code>126552f</code></a>
feat: update error location in <code>for-direction</code> and
<code>no-dupe-args</code> (<a
href="https://redirect.github.com/eslint/eslint/issues/20258">#20258</a>)
(Tanuj Kanti)</li>
<li><a
href="https://github.com/eslint/eslint/commit/167d0970d3802a66910e9820f31dcd717fab0b2a"><code>167d097</code></a>
feat: update <code>complexity</code> rule to highlight only static block
header (<a
href="https://redirect.github.com/eslint/eslint/issues/20245">#20245</a>)
(jaymarvelz)</li>
</ul>
<h2>Bug Fixes</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/15f5c7c168d0698683943f51dd617f14a5e6815c"><code>15f5c7c</code></a>
fix: forward traversal <code>step.args</code> to visitors (<a
href="https://redirect.github.com/eslint/eslint/issues/20253">#20253</a>)
(jaymarvelz)</li>
<li><a
href="https://github.com/eslint/eslint/commit/5a1a534e877f7c4c992885867f923df307c3929d"><code>5a1a534</code></a>
fix: allow JSDoc comments in object-shorthand rule (<a
href="https://redirect.github.com/eslint/eslint/issues/20167">#20167</a>)
(Nitin Kumar)</li>
<li><a
href="https://github.com/eslint/eslint/commit/e86b813eb660f1a5adc8e143a70d9b683cd12362"><code>e86b813</code></a>
fix: Use more types from <code>@​eslint/core</code> (<a
href="https://redirect.github.com/eslint/eslint/issues/20257">#20257</a>)
(Nicholas C. Zakas)</li>
<li><a
href="https://github.com/eslint/eslint/commit/927272d1f0d5683b029b729d368a96527f283323"><code>927272d</code></a>
fix: correct <code>Scope</code> typings (<a
href="https://redirect.github.com/eslint/eslint/issues/20198">#20198</a>)
(jaymarvelz)</li>
<li><a
href="https://github.com/eslint/eslint/commit/37f76d9c539bb6fc816fedb7be4486b71a58620a"><code>37f76d9</code></a>
fix: use <code>AST.Program</code> type for Program node (<a
href="https://redirect.github.com/eslint/eslint/issues/20244">#20244</a>)
(Francesco Trotta)</li>
<li><a
href="https://github.com/eslint/eslint/commit/ae07f0b3334ebd22ae2e7b09bca5973b96aa9768"><code>ae07f0b</code></a>
fix: unify timing report for concurrent linting (<a
href="https://redirect.github.com/eslint/eslint/issues/20188">#20188</a>)
(jaymarvelz)</li>
<li><a
href="https://github.com/eslint/eslint/commit/b165d471be6062f4475b972155b02654a974a0e9"><code>b165d47</code></a>
fix: correct <code>Rule</code> typings (<a
href="https://redirect.github.com/eslint/eslint/issues/20199">#20199</a>)
(jaymarvelz)</li>
<li><a
href="https://github.com/eslint/eslint/commit/fb97cda70d87286a7dbd2457f578ef578d6905e8"><code>fb97cda</code></a>
fix: improve error message for missing fix function in suggestions (<a
href="https://redirect.github.com/eslint/eslint/issues/20218">#20218</a>)
(jaymarvelz)</li>
</ul>
<h2>Documentation</h2>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/d3e81e30ee6be5a21151b7a17ef10a714b6059c0"><code>d3e81e3</code></a>
docs: Always recommend to include a files property (<a
href="https://redirect.github.com/eslint/eslint/issues/20158">#20158</a>)
(Percy Ma)</li>
<li><a
href="https://github.com/eslint/eslint/commit/0f0385f1404dcadaba4812120b1ad02334dbd66a"><code>0f0385f</code></a>
docs: use consistent naming recommendation (<a
href="https://redirect.github.com/eslint/eslint/issues/20250">#20250</a>)
(Alex M. Spieslechner)</li>
<li><a
href="https://github.com/eslint/eslint/commit/a3b145609ac649fac837c8c0515cbb2a9321ca40"><code>a3b1456</code></a>
docs: Update README (GitHub Actions Bot)</li>
<li><a
href="https://github.com/eslint/eslint/commit/cf5f2dd58dd98084a21da04fe7b9054b9478d552"><code>cf5f2dd</code></a>
docs: fix correct tag of <code>no-useless-constructor</code> (<a
href="https://redirect.github.com/eslint/eslint/issues/20255">#20255</a>)
(Tanuj Kanti)</li>
<li><a
href="https://github.com/eslint/eslint/commit/10b995c8e5473de8d66d3cd99d816e046f35e3ec"><code>10b995c</code></a>
docs: add TS options and examples for <code>nofunc</code> in
<code>no-use-before-define</code> (<a
href="https://redirect.github.com/eslint/eslint/issues/20249">#20249</a>)
(Tanuj Kanti)</li>
<li><a
href="https://github.com/eslint/eslint/commit/2584187e4a305ea7a98e1a5bd4dca2a60ad132f8"><code>2584187</code></a>
docs: remove repetitive word in comment (<a
href="https://redirect.github.com/eslint/eslint/issues/20242">#20242</a>)
(reddaisyy)</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/eslint/eslint/commit/9278324aa0023d223874825b0d4b6ac75783096a"><code>9278324</code></a>
9.39.2</li>
<li><a
href="https://github.com/eslint/eslint/commit/542266ad3c58b47066d4b8ae61d419b423acee8f"><code>542266a</code></a>
Build: changelog update for 9.39.2</li>
<li><a
href="https://github.com/eslint/eslint/commit/7ca0af7f9f89dd4a01736dae01931c45d528171b"><code>7ca0af7</code></a>
chore: upgrade to <code>@eslint/js@9.39.2</code> (<a
href="https://redirect.github.com/eslint/eslint/issues/20394">#20394</a>)</li>
<li><a
href="https://github.com/eslint/eslint/commit/c43ce24ff0ce073ec4ad691cd5a50171dfe6cf1e"><code>c43ce24</code></a>
chore: package.json update for <code>@​eslint/js</code> release</li>
<li><a
href="https://github.com/eslint/eslint/commit/57058331946568164449c5caabe2cf206e4fb5d9"><code>5705833</code></a>
fix: warn when <code>eslint-env</code> configuration comments are found
(<a
href="https://redirect.github.com/eslint/eslint/issues/20381">#20381</a>)</li>
<li><a
href="https://github.com/eslint/eslint/commit/506f1549a64aa65bdddc75c71cb62f0ab94b5a23"><code>506f154</code></a>
build: add .scss files entry to knip (<a
href="https://redirect.github.com/eslint/eslint/issues/20391">#20391</a>)</li>
<li><a
href="https://github.com/eslint/eslint/commit/4c9858e47bb9146cf20f546a562bc58a9ee3dae1"><code>4c9858e</code></a>
ci: add <code>v9.x-dev</code> branch (<a
href="https://redirect.github.com/eslint/eslint/issues/20382">#20382</a>)</li>
<li><a
href="https://github.com/eslint/eslint/commit/e2772811a8595d161870835ff04822b25a2cdf45"><code>e277281</code></a>
9.39.1</li>
<li><a
href="https://github.com/eslint/eslint/commit/4cdf397b30b2b749865ea0fcf4d30eb8ba458896"><code>4cdf397</code></a>
Build: changelog update for 9.39.1</li>
<li><a
href="https://github.com/eslint/eslint/commit/92db329211c8da5ce8340a4d4c05ce9c12845381"><code>92db329</code></a>
chore: update <code>@eslint/js</code> version to 9.39.1 (<a
href="https://redirect.github.com/eslint/eslint/issues/20284">#20284</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/eslint/eslint/compare/v9.32.0...v9.39.2">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=eslint&package-manager=npm_and_yarn&previous-version=9.32.0&new-version=9.39.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Abdullah <125115953+mabdullahabaid@users.noreply.github.com>
2025-12-29 12:24:55 +05:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3278950415 build(deps-dev): bump msw-storybook-addon from 2.0.5 to 2.0.6 (#16830)
Bumps
[msw-storybook-addon](https://github.com/mswjs/msw-storybook-addon/tree/HEAD/packages/msw-addon)
from 2.0.5 to 2.0.6.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/mswjs/msw-storybook-addon/releases">msw-storybook-addon's
releases</a>.</em></p>
<blockquote>
<h2>v2.0.6</h2>
<h4>🐛 Bug Fix</h4>
<ul>
<li>fix: add a <code>@deprecated</code> tag to the
<code>mswDecorator</code> <a
href="https://redirect.github.com/mswjs/msw-storybook-addon/pull/178">#178</a>
(<a
href="https://github.com/connorshea"><code>@​connorshea</code></a>)</li>
</ul>
<h4>Authors: 1</h4>
<ul>
<li>Connor Shea (<a
href="https://github.com/connorshea"><code>@​connorshea</code></a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/mswjs/msw-storybook-addon/blob/main/packages/msw-addon/CHANGELOG.md">msw-storybook-addon's
changelog</a>.</em></p>
<blockquote>
<h1>v2.0.6 (Fri Oct 10 2025)</h1>
<h4>🐛 Bug Fix</h4>
<ul>
<li>fix: add a <code>@deprecated</code> tag to the
<code>mswDecorator</code> <a
href="https://redirect.github.com/mswjs/msw-storybook-addon/pull/178">#178</a>
(<a
href="https://github.com/connorshea"><code>@​connorshea</code></a>)</li>
</ul>
<h4>Authors: 1</h4>
<ul>
<li>Connor Shea (<a
href="https://github.com/connorshea"><code>@​connorshea</code></a>)</li>
</ul>
<hr />
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/mswjs/msw-storybook-addon/commit/ae7ce4de01bf9665a03816f3ca4908feb5f90653"><code>ae7ce4d</code></a>
Update CHANGELOG.md [skip ci]</li>
<li><a
href="https://github.com/mswjs/msw-storybook-addon/commit/0b9594003ce8226767d51b444bad505db401c387"><code>0b95940</code></a>
fix: add a <code>@deprecated</code> tag to the <code>mswDecorator</code>
(<a
href="https://github.com/mswjs/msw-storybook-addon/tree/HEAD/packages/msw-addon/issues/178">#178</a>)</li>
<li>See full diff in <a
href="https://github.com/mswjs/msw-storybook-addon/commits/v2.0.6/packages/msw-addon">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=msw-storybook-addon&package-manager=npm_and_yarn&previous-version=2.0.5&new-version=2.0.6)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-29 12:22:47 +05:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
3005f7ba41 build(deps): bump @opentelemetry/auto-instrumentations-node from 0.60.0 to 0.60.1 (#16828)
Bumps
[@opentelemetry/auto-instrumentations-node](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/HEAD/packages/auto-instrumentations-node)
from 0.60.0 to 0.60.1.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/open-telemetry/opentelemetry-js-contrib/releases"><code>@​opentelemetry/auto-instrumentations-node</code>'s
releases</a>.</em></p>
<blockquote>
<h2>instrumentation-aws-lambda: v0.60.1</h2>
<h2><a
href="https://github.com/open-telemetry/opentelemetry-js-contrib/compare/instrumentation-aws-lambda-v0.60.0...instrumentation-aws-lambda-v0.60.1">0.60.1</a>
(2025-11-24)</h2>
<h3>Dependencies</h3>
<ul>
<li>The following workspace dependencies were updated
<ul>
<li>devDependencies
<ul>
<li><code>@​opentelemetry/propagator-aws-xray</code> bumped from ^2.1.3
to ^2.1.4</li>
<li><code>@​opentelemetry/propagator-aws-xray-lambda</code> bumped from
^0.55.3 to ^0.55.4</li>
</ul>
</li>
</ul>
</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/packages/auto-instrumentations-node/CHANGELOG.md"><code>@​opentelemetry/auto-instrumentations-node</code>'s
changelog</a>.</em></p>
<blockquote>
<h2><a
href="https://github.com/open-telemetry/opentelemetry-js-contrib/compare/auto-instrumentations-node-v0.60.0...auto-instrumentations-node-v0.60.1">0.60.1</a>
(2025-06-05)</h2>
<h3>Dependencies</h3>
<ul>
<li>The following workspace dependencies were updated
<ul>
<li>dependencies
<ul>
<li><code>@​opentelemetry/instrumentation-hapi</code> bumped from
^0.48.0 to ^0.49.0</li>
<li><code>@​opentelemetry/instrumentation-koa</code> bumped from ^0.50.0
to ^0.50.1</li>
<li><code>@​opentelemetry/instrumentation-mongodb</code> bumped from
^0.55.0 to ^0.55.1</li>
<li><code>@​opentelemetry/instrumentation-net</code> bumped from ^0.46.0
to ^0.46.1</li>
<li><code>@​opentelemetry/instrumentation-redis</code> bumped from
^0.49.0 to ^0.49.1</li>
<li><code>@​opentelemetry/instrumentation-restify</code> bumped from
^0.48.0 to ^0.48.1</li>
<li><code>@​opentelemetry/instrumentation-undici</code> bumped from
^0.13.0 to ^0.13.1</li>
</ul>
</li>
</ul>
</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/open-telemetry/opentelemetry-js-contrib/commits/auto-instrumentations-node-v0.60.1/packages/auto-instrumentations-node">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@opentelemetry/auto-instrumentations-node&package-manager=npm_and_yarn&previous-version=0.60.0&new-version=0.60.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-29 05:40:40 +01:00
Félix MalfaitandGitHub 1b6a0cd05a fix(billing): redirect to Stripe payment method setup when subscribing without payment method (#16827)
## Summary

When users click 'Subscribe Now' during a trial period without a payment
method configured, they previously saw an unhelpful error message: "No
payment method found. Please update your billing details."

This PR improves the UX by redirecting users directly to Stripe's
billing portal payment method update flow, where they can add their
payment information. After adding a payment method, users are redirected
back to the billing settings page and can click 'Subscribe Now' again to
successfully activate their subscription.

## Changes

### Backend
- **stripe-billing-portal.service.ts**: Added
`createBillingPortalSessionForPaymentMethodUpdate` method that creates a
Stripe billing portal session with `flow_data.type:
'payment_method_update'`
- **billing-portal.workspace-service.ts**: Added
`computeBillingPortalSessionURLForPaymentMethodUpdate` method to build
the portal URL
- **billing-end-trial-period.output.ts**: Added optional
`billingPortalUrl` field to the GraphQL output DTO
- **billing-subscription.service.ts**: Modified `endTrialPeriod` to
return `stripeCustomerId` when no payment method exists
- **billing.resolver.ts**: Updated resolver to orchestrate billing
portal URL generation when no payment method

### Frontend
- **useEndSubscriptionTrialPeriod.ts**: Redirect to billing portal URL
instead of showing error snackbar
- **endSubscriptionTrialPeriod.ts**: Added `billingPortalUrl` to
mutation response fields

## User Flow

1. User clicks "Subscribe Now" during trial
2. Backend checks for payment method
3. If no payment method → redirect to Stripe billing portal payment
method update page
4. User adds payment method in Stripe
5. User is redirected back to `/settings/billing`
6. User clicks "Subscribe Now" again to activate subscription
2025-12-29 05:39:53 +01:00
6bd14dc847 i18n - translations (#16825)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-28 16:00:59 +01:00
Félix MalfaitandGitHub 7021a51747 feat(billing): implement credit rollover from one billing period to another (#16802)
## Summary
This PR implements credit rollover functionality for billing, allowing
unused credits from one billing period to carry over to the next (capped
at the current period's subscription tier cap).

## Changes

### New Services
- **StripeCreditGrantService**: Interacts with Stripe's Billing Credits
API to create credit grants, retrieve customer credit balances, and void
grants
- **BillingCreditRolloverService**: Contains the rollover logic -
calculates unused credits and creates new grants for the next period
- **BillingWebhookCreditGrantService**: Handles
`billing.credit_grant.created` and `billing.credit_grant.updated`
webhooks to update billing alerts

### Modified Services
- **StripeBillingAlertService**: Updated to include credit balance when
calculating usage threshold alerts
- **BillingUsageService**: Returns rollover credits to the frontend for
display
- **BillingSubscriptionService**: Queries credit balance when creating
billing alerts
- **BillingWebhookInvoiceService**: Triggers rollover processing on
`invoice.finalized` webhook

### Frontend
- Updated `SettingsBillingCreditsSection` to display base credits,
rollover credits, and total available
- Updated GraphQL query to fetch new `rolloverCredits` and
`totalGrantedCredits` fields

### Stripe SDK Upgrade
- Upgraded from v17.3.1 to v19.3.1 to get proper types for
billing.credit_grant events
- Fixed breaking changes: invoice.subscription path, subscription period
fields location, removed properties

## How it works

1. When `invoice.finalized` webhook is received for
`subscription_cycle`, the system:
   - Calculates usage from the previous period
   - Determines unused credits (tier cap - usage)
   - Caps rollover at current tier cap
   - Creates a Stripe credit grant with expiration at end of new period

2. When credit grants are created/updated/voided:
   - Billing alerts are recreated with the updated credit balance

3. The UI displays:
   - Base credits (from subscription tier)
   - Rollover credits (from previous periods)
   - Total available credits

## Edge Cases Handled
- Credit grant voided: `billing.credit_grant.updated` webhook triggers
alert update
- Credit grant expired: Stripe's `creditBalanceSummary` API excludes
expired grants
- No unused credits: Rollover service skips grant creation
- Customer ID as object: Controller extracts `.id` from expanded
customer
2025-12-28 15:42:18 +01:00
Abdul RahmanandGitHub 952dee955c fix: Stop autoscroll when user manually scrolls up during streaming (#16795)
https://github.com/user-attachments/assets/2ca908ca-63b8-4895-9ed7-7beaeea13ca9
2025-12-27 09:19:44 +01:00
MarieandGitHub 7400a3051c Small improvements with views (#16821)
- when a view is deleted, it is removed from left menu + from list views
in dropdown
- deactivated fields are not suggested as options to group records by
for a view (only in FE, not forbidden by BE)
2025-12-27 07:11:04 +01:00
Félix MalfaitandGitHub 265345fd69 fix: prevent infinite loop when metadata version cache is empty (#16816)
## Context

After flushing the Redis cache (e.g., via `cache:flush` command), users
get stuck in an infinite loop showing "Your workspace has been updated
with a new data model. Please refresh the page." - refreshing the page
doesn't help.

## Root Cause

When the cache is flushed, `getMetadataVersion()` returns `undefined`.
The version comparison in the error handler then becomes:

```typescript
requestMetadataVersion !== `${currentMetadataVersion}`
// Evaluates to: "5" !== "undefined" → always true
```

This triggers the schema mismatch error on every request, even after
page refresh.

## History

| Date | Commit | What Happened |
|------|--------|---------------|
| Aug 2024 | #6691 (`17a1760afd`) | Introduced the
`${currentMetadataVersion}` template literal that converts `undefined`
to the string `"undefined"` |
| Dec 2025 | #16536 (`0035fc1145`) | Removed the safety check that would
throw an early error when cache is empty, allowing `undefined` to
propagate |

## Fix

Add `isDefined(currentMetadataVersion)` check before comparing versions.
If the server doesn't have a cached version, we shouldn't treat it as a
mismatch - the schema factory already handles populating the cache when
it actually needs the version.

```typescript
if (
  requestMetadataVersion &&
  isDefined(currentMetadataVersion) &&  // ← Added this check
  requestMetadataVersion !== `${currentMetadataVersion}`
) {
```

## Testing

1. Flush the cache: `npx nx run twenty-server:command cache:flush`
2. Refresh the page
3. Verify no infinite loop occurs and app loads normally
2025-12-27 07:09:44 +01:00
bbdad09399 i18n - translations (#16823)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-26 19:01:17 +01:00
c020f71ba1 Add "number of decimal" on currency field. (#16439)
Closes [571](https://github.com/twentyhq/core-team-issues/issues/571).

Replicates the behavior of number field and allows specifying the number
of decimals for currency field.

<img width="931" height="858" alt="image"
src="https://github.com/user-attachments/assets/f5100d58-b1b0-4a88-a090-e98b2feeebd0"
/>

Currencies around the world have a maximum of three decimal places -
BHD, KWD etc. However, I have added a maximum of five decimal places in
case someone wants to use the currency field type for displaying things
like `per-second-billing` or `exchange rates`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Adds configurable decimals (0–5) for currency fields, updating
settings UI, types/schema, display/aggregate formatting, and input
precision.
> 
> - **Currency field settings**:
> - Add `decimals` (0–5) to `FieldCurrencyMetadata.settings` and
validate via `currencyFieldSettingsSchema`.
> - Update `SettingsDataModelFieldCurrencyForm` to manage `format`
(short/full) and `decimals` with counter when `full`; wire defaults via
`useCurrencySettingsFormInitialValues`.
> - **Display & aggregation**:
> - `CurrencyDisplay` and
`transformAggregateRawValueIntoAggregateDisplayValue` honor `decimals`
when `format` is `full`; keep short format using `formatToShortNumber`.
> - **Input**:
>   - Increase currency `IMaskInput` precision with `scale=5`.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
959a8fc1ea. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2025-12-26 22:53:43 +05:00
28dc3e470e i18n - translations (#16814)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-26 09:39:27 +01:00
874e4e4666 i18n - translations (#16813)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-26 09:22:02 +01:00
6547c11862 i18n - docs translations (#16799)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-25 10:12:14 +01:00
Baptiste DevessierandGitHub 06d0ac13c4 Ensure record fields uniqueness across widgets (#16781)
This PR dissociates record inputs so that several inputs for the same
record field can live on the same page.

## Simple values demo


https://github.com/user-attachments/assets/a8c224d8-4cd6-4fe3-9cf8-01f6bdd2fca9

## Relations demo


https://github.com/user-attachments/assets/87267a8b-8ce5-41ce-8a78-cba2384828bb

## Doesn't break Record Table


https://github.com/user-attachments/assets/bcdd2b05-7cb4-4ed2-9093-58be3e04e43e

## Doesn't break Show Page


https://github.com/user-attachments/assets/f9ab9e14-012c-451e-a35f-01a165523f95
2025-12-24 17:01:10 +01:00
Félix MalfaitandGitHub 6a4974e285 feat: enforce credit limits via Stripe alerts for all billing scenarios (#16801)
## Summary

This PR ensures usage alerts are created for all billing scenarios.

## Background

Per [Stripe
documentation](https://docs.stripe.com/billing/subscriptions/usage-based/alerts),
usage alerts are **one-time per customer** - they trigger once and only
consider usage reported after the alert is created. This means we need
to create a new alert whenever:

1.  Subscription is created (trial) - Already implemented
2.  Trial ends (user becomes Active subscriber) - **Added in this PR**
3.  Credit tier changes (upgrade) - **Added in this PR**
4.  **New billing cycle starts** - **Critical fix in this PR!**

## The Issue

Previously, the invoice webhook reset `hasReachedCurrentPeriodCap =
false` at cycle end, but didn't create a new alert. This meant after the
first billing period, there was no alert to trigger and users could
exceed their limit without being blocked.

## Changes

### 1. Invoice Webhook (`billing-webhook-invoice.service.ts`)
When invoice is finalized for `subscription_cycle`:
- Reset `hasReachedCurrentPeriodCap = false`  (already done)
- **NEW**: Create alert at the current tier cap

### 2. End Trial Period (`billing-subscription.service.ts`)
In `endTrialPeriod()`:
- **NEW**: Create alert at the paid tier cap (not trial cap)

### 3. Credit Tier Upgrades (`billing-subscription.service.ts`)
In `changeMeteredPrice()`, when upgrading immediately (not scheduled for
period end):
- **NEW**: Reset `hasReachedCurrentPeriodCap = false`
- **NEW**: Create alert at new tier cap

### 4. Alert Title Update (`stripe-billing-alert.service.ts`)
Changed from "Trial usage cap" to "Usage cap" since alerts are now used
for all scenarios.

## Stripe Alert Limits

- Max 25 alerts per meter+customer combination
- Alerts only evaluate usage reported after creation
- One-time alerts trigger once per customer

With monthly billing cycles + occasional tier changes, we should stay
well under the 25 alert limit.

## Testing

- TypeScript typechecking passes
- Backend services properly inject new dependencies
2025-12-24 16:32:31 +01:00
MarieandGitHub 66daf69a5d [Tests E2E] Attempt to improve speed (#16755)
This PR presents an attempt to increase the speed of the tests to run,
by using the same front-end built for Front and E2E CIs. It implied
merging front and E2E in one CI, but allowed to still have two different
status, and to have E2E run even if no front files have changed.

Also now using depot to build FE. 

<img width="270" height="546" alt="image"
src="https://github.com/user-attachments/assets/d9eccc62-4494-4102-ad4e-241fec4bd4ea"
/>
2025-12-24 16:30:48 +01:00
Rajdeep DasandGitHub dc1bf8dac9 Fix Hide empty groups in List view when Group By is enabled (#16752)
Fixed inconsistency where List view (Group By) still showed empty groups
while Kanban hides them.
Update `visibleRecordGroupIdsComponentFamilySelector` now filters out
groups with zero records using
`recordIndexRecordIdsByGroupComponentFamilyState` and
`recordIndexShouldHideEmptyRecordGroupsComponentState`, ensuring empty
groups are consistently hidden across views.

Fixes #16212
2025-12-24 16:01:57 +01:00
5d6c39ec7e i18n - translations (#16800)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-24 15:47:58 +01:00
BhoomaahamsoandGitHub 08527930d7 fix: 🐛 visible fields count updates when toggling field (#16789)
Fixes: #16734

Solution:
The ObjectOptionsDropdownDefaultView was reading from
recordIndexFieldDefinitionsState via useObjectOptionsForBoard, while
field visibility changes update currentRecordFieldsComponentState. This
caused the "X shown" count to remain stale after hiding fields.

Changed to use visibleRecordFieldsComponentSelector (same state source
used by ViewFieldsVisibleDropdownSection) so both components react to
the same state updates.



https://github.com/user-attachments/assets/62eb5c98-f15f-4ee8-bdce-1ab4e4752f66
2025-12-24 15:44:55 +01:00
Félix MalfaitandGitHub b46e9d2e64 feat: add AI chat error handling for billing and API key errors (#16797)
## Summary

This PR adds user-friendly error handling for AI chat features,
specifically for **billing credits exhausted** and **API key not
configured** errors.

## Changes

### Backend
- Added `BILLING_CREDITS_EXHAUSTED` exception code with 402 status
- Added `API_KEY_NOT_CONFIGURED` exception code with 503 status
- Added billing check before AI chat streaming in
`agent-chat.controller.ts`
- Added error code to HTTP exception response body for frontend error
type detection
- Created `AgentRestApiExceptionFilter` for agent-specific errors

### Frontend
- Created `AIChatBanner` - reusable banner component for error/warning
messages
- Created `AIChatCreditsExhaustedMessage` - shows upgrade prompts based
on user permissions
- Created `AIChatApiKeyNotConfiguredMessage` - shows configuration
guidance with docs link
- Created `AIChatErrorRenderer` - encapsulates error type switching
logic (fixes nested ternary)
- Created `AIChatStandaloneError` - displays errors when there are no
messages
- Split `aiChatErrorUtils.ts` into separate files (1 export per file):
  - `AIChatErrorCode.ts`
  - `extractErrorCode.ts`
  - `isAIChatErrorOfType.ts`
  - `isBillingCreditsExhaustedError.ts`
  - `isApiKeyNotConfiguredError.ts`
- Added comprehensive test coverage (27 tests)

### Other
- Updated trial period banner messaging

## Testing
- All lint checks pass
- All 27 new tests pass
- TypeScript typecheck passes
2025-12-24 15:30:28 +01:00
EtienneandGitHub bc0ffc98bb Billing - fixes and updates (#16796)
Improvements :
- phase 2 date calculation issue
- quantity update issue
- unnecessary phase creation - schedule should be created only when a
next phase is planned
2025-12-24 14:18:06 +00:00
37e59d0cf1 i18n - translations (#16798)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-24 14:49:45 +01:00
martmullandGitHub 158a7a89d5 1859 extensibility improve application settings section (#16786)
## After
<img width="934" height="750" alt="image"
src="https://github.com/user-attachments/assets/f2d7f743-fa4f-4e7d-a060-033f6087e4b6"
/>
<img width="1008" height="652" alt="image"
src="https://github.com/user-attachments/assets/3d36bfae-aa30-4946-88f2-e99bf074f768"
/>
2025-12-24 14:35:36 +01:00
2eb8cf9e81 i18n - docs translations (#16793)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-24 14:28:34 +01:00
Brian PursleyandGitHub 766822d04b Fix dashboard drag error (#16731)
Fixes https://github.com/twentyhq/twenty/issues/16730
2025-12-24 11:16:47 +01:00
1cd413834d i18n - docs translations (#16791)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-24 08:40:04 +01:00
Félix MalfaitandGitHub b27a97f2c5 feat: enforce @/ alias for imports and fix all relative parent imports (#16787)
## Summary
This PR enforces the use of `@/` alias for imports instead of relative
parent imports (`../`).

## Changes

### ESLint Configuration
- Added `no-restricted-imports` pattern in `eslint.config.react.mjs` to
block `../*` imports with the message "Relative parent imports are not
allowed. Use @/ alias instead."
- Removed the non-working `import/no-relative-parent-imports` rule
(doesn't work properly in ESLint flat config)

### VS Code Settings
- Added `javascript.preferences.importModuleSpecifier: non-relative` to
`.vscode/settings.json` (TypeScript setting was already there)

### Code Fixes
- Fixed **941 relative parent imports** across **706 files** in
`packages/twenty-front`
- All `../` imports converted to use `@/` alias

## Why
- Consistent import style across the codebase
- Easier to move files without breaking imports
- Better IDE support for auto-imports
- Clearer understanding of where imports come from
2025-12-23 22:57:51 +01:00
781b96e80b i18n - docs translations (#16790)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-23 21:18:37 +01:00
17e923b908 i18n - translations (#16788)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-23 19:01:31 +01:00
Lucas BordeauandGitHub 0b5be7caa3 Refactored Date to Temporal in critical date zones (#16544)
Fixes https://github.com/twentyhq/twenty/issues/16110

This PR implements Temporal to replace the legacy Date object, in all
features that are time zone sensitive. (around 80% of the app)

Here we define a few utils to handle Temporal primitives and obtain an
easier DX for timezone manipulation, front end and back end.

This PR deactivates the usage of timezone from the graph configuration,
because for now it's always UTC and is not really relevant, let's handle
that later.

Workflows code and backend only code that don't take user input are
using UTC time zone, the affected utils have not been refactored yet
because this PR is big enough.

# New way of filtering on date intervals

As we'll progressively rollup Temporal everywhere in the codebase and
remove `Date` JS object everywhere possible, we'll use the way to filter
that is recommended by Temporal.

This way of filtering on date intervals involves half-open intervals,
and is the preferred way to avoid edge-cases with DST and smallest time
increment edge-case.

## Filtering endOfX with DST edge-cases

Some day-light save time shifts involve having no existing hour, or even
day on certain days, for example Samoa Islands have no 30th of December
2011 : https://www.timeanddate.com/news/time/samoa-dateline.html, it
jumps from 29th to 31st, so filtering on `< next period start` makes it
easier to let the date library handle the strict inferior comparison,
than filtering on `≤ end of period` and trying to compute manually the
end of the period.

For example for Samoa Islands, is end of day `2011-12-29T23:59:59.999`
or is it `2011-12-30T23:59:59.999` ? If you say I don't need to know and
compute it, because I want everything strictly before
`2011-12-29T00:00:00 + start of next day (according to the library which
knows those edge-cases)`, then you have a 100% deterministic way of
computing date intervals in any timezone, for any day of any year.

Of course the Samoa example is an extreme one, but more common ones
involve DST shifts of 1 hour, which are still problematic on certain
days of the year.

## Computing the exact _end of period_

Having an open interval filtering, with `[included - included]` instead
of half-open `[included - excluded)`, forces to compute the open end of
an interval, which often involves taking an arbitrary unit like minute,
second, microsecond or nanosecond, which will lead to edge-case of
unhandled values.

For example, let's say my code computes endOfDay by setting the time to
`23:59:59.999`, if another library, API, or anything else, ends up
giving me a date-time with another time precision `23:59:59.999999999`
(down to the nanosecond), then this date-time will be filtered out,
while it should not.

The good deterministic way to avoid 100% of those complex bugs is to
create a half-open filter :

`≥ start of period` to `< start of next period` 

For example : 

`≥ 2025-01-01T00:00:00` to `< 2025-01-02T00:00:00` instead of `≥
2025-01-01T00:00:00` to `≤ 2025-01-01T23:59:59.999`

Because, `2025-01-01T00:00:00` = `2025-01-01T00:00:00.000` =
`2025-01-01T00:00:00.000000` = `2025-01-01T00:00:00.000000000` => no
risk of error in computing start of period

But `2025-01-01T23:59:59` ≠ `2025-01-01T23:59:59.999` ≠
`2025-01-01T23:59:59.999999` ≠ `2025-01-01T23:59:59.999999999` =>
existing risk of error in computing end of period

This is why an half-open interval has no risk of error in computing a
date-time interval filter.

Here is a link to this debate :
https://github.com/tc39/proposal-temporal/issues/2568

> For this reason, we recommend not calculating the exact nanosecond at
the end of the day if it's not absolutely necessary. For example, if
it's needed for <= comparisons, we recommend just changing the
comparison code. So instead of <= zdtEndOfDay your code could be <
zdtStartOfNextDay which is easier to calculate and not subject to the
issue of not knowing which unit is the right one.
>
> [Justin Grant](https://github.com/justingrant), top contributor of
Temporal

## Application to our codebase

Applying this half-open filtering paradigm to our codebase means we
would have to rename `IS_AFTER` to `IS_AFTER_OR_EQUAL` and to keep
`IS_BEFORE` (or even `IS_STRICTLY_BEFORE`) to make this half-open
interval self-explanatory everywhere in the codebase, this will avoid
any confusion.

See the relevant issue :
https://github.com/twentyhq/core-team-issues/issues/2010

In the mean time, we'll keep this operand and add this semantic in the
naming everywhere possible.

## Example with a different user timezone 

Example on a graph grouped by week in timezone Pacific/Samoa, on a
computer running on Europe/Paris :

<img width="342" height="511" alt="image"
src="https://github.com/user-attachments/assets/9e7d5121-ecc4-4233-835b-f59293fbd8c8"
/>

Then the associated data in the table view, with our **half-open
date-time filter** :

<img width="804" height="262" alt="image"
src="https://github.com/user-attachments/assets/28efe1d7-d2fc-4aec-b521-bada7f980447"
/>

And the associated SQL query result to see how DATE_TRUNC in Postgres
applies its internal start of week logic :

<img width="709" height="220" alt="image"
src="https://github.com/user-attachments/assets/4d0542e1-eaae-4b4b-afa9-5005f48ffdca"
/>

The associated SQL query without parameters to test in your SQL client :

```SQL
SELECT "opportunity"."closeDate" as "close_date", TO_CHAR(DATE_TRUNC('week', "opportunity"."closeDate", 'Pacific/Samoa') AT TIME ZONE 'Pacific/Samoa', 'YYYY-MM-DD') AS "DATE_TRUNC by week start in timezone Pacific/Samoa", "opportunity"."name" FROM "workspace_1wgvd1injqtife6y4rvfbu3h5"."opportunity" "opportunity" ORDER BY "opportunity"."closeDate" ASC NULLS LAST
```

# Date picker simplification (not in this PR)

Our DatePicker component, which is wrapping `react-datepicker` library
component, is now exposing plain dates as string instead of Date object.
The Date object is still used internally to manage the library
component, but since the date picker calendar is only manipulating plain
dates, there is no need to add timezone management to it, and no need to
expose a handleChange with Date object.

The timezone management relies on date time inputs now.

The modification has been made in a previous PR :
https://github.com/twentyhq/twenty/issues/15377 but it's good to
reference it here.

# Calendar feature refactor

Calendar feature has been refactored to rely on Temporal.PlainDate as
much as possible, while leaving some date-fns utils to avoid re-coding
them.

Since the trick is to use utils to convert back and from Date object in
exec env reliably, we can do it everywhere we need to interface legacy
Date object utils and Temporal related code.

## TimeZone is now shown on Calendar :

<img width="894" height="958" alt="image"
src="https://github.com/user-attachments/assets/231f8107-fad6-4786-b532-456692c20f1d"
/>

## Month picker has been refactored 

<img width="503" height="266" alt="image"
src="https://github.com/user-attachments/assets/cb90bc34-6c4d-436d-93bc-4b6fb00de7f5"
/>

Since the days weren't useful, the picker has been refactored to remove
the days.

# Miscellaneous 
- Fixed a bug with drag and drop edge-case with 2 items in a list.

# Improvements 

## Lots of chained operations
It would be nice to create small utils to avoid repeated chained
operations, but that is how Temporal is designed, a very small set of
primitive operations that allow to compose everything needed. Maybe
we'll have wrappers on top of Temporal in the coming years.

## Creation of Temporal objects is throwing errors

If the input is badly formatted Temporal will throw, we might want to
adopt a global strategy to avoid that.

Example : 

```ts
const newPlainDate = Temporal.PlainDate.from('bad-string'); // Will throw
```
2025-12-23 17:40:26 +00:00
Félix Malfait 4d5d2233bc fix: update date-utils test to expect French translation
Lingui translations work correctly for plural() macro,
so the short format returns French 'an' not English 'year'
2025-12-23 17:32:43 +01:00
e3757f300a i18n - docs translations (#16779)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-23 17:06:38 +01:00
Raphaël BosiandGitHub 1bc344c6fa [DASHBOARDS] Fix filter parsing (#16782)
## Fix filter parsing for charts

Fixes https://github.com/twentyhq/twenty/issues/16606
Fixes https://github.com/twentyhq/private-issues/issues/396

When clicking on a chart slice/bar grouped by certain field types, the
filter value was passed as a plain string instead of a JSON array,
causing a JSON parse error on navigation.

This happens because `arrayOfStringsOrVariablesSchema` in the filter
parsing logic expects JSON array format for certain field types, but the
values weren't wrapped correctly for all cases.

Extracted the util `formatChartFilterValue` and renamed it to
`serializeChartBucketValueForFilter` and modified it to handle JSON
array wrapping for:
- CURRENCY fields with currencyCode subfield (IS operand)
- MULTI_SELECT fields (CONTAINS operand)
- ADDRESS fields with addressCountry subfield (CONTAINS operand)

Added unit tests for the new utility

### Before


https://github.com/user-attachments/assets/9a52572b-e896-445a-9f5c-e21963f78441

### After


https://github.com/user-attachments/assets/12eed5e5-a49c-4557-a45c-ac7e00b3422a
2025-12-23 17:00:38 +01:00
b1aaf21356 i18n - translations (#16784)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-23 16:47:52 +01:00
Raphaël BosiandGitHub 19e77f9dd7 [DASHBOARDS] Update iFrame error message (#16777)
`Invalid URL` instead of `no data` for iFrame widgets.

<img width="1142" height="638" alt="CleanShot 2025-12-23 at 14 13 17@2x"
src="https://github.com/user-attachments/assets/22621e57-c4ba-4e1f-91d0-5c4ef435c649"
/>
2025-12-23 15:33:55 +00:00
67f511bae3 i18n - translations (#16776)
Created by Github action

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Broad i18n refresh touching email and front-end locales, with
new/updated strings and some path/key adjustments.
> 
> - Adds "Updates" settings page strings (e.g., `Updates`, `Early
access`, `Read changelog`, "Check out our latest releases") and
removes/replaces prior "Releases/Changelog" entries
> - Introduces chart color palette label (`Default palette`) and page
layout field widget messages (`No field configured`, `Select a field to
display…`, `No related records`)
> - Updates locale files for many languages (af-ZA, ar-SA, ca-ES, cs-CZ,
da-DK, de-DE, el-GR, es-ES, fi-FI, aa-ER) with new or corrected
translations and component path changes
> - Email (vi-VN): adjusts generated translations; leaves some strings
untranslated and clears one obsolete translation in `vi-VN.po`
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
0246b729af. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
Co-authored-by: github-actions <github-actions@twenty.com>
Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2025-12-23 14:32:25 +01:00
3dd858c91e i18n - docs translations (#16774)
Created by Github action

Pulls the latest documentation translations from Crowdin for all
supported languages:
- French (fr)
- Arabic (ar)  
- Czech (cs)
- German (de)
- Spanish (es)
- Italian (it)
- Japanese (ja)
- Korean (ko)
- Portuguese (pt)
- Romanian (ro)
- Russian (ru)
- Turkish (tr)
- Chinese (zh-CN)

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-23 14:26:11 +01:00
Raphaël BosiandGitHub 7b6071619c Refactor command menu input (#16773)
- Open input on item click
- `CommandMenuItemNumberInput` and `CommandMenuItemTextInput` don't only
define the input but the whole menu item now
- Fixed behavior on escape

## Video QA


https://github.com/user-attachments/assets/bf2f03e9-d07c-4a1e-9bc8-6606839269ff
2025-12-23 14:00:04 +01:00
Abdul RahmanandGitHub 81918e8720 Increase hover target area for workflow node dots (#16750)
Closes #14137 



https://github.com/user-attachments/assets/99f756be-ff8e-47ed-98fc-8672c2522d8f
2025-12-23 11:49:52 +01:00
Abdul RahmanandGitHub 42ad4630ea Auto-focus workflow title field when creating new workflow (#16765)
Closes #14135 



https://github.com/user-attachments/assets/4170c33d-4a2e-450a-98c0-20163d4b2382
2025-12-23 11:36:23 +01:00
Lucky GoyalandGitHub 1dbb326fd6 fix: prevent workflow step title from transferring between steps. (#16762)
fixes (#16754)

Solution:
Add key prop to CommandMenuWorkflowStepInfo to force React to remount
the component when switching between steps, ensuring fresh state.



https://github.com/user-attachments/assets/77f51f5b-6b25-4c05-aaf7-8704ab8bee0f
2025-12-23 10:35:53 +01:00
Félix MalfaitandGitHub c2c8f6e41c fix: prevent API keys from creating UNLISTED views (#16770)
## Summary
UNLISTED views are personal views tied to a specific user, so API keys
should not be able to create them.

## Changes
- Added check in `canUserCreateView` to block API keys from creating
UNLISTED views
- Refactored the service to use smaller functions with early returns (no
nested if/else)

## Behavior Matrix

### Creating Views
| Caller | Visibility | Has VIEWS Permission | Result |
|--------|------------|---------------------|--------|
| User | UNLISTED | (not checked) |  Allow |
| User | WORKSPACE | Yes |  Allow |
| User | WORKSPACE | No |  Denied |
| **API Key** | **UNLISTED** | (not checked) | ** Denied** |
| API Key | WORKSPACE | Yes |  Allow |
| API Key | WORKSPACE | No |  Denied |
2025-12-23 10:13:00 +01:00
Abdul RahmanandGitHub ba76cf4fed Fix: Record label identifier setting not saving on first attempt (#16769) 2025-12-23 09:17:31 +01:00
eeegggandGitHub 65dced14ff fix: enable API key management of workspace views + fix permission bypass vulnerability (#16768)
Fixes #16739

- Remove empty string coercion in createCoreView that caused PostgreSQL
UUID errors for API keys
- Add permission check allowing API keys with VIEWS permission to manage
workspace views they created

API keys with 'Manage Views' permission can now create, update, and
delete workspace views via both GraphQL and REST APIs.
2025-12-23 09:06:47 +01:00
79998ef8fc Allow creation date import (#16764)
PR for #15313 

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Enables importing timestamp fields that were previously filtered out.
> 
> - Removes explicit exclusions of `createdAt` and `updatedAt` in
`spreadsheetImportFilterAvailableFieldMetadataItems`
> - Keeps existing constraints: only active fields, system fields
limited (except `id`), exclude `deletedAt`, and only allow `RELATION`
fields that are `MANY_TO_ONE`; sorting unchanged
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
a2b36e4cc0. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2025-12-23 08:05:01 +00:00
99d5aa2589 i18n - docs translations (#16767)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-23 01:40:21 +01:00
c6ea7ae288 Allow custom fields to be editable for system objects and prevent the error for timeline activity on system object pages. (#16268)
Solves #16015 

- Added a check in `useTimelineActivities.ts` to see if the system
object page we're viewing has timelineActivity being tracked before
querying to get the activity history.
- Removed @WorkspaceIsObjectUIReadOnly decorator from system objects and
added @WorkspaceIsFieldUIReadOnly to standard and system fields to allow
custom field edits as requested in the issue.
- Did not add calendarEvents or other system objects to timelineActivity
just yet since keeping track of timeline activity for every one of them
felt counter-intuitive and bloated. In order to determine which objects
need timelineActivity, I think we need to fix the broken views of system
objects first, such as the one in the attached screenshots - a good
number of them are broken. The check I added to
`useTimelineActivities.ts` hook displays timeline activity as empty for
the time - error would not be shown as suggested by Thomas.

<img width="1062" height="858" alt="image"
src="https://github.com/user-attachments/assets/e877e0fe-b665-46e3-b785-e84f2af7f833"
/>

<br />

<img width="1061" height="858" alt="image"
src="https://github.com/user-attachments/assets/0eba8c1c-444a-4b13-beda-64b95cf39077"
/>

- Editing custom fields on calendar events (and other objects without
position fields) crashed with TypeError: Cannot convert undefined or
null to object in sortCachedObjectEdges. This happened because some
cached queries had empty orderBy arrays ([]), and the optimistic effect
tried to sort with them. Objects without position fields returned
empty orderBy arrays when there were no sorts, while objects with
position fields automatically got [{ position: 'AscNullsFirst' }].
The backend always adds { id: 'AscNullsFirst' } as a fallback, but
the frontend didn't match this. So, I added { id: 'AscNullsFirst' } to
the Frontend as default orderBy when there are no sorts and no position
field.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Apply per-field UI read-only to system/standard fields and skip
timeline activity fetching when the target object isn’t related; refine
record-table cell open/navigation behavior.
> 
> - Server: Replace object-level UI read-only with per-field
`isUIReadOnly` across many standard objects (e.g., `calendarEvent`,
`workspaceMember`, messaging, calendar, favorites, attachments,
workflows, etc.), and mirror this via `@WorkspaceIsFieldUIReadOnly` on
workspace entities.
> - Frontend: In `useTimelineActivities.ts`, check object metadata for a
relation to `timelineActivity` and `skip` the query when absent,
preventing errors on system object pages.
> - Frontend: Simplify/adjust record-table cell logic—remove unused
args, allow navigation from first column when non-empty, block editing
for read-only records (while still allowing navigation), and update
button handlers/hover styles accordingly.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
dac1262d70. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2025-12-22 22:22:30 +00:00
5003fc4196 i18n - docs translations (#16761)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-22 19:22:30 +01:00
StephanieJoly4andGitHub 60897b255a Adding one How To article to the workflow section (#16760)
- added an image, one article
- updated the 2 files under the Navigation folder but not the docs.json
- no need to redirect the links given this is a new article
2025-12-22 19:10:54 +01:00
Félix MalfaitandGitHub 0dec4b9b67 docs: add IS_MULTIWORKSPACE_ENABLED documentation (#16758)
## Summary

Adds comprehensive documentation for the `IS_MULTIWORKSPACE_ENABLED`
configuration variable, which was previously undocumented despite being
a fundamental configuration option that significantly changes how Twenty
behaves.

## Changes

### Self-Host Setup Guide (`setup.mdx`)

Added a new **Multi-Workspace Mode** section that explains:

- **Single-workspace mode (default)**: Only one workspace allowed, first
user gets admin privileges, signups disabled after first workspace
- **Multi-workspace mode**: Multiple workspaces with subdomain-based
URLs (e.g., `sales.your-domain.com`)
- **Related config variables**: `DEFAULT_SUBDOMAIN` and
`IS_WORKSPACE_CREATION_LIMITED_TO_SERVER_ADMINS`
- **DNS configuration**: Wildcard DNS setup for dynamic subdomains
- **Workspace creation restrictions**: How to limit workspace creation
to server admins

### Local Setup Guide (`local-setup.mdx`)

Added an info callout in the environment variables section to make
contributors aware of multi-workspace mode, useful when testing
subdomain-based features.

## Why This Matters

The `IS_MULTIWORKSPACE_ENABLED` variable controls:
- Whether multiple workspaces can exist on a single instance
- URL structure (plain domain vs subdomains)
- First user privileges
- Sign-up behavior after initial setup
- SSO workspace resolution logic

This is critical knowledge for self-hosters who want to run Twenty as a
multi-tenant SaaS.
2025-12-22 18:10:41 +01:00
Félix Malfait 6a31f0667e fix: remove invalid crowdin flag 2025-12-22 17:43:27 +01:00
Félix Malfait 354c43988d fix(i18n): allow updating existing docs files in Crowdin
- Add upload_sources_args: '--update-strings' to update existing files
- Remove duplicate steps in workflow
2025-12-22 17:38:34 +01:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
cf51baedae Bump tsx from 4.20.5 to 4.21.0 (#16738)
Bumps [tsx](https://github.com/privatenumber/tsx) from 4.20.5 to 4.21.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/privatenumber/tsx/releases">tsx's
releases</a>.</em></p>
<blockquote>
<h2>v4.21.0</h2>
<h1><a
href="https://github.com/privatenumber/tsx/compare/v4.20.6...v4.21.0">4.21.0</a>
(2025-11-30)</h1>
<h3>Features</h3>
<ul>
<li>upgrade esbuild (<a
href="https://redirect.github.com/privatenumber/tsx/issues/748">#748</a>)
(<a
href="https://github.com/privatenumber/tsx/commit/048fb623870f22c5026ad84187b545d418d2dfe8">048fb62</a>)</li>
</ul>
<hr />
<p>This release is also available on:</p>
<ul>
<li><a href="https://www.npmjs.com/package/tsx/v/4.21.0"><code>npm
package (@​latest dist-tag)</code></a></li>
</ul>
<h2>v4.20.6</h2>
<h2><a
href="https://github.com/privatenumber/tsx/compare/v4.20.5...v4.20.6">4.20.6</a>
(2025-09-26)</h2>
<h3>Bug Fixes</h3>
<ul>
<li>properly hide relaySignal from process.listeners() (<a
href="https://redirect.github.com/privatenumber/tsx/issues/741">#741</a>)
(<a
href="https://github.com/privatenumber/tsx/commit/710a42473ebfdff362818bed4fd1f5c7a27837e2">710a424</a>)</li>
</ul>
<hr />
<p>This release is also available on:</p>
<ul>
<li><a href="https://www.npmjs.com/package/tsx/v/4.20.6"><code>npm
package (@​latest dist-tag)</code></a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/privatenumber/tsx/commit/f6284cd50575ce6e8d110f63266d66cb9cde3b88"><code>f6284cd</code></a>
ci: lock in semantic-release v24</li>
<li><a
href="https://github.com/privatenumber/tsx/commit/048fb623870f22c5026ad84187b545d418d2dfe8"><code>048fb62</code></a>
feat: upgrade esbuild (<a
href="https://redirect.github.com/privatenumber/tsx/issues/748">#748</a>)</li>
<li><a
href="https://github.com/privatenumber/tsx/commit/710a42473ebfdff362818bed4fd1f5c7a27837e2"><code>710a424</code></a>
fix: properly hide relaySignal from process.listeners() (<a
href="https://redirect.github.com/privatenumber/tsx/issues/741">#741</a>)</li>
<li><a
href="https://github.com/privatenumber/tsx/commit/20b91c44bbb00006f182fee3b0bcfc55aaec6e44"><code>20b91c4</code></a>
docs: make sponsors dynamic</li>
<li><a
href="https://github.com/privatenumber/tsx/commit/08dcd59a3a05774897a641a943702ca4b47192e0"><code>08dcd59</code></a>
chore: move vercel settings to root</li>
<li>See full diff in <a
href="https://github.com/privatenumber/tsx/compare/v4.20.5...v4.21.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=tsx&package-manager=npm_and_yarn&previous-version=4.20.5&new-version=4.21.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-22 17:35:42 +01:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
5b69173c44 Bump ts-loader from 9.5.1 to 9.5.4 (#16737)
Bumps [ts-loader](https://github.com/TypeStrong/ts-loader) from 9.5.1 to
9.5.4.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/TypeStrong/ts-loader/releases">ts-loader's
releases</a>.</em></p>
<blockquote>
<h2>v9.5.4</h2>
<ul>
<li><a
href="https://redirect.github.com/TypeStrong/ts-loader/pull/1676">chore:
typescript 5.9 upgrade</a> - thanks <a
href="https://github.com/johnnyreilly"><code>@​johnnyreilly</code></a></li>
</ul>
<p>Skipping 9.5.3 due to a publishing issue</p>
<h2>v9.5.3</h2>
<ul>
<li><a
href="https://redirect.github.com/TypeStrong/ts-loader/pull/1665">fix:
add more detailed error messages</a> - thanks <a
href="https://github.com/hai-x"><code>@​hai-x</code></a></li>
</ul>
<h2>v9.5.2</h2>
<ul>
<li><a
href="https://redirect.github.com/TypeStrong/ts-loader/pull/1665">fix:
add more detailed error messages</a> - thanks <a
href="https://github.com/hai-x"><code>@​hai-x</code></a></li>
</ul>
<p><em>This release is actually v9.5.2 but due to a problem with the
initial release workflow we incremented to v9.5.3</em></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/TypeStrong/ts-loader/blob/main/CHANGELOG.md">ts-loader's
changelog</a>.</em></p>
<blockquote>
<h2>9.5.4</h2>
<ul>
<li><a
href="https://redirect.github.com/TypeStrong/ts-loader/pull/1676">chore:
typescript 5.9 upgrade</a> - thanks <a
href="https://github.com/johnnyreilly"><code>@​johnnyreilly</code></a></li>
</ul>
<p>Skipping 9.5.3 due to a publishing issue</p>
<h2>9.5.2</h2>
<ul>
<li><a
href="https://redirect.github.com/TypeStrong/ts-loader/pull/1665">fix:
add more detailed error messages</a> - thanks <a
href="https://github.com/hai-x"><code>@​hai-x</code></a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/f7d022f79d1dae3c0c07ee63ec63c697eb99b32a"><code>f7d022f</code></a>
Update changelog for version 9.5.4 (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1677">#1677</a>)</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/ba825c2520383072cedd66130ab490c5e6bc8f4e"><code>ba825c2</code></a>
chore: TypeScript 5.9 upgrade (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1676">#1676</a>)</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/847a24936aa12fa18dab21ca8ec37595cadc72c6"><code>847a249</code></a>
feat: stub for 5.8 (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1668">#1668</a>)</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/0ee403558eeddfcb912c5ed9d8f6224210f6c477"><code>0ee4035</code></a>
feat: Update push.yml with workflow_dispatch</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/d7352989b8edda7b6ae80a89c4351c27643d4927"><code>d735298</code></a>
chore: update lockfile (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1666">#1666</a>)</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/e652315ddee8b82b38e7aa9d0ce7f179e281377e"><code>e652315</code></a>
fix: add more detailed error messages (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1665">#1665</a>)</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/36b6bf24c6ccbffce43565bc09f4b08b9ea5f5f6"><code>36b6bf2</code></a>
Upgrade TypeScript to 5.7 (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1661">#1661</a>)</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/6a4e29c729fd6727c1c625fad3a65d509c2c37eb"><code>6a4e29c</code></a>
Create SECURITY.md</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/5379bb1fc4c4ea53b14a2c2ba88154fedb7de11e"><code>5379bb1</code></a>
Update testpack for TypeScript 5.6 (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1656">#1656</a>)</li>
<li><a
href="https://github.com/TypeStrong/ts-loader/commit/95110c67b97aa8c60c86485064fb35a85def2819"><code>95110c6</code></a>
Ts 55 (<a
href="https://redirect.github.com/TypeStrong/ts-loader/issues/1651">#1651</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/TypeStrong/ts-loader/compare/v9.5.1...v9.5.4">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=ts-loader&package-manager=npm_and_yarn&previous-version=9.5.1&new-version=9.5.4)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-22 17:35:26 +01:00
Félix MalfaitandGitHub e6491d6a80 feat(i18n): fix translation QA issues and add automation (#16756)
## Summary

This PR fixes translation QA issues and adds automation to prevent
future issues.

### Translation Fixes
- Fixed **escaped Unicode sequences** in translations (e.g.,
`\u62db\u5f85` → `招待`)
- Removed **corrupted control characters** from .po files (null bytes,
invalid characters)
- Fixed **missing/incorrect placeholders** in various languages
- Deleted **35 problematic translations** via Crowdin API that had
variable mismatches

### New Scripts (in `packages/twenty-utils/`)
- `fix-crowdin-translations.ts` - Auto-fixes encoding issues and syncs
to Crowdin
- `fix-qa-issues.ts` - Fixes specific QA issues via Crowdin API
- `translation-qa-report.ts` - Generates weekly QA report from Crowdin
API

### New Workflow
- `i18n-qa-report.yaml` - Weekly workflow that creates a PR with
translation QA issues for review

### Other Changes
- Moved GitHub Actions from `.github/workflows/actions/` to
`.github/actions/`
- Fixed `date-utils.ts` to avoid nested `t` macros in plural expressions
(root cause of confusing placeholders)

### QA Status After Fixes
| Category | Count | Status |
|----------|-------|--------|
| variables | 0  | Fixed |
| tags | 1 | Minor |
| empty | 0  | Fixed |
| spaces | 127 | Low priority |
| numbers | 246 | Locale-specific |
| special_symbols | 268 | Locale-specific |
2025-12-22 17:30:46 +01:00
Abdullah.andGitHub ede261abf4 fix: storybook manager bundle may expose environment variables during build (#16747)
Resolves [Dependabot Alert
348](https://github.com/twentyhq/twenty/security/dependabot/348).

Updated the patch version - 8.6.14 to 8.6.15.
2025-12-22 16:53:52 +01:00
Baptiste DevessierandGitHub 1324ad1ee3 Edit simple values in Field widget (#16749)
https://github.com/user-attachments/assets/116b8259-b366-47bf-8068-b5276b138e03
2025-12-22 14:21:39 +00:00
martmullandGitHub bb73cbc380 1774 extensibility v1 create an exhaustive documentation readme or dedicated section in twenty contributing doc (#16751)
As title

<img width="1108" height="894" alt="image"
src="https://github.com/user-attachments/assets/e2dc7e12-72e3-4ca3-ac7b-a94de547f82a"
/>
2025-12-22 15:19:11 +01:00
MarieandGitHub 50b0665c44 Enable read on replica for all (#16740)
Removing the feature flag to enable read on replica for all workspaces.
It will still be possible to toggle off the feature by removing the env
variable `PG_DATABASE_REPLICA_URL`.
2025-12-22 14:32:04 +01:00
Abdullah.andGitHub 869608327e feat: validator is vulnerable to incomplete filtering of one or more instances of special elements (#16748)
Resolves [Dependabot Alert
336](https://github.com/twentyhq/twenty/security/dependabot/336).

Used `yarn up validator --recursive` since minor version upgrades are
allowed by definition of packages.
2025-12-22 14:28:38 +01:00
Félix MalfaitandGitHub ea6d497c3b fix(docs): configure target languages in crowdin.yml (#16745)
## Summary
Fixes the Crowdin GitHub Action failure by properly configuring target
languages.

## Problem
The previous PR (#16744) used `download_language` parameter, but that
only accepts a **single language**, not a comma-separated list. This
caused the error:
```
Language 'fr,ar,cs,de,es,it,ja,ko,pt,ro,ru,tr,zh-CN' doesn't exist in the project
```

## Solution
- Added `languages` array to `crowdin.yml` to specify target languages
for download
- Removed the broken `download_language` parameter from the workflow

The languages list matches `supported-languages.ts`:
- fr, ar, cs, de, es, it, ja, ko, pt, ro, ru, tr, zh-CN
2025-12-22 14:03:38 +01:00
4bfc0a79c7 I18n Docs (#16746)
Attempt to fix translations...

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-22 14:03:22 +01:00
0731a616b7 Restore navigation structure from PR #16705 (#16742)
## Summary
The merge conflict resolution from PR #16705 incorrectly discarded the
new documentation structure changes. This PR updates the navigation JSON
files (the correct approach) to restore the intended changes.

## Changes restored
- New 'Capabilities' and 'How-Tos' subgroups organization
- Renamed sections (e.g., 'Getting Started' → 'Discover Twenty')
- New sections: Data Migration, Calendar & Emails, AI, Views &
Pipelines, Dashboards, Permissions & Access, Billing
- Reorganized Developers section with Extend, Self-Host, and Contribute
groups

## Files updated
- `navigation/base-structure.json`
- `navigation/navigation-schema.json`
- `navigation/navigation.template.json`

## Context
PR #16705 was merged but the merge conflict was incorrectly resolved,
causing all the structural changes to be lost. The previous fix (PR
#16741) updated docs.json directly, but the correct approach is to
update the navigation JSON files instead. This PR properly restores
those changes from the final commit of PR #16705
(`c856e0d598a0056c2bdaf528502e08261daf7c7c`).

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-22 13:29:25 +01:00
Félix MalfaitandGitHub df3d34e16b fix(docs): only download translations for supported languages (#16744)
## Summary
The Crowdin GitHub Action was failing at ~54% progress with the error:
> Failed to build translation. Please contact our support team for help

## Root Cause
The build was attempting to process all target languages configured in
Crowdin, including languages not supported by Mintlify (as defined in
`supported-languages.ts`). Some of these unsupported languages had
translation issues causing the build to fail.

## Fix
Added the `download_language` parameter to the Crowdin GitHub Action to
restrict downloads to only the languages supported by Mintlify:
- fr, ar, cs, de, es, it, ja, ko, pt, ro, ru, tr, zh-CN

## Testing
Verified via Crowdin API that builds succeed when specifying only these
supported languages, while the full build fails.
2025-12-22 13:25:11 +01:00
Félix MalfaitandGitHub 57517d687e Restore docs.json user guide structure from PR #16705 (#16741)
## Summary
The merge conflict resolution from PR #16705 incorrectly discarded the
new documentation structure changes. This PR restores the intended
changes.

## Changes restored
- New 'Capabilities' and 'How-Tos' subgroups organization
- Renamed sections (e.g., 'Getting Started' → 'Discover Twenty')
- New sections: Data Migration, Calendar & Emails, AI, Views &
Pipelines, Dashboards, Permissions & Access, Billing
- Reorganized Developers section with API subsection
- URL redirects for SEO and user experience continuity

## Context
PR #16705 was merged but the merge conflict was incorrectly resolved,
causing all the structural changes to be lost. This PR brings back those
changes from the final commit of PR #16705
(`c856e0d598a0056c2bdaf528502e08261daf7c7c`).
2025-12-22 10:45:58 +01:00
StephanieJoly4GitHubcubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>github-actionsAbdul RahmanFélix Malfait
183d034716 User guide structure update (#16705)
Reorganizing by Feature sections

Capabilities folders to give an overview of each feature

How-Tos folders to give guidance for advanced customizations

Reorganized the Developers section as well, moving the API sub section
there

added some new visuals and videos to illustrate the How-Tos articles

checked the typos, the links and added a section at the end of the
doc.json file to redirect existing links to the new ones (SEO purpose +
continuity of the user experience)

What I have not updated is the "l" folder that, per my understanding,
contains the translation of the User Guide - that I only edited in
English

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) is
generating a summary for commit
5301502a32. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@twenty.com>
Co-authored-by: Abdul Rahman <ar5438376@gmail.com>
Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2025-12-22 09:07:06 +01:00
Charles BochetandGitHub 9c49f4ba82 Fix Global workflows not pinned (#16728)
A bug was reported where workflow actions marked as Pinned were actually
not pinned in the top right

In workflow edit:
<img width="400" height="379" alt="image"
src="https://github.com/user-attachments/assets/adea9b4e-c898-4395-8cbf-d21282770fac"
/>

Consequence on Header:
<img width="400" height="53" alt="image"
src="https://github.com/user-attachments/assets/a39e4201-2450-4566-978a-7f464d3a64f0"
/>
2025-12-20 12:29:45 +01:00
Baptiste DevessierandGitHub 9984981e82 Field widget edit relations (#16714)
- Let the user edit their relations
- Create a `useCurrentWidget` that returns the widget information in the
context of a rendered widget. Relies on a component instance context.


https://github.com/user-attachments/assets/e908364f-2d53-4adb-97a1-4d950f51976a

Follow up:

- Show pen button for all Field widgets
2025-12-19 21:21:00 +01:00
f9744ef245 i18n - docs translations (#16721)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-19 19:22:08 +01:00
Thomas TrompetteandGitHub 9aa77ab991 Fix composite upsert (#16718)
Doing an upsert on existing value, composite field not updated properly.

```
Input: {
  id: "08ca34fe-fc39-474f-adac-4d89f844e922",
  name: "tom",
  linkedinLink: {
    primaryLinkUrl: "https://www.linkedin.com/in/etienneyaouni1982",
    primaryLinkLabel: "etienne",
    secondaryLinks: null,
  },
}
```

Building `overwrites` for upsert forgets `linkedinLink` because column
names are not flattened yet.
We don't want to call formatData yet on the input, because this is
heavy.

Overriding `overwrites` on execute.
2025-12-19 18:28:28 +01:00
neo773andGitHub 0849dda153 Gmail error handling fixes (#16719)
- Replaced direct instance checks for GaxiosError with a utility
function isGmailApiError for better error handling consistency across
services.
-  Debug logs
2025-12-19 18:23:14 +01:00
neo773andGitHub d30580fc4e remove IMAP_SMTP_CALDAV feature flag (#16695)
To be merged after 
https://github.com/twentyhq/twenty/pull/16479
https://github.com/twentyhq/twenty/pull/16694
2025-12-19 18:20:12 +01:00
Thomas TrompetteandGitHub 6355557356 [POC] Real-Time (#16633)
https://github.com/user-attachments/assets/3ad7a4f3-d08b-4a1c-b3c2-bb42ef9f3575

Real time POC.

Next steps:
- find out the correct API for subscription. Should be triggered
directly in query hooks (useFindManyRecords, useLazy...)
- improve query matching
2025-12-19 07:17:02 -10:00
b587cde216 i18n - translations (#16720)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-19 18:02:03 +01:00
neo773andGitHub 024ee152a0 Add useUpdateManyRecords hook and message folders sync status mutation (#16694)
- Added new `useUpdateManyRecords` hook for batch record updates with
optimistic cache updates
- Added `updateMessageFoldersSyncStatus` hook for managing message
folder sync state
- Redesigned Message Folders List with BreadCrumb and Animations
2025-12-19 17:22:59 +01:00
a19b9e1cb8 i18n - docs translations (#16717)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-19 17:22:06 +01:00
abe774da15 Message folders optimization (#16479)
- Batch Gmail API calls using `googleapis-batcher` for folder processing
  - Add concurrency limit for Microsoft Graph folder processing 
- Skip IMAP folder sync when no new messages (checks UIDVALIDITY/MODSEQ)
- Refactored `syncMessageFolders` to return folder state directly,
avoiding extra DB round-trips
- Refactored `processPendingFolderActions` to reuse state instead of
querying DB again
  - Add unique index on message folders entity

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-19 17:04:48 +01:00
martmullandGitHub 57dc1ae6e8 Fix create twenty app template (#16708)
Adds a default function role to scaffolded application
2025-12-19 16:40:12 +01:00
Abdullah.andGitHub 936b803cba fix: auth0/node-jws improperly verifies HMAC signature (#16712)
Resolves [Dependabot Alert
339](https://github.com/twentyhq/twenty/security/dependabot/339),
[Dependabot Alert
340](https://github.com/twentyhq/twenty/security/dependabot/340) and
[Dependabot Alert
341](https://github.com/twentyhq/twenty/security/dependabot/341).
2025-12-19 16:27:10 +01:00
Abdullah.andGitHub 964e1a5beb fix: next has a denial of service with server components (#16710)
Resolves the following alert created as a follow up to the previously
merged PR: [Dependabot Alert
351](https://github.com/twentyhq/twenty/security/dependabot/351).
2025-12-19 16:26:47 +01:00
0683ea5e0c i18n - translations (#16711)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-19 16:21:37 +01:00
9a094d8a50 feat: rename Releases settings page to Updates (#16634)
- Rename page title from 'Releases' to 'Updates'
- Rename navigation item label from 'Releases' to 'Updates'
- Remove tabbed interface (Changelog/Lab tabs)
- Add 'Releases' section with external link to changelog
- Add 'Early access' section with lab features
- Add IconTransform to twenty-ui exports
- Delete unused tab-related components and constants

Screenshot:

<img width="2158" height="1698" alt="CleanShot 2025-12-17 at 17 53
46@2x"
src="https://github.com/user-attachments/assets/87ead041-24a7-4afb-9dfc-71e5c20324d6"
/>

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-19 15:39:35 +01:00
Charles Bochet 2eb8006a30 Fix tests 2025-12-19 15:38:10 +01:00
1e47115d0b fix: Next has a denial of service with server components (#16702)
The alerts regarding CVE-2025-55182, CVE-2025-55183, CVE-2025-55184 are
false-positive given Twenty only imported Next 15.2.4 via `react-emails`
as a devDependency, so it should have never made it to the production
build - it was reported due to yarn.lock file containing the version.
However, in order to remove the alerts, updated react-emails to 4.0.17
(latest patch in 4.0 minor release) and Next version it imports to
15.5.9.

[Dependabot Alert
337](https://github.com/twentyhq/twenty/security/dependabot/337),
[Dependabot Alert
343](https://github.com/twentyhq/twenty/security/dependabot/343),
[Dependabot Alert
344](https://github.com/twentyhq/twenty/security/dependabot/344).

Additionally, updated Next 14.2.33 to 14.2.35 to resolve another couple
alerts reported in CVE-2025-55184.

[Dependabot Alert
345](https://github.com/twentyhq/twenty/security/dependabot/345),
[Dependabot Alert
346](https://github.com/twentyhq/twenty/security/dependabot/346).

---------

Co-authored-by: Guillim <guillim@users.noreply.github.com>
2025-12-19 14:36:56 +00:00
Abdul RahmanandGitHub 6dcdf5f4d8 Filter expected errors from sentry (#16642)
Ty!
2025-12-19 15:23:53 +01:00
Charles BochetandGitHub 8d1329953c Refactor upsertRecordsInStore to accept an object with partialRecords (#16707)
Fixes https://github.com/twentyhq/twenty/issues/16624

Original issue:
- while persisting a field (calling useUpdateOne), the response from the
backend is missing the taskTargets many to many (same for note). As we
optimistically update the cache, we lose the "Relations" in the UI
- I'm changing the behavior of useUpsertInRecordStore to accept
recordGqlFields to only update the fields we want in the record store
(this way, we are not losing the targets information in our case)
2025-12-19 15:22:54 +01:00
Abdullah.andGitHub 27ca79be7d fix: nodemailer is vulnerable to DoS through uncontrolled recursion. (#16698)
Resolves [Dependabot Alert
331](https://github.com/twentyhq/twenty/security/dependabot/331),
[Dependabot Alert
332](https://github.com/twentyhq/twenty/security/dependabot/332),
[Dependabot Alert
349](https://github.com/twentyhq/twenty/security/dependabot/349), and
[Dependabot Alert
350](https://github.com/twentyhq/twenty/security/dependabot/350).

Updated Nodemailer and packages dependent on it to use the fixed patch
version (7.0.11).
2025-12-19 15:12:07 +01:00
Raphaël BosiandGitHub 088cd3025a Implement new version of the side panel sub header (#16683)
## Before
<img width="822" height="302" alt="CleanShot 2025-12-18 at 17 08 09@2x"
src="https://github.com/user-attachments/assets/d4d0f783-64f2-4164-9a4d-42c341fa828d"
/>

## After
<img width="836" height="370" alt="CleanShot 2025-12-18 at 17 07 49@2x"
src="https://github.com/user-attachments/assets/aca7a72f-bb83-4e40-89d2-f62bb7c8f053"
/>
2025-12-19 14:31:57 +01:00
Abdul RahmanandGitHub 3dc759bd91 fix: resolve react warning when updating state during render in SettingsPublicDomainsListCard (#16700)
Closes #15154
2025-12-19 13:47:58 +01:00
Paul RastoinandGitHub 6f2ff06a35 Refactor workspace creation (#16689)
# Introduction
Created an env variable to will inject a feature flag during any new
workspace init to be created through v2
2025-12-19 12:47:31 +01:00
32bb69c52f changing location of lint rule (#16703)
rule moved after discussion with @charlesBochet (previous PR was already
merged)

---------

Co-authored-by: Abdullah <125115953+mabdullahabaid@users.noreply.github.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
Co-authored-by: Marie <51697796+ijreilly@users.noreply.github.com>
2025-12-19 10:28:39 +00:00
de907f8c81 fix: mdast-util-to-hast has unsanitized class attribute (#16699)
Resolves [Dependabot Alert
333](https://github.com/twentyhq/twenty/security/dependabot/333).

Used yarn up in recursive mode to bump up version from 13.2.0 to 13.2.1.

---------

Co-authored-by: guillim <guigloo@msn.com>
2025-12-19 10:12:22 +00:00
MarieandGitHub afaf47cdf5 Read some endpoints on replica db (behind feature flag) (#16677)
Next steps: 
- move some workers' activities to replica db
2025-12-19 10:48:18 +01:00
Lucas BordeauandGitHub 1d2aba5b22 Make view bar filter dropdown field select scrollable (#16684)
From PR https://github.com/twentyhq/twenty/pull/16640

Fixes https://github.com/twentyhq/twenty/issues/16637

QA 



https://github.com/user-attachments/assets/e6651309-0b10-4085-ba1f-e8d25bab1aa5
2025-12-19 10:25:36 +01:00
21695d743b i18n - translations (#16692)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 19:22:12 +01:00
Paul RastoinandGitHub 8acfa60412 Fix standard agent and roles deletion command (#16686)
# Introduction
Caught red handed, introduced a failing command in
https://github.com/twentyhq/twenty/pull/16499 that was failing even in
system build which is should not
2025-12-18 19:14:24 +01:00
efc1aa7c83 i18n - translations (#16690)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 18:36:53 +01:00
Baptiste DevessierandGitHub b5ebc44fee Add field widget (#16609)
- Ability to display the details of a field
- The field can be edited (relations edition will be supported later)
- For now, the widget configuration stores the name of the field instead
of its fieldMetadataId. A hook resolves the fieldMetadataId from the
list of fields and the provided name. This will be replaced once we
migrate the configuration to the backend.

## Demo


https://github.com/user-attachments/assets/ab7efbda-66b2-46c1-b641-c350977c31dd

## Remaining to do

- Edition of relations
2025-12-18 17:25:51 +00:00
Thomas TrompetteandGitHub 79a03b8041 Fix ts error resolve rich text (#16688)
As title
2025-12-18 18:00:42 +01:00
4fd79e0c38 i18n - translations (#16687)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 17:53:23 +01:00
Thomas TrompetteGitHubcubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
b2d2babbb9 Add pattern for variable tag in tiptap (#16652)
Since we now store rich text value in blocknote rather than markdown,
variables need to be resolved accordingly.

Replacing the variable tag pattern
`{"type":"variableTag","attrs":\{"variable":"(\{\{[^{}]+\}\})"\}\}` by a
blocknote text `{"type":"text","text":"${escapedText}"}`

Fixes https://github.com/twentyhq/twenty/issues/16583

To test :
- build a workflow that creates a note/ sends an email with a variable
in the body
- make sure the result is properly formatted once run

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2025-12-18 17:24:13 +01:00
636cec0f59 i18n - docs translations (#16685)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 17:22:17 +01:00
Raphaël BosiandGitHub b1320830b5 [DASHBOARDS] Fix settings color palette (#16681)
Before, the settings color palette was hardcoded according to the Figma
design, now we generate it dynamically with the same util used by the
chart so it always corresponds to the same color. Even if we update the
graph color registry, it will be reflected inside the settings.

<img width="1512" height="741" alt="image"
src="https://github.com/user-attachments/assets/fac2d433-62b3-4b00-a362-cebbbe9f8aca"
/>
2025-12-18 17:11:13 +01:00
Paul RastoinandGitHub 38785cd4e9 Refactor seed to use twenty-standard application (#16598)
# Introduction
In this pull-request we introduce a service dedicated to the
twenty-standard app installation, we will later be able to re-use
existing logic to be more generic and allow any app installation.
For the moment sticking to this usage
https://github.com/twentyhq/core-team-issues/issues/1995

## Encountered issues
- We decided not to migrate deprecated fields ( also they will become
custom field for any existing workspace having them in the future )
- duplicate criteria
- wrong search index declaration
- forgotten isSearchable
- Attachement seed
- Restored standardId

## Note
For the moment we're still searching through standardId for code that
run on both existing and new workspaces.
For code running on new workspace exclusively we're searching using
universalIdentifier
We will standardize universalIdentifier usage later when we've migratred
all the existing workspaces

## Workspace creation
Will handle workspace creation the same way in another PR

Related https://github.com/twentyhq/twenty/pull/15065

## TODO
- [ ] Double all frontend hardcoded queries to not refer to deprecated
fields especially attachments
2025-12-18 17:08:55 +01:00
d7fc9387a0 i18n - translations (#16682)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 16:36:39 +01:00
EtienneandGitHub 65f0a5bb18 Billing - fix duplicate key value violates unique constraint "IndexOnActiveSubscriptionPerWorkspace" (#16676)
[Sentry event
example](https://twenty-v7.sentry.io/issues/6606854024/events/4a78b9d1a9d5468e897ec0f90a643112/)


fixes https://github.com/twentyhq/twenty/issues/16573
2025-12-18 15:59:07 +01:00
5984be992d i18n - translations (#16678)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 15:58:15 +01:00
EtienneandGitHub e93187fded Billing - Fix subscription_schedule release (#16669)
At subscription_schedule released, a subscription_schedule.update event
is received in webhook stripe controller but not handled. [Sentry event
example

](https://twenty-v7.sentry.io/issues/6606854024/events/e737c528a55048e5981756a4fad9028f/)

Payload example ⬇️ 
```
{
  "object": {
    "id": "sub_sched_1SfeABHDlIZyMfEDBhgJUCN2",
    "object": "subscription_schedule",
     ....
    "phases": [
      {
        "add_invoice_items": [],
        "application_fee_percent": null,
        "automatic_tax": {
          "disabled_reason": null,
          "enabled": false,
          "liability": null
        },
        "billing_cycle_anchor": null,
        "billing_thresholds": {
          "amount_gte": 10000,
          "reset_billing_cycle_anchor": false
        },
        "collection_method": "charge_automatically",
        "coupon": null,
        "currency": "usd",
        "default_payment_method": null,
        "default_tax_rates": [],
        "description": null,
        "discounts": [],
        "end_date": 1768731003,
        "invoice_settings": {
          "account_tax_ids": null,
          "days_until_due": null,
          "issuer": {
            "type": "self"
          }
        },
        "items": [
          {
            "billing_thresholds": null,
            "discounts": [],
            "metadata": {},
            "plan": "price_1SChAfHDlIZyMfEDCP3pGHHv",
            "price": "price_1SChAfHDlIZyMfEDCP3pGHHv",
            "quantity": 1,
            "tax_rates": []
          },
          {
            "billing_thresholds": null,
            "discounts": [],
            "metadata": {},
            "plan": "price_1SChAaHDlIZyMfEDkGCDIIjm",
            "price": "price_1SChAaHDlIZyMfEDkGCDIIjm",
            "tax_rates": []
          }
        ],
        "metadata": {},
        "on_behalf_of": null,
        "proration_behavior": "none",
        "start_date": 1766053422,
        "transfer_data": null,
        "trial_end": null
      }
    ],
    "released_at": 1768731003,
    "released_subscription": "sub_1Sfe0oHDlIZyMfEDs1lYui6v", // here !
    "subscription": null,
    "test_clock": "clock_1SfeT1HDlIZyMfEDNnlhPmOM"
  },
  "previous_attributes": {
    "released_subscription": null,
    "subscription": "sub_1Sfe0oHDlIZyMfEDs1lYui6v"
  }
}
```

related to https://github.com/twentyhq/twenty/issues/16573
2025-12-18 15:57:56 +01:00
Raphaël BosiandGitHub 01ffca0cef [DASHBOARDS] Add the ability to click to create a widget (#16673)
## Video QA


https://github.com/user-attachments/assets/813a2040-6ee9-418c-b7da-1126c9720446
2025-12-18 14:37:22 +00:00
4bdd866a20 Fix/close filter by enter (#16643)
Fixes #16636 

Added useCloseDropdown() hook and set onEnter prop to
onEnter={closeDropDown()} using dropdownID

EDIT from @charlesBochet after refactoring:
- ObjectDropdownFilters are used in 3 places: Main Filter menu,
EditableChip, AdvancedFilters
- deprecate vectorSearch in view filter area, we are not using them, we
are doing a anyField filter now. While refactoring the points below, I
did not want to maintain vectorSearch as it was not used anymore
- stop confusing the dropdownId (which is an id to interact with a
specific dropdown) and componentInstanceIds (which is used to scope
component states) for EditableFilter case
- I haven't fixed the confusion for MainFilter case
- It was already handled for AdvancedFilter case

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-12-18 15:25:56 +01:00
martmullandGitHub 52cf3775b3 Fix subscription cross tenant issue (#16670)
As title
2025-12-18 15:22:17 +01:00
c36bb8f3a1 i18n - docs translations (#16667)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 13:23:08 +01:00
df456cfa2f i18n - translations (#16666)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 13:01:49 +01:00
Lucas BordeauandGitHub ce7f0c03f7 Fixed command menu and main container layout (#16665)
This PR fixes https://github.com/twentyhq/twenty/issues/16645

It solves two problems : 
- Command menu for mobile was outside of its proper place, it should
have been portaled instead of lifted that high in the hierarchy, which
is done here, thus avoiding context issues.
- CSS was odd due to a code path removing main container styling for
mobile display, everything has been cleaned with explicit and durable
naming. I used "main container layout" instead of "page layout" to
disambiguate from page layout feature.

## Before 

<img width="567" height="907" alt="image"
src="https://github.com/user-attachments/assets/73a335f6-d5b6-4e8a-a33f-73aa624c7ca5"
/>


## After 

<img width="566" height="907" alt="image"
src="https://github.com/user-attachments/assets/0433b7d8-c8de-4b2b-b3fd-0d8d45b92d75"
/>
2025-12-18 12:48:31 +01:00
Raphaël BosiandGitHub 52604e1c52 Always enable drag selection when side panel is opened (#16664)
We disabled that before because the side panel was always on top of the
content. But now it makes sense to enable this.
2025-12-18 11:21:44 +00:00
Paul RastoinandGitHub 47a8a15598 Metadata modules for PageLayoutTab PageLayoutWidget (#16662)
# Introduction
Creating dedicated folders and module for both `page-layout-tab` and
`page-layout-widget`

The addition diff with deletion is due to the module being added
2025-12-18 11:15:29 +00:00
Raphaël BosiandGitHub db960cf509 Fix command menu input text color (#16661)
## Before
<img width="798" height="164" alt="CleanShot 2025-12-18 at 11 48 15@2x"
src="https://github.com/user-attachments/assets/f67c0d4b-8480-4649-8e46-f8ff6c9bacca"
/>

## After
<img width="400" height="76" alt="image"
src="https://github.com/user-attachments/assets/502a378b-ce89-4992-b5da-3fe6f4413feb"
/>
2025-12-18 10:57:50 +00:00
Félix MalfaitandGitHub daaa009fb4 fix: prevent text overflow in view picker and record table action row (#16658)
## Summary
Fixes text overflow issues in the UI that were particularly visible with
longer translations (e.g., French).

## Changes

### RecordTableActionRow
- Added `white-space: nowrap` to prevent the 'Add New' text from
wrapping to multiple lines
- Removed the fixed `width: 100px` that was causing overflow issues

### ViewPickerDropdown
- Fixed flexbox layout to properly handle long view names
- Added `flex-shrink: 0` to the icon container and adornments to prevent
them from shrinking
- Added `min-width: 0` to the view name container for proper text
truncation
- Removed `display: inline-block` and `vertical-align: middle` which
don't work in flex containers

## Before
- 'Ajouter Nouveau' was displayed on two lines
- View names could push the count to a new line
- Icons could shrink when view names were long

## After
- Text stays on one line with proper ellipsis truncation
- Layout remains stable regardless of text length
- Icons maintain their size
2025-12-18 11:38:14 +01:00
34a1c64b7e i18n - docs translations (#16660)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 11:21:25 +01:00
3a1e2618e2 i18n - translations (#16657)
Created by Github action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 11:01:06 +01:00
b4afbaefff I18n Translations (#16656)
Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-18 10:41:08 +01:00
Félix MalfaitandGitHub 12544da527 feat: move support links to workspace switcher (#16653)
## Summary
Move the Support and Documentation links from the bottom left navigation
drawer to the workspace switcher dropdown menu.

## Changes
- **Workspace Switcher**: Added Support (conditional) and Documentation
links before Log out
- **Settings Navigation**: Added Support and Documentation links in the
Other section
- **Support visibility**: Support link only appears when FrontChat is
configured (not waiting for script to load)
- **FrontChat loading**: Created `SupportChatEffect` component to ensure
FrontChat script loads at app startup for popup notifications
- **Bug fix**: Fixed settings navigation items without a path appearing
highlighted
- **Cleanup**: Removed unused `SupportDropdown`, `SupportButton`, and
`SupportButtonSkeletonLoader` components
- **Hidden**: Temporarily commented out Integrations page

## Screenshots
The Support and Documentation links now appear in:
1. Workspace switcher dropdown (top left)
2. Settings navigation (Other section)
2025-12-18 10:09:10 +01:00
Félix MalfaitandGitHub 4fe8e3d3b6 feat: add resizable navigation drawer and command menu panels (#16612)
## Summary

Adds Notion-style resizable panels for the navigation drawer (left
sidebar) and command menu (right panel).

## Behavior

- **Hover** at panel edge → resize cursor appears
- **Click** → collapse/close the panel
- **Drag** → resize the panel (5px movement threshold to distinguish
from click)

## Constraints

| Panel | Min | Max | Default | Collapse Threshold |
|-------|-----|-----|---------|-------------------|
| Navigation Drawer | 180px | 350px | 220px | 150px |
| Command Menu | 320px | 600px | 400px | 250px |

## Performance Optimizations

- **CSS variables** for smooth 60fps resize (no React re-renders during
drag)
- **Table resize observer disabled** during panel resize to prevent
expensive recalculations
- **React.memo wrapper** on page body to prevent unnecessary re-renders

## Architecture

- `useResizablePanel` hook following the same pattern as
`useResizeTableHeader`
- `ResizablePanelEdge` - resize handle positioned at panel edge
- `ResizablePanelGap` - resize handle in the gap between panels
- `cssVariableEffect` - Recoil effect to sync CSS variables with state

## Refactoring

- Split `recoil-effects.ts` into separate files in `utils/recoil/` (one
export per file)
- Persist panel widths to localStorage via existing `localStorageEffect`
2025-12-18 09:09:21 +01:00
Félix MalfaitandGitHub 6682d4eb02 fix: bill all events in BillingUsageService.billUsage() instead of only the first one (#16650)
## Summary

Fixes a bug where `BillingUsageService.billUsage()` only sent the first
event from the `billingEvents` array to Stripe, silently ignoring all
subsequent events.

## Bug Description

The `billUsage()` method accepts an array of `BillingUsageEvent[]` but
was only processing `billingEvents[0]`, causing:
- Customers to be undercharged for their usage
- Revenue loss due to unbilled events
- Incorrect usage tracking

## Fix

Changed the implementation to use `Promise.all()` to send all events in
the array concurrently to Stripe.

## Before
```typescript
await this.stripeBillingMeterEventService.sendBillingMeterEvent({
  eventName: billingEvents[0].eventName,  // Only first event
  value: billingEvents[0].value,
  stripeCustomerId: workspaceStripeCustomer.stripeCustomerId,
  dimensions: billingEvents[0].dimensions,
});
```

## After
```typescript
await Promise.all(
  billingEvents.map((event) =>
    this.stripeBillingMeterEventService.sendBillingMeterEvent({
      eventName: event.eventName,
      value: event.value,
      stripeCustomerId: workspaceStripeCustomer.stripeCustomerId,
      dimensions: event.dimensions,
    }),
  ),
);
```
2025-12-18 08:38:15 +01:00
Félix MalfaitandGitHub 4e15f7fe13 Use parameterized query in getRemoteTableLocalName (#16651)
This PR updates the `isNameAvailable` function in
`getRemoteTableLocalName` to use parameterized queries instead of string
interpolation when querying the information_schema.

**Changes:**
- Replaced template literal interpolation with PostgreSQL's `$1`, `$2`
placeholder syntax
- Parameters are now passed as a separate array argument to
`dataSource.query()`

This follows best practices for database queries.
2025-12-18 08:37:43 +01:00
Félix MalfaitandGitHub 1e615f7102 fix: ensure QueryRunner is released in workspace schema operations (#16649)
## Summary

Fixes a database connection leak in `WorkspaceDataSourceService` where
`QueryRunner.release()` was not being called when schema operations
failed.

## Problem

The `createWorkspaceDBSchema` and `deleteWorkspaceDBSchema` methods use
TypeORM's QueryRunner but didn't wrap the operations in
try-catch-finally blocks. When schema operations fail (e.g., permission
denied, schema conflicts), the `QueryRunner.release()` method was never
called.

**Impact:** Failed schema operations leak database connections, which
can exhaust the connection pool and cause the application to hang or
crash under load.

## Solution

Wrap both methods in try-finally blocks to ensure
`queryRunner.release()` is always called, regardless of whether the
operation succeeds or fails.

## Changes

- `createWorkspaceDBSchema`: Wrapped in try-finally to ensure connection
release
- `deleteWorkspaceDBSchema`: Wrapped in try-finally to ensure connection
release
2025-12-18 08:26:07 +01:00
Félix MalfaitandGitHub 75ae2b401b feat: soft disable LOCAL code interpreter driver in production (#16647)
## Summary

Instead of throwing an error at server startup when LOCAL code
interpreter is configured in production, we now return a DisabledDriver
that only throws when the code interpreter is actually used.

## Changes

- Created `DisabledDriver` class that implements `CodeInterpreterDriver`
but throws an error only when `execute()` is called
- Added `DISABLED` to the `CodeInterpreterDriverType` enum
- Updated the factory to return a `DISABLED` driver config instead of
throwing when LOCAL is used in production
- Updated the module to handle the new `DISABLED` driver type

## Motivation

Many users don't need the code interpreter feature and want to deploy to
production without configuring E2B. Previously, the server would crash
at startup if `CODE_INTERPRETER_TYPE=LOCAL` was set in production.

**Before:** Server crashes at startup in production if
`CODE_INTERPRETER_TYPE=LOCAL`

**After:** Server starts fine. The error only occurs if someone actually
tries to **use** the code interpreter feature, at which point they get a
clear error message explaining how to configure E2B.
2025-12-18 08:03:13 +01:00
e5f655fcae i18n - docs translations (#16646)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-17 23:20:56 +01:00
82b0ee5995 i18n - translations (#16644)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-17 22:46:52 +01:00
Félix MalfaitandGitHub 1088f7bbab feat: add lingui/no-unlocalized-strings ESLint rule and fix translations (#16610)
## Summary
This PR adds the `lingui/no-unlocalized-strings` ESLint rule to detect
untranslated strings and fixes translation issues across multiple
components.

## Changes

### ESLint Configuration (`eslint.config.react.mjs`)
- Added comprehensive `ignore` patterns for non-translatable strings
(CSS values, HTML attributes, technical identifiers)
- Added `ignoreNames` for props that don't need translation (className,
data-*, aria-*, etc.)
- Added `ignoreFunctions` for console methods, URL APIs, and other
non-user-facing functions
- Disabled rule for debug files, storybook, and test files

### Components Fixed (~19 files)
- Object record components (field inputs, pickers, merge dialogs)
- Settings components (accounts, admin panel)
- Serverless function components
- Record table and title cell components

## Status
🚧 **Work in Progress** - ~124 files remaining to fix

This PR is being submitted as draft to allow progressive fixing of
remaining translation issues.

## Testing
- Run `npx eslint "src/**/*.tsx"` in `packages/twenty-front` to check
remaining issues
2025-12-17 22:08:33 +01:00
Abdullah.andGitHub c13b955a36 fix: hide GraphQL stack traces and messages in production (#16593)
Resolves [Code Scanning Alert
180](https://github.com/twentyhq/twenty/security/code-scanning/180).

- Normalize unexpected GraphQL errors in convertExceptionToGraphql to a
generic "Internal Server Error" instead of exposing exception.name
directly to clients.
- Only attach stack and response (original error message) in
development, so production responses don’t leak internal class names,
implementation details, or stack traces, while observability is
preserved via `ExceptionHandlerService`/Sentry.
- Keep behavior consistent with `convertHttpExceptionToGraphql`, which
also only exposes detailed response and stack information when `NODE_ENV
=== DEVELOPMENT`.
2025-12-17 18:29:40 +01:00
Raphaël BosiandGitHub b0e256221a Create typeguards for widget configurations (#16627)
We checked for widget types by doing `configuration?.__typename ===
'LineChartConfiguration'` which made the code difficult to read.

In this PR, I introduce type guards for each widget type.

Note: the configuration type is `WidgetConfiguration |
FieldsConfiguration` for now but should be changed to
`WidgetConfiguration` when @Devessier adds FieldsConfiguration to the
backend type `WidgetConfiguration`.
2025-12-17 17:48:34 +01:00
a560e8ac83 feat: 🎸 added higher resoulution options in the dateTime Filter (#16548)
Title: "feat: Add second, minute & hour resolution options to relative
date Filter action"
---

## Summary

This PR enables support for smaller time units — **Seconds, Minutes, and
Hours** — in the *Relative Date* filter used in workflows, rather than
being limited to days only.

---

## What Changed

This PR extends the relative date filter to include support for the
following units:

✔️ `SECOND`  
✔️ `MINUTE`  
✔️ `HOUR`  
✔️ (Existing: `DAY`, `WEEK`, `MONTH`, etc.)

Changes include:

- Adding `SECOND`, `MINUTE`, and `HOUR` options to the internal relative
date unit enum/constant.
- Updating utility functions and parsers to correctly interpret and
evaluate these new units.
- Enhancing existing tests and adding new tests to cover second, minute,
and hour relative filters.

---

## Testing

New and updated tests include:

- Unit tests for serialization of relative filter values including
seconds, minutes, and hours.
- Workflow filter evaluation tests that verify minute/hour resolution
behaves correctly.

Tests are included in the changeset.

---

## Backward Compatibility

This change is fully backward compatible:

- All existing relative date filters using days or larger units behave
exactly as before.
- Adding finer units does not alter existing stored data or workflow
definitions.

---

##  Issue Reference

Fixes: **twentyhq/twenty#15525**  

<img width="1909" height="896" alt="image"
src="https://github.com/user-attachments/assets/328d03dc-ca0b-4c3f-84e5-58961c178398"
/>

---------

Co-authored-by: Guillim <guillim@users.noreply.github.com>
Co-authored-by: guillim <guigloo@msn.com>
2025-12-17 16:46:11 +00:00
Raphaël BosiandGitHub 100d4f7f42 [DASHBOARDS] Hide tab menu items instead of disabling them (#16629)
## Before

<img width="818" height="1052" alt="CleanShot_2025-12-15_at_14 29 302x"
src="https://github.com/user-attachments/assets/5eceefce-559d-4710-8fa7-118ca32a4dc7"
/>

## After


https://github.com/user-attachments/assets/b6559600-d7cd-47a8-9ef7-e9c638637cb0
2025-12-17 17:42:58 +01:00
Abdullah.andGitHub 1f1a1ea138 fix(workflows): align variable regex with validation and prevent ReDoS (#16607)
**What this fixes:**
- Addresses a CodeQL security finding: the regex used to find variables
in workflow strings could be slow on malicious inputs (ReDoS).
- Two alerts: [Code Scanning
181](https://github.com/twentyhq/twenty/security/code-scanning/181) and
[Code Scanning
182](https://github.com/twentyhq/twenty/security/code-scanning/182)

**Context:**
- Our workflow system lets users insert variables like `{{user.name}}`
or `{{trigger.properties.after.name}}` into strings and JSON (HTTP
request bodies, record field values, etc.).
- The `variable-resolver.ts` module scans these strings and replaces
variables with actual values.
- Our validation (`isValidVariable`) already enforces that variables
contain no `{` or `}` inside them (only simple property paths like
`user.name`).

**The change:**
- Updated the regex from `/\{\{(.*?)\}\}/g` to `/\{\{([^{}]+)\}\}/g` to
match our validation pattern.
- This removes the ReDoS risk and aligns the resolver with the
validation contract.

**Why this is safe:**
- All supported workflow usage (simple variable paths) continues to
work.
- Both `match` and `replace` behave the same for valid variables.
- Only unsupported patterns with nested braces (e.g., `{{foo {bar}}}`)
would stop matching, which isn't part of our supported syntax anyway.
2025-12-17 17:13:55 +01:00
59d3a14922 Common API - Add tests on position field validation at creation (#16630)
Co-authored-by: guillim <guigloo@msn.com>
2025-12-17 16:02:37 +00:00
Paul RastoinandGitHub 0e6a8c04c4 Async validators and additional cache maps in v2 Builder (#16618)
# Introduction
@bosiraphael has to introduce async validators and feature flag
contextual validator
In this way in this PR we make all entity validators asyncable
Also added an `additionalCacheDataMaps` to the low level args validators
2025-12-17 15:43:25 +01:00
Raphaël BosiandGitHub ca976afa10 Fix drag and drop in dropdown (#16622)
## Bug description

Due to the dropdown using floating ui, there was an offset on the
draggable item when the drag and drop was implemented inside a
scrollable dropdown.

## Video QA

### Before


https://github.com/user-attachments/assets/fe4b4c36-39ae-4d26-9e19-85d5ffd23b30


### After


https://github.com/user-attachments/assets/1f00b9b0-c231-49cb-a232-75ca42a98e8c
2025-12-17 13:41:37 +00:00
martmullandGitHub 967298fe09 Remove position input from zapier (#16616)
As title
Fixes zapier tests
2025-12-17 14:39:51 +01:00
Charles BochetandGitHub a60f750ed7 Follow up on FieldInput fix (#16611)
Follow up on https://github.com/twentyhq/twenty/pull/16603
2025-12-17 14:16:14 +01:00
EtienneandGitHub 2e62bb133b Second Action Button - fix (#16613)
Merged https://github.com/twentyhq/twenty/pull/16582 without testing
case when fieldDefinition.metadata.settings?.clickAction is not set
(default value)

To test : 
When 
<img width="548" height="537" alt="Screenshot 2025-12-17 at 09 37 26"
src="https://github.com/user-attachments/assets/96a85093-24bb-4436-9000-340cd020e343"
/>
is set (or default)
In table view you can copy cell content
<img width="252" height="77" alt="Screenshot 2025-12-17 at 09 36 58"
src="https://github.com/user-attachments/assets/44b938f3-74b8-4d58-8b1a-344b4f39bfbd"
/>
2025-12-17 10:57:30 +00:00
6de424bc32 handle localization and property parameters in CalDAV iCal parsing (#16519)
Co-authored-by: guillim <guigloo@msn.com>
2025-12-17 11:47:16 +01:00
2717afce59 i18n - docs translations (#16620)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-17 11:21:57 +01:00
Lucky GoyalandGitHub 659ed6b080 feat: add full path label tooltip for workflow filter field (#16580)
# Closes Issue: Can't distinguish between fields with identical names
(#16285)

There was a UX bug in the workflow filter interface where **two
variables coming from different steps but sharing the same field name**
were displayed identically. This made it difficult for users to tell
them apart when used in a filter group, leading to confusion when
building workflows.

---

# Fix: Add Full Path Label Tooltip for Workflow Filter Field

- Adds a **tooltip/label showing the complete path** so users can
distinguish fields from different workflow steps even if they share the
same name.

## UX Improvements
<img width="495" height="288" alt="image"
src="https://github.com/user-attachments/assets/fa26f381-835b-4d14-bf73-f04b59c8d0b5"
/>
2025-12-17 11:13:10 +01:00
30c2c22fc2 i18n - translations (#16614)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-17 09:52:49 +01:00
d43e21b695 Feature 15797 add secondary action button (#16582)
This is a fix for #15797 

This pull request is to replace PR #16307 and to extend #16265 

Just to repeat, this PR does the following -> 
**Table Cell Button and Edit Button Improvements**
- Enhanced RecordTableCellButton to support a secondary action and icon,
enabling both the primary and secondary actions based on the selected
action mode.
- Updated RecordTableCellEditButton to determine the action mode for
actionable fields, and provide both copy and navigate actions as
primary/secondary buttons, with appropriate feedback.

## When primary function is to copy
<img width="1817" height="939" alt="image"
src="https://github.com/user-attachments/assets/7ec6c6aa-80d8-402b-a210-519163d39ef6"
/>


## When primary function is to open link
<img width="1784" height="942" alt="image"
src="https://github.com/user-attachments/assets/dfe0fcf1-ba72-4083-a5f9-7165a03db3df"
/>

Hey @etiennejouan, please have a look!
Thank you

---------

Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2025-12-17 09:13:00 +01:00
MarieandGitHub 0145920d7e e2e tests (#16533)
In this PR, 
- current basic E2E tests are fixed, and some were added, covering some
basic scenarios
- some tests avec been commented out, until we decide whether they are
worth fixing

The next steps are
- evaluate the flakiness of the tests. Once they've proved not to be
flaky, we should add more tests + re-write the current ones not using
aria-label (cf @lucasbordeau indication).
- We will add them back to the development flow
2025-12-17 08:48:17 +01:00
martmullandGitHub 1cbbd04761 Function trigger updates 2 (#16608)
- Improves route trigger job performances
- expose function params types

## Before

<img width="938" height="271" alt="image"
src="https://github.com/user-attachments/assets/5752ba64-f31d-44ed-974d-536e63458f2c"
/>


## After

<img width="1000" height="559" alt="image"
src="https://github.com/user-attachments/assets/b1f4927a-5f43-49f0-a606-244c72356772"
/>
2025-12-16 18:20:26 +01:00
Charles BochetandGitHub 58c85e7cca Fix bug on Links, Array, Emails, Phones Field inputs (#16603)
The following PR introduced several bugs:
https://github.com/twentyhq/twenty/pull/16042



https://github.com/user-attachments/assets/2c0fd211-3579-4a22-9a5f-dcec9cbe6a2e
2025-12-16 18:18:15 +01:00
Raphaël BosiandGitHub 576019e465 [DASHBOARDS] Rotate ticks on bar and line charts (#16528)
## Description

3 steps depending on the widget width. From bigger to tighter space:
- Fully shown horizontal text
- Rotated text
- Rotated text with skipped ticks to avoid overlapping

Also created common files for all constants for bar and pie charts.
Since a lot of them are shared, they can be inherited from a common
file.

## Video QA


https://github.com/user-attachments/assets/fd58d412-1a8b-4bd6-a420-4c03767e98d5
2025-12-16 16:39:42 +00:00
Raphaël BosiandGitHub 5a5bf112cf Update dashboard Icons (#16605)
New Icons:

<img width="790" height="84" alt="CleanShot 2025-12-16 at 15 53 45@2x"
src="https://github.com/user-attachments/assets/6700efd4-2ae9-4521-8fe9-ed43b3cef438"
/>

<img width="794" height="72" alt="CleanShot 2025-12-16 at 15 54 19@2x"
src="https://github.com/user-attachments/assets/ac4ecc88-4012-463f-875a-0bbb29d09ce3"
/>

<img width="184" height="76" alt="CleanShot 2025-12-16 at 15 53 56@2x"
src="https://github.com/user-attachments/assets/8e8353b0-90d5-4543-9d16-88b3eafdc1ae"
/>
2025-12-16 16:57:22 +01:00
martmullandGitHub 9b00084fb0 Vendor twenty-shared into twenty-sdk (#16592)
twenty-shared is not bundled properly when deploying twenty-sdk to npm.
This aims to fix that issue
2025-12-16 16:48:38 +01:00
38a0bba57b i18n - docs translations (#16600)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-16 15:21:59 +01:00
a6127c2128 i18n - translations (#16596)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-16 15:04:08 +01:00
Félix MalfaitandGitHub 04c596817a feat(server): enforce userFriendlyMessage on all exceptions (#16589)
## Summary
This PR enforces that all custom exceptions must provide a
`userFriendlyMessage`, ensuring end users always see readable error
messages.

## Changes

### Core Changes
- **`CustomException` simplified**: Removed the `ForceFriendlyMessage`
generic parameter - `userFriendlyMessage` is now always required
- **Type safety**: The constructor now requires `{ userFriendlyMessage:
MessageDescriptor }` (no longer optional)

### Updated Files
- **74+ exception classes** updated to provide default user-friendly
messages using Lingui `msg` macro
- Each exception class has a sensible fallback message (e.g., `msg\`An
authentication error occurred.\``)
- Exception classes that had code-specific message maps retain their
behavior

## Benefits
- **Compile-time enforcement**: Forgetting to add a user-friendly
message now causes a TypeScript error
- **Better UX**: End users always see a localized, human-readable error
message
- **Simpler API**: No more boolean generic parameter to think about

## Testing
- `npx nx run twenty-server:typecheck` passes
- `npx nx run twenty-server:lint` passes

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Enforces `userFriendlyMessage` on `CustomException` and updates all
exception classes to supply localized default messages, with
filters/tests adjusted accordingly.
> 
> - **Core**:
> - Enforce required `userFriendlyMessage` in `CustomException` (remove
optional generic; constructor now requires `{ userFriendlyMessage:
MessageDescriptor }`).
> - **Exceptions**:
> - Update ~70+ exception classes to set default localized messages via
Lingui `msg` maps and pass them in constructors (e.g., `AuthException`,
`ObjectMetadataException`, `FieldMetadataException`, etc.).
> - Add fallback messages where needed (e.g., `INTERNAL_SERVER_ERROR` or
domain-specific defaults).
> - **HTTP/GraphQL Filters**:
> - Ensure fallbacks create `UnknownException` with `msg` for
user-friendly text in REST/GraphQL exception filters.
> - **Tests**:
>   - Adjust unit tests to pass `userFriendlyMessage` to exceptions.
> - Update Jest snapshots to include `extensions.userFriendlyMessage` or
message objects where applicable.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
221004fdfc. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2025-12-16 14:44:27 +01:00
martmullandGitHub 3ac72683da Update migration command (#16578)
Avoid pg_ table request
2025-12-16 13:35:03 +00:00
Abdullah.andGitHub d998e3b92c Display a CTA to view the existing duplicate when adding a duplicate email/domain. (#16483)
Closes [89](https://github.com/twentyhq/core-team-issues/issues/89)

## Problem

When users attempt to create or update a record with a duplicate value
for a unique field (e.g., duplicate email or domain name), they receive
a generic error message: "This record already exists. Please check your
data and try again." This provides no actionable way to locate and view
the existing conflicting record, forcing users to manually search for
it.

## Solution

This PR enhances duplicate key constraint error handling to
automatically detect the conflicting record and display a "View existing
record" link in the error notification. When clicked, users are
navigated directly to the existing record's detail page.

## Backend Changes

### 1. PostgreSQL Error Parsing
(`parse-postgres-constraint-error.util.ts`)
- Extracts structured information from PostgreSQL `QueryFailedError`
messages.

### 2. Conflicting Record Lookup (`find-conflicting-record.util.ts`)
- Queries the database to find the existing record with the conflicting
value

### 3. Error Handling Orchestration
(`handle-duplicate-key-error.util.ts`)
- Parses PostgreSQL error to extract column name and conflicting value
- Attempts to find the conflicting record
- Enriches `TwentyORMException` with `conflictingRecordId` and
`conflictingObjectNameSingular` if found

### 4. Exception Computation Updates (`compute-twenty-orm-exception.ts`)
- Made function `async` and added optional `entityManager` and
`internalContext` parameters
- Needed to support async database queries for conflicting record lookup

### 5. GraphQL Error Handler
(`twenty-orm-graphql-api-exception-handler.util.ts`)
- **Changes**: Enhanced `DUPLICATE_ENTRY_DETECTED` case to include
`conflictingRecordId` and `conflictingObjectNameSingular` in GraphQL
error extensions

## Frontend Changes

### 1. Error Extraction Utility
(`get-conflicting-record-from-apollo-error.util.ts`)
- Accesses GraphQL error extensions
- Validates that both `conflictingRecordId` and
`conflictingObjectNameSingular` exist and are strings
- Returns `null` if validation fails

### 2. SnackBar Enhancement (`useSnackBar.ts`)
- Extracts conflicting record info from Apollo error
- Constructs URL using `getAppPath` utility
- Adds link object to snackbar options with text "View existing record"

<img width="931" height="858" alt="image"
src="https://github.com/user-attachments/assets/28137dc7-18ab-4ffe-b669-1f2d4ec264d1"
/>
2025-12-16 14:27:34 +01:00
Paul RastoinandGitHub 75bba5a8ee Standard Agent, Role, Role target (#16499)
# Introduction
In this pullrequest have been migrated to the flat standard entities:
Role, Agent and RoleTargets.

## What happens
- Removed createStandardMorph tool util in favor of dynamic typing of
`createMorphOrRelationStandardField`
- Implemented a command to remove standard agents and their role that
has been removed in https://github.com/twentyhq/twenty/pull/16513 also
added a default role target to data manipulator role to the only
remaining agent
- Implemented an agent deleteMany service handler
2025-12-16 14:17:31 +01:00
Abdullah.andGitHub 553efe0cee fix: incomplete URL substring sanitization in linkedin-browser-extension. (#16586)
Tighten LinkedIn browser extension popup URL handling by parsing the
active tab URL and matching on protocol, hostname, and pathname instead
of substring checks, preventing logic from running on non-LinkedIn
hosts.

Resolves [Code Scanning Alert
209](https://github.com/twentyhq/twenty/security/code-scanning/209) and
[Code Scanning Alert
210](https://github.com/twentyhq/twenty/security/code-scanning/210).
2025-12-16 13:22:35 +01:00
martmullandGitHub 48a7a24380 Update hello-world twenty-sdk version (#16579)
yarn lock update after cli package release
2025-12-15 19:42:30 +01:00
e8fd5fa3ed Added relative date filter to dashboards (#16292)
This PR adds relative date filter operand to dashboard filters : 

<img width="1685" height="558" alt="image"
src="https://github.com/user-attachments/assets/a1f927e7-8c99-4171-b487-4b6a28779547"
/>

It also refactors the logic to add timezone and first day of the week
taking users preferences.

It has been tested on workflows and regular advanced filters also.


For step filters, which use a JSON format to store relative date
filters, I kept the current way to handle it.

There are a few workspaces that use a relative date filter in step
filter, so we want to avoid a migration, and instead handle both code
paths, and refactor everything to JSON later.

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-15 18:51:57 +01:00
Abdul RahmanandGitHub 31467f2173 Fix action menu modals rendering inside dropdown containers (#16478)
Closes #16363

- Updated modals to open in the full screen by default


<img width="1356" height="940" alt="Screenshot 2025-12-11 at 12 15
15 AM"
src="https://github.com/user-attachments/assets/a27bf2f2-8778-457a-a4ea-e3f3f30de302"
/>
2025-12-15 18:36:24 +01:00
nitinandGitHub 9c3cd959ba [Dashboards] add legend hover highlight for graph widgets (#16551)
closes https://github.com/twentyhq/core-team-issues/issues/1959

line - 


https://github.com/user-attachments/assets/3fcefd47-c065-488c-a9e1-e820e8a03349

bar - 


https://github.com/user-attachments/assets/a138e376-9304-46b9-b6ba-c642f7b85ae2

pie - 



https://github.com/user-attachments/assets/cc008d0e-ec7f-47a3-ac14-5fef56426f6a

onClick - 



https://github.com/user-attachments/assets/94c1791d-b820-449c-81f9-c3d10361b694
2025-12-15 17:28:51 +00:00
Abdul RahmanandGitHub 289e8bf1d4 fix: ensure unique GraphQL schema caching per API key (#16411)
## Description

This PR fixes an issue where the GraphQL schema was being incorrectly
cached and shared across different API keys within the same workspace.
This resulted in the `createdBy` field (Actor) from the first API key's
request being erroneously attributed to subsequent requests made by
different API keys.

## Changes

- Updated the `@graphql-yoga/nestjs` patch to include the request's
`Authorization` header in the schema cache key generation logic.
- This ensures that every unique authentication token (and thus every
unique API key) generates a distinct cache entry, preventing schema
context collisions.

Closes #15093
2025-12-15 18:23:33 +01:00
EtienneandGitHub 0ecb60f50b E2B var env fix (#16576) 2025-12-15 18:20:22 +01:00
nitinandGitHub cd0318ea65 revert bundle size increase (#16575) 2025-12-15 18:13:05 +01:00
MarieandGitHub a0b963ef86 Remove viewGroup.fieldMetadataId (#16571)
Final step of
https://github.com/orgs/twentyhq/projects/1/views/8?pane=issue&itemId=142348748&issue=twentyhq%7Ccore-team-issues%7C1965

Removing viewGroup.fieldMetadataId.
It's already not used in FE anymore
2025-12-15 17:58:45 +01:00
neo773andGitHub 66d242da24 prevent filtering out messages sent by user when their handle resembes group email (#16508) 2025-12-15 17:58:25 +01:00
martmullandGitHub e289f3056e 1895 extensibility v1 application tokens 3 (#16504)
- moves applicationRoleId to application entity
- add new `APPLICATION` FieldActorSource and `APPLICATION`
JwtTokenTypeEnum value
- create a new token with applicationId when executing a function
- when applicationId is in token, check for application.defaultRole
permissions
-use twenty-shared types in `twenty-sdk/application`
- create a new import from generate called "Twenty" that you can use
directly without having to set TWENTY_API_KEY AND TWENTY_API_URL (keep
metadata or core parameter only)
- provide to serverless unique one time BEARER TOKEN to run it

Result
<img width="977" height="566" alt="image"
src="https://github.com/user-attachments/assets/e78428a0-5b13-4975-aa13-58ee3b32450c"
/>

<img width="910" height="596" alt="image"
src="https://github.com/user-attachments/assets/6ec72bf5-7655-4093-a45e-ad269595a324"
/>

<img width="741" height="568" alt="image"
src="https://github.com/user-attachments/assets/7683944c-fd79-4417-8fb2-8e4815cc112f"
/>
2025-12-15 17:44:23 +01:00
e33f18bfa8 i18n - translations (#16574)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-15 17:22:24 +01:00
039a3d99a8 Fix APIKey typing (#16541)
Following this https://github.com/twentyhq/twenty/pull/16540
Those were not failing (yet) but were wrongly typed and error prone

---------

Co-authored-by: Guillim <guillim@users.noreply.github.com>
2025-12-15 16:05:28 +00:00
nitinandGitHub fc74a06f53 [Dashboards] add hide empty category option for pie charts (#16550)
closes
https://discord.com/channels/1130383047699738754/1445403391722520677


https://github.com/user-attachments/assets/980225a8-153e-4b49-89f7-5944227c8fdb


toggle label ie `Hide empty category` -- debatable
2025-12-15 15:40:46 +00:00
nitinandGitHub 75f2c26d3f lazy load rich text widget (#16569) 2025-12-15 16:30:54 +01:00
Thomas TrompetteandGitHub 95e0793f81 Compute output schema on frontend (#16530)
Fixes https://github.com/twentyhq/core-team-issues/issues/1382

Current issue : all step output schemas are computed and stored on
backend side. Which means that, when the database schema is updated -
like a field creation - steps needs to be deleted an recreated. Which is
invisible to users.

Solution : schema generation is moved on frontend side

1. Coming on the page the first time, the schema is populated for all
steps except a few ones that are handled differently (Code, Webhook,
http node, Agent)

2. A separated state allow to determine if a step needs a recomputation.

3. The user only needs a refresh to see the whole schema re-computed

Follow-up:
- check if remaining backend steps could be moved to runtime
computation. But Code will still require storage.
- Clean backend service that is not used anymore
2025-12-15 16:20:35 +01:00
Félix MalfaitandGitHub 2e104c8e76 feat(ai): add code interpreter for AI data analysis (#16559)
## Summary

- Add code interpreter tool that enables AI to execute Python code for
data analysis, CSV processing, and chart generation
- Support for both local (development) and E2B (sandboxed production)
execution drivers
- Real-time streaming of stdout/stderr and generated files
- Frontend components for displaying code execution results with
expandable sections

## Code Quality Improvements

- Extract `getMimeType` to shared utility to reduce code duplication
between drivers
- Fix security issue: escape single quotes/backslashes in E2B driver env
variable injection
- Add `buildExecutionState` helper to reduce duplicated state object
construction
- Add `DEFAULT_CODE_INTERPRETER_TIMEOUT_MS` constant for consistency
- Fix lingui linting warning and TypeScript theme errors in frontend

## Test Plan

- [ ] Test code interpreter with local driver in development
- [ ] Test code interpreter with E2B driver in production environment
- [ ] Verify streaming output displays correctly in chat UI
- [ ] Verify generated files (charts, CSVs) are uploaded and
downloadable
- [ ] Test file upload flow (CSV, Excel) triggers code interpreter

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Updates generated i18n catalogs for Polish and pseudo-English, adding
strings for code execution/output (code interpreter) and various UI
messages, with minor text adjustments.
> 
> - **Localization**:
> - **Generated catalogs**: Refresh `locales/generated/pl-PL.ts` and
`locales/generated/pseudo-en.ts`.
> - Add strings for code execution/output (e.g., code, copy code/output,
running/waiting states, download files, generated files, Python code
execution).
> - Include new UI texts (errors, prompts, menus) and minor text
corrections.
>   - No changes to `pt-BR`; other files unchanged functionally.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
befc13d02c. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2025-12-15 16:11:24 +01:00
Charles BochetandGitHub 4281a71f40 Increase bundle size to 6.9MB (#16568)
Likely a missing lazy load in:
https://github.com/twentyhq/twenty/pull/16437

Let's unblock and fix separately
2025-12-15 15:25:22 +01:00
EtienneandGitHub 3e55e772d4 Update null command (#16567)
Remove version condition to re-run the command on upgraded workspaces on
which it fails
2025-12-15 13:55:32 +00:00
neo773andGitHub a83732d7a6 fix messaging error parsing (#16448) 2025-12-15 13:33:37 +01:00
Abhishek KumarandGitHub 042972d7b2 fix(workflow): line break not supported by Send Email Nodes (#16561)
Closes #16557

Tiptap Editor (which the Send Email Node uses) , creates a content json
with type 'hardBreak' for line breaks.

The was no rederer defined for this `hardBreak` node type, so the
`renderNode` function was ignoring that node (returning null).

**Fix :** Added a renderer for  `hardBreak` node type.
2025-12-15 13:24:31 +01:00
d7b34fc636 feat(workflow): improve Add node discovery (#16547)
## Description

This PR improves the discoverability of the 'Add node' action in the
workflow builder by making it always visible in the action menu.

### Changes:
1. **Pin the 'Add node' action** - Changed \isPinned\ from \ alse\ to \
rue\ for the \ADD_NODE\ action so it's always visible and easily
accessible when viewing a workflow
2. **Unpin 'Add to favorites' and 'Remove from favorites'** - These
actions are less frequently used in the workflow context, so they've
been unpinned to make room for the more relevant 'Add node' CTA

### Files Changed:
-
\packages/twenty-front/src/modules/action-menu/actions/record-actions/constants/WorkflowActionsConfig.tsx\

Fixes #16538

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Pins `ADD_NODE` in the workflow action menu and unpins
`ADD_TO_FAVORITES`/`REMOVE_FROM_FAVORITES` to prioritize
workflow-related actions.
> 
> - **Workflow action menu config (`WorkflowActionsConfig.tsx`)**:
> - **Pinning**: Set `isPinned: true` for
`WorkflowSingleRecordActionKeys.ADD_NODE`.
> - **Unpinning**: Set `isPinned: false` for
`SingleRecordActionKeys.ADD_TO_FAVORITES` and
`SingleRecordActionKeys.REMOVE_FROM_FAVORITES` under
`propertiesToOverwrite`.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
67b65df0a7. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2025-12-15 11:30:56 +01:00
Paul RastoinandGitHub 8c79353bfb Fix rename index collides with existing v2 index (#16560)
## Introduction
When migrating a v1 index name to v2 it might collide with an existing
v2 index
In this case we remove both the v1 metadata and pg index

In case of a metadata and pg_index desync this might occur too late in
the process that's why we have two fallback
One computing the v1 deletion from the metadata and another one in the
catch block of the v1 to migration transaction commit
2025-12-15 11:06:09 +01:00
Abdullah.andGitHub cf6fb419e0 fix: ensure deactivated object records do not appear in search (#16532)
Deactivating an object still allowed querying its records in search.

<img width="1512" height="856" alt="image"
src="https://github.com/user-attachments/assets/0a1ba36f-1ecf-44d3-8e97-294bb4e81e4f"
/>

<br />
<br />

This PR introduces a minor improvement to not query records of
deactivated objects.

<img width="1512" height="856" alt="image"
src="https://github.com/user-attachments/assets/f5fd1377-2fda-4653-b3cc-30a59d52e4cf"
/>
2025-12-15 10:42:22 +01:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
9fd2853315 Bump @types/unzipper from 0.10.10 to 0.10.11 (#16554)
Bumps
[@types/unzipper](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/unzipper)
from 0.10.10 to 0.10.11.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/unzipper">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@types/unzipper&package-manager=npm_and_yarn&previous-version=0.10.10&new-version=0.10.11)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-15 10:25:53 +01:00
1119e3d77e fix(twenty-shared): preserve special characters in URLs (#16312)
# Fix: URL Encoding Bug & Code Refactor

## Issue

**Bug**: URLs with encoded characters (e.g., `%20` for spaces) were
being double-encoded or incorrectly processed in
[lowercaseUrlOriginAndRemoveTrailingSlash](cci:1://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/lowercaseUrlOriginAndRemoveTrailingSlash.ts:4:0-16:2),
causing URL mismatches and potential data integrity issues.

**Build Error**: `TS2307: Cannot find module
'src/modules/messaging/message-import-manager/drivers/imap/utils/safe-decode-uri-component.util'`

## Root Cause Analysis

### 1. Missing URL Decoding
The
[lowercaseUrlOriginAndRemoveTrailingSlash](cci:1://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/lowercaseUrlOriginAndRemoveTrailingSlash.ts:4:0-16:2)
function was processing URLs without properly decoding URI components.
When URLs contained encoded characters like `%20`, `%2F`, etc., they
weren't being normalized correctly.

### 2. Invalid Cross-Package Import
The fix attempted to import
[safeDecodeURIComponent](cci:1://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/safeDecodeURIComponent.ts:0:0-6:2)
from `twenty-server`:

```typescript
import { safeDecodeURIComponent } from 'src/modules/messaging/message-import-manager/drivers/imap/utils/safe-decode-uri-component.util';
```

This failed because:
- The file resides in `twenty-shared`, a separate package
- TypeScript cannot resolve internal paths from another package
- The monorepo uses package exports (`twenty-shared/utils`) for
cross-package imports, not direct file paths

## Solution

### 1. Bug Fix: Added Safe URI Decoding

Updated
[lowercaseUrlOriginAndRemoveTrailingSlash.ts](cci:7://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/lowercaseUrlOriginAndRemoveTrailingSlash.ts:0:0-0:0)
to properly decode URL components:

```typescript
export const lowercaseUrlOriginAndRemoveTrailingSlash = (rawUrl: string) => {
  const url = getURLSafely(rawUrl);

  if (!isDefined(url)) {
    return rawUrl;
  }

  const lowercaseOrigin = url.origin.toLowerCase();
  const path =
    safeDecodeURIComponent(url.pathname) + 
    safeDecodeURIComponent(url.search) + 
    url.hash;

  return (lowercaseOrigin + path).replace(/\/$/, '');
};
```

The
[safeDecodeURIComponent](cci:1://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/safeDecodeURIComponent.ts:0:0-6:2)
wrapper handles malformed URI sequences gracefully by returning the
original string if decoding fails, preventing runtime crashes.

### 2. Refactor: Consolidated Shared Utility

**Before**: Duplicate utility existed in `twenty-server`
```
twenty-server/src/modules/messaging/.../utils/safe-decode-uri-component.util.ts
```

**After**: Single source of truth in `twenty-shared`
```
twenty-shared/src/utils/url/safeDecodeURIComponent.ts
```

This follows the established pattern in the codebase where shared
utilities live in `twenty-shared` and are imported via subpath exports:

```typescript
// In twenty-server
import { safeDecodeURIComponent } from 'twenty-shared/utils';

// In twenty-shared (local import)
import { safeDecodeURIComponent } from './safeDecodeURIComponent';
```

## Files Changed

| File | Action | Description |
|------|--------|-------------|
|
[twenty-shared/src/utils/url/safeDecodeURIComponent.ts](cci:7://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/safeDecodeURIComponent.ts:0:0-0:0)
| **Created** | New shared utility (moved from twenty-server) |
|
[twenty-shared/src/utils/url/index.ts](cci:7://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/index.ts:0:0-0:0)
| **Modified** | Added export for
[safeDecodeURIComponent](cci:1://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/safeDecodeURIComponent.ts:0:0-6:2)
|
|
[twenty-shared/src/utils/url/lowercaseUrlOriginAndRemoveTrailingSlash.ts](cci:7://file:///Users/apple/WebstormProjects/twenty/packages/twenty-shared/src/utils/url/lowercaseUrlOriginAndRemoveTrailingSlash.ts:0:0-0:0)
| **Modified** | Fixed import path, now uses local relative import |
| `twenty-server/.../imap-message-text-extractor.service.ts` |
**Modified** | Updated import to use `twenty-shared/utils` |
| `twenty-server/.../safe-decode-uri-component.util.ts` | **Deleted** |
Removed duplicate utility |

## The Utility

```typescript
// safeDecodeURIComponent.ts
export const safeDecodeURIComponent = (text: string): string => {
  try {
    return decodeURIComponent(text);
  } catch {
    return text;
  }
};
```

This wrapper is necessary because `decodeURIComponent()` throws a
`URIError` on malformed sequences (e.g., `%E0%A4%A`). The safe version
returns the original string instead of crashing.

## Testing

- **342 tests passed** in `twenty-shared`
- `lowercaseUrlOriginAndRemoveTrailingSlash.test.ts` validates URL
normalization behavior
- No regressions in existing functionality

## Impact

- **Bug Fixed**: URLs with encoded characters are now properly
normalized
- **Code Quality**: Eliminated code duplication between packages
- **Maintainability**: Single source of truth for URI decoding utility
- **Build**: Resolved TS2307 compilation error

---------

Co-authored-by: Joker <apple@Apples-MacBook-Pro.local>
2025-12-15 08:41:57 +00:00
Paul RastoinandGitHub d189e3f57e Fix rename command error code edge case (#16556) 2025-12-15 08:36:35 +00:00
da9ade72c8 i18n - translations (#16545)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-12 19:22:27 +01:00
7f50486de5 Facebook links: display profile instead of full url (#16414)
Like we do for LinkedIn/Twitter

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-12 18:49:58 +01:00
EtienneandGitHub d36d0d49d1 Investigate - Slow transformRichTextV2 function (#16535)
Investigate CPU overloading ...

related to https://github.com/twentyhq/twenty/issues/15916
2025-12-12 18:39:01 +01:00
nitinandGitHub 44f0cfdd9e [Dashboards] Rich text editor frontend (#16437)
closes https://github.com/twentyhq/core-team-issues/issues/1894
2025-12-12 23:06:59 +05:30
Charles BochetandGitHub afcca283c4 Prevent table columns to be too narrow (#16542)
😬
<img width="453" height="312" alt="image"
src="https://github.com/user-attachments/assets/d233a430-8364-4f82-bae9-4324690bac9a"
/>
2025-12-12 18:15:25 +01:00
WeikoandGitHub 62408e7fd3 Fix APIKey in search resolver for get role (#16540)
Fixes https://github.com/twentyhq/twenty/issues/16534

Typing was wrong, apiKey from request object is ApiKeyEntity and not a
string which was then failing when using
```typescript
const roleId = apiKeyRoleMap[apiKeyId];

    if (!isDefined(roleId)) {
      throw new ApiKeyException(
        `API key ${apiKeyId} has no role assigned`,
        ApiKeyExceptionCode.API_KEY_NO_ROLE_ASSIGNED,
      );
    }
```

error
```
API key [object Object] has no role assigned"
```

## Before
<img width="963" height="316" alt="Screenshot 2025-12-12 at 17 37 06"
src="https://github.com/user-attachments/assets/761a75c6-1bac-48d7-b8cd-3356e9a56028"
/>

## After
<img width="905" height="313" alt="Screenshot 2025-12-12 at 17 36 44"
src="https://github.com/user-attachments/assets/475b7106-713c-408e-99d0-1447599f7152"
/>
2025-12-12 17:54:07 +01:00
ee47a773bd Fixed Apollo cache bug (#16523)
Fixes https://github.com/twentyhq/twenty/issues/16520

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-12 17:45:50 +01:00
Paul RastoinandGitHub f0af947331 [RenameIndexCommand] Fix orphaned index edge case (#16539)
We've been facing orphaned metadata index that would result in alter
error, now if we encounter one we just delete it
2025-12-12 16:44:00 +00:00
WeikoandGitHub 0035fc1145 Fix rest metadata version missing (#16536)
## Context

The REST pipeline re-fetches/sets the metadata version later in
RestApiBaseHandler#getObjectMetadata by reading from DB and seeding the
cache if it’s missing. That’s the place that actually needs it and
already handles the “undefined” case.

This also mirror the graphql path that was updated 3 weeks ago
2025-12-12 17:25:57 +01:00
3e17140385 i18n - docs translations (#16537)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-12 17:21:40 +01:00
Paul RastoinandGitHub 59663ec34e fix(server): non blocking CleanEmptyStringNullInTextFieldsCommand error (#16529)
# Introduction
Getting query timeout on prod upgrade for workspace that has huge
timeline activity table
2025-12-12 16:02:23 +01:00
4b292ac780 i18n - translations (#16527)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-12 15:21:11 +01:00
Raphaël BosiandGitHub d30453f38f [DASHBOARDS] Fix date order by (#16521)
## Bug description

The date order by was always set to date ascending regardless of the
setting. This PR fixes this and removes the possibility to sort by value
for date fields as it doesn't really make sense.

## Video QA


https://github.com/user-attachments/assets/cffc69e7-bee0-4944-88bb-bdf24fe0dd54
2025-12-12 14:55:44 +01:00
6acdde72ef Fix fetch more notes (#16442)
fixes : https://github.com/twentyhq/twenty/issues/16320

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-12 14:43:21 +01:00
8dbcd506ed feat: add feature to customize onClick behaviour for phone, email and links data type (#16265)
Fixes Issue: #15797

This PR adds a configurable click behavior setting for Phone, Email, and
Links field types, allowing users to customize what happens when
clicking on these fields.

A new option (**Click Behaviour**) to configure the default behaviour
for onClick of data is added in the settings page (Settings → Data Model
→ Object → Field Edit) for Phone, Email and Links data types.

Users can now choose between two actions:
- **Copy to clipboard**: Copies the value to clipboard with a success
toast message
- **Open as link**: Opens the value as a link (tel:, mailto:, or
http/https)

The default behaviour is persisted for all these three types(phone- Copy
to clipboard, email & links: open link) to maintain backward
compatibility.

**Screenshots :** 
<img width="2084" height="1736" alt="image"
src="https://github.com/user-attachments/assets/eb5d129c-e3e0-4334-b426-eb38d8a4840c"
/>

<img width="1474" height="1428" alt="image"
src="https://github.com/user-attachments/assets/487f4e44-6151-4254-bc5c-5398be5fc087"
/>
<img width="1594" height="1398" alt="image"
src="https://github.com/user-attachments/assets/abdbc213-7223-4d57-809e-4d55c90cda80"
/>

---------

Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2025-12-12 14:34:47 +01:00
Félix MalfaitandGitHub 4f91b48470 feat(ai): add context usage display to AI chat (BREAKING: deploy server first) (#16518)
## Summary

- Add a context usage indicator to the AI chat interface inspired by
Vercel's AI SDK Context component
- Display token consumption, context window utilization percentage, and
estimated cost in credits
- Show a circular progress ring with percentage, revealing detailed
breakdown on hover

## Changes

### Backend
- Stream usage metadata (tokens, model config) via `messageMetadata`
callback in `agent-chat-streaming.service.ts`
- Return model config from `chat-execution.service.ts`
- Add usage and model types to `ExtendedUIMessage` metadata

### Frontend
- New `ContextUsageProgressRing` component - circular SVG progress
indicator
- New `AIChatContextUsageButton` component with hover card showing:
  - Progress bar with used/total tokens
  - Input/output token counts with credit costs
  - Total credits consumed
- Track cumulative usage in Recoil state (`agentChatUsageState`)
- Reset usage when creating new chat thread
- Integrate button into `AIChatTab`

## Test plan

- [ ] Open AI chat and send a message
- [ ] Verify the context usage button appears with percentage
- [ ] Hover over the button to see detailed breakdown
- [ ] Verify credits are calculated correctly
- [ ] Create a new chat thread and verify usage resets to 0
2025-12-12 13:42:00 +01:00
ec243e9874 i18n - docs translations (#16524)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-12 13:22:59 +01:00
19f20cd37b i18n - translations (#16522)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-12 12:20:58 +01:00
EtienneandGitHub c274adf4d8 Fix raw json field display in read only (#16502)
Preview
<img width="1185" height="617" alt="Screenshot 2025-12-11 at 15 54 07"
src="https://github.com/user-attachments/assets/863fb58c-04df-4e4d-bf8c-0045c833466c"
/>

Fixes https://github.com/twentyhq/twenty/issues/16311
2025-12-12 11:27:02 +01:00
WeikoandGitHub bd8ed03990 Add TTL eviction to local data cache (#16510)
We keep different versions of our cache to avoid race conditions but we
never evict stale data. This PR should fix that
2025-12-12 10:14:46 +01:00
Abdul RahmanandGitHub 4b2a604ef0 Filter BAD_USER_INPUT errors from Sentry (#16511)
Closes #15561
2025-12-12 09:08:50 +01:00
Abdul RahmanandGitHub 865265d0d9 fix: Display locked UI for restricted email thread messages (#16512)
Closes #15289 

<img width="410" height="609" alt="Screenshot 2025-12-12 at 1 08 46 AM"
src="https://github.com/user-attachments/assets/34ea73e6-8664-4b59-96ad-3c15d04e148c"
/>
2025-12-12 09:05:52 +01:00
Félix MalfaitandGitHub 5f4f4c0af8 feat(ai): add dashboard tools for AI chat (#16517)
## Summary

- Implements real tools for the dashboard-building skill to create and
manage dashboards through the AI chat interface
- Adds 6 new dashboard tools: `create_complete_dashboard`,
`list_dashboards`, `get_dashboard`, `add_dashboard_widget`,
`update_dashboard_widget`, `delete_dashboard_widget`
- Improves widget configuration robustness with typed Zod schemas and
discriminated unions for graph types

## Key Changes

**New Dashboard Tools:**
- `create_complete_dashboard` - Creates a dashboard with layout, tab,
and widgets in a single call
- `list_dashboards` - Lists all dashboards in the workspace
- `get_dashboard` - Gets full dashboard details including tabs and
widget configurations
- `add_dashboard_widget` - Adds a widget to an existing dashboard tab
- `update_dashboard_widget` - Updates widget properties or configuration
- `delete_dashboard_widget` - Removes a widget from a dashboard

**Widget Configuration Improvements:**
- Typed Zod schemas for each chart type (AGGREGATE, BAR, LINE, PIE)
- Discriminated union validation based on `graphType`
- Widget-level error handling for partial success when creating
dashboards
- Clear documentation about required `objectMetadataId` and field UUIDs

**Skill Documentation Updates:**
- Updated `dashboard-building.skill.ts` with critical guidance about
looking up field metadata first
- Added workflow instructions: use `list_object_metadata_items` before
creating GRAPH widgets
- Practical grid layout recommendations

## Test plan

- [ ] Create a new dashboard via AI chat
- [ ] Verify widgets display data correctly when proper field IDs are
provided
- [ ] Test adding/updating/deleting widgets on existing dashboards
- [ ] Verify error messages are helpful when configuration is incorrect
2025-12-12 07:35:14 +01:00
Félix MalfaitandGitHub 70a78aafe9 feat(ai): replace agent search with skills system (#16513)
## Summary

- Replace the agent search mechanism with a new skills-based system
- Add a `skills` module with predefined skill definitions that the AI
can load on demand
- Remove specialized agents (workflow-builder, data-manipulator,
dashboard-builder, metadata-builder, researcher), keeping only the
helper agent
- Add `recordReferences` to workflow creation tool for chip linking in
the UI

## Changes

### New Skills Module
- `skill-definitions.ts` - Contains 5 skill definitions with detailed
instructions
- `skills.service.ts` - Service to get skills by name
- `load-skill.tool.ts` - Tool for AI to load skills explicitly

### Removed
- `agent-search.tool.ts` - Replaced by skill loading
- Specialized agent definitions (converted to skills)

### Updated
- Chat execution now shows skill catalog in system prompt
- Workflow creation returns `recordReferences` for UI linking

## Test plan
- [ ] Verify AI can load skills using `load_skill` tool
- [ ] Verify skill content is returned correctly
- [ ] Verify workflow creation shows clickable chip in chat
- [ ] Verify helper agent still works
2025-12-12 06:51:25 +01:00
4d90a8f6e3 i18n - docs translations (#16516)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-12 02:07:40 +01:00
14b2487d25 i18n - translations (#16515)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-12 00:01:10 +01:00
aad581a353 i18n - translations (#16514)
Created by Github action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 23:21:05 +01:00
Félix MalfaitandGitHub a13727335b feat(ai): refresh AI models with deprecation support and multi-provider defaults (BREAKING: deploy server before frontend please) (#16503)
## Summary

- Add latest AI models from OpenAI (GPT-4.1, o3, o4-mini), Anthropic
(Claude 4.5 Opus/Sonnet/Haiku), and xAI (Grok 4.1)
- Mark deprecated models (GPT-4o, GPT-4o-mini, GPT-4-turbo, Claude Opus
4, Claude Sonnet 4) with a `deprecated` flag
- Split AI models into separate files per provider for better
maintainability
- Support comma-separated default model lists for automatic fallback
across providers (works out of the box for self-hosters regardless of
which provider they configure)
- Filter deprecated models from dropdown selection while keeping them
functional for existing agents

## Changes

### New Models Added
| Provider | Models |
|----------|--------|
| OpenAI | gpt-4.1, gpt-4.1-mini, o3, o4-mini |
| Anthropic | claude-opus-4-5, claude-sonnet-4-5, claude-haiku-4-5 |
| xAI | grok-4-1-fast-reasoning |

### Deprecated Models
- gpt-4o, gpt-4o-mini, gpt-4-turbo (OpenAI)
- claude-opus-4-20250514, claude-sonnet-4-20250514 (Anthropic)

### Config Changes
Default model configs now support comma-separated fallback lists:
-
`DEFAULT_AI_SPEED_MODEL_ID=gpt-4.1-mini,claude-haiku-4-5-20251001,grok-3-mini`
-
`DEFAULT_AI_PERFORMANCE_MODEL_ID=gpt-4.1,claude-sonnet-4-5-20250929,grok-4`

## Test plan

- [x] Unit tests pass
- [x] Typecheck passes
- [x] Lint passes
- [ ] Verify deprecated models don't appear in model dropdowns
- [ ] Verify agents with deprecated models still work correctly
- [ ] Verify default model fallback works when only one provider is
configured
2025-12-11 21:47:38 +01:00
GuillimandGitHub 999bc84b17 fix(server): Favortites, attachments, timeline... (#16509)
fix(server): system objects like Favortites, attachments, timeline...
should be system fields
2025-12-11 18:28:14 +01:00
WeikoandGitHub 083a038f8a Deprecate workspace datasoure (#16507) 2025-12-11 18:27:49 +01:00
Raphaël BosiandGitHub 3dd2684254 Fix dashboard duplication (#16505)
Use `UUID!`
2025-12-11 16:47:51 +01:00
Raphaël BosiandGitHub 2da56c1886 Fix default order by (#16492)
Always apply an order by on the group by
2025-12-11 15:46:48 +01:00
7f9e948e05 i18n - docs translations (#16501)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 15:21:36 +01:00
ec8773437e Improved table flash on reload (#16419)
This PR fixes https://github.com/twentyhq/core-team-issues/issues/1732

There is still some room for improvement but the main goal is reached :
removing the flash effect each time the table virtualization has to
recompute due to an update after initial loading.

# QA

## Create 


https://github.com/user-attachments/assets/1b4fc307-42ce-4ba6-b557-68ac7fcad40f

## Update with sort


https://github.com/user-attachments/assets/e0700f44-8926-4395-8ab8-b32773f21de8

## Update with filter


https://github.com/user-attachments/assets/d325f85a-1a7b-4366-aac3-250331be7575

## Soft delete


https://github.com/user-attachments/assets/2c980183-c637-4aa7-a0ca-244e61396b20

## Restore and destroy


https://github.com/user-attachments/assets/01af9ec7-b442-4686-a1d7-ea1fc543fe62

## Drag & drop


https://github.com/user-attachments/assets/bba76bdb-d4ec-433d-b44e-37fdb9952b06

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-11 15:14:20 +01:00
Félix MalfaitandGitHub 3cea19baf4 feat(ai): add view management tools for AI chat (#16495)
## Summary

Adds a new **VIEW** tool category for the AI chat, enabling it to work
with views:

- **get-views**: List views in the workspace, optionally filtered by
object metadata ID
- **get-view-query-parameters**: Convert a view's filters and sorts into
GraphQL query parameters that can be passed to existing `find_*` data
tools
- **create-view**, **update-view**, **delete-view**: CRUD operations for
view management

### Key design decisions

1. **No pagination duplication**: Instead of creating a
`find-records-from-view` tool that would duplicate pagination logic,
`get-view-query-parameters` returns filter/sort parameters that the AI
can pass to existing record-fetching tools.

2. **Permission model**:
- Read tools (get-views, get-view-query-parameters) are available to all
users
   - Write tools require the `VIEW` permission
   - UNLISTED views can only be modified by their creator

3. **Leverages existing utilities**: Uses
`computeRecordGqlOperationFilter` from `twenty-shared` for filter
conversion.

### Files changed

- Added `ViewToolProvider`, `ViewToolsFactory`, and
`ViewQueryParamsService`
- Added `VIEW` to `ToolCategory` enum and tool registry
- Updated `chat-execution.service.ts` to include view tools in the
catalog and pass viewId in browsing context
- Extracted shared `formatValidationErrors` utility to reduce
duplication

## Test plan

- [x] Unit tests for `ViewToolsFactory` 
- [x] Unit tests for `ViewQueryParamsService`
- [x] Lint and typecheck pass
2025-12-11 15:05:42 +01:00
2943125410 i18n - translations (#16500)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 15:01:58 +01:00
Paul RastoinandGitHub f06a5ccacd Remove sync metadata from upgrade (#16491)
# Introduction
Related https://github.com/twentyhq/core-team-issues/issues/1910
From now on the upgrade won't integrate any sync metadata as it's going
to be deprecated very soon
Any updates to about to removes workspace-entity or standard flat entity
will require a dedicated upgrade command, what we've already started
doing during the 1.13 sprint, until we have totally migrated the v2 to
be workspace agnostic
2025-12-11 14:50:56 +01:00
Baptiste DevessierandGitHub 9c1197c0b2 fix: constrain side column width (#16498)
## Before


https://github.com/user-attachments/assets/18bfd8b0-7636-40b2-aa64-24c84ab74009

## After

<img width="3456" height="2160" alt="CleanShot 2025-12-11 at 14 13
23@2x"
src="https://github.com/user-attachments/assets/e10dc51c-afdb-4145-8ed5-0aaadfebb48b"
/>
2025-12-11 14:32:26 +01:00
GuillimandGitHub b83dc3aaff TimelineActivity migration to morph (#15652)
# TimelineActivity migration to morph


- Creates `timelineActivities2` relations on Company, Dashboard, Note,
Opportunity, Person, Task, Workflow, WorkflowRun, and WorkflowVersion
entities with proper metadata and cascade delete behavior.

It was required to create standard fields as well since the
mapObjectMetadataByUniqueIdentifier needs it. otherwise the fields won't
be considered

- Feature Flag `IS_TIMELINE_ACTIVITY_MIGRATED` necessary to have the two
states in parallel. It is used as a stamp once the migration has been
run

- Migration is done using the coreDataSource. Why ?
even though is unsafe to use, the first implementation of the migration
took forever on each workspace. See [this
commit](https://github.com/twentyhq/twenty/pull/15652/commits/477011e8d7d4c580f79ba7ec4a8fb002a3ec86b2)

The plan for this complex migration is as follows :

![plan](https://github.com/user-attachments/assets/51c63ea6-fb0d-40b4-b99d-3e0b35a204e6)
Note: we will need to rename fields in the release 1.12 (there is no
easy way to do all this in one release)
2025-12-11 14:28:26 +01:00
Baptiste DevessierandGitHub c13ef0c4a4 Fix overflow text with tooltip (#16490)
This PR allows the `OverflowingTextWithTooltip` component to take
complex content as parameter. It fixes the buggy display of long records
pinned as favorites.


https://github.com/user-attachments/assets/0224da09-8547-4def-927d-3f545406287e

Created extensive stories to test every case. Cleaned the component.

## Demo


https://github.com/user-attachments/assets/a8f257b5-2baf-42da-897b-a76b8a9ab664
2025-12-11 13:49:56 +01:00
918b145fb5 i18n - docs translations (#16497)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 13:43:50 +01:00
310bf5fe9a i18n - translations (#16496)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 13:02:10 +01:00
Raphaël BosiandGitHub 5af2d37253 [DASHBOARDS] Dashboard duplication (#16291)
## Description

- Created a Dashboard duplication action
- Created a new duplication custom resolver
- Created the service using the v2 of the API
- Created the integration tests following the v2 methodology

## Video QA


https://github.com/user-attachments/assets/e409951a-5946-4da0-91a0-1f7d2ecadb08
2025-12-11 11:15:15 +00:00
6c728fff78 i18n - docs translations (#16489)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 11:21:26 +01:00
5a697e914b i18n - translations (#16487)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 11:01:08 +01:00
Félix MalfaitandGitHub bc57b8ee4e feat(ai): add browsing context and fix tool loading (#16476)
## Summary

- Add `BrowsingContext` type to automatically pass what the user is
currently viewing (recordPage or listView) to the AI chat
- Simplify context architecture: remove toggleable context UI, make it
automatic and invisible to the user
- Fix tool loading: add `unionOf` handling in
`getDatabaseToolsForObject` and fix regex ordering so `find_one_*` tools
are properly registered
- Use plural names for find tools (`find_people` vs `find_one_person`)
for better semantics
- Clean up unused components and states

## Changes

### Frontend
- New `BrowsingContext` type and `useGetBrowsingContext` hook to gather
context from Recoil state
- Simplified `useAgentChat` to use the new browsing context
- Removed toggleable context UI components
(`AgentChatContextRecordPreview`, `SendMessageWithRecordsContextButton`,
etc.)
- Removed `isAgentChatCurrentContextActiveState`

### Backend
- New `BrowsingContextType` for recordPage and listView contexts
- Updated `ChatExecutionService` to build context from browsing context
- Fixed `tool-registry.service.ts`:
  - Added `unionOf` handling in permission config
- Fixed regex ordering (`find_one` before `find`) so tools load
correctly
- Use plural names for search tools (`find_people` instead of
`find_person`)

## Test plan

- [x] Typecheck passes
- [x] Lint passes
- [ ] Test AI chat on record page - should show context in system prompt
- [ ] Test AI chat on list view - should show view name and filters
- [ ] Test `find_one_*` tools now load correctly
- [ ] Test `find_*` tools use plural naming
2025-12-11 10:19:27 +01:00
GuillimandGitHub 5daef28328 Morph INPUT integration test (#16464)
- Adding a new target to the test setup suite
- We add the MORPH_RELATION to the list of types we wanna test in the
current test suites

Important:
I noticed the REST API was not working well with Morph relations. I
created [an
issue](https://github.com/twentyhq/core-team-issues/issues/2002) to work
on that. Within that timeframe, I `xdescribed` the related tests

Fixes https://github.com/twentyhq/core-team-issues/issues/1327
2025-12-11 10:10:30 +01:00
Thomas TrompetteandGitHub 7021cd41ea Use rich text editor in form field (#16474)
Fix https://github.com/twentyhq/twenty/issues/15948

Before
<img width="982" height="505" alt="Capture d’écran 2025-12-10 à 17 26
17"
src="https://github.com/user-attachments/assets/661a8205-cb1f-4b4b-8f0a-813c09ac9d16"
/>

After
<img width="982" height="767" alt="Capture d’écran 2025-12-10 à 17 25
49"
src="https://github.com/user-attachments/assets/58fa83a8-890e-42cb-a0bd-c5f6d7890d37"
/>
2025-12-11 08:43:29 +01:00
1077cf1560 i18n - translations (#16482)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-11 01:40:49 +01:00
MarieandGitHub 7a7f36d38c [Fix] Forbid default value removal for non-nullable select field (#16465)
Permanently fixes https://github.com/twentyhq/private-issues/issues/389

On a non-nullable select field, default value should not be removable,
otherwise users won't be able to create new records from the interface.
This PR enforces this in FE and BE.


https://github.com/user-attachments/assets/1dfa2bcc-b9df-4a00-9915-679d36ec1b25
2025-12-11 00:53:48 +01:00
Charles BochetandGitHub bed5270f3c Message/Calendar thread temporary fix during datasource refactoring (#16480)
The current repository implementation require the caller to pass the
permissionConfig which is not the case in messaging and calendar custom
resolver. We are bypassing the permission as fetching the role in the
caller will likely not be needed anymore in the new datasource / orm
implementation
2025-12-11 00:22:48 +01:00
Charles BochetandGitHub 2948880a0b Fix typecheck on messaging (#16477)
As per title
2025-12-10 17:59:45 +01:00
neo773andGitHub b760e6df46 fix process group emails (#16473) 2025-12-10 17:43:50 +01:00
WeikoandGitHub 9bd8f94b3a Refactor global datasource part 3 (#16447)
## Context
Following https://github.com/twentyhq/twenty/pull/16399
Now using the new global orm manager everywhere and returning a
GlobalDatasource/WorkspaceDatasource based on a feature flag.
This means we now need to wrap all our ORM calls within
executeInWorkspaceContext callback (at least for now) so the global
datasource can dynamically hydrate its context via the new store (the
global datasource does not store anything related to workspaces as it is
now a unique singleton). If feature flag is off it still uses local data
stored in the workspace datasource.
2025-12-10 17:17:33 +01:00
Paul RastoinandGitHub 4f13022774 Remaining standard view, view filter/group/field (#16466)
# Introduction
Following https://github.com/twentyhq/twenty/pull/16436
Related https://github.com/twentyhq/core-team-issues/issues/1995

## Objects

### 1. **Task** 📋
- **3 Views**: allTasks, byStatus, assignedToMe
- **20 View Fields** across all views
- **7 View Groups**: 4 for assignedToMe (TODO, IN_PROGRESS, DONE,
empty), 3 for byStatus
- **1 View Filter**: assigneeIsMe

### 2. **Opportunity** 💼
- **2 Views**: allOpportunities, byStage (kanban with MIN aggregation)
- **12 View Fields** (6 per view)
- **5 View Groups**: NEW, SCREENING, MEETING, PROPOSAL, CUSTOMER

### 3. **Company** 🏢
- **1 View**: allCompanies
- **8 View Fields** (includes COUNT, MAX, PERCENTAGE_EMPTY aggregations)

### 4. **Person** 👤
- **1 View**: allPeople
- **10 View Fields** (includes COUNT_UNIQUE_VALUES, PERCENTAGE_EMPTY,
MIN aggregations)

### 5. **Note** 📝
- **1 View**: allNotes
- **5 View Fields**

### 6. **Message** 📧
- **1 View**: allMessages
- **7 View Fields**

### 7. **Message Thread** 💬
- **1 View**: allMessageThreads
- **2 View Fields**

### 8. **Calendar Event** 📅
- **1 View**: allCalendarEvents (with calendar field: startsAt)
- **8 View Fields**

### 9. **Workflow** ⚙️
- **1 View**: allWorkflows
- **6 View Fields**

### 10. **Workflow Run** 🏃
- **1 View**: allWorkflowRuns
- **3 View Fields**

### 11. **Dashboard** 📊
- **1 View**: allDashboards
- **4 View Fields**

---
2025-12-10 16:44:20 +01:00
Lucas BordeauandGitHub 3648fa064c Fixed workflow filter initialization (#16471)
This PR fixes https://github.com/twentyhq/twenty/issues/16165.

The bug was due to a wrong initialization of a record filter, which was
using another object metadata item than the filtered one.

As we can see in the original issue : 

```
...
"fieldMetadataId": "f12697bf-1eba-4061-bdd4-3e8a81172b79"
...
"fieldMetadataId": "658c531c-0c2e-43a1-8f70-4d6266c3841f",
...
```

The fix was to update the hook that returned the default field metadata
item to use for a new filter, and force the caller to tell which object
metadata item to use.
2025-12-10 16:43:20 +01:00
b17e45f272 Feat/wrap nav drawer with overflowing text with tooltip (#16455)
# **feat: Add tooltips for truncated names in navigation components**

### **Summary**

Adds hover tooltips across navigation components so users can view full
names when text is truncated due to limited space.

---

# **Changes Made**

### **Sidebar Navigation**

* Added tooltips to navigation drawer items and menu labels.
* Long workspace or company names now show full text on hover.

### **Top Bar**

* Added tooltip support to the View Picker dropdown header.
* Long view names (e.g., *“AuraML, very very long name”*) now reveal
their full value on hover.

---

# **Implementation**

* Integrated `OverflowingTextWithTooltip` from `twenty-ui/display`.
* Wrapped navigation and view labels with the component.
* Updated layout styles to allow accurate overflow detection.
* Tooltip appears **only** when truncation occurs; short names show no
tooltip.

---

# **User Experience**

Users can hover over any truncated workspace, company, navigation, or
view name to see the complete text—improving clarity, accessibility, and
overall navigation usability.


[https://github.com/user-attachments/assets/97f9ea6c-409c-4ec5-a27c-a7b1c5aa5682](https://github.com/user-attachments/assets/97f9ea6c-409c-4ec5-a27c-a7b1c5aa5682)

---

### **Fixes**

Closes **#16412**

---

---------

Co-authored-by: Devessier <baptiste@devessier.fr>
2025-12-10 16:08:44 +01:00
WeikoandGitHub 0a11add616 Fix sync role v1 (#16459)
## Context
SyncMetadata for role update was broken when those roles had permission
flags in them.
This PR https://github.com/twentyhq/twenty/issues/16365 introduced a
change in all existing standard roles which probably triggered the
update of faulty roles for the first time. Down the line, some
properties from flat were not omit before querying the DB (in this case
permissionFlagIds does not exist as a column in role table)

The fix is definitely not great, this also probably broke the update of
permissionFlags for existing STANDARD roles but it's not subject to
change (It actually never changed. Again, what has been updated was not
the permission flag but a new boolean introduced 2 days ago which forced
the "UPDATE" path in the sync which was probably never triggered before,
or at least not for roles with permission flags which are "quite" new).
Also we are about to remove this whole code in favor of the new
migration v2
2025-12-10 15:45:04 +01:00
Paul RastoinandGitHub 478c753a50 [Validate build and run] Early return if workspace migration has no actions (#16467)
# Introduction
Early returning in `validateBuildAndRun` as the runner even if passed an
empty workspace migration actions array be invalidating dependency
related flat entity maps.
When we will refactor the runner to consume the generic flat entity maps
tools such as
`addFlatEntityToFlatEntityAndRelatedEntityMapsThroughMutationOrThrow` we
will be able to remove the dependency cache invalidation
2025-12-10 14:23:22 +00:00
ac0ec88a87 i18n - docs translations (#16470)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-10 15:21:40 +01:00
Félix MalfaitandGitHub 5df8fd90c3 feat: simplify AI chat architecture and add record links (#16463)
## Summary

This PR significantly simplifies the AI chat architecture by removing
complex routing/planning mechanisms and introduces clickable record
links in AI responses.

## Changes

### AI Chat Architecture Simplification
- **Removed** the entire `ai-chat-router` module (~850 lines) including:
  - Strategy decider service
  - Plan generator service
  - Complex routing logic
- **Removed** agent execution planning services (~700 lines):
  - `agent-execution.service.ts`
  - `agent-plan-executor.service.ts`
  - `agent-tool-generator.service.ts`
- **Added** centralized `ToolRegistryService` for tool management:
  - Builds searchable tool index (database, action, workflow tools)
  - Provides tool lookup by name
  - Supports agent search for loading expertise
- **Added** `ChatExecutionService` as simple replacement:
  - Includes full tool catalog in system prompt
- Pre-loads common tools (find/create/update for company, person,
opportunity, task, note)
  - Uses `load_tools` mechanism for dynamic tool activation
  - Enables native web search by default

### Record References in AI Responses
- Added `recordReferences` field to tool outputs for create, find, and
update operations
- Implemented `[[record:objectName:recordId:displayName]]` syntax for AI
to reference records
- Created `RecordLink` component that renders clickable chips with
object icons
- Integrated record link parsing into the markdown renderer
- Users can now click directly on created/found records in AI responses

### Workflow Agent Fixes
- Fixed cache invalidation issue when creating agents in workflows
- Added default prompt for workflow-created agents to prevent validation
errors
- Relaxed agent validation to only check properties being updated (not
all required properties)

### Code Quality Improvements
- Extracted `getRecordDisplayName` utility that mirrors frontend's
`getLabelIdentifierFieldValue` logic
- Uses object metadata to determine the correct label identifier field
- Handles `FULL_NAME` composite type for person/workspaceMember objects
- Shared across create, find, and update record services

## Net Impact
- **~1,200 lines deleted** (complex routing/planning code)
- **~500 lines added** (simpler tool registry + record links)
- Significantly reduced code complexity
- Better tool discovery through full catalog in system prompt
- Improved UX with clickable record references

## Testing
- Typecheck passes
- Lint passes
- Manual testing of AI chat with record creation and linking
2025-12-10 15:14:12 +01:00
WeikoandGitHub 59b54f254e Fix missing shouldHideEmptyGroups in fromCreateViewInputToFlatViewToCreate typecheck (#16468) 2025-12-10 14:09:31 +00:00
EtienneandGitHub 5e44781be1 Fix line break in richTextV2 field workflow editor (#16462)
Api expect markdown format where '\n' is escape (but not '  \n')

fixes https://github.com/twentyhq/twenty/issues/14976
2025-12-10 14:08:08 +00:00
89cc59d8ab fix(CSV export): update the csv export format for multi-select and arrray fields to match the import template format (#16450)
Closes #16432

Multi-Select and Array fields were exported in an incompatible format:
**Before**: {"0":"VALUE1","1":"VALUE2"} (object with numeric keys)
**After**: ["VALUE1","VALUE2"] (JSON array)

This prevented exported CSV files from being re-imported successfully.

### Changes
Modified useExportProcessRecordsForCSV hook to stringify Multi-Select
and Array fields as JSON arrays before CSV generation

---------

Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2025-12-10 14:07:43 +00:00
Raphaël BosiandGitHub f48adb5f07 Migrate page layout services (#16443)
Last step of the page layout migration:
- Migrate services
- Write integration tests
2025-12-10 13:49:44 +00:00
Abdul RahmanandGitHub 1839f8e946 Fix: Persist hide empty groups setting on backend (BREAKING: deploy server first) (#16385)
Closes #13754 and [core team issue
#414](https://github.com/twentyhq/core-team-issues/issues/414)
2025-12-10 19:10:29 +05:30
Baptiste DevessierandGitHub 20f2ca6864 Prevent seeding empty configuration for dashboard widgets (#16458)
We used to seed widgets with empty configuration when the fields they
required weren't defined. I suggest we only seed properly defined
widgets.
2025-12-10 14:40:02 +01:00
Paul RastoinandGitHub 20879c8147 Standard views tooling (#16436)
# Introduction
In this PR we've introduced the type safe generation tooling for
standard view, view fields, view filters and view groups.
Also generated the ids before such as what was done for object and
fields, it's still temporary as will be replaced by universalIdentifier
mapping afterwards

## Task views
In this PR only implemented the `task` views and view groups, filters
and fields in order to battle test all the generation tools
Will create a dedicated PR that will implement all the remaining views.
2025-12-10 14:29:01 +01:00
1e166ccb53 Fix file preview modal to always open full screen from command menu (#16446)
Closes #16434 




https://github.com/user-attachments/assets/ecf838ea-9f59-42d9-9a2d-97a4fa3b7910

---------

Co-authored-by: Baptiste Devessier <baptiste@devessier.fr>
2025-12-10 13:16:57 +00:00
bc274b9937 i18n - docs translations (#16461)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-10 13:23:06 +01:00
Abdul RahmanandGitHub d932ec28e3 Show friendly message for non-previewable file previews (#16372)
<img width="1507" height="807" alt="Screenshot 2025-12-06 at 12 50
42 AM"
src="https://github.com/user-attachments/assets/9e13d813-76fa-43e9-9dea-ead1dca4ca1f"
/>

Closes #15771
2025-12-10 12:50:29 +01:00
30e3aa5961 i18n - translations (#16457)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-10 11:21:54 +01:00
WeikoandGitHub 915e0fd436 Fix formatData util logging (#16454)
Log introduced in https://github.com/twentyhq/twenty/pull/16389
However this is a util hence cannot simply inject the logger service.
I'm removing the log for now as adding loggerService as a parameter of a
util might not be the right solution (yet)
```typescript
this.logger.warn(`Field metadata for field "${key}" is missing in object metadata ${flatObjectMetadata.nameSingular} for data: ${JSON.stringify(data)}`);
                 ^
TypeError: Cannot read properties of undefined (reading 'logger')
```
2025-12-10 10:53:18 +01:00
Baptiste DevessierandGitHub fd54a2af5c Create fields widget (#16403)
https://github.com/user-attachments/assets/b150815a-5d54-4d4a-b984-20dcf7b29aa7
2025-12-10 10:31:36 +01:00
Paul RastoinandGitHub 7b98804ec1 Fix flat field metadata date type (#16445)
# Introduction
Following https://github.com/twentyhq/twenty/pull/16420
2025-12-09 19:53:36 +01:00
Charles BochetandGitHub 83fc434c5d Fix workspace invite onboarding loop (#16444)
- The issue is that the listener is not triggered if they are no change
to the workspaceMember (which happens when name is already filled
through GoogleSSO)

Fixes https://github.com/twentyhq/twenty/issues/16440
2025-12-09 19:18:17 +01:00
nitinandGitHub 3e9820fa8d fix line chart's no data calculations and update tests (#16441)
closes
https://discord.com/channels/1130383047699738754/1447976382528360520
2025-12-09 23:03:32 +05:30
adb38631b3 i18n - docs translations (#16435)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-09 17:22:08 +01:00
Charles BochetandGitHub aa519e7d81 Fix messaging errors on message folder list (#16404)
This is a known quirk of many Google APIs, including Gmail. Some error
responses use numeric code fields (e.g., 403), while others may return
them as strings (e.g., "403"). This depends on which internal service
returns the error and the language client you’re using.
2025-12-09 17:01:25 +01:00
Charles BochetandGitHub a18203934c Fix flat entity maps date serialization (#16420)
Changes:
- as we store date in redis as serialized, let's make all flatEntity
dates as string. This requires changing FlatEntity types and making sure
that entity are converted to flatEntity and flatEntity to dtos
2025-12-09 16:41:50 +01:00
608e5751a9 i18n - translations (#16433)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-09 16:21:37 +01:00
nitinandGitHub 7af3da9393 [Dashboards] add ratio aggregate on aggregate chart (#16413)
closes https://github.com/twentyhq/core-team-issues/issues/1960
video QA


https://github.com/user-attachments/assets/e90cee44-5edc-430d-b003-03ab4ea921f7
2025-12-09 15:23:21 +01:00
Thomas TrompetteandGitHub bd49fd8d5f Remove object relation schema from step output (#16428)
Fix https://github.com/twentyhq/core-team-issues/issues/1931

On trigger database event and step record crud, we still display the
full object for relation in the variable picker (Account Owner in
screenshot).
<img width="259" height="189" alt="Capture d’écran 2025-12-09 à 14 43
06"
src="https://github.com/user-attachments/assets/1d7fdebf-9183-4197-929a-7b7d719c465a"
/>

But as we do not enrich the data anymore, those fields are actually
empty. We should instead display AccountOwnerId and, if the user needs
the full Account owner, a search can be used.
<img width="259" height="189" alt="Capture d’écran 2025-12-09 à 14 42
37"
src="https://github.com/user-attachments/assets/87b46762-3204-4d25-9b6a-077d6b8567bd"
/>
2025-12-09 14:10:12 +00:00
Paul RastoinandGitHub e758f78caf Finalize standard index as code declaration (#16429)
# Introduction
Following https://github.com/twentyhq/twenty/pull/16426
Related https://github.com/twentyhq/core-team-issues/issues/1995
2025-12-09 14:05:27 +00:00
Thomas TrompetteandGitHub 3ba7a070d9 Fix is empty and non empty filter for numbers (#16424)
isNonEmptyString does not work for a number. We need to properly handle
null and undefined
2025-12-09 14:55:14 +01:00
Paul RastoinandGitHub e8d4f11d8e Standard index as code introduction + type refactor (#16426)
# Introduction
Related https://github.com/twentyhq/core-team-issues/issues/1995

In this PR we're introducing the standard index tools for their
declaration
Also adding a common typing in order to have a simily consistency across
standard builders

Will implement remaining standard index builder in an other PR
2025-12-09 14:52:25 +01:00
Paul RastoinandGitHub 4996f3dd28 Finalize twenty standard app as workspace migration object and fields (#16353)
# Introduction
Related to https://github.com/twentyhq/core-team-issues/issues/1995
In this PR we're fixing the remaining object/fields validation errors
resulting from standard objects and fields now passing a validation that
wasn't when using the sync metadata

## Key Changes
- **Field naming**: Renamed `iCalUID` to `iCalUid` for consistent
camelCase convention across calendar events
- **Enum standardization**: Uppercased enum values for message channels
(email→EMAIL), message participants (from→FROM, to→TO, cc→CC, bcc→BCC),
and message direction (incoming→INCOMING, outgoing→OUTGOING)
- **Label simplification**: Removed example values from workspace member
number format labels for cleaner UI
- **Migration infrastructure**: Added `isSystemBuild` flag throughout
field metadata service pipeline to allow system-level updates of
standard fields that bypass normal restrictions

## Migrating the existing data
We've created an upgrade command that will identify using the existing
object and field standard id field that needs to be updated, even though
the sync metadata still in usage could have fix them ( and the goal is
to deprecate it by the end of the sprint )
We will call the updateOneField for each of them, we're passing by the
field service in order to battle test what are going to be the temporary
way to handle standard migrations when we will start deprecating the
sync metadata but haven't still refactored the v2 workspace migration to
be workspace agnostic

## Twenty eng migration
Tested the whole migration + upgrade on twenty eng
Here are generated workspace migration
Records are handled natively gracefully too

### ICalUid
```json
{
  "status": "success",
  "workspaceMigration": {
    "relatedFlatEntityMapsKeys": [
      "flatFieldMetadataMaps",
      "flatIndexMaps",
      "flatViewFilterMaps",
      "flatViewGroupMaps",
      "flatViewMaps",
      "flatViewFieldMaps",
      "flatObjectMetadataMaps"
    ],
    "actions": [
      {
        "type": "update_field",
        "fieldMetadataId": "",
        "objectMetadataId": "",
        "updates": [
          {
            "from": "iCalUID",
            "to": "iCalUid",
            "property": "name"
          }
        ]
      }
    ],
    "workspaceId": ""
  }
}
```

### Incoming Outgoing
None as already caps in database somehow
```json
{
  "status": "success",
  "workspaceMigration": {
    "relatedFlatEntityMapsKeys": [
      "flatFieldMetadataMaps",
      "flatIndexMaps",
      "flatViewFilterMaps",
      "flatViewGroupMaps",
      "flatViewMaps",
      "flatViewFieldMaps",
      "flatObjectMetadataMaps"
    ],
    "actions": [],
    "workspaceId": ""
  }
}
```

### EMAIL
```json
{
  "status": "success",
  "workspaceMigration": {
    "relatedFlatEntityMapsKeys": [
      "flatFieldMetadataMaps",
      "flatIndexMaps",
      "flatViewFilterMaps",
      "flatViewGroupMaps",
      "flatViewMaps",
      "flatViewFieldMaps",
      "flatObjectMetadataMaps"
    ],
    "actions": [
      {
        "type": "update_field",
        "fieldMetadataId": "",
        "objectMetadataId": "",
        "updates": [
          {
            "from": "'email'",
            "to": "'EMAIL'",
            "property": "defaultValue"
          },
          {
            "from": [
              {
                "color": "green",
                "id": "",
                "label": "Email",
                "position": 0,
                "value": "email"
              },
              {
                "color": "blue",
                "id": "",
                "label": "SMS",
                "position": 1,
                "value": "sms"
              }
            ],
            "to": [
              {
                "color": "green",
                "id": "",
                "label": "Email",
                "position": 0,
                "value": "EMAIL"
              },
              {
                "color": "blue",
                "id": "",
                "label": "SMS",
                "position": 1,
                "value": "SMS"
              }
            ],
            "property": "options"
          }
        ]
      }
    ],
    "workspaceId": "e"
  }
}
```

### MessageParticipantRole
```json
{
  "status": "success",
  "workspaceMigration": {
    "relatedFlatEntityMapsKeys": [
      "flatFieldMetadataMaps",
      "flatIndexMaps",
      "flatViewFilterMaps",
      "flatViewGroupMaps",
      "flatViewMaps",
      "flatViewFieldMaps",
      "flatObjectMetadataMaps"
    ],
    "actions": [
      {
        "type": "update_field",
        "fieldMetadataId": "",
        "objectMetadataId": "",
        "updates": [
          {
            "from": "'from'",
            "to": "'FROM'",
            "property": "defaultValue"
          },
          {
            "from": [
              {
                "color": "green",
                "id": "",
                "label": "From",
                "position": 0,
                "value": "from"
              },
              {
                "color": "blue",
                "id": "",
                "label": "To",
                "position": 1,
                "value": "to"
              },
              {
                "color": "orange",
                "id": "",
                "label": "Cc",
                "position": 2,
                "value": "cc"
              },
              {
                "color": "red",
                "id": "",
                "label": "Bcc",
                "position": 3,
                "value": "bcc"
              }
            ],
            "to": [
              {
                "color": "green",
                "id": "",
                "label": "From",
                "position": 0,
                "value": "FROM"
              },
              {
                "color": "blue",
                "id": "",
                "label": "To",
                "position": 1,
                "value": "TO"
              },
              {
                "color": "orange",
                "id": "",
                "label": "Cc",
                "position": 2,
                "value": "CC"
              },
              {
                "color": "red",
                "id": "",
                "label": "Bcc",
                "position": 3,
                "value": "BCC"
              }
            ],
            "property": "options"
          }
        ]
      }
    ],
    "workspaceId": ""
  }
}
```

### Workspace member number format labels
```json
{
  "status": "success",
  "workspaceMigration": {
    "relatedFlatEntityMapsKeys": [
      "flatFieldMetadataMaps",
      "flatIndexMaps",
      "flatViewFilterMaps",
      "flatViewGroupMaps",
      "flatViewMaps",
      "flatViewFieldMaps",
      "flatObjectMetadataMaps"
    ],
    "actions": [
      {
        "type": "update_field",
        "fieldMetadataId": "",
        "objectMetadataId": "",
        "updates": [
          {
            "from": [
              {
                "color": "turquoise",
                "id": "",
                "label": "System",
                "position": 0,
                "value": "SYSTEM"
              },
              {
                "color": "blue",
                "id": "",
                "label": "Commas and dot (1,234.56)",
                "position": 1,
                "value": "COMMAS_AND_DOT"
              },
              {
                "color": "green",
                "id": "",
                "label": "Spaces and comma (1 234,56)",
                "position": 2,
                "value": "SPACES_AND_COMMA"
              },
              {
                "color": "orange",
                "id": "",
                "label": "Dots and comma (1.234,56)",
                "position": 3,
                "value": "DOTS_AND_COMMA"
              },
              {
                "color": "purple",
                "id": "",
                "label": "Apostrophe and dot (1'234.56)",
                "position": 4,
                "value": "APOSTROPHE_AND_DOT"
              }
            ],
            "to": [
              {
                "color": "turquoise",
                "id": "",
                "label": "System",
                "position": 0,
                "value": "SYSTEM"
              },
              {
                "color": "blue",
                "id": "",
                "label": "Commas and dot",
                "position": 1,
                "value": "COMMAS_AND_DOT"
              },
              {
                "color": "green",
                "id": "",
                "label": "Spaces and comma",
                "position": 2,
                "value": "SPACES_AND_COMMA"
              },
              {
                "color": "orange",
                "id": "",
                "label": "Dots and comma",
                "position": 3,
                "value": "DOTS_AND_COMMA"
              },
              {
                "color": "purple",
                "id": "",
                "label": "Apostrophe and dot",
                "position": 4,
                "value": "APOSTROPHE_AND_DOT"
              }
            ],
            "property": "options"
          }
        ]
      }
    ],
    "workspaceId": ""
  }
}
```
2025-12-09 14:09:48 +01:00
EtienneandGitHub be91d870f9 Fix - revert standard sync logic on index + fix command (#16421) 2025-12-09 12:54:01 +00:00
2009112712 i18n - docs translations (#16423)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-09 13:23:10 +01:00
82ee097bdc i18n - translations (#16422)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-09 12:32:54 +01:00
e5fea85351 fix : slash menu overflow causing page scroll (#16303)
Issue : #15794 

## Context
As shown in the linked issue, slash menu dropdown for rich text editor
at bottom of notes editor screen extended beyond the page container,
causing main page to scroll.

## Changes Made
Added floating UI's `flip()` middleware to the component in
`CustomSlashMenu.tsx` so that the menu automatically flips upward when
detecting not enough space for dropdown. This prevents overflow beyond
the page container.

Additionally, added offset to menu when flipping up to prevent
overlapping of the current line / caret.

## Results


https://github.com/user-attachments/assets/47a79468-779c-4fd7-8e22-2b496456ea92

---------

Co-authored-by: Hyeonjae Park <hyeonjaep@Hyeonjaes-MacBook-Pro.local>
Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2025-12-09 10:52:58 +00:00
nitinandGitHub 7e8151355d [Dashboards] add No data layer on charts (#16397)
video qa


https://github.com/user-attachments/assets/01c790de-eae7-406e-9308-af036f53ab2e
2025-12-09 10:47:42 +00:00
MarieandGitHub 790a8d6f93 Fixes on views (#16407)
Fixes

- Fixes https://github.com/twentyhq/twenty/issues/15640 : we have some
viewGroups that were in the past wrongly migrated; eg deleteing an
enum's option did not lead to deleting the associated viewGroup. We have
not cleaned that (we could do a command), but we can identify them and
choose not to display them - otherwise currently they are shown as a
duplicate of "No value" column
- Fixes buggy edge case introduced by
https://github.com/twentyhq/twenty/pull/16382 : after updating a view
from Table/Calendar to Kanban, then visiting another view, when coming
back to the newly updated kanban view the view groups were empty. This
is due to to the view groups being optimistically created with
on-the-fly computed ids when the view is updated, while we call
refreshCoreViewsByObjectMetadataId() after. The view groups we get from
the refresh obviously have different ids. It is not possible to indicate
the ids of the view group through the update of the view as they are a
side effect of the view update.
2025-12-09 10:42:00 +00:00
EtienneandGitHub ec2b6ae691 Fix storybook test (#16416) 2025-12-09 10:29:23 +00:00
ae2919e564 fix: migrate wildcard routes to named parameters (#16380)
Closes #16189

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-09 09:52:32 +01:00
Alex GaleyandGitHub b578ea5951 Fireflies app reached beta : utilities to ingest one or many meetings - No production webhook without headers forwarding (#16410)
# Fireflies
Automatically (with cli util : webhook not working and no cron added)
captures meeting notes with AI-generated summaries and insights from
Fireflies.ai into your Twenty CRM.

## Current Status
- Doesn't work with Fireflies webhook yet due to missing headers
forwarding in twenty serverless func
- Meeting ingestion utility script are available for individual meeting
insertion and historical meetings with filters with yarn meeting:all
- You have to push the secrets as application.config.ts values (despite
env variables in .env in docker compose or container I couldn't push the
secrets with the cli)

## Current Platform Limitation (Headers)

- Twenty serverless route triggers currently do **not forward HTTP
headers** to functions. Fireflies signatures sent in headers are
stripped, so header-based verification does not work in production.
- Workaround: the provided test script also includes the signature
inside the payload; the handler falls back to that payload signature.
Use this only for testing until header forwarding is supported.

## Utilities for meeting insertion (workarounds)

- Ingest a specific Fireflies meeting into Twenty:
`yarn meeting:ingest <meetingId>` or `MEETING_ID=... yarn
meeting:ingest`

- Fetch all/historical Fireflies meetings into Twenty:
`yarn meeting:all [--from 2024-01-01] [--to 2024-02-01] [--organizer
a@x.com] [--participant b@x.com] [--channel <channelId>] [--mine]
[--dry-run]`

  - Filters (combine as needed):
    - `--from` / `--to`: ISO or date string range filter
    - `--organizer` / `--participant`: comma-separated emails
    - `--channel`: Fireflies channel id
    - `--mine`: only meetings for the current Fireflies user
  - Controls:
    - `--dry-run`: list and transform without writing to Twenty
    - `--page-size`: pagination size (default 50)
    - `--max-records`: stop after N transcripts (default 500)
    
    
    I am closing previous #16378  as this one includes it all
2025-12-09 09:27:01 +01:00
95c69507aa i18n - docs translations (#16409)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-08 21:21:35 +01:00
0b8984116b i18n - translations (#16408)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-08 20:20:32 +01:00
Abdul RahmanandGitHub 77e592502c fix: improve CRON schedule validation and display (#16360)
Fixes multiple issues with CRON schedule input validation and execution
time display.

### Issues Fixed

1. **UTC label placement** - Added "UTC" suffix to specific times (e.g.,
"at 09:30 UTC") but not to interval descriptions (e.g., "every hour")

2. **Upcoming execution time calculation** - Fixed incorrect execution
times for malformed CRON expressions by implementing auto-correction

### Changes

- Created `normalizeCronExpression` utility to standardize cron
expressions before parsing
- Updated `formatTime` to support optional UTC suffix
- Enhanced `getHoursDescription` to append UTC to specific times
- Added comprehensive test coverage (102 tests passing)

### Before

- `"1 /3 * * *"` showed daily executions at same time (incorrect)
- `"9 * * *"` showed same time repeated 3 times (incorrect)
- No UTC labels on schedule descriptions (confusing)

### After

- All malformed expressions auto-corrected and show correct execution
times
- UTC labels clearly indicate timezone for specific times
- User-friendly error messages for truly invalid patterns

Closes #15870
2025-12-09 00:09:11 +05:30
f80b2f2c38 i18n - docs translations (#16406)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-08 19:22:30 +01:00
07cfaa78ef Fix unique standard field (#16371)
Fixes https://github.com/twentyhq/twenty/issues/15925

- update field metadata update logic
- uniformize the way index are named
- command to migrate v1-named unique index
- add integration testing

---------

Co-authored-by: prastoin <paul@twenty.com>
2025-12-08 18:05:28 +00:00
950f452fef i18n - translations (#16405)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-08 19:01:09 +01:00
4fe9e57847 fix(http-request-action): pretty-print JSON errors in test HTTP requeset hook (#16387)
Before:
<img width="415" height="319" alt="Screenshot from 2025-12-08 09-00-48"
src="https://github.com/user-attachments/assets/bd99cf74-d278-4344-a3c2-e7740d7d058b"
/>

After:
<img width="399" height="371" alt="Screenshot from 2025-12-08 08-59-05"
src="https://github.com/user-attachments/assets/5c75bded-1632-4a9a-9b51-ed3c83f36b3b"
/>

fixes #16243

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-08 18:23:55 +01:00
Lucky GoyalandGitHub d7dbb87a8f use micros converters in FormCurrencyFieldInput (#16330)
Fixes: #15887

The currency fields were expecting values in micros (multiplied by
10^6), but
this requirement was not indicated anywhere in the workflow UI. Users
had to
manually add a code node to multiply amounts by 10^6 before using the
new
currency value.

This change integrates the micros conversion logic directly into
FormCurrencyFieldInput by using convertCurrencyAmountToCurrencyMicros
and
convertCurrencyMicrosToCurrencyAmount utilities. This allows users to
input
human-readable decimal amounts (e.g., 3.21 for $3.21) in the form, which
are
automatically converted to micros internally for storage and processing.

This eliminates the need for users to add separate code nodes for
conversion
and improves the user experience by making the expected input format
clear.
2025-12-08 17:50:50 +01:00
9efeb180d6 i18n - docs translations (#16402)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-08 17:22:01 +01:00
Thomas TrompetteandGitHub 1c14567bf1 Workflow statuses update on record table - use cache instead of web sockets (#16391)
Updated the 3 hooks - activate, deactivate and discard draft
(deleteVersion) - so those updates the cache.
Removed the update listeners.

Also wrapped a few actions to unsure workflowId is not undefined when
received by useWorkflowWithCurrentVersion hook. Otherwise, useFindRecord
with by performed with skip true, disconnecting tmp from the cache and
making it miss a statuses update.



https://github.com/user-attachments/assets/5fc355e8-cf18-4881-855b-744eb253b79e
2025-12-08 17:17:13 +01:00
Thomas TrompetteandGitHub ac89b5aff6 Improve object record changed performances (#16398)
Using deepEqual, average over 3 calls:
- version trigger 1.53ms
- version steps 38.3ms
- run state 372.8 ms

Using stringified hash, average over 3 calls:
- version trigger 0.07ms
- version steps 0.74 ms
- run state 0.521ms

Short fastDeepEqual
- version trigger 0.028ms
- version steps 0.197ms
- run state 0.214ms

Lib fastDeepEqual
- version trigger 0.038ms
- version steps 0.187ms
- run state 0.230ms
2025-12-08 17:06:53 +01:00
WeikoandGitHub 859004f4fc Refactor global datasource part 2 (#16399)
## Context
Deprecating TwentyORMManager in favor of TwentyORMGlobalManager
(temporarily, as this will simplify the ultimate goal to later replace
all usages with the new TwentyORMGlobalManagerV2 which will have a
similar signature)
This means this PR had to refactor a bit of code to pass down the
workspaceId when not available directly as it is now a requirement,
meaning we also deprecated scopedWorkspaceContextFactory to have a less
obscure way to fetch the workspaceId and have something more
declarative.

Step 3 will be to update TwentyORMGlobalManager to use a featureFlag
toggling and use the new GlobalWorkspaceOrmManager internally using the
new cache service

Step 4 will be to remove the feature flag and pg_pool patch
2025-12-08 17:05:00 +01:00
c2d3fbcd21 i18n - translations (#16400)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-08 15:49:13 +01:00
Raphaël BosiandGitHub 5fb7e76005 Migrate page layout to v2 (#16364) 2025-12-08 14:11:24 +00:00
MarieandGitHub 86df188e83 [fix] Fix switch view type from "Layout" switcher (#16382)
In this previous work aiming at eliminating the creation of viewGroups
being separated from the views, I removed the creation of viewGroups
from the FE at view creation, but forgot to do it at view update when
the user chooses "change Layout" option (from Table/Kanban/Calendar to
another).

In this PR
- I removed creation, deletion and destroy of viewGroups from
usePersistViewGroupRecords. I left update because it useful for
visibility and position
- since usePersistViewGroups record was also handling optimistic, I
moved optimistic logic to a new hook useViewsSideEffectsOnViewGroups. I
realized that so far we optimistic is only useful for creation. For the
update though we do need to compute the view groups that will be created
to be able to call loadRecordIndexState, so I created a function for
that, but I did not seek to perform real optimistic, with writing and
deleting groups from the cache as it was a bit heavier and not in use
for now and I want to merge this asap as it fixes the creation of
viewGroups.
2025-12-08 15:05:05 +01:00
Charles BochetandGitHub 2790d5dd93 Message fixes (#16389)
In this PR:
- add more logs to troubleshoot issues in production
- use messageChannelSyncStatus in messageSync service instead of making
a manual update
2025-12-08 14:56:43 +01:00
neo773andGitHub 5f4c7e016c refactor imap gql resolver (#16375) 2025-12-08 14:54:24 +01:00
Baptiste DevessierandGitHub 51c0a8dd86 [Page layouts] Sync tabs with URL hash (#16341)
There are three identified scenarios.

## First scenario

The user uses a desktop. They click on a company, which is opened in the
side panel. They click on a tab, like "Tasks". The user chooses to open
the record in fullscreen. The "Tasks" tab is opened by default in the
fullscreen record page.

If the user refreshes the page, the default tab is shown: "Timeline".
**This was the behavior on the show pages, and I kept it.** If we wanted
to show the "Tasks" tab here, we would have to put the id of the "Tasks"
tab in the URL hash when we open the record in fullscreen and an active
tab id is already set.


https://github.com/user-attachments/assets/205776ac-9ad7-4e79-af9a-6b44360a5d77

## Second scenario

The user uses a desktop or a mobile device and interacts with a company
record. They click on a tab. If they refresh, the selected tab will be
displayed by default.

### Desktop


https://github.com/user-attachments/assets/d4e1908b-a591-42f6-bb82-5aec592e2778

### Mobile


https://github.com/user-attachments/assets/7bab73cc-a2ff-4ce8-9bc6-325efef2d500

## Third scenario

The user uses a desktop. They click on a dashboard, which is opened in
fullscreen mode by default. They select tabs. If they refresh, the last
selected tab is opened by default.

When the user turns edit mode on, **the url hash is removed**. The last
selected tab remains selected. If the user selects another tab, the url
hash isn't set, but the newly selected tab is displayed correctly. If
the user saves their changes, the selected tab remains selected.
However, if they refresh the page, the default tab replaces the
previously selected tab.

Not setting the url hash when editing a page layout simplifies the code.
I'm okay with this tradeoff as the feature is primarily meant to let
users share specific tabs of their records.

**This behavior will also be used for record page layout once edit mode
is supported.**


https://github.com/user-attachments/assets/869657a1-6895-4ade-816c-972c77aaab9e

Closes https://github.com/twentyhq/core-team-issues/issues/1784
2025-12-08 10:47:46 +01:00
martmullandGitHub 7f1e69740a 1895 extensibility v1 application tokens (#16365)
First PR to implement application tokens
- add new application role in twenty-server
- move duplicated constants and types to twenty-shared
- will  add role configuration utils into twenty-sdk in another PR
2025-12-08 10:42:46 +01:00
Félix MalfaitandGitHub 1f9a6b067a fix: make impersonation audit logging non-blocking (#16390)
## Summary

This PR makes the Clickhouse audit logging in the impersonation flow
**non-blocking** (fire-and-forget).

## Problem

When the Clickhouse server is unavailable or slow, the impersonation
feature becomes blocked because all audit logging calls use `await`,
causing the entire impersonation flow to hang.

## Solution

Remove the `await` keyword from all audit logging calls in the
impersonation flow. The `ClickHouseService.insert()` method already
handles errors internally (catches and logs them), so there's no risk of
unhandled promise rejections.

## Changes

- **`impersonation.service.ts`**: 4 audit calls made non-blocking
- **`auth.resolver.ts`**: 5 audit calls made non-blocking  
- **`auth.service.ts`**: 2 audit calls made non-blocking

## Testing

- Impersonation flow continues to work when Clickhouse is available
- Impersonation flow no longer blocks when Clickhouse is unavailable
2025-12-08 08:48:44 +00:00
Paul RastoinandGitHub 3e57aa14d3 Refactor page layout tab and widgets migration (#16367)
# Introduction
Making columns nullable instead of required + metadata on the fly
migration in typeorm migration that could affect other breaking change
migrations to be run
2025-12-06 10:23:24 +01:00
Félix MalfaitandGitHub 223082a4da refactor(twenty-server): consolidate AI tool provider architecture (#16355)
## Summary

Consolidates the AI tool provider architecture by creating a single
`ToolProviderService` as the entry point for all tool generation. This
removes multiple intermediate services and simplifies the codebase.

## Changes

### New Architecture
- **`ToolProviderService`**: Single service for all tool generation
with:
  - `getTools(spec)` - Get tools by category with permissions
  - `getToolByType(type)` - Get specific tool for workflow execution
  
- **`ToolCategory` enum**: Declarative specification of tool types:
  - `DATABASE_CRUD` - Record CRUD operations
  - `ACTION` - HTTP requests, email sending, article search
  - `WORKFLOW` - Workflow management tools
  - `METADATA` - Object/field metadata tools
  - `NATIVE_MODEL` - Model-specific tools (e.g., web search)

- **`ToolSpecification` type**: Clean API for requesting tools with
permissions

### Removed
- `AiToolsModule` - No longer needed
- `ToolService` - Logic inlined into ToolProviderService
- `ToolAdapterService` - Logic inlined into ToolProviderService
- `ToolRegistryService` - Logic inlined into ToolProviderService

### Updated
- All consumers (agents, chat, MCP, workflows) now use
`ToolProviderService`
- Test files updated accordingly

## Stats
- **547 insertions, 1146 deletions** (net ~600 lines removed)
- 4 services deleted
- 1 module deleted

## Testing
- [x] Typecheck passes
- [x] Lint passes
2025-12-06 06:51:47 +01:00
nitinandGitHub 43ed4963d6 [Dashboards] Improve tooltip animations (#16357)
before - 


https://github.com/user-attachments/assets/069a8737-fcc9-4186-bdbf-e9ed0dfa41a8


after - 


https://github.com/user-attachments/assets/dbc8604c-dda0-46a9-a67b-f59cc91d7f53
2025-12-05 18:28:26 +01:00
Abdul RahmanandGitHub b706664c99 Show add step button on trigger node without hover (#16361)
https://github.com/user-attachments/assets/3407bbea-356b-4508-b931-27b45818a339

Closes #14136
2025-12-05 18:28:13 +01:00
Paul RastoinandGitHub c8f541618d Refactor validate build and run for configuration to be less verbose and more reliable (#16343)
# Introduction
Refactored the api `validateBuildAndRunWorkspaceMigration` to be require
less configuration but to infer required args dynamically depending on
provided metadata maps to compare

## `inferDeletionFromMissingEntities`
Is not dynamically computed avoiding any miss configuration issue and
any missleading devxp

## Maps computation

Making only one call to redis to build both dependency and to be
compared entity maps. It does not matter to avoid passing a about to
compared flat entity maps to could also be a depedency, it's handled
directly in the builder setup optimistic cache logic

Please note that the flat maps used for the service input transpilation
might differ from the one that we will dynamically compute and inject in
the builder. Leading to do 2 redis calls but also race condition prone
validation error
We prefer that this occurs at the builder rather than at the runner
level as the pg instance is not cache and reflect the real state of a
given workspace
In a nutshell, there's a possible race condition between cache
invalidation and computation in both service input transpilers and
builder but we're totally ok with that
2025-12-05 15:41:56 +00:00
fee3e6b7a1 fix folder actions (#16344)
Co-authored-by: Charles Bochet <charles@twenty.com>
2025-12-05 16:19:50 +01:00
Thomas TrompetteandGitHub de4e78e5b2 Fix workflow relation variables (#16362)
display many to one relations instead of one to many
2025-12-05 16:11:37 +01:00
Baptiste DevessierandGitHub 2466d81ace [Record Page Layouts] Pin record header (#16339)
https://github.com/user-attachments/assets/df988bf2-d2d6-49a4-b062-bc7ec49e1fad

Closes https://github.com/twentyhq/core-team-issues/issues/1806
2025-12-05 16:10:08 +01:00
MarieandGitHub 58b8b49d1d Fix flaky storybook test (#16358)
RecordTable story was flaky with this kind of error
[(1)](https://www.apollographql.com/docs/react/errors#%7B%22version%22%3A%223.13.8%22%2C%22message%22%3A13%2C%22args%22%3A%5B%22addressStreet2%22%2C%22%7B%5Cn%20%20%5C%22__typename%5C%22%3A%20%5C%22Address%5C%22%2C%5Cn%20%20%5C%22addressLine1%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%5C%22addressLine2%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%5C%22addressCity%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%5C%22addressState%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%5C%22addressCountry%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%5C%22addressPostcode%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%5C%22addressLat%5C%22%3A%20null%2C%5Cn%20%20%5C%22addressLng%5C%22%3A%20null%5Cn%7D%22%5D%7D):
_Missing field 'addressStreet2' while writing result { "typename":
"Address", "addressLine1": "", "addressLine2": "", "addressCity": "",
"addressState": "", "addressCountry": "", "addressPostcode": "",
"addressLat": null, "addressLng": null }_ or
[(2)](https://www.apollographql.com/docs/react/errors#%7B%22version%22%3A%223.13.8%22%2C%22message%22%3A13%2C%22args%22%3A%5B%22deletedAt%22%2C%22%7B%5Cn%20%20%5C%22__typename%5C%22%3A%20%5C%22Company%5C%22%2C%5Cn%20%20%5C%22id%5C%22%3A%20%5C%2220202020-5d81-46d6-bf83-f7fd33ea6102%5C%22%2C%5Cn%20%20%5C%22employees%5C%22%3A%20null%2C%5Cn%20%20%5C%22createdAt%5C%22%3A%20%5C%222025-01-06T08%3A30%3A15.412Z%5C%22%2C%5Cn%20%20%5C%22updatedAt%5C%22%3A%20%5C%222025-01-06T14%3A45%3A22.412Z%5C%22%2C%5Cn%20%20%5C%22name%5C%22%3A%20%5C%22Facebook%5C%22%2C%5Cn%20%20%5C%22idealCustomerProfile%5C%22%3A%20false%2C%5Cn%20%20%5C%22accountOwner%5C%22%3A%20null%2C%5Cn%20%20%5C%22accountOwnerId%5C%22%3A%20null%2C%5Cn%20%20%5C%22domainName%5C%22%3A%20%7B%5Cn%20%20%20%20%5C%22__typename%5C%22%3A%20%5C%22Links%5C%22%2C%5Cn%20%20%20%20%5C%22primaryLinkUrl%5C%22%3A%20%5C%22https%3A%2F%2Ffacebook.com%5C%22%2C%5Cn%20%20%20%20%5C%22primaryLinkLabel%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22secondaryLinks%5C%22%3A%20%5B%5D%5Cn%20%20%7D%2C%5Cn%20%20%5C%22address%5C%22%3A%20%7B%5Cn%20%20%20%20%5C%22addressStreet1%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22addressStreet2%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22addressCity%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22addressState%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22addressCountry%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22addressPostcode%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22addressLat%5C%22%3A%20null%2C%5Cn%20%20%20%20%5C%22addressLng%5C%22%3A%20null%5Cn%20%20%7D%2C%5Cn%20%20%5C%22previousEmployees%5C%22%3A%20null%2C%5Cn%20%20%5C%22annualRecurringRevenue%5C%22%3A%20%7B%5Cn%20%20%20%20%5C%22__typename%5C%22%3A%20%5C%22Currency%5C%22%2C%5Cn%20%20%20%20%5C%22amountMicros%5C%22%3A%20null%2C%5Cn%20%20%20%20%5C%22currencyCode%5C%22%3A%20%5C%22%5C%22%5Cn%20%20%7D%2C%5Cn%20%20%5C%22position%5C%22%3A%202%2C%5Cn%20%20%5C%22xLink%5C%22%3A%20%7B%5Cn%20%20%20%20%5C%22__typename%5C%22%3A%20%5C%22Links%5C%22%2C%5Cn%20%20%20%20%5C%22primaryLinkLabel%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22primaryLinkUrl%5C%22%3A%20%5C%22%5C%22%2C%5Cn%20%20%20%20%5C%22secondaryLinks%5C%22%3A%20%5B%5D%5Cn%20%20%7D%2C%5Cn%20%20%5C%22linkedinLink%5C%22%3A%20%7B%5Cn%20%20%20%20%5C%22__typename%5C%22%3A%20%5C%22Links%5C%22%2C%5Cn%20%20%20%20%5C%22primary%22%5D%7D):
_Missing field 'deletedAt' while writing result..._

What the issue is and why is it flaky?
<img width="463" height="525" alt="image"
src="https://github.com/user-attachments/assets/af82a5ae-bce8-4e2f-a25b-b6f027082bc1"
/>
flakines may be due to timing of when the error is thrown vs when test
assertions run
2025-12-05 15:27:25 +01:00
a9033a3045 i18n - docs translations (#16359)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-05 15:21:01 +01:00
MarieandGitHub 7ce22d5c7e breaking (soft) - Migrate viewGroup.fieldMetadataId -> view.mainGroupByFieldMetadataId (2/3) (#16277)
Should be merged once https://github.com/twentyhq/twenty/pull/16206 has
been released + command run to prod

In this PR
- Remove usage of viewGroup.fieldMetadataId, both in BE and FE states. 
- But we still need to properly populate it until we fully remove
viewGroup.fieldMetadataId from db and ORM entity (upcoming 3rd PR out of
3). fieldMetadataId was removed from CoreViewGroup type and
CreateViewGroupInput and is determined BE-side based on the associated
view's mainGroupByFieldMetadataId. **I expect this means a downtime on
viewGroup creation, until both FE and BE are deployed and cache is
flushed.** This seems acceptable to me as it only regards viewGroup
creation.
    - this information is replaced by view.mainGroupByFieldMetadataID
- Handle view group creation, update and deletion in the BE as a
side-effect of a view creation, update or deletion. Optimistic effects
are still used
- Add validation at view creation or update regarding
mainGroupByFieldMetadata

Left to do in 3rd PR
- Remove viewGroup.fieldMetadataId from db and ORM entity
- Restore feature allowing to update an existing grouped view's group by
field (already OK on BE side but need to rebuild FE optimistic)
2025-12-05 14:00:03 +00:00
17d88a074b i18n - translations (#16356)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-05 14:40:04 +01:00
Raphaël BosiandGitHub 077be7644c Migrate page layout widget to v2 of the API (#16323) 2025-12-05 13:04:06 +00:00
Charles BochetandGitHub 56e66315cd Fix messaging direct import (#16354)
Mainly clarifying naming (scheduleMessageImport was actually tagging as
PENDING)
+ tagging as SCHEDULED in case of direct import (we skip PENDING state)
2025-12-05 10:48:09 +01:00
Charles BochetandGitHub 10b5e156e5 Improvement on messaging (#16351)
In this PR:
- change messaging / calendar stale duration check to 30minutes (cron is
running every 1h, duration check was 1h, so evaluation was flaky)
- when temporary error (throttling), preserve syncStageStartedAt as this
is necessary to assess exponential throttling
2025-12-05 00:04:07 +01:00
Félix MalfaitandGitHub 2803292521 feat: add Metadata Builder agent for data model management (#16350)
## Summary

This PR adds a new **Metadata Builder** AI agent that specializes in
managing the workspace data model (creating objects, adding fields,
etc.).

## Changes

### New Files
- `data-model-manager-role.ts` - New standard role with `DATA_MODEL`
permission flag
- `metadata-builder-agent.ts` - New standard agent for data model
management

### Modified Files
- **ChatToolsProviderService**: Refactored to consolidate all
permission-based tools into a single `getChatTools()` method. Now
injects both workflow tools and metadata tools based on permissions.
- **AgentChatRoutingService**: Updated to use the new consolidated
`getChatTools()` method
- **AiChatModule**: Added imports for `ObjectMetadataModule` and
`FieldMetadataModule`
- **Router system prompt**: Added metadata-builder agent selection rules
with clear distinction between schema operations vs data operations
- **Metadata tools factories**: Improved error messages to show detailed
validation errors instead of generic messages

### Refactoring
- Renamed `index.ts` files to `standard-agent-definitions.ts` and
`standard-role-definitions.ts` to follow naming conventions
- Renamed exports from `standardAgentDefinitions` to
`STANDARD_AGENT_DEFINITIONS` (SCREAMING_SNAKE_CASE)

## Key Features

1. **Metadata Builder Agent** can:
   - Create new custom objects
   - Add fields to existing objects
   - Update object and field properties
   - Create relations between objects

2. **Permission-based tool injection**: Tools are automatically injected
based on the `DATA_MODEL` permission flag

3. **Improved routing**: The router now correctly distinguishes between:
   - "Create an object called Project" → metadata-builder (schema)
   - "Create a company called Acme" → data-manipulator (data)

4. **Better error messages**: Validation errors now show detailed
messages like:
   ```
   Validation errors:
   [objectMetadata] Name must be in camelCase format
   [objectMetadata] Label is required
   ```
2025-12-04 23:26:29 +01:00
Félix MalfaitandGitHub 34d7d82099 refactor(mcp): call metadata services directly instead of REST layer (#16349)
## Summary

Refactors MCP metadata tools to call underlying services directly
instead of going through the REST layer. This makes MCP a pure
presentation layer.

### Changes

**Created:**
-
`packages/twenty-server/src/engine/metadata-modules/metadata-tools/metadata-tools.module.ts`
- Module that exports MetadataToolsFactory
-
`packages/twenty-server/src/engine/metadata-modules/metadata-tools/services/metadata-tools.factory.ts`
- Factory that generates 8 metadata tools using Zod schemas:
- `get-object-metadata`, `create-object-metadata`,
`update-object-metadata`, `delete-object-metadata`
- `get-field-metadata`, `create-field-metadata`,
`update-field-metadata`, `delete-field-metadata`

**Modified:**
-
`packages/twenty-server/src/engine/api/mcp/services/mcp-metadata.service.ts`
- Uses new factory instead of REST-based services
- `packages/twenty-server/src/engine/api/mcp/mcp.module.ts` - Imports
MetadataToolsModule, removes old service imports

**Deleted:**
-
`packages/twenty-server/src/engine/api/mcp/services/tools/create.tools.service.ts`
-
`packages/twenty-server/src/engine/api/mcp/services/tools/update.tools.service.ts`
-
`packages/twenty-server/src/engine/api/mcp/services/tools/delete.tools.service.ts`
-
`packages/twenty-server/src/engine/api/mcp/services/tools/get.tools.service.ts`
-
`packages/twenty-server/src/engine/api/mcp/services/tools/mcp-metadata-tools.service.ts`

### Architecture Improvement

**Before:**
```
MCP Tool → MetadataQueryBuilderFactory → RestApiService → GraphQL API → Service
```

**After:**
```
MCP Tool → Service (ObjectMetadataService / FieldMetadataService)
```

This follows the pattern established by `direct-record-tools.factory.ts`
and workflow tools.
2025-12-04 22:21:16 +01:00
aa0471ca1f i18n - translations (#16348)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-04 21:21:31 +01:00
Félix MalfaitandGitHub 9cecbaebc3 refactor(workflow-tools): reorganize to one file per tool with co-located schemas (#16313)
## Summary

Reorganizes workflow tools to improve maintainability and
discoverability by having one file per tool with co-located input
schemas.

## Changes

- Create individual tool files in `tools/` directory (11 files)
- Co-locate input schemas with their tool implementations
- Add shared types file for dependencies and context
- Simplify workspace service to aggregate tool factories
- Remove centralized `schemas/` directory

## New Structure

```
workflow-tools/
├── services/
│   └── workflow-tool.workspace-service.ts
├── tools/
│   ├── activate-workflow-version.tool.ts
│   ├── compute-step-output-schema.tool.ts
│   ├── create-complete-workflow.tool.ts
│   ├── create-draft-from-workflow-version.tool.ts
│   ├── create-workflow-version-edge.tool.ts
│   ├── create-workflow-version-step.tool.ts
│   ├── deactivate-workflow-version.tool.ts
│   ├── delete-workflow-version-edge.tool.ts
│   ├── delete-workflow-version-step.tool.ts
│   ├── update-workflow-version-positions.tool.ts
│   └── update-workflow-version-step.tool.ts
├── types/
│   └── workflow-tool-dependencies.type.ts
└── workflow-tools.module.ts
```

## Benefits

- **Co-location**: Schema and tool logic are in the same file
- **Single responsibility**: Each file handles one tool
- **Easier maintenance**: Changes to a tool only touch one file
- **Better discoverability**: File names match tool names
2025-12-04 21:06:49 +01:00
WeikoandGitHub 1991ee850e Fix seeding perf + batch role targets creation (#16337) 2025-12-04 20:29:48 +01:00
e653385485 i18n - docs translations (#16345)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-04 19:22:39 +01:00
ddece3aac8 i18n - translations (#16342)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-04 19:01:28 +01:00
nitinandGitHub 8f756937ae [Dashboards] Pie chart custom tooltip (#16318)
closes https://github.com/twentyhq/core-team-issues/issues/1884

and https://discord.com/channels/1130383047699738754/1443679780414427267


before - 


https://github.com/user-attachments/assets/db19657f-d7d3-4965-9b88-83e5829d3942


after -


https://github.com/user-attachments/assets/d88ec686-0298-4b5f-a214-03e8d8169e7d
2025-12-04 17:22:21 +00:00
aede5bab34 i18n - translations (#16338)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-12-04 18:21:26 +01:00
Paul RastoinandGitHub 28cdb02fbb Twenty standard application Objects and fields as allFlatEntityMaps ID non-agnostic (#16298)
# Introduction

Related to https://github.com/twentyhq/core-team-issues/issues/1995
This PR introduces the basis of the `twentyStandard` application as code
on demand, it's highly tied to `ids` where it will becomes workspace
agnostic following the builder and runner `universalIdentifier` refactor
later.

The goal here to allow computing the `allFlatEntityMaps` `to` of the
`twentyStandard` application on a empty workspace ( workspace creation
). Allowing installing the twenty standard app through a workspace
migration instead of passing by the sync metadata

Nothing done will be run in production for the moment if it's not the
small validation refactor we've introduced

Please note that everything introduced here will be replaced at some
point by a twenty app instance when the twenty sdk is mature enough to
handle of the edge cases we need here

## How we've proceeded
We've been iterating over every workspace entity both objects and their
fields, and transpiled them to flatEntity.
Being sure we migrate the defaultValue, settings and so on accordingly.
We've also compute all the ids in prior of the whole entities
computation so we don't face any hoisting issue.

## Current state
At the moment only handling all of the 29 standard objects and their
fields
Settings a unique universalIdentifier for all of them

Will come views, agent role targets and so on later

## `workspace:compute-twenty-standard-migration` command
This command allow generating a workspace migration that will result in
installing the twenty standard app in an empty workspace
It's temporary and aims to allow debugging for the moment we might not
keep it in the future as it is right now
It contains debug writeFileSync which is expected no worries greptile

## `LabelFieldMetadataIdentifierId`
Small refactor allowing defining the label identifier field metadata id
of a uuid field metadata type for system object, as some of our standard
object don't have a name field and don't aim to
Also please note that we might remove this build options later in the
sake of the currently installed universal identifier application that we
could compare with the deterministic twenty standard one

## `runFlatFieldMetadataValidators`
Deprecated this pattern which was redundant and not v2 friendly pattern

## Current errors that will address in upcoming PR
Current standard objects and fields metadata does not pass the
validation that we have in place, as historically the sync metadata
would directly consume the repositories and would just ignore the
validation. This is about to change.
Will handle the below errors in dedicated PRs as they will required
upgrade commands in order to migrate the data, or will handle that from
the sync metadata instead still to be determined but nothing critical
here

- camel case field metadata name
- options label invalid format

```json
{
  "status": "fail",
  "report": {
    "fieldMetadata": [
      {
        "status": "fail",
        "errors": [
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Name should be in camelCase",
            "userFriendlyMessage": {
              "id": "P+jdmX",
              "message": "Name should be in camelCase"
            },
            "value": "iCalUID"
          }
        ],
        "flatEntityMinimalInformation": {
          "id": "68dd83cd-92c8-4233-bb28-47939bab6124",
          "name": "iCalUID",
          "objectMetadataId": "11c16ab6-9176-439e-a2db-a12c5a58a524"
        },
        "type": "create_field"
      },
      {
        "status": "fail",
        "errors": [
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"email\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "email"
              }
            },
            "value": "email"
          },
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"sms\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "sms"
              }
            },
            "value": "sms"
          }
        ],
        "flatEntityMinimalInformation": {
          "id": "e3caaf2a-e07d-4146-8dfc-9eef904e82c9",
          "name": "type",
          "objectMetadataId": "4b777de5-4c7b-4af4-9b92-655c0f87512b"
        },
        "type": "create_field"
      },
      {
        "status": "fail",
        "errors": [
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"incoming\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "incoming"
              }
            },
            "value": "incoming"
          },
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"outgoing\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "outgoing"
              }
            },
            "value": "outgoing"
          }
        ],
        "flatEntityMinimalInformation": {
          "id": "d96233a4-93be-45ea-9548-3b50f3c700cf",
          "name": "direction",
          "objectMetadataId": "480a648a-d2e5-482a-992f-ef053e1b4bb0"
        },
        "type": "create_field"
      },
      {
        "status": "fail",
        "errors": [
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"from\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "from"
              }
            },
            "value": "from"
          },
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"to\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "to"
              }
            },
            "value": "to"
          },
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"cc\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "cc"
              }
            },
            "value": "cc"
          },
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Value must be in UPPER_CASE and follow snake_case \"bcc\"",
            "userFriendlyMessage": {
              "id": "UBPzFQ",
              "message": "Value must be in UPPER_CASE and follow snake_case \"{sanitizedValue}\"",
              "values": {
                "sanitizedValue": "bcc"
              }
            },
            "value": "bcc"
          }
        ],
        "flatEntityMinimalInformation": {
          "id": "961c598e-67c3-452d-8bb2-b92c0bc64404",
          "name": "role",
          "objectMetadataId": "8af8a13c-ff97-4cd3-b70d-52a7dc2924b4"
        },
        "type": "create_field"
      },
      {
        "status": "fail",
        "errors": [
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Label must not contain a comma",
            "userFriendlyMessage": {
              "id": "k731jp",
              "message": "Label must not contain a comma"
            },
            "value": "Commas and dot (1,234.56)"
          },
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Label must not contain a comma",
            "userFriendlyMessage": {
              "id": "k731jp",
              "message": "Label must not contain a comma"
            },
            "value": "Spaces and comma (1 234,56)"
          },
          {
            "code": "INVALID_FIELD_INPUT",
            "message": "Label must not contain a comma",
            "userFriendlyMessage": {
              "id": "k731jp",
              "message": "Label must not contain a comma"
            },
            "value": "Dots and comma (1.234,56)"
          }
        ],
        "flatEntityMinimalInformation": {
          "id": "7fa20caf-2597-42e3-84e5-15a91b125b9b",
          "name": "numberFormat",
          "objectMetadataId": "a6974302-9e72-461c-aa09-9390f4ff16fc"
        },
        "type": "create_field"
      }
    ],
    "objectMetadata": [],
    "view": [],
    "viewField": [],
    "viewGroup": [],
    "index": [],
    "serverlessFunction": [],
    "cronTrigger": [],
    "databaseEventTrigger": [],
    "routeTrigger": [],
    "viewFilter": [],
    "role": [],
    "roleTarget": [],
    "agent": []
  }
}
```
2025-12-04 17:39:12 +01:00
b2d785de4b Page layout tab v2 (#16319)
# Introduction
Migrating `pageLayoutTab` to the v2 engine
- Types and constants
- Builder and validate
- Runner

Introduced a new `StrictSyncableEntity` that enforces that
`universalIdentifier` and `applicationId` are defined
As these entities are brand new we could enforce this rule already
This still requires a migration command to associate the existing
entities to custom workspace application instance and define
universalIdentifier

Handled retro-comp of the migration through a migration as upgrade
command fallback

---------

Co-authored-by: bosiraphael <raphael.bosi@gmail.com>
2025-12-04 17:37:16 +01:00
9771 changed files with 590171 additions and 366528 deletions
+6 -2
View File
@@ -56,7 +56,9 @@ npx nx storybook:build twenty-front # Build Storybook
npx nx storybook:serve-and-test:static # Run Storybook tests
# Development
npx nx lint twenty-front # Run linter
npx nx lint:diff-with-main twenty-front # Lint files changed vs main (fastest)
npx nx lint:diff-with-main twenty-front --configuration=fix # Auto-fix changed files
npx nx lint twenty-front # Lint all files (slower)
npx nx typecheck twenty-front # Type checking
npx nx run twenty-front:graphql:generate # Generate GraphQL types
```
@@ -70,7 +72,9 @@ npx nx run twenty-server:database:migrate:prod # Run migrations
# Development
npx nx run twenty-server:start # Start the server
npx nx run twenty-server:lint # Run linter (add --fix to auto-fix)
npx nx lint:diff-with-main twenty-server # Lint files changed vs main (fastest)
npx nx lint:diff-with-main twenty-server --configuration=fix # Auto-fix changed files
npx nx run twenty-server:lint # Lint all files (slower)
npx nx run twenty-server:typecheck # Type checking
npx nx run twenty-server:test # Run unit tests
npx nx run twenty-server:test:integration:with-db-reset # Run integration tests
+13 -2
View File
@@ -12,7 +12,12 @@ alwaysApply: true
npx nx run twenty-front:build
npx nx run twenty-server:test
# Run target for all projects
# Lint diff with main (recommended - much faster!)
npx nx lint:diff-with-main twenty-front # Lint only files changed vs main
npx nx lint:diff-with-main twenty-server
npx nx lint:diff-with-main twenty-front --configuration=fix # Auto-fix changed files
# Run target for all projects (slower)
npx nx run-many --target=build --all
npx nx run-many --target=test --projects=twenty-front,twenty-server
@@ -43,12 +48,18 @@ npx nx g @nx/react:component my-component
}
```
## Linting Strategy
For faster development, always prefer linting only changed files:
- Use `npx nx lint:diff-with-main <project>` to lint only files changed vs main branch
- Use `--configuration=fix` to auto-fix issues in changed files
- Only use `npx nx lint <project>` when you need to lint the entire project
## Dependency Graph
```bash
# View project dependencies
npx nx graph
# Check what's affected by changes
# Check what's affected by changes (runs target on affected projects)
npx nx affected --target=test
npx nx affected --target=build --base=main
```
@@ -20,7 +20,7 @@ runs:
id: cache-primary-key-builder
shell: bash
run: |
echo "CACHE_PRIMARY_KEY_PREFIX=v3-${{ inputs.key }}-${{ github.ref_name }}" >> "${GITHUB_OUTPUT}"
echo "CACHE_PRIMARY_KEY_PREFIX=v4-${{ inputs.key }}-${{ github.ref_name }}" >> "${GITHUB_OUTPUT}"
- name: Restore cache
uses: actions/cache/restore@v4
id: restore-cache
@@ -32,4 +32,4 @@ runs:
.nx
node_modules/.cache
packages/*/node_modules/.cache
${{ inputs.additional-paths }}
${{ inputs.additional-paths }}
+92 -92
View File
@@ -63,9 +63,9 @@ jobs:
- 8123:8123
- 9000:9000
options: >-
--health-cmd "clickhouse-client --host=localhost --port=9000 --user=default --password=clickhousePassword --query='SELECT 1'"
--health-interval 10s
--health-timeout 5s
--health-cmd "clickhouse-client --host=localhost --port=9000 --user=default --password=clickhousePassword --query='SELECT 1'"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
@@ -78,12 +78,12 @@ jobs:
id: merge_attempt
run: |
echo "Attempting to merge main into current branch..."
git fetch origin main
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "Current branch: $CURRENT_BRANCH"
if git merge origin/main --no-edit; then
echo "✅ Successfully merged main into current branch"
echo "merged=true" >> $GITHUB_OUTPUT
@@ -91,16 +91,16 @@ jobs:
else
echo "❌ Merge failed due to conflicts"
echo "⚠️ Falling back to comparing current branch against main without merge"
# Abort the failed merge
git merge --abort
echo "merged=false" >> $GITHUB_OUTPUT
echo "BRANCH_STATE=conflicts" >> $GITHUB_ENV
fi
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Build shared dependencies
run: |
@@ -128,22 +128,22 @@ jobs:
local var_name="$1"
local var_value="$2"
local env_file="packages/twenty-server/.env"
echo "" >> "$env_file"
if grep -q "^${var_name}=" "$env_file" 2>/dev/null; then
sed -i "s|^${var_name}=.*|${var_name}=${var_value}|" "$env_file"
else
echo "${var_name}=${var_value}" >> "$env_file"
fi
}
set_env_var "PG_DATABASE_URL" "postgres://postgres:postgres@localhost:5432/current_branch"
set_env_var "NODE_PORT" "${{ env.CURRENT_SERVER_PORT }}"
set_env_var "REDIS_URL" "redis://localhost:6379"
set_env_var "CLICKHOUSE_URL" "http://default:clickhousePassword@localhost:8123/twenty"
set_env_var "CLICKHOUSE_PASSWORD" "clickhousePassword"
npx nx run twenty-server:database:init:prod
npx nx run twenty-server:database:migrate:prod
@@ -166,19 +166,19 @@ jobs:
timeout=300
interval=5
elapsed=0
while [ $elapsed -lt $timeout ]; do
if curl -s "http://localhost:${{ env.CURRENT_SERVER_PORT }}/graphql" > /dev/null 2>&1 && \
curl -s "http://localhost:${{ env.CURRENT_SERVER_PORT }}/rest/open-api/core" > /dev/null 2>&1; then
echo "Current branch server is ready!"
break
fi
echo "Current branch server not ready yet, waiting ${interval}s..."
sleep $interval
elapsed=$((elapsed + interval))
done
if [ $elapsed -ge $timeout ]; then
echo "Timeout waiting for current branch server to start"
echo "Current server log:"
@@ -188,15 +188,15 @@ jobs:
- name: Download GraphQL and REST responses from current branch
run: |
# Admin token from jest-integration.config.ts
ADMIN_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyMDIwMjAyMC05ZTNiLTQ2ZDQtYTU1Ni04OGI5ZGRjMmIwMzQiLCJ3b3Jrc3BhY2VJZCI6IjIwMjAyMDIwLTFjMjUtNGQwMi1iZjI1LTZhZWNjZjdlYTQxOSIsIndvcmtzcGFjZU1lbWJlcklkIjoiMjAyMDIwMjAtMDY4Ny00YzQxLWI3MDctZWQxYmZjYTk3MmE3IiwidXNlcldvcmtzcGFjZUlkIjoiMjAyMDIwMjAtOWUzYi00NmQ0LWE1NTYtODhiOWRkYzJiMDM1IiwiaWF0IjoxNzM5NTQ3NjYxLCJleHAiOjMzMjk3MTQ3NjYxfQ.fbOM9yhr3jWDicPZ1n771usUURiPGmNdeFApsgrbxOw"
# Read admin token from shared test tokens file (single source of truth)
ADMIN_TOKEN=$(jq -r '.APPLE_JANE_ADMIN_ACCESS_TOKEN' packages/twenty-server/test/integration/constants/test-tokens.json)
# Load introspection query from file
INTROSPECTION_QUERY=$(cat packages/twenty-utils/graphql-introspection-query.graphql)
# Prepare the query payload
QUERY_PAYLOAD=$(echo "$INTROSPECTION_QUERY" | tr '\n' ' ' | sed 's/"/\\"/g')
echo "Downloading GraphQL schema from current server..."
curl -X POST "http://localhost:${{ env.CURRENT_SERVER_PORT }}/graphql" \
-H "Content-Type: application/json" \
@@ -205,7 +205,7 @@ jobs:
-o current-schema-introspection.json \
-w "HTTP Status: %{http_code}\n" \
-s
echo "Downloading GraphQL metadata schema from current server..."
curl -X POST "http://localhost:${{ env.CURRENT_SERVER_PORT }}/metadata" \
-H "Content-Type: application/json" \
@@ -214,32 +214,32 @@ jobs:
-o current-metadata-schema-introspection.json \
-w "HTTP Status: %{http_code}\n" \
-s
# Download current branch OpenAPI specs
echo "Downloading OpenAPI specifications from current server..."
curl -s "http://localhost:${{ env.CURRENT_SERVER_PORT }}/rest/open-api/core" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" \
-o current-rest-api.json \
-w "HTTP Status: %{http_code}\n"
curl -s "http://localhost:${{ env.CURRENT_SERVER_PORT }}/rest/open-api/metadata" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" \
-o current-rest-metadata-api.json \
-w "HTTP Status: %{http_code}\n"
# Verify the downloads
echo "Current branch files downloaded:"
ls -la current-*
- name: Preserve current branch files
run: |
# Create a temp directory to store current branch files
mkdir -p /tmp/current-branch-files
# Move current branch files to temp directory
mv current-* /tmp/current-branch-files/ 2>/dev/null || echo "No current-* files to preserve"
echo "Preserved current branch files for later restoration"
- name: Stop current branch server
@@ -263,7 +263,7 @@ jobs:
rm -rf node_modules packages/*/node_modules packages/*/dist dist .nx/cache
- name: Install dependencies for main branch
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Build main branch dependencies
run: |
@@ -281,22 +281,22 @@ jobs:
local var_name="$1"
local var_value="$2"
local env_file="packages/twenty-server/.env"
echo "" >> "$env_file"
if grep -q "^${var_name}=" "$env_file" 2>/dev/null; then
sed -i "s|^${var_name}=.*|${var_name}=${var_value}|" "$env_file"
else
echo "${var_name}=${var_value}" >> "$env_file"
fi
}
set_env_var "PG_DATABASE_URL" "postgres://postgres:postgres@localhost:5432/main_branch"
set_env_var "NODE_PORT" "${{ env.MAIN_SERVER_PORT }}"
set_env_var "REDIS_URL" "redis://localhost:6379"
set_env_var "CLICKHOUSE_URL" "http://default:clickhousePassword@localhost:8123/twenty"
set_env_var "CLICKHOUSE_PASSWORD" "clickhousePassword"
npx nx run twenty-server:database:init:prod
npx nx run twenty-server:database:migrate:prod
@@ -319,19 +319,19 @@ jobs:
timeout=300
interval=5
elapsed=0
while [ $elapsed -lt $timeout ]; do
if curl -s "http://localhost:${{ env.MAIN_SERVER_PORT }}/graphql" > /dev/null 2>&1 && \
curl -s "http://localhost:${{ env.MAIN_SERVER_PORT }}/rest/open-api/core" > /dev/null 2>&1; then
echo "Main branch server is ready!"
break
fi
echo "Main branch server not ready yet, waiting ${interval}s..."
sleep $interval
elapsed=$((elapsed + interval))
done
if [ $elapsed -ge $timeout ]; then
echo "Timeout waiting for main branch server to start"
echo "Main server log:"
@@ -341,15 +341,15 @@ jobs:
- name: Download GraphQL and REST responses from main branch
run: |
# Admin token from jest-integration.config.ts
ADMIN_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyMDIwMjAyMC05ZTNiLTQ2ZDQtYTU1Ni04OGI5ZGRjMmIwMzQiLCJ3b3Jrc3BhY2VJZCI6IjIwMjAyMDIwLTFjMjUtNGQwMi1iZjI1LTZhZWNjZjdlYTQxOSIsIndvcmtzcGFjZU1lbWJlcklkIjoiMjAyMDIwMjAtMDY4Ny00YzQxLWI3MDctZWQxYmZjYTk3MmE3IiwidXNlcldvcmtzcGFjZUlkIjoiMjAyMDIwMjAtOWUzYi00NmQ0LWE1NTYtODhiOWRkYzJiMDM1IiwiaWF0IjoxNzM5NTQ3NjYxLCJleHAiOjMzMjk3MTQ3NjYxfQ.fbOM9yhr3jWDicPZ1n771usUURiPGmNdeFApsgrbxOw"
# Read admin token from shared test tokens file (single source of truth)
ADMIN_TOKEN=$(jq -r '.APPLE_JANE_ADMIN_ACCESS_TOKEN' packages/twenty-server/test/integration/constants/test-tokens.json)
# Load introspection query from file
INTROSPECTION_QUERY=$(cat packages/twenty-utils/graphql-introspection-query.graphql)
# Prepare the query payload
QUERY_PAYLOAD=$(echo "$INTROSPECTION_QUERY" | tr '\n' ' ' | sed 's/"/\\"/g')
echo "Downloading GraphQL schema from main server..."
curl -X POST "http://localhost:${{ env.MAIN_SERVER_PORT }}/graphql" \
-H "Content-Type: application/json" \
@@ -358,7 +358,7 @@ jobs:
-o main-schema-introspection.json \
-w "HTTP Status: %{http_code}\n" \
-s
echo "Downloading GraphQL metadata schema from main server..."
curl -X POST "http://localhost:${{ env.MAIN_SERVER_PORT }}/metadata" \
-H "Content-Type: application/json" \
@@ -367,33 +367,33 @@ jobs:
-o main-metadata-schema-introspection.json \
-w "HTTP Status: %{http_code}\n" \
-s
# Download main branch OpenAPI specs
echo "Downloading OpenAPI specifications from main server..."
curl -s "http://localhost:${{ env.MAIN_SERVER_PORT }}/rest/open-api/core" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" \
-o main-rest-api.json \
-w "HTTP Status: %{http_code}\n"
curl -s "http://localhost:${{ env.MAIN_SERVER_PORT }}/rest/open-api/metadata" \
-H "Authorization: Bearer ${ADMIN_TOKEN}" \
-o main-rest-metadata-api.json \
-w "HTTP Status: %{http_code}\n"
# Verify the downloads
echo "Main branch files downloaded:"
ls -la main-*
- name: Restore current branch files
run: |
# Move current branch files back to working directory
mv /tmp/current-branch-files/* . 2>/dev/null || echo "No files to restore"
# Verify all files are present
echo "All API files restored:"
ls -la current-* main-* 2>/dev/null || echo "Some files may be missing"
# Clean up temp directory
rm -rf /tmp/current-branch-files
@@ -406,9 +406,9 @@ jobs:
run: |
echo "=== INSTALLING GRAPHQL INSPECTOR CLI ==="
npm install -g @graphql-inspector/cli
echo "=== GENERATING GRAPHQL DIFF REPORTS ==="
# Check if GraphQL schema has changes
echo "Checking GraphQL schema for changes..."
if graphql-inspector diff main-schema-introspection.json current-schema-introspection.json >/dev/null 2>&1; then
@@ -426,7 +426,7 @@ jobs:
echo "\`\`\`" >> graphql-schema-diff.md
}
fi
# Check if GraphQL metadata schema has changes
echo "Checking GraphQL metadata schema for changes..."
if graphql-inspector diff main-metadata-schema-introspection.json current-metadata-schema-introspection.json >/dev/null 2>&1; then
@@ -444,7 +444,7 @@ jobs:
echo "\`\`\`" >> graphql-metadata-diff.md
}
fi
# Show summary
echo "Generated diff files:"
ls -la *-diff.md 2>/dev/null || echo "No diff files generated (no changes detected)"
@@ -452,32 +452,32 @@ jobs:
- name: Check REST API Breaking Changes
run: |
echo "=== CHECKING REST API FOR BREAKING CHANGES ==="
# Use the Java-based openapi-diff via Docker
docker run --rm -v "$(pwd):/specs" openapitools/openapi-diff:latest \
--json /specs/rest-api-diff.json \
/specs/main-rest-api.json /specs/current-rest-api.json || echo "OpenAPI diff completed with exit code $?"
# Check if the output file was created and is valid JSON
if [ -f "rest-api-diff.json" ] && jq empty rest-api-diff.json 2>/dev/null; then
# Check for breaking changes using Java openapi-diff JSON structure
incompatible=$(jq -r '.incompatible // false' rest-api-diff.json)
different=$(jq -r '.different // false' rest-api-diff.json)
# Count changes
new_endpoints=$(jq -r '.newEndpoints | length' rest-api-diff.json 2>/dev/null || echo "0")
missing_endpoints=$(jq -r '.missingEndpoints | length' rest-api-diff.json 2>/dev/null || echo "0")
changed_operations=$(jq -r '.changedOperations | length' rest-api-diff.json 2>/dev/null || echo "0")
if [ "$incompatible" = "true" ]; then
echo "❌ Breaking changes detected in REST API"
# Generate breaking changes report
echo "# REST API Breaking Changes" > rest-api-diff.md
echo "" >> rest-api-diff.md
echo "⚠️ **Breaking changes detected that may affect existing API consumers**" >> rest-api-diff.md
echo "" >> rest-api-diff.md
# Parse and format the changes from Java openapi-diff
jq -r '
if (.missingEndpoints | length) > 0 then
@@ -493,7 +493,7 @@ jobs:
(.newEndpoints | map("- " + .method + " " + .pathUrl + ": " + (.summary // "")) | join("\n"))
else "" end
' rest-api-diff.json >> rest-api-diff.md
elif [ "$different" = "true" ]; then
echo "📝 Non-breaking changes detected ($new_endpoints new endpoints, $missing_endpoints removed, $changed_operations changed) - no PR comment will be posted"
# Don't create markdown file for non-breaking changes to avoid PR comments
@@ -503,7 +503,7 @@ jobs:
fi
else
echo "⚠️ OpenAPI diff tool could not process the files"
echo "# REST API Analysis Error" > rest-api-diff.md
echo "" >> rest-api-diff.md
echo "⚠️ **Error occurred while analyzing REST API changes**" >> rest-api-diff.md
@@ -512,7 +512,7 @@ jobs:
echo "\`\`\`" >> rest-api-diff.md
docker run --rm -v "$(pwd):/specs" openapitools/openapi-diff:latest /specs/main-rest-api.json /specs/current-rest-api.json 2>&1 >> rest-api-diff.md || echo "Could not capture error output"
echo "\`\`\`" >> rest-api-diff.md
# Don't fail the workflow for tool errors
echo "::warning::REST API analysis tool error - continuing workflow"
fi
@@ -520,33 +520,33 @@ jobs:
- name: Check REST Metadata API Breaking Changes
run: |
echo "=== CHECKING REST METADATA API FOR BREAKING CHANGES ==="
# Use the Java-based openapi-diff for metadata API as well
docker run --rm -v "$(pwd):/specs" openapitools/openapi-diff:latest \
--json /specs/rest-metadata-api-diff.json \
/specs/main-rest-metadata-api.json /specs/current-rest-metadata-api.json || echo "OpenAPI diff completed with exit code $?"
# Check if the output file was created and is valid JSON
if [ -f "rest-metadata-api-diff.json" ] && jq empty rest-metadata-api-diff.json 2>/dev/null; then
# Check for breaking changes using Java openapi-diff JSON structure
incompatible=$(jq -r '.incompatible // false' rest-metadata-api-diff.json)
different=$(jq -r '.different // false' rest-metadata-api-diff.json)
# Count changes
new_endpoints=$(jq -r '.newEndpoints | length' rest-metadata-api-diff.json 2>/dev/null || echo "0")
missing_endpoints=$(jq -r '.missingEndpoints | length' rest-metadata-api-diff.json 2>/dev/null || echo "0")
changed_operations=$(jq -r '.changedOperations | length' rest-metadata-api-diff.json 2>/dev/null || echo "0")
if [ "$incompatible" = "true" ]; then
echo "❌ Breaking changes detected in REST Metadata API"
# Generate breaking changes report (only for breaking changes)
echo "# REST Metadata API Breaking Changes" > rest-metadata-api-diff.md
echo "" >> rest-metadata-api-diff.md
echo "⚠️ **Breaking changes detected that may affect existing API consumers**" >> rest-metadata-api-diff.md
echo "" >> rest-metadata-api-diff.md
# Parse and format the changes from Java openapi-diff
# Parse and format the changes from Java openapi-diff
jq -r '
if (.missingEndpoints | length) > 0 then
"## 🚨 Removed Endpoints (" + (.missingEndpoints | length | tostring) + ")\n" +
@@ -570,7 +570,7 @@ jobs:
fi
else
echo "⚠️ OpenAPI diff tool could not process the metadata API files"
echo "# REST Metadata API Analysis Error" > rest-metadata-api-diff.md
echo "" >> rest-metadata-api-diff.md
echo "⚠️ **Error occurred while analyzing REST Metadata API changes**" >> rest-metadata-api-diff.md
@@ -579,7 +579,7 @@ jobs:
echo "\`\`\`" >> rest-metadata-api-diff.md
docker run --rm -v "$(pwd):/specs" openapitools/openapi-diff:latest /specs/main-rest-metadata-api.json /specs/current-rest-metadata-api.json 2>&1 >> rest-metadata-api-diff.md || echo "Could not capture error output"
echo "\`\`\`" >> rest-metadata-api-diff.md
# Don't fail the workflow for tool errors
echo "::warning::REST Metadata API analysis tool error - continuing workflow"
fi
@@ -592,7 +592,7 @@ jobs:
const fs = require('fs');
let hasChanges = false;
let comment = '';
try {
if (fs.existsSync('graphql-schema-diff.md')) {
const graphqlDiff = fs.readFileSync('graphql-schema-diff.md', 'utf8');
@@ -604,7 +604,7 @@ jobs:
comment += '### GraphQL Schema Changes\n' + graphqlDiff + '\n\n';
}
}
if (fs.existsSync('graphql-metadata-diff.md')) {
const graphqlMetadataDiff = fs.readFileSync('graphql-metadata-diff.md', 'utf8');
if (graphqlMetadataDiff.trim()) {
@@ -615,7 +615,7 @@ jobs:
comment += '### GraphQL Metadata Schema Changes\n' + graphqlMetadataDiff + '\n\n';
}
}
if (fs.existsSync('rest-api-diff.md')) {
const restDiff = fs.readFileSync('rest-api-diff.md', 'utf8');
if (restDiff.trim()) {
@@ -626,7 +626,7 @@ jobs:
comment += restDiff + '\n\n';
}
}
if (fs.existsSync('rest-metadata-api-diff.md')) {
const metadataDiff = fs.readFileSync('rest-metadata-api-diff.md', 'utf8');
if (metadataDiff.trim()) {
@@ -637,37 +637,37 @@ jobs:
comment += metadataDiff + '\n\n';
}
}
// Only post comment if there are changes
if (hasChanges) {
// Add branch state information only if there were conflicts
const branchState = process.env.BRANCH_STATE || 'unknown';
let branchStateNote = '';
if (branchState === 'conflicts') {
branchStateNote = '\n\n⚠️ **Note**: Could not merge with `main` due to conflicts. This comparison shows changes between the current branch and `main` as separate states.\n';
}
// Check if there are any breaking changes detected
let hasBreakingChanges = false;
let breakingChangeNote = '';
// Check for breaking changes in any of the diff files
if (fs.existsSync('rest-api-diff.md')) {
const restDiff = fs.readFileSync('rest-api-diff.md', 'utf8');
if (restDiff.includes('Breaking Changes') || restDiff.includes('🚨') ||
if (restDiff.includes('Breaking Changes') || restDiff.includes('🚨') ||
restDiff.includes('Removed Endpoints') || restDiff.includes('Changed Operations')) {
hasBreakingChanges = true;
}
}
if (fs.existsSync('rest-metadata-api-diff.md')) {
const metadataDiff = fs.readFileSync('rest-metadata-api-diff.md', 'utf8');
if (metadataDiff.includes('Breaking Changes') || metadataDiff.includes('🚨') ||
if (metadataDiff.includes('Breaking Changes') || metadataDiff.includes('🚨') ||
metadataDiff.includes('Removed Endpoints') || metadataDiff.includes('Changed Operations')) {
hasBreakingChanges = true;
}
}
// Also check GraphQL changes for breaking changes indicators
if (fs.existsSync('graphql-schema-diff.md')) {
const graphqlDiff = fs.readFileSync('graphql-schema-diff.md', 'utf8');
@@ -675,18 +675,18 @@ jobs:
hasBreakingChanges = true;
}
}
if (fs.existsSync('graphql-metadata-diff.md')) {
const graphqlMetadataDiff = fs.readFileSync('graphql-metadata-diff.md', 'utf8');
if (graphqlMetadataDiff.includes('Breaking changes') || graphqlMetadataDiff.includes('BREAKING')) {
hasBreakingChanges = true;
}
}
// Check PR title for "breaking"
const prTitle = ${{ toJSON(github.event.pull_request.title) }};
const titleContainsBreaking = prTitle.toLowerCase().includes('breaking');
if (hasBreakingChanges) {
if (titleContainsBreaking) {
breakingChangeNote = '\n\n## ✅ Breaking Change Protocol\n\n' +
@@ -702,20 +702,20 @@ jobs:
'For breaking changes, add to commit message:\n```\nfeat: add new API endpoint\n\nBREAKING CHANGE: removed deprecated field from User schema\n```';
}
}
const COMMENT_MARKER = '<!-- API_CHANGES_REPORT -->';
const commentBody = COMMENT_MARKER + '\n' + comment + branchStateNote + '\n⚠️ **Please review these API changes carefully before merging.**' + breakingChangeNote;
// Get all comments to find existing API changes comment
const {data: comments} = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
// Find our existing comment
const botComment = comments.find(comment => comment.body.includes(COMMENT_MARKER));
if (botComment) {
// Update existing comment
await github.rest.issues.updateComment({
@@ -737,17 +737,17 @@ jobs:
}
} else {
console.log('No API changes detected - skipping PR comment');
// Check if there's an existing comment to remove
const {data: comments} = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const COMMENT_MARKER = '<!-- API_CHANGES_REPORT -->';
const botComment = comments.find(comment => comment.body.includes(COMMENT_MARKER));
if (botComment) {
await github.rest.issues.deleteComment({
owner: context.repo.owner,
@@ -780,7 +780,7 @@ jobs:
/tmp/main-server.log
/tmp/current-server.log
*-api.json
*-schema-introspection.json
*-schema-introspection.json
*-diff.md
*-diff.json
+5 -3
View File
@@ -27,7 +27,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
task: [lint, typecheck, test, build]
task: [lint, typecheck, test]
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.11.0
@@ -38,9 +38,11 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Build
run: npx nx build create-twenty-app
- name: Run ${{ matrix.task }} task
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:create-app
tasks: ${{ matrix.task }}
+1 -1
View File
@@ -40,7 +40,7 @@ jobs:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Docs / Lint English MDX files
run: npx eslint "packages/twenty-docs/{developers,user-guide,twenty-ui,getting-started,snippets}/**/*.mdx" --max-warnings 0
-136
View File
@@ -1,136 +0,0 @@
name: CI E2E Playwright Tests
on:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened, labeled]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
changed-files-check:
uses: ./.github/workflows/changed-files.yaml
with:
files: |
packages/**
playwright.config.ts
.github/workflows/ci-e2e.yaml
test:
runs-on: ubuntu-latest
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true' && ( github.event_name == 'push' || (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'run-e2e')))
timeout-minutes: 30
env:
# https://github.com/actions/runner-images/issues/70#issuecomment-589562148
NODE_OPTIONS: "--max-old-space-size=10240"
services:
postgres:
image: twentycrm/twenty-postgres-spilo
env:
PGUSER_SUPERUSER: postgres
PGPASSWORD_SUPERUSER: postgres
ALLOW_NOSSL: "true"
SPILO_PROVIDER: "local"
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
redis:
image: redis
ports:
- 6379:6379
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: lts/*
- name: Check system resources
run: |
echo "Available memory:"
free -h
echo "Available disk space:"
df -h
echo "CPU info:"
lscpu
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
- name: Build twenty-shared
run: npx nx build twenty-shared
- name: Install Playwright Browsers
run: npx nx setup twenty-e2e-testing
- name: Setup environment files
run: |
cp packages/twenty-front/.env.example packages/twenty-front/.env
npx nx reset:env twenty-server
- name: Build frontend
run: NODE_ENV=production NODE_OPTIONS="--max-old-space-size=10240" npx nx build twenty-front
- name: Build server
run: npx nx build twenty-server
- name: Create and setup database
run: |
PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "default";'
PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "test";'
npx nx run twenty-server:database:reset
- name: Start server
run: |
npx nx start twenty-server &
echo "Waiting for server to be ready..."
timeout 60 bash -c 'until curl -s http://localhost:3000/health; do sleep 2; done'
- name: Start frontend
run: |
npm_config_yes=true npx serve -s packages/twenty-front/build -l 3001 &
echo "Waiting for frontend to be ready..."
timeout 60 bash -c 'until curl -s http://localhost:3001; do sleep 2; done'
- name: Start worker
run: |
npx nx run twenty-server:worker &
echo "Worker started"
- name: Run Playwright tests
run: npx nx test twenty-e2e-testing
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: packages/twenty-e2e-testing/run_results/
retention-days: 30
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: packages/twenty-e2e-testing/playwright-report/
retention-days: 30
ci-e2e-status-check:
if: always() && !cancelled()
timeout-minutes: 5
runs-on: ubuntu-latest
needs: [changed-files-check, test]
steps:
- name: Fail job if any needs failed
if: contains(needs.*.result, 'failure')
run: exit 1
+5 -5
View File
@@ -32,7 +32,7 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Build twenty-emails
run: npx nx build twenty-emails
- name: Run email tests
@@ -40,17 +40,17 @@ jobs:
# Start the email server in the background
npx nx run twenty-emails:start &
SERVER_PID=$!
# Wait for server to start
sleep 20
# Check if server is running
if ! curl -s http://localhost:4001/preview/test.email > /dev/null; then
echo "Email server failed to start"
kill $SERVER_PID
exit 1
fi
# Kill the server
kill $SERVER_PID
ci-emails-status-check:
@@ -61,4 +61,4 @@ jobs:
steps:
- name: Fail job if any needs failed
if: contains(needs.*.result, 'failure')
run: exit 1
run: exit 1
+174 -21
View File
@@ -1,12 +1,10 @@
name: CI Front
name: CI Front and E2E
on:
push:
branches:
- main
pull_request:
merge_group:
permissions:
contents: read
@@ -15,8 +13,9 @@ concurrency:
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
env:
# restore-cache action adds 'v4-' prefix and '-<branch>-<sha>' suffix to the key
STORYBOOK_BUILD_CACHE_KEY_FOR_RESTORE_ACTION: storybook-build-depot-ubuntu-24.04-8-runner
STORYBOOK_BUILD_CACHE_KEY_FOR_SAVE_ACTION: v3-storybook-build-depot-ubuntu-24.04-8-runner-${{ github.ref_name }}-${{ github.sha }}
STORYBOOK_BUILD_CACHE_KEY_FOR_SAVE_ACTION: v4-storybook-build-depot-ubuntu-24.04-8-runner-${{ github.ref_name }}-${{ github.sha }}
jobs:
changed-files-check:
@@ -28,6 +27,13 @@ jobs:
packages/twenty-front/**
packages/twenty-ui/**
packages/twenty-shared/**
changed-files-check-e2e:
uses: ./.github/workflows/changed-files.yaml
with:
files: |
packages/**
playwright.config.ts
.github/workflows/ci-front.yaml
front-sb-build:
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true'
@@ -45,15 +51,17 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Diagnostic disk space issue
run: df -h
- name: Front / Write .env
run: npx nx reset:env twenty-front
- name: Front / Clean storybook-static
run: rm -rf packages/twenty-front/storybook-static
- name: Front / Build storybook
run: npx nx storybook:build twenty-front
- name: Save storybook build cache
uses: ./.github/workflows/actions/save-cache
uses: ./.github/actions/save-cache
with:
key: ${{ env.STORYBOOK_BUILD_CACHE_KEY_FOR_SAVE_ACTION }}
front-sb-test:
@@ -74,11 +82,11 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Install Playwright
run: cd packages/twenty-front && npx playwright install
- name: Restore storybook build cache
uses: ./.github/workflows/actions/restore-cache
uses: ./.github/actions/restore-cache
with:
key: ${{ env.STORYBOOK_BUILD_CACHE_KEY_FOR_RESTORE_ACTION }}
- name: Front / Write .env
@@ -107,7 +115,7 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- uses: actions/download-artifact@v4
with:
pattern: coverage-artifacts-${{ matrix.storybook_scope }}-${{ github.run_id }}-*
@@ -121,7 +129,7 @@ jobs:
run: npx nx storybook:coverage twenty-front --checkCoverage=true --configuration=${{ matrix.storybook_scope }}
front-chromatic-deployment:
timeout-minutes: 30
if: contains(github.event.pull_request.labels.*.name, 'run-chromatic') || github.event_name == 'push'
if: false
needs: front-sb-build
runs-on: depot-ubuntu-24.04-8
env:
@@ -132,11 +140,11 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Restore storybook build cache
uses: ./.github/workflows/actions/restore-cache
uses: ./.github/actions/restore-cache
with:
key: ${{ env.STORYBOOK_BUILD_CACHE_KEY }}
key: ${{ env.STORYBOOK_BUILD_CACHE_KEY_FOR_RESTORE_ACTION }}
- name: Front / Write .env
run: |
cd packages/twenty-front
@@ -165,26 +173,162 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Restore ${{ matrix.task }} cache
id: restore-task-cache
uses: ./.github/workflows/actions/restore-cache
uses: ./.github/actions/restore-cache
with:
key: ${{ env.TASK_CACHE_KEY }}
- name: Reset .env
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:frontend
tasks: reset:env
- name: Run ${{ matrix.task }} task
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:frontend
tasks: ${{ matrix.task }}
- name: Save ${{ matrix.task }} cache
uses: ./.github/workflows/actions/save-cache
uses: ./.github/actions/save-cache
with:
key: ${{ steps.restore-task-cache.outputs.cache-primary-key }}
front-build:
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true'
timeout-minutes: 30
runs-on: depot-ubuntu-24.04-8
env:
NODE_OPTIONS: "--max-old-space-size=10240"
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.11.0
with:
access_token: ${{ github.token }}
- name: Fetch custom Github Actions and base branch history
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/actions/yarn-install
- name: Front / Write .env
run: npx nx reset:env twenty-front
- name: Build frontend
run: npx nx build twenty-front
- name: Upload frontend build artifact
uses: actions/upload-artifact@v4
with:
name: frontend-build
path: packages/twenty-front/build
retention-days: 1
e2e-test:
runs-on: ubuntu-latest
needs: [changed-files-check-e2e, front-build]
if: |
always() &&
needs.changed-files-check-e2e.outputs.any_changed == 'true' &&
(needs.front-build.result == 'success' || needs.front-build.result == 'skipped') &&
(github.event_name == 'push' || github.event_name == 'merge_group' || (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'run-e2e')))
timeout-minutes: 30
env:
NODE_OPTIONS: "--max-old-space-size=10240"
services:
postgres:
image: twentycrm/twenty-postgres-spilo
env:
PGUSER_SUPERUSER: postgres
PGPASSWORD_SUPERUSER: postgres
ALLOW_NOSSL: "true"
SPILO_PROVIDER: "local"
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
redis:
image: redis
ports:
- 6379:6379
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: lts/*
- name: Check system resources
run: |
echo "Available memory:"
free -h
echo "Available disk space:"
df -h
echo "CPU info:"
lscpu
- name: Install dependencies
uses: ./.github/actions/yarn-install
- name: Build twenty-shared
run: npx nx build twenty-shared
- name: Install Playwright Browsers
run: npx nx setup twenty-e2e-testing
- name: Setup environment files
run: |
cp packages/twenty-front/.env.example packages/twenty-front/.env
npx nx reset:env:e2e-testing-server twenty-server
- name: Download frontend build artifact
if: needs.front-build.result == 'success'
uses: actions/download-artifact@v4
with:
name: frontend-build
path: packages/twenty-front/build
- name: Build frontend (if not available from front-build)
if: needs.front-build.result == 'skipped'
run: NODE_ENV=production NODE_OPTIONS="--max-old-space-size=10240" npx nx build twenty-front
- name: Build server
run: npx nx build twenty-server
- name: Create and setup database
run: |
PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "default";'
PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "test";'
npx nx run twenty-server:database:reset
- name: Start server
run: |
npx nx start twenty-server &
echo "Waiting for server to be ready..."
timeout 60 bash -c 'until curl -s http://localhost:3000/health; do sleep 2; done'
- name: Start frontend
run: |
npm_config_yes=true npx serve -s packages/twenty-front/build -l 3001 &
echo "Waiting for frontend to be ready..."
timeout 60 bash -c 'until curl -s http://localhost:3001; do sleep 2; done'
- name: Start worker
run: |
npx nx run twenty-server:worker &
echo "Worker started"
- name: Run Playwright tests
run: npx nx test twenty-e2e-testing
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: packages/twenty-e2e-testing/run_results/
retention-days: 30
ci-front-status-check:
if: always() && !cancelled()
timeout-minutes: 5
@@ -193,7 +337,7 @@ jobs:
[
changed-files-check,
front-task,
front-chromatic-deployment,
front-build,
merge-reports-and-check-coverage,
front-sb-test,
front-sb-build,
@@ -202,3 +346,12 @@ jobs:
- name: Fail job if any needs failed
if: contains(needs.*.result, 'failure')
run: exit 1
ci-e2e-status-check:
if: always() && !cancelled()
timeout-minutes: 5
runs-on: ubuntu-latest
needs: [changed-files-check-e2e, e2e-test]
steps:
- name: Fail job if any needs failed
if: contains(needs.*.result, 'failure')
run: exit 1
+1 -1
View File
@@ -56,4 +56,4 @@ jobs:
title: Release v${{ steps.sanitize.outputs.version }}
labels: |
release
${{ github.event.inputs.create_release == true && 'create_release' || '' }}
${{ github.event.inputs.create_release == true && 'create_release' || '' }}
+7 -7
View File
@@ -1,9 +1,7 @@
name: CI SDK
on:
push:
branches:
- main
merge_group:
pull_request:
@@ -27,7 +25,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
task: [lint, typecheck, test, build]
task: [lint, typecheck, test]
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.11.0
@@ -38,9 +36,11 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Build
run: npx nx build twenty-sdk
- name: Run ${{ matrix.task }} task
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:sdk
tasks: ${{ matrix.task }}
@@ -76,7 +76,7 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Server / Append billing config to .env.test
working-directory: packages/twenty-server
run: |
+14 -16
View File
@@ -1,12 +1,10 @@
name: CI Server
on:
push:
branches:
- main
pull_request:
merge_group:
permissions:
contents: read
@@ -59,16 +57,16 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Restore server setup
id: restore-server-setup-cache
uses: ./.github/workflows/actions/restore-cache
uses: ./.github/actions/restore-cache
with:
key: ${{ env.SERVER_SETUP_CACHE_KEY }}
- name: Build twenty-shared
run: npx nx build twenty-shared
- name: Server / Run lint & typecheck
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:backend
tasks: lint,typecheck
@@ -140,7 +138,7 @@ jobs:
exit 1
fi
- name: Save server setup
uses: ./.github/workflows/actions/save-cache
uses: ./.github/actions/save-cache
with:
key: ${{ steps.restore-server-setup-cache.outputs.cache-primary-key }}
server-test:
@@ -153,13 +151,13 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Restore server setup
uses: ./.github/workflows/actions/restore-cache
uses: ./.github/actions/restore-cache
with:
key: ${{ env.SERVER_SETUP_CACHE_KEY }}
- name: Server / Run Tests
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:backend
tasks: test
@@ -171,7 +169,7 @@ jobs:
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4, 5]
shard: [1, 2, 3, 4, 5, 6, 7, 8]
services:
postgres:
image: twentycrm/twenty-postgres-spilo
@@ -209,14 +207,14 @@ jobs:
ANALYTICS_ENABLED: true
CLICKHOUSE_URL: "http://default:clickhousePassword@localhost:8123/twenty"
CLICKHOUSE_PASSWORD: clickhousePassword
SHARD_COUNTER: 5
SHARD_COUNTER: 8
steps:
- name: Fetch custom Github Actions and base branch history
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Update .env.test for integrations tests
run: |
echo "" >> .env.test
@@ -226,7 +224,7 @@ jobs:
echo "BILLING_STRIPE_WEBHOOK_SECRET=test-webhook-secret" >> .env.test
echo "BILLING_PLAN_REQUIRED_LINK=http://localhost:3001/stripe-redirection" >> .env.test
- name: Restore server setup
uses: ./.github/workflows/actions/restore-cache
uses: ./.github/actions/restore-cache
with:
key: ${{ env.SERVER_SETUP_CACHE_KEY }}
- name: Server / Build
@@ -243,7 +241,7 @@ jobs:
- name: Run ClickHouse seeds
run: npx nx clickhouse:seed twenty-server
- name: Server / Run Integration Tests
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:backend
tasks: 'test:integration'
+3 -5
View File
@@ -1,9 +1,7 @@
name: CI Shared
on:
push:
branches:
- main
merge_group:
pull_request:
@@ -38,9 +36,9 @@ jobs:
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Run ${{ matrix.task }} task
uses: ./.github/workflows/actions/nx-affected
uses: ./.github/actions/nx-affected
with:
tag: scope:frontend
tasks: ${{ matrix.task }}
@@ -1,9 +1,11 @@
name: 'Test Docker Compose'
name: CI Docker Compose
permissions:
contents: read
on:
merge_group:
pull_request:
concurrency:
+3 -3
View File
@@ -30,12 +30,12 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Utils / Run Danger.js
run: cd packages/twenty-utils && npx nx danger:ci
env:
DANGER_GITHUB_API_TOKEN: ${{ github.token }}
congratulate:
timeout-minutes: 3
runs-on: ubuntu-latest
@@ -43,7 +43,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Run congratulate-dangerfile.js
run: cd packages/twenty-utils && npx nx danger:congratulate
env:
+2 -4
View File
@@ -4,9 +4,7 @@ permissions:
contents: read
on:
push:
branches:
- main
merge_group:
pull_request:
@@ -47,7 +45,7 @@ jobs:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Server / Create DB
run: PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d postgres -c 'CREATE DATABASE "default";'
+33 -41
View File
@@ -24,7 +24,7 @@ on:
pull_request:
paths:
- 'packages/twenty-docs/**'
- 'crowdin.yml'
- 'crowdin-docs.yml'
- '.github/workflows/docs-i18n-pull.yaml'
concurrency:
@@ -42,31 +42,14 @@ jobs:
token: ${{ github.token }}
ref: ${{ github.event_name == 'pull_request' && github.head_ref || github.ref }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
uses: ./.github/actions/yarn-install
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Setup i18n branch
- name: Setup i18n-docs branch
if: github.event_name != 'pull_request'
run: |
git fetch origin i18n || true
git checkout -B i18n origin/i18n || git checkout -b i18n
git fetch origin i18n-docs || true
git checkout -B i18n-docs origin/i18n-docs || git checkout -b i18n-docs
- name: Configure git
run: |
@@ -79,26 +62,35 @@ jobs:
git add .
git stash || true
# Install Crowdin CLI for downloading translations
- name: Install Crowdin CLI
if: github.event_name != 'pull_request' && (inputs.force_pull == true || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
run: npm install -g @crowdin/cli
# Pull docs translations from Crowdin one language at a time
# This avoids build timeout issues when processing all languages at once
- name: Pull translated docs from Crowdin
if: github.event_name != 'pull_request' && (inputs.force_pull == true || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
uses: crowdin/github-action@v2
with:
upload_sources: false
upload_translations: false
download_translations: true
source: 'packages/twenty-docs/**/*.mdx'
translation: 'packages/twenty-docs/l/%two_letters_code%/**/%original_file_name%'
export_only_approved: false
localization_branch_name: i18n
base_url: 'https://twenty.api.crowdin.com'
skip_untranslated_files: true
push_translations: false
create_pull_request: false
skip_ref_checkout: true
dryrun_action: false
run: |
# Languages supported by Mintlify (see packages/twenty-docs/src/shared/supported-languages.ts)
LANGUAGES="fr ar cs de es it ja ko pt ro ru tr zh-CN"
for lang in $LANGUAGES; do
echo "=== Pulling translations for $lang ==="
crowdin download \
--config crowdin-docs.yml \
--token "$CROWDIN_PERSONAL_TOKEN" \
--base-url "https://twenty.api.crowdin.com" \
--language "$lang" \
--skip-untranslated-strings=false \
--skip-untranslated-files=false \
--export-only-approved=false \
--verbose || echo "Warning: Failed to pull $lang, continuing with other languages..."
echo ""
done
echo "=== Download complete ==="
env:
GITHUB_TOKEN: ${{ github.token }}
CROWDIN_PROJECT_ID: '1'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: Fix file permissions
@@ -142,13 +134,13 @@ jobs:
- name: Push changes
if: github.event_name != 'pull_request' && steps.check_changes.outputs.changes_detected == 'true'
run: git push origin HEAD:i18n
run: git push origin HEAD:i18n-docs
- name: Create pull request
if: github.event_name != 'pull_request' && steps.check_changes.outputs.changes_detected == 'true'
run: |
if git diff --name-only origin/main..HEAD | grep -q .; then
gh pr create -B main -H i18n --title 'i18n - docs translations' --body 'Created by Github action' || true
gh pr create -B main -H i18n-docs --title 'i18n - docs translations' --body 'Created by Github action' || true
else
echo "No file differences between branches, skipping PR creation"
fi
+9 -26
View File
@@ -7,11 +7,12 @@ on:
workflow_dispatch:
workflow_call:
push:
branches: ['main', 'docs-localized-navigation']
branches: ['main']
paths:
- 'packages/twenty-docs/**/*.mdx'
- '!packages/twenty-docs/fr/**'
- 'crowdin.yml'
- '!packages/twenty-docs/l/**'
- 'packages/twenty-docs/navigation/navigation.template.json'
- 'crowdin-docs.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
@@ -28,28 +29,8 @@ jobs:
token: ${{ github.token }}
ref: ${{ github.ref }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Generate navigation template for Crowdin
run: yarn docs:generate-navigation-template
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Install dependencies
run: yarn install --frozen-lockfile
uses: ./.github/actions/yarn-install
- name: Generate navigation template for Crowdin
run: yarn docs:generate-navigation-template
@@ -60,9 +41,11 @@ jobs:
upload_sources: true
upload_translations: false
download_translations: false
localization_branch_name: i18n
localization_branch_name: i18n-docs
base_url: 'https://twenty.api.crowdin.com'
config: 'crowdin-docs.yml'
env:
CROWDIN_PROJECT_ID: 1
# Docs translations project
CROWDIN_PROJECT_ID: '2'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
+10 -4
View File
@@ -46,7 +46,7 @@ jobs:
git checkout -B i18n origin/i18n || git checkout -b i18n
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Build twenty-shared
run: npx nx build twenty-shared
@@ -85,12 +85,14 @@ jobs:
push_sources: false
skip_untranslated_strings: false
skip_untranslated_files: false
push_translations: true
push_translations: false
create_pull_request: false
skip_ref_checkout: true
dryrun_action: false
config: 'crowdin-app.yml'
env:
GITHUB_TOKEN: ${{ github.token }}
# App translations project
CROWDIN_PROJECT_ID: '1'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
@@ -99,6 +101,12 @@ jobs:
- name: Fix file permissions
run: sudo chown -R runner:docker .
# Fix encoding issues (escaped Unicode like \u62db -> 招) and push fixes back to Crowdin
- name: Fix translation encoding and sync to Crowdin
run: npx ts-node packages/twenty-utils/fix-crowdin-translations.ts
env:
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: Compile translations
id: compile_translations
# Because we have set English as a fallback locale, this condition does not work anymore
@@ -108,8 +116,6 @@ jobs:
npx nx run twenty-emails:lingui:compile
npx nx run twenty-front:lingui:compile
git status
git config --global user.name 'github-actions'
git config --global user.email 'github-actions@twenty.com'
git add .
if ! git diff --staged --quiet --exit-code; then
git commit -m "chore: compile translations"
+4 -5
View File
@@ -31,7 +31,7 @@ jobs:
git checkout -B i18n origin/i18n || git checkout -b i18n
- name: Install dependencies
uses: ./.github/workflows/actions/yarn-install
uses: ./.github/actions/yarn-install
- name: Build dependencies
run: npx nx build twenty-shared
@@ -87,11 +87,10 @@ jobs:
download_translations: false
localization_branch_name: i18n
base_url: 'https://twenty.api.crowdin.com'
config: 'crowdin-app.yml'
env:
# A numeric ID, found at https://crowdin.com/project/<projectName>/tools/api
CROWDIN_PROJECT_ID: 1
# Visit https://crowdin.com/settings#api-key to create this token
# App translations project
CROWDIN_PROJECT_ID: '1'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: Create a pull request
if: steps.check_extract_changes.outputs.changes_detected == 'true' || steps.check_compile_changes.outputs.changes_detected == 'true'
+118
View File
@@ -0,0 +1,118 @@
# Weekly translation QA report using Crowdin's native QA checks
name: 'Weekly Translation QA Report'
permissions:
contents: write
pull-requests: write
on:
schedule:
- cron: '0 9 * * 1' # Every Monday at 9am UTC
workflow_dispatch: # Allow manual trigger
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
qa_report:
name: Generate QA Report
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
uses: ./.github/actions/yarn-install
- name: Build twenty-shared
run: npx nx build twenty-shared
- name: Generate QA report from Crowdin
id: generate_report
run: |
npx ts-node packages/twenty-utils/translation-qa-report.ts || true
if [ -f TRANSLATION_QA_REPORT.md ]; then
echo "report_generated=true" >> $GITHUB_OUTPUT
# Count critical issues (exclude spellcheck)
CRITICAL=$(grep -oP '⚠️\s+\K\d+' TRANSLATION_QA_REPORT.md 2>/dev/null || echo "0")
echo "critical_issues=$CRITICAL" >> $GITHUB_OUTPUT
else
echo "report_generated=false" >> $GITHUB_OUTPUT
echo "critical_issues=0" >> $GITHUB_OUTPUT
fi
env:
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: Create QA branch and commit report
if: steps.generate_report.outputs.report_generated == 'true'
run: |
git config --global user.name 'github-actions'
git config --global user.email 'github-actions@twenty.com'
BRANCH_NAME="i18n-qa-report-$(date +%Y-%m-%d)"
git checkout -B $BRANCH_NAME
git add TRANSLATION_QA_REPORT.md
if ! git diff --staged --quiet --exit-code; then
git commit -m "docs: weekly translation QA report"
git push origin HEAD:$BRANCH_NAME --force
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
else
echo "No changes to commit"
echo "BRANCH_NAME=" >> $GITHUB_ENV
fi
- name: Create pull request
if: steps.generate_report.outputs.report_generated == 'true' && env.BRANCH_NAME != ''
run: |
CRITICAL="${{ steps.generate_report.outputs.critical_issues }}"
BODY=$(cat <<EOF
## Weekly Translation QA Report
**Critical issues (excluding spellcheck): $CRITICAL**
📊 **View in Crowdin**: https://twenty.crowdin.com/u/projects/1/all?filter=qa-issue
### For AI-Assisted Fixing
Open this PR in Cursor and say:
> "Fix the translation QA issues using the Crowdin API"
The AI can help fix:
- ✅ Variables mismatch (missing/wrong placeholders)
- ✅ Escaped Unicode sequences
- ⚠️ Tags mismatch
- ⚠️ Empty translations
### Available Scripts
\`\`\`bash
# View QA report
CROWDIN_PERSONAL_TOKEN=xxx npx ts-node packages/twenty-utils/translation-qa-report.ts
# Fix encoding issues automatically
CROWDIN_PERSONAL_TOKEN=xxx npx ts-node packages/twenty-utils/fix-crowdin-translations.ts
\`\`\`
---
*Close without merging after issues are addressed*
EOF
)
EXISTING_PR=$(gh pr list --head $BRANCH_NAME --json number --jq '.[0].number' 2>/dev/null || echo "")
if [ -n "$EXISTING_PR" ]; then
gh pr edit $EXISTING_PR --body "$BODY"
else
gh pr create \
--base main \
--head $BRANCH_NAME \
--title "i18n: Translation QA Report ($CRITICAL critical issues)" \
--body "$BODY" || true
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1
View File
@@ -48,3 +48,4 @@ dump.rdb
mcp.json
/.junie/
TRANSLATION_QA_REPORT.md
+1 -1
View File
@@ -67,7 +67,7 @@
"--config",
"./jest-integration.config.ts",
"${relativeFile}",
"--silent=false"
"--silent=false",
],
"cwd": "${workspaceFolder}/packages/twenty-server",
"console": "integratedTerminal",
+1
View File
@@ -31,6 +31,7 @@
"editor.formatOnSave": true
},
"javascript.format.enable": false,
"javascript.preferences.importModuleSpecifier": "non-relative",
"typescript.format.enable": false,
"cSpell.enableFiletypes": [
"!javascript",
+9 -4
View File
@@ -36,10 +36,15 @@ When testing the UI end to end, click on "Continue with Email" and use the prefi
### Code Quality
```bash
# Linting
npx nx lint twenty-front # Frontend linting
npx nx lint twenty-server # Backend linting
npx nx lint twenty-front --fix # Auto-fix linting issues
# Linting (diff with main - fastest)
npx nx lint:diff-with-main twenty-front # Lint only files changed vs main
npx nx lint:diff-with-main twenty-server # Lint only files changed vs main
npx nx lint:diff-with-main twenty-front --configuration=fix # Auto-fix files changed vs main
# Linting (full project)
npx nx lint twenty-front # Lint all files in frontend
npx nx lint twenty-server # Lint all files in backend
npx nx lint twenty-front --fix # Auto-fix all linting issues
# Type checking
npx nx typecheck twenty-front
+22
View File
@@ -0,0 +1,22 @@
#
# Crowdin CLI configuration for App translations (twenty-front, twenty-server, twenty-emails)
# Project ID: 1
# See https://crowdin.github.io/crowdin-cli/configuration for more information
#
"preserve_hierarchy": true
files: [
{
#
# Source files filter - PO files for Lingui
#
"source": "**/en.po",
#
# Translation files path
#
"translation": "%original_path%/%locale%.po",
}
]
+44
View File
@@ -0,0 +1,44 @@
#
# Crowdin CLI configuration for Documentation translations
# See https://crowdin.github.io/crowdin-cli/configuration for more information
#
"project_id": 2
"preserve_hierarchy": true
"base_url": "https://twenty.api.crowdin.com"
files: [
{
#
# MDX documentation files - user-guide
# Using md type to preserve JSX component structure
# This prevents Crowdin from reformatting <Warning>, <Accordion>, etc.
#
"source": "packages/twenty-docs/user-guide/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/user-guide/**/%original_file_name%",
},
{
#
# MDX documentation files - developers
# Using md type to preserve JSX component structure
#
"source": "packages/twenty-docs/developers/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/developers/**/%original_file_name%",
},
{
#
# MDX documentation files - twenty-ui
# Using md type to preserve JSX component structure
#
"source": "packages/twenty-docs/twenty-ui/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/twenty-ui/**/%original_file_name%",
},
{
#
# Navigation labels template - translated into per-locale navigation.json
#
"source": "packages/twenty-docs/navigation/navigation.template.json",
"translation": "packages/twenty-docs/l/%two_letters_code%/navigation.json",
}
]
-63
View File
@@ -1,63 +0,0 @@
#
# Basic Crowdin CLI configuration
# See https://crowdin.github.io/crowdin-cli/configuration for more information
# See https://support.crowdin.com/developer/configuration-file/ for all available options
#
#
# Defines whether to preserve the original directory structure in the Crowdin project
# Recommended to set to true
#
"preserve_hierarchy": true
#
# Files configuration.
# See https://support.crowdin.com/developer/configuration-file/ for all available options
#
files: [
{
#
# Source files filter
# e.g. "/resources/en/*.json"
#
"source": "**/en.po",
#
# Translation files filter
# e.g. "/resources/%two_letters_code%/%original_file_name%"
#
"translation": "%original_path%/%locale%.po",
},
{
#
# MDX documentation files - user-guide
# Using md type to preserve JSX component structure
# This prevents Crowdin from reformatting <Warning>, <Accordion>, etc.
#
"source": "packages/twenty-docs/user-guide/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/user-guide/**/%original_file_name%",
},
{
#
# MDX documentation files - developers
# Using md type to preserve JSX component structure
#
"source": "packages/twenty-docs/developers/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/developers/**/%original_file_name%",
},
{
#
# MDX documentation files - twenty-ui
# Using md type to preserve JSX component structure
#
"source": "packages/twenty-docs/twenty-ui/**/*.mdx",
"translation": "packages/twenty-docs/l/%two_letters_code%/twenty-ui/**/%original_file_name%",
},
{
#
# Navigation labels template - translated into per-locale navigation.json
#
"source": "packages/twenty-docs/navigation/navigation.template.json",
"translation": "packages/twenty-docs/l/%two_letters_code%/navigation.json",
}
]
+2 -6
View File
@@ -75,10 +75,6 @@ export default [
sourceTag: 'scope:frontend',
onlyDependOnLibsWithTags: ['scope:shared', 'scope:frontend'],
},
{
sourceTag: 'scope:zapier',
onlyDependOnLibsWithTags: ['scope:shared'],
},
],
},
],
@@ -141,10 +137,10 @@ export default [
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/no-empty-interface': [
'@typescript-eslint/no-empty-object-type': [
'error',
{
allowSingleExtends: true,
allowInterfaces: 'with-single-extends',
},
],
'@typescript-eslint/no-explicit-any': 'off',
+496 -6
View File
@@ -128,6 +128,375 @@ export default [
additionalHooks: 'useRecoilCallback',
},
],
// Lingui - detect untranslated strings
'lingui/no-unlocalized-strings': [
'error',
{
ignore: [
// Ignore strings which are a single "word" (no spaces) and don't start with uppercase
'^(?![A-Z])\\S+$',
// Ignore UPPERCASE literals (constants, env vars)
'^[A-Z0-9_-]+$',
// Ignore strings that look like code/technical (contain special chars)
'^[\\s]*$', // whitespace only
'.*[{}/<>].*', // contains code-like characters
'^\\d+(\\.\\d+)?(px|rem|em|%|vh|vw|s|ms)?$', // CSS units
'^[\\d.]+(px|rem|em|%|vh|vw|fr|s|ms)?(\\s+[\\d.]+(px|rem|em|%|vh|vw|fr|s|ms)?)*$', // CSS values like "200px 1fr 20px"
'^#[0-9a-fA-F]{3,8}$', // hex colors
'^rgba?\\(.*\\)$', // rgb/rgba colors
'^(auto|none|inherit|initial|unset|flex|grid|block|inline|inline-block|relative|absolute|fixed|sticky)$', // CSS keywords
'^color:.*$', // CSS color declarations
'^font-.*$', // CSS font declarations
'^\\d+$', // numbers only
'^https?:\\/\\/.*', // URLs
'^@.*', // @ mentions or decorators
'^\\/.*', // paths starting with /
'^[HhMmSsYyDdAaPp:.,\\s-]+$', // date format patterns (HH:mm, yyyy-MM-dd, etc.)
'^Arrow(Up|Down|Left|Right)$', // keyboard keys
'^(Enter|Escape|Tab|Space|Backspace|Delete)$', // keyboard keys
'^Text$', // clipboard data type
'^(allow-|sandbox)', // iframe sandbox values
'^Id$', // technical identifier suffix (e.g., fieldNameId)
'^(string|number|boolean|void|any|unknown|never|object)$', // TypeScript type keywords
'^(Dark|Light)$', // color schemes
'^translate\\(.*\\)$', // CSS transform strings
'^svg .*$', // CSS selectors
'^Icon[A-Z]\\w*$', // Icon names like IconDefault, IconTable, IconSettings
'^\\w*Icon$', // Icon names that end with Icon like FieldIcon
'^%c.*$', // Console format strings
// Common item IDs for selectable lists
'^(Group|CalendarView|CalendarDateField|Compact view)$',
'^(Layout|Visibility|Fields|Delete view|Copy link to view|Create custom view)$',
'^(GroupBy|Sort|HideEmptyGroups|HiddenGroups)$',
// HTTP headers and auth (technical, not user-facing)
'^Authorization$',
'^Bearer .*',
// Allow object keys that are technical identifiers
'^(topLeft|topRight|bottomLeft|bottomRight)$',
// Color schemes and CSS media queries
'^System$',
'^\\(prefers-color-scheme:',
// GraphQL query names (used in refetchQueries)
'^Get[A-Z]\\w*$',
// React Context names (technical identifiers)
'.*Context$',
// SVG paths (geometric coordinates, not translatable)
'^M[0-9 LML]+$',
'^[ML][0-9 ]+$',
// Database ordering values (technical, backend API)
'^(Asc|Desc)Nulls(First|Last)$',
// Calendar response status values (backend enum values, not user-facing)
'^(Yes|No|Maybe)$',
// Email validation error prefixes (combined with dynamic content)
'^Invalid email(s)?:',
// GraphQL type construction patterns
'.*FilterInput$',
'.*OrderByInput.*',
'^\\$filter.*',
'^\\$orderBy.*',
'^\\$after.*',
'^\\$before.*',
'^\\$first.*',
'^\\$last.*',
// Logger names (technical identifiers)
'^Twenty(-\\w+)?$',
// Cookie names and cookie string patterns
'^twenty_session_id$',
'^; domain=',
// Context names for createRequiredContext
'^[A-Z][a-zA-Z]+$',
// JSON-like filter patterns
'^%"type":',
'^%"objectNameSingular":',
],
ignoreNames: [
// HTML/React attributes that shouldn't be translated
{ regex: { pattern: 'className', flags: 'i' } },
{ regex: { pattern: 'styleName', flags: 'i' } },
{ regex: { pattern: 'testId', flags: 'i' } },
'data-testid',
'dataTestId',
'src',
'srcSet',
'href',
'target',
'rel',
'type',
'id',
'key',
'name',
'htmlFor',
'width',
'height',
'fill',
'stroke',
'viewBox',
'clipPath',
'd', // SVG path
'transform',
'displayName',
'defaultValue',
'to', // router links
'path',
'pathname',
'hash',
'componentInstanceId',
'hotkeyScope',
'dropdownId',
'recoilScopeId',
'modalId',
'dialogId',
'itemId',
'selectableItemIdArray',
'listenerId',
'focusId',
'color', // color prop values
'variant', // component variants
'size', // size prop values
'position', // position values
'align', // alignment values
'justify', // justification values
'direction', // direction values
'orientation', // orientation values
'status', // status values
'state', // state values
'mode', // mode values
'accent', // accent values
// CSS-related props
'gridAutoColumns',
'gridAutoRows',
'gridTemplateColumns',
'gridTemplateRows',
'gridColumn',
'gridRow',
'gap',
'margin',
'padding',
'border',
'borderRadius',
'boxShadow',
'flex',
'flexDirection',
'flexWrap',
'justifyContent',
'alignItems',
'alignContent',
'overflow',
'display',
'cursor',
'zIndex',
'opacity',
'fontWeight',
'fontSize',
'lineHeight',
'textAlign',
'textDecoration',
'whiteSpace',
'wordBreak',
'objectFit',
'backgroundSize',
'backgroundPosition',
'minWidth',
'maxWidth',
'minHeight',
'maxHeight',
'mobileGridAutoColumns',
'tabletGridAutoColumns',
// Styled components
'css',
'theme',
'animation',
'transition',
// GraphQL
'query',
'mutation',
'subscription',
'fragment',
'operationName',
'variables',
'__typename',
// Technical identifiers
'fieldName',
'columnName',
'objectNameSingular',
'objectNamePlural',
'metadataId',
'nameSingular',
'namePlural',
// Event types
'eventName',
'event',
'action',
'actionType',
// Icon names
'iconName',
{ regex: { pattern: '^Icon[A-Z]' } },
// UPPER_CASE names (constants)
{ regex: { pattern: '^[A-Z][A-Z0-9_]*$' } },
// Sort direction values (backend API)
'orderBy',
{ regex: { pattern: '^(Asc|Desc)(NullsFirst|NullsLast)?$' } },
// HTTP headers (technical, not user-facing)
'Authorization',
],
ignoreFunctions: [
// Console and logging
'console.*',
'*.log',
'*.warn',
'*.error',
'*.debug',
'*.info',
'*.trace',
'logDebug',
'formatTitle',
// Error handling (technical messages, not user-facing)
'Error',
'TypeError',
'RangeError',
'SyntaxError',
'throw',
'assertUnreachable',
'CustomError',
'parseInitialBlocknote',
// Testing
'describe',
'it',
'test',
'expect',
'jest.*',
'*.toBe',
'*.toEqual',
'*.toContain',
'*.toMatch',
'*.toThrow',
// React/Libraries internals
'require',
'import',
'styled',
'styled.*',
'css',
'keyframes',
'createGlobalStyle',
// Router
'useNavigate',
'navigate',
'useLocation',
'useParams',
// Date formatting (patterns are not translatable)
'format',
'formatDate',
'formatDateTime',
'formatTime',
'parseISO',
'parse',
// Navigation
'useNavigationSection',
// Recoil
'atom',
'atomFamily',
'selector',
'selectorFamily',
'useSetRecoilState',
'useRecoilState',
'useRecoilValue',
// GraphQL operations
'gql',
'useQuery',
'useMutation',
'useLazyQuery',
'useSubscription',
// Type checking and validation
'*.includes',
'*.indexOf',
'*.startsWith',
'*.endsWith',
'*.split',
'*.join',
'*.match',
'*.replace',
'*.test',
'Object.keys',
'Object.values',
'Object.entries',
'Array.isArray',
// DOM operations
'*.getElementById',
'*.getElementsByClassName',
'*.querySelector',
'*.querySelectorAll',
'*.getAttribute',
'*.setAttribute',
'*.addEventListener',
'*.removeEventListener',
'*.dispatchEvent',
'*.createElement',
// Storage
'localStorage.*',
'sessionStorage.*',
'searchParams.*',
'*.get',
'*.set',
'*.has',
'*.delete',
// Misc utilities
'cva',
'cn',
'clsx',
'classNames',
'track',
'*.postMessage',
'*.dispatch',
'*.commit',
// Event handlers (typically receive enum values, not user-facing text)
'onChange',
'onClick',
'onSelect',
'onSubmit',
'onFocus',
'onBlur',
'onKeyDown',
'onKeyUp',
'onMouseEnter',
'onMouseLeave',
// Logging functions (technical messages, not user-facing)
'logError',
'logDebug',
'logInfo',
'logWarn',
'loggerLink',
// Context creation (technical names)
'createRequiredContext',
// GraphQL refetch queries (technical identifiers)
'refetchQueries',
],
},
],
},
},
@@ -152,6 +521,10 @@ export default [
'error',
{
patterns: [
{
group: ['../*'],
message: 'Relative parent imports are not allowed. Use @/ alias instead.',
},
{
group: ['@tabler/icons-react'],
message: 'Please import icons from `twenty-ui`',
@@ -175,7 +548,7 @@ export default [
'@typescript-eslint/ban-ts-comment': 'error',
'@typescript-eslint/consistent-type-imports': [
'error',
{
{
prefer: 'type-imports',
fixStyle: 'inline-type-imports'
},
@@ -183,10 +556,10 @@ export default [
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/no-empty-interface': [
'@typescript-eslint/no-empty-object-type': [
'error',
{
allowSingleExtends: true,
allowInterfaces: 'with-single-extends',
},
],
'@typescript-eslint/no-empty-function': 'off',
@@ -208,14 +581,119 @@ export default [
},
},
// Storybook files
// Storybook files and story-related files
{
files: ['*.stories.@(ts|tsx|js|jsx)'],
files: [
'**/*.stories.ts',
'**/*.stories.tsx',
'**/*.stories.js',
'**/*.stories.jsx',
'**/__stories__/**/*',
],
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
'lingui/no-unlocalized-strings': 'off',
},
},
// Debug files - development only, not user-facing
{
files: [
'**/Debug*.tsx',
'**/*Debug*.tsx',
'**/*DebugDisplay*.tsx',
'**/*DebugHelper*.tsx',
'**/*DebugObserver*.tsx',
],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// Testing utilities and mock data - not user-facing
{
files: [
'**/testing/**/*.tsx',
'**/testing/**/*.ts',
'**/__mocks__/**/*',
'**/*mock*.ts',
'**/*Mock*.ts',
'**/perf/**/*',
],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// Constants files - technical values, not user-facing
{
files: [
'**/constants/**/*.ts',
'**/*.constants.ts',
'**/validation-schemas/**/*.ts',
'**/*Schema.ts',
'**/*-schema.ts',
],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// Layout configuration files - titles are translated at consumption time
{
files: ['**/layouts/**/*.ts'],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// Service files - contain technical strings (logger names, HTTP headers, etc.)
{
files: ['**/services/**/*.ts'],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// State files - contain technical default values
{
files: ['**/states/**/*.ts'],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// Utility files - technical/developer-facing
{
files: [
'**/utils/**/*.ts',
'**/*Utils.ts',
'**/*-utils.ts',
'**/*Util.ts',
'**/*-util.ts',
'**/errors/**/*.ts',
'**/*Error.ts',
'**/*-error.ts',
],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// Config and setup files - not user-facing
{
files: [
'**/*.config.ts',
'**/*.config.js',
'**/vite.config.ts',
'**/.storybook/**/*',
],
rules: {
'lingui/no-unlocalized-strings': 'off',
},
},
// JavaScript specific configuration
{
files: ['*.{js,jsx}'],
@@ -250,7 +728,18 @@ export default [
// Test files
{
files: [
'*.test.@(ts|tsx|js|jsx)',
'**/*.test.ts',
'**/*.test.tsx',
'**/*.test.js',
'**/*.test.jsx',
'**/*.spec.ts',
'**/*.spec.tsx',
'**/*.spec.js',
'**/*.spec.jsx',
'**/__tests__/**/*.ts',
'**/__tests__/**/*.tsx',
'**/__mocks__/**/*.ts',
'**/__mocks__/**/*.tsx',
],
languageOptions: {
globals: {
@@ -266,6 +755,7 @@ export default [
},
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
'lingui/no-unlocalized-strings': 'off',
},
},
+96 -26
View File
@@ -4,7 +4,9 @@
"libsDir": "packages"
},
"namedInputs": {
"default": ["{projectRoot}/**/*"],
"default": [
"{projectRoot}/**/*"
],
"excludeStories": [
"default",
"!{projectRoot}/.storybook/*",
@@ -32,17 +34,26 @@
"targetDefaults": {
"build": {
"cache": true,
"inputs": ["^production", "production"],
"dependsOn": ["^build"]
"inputs": [
"^production",
"production"
],
"dependsOn": [
"^build"
]
},
"start": {
"cache": false,
"dependsOn": ["^build"]
"dependsOn": [
"^build"
]
},
"lint": {
"executor": "@nx/eslint:lint",
"cache": true,
"outputs": ["{options.outputFile}"],
"outputs": [
"{options.outputFile}"
],
"options": {
"eslintConfig": "{projectRoot}/eslint.config.mjs",
"cache": true,
@@ -56,7 +67,22 @@
"fix": true
}
},
"dependsOn": ["^build"]
"dependsOn": [
"^build"
]
},
"lint:diff-with-main": {
"executor": "nx:run-commands",
"cache": false,
"options": {
"command": "git diff --name-only --diff-filter=d main | grep -E '{args.pattern}' | grep '^{projectRoot}/' | xargs sh -c 'if [ $# -gt 0 ]; then npx eslint --config {projectRoot}/eslint.config.mjs \"$@\"; fi' _",
"pattern": "\\.(ts|tsx|js|jsx)$"
},
"configurations": {
"fix": {
"command": "git diff --name-only --diff-filter=d main | grep -E '{args.pattern}' | grep '^{projectRoot}/' | xargs sh -c 'if [ $# -gt 0 ]; then npx eslint --config {projectRoot}/eslint.config.mjs --fix \"$@\"; fi' _"
}
}
},
"fmt": {
"executor": "nx:run-commands",
@@ -77,7 +103,9 @@
"write": true
}
},
"dependsOn": ["^build"]
"dependsOn": [
"^build"
]
},
"typecheck": {
"executor": "nx:run-commands",
@@ -91,22 +119,30 @@
"watch": true
}
},
"dependsOn": ["^build"]
"dependsOn": [
"^build"
]
},
"test": {
"executor": "@nx/jest:jest",
"cache": true,
"dependsOn": ["^build"],
"dependsOn": [
"^build"
],
"inputs": [
"^default",
"excludeStories",
"{workspaceRoot}/jest.preset.js"
],
"outputs": ["{projectRoot}/coverage"],
"outputs": [
"{projectRoot}/coverage"
],
"options": {
"jestConfig": "{projectRoot}/jest.config.mjs",
"coverage": true,
"coverageReporters": ["text-summary"],
"coverageReporters": [
"text-summary"
],
"cacheDirectory": "../../.cache/jest/{projectRoot}"
},
"configurations": {
@@ -115,7 +151,10 @@
"maxWorkers": 3
},
"coverage": {
"coverageReporters": ["lcov", "text"]
"coverageReporters": [
"lcov",
"text"
]
},
"watch": {
"watch": true
@@ -124,25 +163,36 @@
},
"test:e2e": {
"cache": true,
"dependsOn": ["^build"]
"dependsOn": [
"^build"
]
},
"storybook:build": {
"executor": "nx:run-commands",
"cache": true,
"inputs": ["^default", "excludeTests"],
"outputs": ["{projectRoot}/{options.output-dir}"],
"inputs": [
"^default",
"excludeTests"
],
"outputs": [
"{projectRoot}/{options.output-dir}"
],
"options": {
"cwd": "{projectRoot}",
"command": "VITE_DISABLE_TYPESCRIPT_CHECKER=true storybook build --test",
"command": "NODE_OPTIONS='--max-old-space-size=10240' VITE_DISABLE_TYPESCRIPT_CHECKER=true storybook build --test",
"output-dir": "storybook-static",
"config-dir": ".storybook"
},
"dependsOn": ["^build"]
"dependsOn": [
"^build"
]
},
"storybook:serve:dev": {
"executor": "nx:run-commands",
"cache": true,
"dependsOn": ["^build"],
"dependsOn": [
"^build"
],
"options": {
"cwd": "{projectRoot}",
"command": "storybook dev",
@@ -151,7 +201,9 @@
},
"storybook:serve:static": {
"executor": "nx:run-commands",
"dependsOn": ["storybook:build"],
"dependsOn": [
"storybook:build"
],
"options": {
"cwd": "{projectRoot}",
"command": "npx http-server {args.staticDir} -a={args.host} --port={args.port} --silent={args.silent}",
@@ -164,8 +216,13 @@
"storybook:test": {
"executor": "nx:run-commands",
"cache": true,
"inputs": ["^default", "excludeTests"],
"outputs": ["{projectRoot}/coverage/storybook"],
"inputs": [
"^default",
"excludeTests"
],
"outputs": [
"{projectRoot}/coverage/storybook"
],
"options": {
"cwd": "{projectRoot}",
"commands": [
@@ -181,7 +238,10 @@
},
"storybook:test:no-coverage": {
"executor": "nx:run-commands",
"inputs": ["^default", "excludeTests"],
"inputs": [
"^default",
"excludeTests"
],
"options": {
"cwd": "{projectRoot}",
"commands": [
@@ -271,12 +331,20 @@
},
"@nx/vite:test": {
"cache": true,
"inputs": ["default", "^default"]
"inputs": [
"default",
"^default"
]
},
"@nx/vite:build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["default", "^default"]
"dependsOn": [
"^build"
],
"inputs": [
"default",
"^default"
]
}
},
"installation": {
@@ -308,7 +376,9 @@
"tasksRunnerOptions": {
"default": {
"options": {
"cacheableOperations": ["storybook:build"]
"cacheableOperations": [
"storybook:build"
]
}
}
},
+13 -14
View File
@@ -2,7 +2,6 @@
"private": true,
"dependencies": {
"@apollo/client": "^3.7.17",
"@date-fns/tz": "^1.4.1",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@floating-ui/react": "^0.24.3",
@@ -54,6 +53,7 @@
"semver": "^7.5.4",
"slash": "^5.1.0",
"storybook-addon-mock-date": "^0.6.0",
"temporal-polyfill": "^0.3.0",
"ts-key-enum": "^2.0.12",
"tslib": "^2.8.1",
"type-fest": "4.10.1",
@@ -82,20 +82,20 @@
"@nx/vite": "22.0.3",
"@nx/web": "22.0.3",
"@sentry/types": "^8",
"@storybook/addon-actions": "8.6.14",
"@storybook/addon-actions": "8.6.15",
"@storybook/addon-coverage": "^1.0.0",
"@storybook/addon-essentials": "8.6.14",
"@storybook/addon-interactions": "8.6.14",
"@storybook/addon-links": "8.6.14",
"@storybook/blocks": "8.6.14",
"@storybook/core-server": "8.6.14",
"@storybook/addon-essentials": "8.6.15",
"@storybook/addon-interactions": "8.6.15",
"@storybook/addon-links": "8.6.15",
"@storybook/blocks": "8.6.15",
"@storybook/core-server": "8.6.15",
"@storybook/icons": "^1.2.9",
"@storybook/preview-api": "8.6.14",
"@storybook/react": "8.6.14",
"@storybook/react-vite": "8.6.14",
"@storybook/test": "8.6.14",
"@storybook/preview-api": "8.6.15",
"@storybook/react": "8.6.15",
"@storybook/react-vite": "8.6.15",
"@storybook/test": "8.6.15",
"@storybook/test-runner": "^0.23.0",
"@storybook/types": "8.6.14",
"@storybook/types": "8.6.15",
"@stylistic/eslint-plugin": "^1.5.0",
"@swc-node/register": "1.8.0",
"@swc/cli": "^0.3.12",
@@ -109,7 +109,6 @@
"@types/bytes": "^3.1.1",
"@types/chrome": "^0.0.267",
"@types/deep-equal": "^1.0.1",
"@types/express": "^4.17.13",
"@types/fs-extra": "^11.0.4",
"@types/graphql-fields": "^1.3.6",
"@types/inquirer": "^9.0.9",
@@ -178,7 +177,7 @@
"raw-loader": "^4.0.2",
"rimraf": "^5.0.5",
"source-map-support": "^0.5.20",
"storybook": "8.6.14",
"storybook": "8.6.15",
"storybook-addon-cookie": "^3.2.0",
"storybook-addon-pseudo-states": "^2.1.2",
"supertest": "^6.1.3",
+1
View File
@@ -23,6 +23,7 @@ Create Twenty App is the official scaffolding CLI for building apps on top of [T
- A Twenty workspace and an API key (create one at https://app.twenty.com/settings/api-webhooks)
## Quick start
```bash
npx create-twenty-app@latest my-twenty-app
cd my-twenty-app
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "create-twenty-app",
"version": "0.1.3",
"version": "0.2.4",
"description": "Command-line interface to create Twenty application",
"main": "dist/cli.cjs",
"bin": "dist/cli.cjs",
@@ -1,137 +1,29 @@
import js from '@eslint/js';
import typescriptEslint from '@typescript-eslint/eslint-plugin';
import typescriptParser from '@typescript-eslint/parser';
import importPlugin from 'eslint-plugin-import';
import preferArrowPlugin from 'eslint-plugin-prefer-arrow';
import prettierPlugin from 'eslint-plugin-prettier';
import unusedImportsPlugin from 'eslint-plugin-unused-imports';
import tseslint from 'typescript-eslint';
export default [
// Base JS rules
// Base JS recommended rules
js.configs.recommended,
// Global ignores
{
ignores: ['**/node_modules/**', '**/dist/**', '**/coverage/**'],
},
// TypeScript recommended rules
...tseslint.configs.recommended,
// Base config for TS/JS files
{
files: ['**/*.{js,jsx,ts,tsx}'],
files: ['**/*.ts', '**/*.tsx'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: {
prettier: prettierPlugin,
import: importPlugin,
'prefer-arrow': preferArrowPlugin,
'unused-imports': unusedImportsPlugin,
},
rules: {
// General rules (aligned with main project)
'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
'no-console': [
'warn',
{ allow: ['group', 'groupCollapsed', 'groupEnd'] },
],
'no-control-regex': 0,
'no-debugger': 'error',
'no-duplicate-imports': 'error',
'no-undef': 'off',
'no-unused-vars': 'off',
// Import rules
'import/no-relative-packages': 'error',
'import/no-useless-path-segments': 'error',
'import/no-duplicates': ['error', { considerQueryString: true }],
// Prefer arrow functions
'prefer-arrow/prefer-arrow-functions': [
'error',
{
disallowPrototype: true,
singleReturnOnly: false,
classPropertiesAllowed: false,
},
],
// Unused imports
'unused-imports/no-unused-imports': 'warn',
'unused-imports/no-unused-vars': [
'warn',
{
vars: 'all',
varsIgnorePattern: '^_',
args: 'after-used',
argsIgnorePattern: '^_',
},
],
// Prettier (formatting as lint errors if you want)
'prettier/prettier': 'error',
},
},
// TypeScript-specific configuration
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: typescriptParser,
parserOptions: {
ecmaFeatures: {
jsx: true,
},
project: true,
tsconfigRootDir: import.meta.dirname,
},
},
plugins: {
'@typescript-eslint': typescriptEslint,
},
rules: {
// Turn off base rule and use TS-aware versions
'no-redeclare': 'off',
'@typescript-eslint/no-redeclare': 'error',
'@typescript-eslint/ban-ts-comment': 'error',
'@typescript-eslint/consistent-type-imports': [
'error',
{
prefer: 'type-imports',
fixStyle: 'inline-type-imports',
},
],
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/no-empty-interface': [
'error',
{
allowSingleExtends: true,
},
// Common TypeScript-friendly tweaks
'@typescript-eslint/no-unused-vars': [
'warn',
{ argsIgnorePattern: '^_' },
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-unused-vars': 'off',
},
},
// Test files (Jest)
{
files: ['**/*.spec.@(ts|tsx|js|jsx)', '**/*.test.@(ts|tsx|js|jsx)'],
languageOptions: {
globals: {
jest: true,
describe: true,
it: true,
expect: true,
beforeEach: true,
afterEach: true,
beforeAll: true,
afterAll: true,
},
},
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
'no-unused-vars': 'off', // handled by TS rule
},
},
];
@@ -2,6 +2,8 @@ import * as fs from 'fs-extra';
import { join } from 'path';
import { v4 } from 'uuid';
const SOURCE_FOLDER = 'src';
export const copyBaseApplicationProject = async ({
appName,
appDisplayName,
@@ -21,10 +23,23 @@ export const copyBaseApplicationProject = async ({
await createYarnLock(appDirectory);
const sourceFolderPath = join(appDirectory, SOURCE_FOLDER);
await fs.ensureDir(sourceFolderPath);
const defaultServerlessFunctionRoleUniversalIdentifier = v4();
await createDefaultServerlessFunctionRoleConfig({
displayName: appDisplayName,
appDirectory: sourceFolderPath,
defaultServerlessFunctionRoleUniversalIdentifier,
});
await createApplicationConfig({
displayName: appDisplayName,
description: appDescription,
appDirectory,
appDirectory: sourceFolderPath,
defaultServerlessFunctionRoleUniversalIdentifier,
});
};
@@ -76,14 +91,41 @@ yarn-error.log*
await fs.writeFile(join(appDirectory, '.gitignore'), gitignoreContent);
};
const createDefaultServerlessFunctionRoleConfig = async ({
displayName,
appDirectory,
defaultServerlessFunctionRoleUniversalIdentifier,
}: {
displayName: string;
appDirectory: string;
defaultServerlessFunctionRoleUniversalIdentifier: string;
}) => {
const content = `import { type RoleConfig } from 'twenty-sdk';
export const functionRole: RoleConfig = {
universalIdentifier: '${defaultServerlessFunctionRoleUniversalIdentifier}',
label: '${displayName} default function role',
description: '${displayName} default function role',
canReadAllObjectRecords: true,
canUpdateAllObjectRecords: true,
canSoftDeleteAllObjectRecords: true,
canDestroyAllObjectRecords: false,
};
`;
await fs.writeFile(join(appDirectory, 'role.config.ts'), content);
};
const createApplicationConfig = async ({
displayName,
description,
appDirectory,
defaultServerlessFunctionRoleUniversalIdentifier,
}: {
displayName: string;
description?: string;
appDirectory: string;
defaultServerlessFunctionRoleUniversalIdentifier: string;
}) => {
const content = `import { type ApplicationConfig } from 'twenty-sdk';
@@ -91,6 +133,7 @@ const config: ApplicationConfig = {
universalIdentifier: '${v4()}',
displayName: '${displayName}',
description: '${description ?? ''}',
functionRoleUniversalIdentifier: '${defaultServerlessFunctionRoleUniversalIdentifier}',
};
export default config;
@@ -125,13 +168,17 @@ const createPackageJson = async ({
uninstall: 'twenty app uninstall',
help: 'twenty help',
auth: 'twenty auth login',
lint: 'eslint',
'lint-fix': 'eslint --fix',
},
dependencies: {
'twenty-sdk': '0.1.3',
'twenty-sdk': '0.2.4',
},
devDependencies: {
'@types/node': '^24.7.2',
typescript: '^5.9.3',
'@types/node': '^24.7.2',
eslint: '^9.32.0',
'typescript-eslint': '^8.50.0',
},
};
@@ -17,7 +17,7 @@ FIREFLIES_API_KEY=your_fireflies_api_key_here
# Fireflies plan level - affects which fields are available
# Options: free, pro, business, enterprise
# This controls which GraphQL fields are requested to avoid 403 errors
FIREFLIES_PLAN_LEVEL=pro
FIREFLIES_PLAN=free
# Twenty CRM API key for authentication
# Generate this from your Twenty instance: Settings > Developers > API Keys
@@ -0,0 +1 @@
.yarn
@@ -1,5 +1,76 @@
# Changelog
## [0.3.1] - 2025-12-08
Import all
### Added
- Historical import CLI: `yarn meeting:all` to fetch and insert historical Fireflies meetings with filters (date range, organizers, participants, channel, mine) and dry-run support.
- Fireflies transcripts listing with pagination and date filtering to support bulk imports.
### Changed
- Deduplication now checks `firefliesMeetingId` before creating meetings (webhook + bulk).
- Shared historical importer pipeline reusing existing note/meeting formatting.
## [0.3.0] - 2025-12-08
Subscription-based query / Full transcript and AI notes for Pro+ / More
### Added
- **Full transcript capture**: Meeting object now stores the complete meeting transcript with speaker names and timestamps (`transcript` field)
- **Rich AI meeting notes**: Captures detailed AI-generated meeting notes from Fireflies (`notes` field with 7,000+ char summaries)
- **Expanded summary fields**: Now fetches all available Fireflies summary data:
- `notes` - Detailed AI-generated meeting notes with timestamps and section headers
- `bullet_gist` - Emoji-enhanced bullet point summaries
- `outline` / `shorthand_bullet` - Timestamped meeting outline
- `gist` - One-sentence meeting summary
- `short_summary` - Single paragraph summary
- `short_overview` - Brief overview
- **New Meeting fields**:
- `transcript` - Full meeting transcript with speaker attribution
- `notes` - AI-generated detailed notes
- `audioUrl` - Link to audio recording (Pro+)
- `videoUrl` - Link to video recording (Business+)
- `meetingLink` - Original meeting link
- `neutralPercent` - Neutral sentiment percentage
- **Meeting delete utility**: New `yarn meeting:delete <meetingId>` script for cleanup and re-import
- **Debug meeting utility**: New `scripts/debug-meeting.ts` to inspect raw Fireflies API responses
### Changed
- **Plan-based GraphQL queries**: Completely redesigned query system with three tiers:
- **Free**: Basic fields only (title, date, duration, participants, transcript_url, meeting_link)
- **Pro**: Adds full transcript (`sentences`), summary fields, speakers, audio_url
- **Business+**: Adds analytics, video_url, speaker stats, meeting metrics
- **Action items parsing**: Fixed parsing of `action_items` which Fireflies returns as newline-separated string, not array
- **Note body format**: Enhanced with Meeting Notes, Outline, Key Points sections from rich Fireflies data
- **Import status**: Added `PARTIAL` status for imports missing summary/analytics data
### Fixed
- Missing `notes` and `bullet_gist` fields in data transform (were fetched but not passed through)
- Proper fallback: Uses `shorthand_bullet` when `outline` is empty (Fireflies stores outline content there)
- Summary readiness detection now checks `notes` field in addition to `overview` and `action_items`
### Documentation
- Updated README with complete API access comparison table by subscription plan
- Documented all available Fireflies summary fields and their plan requirements
## [0.2.3] - 2025-12-06
### Added
- **Meeting ingest utility**: New `yarn meeting:ingest <meetingId>` script to manually fetch and import specific Fireflies meetings into Twenty
- **Plan-based field selection**: Added `FIREFLIES_PLAN` configuration to control which GraphQL fields are requested based on subscription level (free, pro, business, enterprise)
- **Main entry point**: New `src/index.ts` centralizing all exports for cleaner imports
### Changed
- **Auth configuration**: Disabled authentication requirement for webhook route (`isAuthRequired: false`) to support serverless deployments
- **Signature verification fallback**: Webhook handler now supports signature in payload body as fallback when HTTP headers aren't forwarded to serverless functions (production doesn't work for Fireflies webhook)
- **Improved type safety**: Replaced `any` types with proper TypeScript types throughout codebase
### Enhanced
- **Webhook debugging**: Added detailed debug output including param keys, header info, and signature comparison details
- **Test webhook script**: Includes signature in both header and payload, with diagnostic output for header forwarding status
- **Documentation**: Added README sections on current twenty headers forward limitations and utility scripts
## [0.2.2] - 2025-11-04
### Added
@@ -2,6 +2,10 @@
Automatically captures meeting notes with AI-generated summaries and insights from Fireflies.ai into your Twenty CRM.
### Current Status
- Doesn't work with Fireflies webhook yet due to missing headers forwarding in twenty serverless func
- Meeting ingestion utility scripts are available for individual meeting insertion and historical meetings with filters with yarn meeting:all
## Integration Overview
**Fireflies webhook → Fireflies API → Twenty CRM with summary-focused insights**
@@ -19,19 +23,54 @@ Automatically captures meeting notes with AI-generated summaries and insights fr
## API Access by Subscription Plan
Fireflies API access varies significantly by subscription tier:
Fireflies API access varies by subscription tier. This integration automatically adapts queries based on your plan and falls back gracefully if restrictions are encountered.
### Plan Comparison
| Feature | Free | Pro | Business | Enterprise |
|---------|------|-----|----------|------------|
| **API Rate Limit** | 50 requests/day | 50 requests/day | 60 requests/minute | 60 requests/minute |
| **Storage** | 800 mins/seat | 8,000 mins/seat | Unlimited | Unlimited |
| **AI Summaries** | Limited (20 credits) | Unlimited | Unlimited | Unlimited |
| **Video Upload** | 100MB max | 1.5GB max | 1.5GB max | 1.5GB max |
| **Advanced Features** | Basic transcription | AI apps, analytics | Team analytics, CI | Full API, SSO, compliance |
|---------|:----:|:---:|:--------:|:----------:|
| **API Rate Limit** | 50/day | 50/day | 60/min | 60/min |
| **Basic Data** (title, date, duration) | ✅ | ✅ | ✅ | ✅ |
| **Participants List** | ✅ | ✅ | ✅ | ✅ |
| **Transcript URL** | ✅ | ✅ | ✅ | ✅ |
| **Speakers** | ❌ | ✅ | ✅ | ✅ |
| **Summary** (overview, keywords) | ❌ | ✅ | ✅ | ✅ |
| **Audio URL** | ❌ | ✅ | ✅ | ✅ |
| **Action Items** | ❌ | ❌ | ✅ | ✅ |
| **Topics Discussed** | ❌ | ❌ | ✅ | ✅ |
| **Video URL** | ❌ | ❌ | ✅ | ✅ |
| **Sentiment Analytics** | ❌ | ❌ | ✅ | ✅ |
| **Meeting Attendees (detailed)** | ❌ | ❌ | ✅ | ✅ |
**Key Design Pattern:** Subscription-based API access uses **tiered rate limiting** rather than feature gating. Lower tiers get severely restricted throughput (50/day vs 60/minute = 1,700x difference), making production integrations effectively require Business+ plans.
### What You'll Get Per Plan
**Pro Plan Limitation:** Despite "unlimited" AI summaries, the 50 requests/day limit severely constrains production usage for meeting-heavy organizations.
**Free Plan:**
- Meeting title, date, duration
- Participant names/emails (basic)
- Link to transcript
**Pro Plan:**
- Everything in Free, plus:
- Speaker identification
- AI summary (overview + keywords)
- Audio recording URL
**Business Plan:**
- Everything in Pro, plus:
- Action items extraction
- Topics discussed
- Sentiment analysis (positive/negative/neutral %)
- Video recording URL
- Detailed meeting attendee info
### Configuration
Set your plan in `.env`:
```bash
FIREFLIES_PLAN=free # Options: free, pro, business, enterprise
```
**Rate Limiting:** Free/Pro plans are limited to 50 API calls/day. The integration uses conservative retry settings by default to stay within limits.
## What Gets Captured
@@ -114,11 +153,6 @@ The `setup:fields` script adds 13 custom fields to store rich Fireflies data:
| `firefliesMeetingId` | TEXT | Fireflies Meeting ID | Unique identifier from Fireflies |
| `organizerEmail` | TEXT | Organizer Email | Email address of the meeting organizer |
Then re-sync:
```bash
npx twenty-cli app sync
```
**Note:** Without custom fields, meetings will be created with just the title. The rich summary data will only be stored in Notes for 1-on-1 meetings.
## Configuration
@@ -160,6 +194,29 @@ The integration uses **HMAC SHA-256 signature verification**:
- Twenty verifies signature using your webhook secret
- Invalid signatures are rejected immediately
### Current Platform Limitation (Headers)
- Twenty serverless route triggers currently do **not forward HTTP headers** to functions. Fireflies signatures sent in headers are stripped, so header-based verification does not work in production.
- Workaround: the provided test script also includes the signature inside the payload; the handler falls back to that payload signature. Use this only for testing until header forwarding is supported.
## Utilities for meeting insertion (workarounds)
- Ingest a specific Fireflies meeting into Twenty:
`yarn meeting:ingest <meetingId>` or `MEETING_ID=... yarn meeting:ingest`
- Fetch all/historical Fireflies meetings into Twenty:
`yarn meeting:all [--from 2024-01-01] [--to 2024-02-01] [--organizer a@x.com] [--participant b@x.com] [--channel <channelId>] [--mine] [--dry-run]`
- Filters (combine as needed):
- `--from` / `--to`: ISO or date string range filter
- `--organizer` / `--participant`: comma-separated emails
- `--channel`: Fireflies channel id
- `--mine`: only meetings for the current Fireflies user
- Controls:
- `--dry-run`: list and transform without writing to Twenty
- `--page-size`: pagination size (default 50)
- `--max-records`: stop after N transcripts (default 500)
## Development
```bash
@@ -247,10 +304,7 @@ Client expressed strong interest in the enterprise plan.
## Future Implementation Opportunities
### Past Meetings Retrieval
- **New trigger to retrieve past meetings from a contact** - Enable users to fetch historical meeting data from Fireflies for specific contacts, allowing retrospective capture and analysis of past interactions.
Next iteration would enhance the **intelligence layer** to:
Next iterations would enhance the **intelligence layer** to:
### AI-Powered Insights
- **Extract pain points, objections & buying signals** automatically from transcripts
@@ -1,4 +1,4 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
import { type ApplicationConfig } from 'twenty-sdk';
const config: ApplicationConfig = {
universalIdentifier: 'a4df0c0f-c65e-44e5-8436-24814182d4ac',
@@ -9,17 +9,25 @@ const config: ApplicationConfig = {
FIREFLIES_WEBHOOK_SECRET: {
universalIdentifier: 'f51f7646-be9f-4ba9-9b75-160dd288cd0c',
description: 'Secret key for verifying Fireflies webhook signatures',
isSecret: true,
//isSecret: true,
value: '',
},
FIREFLIES_API_KEY: {
universalIdentifier: 'faa41f07-b28e-4500-b1c0-ce4b3d27924c',
description: 'Fireflies GraphQL API key used to fetch meeting summaries',
isSecret: true,
//isSecret: true,
value: '',
},
FIREFLIES_PLAN: {
universalIdentifier: '57dbb73c-aac5-4247-9fcc-a070bb669f16',
description: 'Fireflies plan: free, pro, business, enterprise',
value: 'free',
},
TWENTY_API_KEY: {
universalIdentifier: '02756551-5bf7-4fb2-8e08-1f622008d305',
description: 'Twenty API key used when running scripts locally',
isSecret: true,
//isSecret: true,
value: '',
},
SERVER_URL: {
universalIdentifier: '9b3a5e8e-5973-4e6b-a059-2966075652aa',
@@ -36,6 +44,11 @@ const config: ApplicationConfig = {
description: 'Log level: silent, error, warn, info, debug (default: error)',
value: 'error',
},
CAPTURE_LOGS: {
universalIdentifier: 'adbcc267-309d-49b2-af71-76f1299d863e',
description: 'Capture logs in webhook response for debugging (true/false)',
value: 'true',
},
FIREFLIES_SUMMARY_STRATEGY: {
universalIdentifier: '562b43d9-cd47-4ec1-ae16-5cc7ebc9729b',
description: 'Summary fetch strategy: immediate_only, immediate_with_retry, delayed_polling, or basic_only',
@@ -1,6 +1,6 @@
{
"name": "fireflies",
"version": "0.2.2",
"version": "0.3.0",
"license": "MIT",
"engines": {
"node": "^24.5.0",
@@ -11,12 +11,15 @@
"scripts": {
"test": "jest",
"setup:fields": "tsx scripts/add-meeting-fields.ts",
"test:webhook": "tsx scripts/test-webhook.ts"
"test:webhook": "tsx scripts/test-webhook.ts",
"meeting:ingest": "tsx scripts/ingest-meeting.ts",
"meeting:delete": "tsx scripts/delete-meeting.ts",
"meeting:all": "tsx scripts/fetch-all-meetings.ts"
},
"dependencies": {
"axios": "^1.13.1",
"dotenv": "^16.3.1",
"twenty-sdk": "0.0.3"
"dotenv": "^17.2.3",
"twenty-sdk": "0.1.3"
},
"devDependencies": {
"@types/jest": "^29.5.5",
@@ -1,7 +1,7 @@
{
"name": "fireflies",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "packages/twenty-apps/fireflies/src",
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "packages/twenty-apps/community/fireflies/src",
"projectType": "application",
"tags": [
"scope:apps"
@@ -13,7 +13,7 @@
"{workspaceRoot}/coverage/{projectRoot}"
],
"options": {
"jestConfig": "packages/twenty-apps/fireflies/jest.config.mjs",
"jestConfig": "packages/twenty-apps/community/fireflies/jest.config.mjs",
"passWithNoTests": true
},
"configurations": {
@@ -36,7 +36,7 @@
],
"options": {
"lintFilePatterns": [
"packages/twenty-apps/fireflies/**/*.{ts,tsx,js,jsx}"
"packages/twenty-apps/community/fireflies/**/*.{ts,tsx,js,jsx}"
]
},
"configurations": {
@@ -50,7 +50,11 @@ interface FieldDefinition {
options?: FieldOption[];
}
// Meeting fields based on Fireflies GraphQL API transcript schema
// See: https://docs.fireflies.ai/graphql-api/query/transcript
// Note: Some fields require higher plans (Pro, Business, Enterprise)
const MEETING_FIELDS: FieldDefinition[] = [
// === Internal Twenty Relations ===
{
type: 'RELATION',
name: 'note',
@@ -59,11 +63,21 @@ const MEETING_FIELDS: FieldDefinition[] = [
icon: 'IconNotes',
isNullable: true,
},
// === Basic Fields (All Plans) ===
{
type: 'TEXT',
name: 'firefliesMeetingId',
label: 'Fireflies ID',
description: 'Unique transcript ID from Fireflies (maps to: id)',
icon: 'IconKey',
isNullable: true,
},
{
type: 'DATE_TIME',
name: 'meetingDate',
label: 'Meeting Date',
description: 'Date and time when the meeting occurred',
description: 'When the meeting occurred (maps to: date)',
icon: 'IconCalendar',
isNullable: true,
},
@@ -71,39 +85,107 @@ const MEETING_FIELDS: FieldDefinition[] = [
type: 'NUMBER',
name: 'duration',
label: 'Duration (minutes)',
description: 'Meeting duration in minutes',
description: 'Meeting duration in minutes (maps to: duration)',
icon: 'IconClock',
isNullable: true,
},
{
type: 'TEXT',
name: 'meetingType',
label: 'Meeting Type',
description: 'Type of meeting (e.g., Sales Call, Sprint Planning, 1:1)',
icon: 'IconTag',
name: 'organizerEmail',
label: 'Organizer Email',
description: 'Meeting organizer email (maps to: organizer_email)',
icon: 'IconMail',
isNullable: true,
},
{
type: 'LINKS',
name: 'transcriptUrl',
label: 'Transcript URL',
description: 'Link to full transcript (maps to: transcript_url)',
icon: 'IconFileText',
isNullable: true,
},
{
type: 'LINKS',
name: 'meetingLink',
label: 'Meeting Link',
description: 'Original meeting link (maps to: meeting_link)',
icon: 'IconLink',
isNullable: true,
},
// === Pro+ Fields (summary, speakers, audio_url, transcript) ===
{
type: 'TEXT',
name: 'transcript',
label: 'Full Transcript',
description: 'Full meeting transcript with speaker names and timestamps [Pro+]',
icon: 'IconFileText',
isNullable: true,
},
{
type: 'TEXT',
name: 'overview',
label: 'Overview',
description: 'AI-generated meeting summary (maps to: summary.overview) [Pro+]',
icon: 'IconFileDescription',
isNullable: true,
},
{
type: 'TEXT',
name: 'notes',
label: 'AI Notes',
description: 'Detailed AI-generated meeting notes (maps to: summary.notes) [Pro+]',
icon: 'IconNotes',
isNullable: true,
},
{
type: 'TEXT',
name: 'keywords',
label: 'Keywords',
description: 'Key topics and themes discussed (comma-separated)',
description: 'Key topics extracted (maps to: summary.keywords) [Pro+]',
icon: 'IconTags',
isNullable: true,
},
{
type: 'LINKS',
name: 'audioUrl',
label: 'Audio URL',
description: 'Link to audio recording (maps to: audio_url) [Pro+]',
icon: 'IconHeadphones',
isNullable: true,
},
// === Business+ Fields (analytics, video_url, full summary) ===
{
type: 'TEXT',
name: 'meetingType',
label: 'Meeting Type',
description: 'AI-detected meeting type (maps to: summary.meeting_type) [Business+]',
icon: 'IconTag',
isNullable: true,
},
{
type: 'TEXT',
name: 'topics',
label: 'Topics Discussed',
description: 'Topics covered in meeting (maps to: summary.topics_discussed) [Business+]',
icon: 'IconListDetails',
isNullable: true,
},
{
type: 'NUMBER',
name: 'sentimentScore',
label: 'Sentiment Score',
description: 'Overall meeting sentiment (0-1 scale, where 1 is most positive)',
icon: 'IconMoodSmile',
name: 'actionItemsCount',
label: 'Action Items',
description: 'Number of action items (count of: summary.action_items) [Business+]',
icon: 'IconCheckbox',
isNullable: true,
},
{
type: 'NUMBER',
name: 'positivePercent',
label: 'Positive %',
description: 'Percentage of positive sentiment in conversation',
description: 'Positive sentiment % (maps to: analytics.sentiments.positive_pct) [Business+]',
icon: 'IconThumbUp',
isNullable: true,
},
@@ -111,69 +193,48 @@ const MEETING_FIELDS: FieldDefinition[] = [
type: 'NUMBER',
name: 'negativePercent',
label: 'Negative %',
description: 'Percentage of negative sentiment in conversation',
description: 'Negative sentiment % (maps to: analytics.sentiments.negative_pct) [Business+]',
icon: 'IconThumbDown',
isNullable: true,
},
{
type: 'NUMBER',
name: 'actionItemsCount',
label: 'Action Items',
description: 'Number of action items identified',
icon: 'IconCheckbox',
name: 'neutralPercent',
label: 'Neutral %',
description: 'Neutral sentiment % (maps to: analytics.sentiments.neutral_pct) [Business+]',
icon: 'IconMoodNeutral',
isNullable: true,
},
{
type: 'LINKS',
name: 'transcriptUrl',
label: 'Transcript URL',
description: 'Link to full transcript in Fireflies',
icon: 'IconFileText',
isNullable: true,
},
{
type: 'LINKS',
name: 'recordingUrl',
label: 'Recording URL',
description: 'Link to video/audio recording in Fireflies',
name: 'videoUrl',
label: 'Video URL',
description: 'Link to video recording (maps to: video_url) [Business+]',
icon: 'IconVideo',
isNullable: true,
},
{
type: 'TEXT',
name: 'firefliesMeetingId',
label: 'Fireflies Meeting ID',
description: 'Unique identifier from Fireflies',
icon: 'IconKey',
isNullable: true,
},
{
type: 'TEXT',
name: 'organizerEmail',
label: 'Organizer Email',
description: 'Email address of the meeting organizer',
icon: 'IconMail',
isNullable: true,
},
// === Import Tracking Fields (Internal) ===
{
type: 'SELECT',
name: 'importStatus',
label: 'Import Status',
description: 'Status of the meeting import from Fireflies',
description: 'Status of the Fireflies import',
icon: 'IconCheck',
isNullable: true,
options: [
{ value: 'SUCCESS', label: 'Success', position: 0, color: 'green' },
{ value: 'FAILED', label: 'Failed', position: 1, color: 'red' },
{ value: 'PENDING', label: 'Pending', position: 2, color: 'yellow' },
{ value: 'RETRYING', label: 'Retrying', position: 3, color: 'orange' },
{ value: 'PARTIAL', label: 'Partial', position: 1, color: 'blue' },
{ value: 'FAILED', label: 'Failed', position: 2, color: 'red' },
{ value: 'PENDING', label: 'Pending', position: 3, color: 'yellow' },
{ value: 'RETRYING', label: 'Retrying', position: 4, color: 'orange' },
],
},
{
type: 'TEXT',
name: 'importError',
label: 'Import Error',
description: 'Error message if meeting import failed',
description: 'Error message if import failed',
icon: 'IconAlertTriangle',
isNullable: true,
},
@@ -181,7 +242,7 @@ const MEETING_FIELDS: FieldDefinition[] = [
type: 'DATE_TIME',
name: 'lastImportAttempt',
label: 'Last Import Attempt',
description: 'Date and time of the last import attempt',
description: 'When import was last attempted',
icon: 'IconClock',
isNullable: true,
},
@@ -189,7 +250,7 @@ const MEETING_FIELDS: FieldDefinition[] = [
type: 'NUMBER',
name: 'importAttempts',
label: 'Import Attempts',
description: 'Number of times import has been attempted',
description: 'Number of import attempts',
icon: 'IconRepeat',
isNullable: true,
},
@@ -414,13 +475,9 @@ const main = async () => {
}
if (createdCount === 0 && skippedCount === MEETING_FIELDS.length) {
console.log('\n✨ All fields already exist. Nothing to do!');
console.log('\n✨ All fields already exist. Nothing to do!\n');
} else if (createdCount > 0) {
console.log('\n✨ Custom fields added successfully!');
console.log('\n📝 Next steps:');
console.log(' 1. Re-sync your app: npx twenty-cli app sync');
console.log(' 2. Update the createMeetingRecord function to use these fields');
console.log(' 3. Test the integration with a real meeting');
console.log('\n✨ Custom fields added successfully!\n');
}
} catch (error) {
@@ -0,0 +1,81 @@
/* eslint-disable no-console */
import * as dotenv from 'dotenv';
import * as path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ path: path.join(__dirname, '../.env') });
const FIREFLIES_API_KEY = process.env.FIREFLIES_API_KEY;
const meetingId = process.argv[2] || '01KBMR1ZYQ34YP8D2KB4B16QPH';
const main = async (): Promise<void> => {
if (!FIREFLIES_API_KEY) {
console.error('❌ FIREFLIES_API_KEY is required');
process.exit(1);
}
const query = `
query GetTranscript($transcriptId: String!) {
transcript(id: $transcriptId) {
id
title
summary {
overview
notes
gist
bullet_gist
short_summary
short_overview
outline
shorthand_bullet
action_items
keywords
topics_discussed
meeting_type
transcript_chapters
}
}
}
`;
const response = await fetch('https://api.fireflies.ai/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${FIREFLIES_API_KEY}`,
},
body: JSON.stringify({ query, variables: { transcriptId: meetingId } }),
});
if (!response.ok) {
const errorText = await response.text();
console.error(`❌ API request failed with status ${response.status}`);
console.error(errorText);
process.exit(1);
}
const json = await response.json();
console.log('=== Fireflies API Response ===\n');
console.log(JSON.stringify(json, null, 2));
if (json.data?.transcript?.summary) {
const s = json.data.transcript.summary;
console.log('\n=== Summary Fields Status ===');
console.log('overview:', s.overview ? `✓ (${s.overview.length} chars)` : '✗ empty');
console.log('notes:', s.notes ? `✓ (${s.notes.length} chars)` : '✗ empty');
console.log('gist:', s.gist ? `✓ (${s.gist.length} chars)` : '✗ empty');
console.log('bullet_gist:', s.bullet_gist ? `✓ (${s.bullet_gist.length} chars)` : '✗ empty');
console.log('outline:', s.outline ? `✓ (${s.outline.length} chars)` : '✗ empty');
console.log('action_items:', s.action_items?.length || 0, 'items');
console.log('topics_discussed:', s.topics_discussed?.length || 0, 'topics');
console.log('keywords:', s.keywords?.length || 0, 'keywords');
}
};
main().catch((error) => {
console.error('❌ Failed to fetch meeting');
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
});
@@ -0,0 +1,59 @@
/* eslint-disable no-console */
import * as dotenv from 'dotenv';
import * as path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ path: path.join(__dirname, '../.env') });
const SERVER_URL = process.env.SERVER_URL || 'http://localhost:3000';
const API_KEY = process.env.TWENTY_API_KEY;
const meetingId = process.argv[2];
const main = async (): Promise<void> => {
if (!API_KEY) {
console.error('❌ TWENTY_API_KEY is required');
process.exit(1);
}
if (!meetingId) {
console.error('Usage: yarn delete:meeting <meetingId>');
process.exit(1);
}
const response = await fetch(`${SERVER_URL}/graphql`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
},
body: JSON.stringify({
query: `mutation DeleteMeeting($id: UUID!) { deleteMeeting(id: $id) { id } }`,
variables: { id: meetingId },
}),
});
if (!response.ok) {
const errorText = await response.text();
console.error(`❌ Delete failed (status ${response.status})`);
console.error(errorText);
process.exit(1);
}
const result = await response.json();
const deletedId = result.data?.deleteMeeting?.id;
if (result.errors || !deletedId) {
const message = result.errors?.[0]?.message || 'deleteMeeting returned null';
console.error('❌ Error:', message);
process.exit(1);
}
console.log('✅ Deleted meeting:', deletedId);
};
main().catch((error) => {
console.error('❌ Failed to delete meeting');
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
});
@@ -0,0 +1,222 @@
/* eslint-disable no-console */
/**
* Fetch historical Fireflies meetings and insert into Twenty.
*
* Usage:
* yarn meeting:all [--from 2024-01-01] [--to 2024-02-01] [--organizer alice@x.com] [--participant bob@x.com] [--channel <channelId>] [--mine] [--dry-run] [--page-size 50] [--max-records 200]
*
* Required env:
* FIREFLIES_API_KEY
* TWENTY_API_KEY
*
* Optional env:
* SERVER_URL (defaults to http://localhost:3000)
* FIREFLIES_PLAN (free|pro|business|enterprise)
* AUTO_CREATE_CONTACTS (true|false)
* FIREFLIES_* retry settings (see README)
*/
import * as dotenv from 'dotenv';
import { existsSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { FirefliesApiClient } from '../src/fireflies-api-client';
import { type HistoricalImportFilters, HistoricalImporter } from '../src/historical-importer';
import { createLogger } from '../src/logger';
import { TwentyCrmService } from '../src/twenty-crm-service';
import {
getApiUrl,
getFirefliesPlan,
getSummaryFetchConfig,
shouldAutoCreateContacts,
} from '../src/utils';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const envPath = join(__dirname, '..', '.env');
if (existsSync(envPath)) {
dotenv.config({ path: envPath });
}
const logger = createLogger('cli:meeting:all');
type CliArgs = {
from?: string;
to?: string;
organizer?: string[];
participant?: string[];
channel?: string;
host?: string;
mine?: boolean;
dryRun?: boolean;
pageSize?: number;
maxRecords?: number;
limit?: number;
};
const parseArgs = (argv: string[]): CliArgs => {
const args: CliArgs = {};
const parseNumberArg = (value?: string): number | undefined => {
if (!value) return undefined;
const parsed = Number.parseInt(value, 10);
return Number.isNaN(parsed) ? undefined : parsed;
};
for (let i = 0; i < argv.length; i += 1) {
const current = argv[i];
const next = argv[i + 1];
switch (current) {
case '--from':
args.from = next;
i += 1;
break;
case '--to':
args.to = next;
i += 1;
break;
case '--organizer':
args.organizer = next ? next.split(',') : [];
i += 1;
break;
case '--participant':
args.participant = next ? next.split(',') : [];
i += 1;
break;
case '--channel':
args.channel = next;
i += 1;
break;
case '--host':
args.host = next;
i += 1;
break;
case '--mine':
args.mine = true;
break;
case '--dry-run':
args.dryRun = true;
break;
case '--page-size':
args.pageSize = parseNumberArg(next);
i += 1;
break;
case '--max-records':
args.maxRecords = parseNumberArg(next);
i += 1;
break;
case '--limit':
args.limit = parseNumberArg(next);
i += 1;
break;
default:
break;
}
}
return args;
};
const parseDate = (value?: string): number | undefined => {
if (!value) {
return undefined;
}
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? undefined : parsed;
};
const main = async (): Promise<void> => {
const args = parseArgs(process.argv.slice(2));
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
const twentyApiKey = process.env.TWENTY_API_KEY || '';
if (!firefliesApiKey) {
console.error('❌ FIREFLIES_API_KEY is required');
process.exit(1);
}
if (!twentyApiKey) {
console.error('❌ TWENTY_API_KEY is required');
process.exit(1);
}
const fromDate = parseDate(args.from);
const toDate = parseDate(args.to);
const filters: HistoricalImportFilters = {
fromDate,
toDate,
organizers: args.organizer,
participants: args.participant,
channelId: args.channel,
hostEmail: args.host,
mine: args.mine,
limit: args.limit,
pageSize: args.pageSize,
maxRecords: args.maxRecords,
};
const summaryConfig = getSummaryFetchConfig();
const plan = getFirefliesPlan();
const autoCreateContacts = shouldAutoCreateContacts();
logger.info(
`Starting historical import (dryRun=${Boolean(args.dryRun)}, plan=${plan}, pageSize=${filters.pageSize ?? 50})`,
);
const firefliesClient = new FirefliesApiClient(firefliesApiKey);
const twentyService = new TwentyCrmService(twentyApiKey, getApiUrl());
const importer = new HistoricalImporter(firefliesClient, twentyService);
const result = await importer.run(filters, {
dryRun: args.dryRun,
autoCreateContacts,
summaryConfig,
plan,
});
console.log('✅ Historical import summary:');
const summary = {
dryRun: result.dryRun,
totalListed: result.totalListed,
imported: result.imported,
skippedExisting: result.skippedExisting,
summaryPending: result.summaryPending,
failed: result.failed,
};
console.log(JSON.stringify(summary, null, 2));
if (result.statuses.length > 0) {
console.log('Status by meeting:');
console.table(
result.statuses.map((s) => ({
meetingId: s.meetingId,
title: s.title ?? '',
status: s.status,
reason: s.reason ?? '',
})),
);
}
if (result.failed.length > 0) {
process.exitCode = 1;
}
};
main().catch((error) => {
console.error('❌ Failed to import historical meetings');
if (error instanceof Error) {
console.error(error.message);
if (error.stack) {
console.error(error.stack);
}
} else {
console.error(String(error));
}
process.exit(1);
});
@@ -0,0 +1,93 @@
/* eslint-disable no-console */
/**
* Fetch a Fireflies meeting by ID and insert it into Twenty using the same path
* as the webhook handler.
*
* Usage:
* yarn meeting:ingest <meetingId>
* Or
* MEETING_ID=... yarn meeting:ingest
*
* Required env:
* FIREFLIES_API_KEY
* FIREFLIES_WEBHOOK_SECRET
* TWENTY_API_KEY
*
* Optional env:
* SERVER_URL (defaults to http://localhost:3000)
* FIREFLIES_PLAN (free|pro|business|enterprise)
*/
import { createHmac } from 'crypto';
import * as dotenv from 'dotenv';
import { existsSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { WebhookHandler } from '../src/webhook-handler';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const envPath = join(__dirname, '..', '.env');
if (existsSync(envPath)) {
dotenv.config({ path: envPath });
}
const args = process.argv.slice(2);
const meetingId = args[0] || process.env.MEETING_ID;
if (!meetingId) {
console.error('❌ meetingId is required (arg or MEETING_ID env)');
process.exit(1);
}
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
const twentyApiKey = process.env.TWENTY_API_KEY || '';
const webhookSecret = process.env.FIREFLIES_WEBHOOK_SECRET || '';
if (!firefliesApiKey) {
console.error('❌ FIREFLIES_API_KEY is required');
process.exit(1);
}
if (!twentyApiKey) {
console.error('❌ TWENTY_API_KEY is required');
process.exit(1);
}
if (!webhookSecret) {
console.error('❌ FIREFLIES_WEBHOOK_SECRET is required to generate signature');
process.exit(1);
}
const payload = {
meetingId,
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = `sha256=${createHmac('sha256', webhookSecret)
.update(body, 'utf8')
.digest('hex')}`;
const main = async (): Promise<void> => {
console.log(`🚀 Ingesting meeting ${meetingId} via webhook handler`);
const handler = new WebhookHandler();
const result = await handler.handle(payload, {
'x-hub-signature': signature,
body,
});
console.log('✅ Result:');
console.log(JSON.stringify(result, null, 2));
if (result.errors && result.errors.length > 0) {
process.exitCode = 1;
}
};
main().catch((error) => {
console.error('❌ Failed to ingest meeting');
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
});
@@ -40,11 +40,13 @@ const FIREFLIES_WEBHOOK_SECRET = process.env.FIREFLIES_WEBHOOK_SECRET || 'test_s
const _FIREFLIES_API_KEY = process.env.FIREFLIES_API_KEY || 'test_api_key';
// Test meeting data (simulating Fireflies API response)
const TEST_MEETING_ID = 'test-meeting-local-' + Date.now();
const TEST_MEETING_ID = process.env.MEETING_ID || 'test-meeting-local-' + Date.now();
const CLIENT_REFERENCE_ID = process.env.CLIENT_REFERENCE_ID;
const TEST_WEBHOOK_PAYLOAD = {
meetingId: TEST_MEETING_ID,
eventType: 'Transcription completed',
clientReferenceId: 'test-client-ref',
...(CLIENT_REFERENCE_ID ? { clientReferenceId: CLIENT_REFERENCE_ID } : {}),
};
// Mock Fireflies GraphQL API response
@@ -119,11 +121,17 @@ const main = async () => {
}
// Prepare webhook payload
const body = JSON.stringify(TEST_WEBHOOK_PAYLOAD);
const signature = generateHMACSignature(body, FIREFLIES_WEBHOOK_SECRET);
const unsignedBody = JSON.stringify(TEST_WEBHOOK_PAYLOAD);
const signature = generateHMACSignature(unsignedBody, FIREFLIES_WEBHOOK_SECRET);
const payloadWithSignature = {
...TEST_WEBHOOK_PAYLOAD,
'x-hub-signature': signature,
};
const body = JSON.stringify(payloadWithSignature);
console.log('📤 Sending webhook payload:');
console.log(JSON.stringify(TEST_WEBHOOK_PAYLOAD, null, 2));
console.log(JSON.stringify(payloadWithSignature, null, 2));
console.log('\n️ Signature is sent both as header (preferred) and in payload as fallback (headers are not passed to serverless functions)\n');
console.log(`\n🔐 HMAC Signature: ${signature}\n`);
// Check if server is reachable
@@ -178,6 +186,31 @@ const main = async () => {
console.log('📥 Response Body:');
console.log(JSON.stringify(responseData, null, 2));
// Report whether the server appears to have received the header signature
const debugMessages = Array.isArray((responseData as any)?.debug)
? ((responseData as any).debug as string[])
: [];
const headerMissing =
debugMessages.some((msg) => msg.includes('headerKeys=none')) ||
debugMessages.some((msg) => msg.includes('providedSignature=undefined'));
const signatureErrors =
Array.isArray((responseData as any)?.errors) &&
((responseData as any).errors as unknown[]).some(
(err) => typeof err === 'string' && err.toLowerCase().includes('signature'),
);
if (headerMissing) {
console.log(
'\n⚠️ Server did not report any received headers; it may be using payload fallback for signature verification.',
);
} else {
console.log('\n✅ Server reported headers present (header-based signature should be used).');
}
if (signatureErrors) {
console.log('⚠️ Signature was rejected by the server (check webhook secret / payload).');
}
if (response.ok) {
console.log('\n✅ Webhook test completed successfully!');
console.log('\n📋 Next steps:');
@@ -1,426 +0,0 @@
import { createLogger } from './logger';
import type { FirefliesMeetingData, FirefliesParticipant, SummaryFetchConfig } from './types';
const logger = createLogger('fireflies-api');
export class FirefliesApiClient {
private apiKey: string;
constructor(apiKey: string) {
if (!apiKey) {
logger.critical('FIREFLIES_API_KEY is required but not provided - this is a critical configuration error');
throw new Error('FIREFLIES_API_KEY is required');
}
this.apiKey = apiKey;
}
async fetchMeetingData(
meetingId: string,
options?: { timeout?: number }
): Promise<FirefliesMeetingData> {
const query = `
query GetTranscript($transcriptId: String!) {
transcript(id: $transcriptId) {
id
title
date
duration
participants
organizer_email
meeting_attendees {
displayName
email
phoneNumber
name
location
}
meeting_attendance {
name
join_time
leave_time
}
speakers {
name
}
summary {
action_items
overview
}
transcript_url
}
}
`;
const controller = new AbortController();
const timeoutId = options?.timeout
? setTimeout(() => controller.abort(), options.timeout)
: null;
try {
const response = await fetch('https://api.fireflies.ai/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
query,
variables: { transcriptId: meetingId },
}),
signal: controller.signal,
});
if (timeoutId) clearTimeout(timeoutId);
if (!response.ok) {
let errorDetails = `Fireflies API request failed with status ${response.status}`;
try {
const errorBody = await response.text();
if (errorBody) {
errorDetails += `: ${errorBody}`;
}
} catch {
// Ignore if we can't read the response body
}
throw new Error(errorDetails);
}
const json = await response.json() as {
data?: { transcript?: any };
errors?: Array<{ message?: string }>;
};
if (json.errors && json.errors.length > 0) {
throw new Error(`Fireflies API error: ${json.errors[0]?.message || 'Unknown error'}`);
}
const transcript = json.data?.transcript;
if (!transcript) {
throw new Error('Invalid response from Fireflies API: missing transcript data');
}
return this.transformMeetingData(transcript, meetingId);
} catch (error) {
if (timeoutId) clearTimeout(timeoutId);
throw error;
}
}
async fetchMeetingDataWithRetry(
meetingId: string,
config: SummaryFetchConfig
): Promise<{ data: FirefliesMeetingData; summaryReady: boolean }> {
// immediate_only: single attempt, no retries
if (config.strategy === 'immediate_only') {
logger.debug(`fetching meeting ${meetingId} (strategy: immediate_only)`);
const meetingData = await this.fetchMeetingData(meetingId, { timeout: 10000 });
const ready = this.isSummaryReady(meetingData);
logger.debug(`summary ready: ${ready}`);
return { data: meetingData, summaryReady: ready };
}
// immediate_with_retry: retry with exponential backoff
logger.debug(`fetching meeting ${meetingId} (strategy: immediate_with_retry, maxAttempts: ${config.retryAttempts})`);
for (let attempt = 1; attempt <= config.retryAttempts; attempt++) {
try {
const meetingData = await this.fetchMeetingData(meetingId, { timeout: 10000 });
const ready = this.isSummaryReady(meetingData);
logger.debug(`attempt ${attempt}/${config.retryAttempts}: summary ready=${ready}`);
if (ready) {
return { data: meetingData, summaryReady: true };
}
if (attempt < config.retryAttempts) {
const delayMs = config.retryDelay * attempt;
logger.debug(`summary not ready, waiting ${delayMs}ms before retry ${attempt + 1}`);
await new Promise(resolve => setTimeout(resolve, delayMs));
} else {
logger.debug(`max retries reached, returning partial data`);
return { data: meetingData, summaryReady: false };
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`attempt ${attempt}/${config.retryAttempts} failed: ${errorMsg}`);
if (attempt === config.retryAttempts) {
throw error;
}
const delayMs = config.retryDelay * attempt;
logger.debug(`retrying in ${delayMs}ms...`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
throw new Error('Failed to fetch meeting data after retries');
}
private isSummaryReady(meetingData: FirefliesMeetingData): boolean {
return (
(meetingData.summary?.action_items?.length > 0) ||
(meetingData.summary?.overview?.length > 0) ||
meetingData.summary_status === 'completed'
);
}
private extractAllParticipants(transcript: any): FirefliesParticipant[] {
const participantsWithEmails: FirefliesParticipant[] = [];
const participantsNameOnly: FirefliesParticipant[] = [];
logger.debug('=== PARTICIPANT EXTRACTION DEBUG ===');
logger.debug('participants field:', JSON.stringify(transcript.participants));
logger.debug('meeting_attendees field:', JSON.stringify(transcript.meeting_attendees));
logger.debug('speakers field:', transcript.speakers?.map((s: any) => s.name));
logger.debug('meeting_attendance field:', transcript.meeting_attendance?.map((a: any) => a.name));
logger.debug('organizer_email:', transcript.organizer_email);
// Helper function to check if a string is an email
const isEmail = (str: string): boolean => {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str.trim());
};
// Helper function to check if already exists
const isDuplicate = (name: string, email: string): boolean => {
const nameLower = name.toLowerCase().trim();
const emailLower = email.toLowerCase().trim();
return participantsWithEmails.some(p =>
p.name.toLowerCase().trim() === nameLower ||
(email && p.email.toLowerCase() === emailLower)
) || participantsNameOnly.some(p =>
p.name.toLowerCase().trim() === nameLower
);
};
// 1. Extract from legacy participants field (with emails)
if (transcript.participants && Array.isArray(transcript.participants)) {
transcript.participants.forEach((participant: string) => {
// Handle comma-separated emails or names
const parts = participant.split(',').map(p => p.trim());
parts.forEach(part => {
const emailMatch = part.match(/<([^>]+)>/);
const email = emailMatch ? emailMatch[1] : '';
// Extract name properly: if there's an email in angle brackets, get the part before it
const name = emailMatch
? part.substring(0, part.indexOf('<')).trim()
: part.trim();
// Skip if the "name" is actually an email address
if (isEmail(name)) {
logger.debug(`Skipping participant with email as name: "${name}"`);
return;
}
// Skip if empty name
if (!name) {
return;
}
// Skip duplicates
if (isDuplicate(name, email)) {
logger.debug(`Skipping duplicate participant: "${name}" <${email}>`);
return;
}
if (name && email) {
participantsWithEmails.push({ name, email });
} else if (name) {
participantsNameOnly.push({ name, email: '' });
}
});
});
}
// 2. Extract from meeting_attendees field (structured)
if (transcript.meeting_attendees && Array.isArray(transcript.meeting_attendees)) {
transcript.meeting_attendees.forEach((attendee: any) => {
const name = attendee.displayName || attendee.name || '';
const email = attendee.email || '';
// Skip if name is actually an email
if (isEmail(name)) {
logger.debug(`Skipping attendee with email as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, email)) {
if (email) {
participantsWithEmails.push({ name, email });
} else {
participantsNameOnly.push({ name, email: '' });
}
}
});
}
// 3. Extract from speakers field (name only)
if (transcript.speakers && Array.isArray(transcript.speakers)) {
transcript.speakers.forEach((speaker: any) => {
const name = speaker.name || '';
// Skip if name is actually an email
if (isEmail(name)) {
logger.debug(`Skipping speaker with email as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, '')) {
participantsNameOnly.push({ name, email: '' });
}
});
}
// 4. Extract from meeting_attendance field (name only)
if (transcript.meeting_attendance && Array.isArray(transcript.meeting_attendance)) {
transcript.meeting_attendance.forEach((attendance: any) => {
const name = attendance.name || '';
// Skip if name is actually an email or contains comma-separated emails
if (isEmail(name) || name.includes(',')) {
logger.debug(`Skipping attendance with email/list as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, '')) {
participantsNameOnly.push({ name, email: '' });
}
});
}
// 5. Add organizer email if available and not already included
const organizerEmail = transcript.organizer_email;
if (organizerEmail) {
// Check if organizer email is already in the participants
const existsWithEmail = participantsWithEmails.some(p =>
p.email.toLowerCase() === organizerEmail.toLowerCase()
);
if (!existsWithEmail) {
// Try to find organizer name from speakers/attendance and match with email
let organizerName = '';
// Extract username from organizer email for matching
const emailUsername = organizerEmail.split('@')[0].toLowerCase();
const emailNameVariations = [emailUsername];
// Add common name variations based on email username
if (emailUsername === 'alex') {
emailNameVariations.push('alexander', 'alexandre', 'alex');
}
// Look for organizer in speakers by matching email username to speaker names
if (transcript.speakers && Array.isArray(transcript.speakers)) {
const potentialOrganizerSpeaker = transcript.speakers.find((speaker: any) => {
const name = (speaker.name || '').toLowerCase();
return emailNameVariations.some(variation =>
name.includes(variation) || variation.includes(name)
);
});
if (potentialOrganizerSpeaker) {
organizerName = potentialOrganizerSpeaker.name;
}
}
// Look for organizer in attendance
if (!organizerName && transcript.meeting_attendance && Array.isArray(transcript.meeting_attendance)) {
const potentialOrganizerAttendance = transcript.meeting_attendance.find((attendance: any) => {
const name = (attendance.name || '').toLowerCase();
return emailNameVariations.some(variation =>
name.includes(variation) || variation.includes(name)
);
});
if (potentialOrganizerAttendance) {
organizerName = potentialOrganizerAttendance.name;
}
}
// If we found a name match, add as participant with email
if (organizerName) {
participantsWithEmails.push({ name: organizerName, email: organizerEmail });
// Remove from name-only participants to avoid duplicates
const nameIndex = participantsNameOnly.findIndex(p =>
p.name.toLowerCase().includes(organizerName.toLowerCase()) ||
organizerName.toLowerCase().includes(p.name.toLowerCase())
);
if (nameIndex !== -1) {
participantsNameOnly.splice(nameIndex, 1);
}
} else {
// If no name found, add with generic organizer name
participantsWithEmails.push({ name: 'Meeting Organizer', email: organizerEmail });
}
}
}
// Return participants with emails first, then name-only participants
const allParticipants = [...participantsWithEmails, ...participantsNameOnly];
logger.debug('=== EXTRACTED PARTICIPANTS ===');
logger.debug('With emails:', participantsWithEmails.length, JSON.stringify(participantsWithEmails));
logger.debug('Name only:', participantsNameOnly.length, JSON.stringify(participantsNameOnly));
logger.debug('Total:', allParticipants.length);
return allParticipants;
}
private transformMeetingData(transcript: any, meetingId: string): FirefliesMeetingData {
// Convert date to ISO string - handle both timestamp and ISO string formats
let dateString: string;
if (transcript.date) {
if (typeof transcript.date === 'number') {
// Unix timestamp in milliseconds
dateString = new Date(transcript.date).toISOString();
} else if (typeof transcript.date === 'string') {
// Could be ISO string or timestamp string
const parsed = Number(transcript.date);
if (!isNaN(parsed)) {
// It's a numeric string (timestamp)
dateString = new Date(parsed).toISOString();
} else {
// It's already an ISO string
dateString = transcript.date;
}
} else {
dateString = new Date().toISOString();
}
} else {
dateString = new Date().toISOString();
}
return {
id: transcript.id || meetingId,
title: transcript.title || 'Untitled Meeting',
date: dateString,
duration: transcript.duration || 0,
participants: this.extractAllParticipants(transcript),
organizer_email: transcript.organizer_email,
summary: {
action_items: Array.isArray(transcript.summary?.action_items)
? transcript.summary.action_items
: (typeof transcript.summary?.action_items === 'string'
? [transcript.summary.action_items]
: []),
overview: transcript.summary?.overview || '',
keywords: transcript.summary?.keywords,
topics_discussed: transcript.summary?.topics_discussed,
meeting_type: transcript.summary?.meeting_type,
},
analytics: transcript.sentiments ? {
sentiments: {
positive_pct: transcript.sentiments.positive_pct || 0,
negative_pct: transcript.sentiments.negative_pct || 0,
neutral_pct: transcript.sentiments.neutral_pct || 0,
}
} : undefined,
transcript_url: transcript.transcript_url || `https://app.fireflies.ai/view/${meetingId}`,
recording_url: transcript.video_url || undefined,
summary_status: transcript.summary_status,
};
}
}
@@ -1,227 +0,0 @@
import type { FirefliesMeetingData, MeetingCreateInput } from './types';
export class MeetingFormatter {
static formatNoteBody(meetingData: FirefliesMeetingData): string {
const meetingDate = new Date(meetingData.date);
const formattedDate = meetingDate.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
const durationMinutes = Math.round(meetingData.duration);
let noteBody = `**Date:** ${formattedDate}\n`;
noteBody += `**Duration:** ${durationMinutes} minutes\n`;
if (meetingData.participants.length > 0) {
const participantNames = meetingData.participants.map(p => p.name).join(', ');
noteBody += `**Participants:** ${participantNames}\n`;
}
// Overview section
if (meetingData.summary?.overview) {
noteBody += `\n## Overview\n${meetingData.summary.overview}\n`;
}
// Key topics
if (meetingData.summary?.topics_discussed && Array.isArray(meetingData.summary.topics_discussed) && meetingData.summary.topics_discussed.length > 0) {
noteBody += `\n## Key Topics\n`;
meetingData.summary.topics_discussed.forEach(topic => {
noteBody += `- ${topic}\n`;
});
}
// Action items
if (meetingData.summary?.action_items && Array.isArray(meetingData.summary.action_items) && meetingData.summary.action_items.length > 0) {
noteBody += `\n## Action Items\n`;
meetingData.summary.action_items.forEach(item => {
noteBody += `- ${item}\n`;
});
}
// Insights section
noteBody += `\n## Insights\n`;
if (meetingData.summary?.keywords && Array.isArray(meetingData.summary.keywords) && meetingData.summary.keywords.length > 0) {
noteBody += `**Keywords:** ${meetingData.summary.keywords.join(', ')}\n`;
}
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
noteBody += `**Sentiment:** ${sentiments.positive_pct}% positive, ${sentiments.negative_pct}% negative, ${sentiments.neutral_pct}% neutral\n`;
}
if (meetingData.summary?.meeting_type) {
noteBody += `**Meeting Type:** ${meetingData.summary.meeting_type}\n`;
}
// Resources section
noteBody += `\n## Resources\n`;
noteBody += `[View Full Transcript](${meetingData.transcript_url})\n`;
if (meetingData.recording_url) {
noteBody += `[Watch Recording](${meetingData.recording_url})\n`;
}
return noteBody;
}
static formatMeetingNotes(meetingData: FirefliesMeetingData): string {
const meetingDate = new Date(meetingData.date);
const formattedDate = meetingDate.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
const durationMinutes = Math.round(meetingData.duration);
let meetingNotes = `**Date:** ${formattedDate}\n`;
meetingNotes += `**Duration:** ${durationMinutes} minutes\n`;
if (meetingData.participants.length > 0) {
const participantNames = meetingData.participants.map(p => p.name).join(', ');
meetingNotes += `**Participants:** ${participantNames}\n`;
}
// Overview section
if (meetingData.summary?.overview) {
meetingNotes += `\n## Overview\n${meetingData.summary.overview}\n`;
}
// Key topics
if (meetingData.summary?.topics_discussed && Array.isArray(meetingData.summary.topics_discussed) && meetingData.summary.topics_discussed.length > 0) {
meetingNotes += `\n## Key Topics\n`;
meetingData.summary.topics_discussed.forEach(topic => {
meetingNotes += `- ${topic}\n`;
});
}
// Action items
if (meetingData.summary?.action_items && Array.isArray(meetingData.summary.action_items) && meetingData.summary.action_items.length > 0) {
meetingNotes += `\n## Action Items\n`;
meetingData.summary.action_items.forEach(item => {
meetingNotes += `- ${item}\n`;
});
}
// Insights section
meetingNotes += `\n## Insights\n`;
if (meetingData.summary?.keywords && Array.isArray(meetingData.summary.keywords) && meetingData.summary.keywords.length > 0) {
meetingNotes += `**Keywords:** ${meetingData.summary.keywords.join(', ')}\n`;
}
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
meetingNotes += `**Sentiment:** ${sentiments.positive_pct}% positive, ${sentiments.negative_pct}% negative, ${sentiments.neutral_pct}% neutral\n`;
}
if (meetingData.summary?.meeting_type) {
meetingNotes += `**Meeting Type:** ${meetingData.summary.meeting_type}\n`;
}
// Resources section
meetingNotes += `\n## Resources\n`;
meetingNotes += `[View Full Transcript](${meetingData.transcript_url})\n`;
if (meetingData.recording_url) {
meetingNotes += `[Watch Recording](${meetingData.recording_url})\n`;
}
return meetingNotes;
}
static toMeetingCreateInput(
meetingData: FirefliesMeetingData,
noteId?: string
): MeetingCreateInput {
const durationMinutes = Math.round(meetingData.duration);
// Build input object with only defined values (omit null fields)
const input: MeetingCreateInput = {
name: meetingData.title,
meetingDate: meetingData.date,
duration: durationMinutes,
actionItemsCount: meetingData.summary?.action_items?.length || 0,
firefliesMeetingId: meetingData.id,
};
// Add direct relationship to note if noteId is provided
if (noteId) {
input.noteId = noteId;
}
// Only add optional fields if they have values
if (meetingData.summary?.meeting_type) {
input.meetingType = meetingData.summary.meeting_type;
}
if (meetingData.summary?.keywords && Array.isArray(meetingData.summary.keywords) && meetingData.summary.keywords.length > 0) {
input.keywords = meetingData.summary.keywords.join(', ');
}
if (meetingData.analytics?.sentiments?.positive_pct) {
input.sentimentScore = meetingData.analytics.sentiments.positive_pct / 100;
input.positivePercent = meetingData.analytics.sentiments.positive_pct;
}
if (meetingData.analytics?.sentiments?.negative_pct) {
input.negativePercent = meetingData.analytics.sentiments.negative_pct;
}
// Only add URLs if they are valid (not empty strings)
if (meetingData.transcript_url && meetingData.transcript_url.trim()) {
input.transcriptUrl = {
primaryLinkUrl: meetingData.transcript_url,
primaryLinkLabel: 'View Transcript'
};
}
if (meetingData.recording_url && meetingData.recording_url.trim()) {
input.recordingUrl = {
primaryLinkUrl: meetingData.recording_url,
primaryLinkLabel: 'Watch Recording'
};
}
if (meetingData.organizer_email) {
input.organizerEmail = meetingData.organizer_email;
}
// Set success status and timestamps
input.importStatus = 'SUCCESS';
input.lastImportAttempt = new Date().toISOString();
input.importAttempts = 1;
return input;
}
static toFailedMeetingCreateInput(
meetingId: string,
title: string,
error: string,
attempts: number = 1
): MeetingCreateInput {
const currentDate = new Date().toISOString();
return {
name: title || `Failed Meeting Import - ${meetingId}`,
meetingDate: currentDate,
duration: 0,
actionItemsCount: 0,
firefliesMeetingId: meetingId,
importStatus: 'FAILED',
importError: error,
lastImportAttempt: currentDate,
importAttempts: attempts,
};
}
}
@@ -1,4 +1,5 @@
export { config, main } from './receive-fireflies-notes';
// Serverless function entry point - re-exports from src/lib
export { config, main } from '../../../src';
export type {
FirefliesMeetingData,
FirefliesParticipant,
@@ -6,5 +7,5 @@ export type {
ProcessResult,
SummaryFetchConfig,
SummaryStrategy
} from './types';
} from '../../../src';
@@ -1,95 +0,0 @@
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
export interface LoggerConfig {
logLevel: LogLevel;
isTestEnvironment: boolean;
}
const LOG_LEVELS: Record<LogLevel, number> = {
debug: 0,
info: 1,
warn: 2,
error: 3,
silent: 4,
};
/**
* App-level Fireflies application logger with configurable log levels.
*/
export class AppLogger {
private config: LoggerConfig;
private context: string;
constructor(context: string) {
this.context = context;
this.config = {
logLevel: this.parseLogLevel(process.env.LOG_LEVEL || 'error'),
isTestEnvironment: process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined,
};
}
private parseLogLevel(level: string): LogLevel {
const normalizedLevel = level.toLowerCase() as LogLevel;
return Object.keys(LOG_LEVELS).includes(normalizedLevel) ? normalizedLevel : 'error';
}
private shouldLog(level: LogLevel): boolean {
return LOG_LEVELS[level] >= LOG_LEVELS[this.config.logLevel];
}
/**
* Log debug information (LOG_LEVEL=debug)
*/
debug(message: string, ...args: any[]): void {
if (this.shouldLog('debug')) {
// eslint-disable-next-line no-console
console.log(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log informational messages (LOG_LEVEL=info or lower)
*/
info(message: string, ...args: any[]): void {
if (this.shouldLog('info')) {
// eslint-disable-next-line no-console
console.log(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log warnings (LOG_LEVEL=warn or lower)
*/
warn(message: string, ...args: any[]): void {
if (this.shouldLog('warn')) {
// eslint-disable-next-line no-console
console.warn(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log errors (LOG_LEVEL=error or lower)
*/
error(message: string, ...args: any[]): void {
if (this.shouldLog('error')) {
// eslint-disable-next-line no-console
console.error(`[${this.context}] ${message}`, ...args);
}
}
/**
* Log critical errors that should ALWAYS be visible regardless of log level
* Use sparingly - only for fatal errors, security issues, or data corruption
*/
critical(message: string, ...args: any[]): void {
// eslint-disable-next-line no-console
console.error(`[${this.context}] CRITICAL: ${message}`, ...args);
}
}
/**
* Factory function to create loggers with automatic context detection
*/
export const createLogger = (context: string): AppLogger => {
return new AppLogger(context);
};
@@ -1,28 +0,0 @@
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
import type { ProcessResult } from './types';
import { WebhookHandler } from './webhook-handler';
export const main = async (
params: unknown,
headers?: Record<string, string>
): Promise<ProcessResult> => {
const handler = new WebhookHandler();
return handler.handle(params, headers);
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: '2d3ea303-667c-4bbe-9e3d-db6ffb9d6c74',
name: 'receive-fireflies-notes',
description:
'Receives Fireflies webhooks, fetches meeting summaries, and stores them in Twenty.',
timeoutSeconds: 30,
triggers: [
{
universalIdentifier: 'a2117dc1-7674-4c7e-9d70-9feb9820e9e8',
type: 'route',
path: '/webhook/fireflies',
httpMethod: 'POST',
isAuthRequired: true,
},
],
};
@@ -1,130 +0,0 @@
// Fireflies API Types
export type FirefliesParticipant = {
email: string;
name: string;
};
export type FirefliesWebhookPayload = {
meetingId: string;
eventType: string;
clientReferenceId?: string;
};
export type FirefliesMeetingData = {
id: string;
title: string;
date: string;
duration: number;
participants: FirefliesParticipant[];
organizer_email?: string;
summary: {
action_items: string[];
keywords?: string[];
overview: string;
gist?: string;
topics_discussed?: string[];
meeting_type?: string;
bullet_gist?: string;
};
analytics?: {
sentiments?: {
positive_pct: number;
negative_pct: number;
neutral_pct: number;
};
};
transcript_url: string;
recording_url?: string;
summary_status?: string;
};
// Configuration Types
export type SummaryStrategy = 'immediate_only' | 'immediate_with_retry' | 'delayed_polling' | 'basic_only';
export type SummaryFetchConfig = {
strategy: SummaryStrategy;
retryAttempts: number;
retryDelay: number;
pollInterval: number;
maxPolls: number;
};
export type WebhookConfig = {
secret: string;
apiUrl: string;
};
// Processing Result Types
export type ProcessResult = {
success: boolean;
meetingId?: string;
noteIds?: string[];
newContacts?: string[];
errors?: string[];
debug?: string[];
summaryReady?: boolean;
summaryPending?: boolean;
enhancementScheduled?: boolean;
actionItemsCount?: number;
sentimentScore?: number;
meetingType?: string;
keyTopics?: string[];
};
// Twenty CRM Types
export type GraphQLResponse<T> = {
data: T;
errors?: Array<{
message?: string;
extensions?: { code?: string }
}>;
};
export type IdNode = { id: string };
export type FindMeetingResponse = {
meetings: { edges: Array<{ node: IdNode }> };
};
export type FindPeopleResponse = {
people: { edges: Array<{ node: { id: string; emails: { primaryEmail: string } } }> };
};
export type CreatePersonResponse = {
createPerson: { id: string }
};
export type CreateNoteResponse = {
createNote: { id: string }
};
export type CreateMeetingResponse = {
createMeeting: { id: string }
};
export type Contact = {
id: string;
email: string;
};
export type MeetingCreateInput = {
name: string;
noteId?: string | null; // This is the relation field
meetingDate: string;
duration: number;
meetingType?: string | null;
keywords?: string | null;
sentimentScore?: number | null;
positivePercent?: number | null;
negativePercent?: number | null;
actionItemsCount: number;
transcriptUrl?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
recordingUrl?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
firefliesMeetingId: string;
organizerEmail?: string | null;
importStatus?: 'SUCCESS' | 'FAILED' | 'PENDING' | 'RETRYING' | null;
importError?: string | null;
lastImportAttempt?: string | null;
importAttempts?: number | null;
};
@@ -1,30 +0,0 @@
export const toBoolean = (value: string | undefined, defaultValue: boolean): boolean => {
if (value === undefined) return defaultValue;
const normalized = value.trim().toLowerCase();
return normalized === 'true' || normalized === '1' || normalized === 'yes';
};
import type { SummaryFetchConfig, SummaryStrategy } from './types';
export const getApiUrl = (): string => {
return process.env.SERVER_URL || 'http://localhost:3000';
};
export const getSummaryFetchConfig = (): SummaryFetchConfig => {
const strategy = (process.env.FIREFLIES_SUMMARY_STRATEGY as SummaryStrategy) || 'immediate_with_retry';
// Ultra-conservative defaults to respect 50 requests/day API limit
// With 3 attempts at 15-minute intervals, max 3 API calls per webhook (45 minutes total)
return {
strategy,
retryAttempts: parseInt(process.env.FIREFLIES_RETRY_ATTEMPTS || '3', 10),
retryDelay: parseInt(process.env.FIREFLIES_RETRY_DELAY || '120000', 10), // 2 minutes
pollInterval: parseInt(process.env.FIREFLIES_POLL_INTERVAL || '120000', 10), // 2 minutes
maxPolls: parseInt(process.env.FIREFLIES_MAX_POLLS || '3', 10),
};
};
export const shouldAutoCreateContacts = (): boolean => {
return toBoolean(process.env.AUTO_CREATE_CONTACTS, true);
};
@@ -1,345 +0,0 @@
import { FirefliesApiClient } from './fireflies-api-client';
import { MeetingFormatter } from './formatters';
import { createLogger } from './logger';
import { TwentyCrmService } from './twenty-crm-service';
import type { FirefliesWebhookPayload, ProcessResult } from './types';
import { getApiUrl, getSummaryFetchConfig, shouldAutoCreateContacts } from './utils';
import {
getWebhookSecretFingerprint,
isValidFirefliesPayload,
verifyWebhookSignature
} from './webhook-validator';
declare const process: { env: Record<string, string | undefined> };
const logger = createLogger('fireflies');
export class WebhookHandler {
private debug: string[] = [];
private isTestEnvironment: boolean;
constructor() {
this.isTestEnvironment = process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined;
}
async handle(params: unknown, headers?: Record<string, string>): Promise<ProcessResult> {
const result: ProcessResult = {
success: false,
noteIds: [],
newContacts: [],
errors: [],
};
try {
logger.debug('invoked');
logger.debug(`apiUrl=${getApiUrl()}`);
// 0) Validate environment configuration
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
const twentyApiKey = process.env.TWENTY_API_KEY || '';
if (!firefliesApiKey) {
logger.critical('FIREFLIES_API_KEY not configured - this is a critical configuration error');
throw new Error('FIREFLIES_API_KEY environment variable is required');
}
if (!twentyApiKey) {
logger.critical('TWENTY_API_KEY not configured - this is a critical configuration error');
throw new Error('TWENTY_API_KEY environment variable is required');
}
// 1) Parse and validate webhook payload and extract headers if wrapped together
const { payload, extractedHeaders } = this.parsePayload(params);
const finalHeaders = extractedHeaders || headers;
logger.debug(`payload meetingId=${payload.meetingId} eventType="${payload.eventType}"`);
// 2) Verify webhook signature
const webhookSecret = process.env.FIREFLIES_WEBHOOK_SECRET || '';
const secretFingerprint = getWebhookSecretFingerprint(webhookSecret);
logger.debug(`webhook secret fingerprint=${secretFingerprint}`);
this.verifySignature(payload, finalHeaders, webhookSecret);
logger.debug('signature verification: ok');
// 3) Fetch meeting data from Fireflies
const summaryConfig = getSummaryFetchConfig();
logger.debug(`summary strategy: ${summaryConfig.strategy} (retryAttempts=${summaryConfig.retryAttempts}, retryDelay=${summaryConfig.retryDelay}ms)`);
logger.debug(`fetching meeting data from Fireflies API`);
const firefliesClient = new FirefliesApiClient(firefliesApiKey);
const { data: meetingData, summaryReady } = await firefliesClient.fetchMeetingDataWithRetry(
payload.meetingId,
summaryConfig
);
logger.debug(`meeting data fetched: title="${meetingData.title}" summaryReady=${summaryReady}`);
result.summaryReady = summaryReady;
result.summaryPending = !summaryReady;
// Extract business intelligence
if (summaryReady) {
result.actionItemsCount = meetingData.summary.action_items.length;
result.keyTopics = meetingData.summary.topics_discussed;
result.meetingType = meetingData.summary.meeting_type;
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
result.sentimentScore = sentiments.positive_pct / 100;
}
}
// 4) Check for duplicate meetings
const twentyService = new TwentyCrmService(
twentyApiKey,
getApiUrl()
);
const existingMeeting = await twentyService.findExistingMeeting(meetingData.title);
if (existingMeeting) {
logger.debug(`meeting already exists id=${existingMeeting.id}`);
result.success = true;
result.meetingId = existingMeeting.id;
result.debug = this.debug;
return result;
}
logger.debug('no existing meeting found, proceeding');
// 5) Match participants to existing contacts
logger.debug(`total participants from API: ${meetingData.participants.length}`);
meetingData.participants.forEach((p, idx) => {
logger.debug(`participant ${idx + 1}: name="${p.name}" email="${p.email || 'none'}"`);
});
const { matchedContacts, unmatchedParticipants } = await twentyService.matchParticipantsToContacts(
meetingData.participants
);
logger.debug(`matched=${matchedContacts.length} unmatched=${unmatchedParticipants.length}`);
unmatchedParticipants.forEach((p, idx) => {
logger.debug(`unmatched ${idx + 1}: name="${p.name}" email="${p.email || 'none'}"`);
});
// 6) Optionally create contacts
const autoCreate = shouldAutoCreateContacts();
const newContactIds = autoCreate
? await twentyService.createContactsForUnmatched(unmatchedParticipants)
: [];
result.newContacts = newContactIds;
logger.debug(`autoCreate=${autoCreate} createdContacts=${newContactIds.length}`);
// 7) Create note first (so we can link to it from the meeting)
const allContactIds = [...matchedContacts.map(({ id }) => id), ...newContactIds];
const noteBody = MeetingFormatter.formatNoteBody(meetingData);
const noteId = await twentyService.createNoteOnly(
`Meeting: ${meetingData.title}`,
noteBody
);
result.noteIds = [noteId];
logger.debug(`created note id=${noteId}`);
// 8) Create meeting with direct relationship to the note
const meetingInput = MeetingFormatter.toMeetingCreateInput(meetingData, noteId);
logger.debug(`meeting duration: ${meetingData.duration} min (raw from API) → ${meetingInput.duration} min (rounded)`);
result.meetingId = await twentyService.createMeeting(meetingInput);
logger.debug(`created meeting id=${result.meetingId} with noteId=${noteId}`);
// 9) Link note to participants (Meeting link is handled via the relation field)
await this.linkNoteToParticipants(
twentyService,
noteId,
allContactIds
);
logger.debug(`linked note to ${allContactIds.length} participants`);
result.success = true;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
logger.error(`error: ${message}`);
result.errors?.push(message);
// Try to create a failed meeting record for tracking
await this.createFailedMeetingRecord(params, message);
}
result.debug = this.debug;
return result;
}
private parsePayload(params: unknown): { payload: FirefliesWebhookPayload; extractedHeaders?: Record<string, string> } {
let normalizedParams = params;
let extractedHeaders: Record<string, string> | undefined;
// Handle string-encoded params
if (typeof normalizedParams === 'string') {
logger.debug(`received params as string length=${normalizedParams.length}`);
try {
const parsed = JSON.parse(normalizedParams);
normalizedParams = parsed;
if (parsed && typeof parsed === 'object') {
const parsedKeys = Object.keys(parsed as Record<string, unknown>);
logger.debug(`parsed params keys: ${parsedKeys.join(',') || 'none'}`);
}
} catch (parseError) {
logger.error(`error parsing string params: ${String(parseError)}`);
throw new Error('Invalid or missing webhook payload');
}
}
// Handle wrapped payloads and extract headers if present
let payload: FirefliesWebhookPayload | undefined;
if (isValidFirefliesPayload(normalizedParams)) {
payload = normalizedParams as FirefliesWebhookPayload;
} else if (normalizedParams && typeof normalizedParams === 'object') {
const wrapper = normalizedParams as Record<string, unknown>;
// Extract headers if present in wrapper
if (wrapper.headers && typeof wrapper.headers === 'object' && !Array.isArray(wrapper.headers)) {
extractedHeaders = wrapper.headers as Record<string, string>;
const headerKeys = Object.keys(extractedHeaders);
logger.debug(`extracted headers from wrapper: ${headerKeys.join(',')}`);
}
const wrapperKeys = ['params', 'payload', 'body', 'data', 'event'];
for (const key of wrapperKeys) {
const candidate = wrapper[key];
if (isValidFirefliesPayload(candidate)) {
logger.debug(`detected payload under wrapper key "${key}"`);
payload = candidate as FirefliesWebhookPayload;
break;
}
}
}
if (!payload) {
logger.error('error: Invalid or missing webhook payload');
throw new Error('Invalid or missing webhook payload');
}
// Log payload keys for debugging
const payloadRecord = payload as Record<string, unknown>;
const payloadKeys = Object.keys(payloadRecord);
if (payloadKeys.length > 0) {
logger.debug(`payload keys: ${payloadKeys.join(',')}`);
}
return { payload, extractedHeaders };
}
private verifySignature(
payload: FirefliesWebhookPayload,
headers: Record<string, string> | undefined,
webhookSecret: string
): void {
// Extract headers
const normalizedHeaders = headers || {};
const headerKeys = Object.keys(normalizedHeaders);
if (headerKeys.length > 0) {
logger.debug(`header keys: ${headerKeys.join(',')}`);
}
const headerSignature = Object.entries(normalizedHeaders).find(
([key]) => key.toLowerCase() === 'x-hub-signature',
)?.[1];
const payloadRecord = payload as Record<string, unknown>;
const payloadSignature =
typeof payloadRecord['x-hub-signature'] === 'string'
? (payloadRecord['x-hub-signature'] as string)
: undefined;
if (payloadSignature) {
logger.debug('found signature inside payload');
}
const signature =
(typeof headerSignature === 'string' ? headerSignature : undefined) || payloadSignature;
const body = typeof normalizedHeaders['body'] === 'string'
? normalizedHeaders['body']
: JSON.stringify(payloadRecord);
const signatureCheck = verifyWebhookSignature(body, signature, webhookSecret);
if (!signatureCheck.isValid) {
logger.debug(
`signature check failed. headerPresent=${Boolean(
headerSignature,
)} payloadSignaturePresent=${Boolean(payloadSignature)}`,
);
if (signature) {
logger.debug(`provided signature=${signature}`);
} else {
logger.debug('provided signature=undefined');
}
logger.debug(
`computed signature=${signatureCheck.computedSignature ?? 'unavailable'}`,
);
logger.critical('Invalid webhook signature - potential security threat detected in production');
throw new Error('Invalid webhook signature');
}
}
private async linkNoteToParticipants(
twentyService: TwentyCrmService,
noteId: string,
contactIds: string[]
): Promise<void> {
// Create Note-Person links for each participant
for (const contactId of contactIds) {
try {
await twentyService.createNoteTarget(noteId, contactId);
logger.debug(`linked note ${noteId} to person ${contactId}`);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
logger.error(`failed to link note to person ${contactId}: ${message}`);
// Continue with other participants
}
}
}
private async createFailedMeetingRecord(params: unknown, error: string): Promise<void> {
try {
const twentyApiKey = process.env.TWENTY_API_KEY || '';
if (!twentyApiKey) {
logger.debug('Cannot create failed meeting record: TWENTY_API_KEY not configured');
return;
}
// Try to extract meeting ID and title from the params
let meetingId = 'unknown';
let meetingTitle = 'Unknown Meeting';
const { payload } = this.parsePayload(params);
if (payload?.meetingId) {
meetingId = payload.meetingId;
// Try to get meeting title from Fireflies API if possible
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
if (firefliesApiKey) {
try {
const firefliesClient = new FirefliesApiClient(firefliesApiKey);
const meetingData = await firefliesClient.fetchMeetingData(meetingId);
meetingTitle = meetingData.title || meetingTitle;
} catch (fetchError) {
logger.debug(`Could not fetch meeting title: ${fetchError instanceof Error ? fetchError.message : 'Unknown error'}`);
}
}
}
const twentyService = new TwentyCrmService(twentyApiKey, getApiUrl());
const failedMeetingData = MeetingFormatter.toFailedMeetingCreateInput(
meetingId,
meetingTitle,
error
);
const failedMeetingId = await twentyService.createFailedMeeting(failedMeetingData);
logger.debug(`Created failed meeting record: ${failedMeetingId}`);
} catch (recordError) {
// Don't throw here - we don't want to break the original error handling
logger.error(`Failed to create failed meeting record: ${recordError instanceof Error ? recordError.message : 'Unknown error'}`);
}
}
}
@@ -4,7 +4,7 @@ import {
main,
type FirefliesMeetingData,
type FirefliesWebhookPayload,
} from '../actions/receive-fireflies-notes';
} from '../';
// Helper to generate HMAC signature
const generateHMACSignature = (body: string, secret: string): string => {
@@ -39,10 +39,12 @@ const mockFirefliesApiResponseWithSummary = {
meeting_type: 'Sales Call',
bullet_gist: '• Demonstrated core product features\n• Discussed enterprise pricing\n• Addressed integration questions',
},
sentiments: { // Note: Raw API has sentiments at top level, not in analytics
positive_pct: 75,
negative_pct: 10,
neutral_pct: 15,
analytics: {
sentiments: {
positive_pct: 75,
negative_pct: 10,
neutral_pct: 15,
},
},
transcript_url: 'https://app.fireflies.ai/transcript/test-001',
video_url: 'https://app.fireflies.ai/recording/test-001',
@@ -81,7 +83,7 @@ const mockMeetingWithFullSummary: FirefliesMeetingData = {
},
},
transcript_url: 'https://app.fireflies.ai/transcript/test-001',
recording_url: 'https://app.fireflies.ai/recording/test-001',
video_url: 'https://app.fireflies.ai/recording/test-001',
summary_status: 'completed',
};
@@ -404,7 +406,11 @@ describe('Fireflies Webhook Integration v2', () => {
expect(result.success).toBe(true);
expect(result.summaryReady).toBe(true);
expect(result.actionItemsCount).toBe(3);
expect(result.sentimentScore).toBeCloseTo(0.75, 2); // Use toBeCloseTo for floating point comparison
expect(result.sentimentAnalysis).toEqual({
positive_pct: 75,
negative_pct: 10,
neutral_pct: 15,
});
expect(result.meetingType).toBe('Sales Call');
expect(result.keyTopics).toEqual(['product features', 'pricing discussion', 'integration capabilities', 'support options']);
});
@@ -565,7 +571,7 @@ describe('Fireflies Webhook Integration v2', () => {
const createNoteMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string, options?: any) => {
global.fetch = jest.fn().mockImplementation((url: string, options?: RequestInit) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
@@ -576,9 +582,9 @@ describe('Fireflies Webhook Integration v2', () => {
}
// Twenty API
const body = options?.body ? JSON.parse(options.body) : {};
if (body.query?.includes('createNote')) {
createNoteMock(body.variables);
const requestBody = options?.body ? JSON.parse(options.body as string) : {};
if (requestBody.query?.includes('createNote')) {
createNoteMock(requestBody.variables);
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
@@ -610,7 +616,7 @@ describe('Fireflies Webhook Integration v2', () => {
expect(noteData.data.bodyV2.markdown).toContain('## Overview'); // Markdown header, not bold
expect(noteData.data.bodyV2.markdown).toContain('## Action Items'); // Markdown header, not bold
expect(noteData.data.bodyV2.markdown).toContain('**Sentiment:**'); // This is bold
expect(noteData.data.bodyV2.markdown).toContain('[View Full Transcript]');
expect(noteData.data.bodyV2.markdown).toContain('View Full Transcript on Fireflies');
});
it('should create meeting records for multi-party meetings', async () => {
@@ -624,7 +630,7 @@ describe('Fireflies Webhook Integration v2', () => {
const createMeetingMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string, options?: any) => {
global.fetch = jest.fn().mockImplementation((url: string, options?: RequestInit) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
@@ -635,9 +641,9 @@ describe('Fireflies Webhook Integration v2', () => {
}
// Twenty API
const body = options?.body ? JSON.parse(options.body) : {};
if (body.query?.includes('createMeeting')) {
createMeetingMock(body.variables);
const requestBody = options?.body ? JSON.parse(options.body as string) : {};
if (requestBody.query?.includes('createMeeting')) {
createMeetingMock(requestBody.variables);
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
@@ -645,7 +651,7 @@ describe('Fireflies Webhook Integration v2', () => {
}),
});
}
if (body.query?.includes('createNote')) {
if (requestBody.query?.includes('createNote')) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
@@ -694,7 +700,7 @@ describe('Fireflies Webhook Integration v2', () => {
});
it('should handle missing payload gracefully', async () => {
const result = await main(null as any, {});
const result = await main(null as unknown, {});
expect(result.success).toBe(false);
expect(result.errors).toBeDefined();
@@ -703,10 +709,10 @@ describe('Fireflies Webhook Integration v2', () => {
it('should handle invalid payload structure', async () => {
const invalidPayload = { invalid: 'data' };
const result = await main(invalidPayload as any, {});
const result = await main(invalidPayload as unknown, {});
expect(result.success).toBe(false);
expect(result.errors).toBeDefined();
expect(result.success).toBe(false);
expect(result.errors).toBeDefined();
});
});
});
@@ -0,0 +1,84 @@
import { HistoricalImporter } from '../historical-importer';
import type { FirefliesMeetingData, SummaryFetchConfig } from '../types';
const summaryConfig: SummaryFetchConfig = {
strategy: 'immediate_with_retry',
retryAttempts: 1,
retryDelay: 0,
pollInterval: 0,
maxPolls: 0,
};
const sampleMeeting: FirefliesMeetingData = {
id: 'm-1',
title: 'Sample',
date: new Date().toISOString(),
duration: 30,
participants: [],
summary: { action_items: [], overview: '' },
transcript_url: 'https://example.com',
};
describe('HistoricalImporter', () => {
const buildImporter = () => {
const firefliesClient = {
listTranscripts: jest.fn(),
fetchMeetingDataWithRetry: jest.fn(),
} as unknown as jest.Mocked<any>;
const twentyService = {
findMeetingByFirefliesId: jest.fn(),
matchParticipantsToContacts: jest.fn(),
createContactsForUnmatched: jest.fn(),
createNoteOnly: jest.fn(),
createMeeting: jest.fn(),
createNoteTarget: jest.fn(),
} as unknown as jest.Mocked<any>;
return { firefliesClient, twentyService };
};
it('skips meetings that already exist by firefliesMeetingId', async () => {
const { firefliesClient, twentyService } = buildImporter();
firefliesClient.listTranscripts.mockResolvedValue([{ id: 'existing' }]);
twentyService.findMeetingByFirefliesId.mockResolvedValue({ id: 'twenty-id' });
const importer = new HistoricalImporter(firefliesClient, twentyService);
const result = await importer.run(
{},
{ dryRun: false, autoCreateContacts: true, summaryConfig, plan: 'free' },
);
expect(result.skippedExisting).toBe(1);
expect(result.imported).toBe(0);
expect(twentyService.createMeeting).not.toHaveBeenCalled();
expect(result.statuses[0].status).toBe('skipped_existing');
});
it('supports dry-run without writing to Twenty', async () => {
const { firefliesClient, twentyService } = buildImporter();
firefliesClient.listTranscripts.mockResolvedValue([{ id: 'm-2' }]);
firefliesClient.fetchMeetingDataWithRetry.mockResolvedValue({
data: sampleMeeting,
summaryReady: false,
});
twentyService.findMeetingByFirefliesId.mockResolvedValue(undefined);
const importer = new HistoricalImporter(firefliesClient, twentyService);
const result = await importer.run(
{},
{ dryRun: true, autoCreateContacts: false, summaryConfig, plan: 'free' },
);
expect(result.imported).toBe(1);
expect(result.summaryPending).toBe(1);
expect(twentyService.createMeeting).not.toHaveBeenCalled();
expect(twentyService.createNoteOnly).not.toHaveBeenCalled();
expect(result.statuses).toHaveLength(1);
expect(result.statuses[0].status).toBe('pending_summary');
});
});
@@ -9,6 +9,7 @@ process.env.AUTO_CREATE_CONTACTS = 'true';
process.env.SERVER_URL = 'http://localhost:3000';
process.env.TWENTY_API_KEY = 'test-api-key';
process.env.LOG_LEVEL = 'silent';
process.env.CAPTURE_LOGS = 'false';
// Reset mocks before each test
beforeEach(() => {
@@ -0,0 +1,40 @@
import { WebhookHandler } from '../webhook-handler';
describe('WebhookHandler log capture', () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = {
...originalEnv,
FIREFLIES_WEBHOOK_SECRET: 'testsecret',
FIREFLIES_API_KEY: '',
TWENTY_API_KEY: '',
CAPTURE_LOGS: 'false',
LOG_LEVEL: 'silent',
};
});
afterEach(() => {
process.env = originalEnv;
});
it('includes debug logs in response when CAPTURE_LOGS is true', async () => {
process.env.CAPTURE_LOGS = 'true';
const handler = new WebhookHandler();
const result = await handler.handle(null);
expect(result.success).toBe(false);
expect(Array.isArray(result.debug)).toBe(true);
});
it('omits debug logs when CAPTURE_LOGS is false', async () => {
process.env.CAPTURE_LOGS = 'false';
const handler = new WebhookHandler();
const result = await handler.handle(null);
expect(result.debug).toBeUndefined();
});
});
@@ -1,11 +0,0 @@
export {
config,
main,
type FirefliesMeetingData,
type FirefliesParticipant,
type FirefliesWebhookPayload,
type ProcessResult,
type SummaryFetchConfig,
type SummaryStrategy
} from '../../serverlessFunctions/receive-fireflies-notes/src/index';
@@ -0,0 +1,823 @@
import { createLogger } from './logger';
import {
FIREFLIES_PLANS,
type FirefliesMeetingData,
type FirefliesParticipant,
type FirefliesPlan,
type FirefliesTranscriptListItem,
type FirefliesTranscriptListOptions,
type SummaryFetchConfig
} from './types';
const logger = createLogger('fireflies-api');
export class FirefliesApiClient {
private apiKey: string;
constructor(apiKey: string) {
if (!apiKey) {
logger.critical('FIREFLIES_API_KEY is required but not provided - this is a critical configuration error');
throw new Error('FIREFLIES_API_KEY is required');
}
this.apiKey = apiKey;
}
async listTranscripts(options: FirefliesTranscriptListOptions = {}): Promise<FirefliesTranscriptListItem[]> {
const {
organizers,
participants,
hostEmail,
participantEmail,
userId,
channelId,
mine,
fromDate,
toDate,
pageSize = 50,
maxRecords = 500,
} = options;
const sanitizedOrganizers = organizers?.filter(Boolean);
const sanitizedParticipants = participants?.filter(Boolean);
const transcripts: FirefliesTranscriptListItem[] = [];
let skip = options.skip ?? 0;
const limit = options.limit ?? pageSize;
const baseQuery = `
query Transcripts(
$limit: Int
$skip: Int
$hostEmail: String
$participantEmail: String
$organizers: [String!]
$participants: [String!]
$userId: String
$channelId: String
$mine: Boolean
$date: Float
) {
transcripts(
limit: $limit
skip: $skip
host_email: $hostEmail
participant_email: $participantEmail
organizers: $organizers
participants: $participants
user_id: $userId
channel_id: $channelId
mine: $mine
date: $date
) {
id
title
date
duration
organizer_email
participants
transcript_url
meeting_link
meeting_info { summary_status }
}
}
`;
while (transcripts.length < maxRecords) {
const pageVariables = {
limit,
skip,
hostEmail,
participantEmail,
organizers: sanitizedOrganizers,
participants: sanitizedParticipants,
userId,
channelId,
mine,
date: fromDate,
};
const page = await this.executeTranscriptListQuery(baseQuery, pageVariables);
const normalized = page
.map((item) => {
const normalizedDate = this.normalizeDate(item.date);
return {
id: (item.id as string) || '',
title: (item.title as string) || 'Untitled Meeting',
date: normalizedDate,
duration: (item.duration as number) || 0,
organizer_email: item.organizer_email as string | undefined,
participants: Array.isArray(item.participants)
? (item.participants as string[])
: undefined,
transcript_url: item.transcript_url as string | undefined,
meeting_link: item.meeting_link as string | undefined,
summary_status: (item.meeting_info as { summary_status?: string } | undefined)?.summary_status,
};
})
.filter((item) => {
if (toDate && item.date) {
const itemTime = Date.parse(item.date);
if (!Number.isNaN(itemTime) && itemTime > toDate) {
return false;
}
}
return true;
});
transcripts.push(...normalized);
if (page.length < limit) {
break;
}
skip += limit;
}
if (transcripts.length > maxRecords) {
return transcripts.slice(0, maxRecords);
}
return transcripts;
}
async fetchMeetingData(
meetingId: string,
options?: { timeout?: number; plan?: FirefliesPlan }
): Promise<FirefliesMeetingData> {
const plan = options?.plan ?? FIREFLIES_PLANS.FREE;
const isPremiumPlan =
plan === FIREFLIES_PLANS.BUSINESS || plan === FIREFLIES_PLANS.ENTERPRISE;
// Minimal query for free plans - only basic fields available on all plans
// Note: audio_url requires Pro+, video_url requires Business+
const freeQuery = `
query GetTranscriptMinimal($transcriptId: String!) {
transcript(id: $transcriptId) {
id
title
date
duration
participants
organizer_email
transcript_url
meeting_link
}
}
`;
// Standard query for pro plans - adds speakers, summary, sentences, and audio_url (Pro+)
// Note: video_url requires Business+
const proQuery = `
query GetTranscriptBasic($transcriptId: String!) {
transcript(id: $transcriptId) {
id
title
date
duration
participants
organizer_email
speakers {
name
}
sentences {
index
speaker_name
text
start_time
end_time
}
summary {
overview
keywords
action_items
notes
gist
bullet_gist
short_summary
short_overview
outline
shorthand_bullet
}
meeting_info {
summary_status
}
transcript_url
audio_url
meeting_link
}
}
`;
// Full query for business/enterprise - includes all fields
const businessQuery = `
query GetTranscriptFull($transcriptId: String!) {
transcript(id: $transcriptId) {
id
title
date
duration
participants
organizer_email
analytics {
sentiments {
positive_pct
negative_pct
neutral_pct
}
categories {
questions
tasks
metrics
date_times
}
speakers {
speaker_id
name
duration
word_count
longest_monologue
filler_words
questions
words_per_minute
}
}
meeting_attendees {
displayName
email
phoneNumber
name
location
}
meeting_attendance {
name
join_time
leave_time
}
speakers {
name
}
sentences {
index
speaker_name
text
start_time
end_time
ai_filters {
task
question
sentiment
}
}
summary {
action_items
overview
keywords
notes
gist
bullet_gist
short_summary
short_overview
outline
shorthand_bullet
topics_discussed
meeting_type
transcript_chapters
}
meeting_info {
summary_status
}
transcript_url
audio_url
video_url
meeting_link
}
}
`;
// Select query based on plan
const queryToUse = isPremiumPlan ? businessQuery :
(plan === FIREFLIES_PLANS.PRO ? proQuery : freeQuery);
const planFeatures = {
[FIREFLIES_PLANS.FREE]: 'basic fields only (no summary, no audio/video)',
[FIREFLIES_PLANS.PRO]: 'summary, speakers, audio_url',
[FIREFLIES_PLANS.BUSINESS]: 'full access including analytics, video_url',
[FIREFLIES_PLANS.ENTERPRISE]: 'full access including analytics, video_url',
};
logger.debug(`using ${plan} plan query (${planFeatures[plan]})`);
try {
return await this.executeTranscriptQuery({
meetingId,
query: queryToUse,
timeout: options?.timeout,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
// Detect plan-specific errors
const requiresBusiness = message.toLowerCase().includes('business or higher');
const requiresPro = message.toLowerCase().includes('pro or higher');
const planError = requiresBusiness || requiresPro ||
message.toLowerCase().includes('higher plan') ||
message.includes('Cannot query field');
// Fallback cascade: business -> pro -> free
if (planError) {
if (isPremiumPlan) {
logger.warn(`Plan limitation detected (configured: ${plan}), falling back to pro query`);
try {
return await this.executeTranscriptQuery({
meetingId,
query: proQuery,
timeout: options?.timeout,
});
} catch (proError) {
const proMessage = proError instanceof Error ? proError.message : String(proError);
if (proMessage.toLowerCase().includes('plan') || proMessage.includes('Cannot query field')) {
logger.warn('Pro query also failed, falling back to minimal free query');
return this.executeTranscriptQuery({
meetingId,
query: freeQuery,
timeout: options?.timeout,
});
}
throw proError;
}
} else if (plan === FIREFLIES_PLANS.PRO) {
logger.warn(`Pro plan query failed (${requiresBusiness ? 'requires Business+' : 'unknown restriction'}), falling back to free query`);
return this.executeTranscriptQuery({
meetingId,
query: freeQuery,
timeout: options?.timeout,
});
} else {
// Already using free query - some field might still be restricted
logger.error(
'Fireflies API rejected the minimal free query. This may indicate: ' +
'1) The transcript ID is invalid, or ' +
'2) Your API key does not have access to this transcript, or ' +
'3) An unexpected API restriction : open an issue'
);
}
}
throw error;
}
}
async fetchMeetingDataWithRetry(
meetingId: string,
config: SummaryFetchConfig,
plan: FirefliesPlan = FIREFLIES_PLANS.FREE
): Promise<{ data: FirefliesMeetingData; summaryReady: boolean }> {
// immediate_only: single attempt, no retries
if (config.strategy === 'immediate_only') {
logger.debug(`fetching meeting ${meetingId} (strategy: immediate_only)`);
const meetingData = await this.fetchMeetingData(meetingId, { timeout: 10000, plan });
const ready = this.isSummaryReady(meetingData);
logger.debug(`summary ready: ${ready}`);
return { data: meetingData, summaryReady: ready };
}
// immediate_with_retry: retry with linear backoff
logger.debug(`fetching meeting ${meetingId} (strategy: immediate_with_retry, maxAttempts: ${config.retryAttempts})`);
for (let attempt = 1; attempt <= config.retryAttempts; attempt++) {
try {
const meetingData = await this.fetchMeetingData(meetingId, { timeout: 10000, plan });
const ready = this.isSummaryReady(meetingData);
logger.debug(`attempt ${attempt}/${config.retryAttempts}: summary ready=${ready}`);
if (ready) {
return { data: meetingData, summaryReady: true };
}
if (attempt < config.retryAttempts) {
const delayMs = config.retryDelay * attempt;
logger.debug(`summary not ready, waiting ${delayMs}ms before retry ${attempt + 1}`);
await new Promise(resolve => setTimeout(resolve, delayMs));
} else {
logger.debug(`max retries reached, returning partial data`);
return { data: meetingData, summaryReady: false };
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`attempt ${attempt}/${config.retryAttempts} failed: ${errorMsg}`);
if (attempt === config.retryAttempts) {
throw error;
}
const delayMs = config.retryDelay * attempt;
logger.debug(`retrying in ${delayMs}ms...`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
throw new Error('Failed to fetch meeting data after retries');
}
private async executeTranscriptQuery({
meetingId,
query,
timeout,
}: {
meetingId: string;
query: string;
timeout?: number;
}): Promise<FirefliesMeetingData> {
const controller = new AbortController();
const timeoutId = timeout ? setTimeout(() => controller.abort(), timeout) : null;
try {
const response = await fetch('https://api.fireflies.ai/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
query,
variables: { transcriptId: meetingId },
}),
signal: controller.signal,
});
if (timeoutId) clearTimeout(timeoutId);
if (!response.ok) {
let errorDetails = `Fireflies API request failed with status ${response.status}`;
try {
const errorBody = await response.text();
if (errorBody) {
errorDetails += `: ${errorBody}`;
}
} catch {
// Ignore if we can't read the response body
}
throw new Error(errorDetails);
}
const json = await response.json() as {
data?: { transcript?: Record<string, unknown> };
errors?: Array<{ message?: string }>;
};
if (json.errors && json.errors.length > 0) {
throw new Error(`Fireflies API error: ${json.errors[0]?.message || 'Unknown error'}`);
}
const transcript = json.data?.transcript;
if (!transcript) {
throw new Error('Invalid response from Fireflies API: missing transcript data');
}
return this.transformMeetingData(transcript, meetingId);
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
}
private isSummaryReady(meetingData: FirefliesMeetingData): boolean {
return (
(meetingData.summary?.action_items?.length > 0) ||
(meetingData.summary?.overview?.length > 0) ||
meetingData.summary_status === 'completed'
);
}
private extractAllParticipants(transcript: Record<string, unknown>): FirefliesParticipant[] {
const participantsWithEmails: FirefliesParticipant[] = [];
const participantsNameOnly: FirefliesParticipant[] = [];
logger.debug('=== PARTICIPANT EXTRACTION DEBUG ===');
logger.debug('participants field:', JSON.stringify(transcript.participants));
logger.debug('meeting_attendees field:', JSON.stringify(transcript.meeting_attendees));
logger.debug('speakers field:', (transcript.speakers as Array<{ name: string }>)?.map((s) => s.name));
logger.debug('meeting_attendance field:', (transcript.meeting_attendance as Array<{ name: string }>)?.map((a) => a.name));
logger.debug('organizer_email:', transcript.organizer_email);
const isEmail = (str: string): boolean => {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str.trim());
};
const isDuplicate = (name: string, email: string): boolean => {
const nameLower = name.toLowerCase().trim();
const emailLower = email.toLowerCase().trim();
return participantsWithEmails.some(p =>
p.name.toLowerCase().trim() === nameLower ||
(email && p.email.toLowerCase() === emailLower)
) || participantsNameOnly.some(p =>
p.name.toLowerCase().trim() === nameLower
);
};
// 1. Extract from legacy participants field (with emails)
if (transcript.participants && Array.isArray(transcript.participants)) {
transcript.participants.forEach((participant: string) => {
const parts = participant.split(',').map(p => p.trim());
parts.forEach(part => {
const emailMatch = part.match(/<([^>]+)>/);
const email = emailMatch ? emailMatch[1] : '';
const name = emailMatch
? part.substring(0, part.indexOf('<')).trim()
: part.trim();
if (isEmail(name)) {
logger.debug(`Skipping participant with email as name: "${name}"`);
return;
}
if (!name) {
return;
}
if (isDuplicate(name, email)) {
logger.debug(`Skipping duplicate participant: "${name}" <${email}>`);
return;
}
if (name && email) {
participantsWithEmails.push({ name, email });
} else if (name) {
participantsNameOnly.push({ name, email: '' });
}
});
});
}
// 2. Extract from meeting_attendees field (structured)
if (transcript.meeting_attendees && Array.isArray(transcript.meeting_attendees)) {
transcript.meeting_attendees.forEach((attendee: Record<string, unknown>) => {
const name = (attendee.displayName || attendee.name || '') as string;
const email = (attendee.email || '') as string;
if (isEmail(name)) {
logger.debug(`Skipping attendee with email as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, email)) {
if (email) {
participantsWithEmails.push({ name, email });
} else {
participantsNameOnly.push({ name, email: '' });
}
}
});
}
// 3. Extract from speakers field (name only)
if (transcript.speakers && Array.isArray(transcript.speakers)) {
transcript.speakers.forEach((speaker: Record<string, unknown>) => {
const name = (speaker.name || '') as string;
if (isEmail(name)) {
logger.debug(`Skipping speaker with email as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, '')) {
participantsNameOnly.push({ name, email: '' });
}
});
}
// 4. Extract from meeting_attendance field (name only)
if (transcript.meeting_attendance && Array.isArray(transcript.meeting_attendance)) {
transcript.meeting_attendance.forEach((attendance: Record<string, unknown>) => {
const name = (attendance.name || '') as string;
if (isEmail(name) || name.includes(',')) {
logger.debug(`Skipping attendance with email/list as name: "${name}"`);
return;
}
if (name && !isDuplicate(name, '')) {
participantsNameOnly.push({ name, email: '' });
}
});
}
// 5. Add organizer email if available and not already included
const organizerEmail = transcript.organizer_email as string | undefined;
if (organizerEmail) {
const existsWithEmail = participantsWithEmails.some(p =>
p.email.toLowerCase() === organizerEmail.toLowerCase()
);
if (!existsWithEmail) {
let organizerName = '';
const emailUsername = organizerEmail.split('@')[0].toLowerCase();
const emailNameVariations = [emailUsername];
if (transcript.speakers && Array.isArray(transcript.speakers)) {
const potentialOrganizerSpeaker = transcript.speakers.find((speaker: Record<string, unknown>) => {
const name = ((speaker.name || '') as string).toLowerCase();
return emailNameVariations.some(variation =>
name.includes(variation) || variation.includes(name)
);
}) as Record<string, unknown> | undefined;
if (potentialOrganizerSpeaker) {
organizerName = potentialOrganizerSpeaker.name as string;
}
}
if (!organizerName && transcript.meeting_attendance && Array.isArray(transcript.meeting_attendance)) {
const potentialOrganizerAttendance = transcript.meeting_attendance.find((attendance: Record<string, unknown>) => {
const name = ((attendance.name || '') as string).toLowerCase();
return emailNameVariations.some(variation =>
name.includes(variation) || variation.includes(name)
);
}) as Record<string, unknown> | undefined;
if (potentialOrganizerAttendance) {
organizerName = potentialOrganizerAttendance.name as string;
}
}
if (organizerName) {
participantsWithEmails.push({ name: organizerName, email: organizerEmail });
const nameIndex = participantsNameOnly.findIndex(p =>
p.name.toLowerCase().includes(organizerName.toLowerCase()) ||
organizerName.toLowerCase().includes(p.name.toLowerCase())
);
if (nameIndex !== -1) {
participantsNameOnly.splice(nameIndex, 1);
}
} else {
participantsWithEmails.push({ name: 'Meeting Organizer', email: organizerEmail });
}
}
}
const allParticipants = [...participantsWithEmails, ...participantsNameOnly];
logger.debug('=== EXTRACTED PARTICIPANTS ===');
logger.debug('With emails:', participantsWithEmails.length, JSON.stringify(participantsWithEmails));
logger.debug('Name only:', participantsNameOnly.length, JSON.stringify(participantsNameOnly));
logger.debug('Total:', allParticipants.length);
return allParticipants;
}
private transformMeetingData(transcript: Record<string, unknown>, meetingId: string): FirefliesMeetingData {
let dateString: string;
if (transcript.date) {
if (typeof transcript.date === 'number') {
dateString = new Date(transcript.date).toISOString();
} else if (typeof transcript.date === 'string') {
const parsed = Number(transcript.date);
if (!isNaN(parsed)) {
dateString = new Date(parsed).toISOString();
} else {
dateString = transcript.date;
}
} else {
dateString = new Date().toISOString();
}
} else {
dateString = new Date().toISOString();
}
const summary = transcript.summary as Record<string, unknown> | undefined;
const analytics = transcript.analytics as Record<string, unknown> | undefined;
const sentiments = analytics?.sentiments as Record<string, number> | undefined;
const categories = analytics?.categories as Record<string, number> | undefined;
const speakersAnalytics = analytics?.speakers as Array<Record<string, unknown>> | undefined;
const meetingInfo = transcript.meeting_info as Record<string, unknown> | undefined;
// Transform sentences array
const rawSentences = transcript.sentences as Array<Record<string, unknown>> | undefined;
const sentences = rawSentences?.map(s => ({
index: (s.index as number) || 0,
speaker_name: (s.speaker_name as string) || 'Unknown',
text: (s.text as string) || '',
start_time: (s.start_time as string) || '0',
end_time: (s.end_time as string) || '0',
ai_filters: s.ai_filters as { task?: boolean; question?: boolean; sentiment?: string } | undefined,
}));
// Transform speaker analytics
const speakers = speakersAnalytics?.map(sp => ({
speaker_id: (sp.speaker_id as string) || '',
name: (sp.name as string) || 'Unknown',
duration: (sp.duration as number) || 0,
word_count: (sp.word_count as number) || 0,
longest_monologue: (sp.longest_monologue as number) || 0,
filler_words: (sp.filler_words as number) || 0,
questions: (sp.questions as number) || 0,
words_per_minute: (sp.words_per_minute as number) || 0,
}));
return {
id: (transcript.id as string) || meetingId,
title: (transcript.title as string) || 'Untitled Meeting',
date: dateString,
duration: (transcript.duration as number) || 0,
participants: this.extractAllParticipants(transcript),
organizer_email: transcript.organizer_email as string | undefined,
sentences,
summary: {
// action_items can be string or array - normalize to array
action_items: Array.isArray(summary?.action_items)
? summary.action_items as string[]
: (typeof summary?.action_items === 'string' && summary.action_items.trim()
? summary.action_items.split('\n').filter((item: string) => item.trim())
: []),
overview: (summary?.overview as string) || '',
notes: summary?.notes as string | undefined,
gist: summary?.gist as string | undefined,
bullet_gist: summary?.bullet_gist as string | undefined,
short_summary: summary?.short_summary as string | undefined,
short_overview: summary?.short_overview as string | undefined,
outline: summary?.outline as string | undefined,
shorthand_bullet: summary?.shorthand_bullet as string | undefined,
keywords: summary?.keywords as string[] | undefined,
topics_discussed: summary?.topics_discussed as string[] | undefined,
meeting_type: summary?.meeting_type as string | undefined,
transcript_chapters: summary?.transcript_chapters as string[] | undefined,
},
analytics: (sentiments || categories || speakers) ? {
sentiments: sentiments ? {
positive_pct: sentiments.positive_pct || 0,
negative_pct: sentiments.negative_pct || 0,
neutral_pct: sentiments.neutral_pct || 0,
} : undefined,
categories: categories ? {
questions: categories.questions || 0,
tasks: categories.tasks || 0,
metrics: categories.metrics || 0,
date_times: categories.date_times || 0,
} : undefined,
speakers,
} : undefined,
meeting_info: meetingInfo ? {
summary_status: meetingInfo.summary_status as string | undefined,
} : undefined,
// URLs by plan availability:
transcript_url: (transcript.transcript_url as string) || `https://app.fireflies.ai/view/${meetingId}`,
audio_url: transcript.audio_url as string | undefined, // Pro+
video_url: transcript.video_url as string | undefined, // Business+
meeting_link: transcript.meeting_link as string | undefined, // All plans
summary_status: (meetingInfo?.summary_status as string) || (transcript.summary_status as string) || undefined,
};
}
private async executeTranscriptListQuery(
query: string,
variables: Record<string, unknown>,
): Promise<Array<Record<string, unknown>>> {
const response = await fetch('https://api.fireflies.ai/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Fireflies transcripts request failed: ${response.status} ${errorBody}`);
}
const json = await response.json() as {
data?: { transcripts?: Array<Record<string, unknown>> };
errors?: Array<{ message?: string }>;
};
if (json.errors && json.errors.length > 0) {
const message = json.errors[0]?.message || 'Unknown error';
throw new Error(`Fireflies API error: ${message}`);
}
return json.data?.transcripts ?? [];
}
private normalizeDate(dateValue: unknown): string | undefined {
if (!dateValue) {
return undefined;
}
if (typeof dateValue === 'number') {
return new Date(dateValue).toISOString();
}
if (typeof dateValue === 'string') {
const parsed = Number(dateValue);
if (!Number.isNaN(parsed)) {
return new Date(parsed).toISOString();
}
return dateValue;
}
return undefined;
}
}
@@ -0,0 +1,259 @@
import type { FirefliesMeetingData, FirefliesSentence, MeetingCreateInput } from './types';
export class MeetingFormatter {
// Format timestamp from seconds to MM:SS
private static formatTimestamp(timeStr: string): string {
const seconds = parseFloat(timeStr);
if (isNaN(seconds)) return '00:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
// Format full transcript from sentences
private static formatTranscript(sentences: FirefliesSentence[]): string {
if (!sentences || sentences.length === 0) return '';
let transcript = '';
let currentSpeaker = '';
for (const sentence of sentences) {
const timestamp = this.formatTimestamp(sentence.start_time);
const speaker = sentence.speaker_name || 'Unknown';
// Add speaker header when speaker changes
if (speaker !== currentSpeaker) {
currentSpeaker = speaker;
transcript += `\n**${speaker}** [${timestamp}]\n`;
}
transcript += `${sentence.text} `;
}
return transcript.trim();
}
static formatNoteBody(meetingData: FirefliesMeetingData): string {
const meetingDate = meetingData.date ? new Date(meetingData.date) : null;
const hasValidDate = meetingDate instanceof Date && !Number.isNaN(meetingDate.getTime());
const formattedDate = hasValidDate
? meetingDate.toLocaleString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
: 'Unknown date';
const durationMinutes = Math.round(meetingData.duration);
let noteBody = `**Date:** ${formattedDate}\n`;
noteBody += `**Duration:** ${durationMinutes} minutes\n`;
if (meetingData.participants.length > 0) {
const participantNames = meetingData.participants.map(p => p.name).join(', ');
noteBody += `**Participants:** ${participantNames}\n`;
}
// Overview section
if (meetingData.summary?.overview) {
noteBody += `\n## Overview\n${meetingData.summary.overview}\n`;
}
// Detailed AI Notes (the rich content from Fireflies)
if (meetingData.summary?.notes) {
noteBody += `\n## Meeting Notes\n${meetingData.summary.notes}\n`;
}
// Bullet gist with emojis (if available and different from notes)
if (meetingData.summary?.bullet_gist && !meetingData.summary?.notes) {
noteBody += `\n## Key Points\n${meetingData.summary.bullet_gist}\n`;
}
// Meeting outline with timestamps (shorthand_bullet contains the timestamped outline)
const outline = meetingData.summary?.outline || meetingData.summary?.shorthand_bullet;
if (outline) {
noteBody += `\n## Outline\n${outline}\n`;
}
// Key topics
if (meetingData.summary?.topics_discussed?.length) {
noteBody += `\n## Key Topics\n`;
meetingData.summary.topics_discussed.forEach(topic => {
noteBody += `- ${topic}\n`;
});
}
// Action items
if (meetingData.summary?.action_items?.length) {
noteBody += `\n## Action Items\n`;
meetingData.summary.action_items.forEach(item => {
noteBody += `- [ ] ${item}\n`;
});
}
// Insights section
noteBody += `\n## Insights\n`;
if (meetingData.summary?.keywords?.length) {
noteBody += `**Keywords:** ${meetingData.summary.keywords.join(', ')}\n`;
}
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
noteBody += `**Sentiment:** ${sentiments.positive_pct}% positive, ${sentiments.negative_pct}% negative, ${sentiments.neutral_pct}% neutral\n`;
}
if (meetingData.summary?.meeting_type) {
noteBody += `**Meeting Type:** ${meetingData.summary.meeting_type}\n`;
}
// Speaker analytics (Business+)
if (meetingData.analytics?.speakers?.length) {
noteBody += `\n### Speaker Stats\n`;
for (const speaker of meetingData.analytics.speakers) {
const talkTime = Math.round(speaker.duration / 60);
noteBody += `- **${speaker.name}**: ${talkTime} min talk time, ${speaker.word_count} words, ${speaker.questions} questions\n`;
}
}
// Meeting metrics (Business+)
if (meetingData.analytics?.categories) {
const cats = meetingData.analytics.categories;
noteBody += `\n### Meeting Metrics\n`;
noteBody += `- Questions asked: ${cats.questions}\n`;
noteBody += `- Tasks identified: ${cats.tasks}\n`;
if (cats.metrics > 0) noteBody += `- Metrics mentioned: ${cats.metrics}\n`;
if (cats.date_times > 0) noteBody += `- Dates/times discussed: ${cats.date_times}\n`;
}
// Resources section
noteBody += `\n## Resources\n`;
noteBody += `[View Full Transcript on Fireflies](${meetingData.transcript_url})\n`;
if (meetingData.video_url) {
noteBody += `[Watch Video Recording](${meetingData.video_url})\n`;
}
if (meetingData.audio_url) {
noteBody += `[Listen to Audio](${meetingData.audio_url})\n`;
}
if (meetingData.meeting_link) {
noteBody += `[Original Meeting Link](${meetingData.meeting_link})\n`;
}
return noteBody;
}
static toMeetingCreateInput(
meetingData: FirefliesMeetingData,
noteId?: string
): MeetingCreateInput {
const durationMinutes = Math.round(meetingData.duration);
const hasSummary = Boolean(meetingData.summary?.overview || meetingData.summary?.action_items?.length);
const hasAnalytics = Boolean(meetingData.analytics?.sentiments);
// Build input object with only defined values (omit null fields)
const input: MeetingCreateInput = {
name: meetingData.title,
meetingDate: meetingData.date,
duration: durationMinutes,
actionItemsCount: meetingData.summary?.action_items?.length || 0,
firefliesMeetingId: meetingData.id,
};
// Add direct relationship to note if noteId is provided
if (noteId) {
input.noteId = noteId;
}
// Basic fields (All plans)
if (meetingData.organizer_email) {
input.organizerEmail = meetingData.organizer_email;
}
if (meetingData.transcript_url?.trim()) {
input.transcriptUrl = {
primaryLinkUrl: meetingData.transcript_url,
primaryLinkLabel: 'View Transcript'
};
}
if (meetingData.meeting_link?.trim()) {
input.meetingLink = {
primaryLinkUrl: meetingData.meeting_link,
primaryLinkLabel: 'Join Meeting'
};
}
// Pro+ fields (transcript, summary, notes, keywords, audio)
if (meetingData.sentences?.length) {
input.transcript = this.formatTranscript(meetingData.sentences);
}
if (meetingData.summary?.overview) {
input.overview = meetingData.summary.overview;
}
if (meetingData.summary?.notes) {
input.notes = meetingData.summary.notes;
}
if (meetingData.summary?.keywords?.length) {
input.keywords = meetingData.summary.keywords.join(', ');
}
if (meetingData.audio_url?.trim()) {
input.audioUrl = {
primaryLinkUrl: meetingData.audio_url,
primaryLinkLabel: 'Listen to Audio'
};
}
// Business+ fields (analytics, video, detailed summary)
if (meetingData.summary?.meeting_type) {
input.meetingType = meetingData.summary.meeting_type;
}
if (meetingData.summary?.topics_discussed?.length) {
input.topics = meetingData.summary.topics_discussed.join(', ');
}
if (meetingData.analytics?.sentiments) {
const sentiments = meetingData.analytics.sentiments;
input.positivePercent = sentiments.positive_pct;
input.negativePercent = sentiments.negative_pct;
input.neutralPercent = sentiments.neutral_pct;
}
if (meetingData.video_url?.trim()) {
input.videoUrl = {
primaryLinkUrl: meetingData.video_url,
primaryLinkLabel: 'Watch Video'
};
}
// Import status based on data completeness
const isPartial = !hasSummary && !hasAnalytics;
input.importStatus = isPartial ? 'PARTIAL' : 'SUCCESS';
input.lastImportAttempt = new Date().toISOString();
input.importAttempts = 1;
return input;
}
static toFailedMeetingCreateInput(
meetingId: string,
title: string,
error: string,
attempts: number = 1
): MeetingCreateInput {
const currentDate = new Date().toISOString();
return {
name: title || `Failed Meeting Import - ${meetingId}`,
meetingDate: currentDate,
duration: 0,
actionItemsCount: 0,
firefliesMeetingId: meetingId,
importStatus: 'FAILED',
importError: error,
lastImportAttempt: currentDate,
importAttempts: attempts,
};
}
}
@@ -0,0 +1,161 @@
import { type FirefliesApiClient } from './fireflies-api-client';
import { MeetingFormatter } from './formatters';
import { createLogger } from './logger';
import { type TwentyCrmService } from './twenty-crm-service';
import type {
FirefliesPlan,
FirefliesTranscriptListOptions,
SummaryFetchConfig,
} from './types';
const logger = createLogger('historical-importer');
export type HistoricalImportFilters = FirefliesTranscriptListOptions;
export type HistoricalImportOptions = {
dryRun?: boolean;
autoCreateContacts: boolean;
summaryConfig: SummaryFetchConfig;
plan: FirefliesPlan;
};
export type HistoricalImportResult = {
dryRun: boolean;
totalListed: number;
imported: number;
skippedExisting: number;
failed: Array<{ meetingId: string; reason: string }>;
summaryPending: number;
statuses: Array<{
meetingId: string;
title?: string;
status: 'imported' | 'skipped_existing' | 'failed' | 'dry_run' | 'pending_summary';
reason?: string;
}>;
};
export class HistoricalImporter {
private firefliesClient: FirefliesApiClient;
private twentyService: TwentyCrmService;
constructor(firefliesClient: FirefliesApiClient, twentyService: TwentyCrmService) {
this.firefliesClient = firefliesClient;
this.twentyService = twentyService;
}
async run(
filters: HistoricalImportFilters,
options: HistoricalImportOptions,
): Promise<HistoricalImportResult> {
const { dryRun = false, autoCreateContacts, summaryConfig, plan } = options;
logger.info('Listing Fireflies transcripts for historical import...');
const transcripts = await this.firefliesClient.listTranscripts(filters);
logger.info(`Found ${transcripts.length} transcript(s) to process`);
let imported = 0;
let skippedExisting = 0;
let summaryPending = 0;
const failed: Array<{ meetingId: string; reason: string }> = [];
const statuses: HistoricalImportResult['statuses'] = [];
for (const transcript of transcripts) {
const meetingId = transcript.id;
try {
const existing = await this.twentyService.findMeetingByFirefliesId(meetingId);
if (existing) {
logger.debug(`Skipping ${meetingId}: already exists in Twenty (${existing.id})`);
skippedExisting += 1;
statuses.push({
meetingId,
title: transcript.title,
status: 'skipped_existing',
});
continue;
}
logger.info(`Fetching meeting ${meetingId} details`);
const { data: meetingData, summaryReady } =
await this.firefliesClient.fetchMeetingDataWithRetry(
meetingId,
summaryConfig,
plan,
);
const isPendingSummary = summaryReady === false;
if (isPendingSummary) {
summaryPending += 1;
}
if (dryRun) {
logger.info(`[dry-run] Would import meeting "${meetingData.title}" (${meetingId})`);
imported += 1;
statuses.push({
meetingId,
title: meetingData.title,
status: isPendingSummary ? 'pending_summary' : 'dry_run',
reason: isPendingSummary ? 'summary not ready' : undefined,
});
continue;
}
const { matchedContacts, unmatchedParticipants } =
await this.twentyService.matchParticipantsToContacts(
meetingData.participants,
);
const newContactIds = autoCreateContacts
? await this.twentyService.createContactsForUnmatched(unmatchedParticipants)
: [];
const allContactIds = [...matchedContacts.map(({ id }) => id), ...newContactIds];
const noteBody = MeetingFormatter.formatNoteBody(meetingData);
const noteId = await this.twentyService.createNoteOnly(
`Meeting: ${meetingData.title}`,
noteBody,
);
const meetingInput = MeetingFormatter.toMeetingCreateInput(meetingData, noteId);
const createdMeetingId = await this.twentyService.createMeeting(meetingInput);
for (const contactId of allContactIds) {
await this.twentyService.createNoteTarget(noteId, contactId);
}
logger.info(
`Imported meeting "${meetingData.title}" (${meetingId}) as ${createdMeetingId}`,
);
imported += 1;
statuses.push({
meetingId,
title: meetingData.title,
status: isPendingSummary ? 'pending_summary' : 'imported',
reason: isPendingSummary ? 'summary not ready' : undefined,
});
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
logger.error(`Failed to import meeting ${meetingId}: ${reason}`);
failed.push({ meetingId, reason });
statuses.push({
meetingId,
title: transcript.title,
status: 'failed',
reason,
});
}
}
return {
dryRun,
totalListed: transcripts.length,
imported,
skippedExisting,
failed,
summaryPending,
statuses,
};
}
}
@@ -0,0 +1,31 @@
// Main exports for the Fireflies integration
export { config, main } from './receive-fireflies-notes';
// Types
export type {
FirefliesMeetingData,
FirefliesParticipant,
FirefliesWebhookPayload,
ProcessResult,
SummaryFetchConfig,
SummaryStrategy
} from './types';
// Services (for advanced usage)
export { FirefliesApiClient } from './fireflies-api-client';
export { MeetingFormatter } from './formatters';
export { TwentyCrmService } from './twenty-crm-service';
export { WebhookHandler } from './webhook-handler';
// Objects
export { Meeting } from './objects';
// Utilities
export { createLogger } from './logger';
export { getApiUrl, getSummaryFetchConfig, shouldAutoCreateContacts, toBoolean } from './utils';
export {
getWebhookSecretFingerprint,
isValidFirefliesPayload,
verifyWebhookSignature
} from './webhook-validator';
@@ -0,0 +1,142 @@
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
export type LoggerConfig = {
logLevel: LogLevel;
isTestEnvironment: boolean;
captureForResponse: boolean;
};
const LOG_LEVELS: Record<LogLevel, number> = {
debug: 0,
info: 1,
warn: 2,
error: 3,
silent: 4,
};
const loggerRegistry = new Set<AppLogger>();
export class AppLogger {
private config: LoggerConfig;
private context: string;
private capturedLogs: string[] = [];
constructor(context: string) {
this.context = context;
this.config = {
logLevel: this.parseLogLevel(process.env.LOG_LEVEL || 'error'),
isTestEnvironment: process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined,
captureForResponse: process.env.CAPTURE_LOGS === 'true',
};
// Silence logs in test environment unless explicitly overridden
if (this.config.isTestEnvironment && process.env.LOG_LEVEL === undefined) {
this.config.logLevel = 'silent';
}
}
private parseLogLevel(level: string): LogLevel {
const normalizedLevel = level.toLowerCase() as LogLevel;
return Object.keys(LOG_LEVELS).includes(normalizedLevel) ? normalizedLevel : 'error';
}
private shouldLog(level: LogLevel): boolean {
return LOG_LEVELS[level] >= LOG_LEVELS[this.config.logLevel];
}
private safeStringify(value: unknown): string {
try {
if (typeof value === 'string') return value;
return JSON.stringify(value);
} catch {
return '[unserializable]';
}
}
private captureLog(level: LogLevel, message: string, ...args: unknown[]): void {
if (!this.config.captureForResponse) {
return;
}
const timestamp = new Date().toISOString();
const formattedMessage =
args.length > 0
? `${message} ${args.map((arg) => this.safeStringify(arg)).join(' ')}`
: message;
this.capturedLogs.push(
`[${timestamp}] [${level.toUpperCase()}] [${this.context}] ${formattedMessage}`,
);
}
debug(message: string, ...args: unknown[]): void {
this.captureLog('debug', message, ...args);
if (this.shouldLog('debug')) {
// eslint-disable-next-line no-console
console.log(`[${this.context}] ${message}`, ...args);
}
}
info(message: string, ...args: unknown[]): void {
this.captureLog('info', message, ...args);
if (this.shouldLog('info')) {
// eslint-disable-next-line no-console
console.log(`[${this.context}] ${message}`, ...args);
}
}
warn(message: string, ...args: unknown[]): void {
this.captureLog('warn', message, ...args);
if (this.shouldLog('warn')) {
// eslint-disable-next-line no-console
console.warn(`[${this.context}] ${message}`, ...args);
}
}
error(message: string, ...args: unknown[]): void {
this.captureLog('error', message, ...args);
if (this.shouldLog('error')) {
// eslint-disable-next-line no-console
console.error(`[${this.context}] ${message}`, ...args);
}
}
// For fatal errors, security issues, or data corruption - always visible
critical(message: string, ...args: unknown[]): void {
this.captureLog('error', `CRITICAL: ${message}`, ...args);
// eslint-disable-next-line no-console
console.error(`[${this.context}] CRITICAL: ${message}`, ...args);
}
getCapturedLogs(): string[] {
return [...this.capturedLogs];
}
clearCapturedLogs(): void {
this.capturedLogs = [];
}
}
export const createLogger = (context: string): AppLogger => {
const logger = new AppLogger(context);
loggerRegistry.add(logger);
return logger;
};
export const removeLogger = (logger: AppLogger): void => {
loggerRegistry.delete(logger);
};
export const getAllCapturedLogs = (): string[] => {
const allLogs: string[] = [];
for (const logger of loggerRegistry) {
allLogs.push(...logger.getCapturedLogs());
}
return allLogs.sort();
};
export const clearAllCapturedLogs = (): void => {
for (const logger of loggerRegistry) {
logger.clearCapturedLogs();
}
};
@@ -0,0 +1,3 @@
export { Meeting } from './meeting';
@@ -1,6 +1,6 @@
import { ObjectMetadata } from 'twenty-sdk/application';
import { Object } from 'twenty-sdk';
@ObjectMetadata({
@Object({
universalIdentifier: 'd1831348-b4a4-4426-9c0b-0af19e7a9c27',
nameSingular: 'meeting',
namePlural: 'meetings',
@@ -0,0 +1,29 @@
import { type FunctionConfig } from 'twenty-sdk';
import type { ProcessResult } from './types';
import { WebhookHandler } from './webhook-handler';
export const main = async (
params: unknown,
headers?: Record<string, string>
): Promise<ProcessResult> => {
const handler = new WebhookHandler();
return handler.handle(params, headers);
};
export const config: FunctionConfig = {
universalIdentifier: '2d3ea303-667c-4bbe-9e3d-db6ffb9d6c74',
name: 'receive-fireflies-notes',
description:
'Receives Fireflies webhooks, fetches meeting summaries, and stores them in Twenty.',
timeoutSeconds: 30,
triggers: [
{
universalIdentifier: 'a2117dc1-7674-4c7e-9d70-9feb9820e9e8',
type: 'route',
path: '/webhook/fireflies',
httpMethod: 'POST',
isAuthRequired: false,
},
],
};
@@ -43,6 +43,20 @@ export class TwentyCrmService {
return response.data?.meetings?.edges?.[0]?.node;
}
async findMeetingByFirefliesId(meetingId: string): Promise<IdNode | undefined> {
const query = `
query FindMeetingByFirefliesId($meetingId: String!) {
meetings(filter: { firefliesMeetingId: { eq: $meetingId } }) {
edges { node { id } }
}
}
`;
const variables = { meetingId };
const response = await this.gqlRequest<FindMeetingResponse>(query, variables);
return response.data?.meetings?.edges?.[0]?.node;
}
async matchParticipantsToContacts(
participants: FirefliesParticipant[],
): Promise<{
@@ -53,21 +67,18 @@ export class TwentyCrmService {
return { matchedContacts: [], unmatchedParticipants: [] };
}
// Split participants into those with emails and those with names only
const participantsWithEmails = participants.filter(p => p.email && p.email.trim());
const participantsNameOnly = participants.filter(p => !p.email || !p.email.trim());
let matchedContacts: Contact[] = [];
let unmatchedParticipants: FirefliesParticipant[] = [];
// 1. Match by email first
if (participantsWithEmails.length > 0) {
const emailMatches = await this.matchByEmail(participantsWithEmails);
matchedContacts.push(...emailMatches.matchedContacts);
unmatchedParticipants.push(...emailMatches.unmatchedParticipants);
}
// 2. For participants without emails, try name-based matching
if (participantsNameOnly.length > 0) {
const nameMatches = await this.matchByName(participantsNameOnly, matchedContacts);
matchedContacts.push(...nameMatches.matchedContacts);
@@ -126,7 +137,6 @@ export class TwentyCrmService {
const matchedContacts: Contact[] = [];
const unmatchedParticipants: FirefliesParticipant[] = [];
// Get set of already matched contact IDs to avoid duplicates
const alreadyMatchedIds = new Set(alreadyMatchedContacts.map(c => c.id));
for (const participant of participants) {
@@ -152,27 +162,37 @@ export class TwentyCrmService {
const firstName = nameParts[0];
const lastName = nameParts.slice(1).join(' ');
// Try exact name match first
let query = `
query FindPeopleByName($firstName: String!, $lastName: String) {
people(filter: {
and: [
{ name: { firstName: { eq: $firstName } } }
${lastName ? '{ name: { lastName: { eq: $lastName } } }' : ''}
]
}) {
edges { node { id emails { primaryEmail } name { firstName lastName } } }
}
}
`;
const hasLastName = Boolean(lastName);
let variables: any = { firstName };
if (lastName) {
variables.lastName = lastName;
}
const query = hasLastName
? `
query FindPeopleByName($firstName: String!, $lastName: String!) {
people(filter: {
and: [
{ name: { firstName: { eq: $firstName } } }
{ name: { lastName: { eq: $lastName } } }
]
}) {
edges { node { id emails { primaryEmail } name { firstName lastName } } }
}
}
`
: `
query FindPeopleByName($firstName: String!) {
people(filter: {
name: { firstName: { eq: $firstName } }
}) {
edges { node { id emails { primaryEmail } name { firstName lastName } } }
}
}
`;
const variables: Record<string, unknown> = hasLastName
? { firstName, lastName }
: { firstName };
try {
const response = await this.gqlRequest<any>(query, variables);
const response = await this.gqlRequest<{ people: { edges: Array<{ node: { id: string; emails?: { primaryEmail?: string }; name?: { firstName?: string; lastName?: string } } }> } }>(query, variables);
const people = response.data?.people?.edges;
if (people && people.length > 0) {
@@ -183,9 +203,8 @@ export class TwentyCrmService {
};
}
// If no exact match and we have a last name, try fuzzy matching
if (lastName) {
query = `
if (hasLastName) {
const fuzzyQuery = `
query FindPeopleByNameFuzzy($firstName: String!) {
people(filter: { name: { firstName: { ilike: $firstName } } }) {
edges { node { id emails { primaryEmail } name { firstName lastName } } }
@@ -193,12 +212,11 @@ export class TwentyCrmService {
}
`;
const fuzzyResponse = await this.gqlRequest<any>(query, { firstName: `%${firstName}%` });
const fuzzyResponse = await this.gqlRequest<{ people: { edges: Array<{ node: { id: string; emails?: { primaryEmail?: string }; name?: { firstName?: string; lastName?: string } } }> } }>(fuzzyQuery, { firstName: `%${firstName}%` });
const fuzzyPeople = fuzzyResponse.data?.people?.edges;
if (fuzzyPeople && fuzzyPeople.length > 0) {
// Find best match by checking if last name contains our target
const bestMatch = fuzzyPeople.find((edge: any) => {
const bestMatch = fuzzyPeople.find((edge) => {
const personLastName = edge.node.name?.lastName || '';
return personLastName.toLowerCase().includes(lastName.toLowerCase());
});
@@ -215,7 +233,6 @@ export class TwentyCrmService {
return null;
} catch {
// Silently fail - don't break the entire process for a single contact lookup
return null;
}
}
@@ -225,17 +242,14 @@ export class TwentyCrmService {
): Promise<string[]> {
const newContactIds: string[] = [];
// Split participants into those with emails and those with names only
const participantsWithEmails = participants.filter(p => p.email && p.email.trim());
const participantsNameOnly = participants.filter(p => !p.email || !p.email.trim());
// Process participants with emails
if (participantsWithEmails.length > 0) {
const emailContactIds = await this.createContactsWithEmails(participantsWithEmails);
newContactIds.push(...emailContactIds);
}
// Process participants with names only
if (participantsNameOnly.length > 0) {
const nameContactIds = await this.createContactsNameOnly(participantsNameOnly);
newContactIds.push(...nameContactIds);
@@ -247,7 +261,6 @@ export class TwentyCrmService {
private async createContactsWithEmails(participants: FirefliesParticipant[]): Promise<string[]> {
const newContactIds: string[] = [];
// Deduplicate participants by email to prevent duplicate contact creation
const uniqueParticipants = participants.reduce<FirefliesParticipant[]>((unique, participant) => {
const existing = unique.find(p => p.email === participant.email);
if (!existing) {
@@ -276,7 +289,10 @@ export class TwentyCrmService {
};
try {
const response = await this.gqlRequest<CreatePersonResponse>(mutation, variables);
const response = await this.gqlRequest<CreatePersonResponse>(mutation, variables, {
suppressErrorCodes: ['BAD_USER_INPUT'],
suppressErrorMessageIncludes: ['Duplicate Emails', 'duplicate entry'],
});
if (!response.data?.createPerson?.id) {
throw new Error(`Failed to create contact for ${participant.email}`);
}
@@ -297,7 +313,6 @@ export class TwentyCrmService {
private async createContactsNameOnly(participants: FirefliesParticipant[]): Promise<string[]> {
const newContactIds: string[] = [];
// Deduplicate participants by name to prevent duplicate contact creation
const uniqueParticipants = participants.reduce<FirefliesParticipant[]>((unique, participant) => {
const existing = unique.find(p =>
p.name.toLowerCase().trim() === participant.name.toLowerCase().trim()
@@ -311,7 +326,6 @@ export class TwentyCrmService {
}, []);
for (const participant of uniqueParticipants) {
// Check if we already have a contact with this exact name to avoid duplicates
const existingContact = await this.findContactByName(participant.name);
if (existingContact) {
logger.warn(`Contact with name "${participant.name}" already exists. Skipping creation.`);
@@ -330,8 +344,6 @@ export class TwentyCrmService {
const variables = {
data: {
name: { firstName, lastName },
// Note: We don't set emails for name-only participants
// This will create a contact without an email address
},
};
@@ -346,7 +358,6 @@ export class TwentyCrmService {
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
logger.warn(`Failed to create contact for ${participant.name}: ${errorMessage}`);
// Continue processing other participants instead of failing completely
continue;
}
}
@@ -409,28 +420,7 @@ export class TwentyCrmService {
},
};
await this.gqlRequest<any>(mutation, variables);
}
async createMeetingTarget(meetingId: string, contactId: string): Promise<void> {
const mutation = `
mutation CreateMeetingTarget($data: NoteTargetCreateInput!) {
createNoteTarget(data: $data) {
id
meetingId
personId
}
}
`;
const variables = {
data: {
meetingId,
personId: contactId,
},
};
await this.gqlRequest<any>(mutation, variables);
await this.gqlRequest<{ createNoteTarget: { id: string; noteId: string; personId: string } }>(mutation, variables);
}
async createMeeting(meetingData: MeetingCreateInput): Promise<string> {
@@ -442,7 +432,6 @@ export class TwentyCrmService {
const variables = { data: meetingData };
// Debug: log the variables being sent
if (!this.isTestEnvironment) {
logger.debug('createMeeting variables:', JSON.stringify(variables, null, 2));
}
@@ -456,7 +445,8 @@ export class TwentyCrmService {
private async gqlRequest<T>(
query: string,
variables?: Record<string, unknown>
variables?: Record<string, unknown>,
options?: { suppressErrorCodes?: string[]; suppressErrorMessageIncludes?: string[] }
): Promise<GraphQLResponse<T>> {
const url = `${this.apiUrl}/graphql`;
@@ -500,7 +490,16 @@ export class TwentyCrmService {
return json;
} catch (error) {
logger.error('GraphQL request error:', error);
const message = error instanceof Error ? error.message : String(error);
const suppressByCode = options?.suppressErrorCodes?.some((code) =>
message.includes(code),
);
const suppressByMessage = options?.suppressErrorMessageIncludes?.some((substring) =>
message.includes(substring),
);
if (!suppressByCode && !suppressByMessage) {
logger.error('GraphQL request error:', error);
}
throw error;
}
}
@@ -525,7 +524,15 @@ export class TwentyCrmService {
return response.data.createMeeting.id;
}
async findFailedMeetings(): Promise<any[]> {
async findFailedMeetings(): Promise<Array<{
id: string;
name: string;
firefliesMeetingId: string;
importError: string;
lastImportAttempt: string;
importAttempts: number;
createdAt: string;
}>> {
const query = `
query FindFailedMeetings {
meetings(filter: { importStatus: { eq: "FAILED" } }) {
@@ -544,8 +551,8 @@ export class TwentyCrmService {
}
`;
const response = await this.gqlRequest<any>(query);
return response.data?.meetings?.edges?.map((edge: any) => edge.node) || [];
const response = await this.gqlRequest<{ meetings: { edges: Array<{ node: { id: string; name: string; firefliesMeetingId: string; importError: string; lastImportAttempt: string; importAttempts: number; createdAt: string } }> } }>(query);
return response.data?.meetings?.edges?.map((edge) => edge.node) || [];
}
async retryFailedMeeting(meetingId: string, updatedData: Partial<MeetingCreateInput>): Promise<void> {
@@ -564,7 +571,7 @@ export class TwentyCrmService {
}
};
await this.gqlRequest<any>(mutation, variables);
await this.gqlRequest<{ updateMeeting: { id: string } }>(mutation, variables);
}
}
@@ -0,0 +1,235 @@
// Fireflies API Types
export type FirefliesParticipant = {
email: string;
name: string;
};
export type FirefliesWebhookPayload = {
meetingId: string;
eventType: string;
clientReferenceId?: string;
};
// Transcript sentence from Fireflies API
export type FirefliesSentence = {
index: number;
speaker_name: string;
text: string;
start_time: string;
end_time: string;
ai_filters?: {
task?: boolean;
question?: boolean;
sentiment?: string;
};
};
// Speaker analytics from Fireflies API (Business+)
export type FirefliesSpeakerAnalytics = {
speaker_id: string;
name: string;
duration: number;
word_count: number;
longest_monologue: number;
filler_words: number;
questions: number;
words_per_minute: number;
};
// Based on Fireflies GraphQL API transcript schema
// See: https://docs.fireflies.ai/graphql-api/query/transcript
export type FirefliesMeetingData = {
id: string;
title: string;
date: string;
duration: number;
participants: FirefliesParticipant[];
organizer_email?: string;
// Full transcript (Pro+)
sentences?: FirefliesSentence[];
summary: {
// Pro+ fields
action_items: string[];
keywords?: string[];
overview: string;
notes?: string; // Detailed AI-generated meeting notes
gist?: string; // 1-sentence summary
bullet_gist?: string; // Bullet point summary with emojis
short_summary?: string; // Single paragraph summary
short_overview?: string; // Brief overview
outline?: string; // Meeting outline with timestamps
shorthand_bullet?: string;
// Business+ fields
topics_discussed?: string[];
meeting_type?: string;
transcript_chapters?: string[];
};
// Business+ analytics
analytics?: {
sentiments?: {
positive_pct: number;
negative_pct: number;
neutral_pct: number;
};
categories?: {
questions: number;
tasks: number;
metrics: number;
date_times: number;
};
speakers?: FirefliesSpeakerAnalytics[];
};
meeting_info?: {
summary_status?: string;
};
// URLs
transcript_url: string;
audio_url?: string; // Pro+
video_url?: string; // Business+
meeting_link?: string; // All plans
summary_status?: string;
};
export type FirefliesTranscriptListItem = {
id: string;
title: string;
date?: string;
duration?: number;
organizer_email?: string;
participants?: string[];
transcript_url?: string;
meeting_link?: string;
summary_status?: string;
};
export type FirefliesTranscriptListOptions = {
limit?: number;
skip?: number;
organizers?: string[];
participants?: string[];
hostEmail?: string;
participantEmail?: string;
userId?: string;
channelId?: string;
mine?: boolean;
fromDate?: number;
toDate?: number;
pageSize?: number;
maxRecords?: number;
};
// Configuration Types
export type SummaryStrategy = 'immediate_only' | 'immediate_with_retry' | 'delayed_polling' | 'basic_only';
export type SummaryFetchConfig = {
strategy: SummaryStrategy;
retryAttempts: number;
retryDelay: number;
pollInterval: number;
maxPolls: number;
};
export const FIREFLIES_PLANS = {
FREE: 'free',
PRO: 'pro',
BUSINESS: 'business',
ENTERPRISE: 'enterprise',
} as const;
export type FirefliesPlan = typeof FIREFLIES_PLANS[keyof typeof FIREFLIES_PLANS];
export type WebhookConfig = {
secret: string;
apiUrl: string;
};
// Processing Result Types
export type ProcessResult = {
success: boolean;
meetingId?: string;
noteIds?: string[];
newContacts?: string[];
errors?: string[];
debug?: string[];
summaryReady?: boolean;
summaryPending?: boolean;
enhancementScheduled?: boolean;
actionItemsCount?: number;
sentimentAnalysis?: {
positive_pct: number;
negative_pct: number;
neutral_pct: number;
};
meetingType?: string;
keyTopics?: string[];
};
// Twenty CRM Types
export type GraphQLResponse<T> = {
data: T;
errors?: Array<{
message?: string;
extensions?: { code?: string }
}>;
};
export type IdNode = { id: string };
export type FindMeetingResponse = {
meetings: { edges: Array<{ node: IdNode }> };
};
export type FindPeopleResponse = {
people: { edges: Array<{ node: { id: string; emails: { primaryEmail: string } } }> };
};
export type CreatePersonResponse = {
createPerson: { id: string }
};
export type CreateNoteResponse = {
createNote: { id: string }
};
export type CreateMeetingResponse = {
createMeeting: { id: string }
};
export type Contact = {
id: string;
email: string;
};
// Twenty CRM Meeting custom field input
// Maps to fields defined in add-meeting-fields.ts
export type MeetingCreateInput = {
name: string;
noteId?: string | null;
// Basic fields (All plans)
meetingDate: string;
duration: number;
firefliesMeetingId: string;
organizerEmail?: string | null;
transcriptUrl?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
meetingLink?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
// Pro+ fields
transcript?: string | null;
overview?: string | null;
notes?: string | null;
keywords?: string | null;
audioUrl?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
// Business+ fields
meetingType?: string | null;
topics?: string | null;
actionItemsCount: number;
positivePercent?: number | null;
negativePercent?: number | null;
neutralPercent?: number | null;
videoUrl?: { primaryLinkUrl: string; primaryLinkLabel: string } | null;
// Import tracking
importStatus?: 'SUCCESS' | 'PARTIAL' | 'FAILED' | 'PENDING' | 'RETRYING' | null;
importError?: string | null;
lastImportAttempt?: string | null;
importAttempts?: number | null;
};
@@ -0,0 +1,41 @@
import { FIREFLIES_PLANS, type FirefliesPlan, type SummaryFetchConfig, type SummaryStrategy } from './types';
export const toBoolean = (value: string | undefined, defaultValue: boolean): boolean => {
if (value === undefined) return defaultValue;
const normalized = value.trim().toLowerCase();
return normalized === 'true' || normalized === '1' || normalized === 'yes';
};
export const getApiUrl = (): string => {
return process.env.SERVER_URL || 'http://localhost:3000';
};
export const getSummaryFetchConfig = (): SummaryFetchConfig => {
const strategy = (process.env.FIREFLIES_SUMMARY_STRATEGY as SummaryStrategy) || 'immediate_with_retry';
// Ultra-conservative defaults to respect 50 requests/day API limit
// With 3 attempts at 15-minute intervals, max 3 API calls per webhook (45 minutes total)
return {
strategy,
retryAttempts: parseInt(process.env.FIREFLIES_RETRY_ATTEMPTS || '3', 10),
retryDelay: parseInt(process.env.FIREFLIES_RETRY_DELAY || '120000', 10), // 2 minutes
pollInterval: parseInt(process.env.FIREFLIES_POLL_INTERVAL || '120000', 10), // 2 minutes
maxPolls: parseInt(process.env.FIREFLIES_MAX_POLLS || '3', 10),
};
};
export const shouldAutoCreateContacts = (): boolean => {
return toBoolean(process.env.AUTO_CREATE_CONTACTS, true);
};
export const getFirefliesPlan = (): FirefliesPlan => {
const plan = (process.env.FIREFLIES_PLAN || FIREFLIES_PLANS.FREE).toLowerCase();
if (plan === FIREFLIES_PLANS.BUSINESS || plan === FIREFLIES_PLANS.ENTERPRISE) {
return plan as FirefliesPlan;
}
if (plan === FIREFLIES_PLANS.PRO) {
return FIREFLIES_PLANS.PRO;
}
return FIREFLIES_PLANS.FREE;
};
@@ -0,0 +1,383 @@
import { FirefliesApiClient } from './fireflies-api-client';
import { MeetingFormatter } from './formatters';
import { clearAllCapturedLogs, createLogger, getAllCapturedLogs } from './logger';
import { TwentyCrmService } from './twenty-crm-service';
import type { FirefliesWebhookPayload, ProcessResult } from './types';
import { getApiUrl, getFirefliesPlan, getSummaryFetchConfig, shouldAutoCreateContacts } from './utils';
import {
getWebhookSecretFingerprint,
isValidFirefliesPayload,
verifyWebhookSignature
} from './webhook-validator';
declare const process: { env: Record<string, string | undefined> };
export class WebhookHandler {
private debug: string[] = [];
private logger: ReturnType<typeof createLogger>;
constructor() {
this.logger = createLogger('fireflies');
}
private addDebugLogs(result: ProcessResult): ProcessResult {
if (process.env.CAPTURE_LOGS === 'true') {
const captured = getAllCapturedLogs();
result.debug = [...this.debug, ...captured];
} else {
delete result.debug;
}
return result;
}
async handle(params: unknown, headers?: Record<string, string>): Promise<ProcessResult> {
clearAllCapturedLogs();
this.debug = [];
const result: ProcessResult = {
success: false,
noteIds: [],
newContacts: [],
errors: [],
};
try {
this.logger.debug('invoked');
this.logger.debug(`apiUrl=${getApiUrl()}`);
const paramKeys =
params && typeof params === 'object'
? Object.keys(params as Record<string, unknown>)
: [];
this.debug.push(
`paramsType=${typeof params}`,
`paramKeys=${paramKeys.join(',') || 'none'}`
);
// 0) Validate environment configuration
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
const twentyApiKey = process.env.TWENTY_API_KEY || '';
if (!firefliesApiKey) {
this.logger.critical('FIREFLIES_API_KEY not configured - this is a critical configuration error');
throw new Error('FIREFLIES_API_KEY environment variable is required');
}
if (!twentyApiKey) {
this.logger.critical('TWENTY_API_KEY not configured - this is a critical configuration error');
throw new Error('TWENTY_API_KEY environment variable is required');
}
// 1) Parse and validate webhook payload and extract headers if wrapped together
const { payload, extractedHeaders } = this.parsePayload(params);
const finalHeaders = extractedHeaders || headers;
this.logger.debug(`payload meetingId=${payload.meetingId} eventType="${payload.eventType}"`);
// 2) Verify webhook signature
const webhookSecret = process.env.FIREFLIES_WEBHOOK_SECRET || '';
const secretFingerprint = getWebhookSecretFingerprint(webhookSecret);
this.logger.debug(`webhook secret fingerprint=${secretFingerprint}`);
this.verifySignature(payload, finalHeaders, webhookSecret);
this.logger.debug('signature verification: ok');
// 3) Fetch meeting data from Fireflies
const summaryConfig = getSummaryFetchConfig();
const firefliesPlan = getFirefliesPlan();
this.logger.debug(`summary strategy: ${summaryConfig.strategy} (retryAttempts=${summaryConfig.retryAttempts}, retryDelay=${summaryConfig.retryDelay}ms)`);
this.logger.debug(`fetching meeting data from Fireflies API`);
const firefliesClient = new FirefliesApiClient(firefliesApiKey);
const { data: meetingData, summaryReady } = await firefliesClient.fetchMeetingDataWithRetry(
payload.meetingId,
summaryConfig,
firefliesPlan
);
this.logger.debug(`meeting data fetched: title="${meetingData.title}" summaryReady=${summaryReady}`);
result.summaryReady = summaryReady;
result.summaryPending = !summaryReady;
// Extract business intelligence
if (summaryReady) {
result.actionItemsCount = meetingData.summary.action_items.length;
result.keyTopics = meetingData.summary.topics_discussed;
result.meetingType = meetingData.summary.meeting_type;
if (meetingData.analytics?.sentiments) {
result.sentimentAnalysis = meetingData.analytics.sentiments;
}
}
// 4) Check for duplicate meetings
const twentyService = new TwentyCrmService(
twentyApiKey,
getApiUrl()
);
const existingMeetingById = await twentyService.findMeetingByFirefliesId(meetingData.id);
if (existingMeetingById) {
this.logger.debug(`meeting already exists by firefliesMeetingId id=${existingMeetingById.id}`);
result.success = true;
result.meetingId = existingMeetingById.id;
return this.addDebugLogs(result);
}
const existingMeetingByTitle = await twentyService.findExistingMeeting(meetingData.title);
if (existingMeetingByTitle) {
this.logger.debug(`meeting already exists by title id=${existingMeetingByTitle.id}`);
result.success = true;
result.meetingId = existingMeetingByTitle.id;
return this.addDebugLogs(result);
}
this.logger.debug('no existing meeting found, proceeding');
// 5) Match participants to existing contacts
this.logger.debug(`total participants from API: ${meetingData.participants.length}`);
meetingData.participants.forEach((p, idx) => {
this.logger.debug(`participant ${idx + 1}: name="${p.name}" email="${p.email || 'none'}"`);
});
const { matchedContacts, unmatchedParticipants } = await twentyService.matchParticipantsToContacts(
meetingData.participants
);
this.logger.debug(`matched=${matchedContacts.length} unmatched=${unmatchedParticipants.length}`);
unmatchedParticipants.forEach((p, idx) => {
this.logger.debug(`unmatched ${idx + 1}: name="${p.name}" email="${p.email || 'none'}"`);
});
// 6) Optionally create contacts
const autoCreate = shouldAutoCreateContacts();
const newContactIds = autoCreate
? await twentyService.createContactsForUnmatched(unmatchedParticipants)
: [];
result.newContacts = newContactIds;
this.logger.debug(`autoCreate=${autoCreate} createdContacts=${newContactIds.length}`);
// 7) Create note first (so we can link to it from the meeting)
const allContactIds = [...matchedContacts.map(({ id }) => id), ...newContactIds];
const noteBody = MeetingFormatter.formatNoteBody(meetingData);
const noteId = await twentyService.createNoteOnly(
`Meeting: ${meetingData.title}`,
noteBody
);
result.noteIds = [noteId];
this.logger.debug(`created note id=${noteId}`);
// 8) Create meeting with direct relationship to the note
const meetingInput = MeetingFormatter.toMeetingCreateInput(meetingData, noteId);
this.logger.debug(`meeting duration: ${meetingData.duration} min (raw from API) → ${meetingInput.duration} min (rounded)`);
result.meetingId = await twentyService.createMeeting(meetingInput);
this.logger.debug(`created meeting id=${result.meetingId} with noteId=${noteId}`);
// 9) Link note to participants (Meeting link is handled via the relation field)
await this.linkNoteToParticipants(
twentyService,
noteId,
allContactIds
);
this.logger.debug(`linked note to ${allContactIds.length} participants`);
result.success = true;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
this.logger.error(`error: ${message}`);
result.errors?.push(message);
// Try to create a failed meeting record for tracking
await this.createFailedMeetingRecord(params, message);
}
return this.addDebugLogs(result);
}
private parsePayload(params: unknown): { payload: FirefliesWebhookPayload; extractedHeaders?: Record<string, string> } {
let normalizedParams = params;
let extractedHeaders: Record<string, string> | undefined;
// Handle string-encoded params
if (typeof normalizedParams === 'string') {
this.logger.debug(`received params as string length=${normalizedParams.length}`);
try {
const parsed = JSON.parse(normalizedParams);
normalizedParams = parsed;
if (parsed && typeof parsed === 'object') {
const parsedKeys = Object.keys(parsed as Record<string, unknown>);
this.logger.debug(`parsed params keys: ${parsedKeys.join(',') || 'none'}`);
}
} catch (parseError) {
this.logger.error(`error parsing string params: ${String(parseError)}`);
throw new Error('Invalid or missing webhook payload');
}
}
// Handle wrapped payloads and extract headers if present
let payload: FirefliesWebhookPayload | undefined;
if (isValidFirefliesPayload(normalizedParams)) {
payload = normalizedParams as FirefliesWebhookPayload;
} else if (normalizedParams && typeof normalizedParams === 'object') {
const wrapper = normalizedParams as Record<string, unknown>;
// Extract headers if present in wrapper
if (wrapper.headers && typeof wrapper.headers === 'object' && !Array.isArray(wrapper.headers)) {
extractedHeaders = wrapper.headers as Record<string, string>;
const headerKeys = Object.keys(extractedHeaders);
this.logger.debug(`extracted headers from wrapper: ${headerKeys.join(',')}`);
}
const wrapperKeys = ['params', 'payload', 'body', 'data', 'event'];
for (const key of wrapperKeys) {
const candidate = wrapper[key];
if (isValidFirefliesPayload(candidate)) {
this.logger.debug(`detected payload under wrapper key "${key}"`);
payload = candidate as FirefliesWebhookPayload;
break;
}
}
}
if (!payload) {
this.logger.error('error: Invalid or missing webhook payload');
throw new Error('Invalid or missing webhook payload');
}
// Log payload keys for debugging
const payloadRecord = payload as Record<string, unknown>;
const payloadKeys = Object.keys(payloadRecord);
if (payloadKeys.length > 0) {
this.logger.debug(`payload keys: ${payloadKeys.join(',')}`);
}
return { payload, extractedHeaders };
}
private verifySignature(
payload: FirefliesWebhookPayload,
headers: Record<string, string> | undefined,
webhookSecret: string
): void {
// Extract headers
const normalizedHeaders = headers || {};
const headerKeys = Object.keys(normalizedHeaders);
if (headerKeys.length > 0) {
this.logger.debug(`header keys: ${headerKeys.join(',')}`);
}
this.debug.push(`headerKeys=${headerKeys.join(',') || 'none'}`);
const headerSignature = Object.entries(normalizedHeaders).find(
([key]) => key.toLowerCase() === 'x-hub-signature',
)?.[1];
const payloadRecord = payload as Record<string, unknown>;
const payloadSignature =
typeof payloadRecord['x-hub-signature'] === 'string'
? (payloadRecord['x-hub-signature'] as string)
: undefined;
if (payloadSignature) {
this.logger.debug('found signature inside payload');
}
const signature =
(typeof headerSignature === 'string' ? headerSignature : undefined) || payloadSignature;
const payloadForSignature =
payloadSignature && 'x-hub-signature' in payloadRecord
? Object.fromEntries(
Object.entries(payloadRecord).filter(
([key]) => key.toLowerCase() !== 'x-hub-signature',
),
)
: payloadRecord;
const body =
typeof normalizedHeaders['body'] === 'string'
? normalizedHeaders['body']
: JSON.stringify(payloadForSignature);
const signatureCheck = verifyWebhookSignature(body, signature, webhookSecret);
if (!signatureCheck.isValid) {
this.debug.push(
`signatureProvided=${Boolean(signature)}`,
`signatureMatched=${signatureCheck.isValid}`,
`webhookSecretFingerprint=${getWebhookSecretFingerprint(webhookSecret)}`
);
this.logger.debug(
`signature check failed. headerPresent=${Boolean(
headerSignature,
)} payloadSignaturePresent=${Boolean(payloadSignature)}`,
);
this.logger.debug(`provided signature present=${Boolean(signature)}`);
this.logger.critical('Invalid webhook signature - potential security threat detected in production');
throw new Error('Invalid webhook signature');
}
}
private async linkNoteToParticipants(
twentyService: TwentyCrmService,
noteId: string,
contactIds: string[]
): Promise<void> {
for (const contactId of contactIds) {
try {
await twentyService.createNoteTarget(noteId, contactId);
this.logger.debug(`linked note ${noteId} to person ${contactId}`);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
this.logger.error(`failed to link note to person ${contactId}: ${message}`);
}
}
}
private async createFailedMeetingRecord(params: unknown, error: string): Promise<void> {
try {
const twentyApiKey = process.env.TWENTY_API_KEY || '';
if (!twentyApiKey) {
this.logger.debug('Cannot create failed meeting record: TWENTY_API_KEY not configured');
return;
}
let meetingId = 'unknown';
let meetingTitle = 'Unknown Meeting';
const { payload } = this.parsePayload(params);
if (payload?.meetingId) {
meetingId = payload.meetingId;
const firefliesApiKey = process.env.FIREFLIES_API_KEY || '';
if (firefliesApiKey) {
try {
const firefliesClient = new FirefliesApiClient(firefliesApiKey);
const meetingData = await firefliesClient.fetchMeetingData(meetingId);
meetingTitle = meetingData.title || meetingTitle;
} catch (fetchError) {
this.logger.debug(
`Could not fetch meeting title: ${
fetchError instanceof Error ? fetchError.message : 'Unknown error'
}`,
);
}
}
}
const twentyService = new TwentyCrmService(twentyApiKey, getApiUrl());
const failedMeetingData = MeetingFormatter.toFailedMeetingCreateInput(
meetingId,
meetingTitle,
error
);
const failedMeetingId = await twentyService.createFailedMeeting(failedMeetingData);
this.logger.debug(`Created failed meeting record: ${failedMeetingId}`);
} catch (recordError) {
this.logger.error(
`Failed to create failed meeting record: ${
recordError instanceof Error ? recordError.message : 'Unknown error'
}`,
);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -3,19 +3,21 @@
Updates Last interaction and Interaction status fields based on last email date
## Requirements
- twenty-cli `npm install -g twenty-cli`
- an `apiKey`. Go to `https://twenty.com/settings/api-webhooks` to generate one
- an `apiKey` - go to Settings > API & Webhooks to generate one
## Setup
1. Add and synchronize app
```bash
twenty auth login
cd last_email_interaction
twenty app sync
cd packages/twenty-apps/community/last-email-interaction
yarn auth
yarn sync
```
2. Go to Settings > Integrations > Last email interaction > Settings and add required variables
## Flow
- Checks if fields are created, if not, creates them on fly
- Extracts the datetime of message and calculates the last interaction status
- Fetches all users and companies connected to them and updates their Last interaction and Interaction status fields
- Fetches all users and companies connected to them and updates their Last interaction and Interaction status fields
## Todo:
- update app with generated Twenty object once extending objects is possible
@@ -1,10 +1,11 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
import { type ApplicationConfig } from 'twenty-sdk';
const config: ApplicationConfig = {
universalIdentifier: '718ed9ab-53fc-49c8-8deb-0cff78ecf0d2',
displayName: 'Last email interaction',
description:
'Updates Last interaction and Interaction status fields based on last received email',
icon: "IconMailFast",
applicationVariables: {
TWENTY_API_KEY: {
universalIdentifier: 'aae3f523-4c1f-4805-b3ee-afeb676c381e',
@@ -10,9 +10,19 @@
"packageManager": "yarn@4.9.2",
"dependencies": {
"axios": "^1.12.2",
"twenty-sdk": "0.0.4"
"twenty-sdk": "0.2.4"
},
"devDependencies": {
"@types/node": "^24.7.2"
},
"scripts": {
"auth": "twenty auth login",
"generate": "twenty app generate",
"dev": "twenty app dev",
"sync": "twenty app sync",
"uninstall": "twenty app uninstall",
"logs": "twenty app logs",
"create-entity": "twenty app add",
"help": "twenty --help"
}
}
@@ -1,277 +0,0 @@
import axios from 'axios';
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
const TWENTY_API_KEY = process.env.TWENTY_API_KEY ?? '';
const TWENTY_URL =
process.env.TWENTY_API_URL !== '' && process.env.TWENTY_API_URL !== undefined
? `${process.env.TWENTY_API_URL}/rest`
: 'https://api.twenty.com/rest';
const create_last_interaction = (id: string) => {
return {
method: 'POST',
url: `${TWENTY_URL}/metadata/fields`,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
data: {
type: 'DATE_TIME',
objectMetadataId: `${id}`,
name: 'lastInteraction',
label: 'Last interaction',
description: 'Date when the last interaction happened',
icon: 'IconCalendarClock',
defaultValue: null,
isNullable: true,
settings: {},
},
};
};
const create_interaction_status = (id: string) => {
return {
method: 'POST',
url: `${TWENTY_URL}/metadata/fields`,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
data: {
type: 'SELECT',
objectMetadataId: `${id}`,
name: 'interactionStatus',
label: 'Interaction status',
description: 'Indicates the health of relation',
icon: 'IconProgress',
defaultValue: null,
isNullable: true,
settings: {},
options: [
{
color: 'green',
label: 'Recent',
value: 'RECENT',
position: 1,
},
{
color: 'yellow',
label: 'Active',
value: 'ACTIVE',
position: 2,
},
{
color: 'sky',
label: 'Cooling',
value: 'COOLING',
position: 3,
},
{
color: 'gray',
label: 'Dormant',
value: 'DORMANT',
position: 4,
},
],
},
};
};
const calculateStatus = (date: string) => {
const day = 1000 * 60 * 60 * 24;
const now = Date.now();
const messageDate = Date.parse(date);
const deltaTime = now - messageDate;
return deltaTime < 7 * day
? 'RECENT'
: deltaTime < 30 * day
? 'ACTIVE'
: deltaTime < 90 * day
? 'COOLING'
: 'DORMANT';
};
const interactionData = (date: string, status: string) => {
return {
lastInteraction: date,
interactionStatus: status,
};
};
const updateInteractionStatus = async (objectName: string, id: string, messageDate: string, status: string) => {
const options = {
method: 'PATCH',
url: `${TWENTY_URL}/${objectName}/${id}`,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
data: {
lastInteraction: messageDate,
interactionStatus: status
}
};
try {
const response = await axios.request(options);
if (response.status === 200) {
console.log('Successfully updated company last interaction field');
}
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
throw error;
}
}
const fetchRelatedCompanyId = async (id: string) => {
const options = {
method: 'GET',
url: `${TWENTY_URL}/people/${id}`,
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
};
try {
const req = await axios.request(options);
if (req.status === 200 && req.data.person.companyId !== null && req.data.person.companyId !== undefined) {
return req.data.person.companyId;
}
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
throw error;
}
}
export const main = async (params: {
properties: Record<string, any>;
recordId: string;
userId: string;
}): Promise<object | undefined> => {
if (TWENTY_API_KEY === '') {
console.log("Function exited as API key or URL hasn't been set properly");
return {};
}
const { properties, recordId } = params;
// Check if fields are created
const options = {
method: 'GET',
url: `${TWENTY_URL}/metadata/objects`,
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
};
try {
const response = await axios.request(options);
const objects = response.data.data.objects;
const company_object = objects.find(
(object: any) => object.nameSingular === 'company',
);
const company_last_interaction = company_object.fields.find(
(field: any) => field.name === 'lastInteraction',
);
const company_interaction_status = company_object.fields.find(
(field: any) => field.name === 'interactionStatus',
);
const person_object = objects.find(
(object: any) => object.nameSingular === 'person',
);
const person_last_interaction = person_object.fields.find(
(field: any) => field.name === 'lastInteraction',
);
const person_interaction_status = person_object.fields.find(
(field: any) => field.name === 'interactionStatus',
);
// If not, create them
if (company_last_interaction === undefined) {
const response2 = await axios.request(
create_last_interaction(company_object.id),
);
if (response2.status === 201) {
console.log('Successfully created company last interaction field');
}
}
if (company_interaction_status === undefined) {
const response2 = await axios.request(
create_interaction_status(company_object.id),
);
if (response2.status === 201) {
console.log('Successfully created company interaction status field');
}
}
if (person_last_interaction === undefined) {
const response2 = await axios.request(
create_last_interaction(person_object.id),
);
if (response2.status === 201) {
console.log('Successfully created person last interaction field');
}
}
if (person_interaction_status === undefined) {
const response2 = await axios.request(
create_interaction_status(person_object.id),
);
if (response2.status === 201) {
console.log('Successfully created person interaction status field');
}
}
// Extract the timestamp of message
const messageDate = properties.after.receivedAt;
const interactionStatus = calculateStatus(messageDate);
// Get the details of person and related company
const messageOptions = {
method: 'GET',
url: `${TWENTY_URL}/messages/${recordId}?depth=1`,
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
};
const messageDetails = await axios.request(messageOptions);
const peopleIds: string[] = [];
for (const participant of messageDetails.data.messages
.messageParticipants) {
peopleIds.push(participant.personId);
}
const companiesIds = [];
for (const id of peopleIds) {
companiesIds.push(await fetchRelatedCompanyId(id));
}
// Update the field value depending on the timestamp
for (const id of peopleIds) {
await updateInteractionStatus("people", id, messageDate, interactionStatus);
}
for (const id of companiesIds) {
await updateInteractionStatus("companies", id, messageDate, interactionStatus);
}
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(error.message);
return {};
}
console.error(error);
return {};
}
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: '683966a0-b60a-424e-86b1-7448c9191bde',
name: 'test',
triggers: [
{
universalIdentifier: 'f4f1e127-87f0-4dcf-99fe-8061adf5cbe6',
type: 'databaseEvent',
eventName: 'message.created',
},
{
universalIdentifier: '4c17878f-b6b3-4d0a-8de6-967b1cb55002',
type: 'databaseEvent',
eventName: 'message.updated',
},
],
};
@@ -0,0 +1,270 @@
import axios from 'axios';
import { type FunctionConfig } from 'twenty-sdk';
const TWENTY_API_KEY = process.env.TWENTY_API_KEY ?? '';
const TWENTY_URL =
process.env.TWENTY_API_URL !== '' && process.env.TWENTY_API_URL !== undefined
? `${process.env.TWENTY_API_URL}/rest`
: 'https://api.twenty.com/rest';
const create_last_interaction = (id: string) => {
return {
method: 'POST',
url: `${TWENTY_URL}/metadata/fields`,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
data: {
type: 'DATE_TIME',
objectMetadataId: `${id}`,
name: 'lastInteraction',
label: 'Last interaction',
description: 'Date when the last interaction happened',
icon: 'IconCalendarClock',
defaultValue: null,
isNullable: true,
settings: {},
},
};
};
const create_interaction_status = (id: string) => {
return {
method: 'POST',
url: `${TWENTY_URL}/metadata/fields`,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
data: {
type: 'SELECT',
objectMetadataId: `${id}`,
name: 'interactionStatus',
label: 'Interaction status',
description: 'Indicates the health of relation',
icon: 'IconProgress',
defaultValue: null,
isNullable: true,
settings: {},
options: [
{
color: 'green',
label: 'Recent',
value: 'RECENT',
position: 1,
},
{
color: 'yellow',
label: 'Active',
value: 'ACTIVE',
position: 2,
},
{
color: 'sky',
label: 'Cooling',
value: 'COOLING',
position: 3,
},
{
color: 'gray',
label: 'Dormant',
value: 'DORMANT',
position: 4,
},
],
},
};
};
const calculateStatus = (date: string) => {
const day = 1000 * 60 * 60 * 24;
const now = Date.now();
const messageDate = Date.parse(date);
const deltaTime = now - messageDate;
return deltaTime < 7 * day
? 'RECENT'
: deltaTime < 30 * day
? 'ACTIVE'
: deltaTime < 90 * day
? 'COOLING'
: 'DORMANT';
};
const updateInteractionStatus = async (objectName: string, id: string, messageDate: string, status: string) => {
const options = {
method: 'PATCH',
url: `${TWENTY_URL}/${objectName}/${id}`,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
data: {
lastInteraction: messageDate,
interactionStatus: status
}
};
try {
const response = await axios.request(options);
if (response.status === 200) {
console.log('Successfully updated company last interaction field');
}
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
throw error;
}
}
const fetchRelatedCompanyId = async (id: string) => {
const options = {
method: 'GET',
url: `${TWENTY_URL}/people/${id}`,
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
};
try {
const req = await axios.request(options);
if (req.status === 200 && req.data.person.companyId !== null && req.data.person.companyId !== undefined) {
return req.data.person.companyId;
}
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
throw error;
}
}
export const main = async (params: {
properties: Record<string, any>;
recordId: string;
userId: string;
}): Promise<object | undefined> => {
if (TWENTY_API_KEY === '') {
console.log("Function exited as API key or URL hasn't been set properly");
return {};
}
const { properties, recordId } = params;
// Check if fields are created
const options = {
method: 'GET',
url: `${TWENTY_URL}/metadata/objects`,
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
};
try {
const response = await axios.request(options);
const objects = response.data.data.objects;
const company_object = objects.find(
(object: any) => object.nameSingular === 'company',
);
const company_last_interaction = company_object.fields.find(
(field: any) => field.name === 'lastInteraction',
);
const company_interaction_status = company_object.fields.find(
(field: any) => field.name === 'interactionStatus',
);
const person_object = objects.find(
(object: any) => object.nameSingular === 'person',
);
const person_last_interaction = person_object.fields.find(
(field: any) => field.name === 'lastInteraction',
);
const person_interaction_status = person_object.fields.find(
(field: any) => field.name === 'interactionStatus',
);
// If not, create them
if (company_last_interaction === undefined) {
const response2 = await axios.request(
create_last_interaction(company_object.id),
);
if (response2.status === 201) {
console.log('Successfully created company last interaction field');
}
}
if (company_interaction_status === undefined) {
const response2 = await axios.request(
create_interaction_status(company_object.id),
);
if (response2.status === 201) {
console.log('Successfully created company interaction status field');
}
}
if (person_last_interaction === undefined) {
const response2 = await axios.request(
create_last_interaction(person_object.id),
);
if (response2.status === 201) {
console.log('Successfully created person last interaction field');
}
}
if (person_interaction_status === undefined) {
const response2 = await axios.request(
create_interaction_status(person_object.id),
);
if (response2.status === 201) {
console.log('Successfully created person interaction status field');
}
}
// Extract the timestamp of message
const messageDate = properties.after.receivedAt;
const interactionStatus = calculateStatus(messageDate);
// Get the details of person and related company
const messageOptions = {
method: 'GET',
url: `${TWENTY_URL}/messages/${recordId}?depth=1`,
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
};
const messageDetails = await axios.request(messageOptions);
const peopleIds: string[] = [];
for (const participant of messageDetails.data.messages
.messageParticipants) {
peopleIds.push(participant.personId);
}
const companiesIds = [];
for (const id of peopleIds) {
companiesIds.push(await fetchRelatedCompanyId(id));
}
// Update the field value depending on the timestamp
for (const id of peopleIds) {
await updateInteractionStatus("people", id, messageDate, interactionStatus);
}
for (const id of companiesIds) {
await updateInteractionStatus("companies", id, messageDate, interactionStatus);
}
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(error.message);
return {};
}
console.error(error);
return {};
}
};
export const config: FunctionConfig = {
universalIdentifier: '683966a0-b60a-424e-86b1-7448c9191bde',
name: 'test',
triggers: [
{
universalIdentifier: 'f4f1e127-87f0-4dcf-99fe-8061adf5cbe6',
type: 'databaseEvent',
eventName: 'message.created',
},
{
universalIdentifier: '4c17878f-b6b3-4d0a-8de6-967b1cb55002',
type: 'databaseEvent',
eventName: 'message.updated',
},
],
};
File diff suppressed because it is too large Load Diff
@@ -12,19 +12,28 @@ function App() {
useEffect(() => {
browser.tabs.query({ active: true, currentWindow: true }, function(tabs) {
const currentTab = tabs[0];
if(currentTab.url?.includes('https://www.linkedin.com/in')) {
sendMessage('getPersonviaRelay').then(data => {
setValue({...data, type: 'person' })
})
}
if(currentTab.url?.includes('https://www.linkedin.com/company')) {
sendMessage('getCompanyviaRelay').then(data => {
setValue({...data, type: 'company'})
})
if (!currentTab.url) {
return;
}
let url = new URL(currentTab.url);
const isLinkedinHost =
url.protocol === 'https:' && url.hostname === 'www.linkedin.com';
if (isLinkedinHost && url.pathname.startsWith('/in/')) {
sendMessage('getPersonviaRelay').then((data) => {
setValue({ ...data, type: 'person' });
});
}
if (isLinkedinHost && url.pathname.startsWith('/company/')) {
sendMessage('getCompanyviaRelay').then((data) => {
setValue({ ...data, type: 'company' });
});
}
});
}, []);
const isPersonValue = (val: Value): val is PersonValue => {
@@ -38,25 +47,29 @@ function App() {
return (
<StyledMain>
<h1>{JSON.stringify(value)}</h1>
{
isPersonValue(value) &&
<button onClick={async () => {
await sendMessage('createPerson', {
firstName: value.firstName,
lastName: value.lastName,
});
}}>save person to twenty</button>
}
{
isCompanyValue(value) &&
<button onClick={async () => {
await sendMessage('createCompany', {
name: value.companyName
});
}}>save company to twenty</button>
}
{isPersonValue(value) && (
<button
onClick={async () => {
await sendMessage('createPerson', {
firstName: value.firstName,
lastName: value.lastName,
});
}}
>
save person to twenty
</button>
)}
{isCompanyValue(value) && (
<button
onClick={async () => {
await sendMessage('createCompany', {
name: value.companyName,
});
}}
>
save company to twenty
</button>
)}
</StyledMain>
);
}
@@ -3,16 +3,15 @@
Synchronizing contacts between Twenty and Mailchimp
## Requirements
- twenty-cli `npm install -g twenty-cli`
- an `apiKey`. Go to `https://twenty.com/settings/api-webhooks` to generate one
- Mailchimp API key - Mailchimp > avatar in top right corner > Profile > Extras > API keys
## Setup
1. Add app to your workspace
```bash
twenty auth login
cd mailchimp-synchronizer
twenty app sync
cd packages/twenty-apps/community/mailchimp-synchronizer
yarn auth
yarn generate
yarn sync
```
2. Go to Settings > Integrations > Mailchimp synchronizer > Settings and add required variables
@@ -1,4 +1,4 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
import { type ApplicationConfig } from 'twenty-sdk';
const config: ApplicationConfig = {
universalIdentifier: '1eadac4e-db9f-4cce-b20b-de75f41e34dc',
@@ -6,16 +6,6 @@ const config: ApplicationConfig = {
description: 'Synchronizes Twenty contacts in Mailchimp',
icon: "IconMailFast",
applicationVariables: {
TWENTY_API_KEY: {
universalIdentifier: '0af17af3-66b8-40cf-b6e2-6a29a1da5464',
isSecret: true,
description: 'Required to send requests to Twenty',
},
TWENTY_API_URL: {
universalIdentifier: '12949c1c-aed7-4a9f-bd06-9fd15f0bfa63',
isSecret: false,
description: 'Optional, defaults to cloud API URL',
},
MAILCHIMP_API_KEY: {
universalIdentifier: 'f10d4e8a-8055-4eb2-b9ad-efd69d43b1f0',
isSecret: true,
@@ -10,9 +10,19 @@
"packageManager": "yarn@4.9.2",
"dependencies": {
"axios": "^1.13.2",
"twenty-sdk": "0.0.4"
"twenty-sdk": "0.2.4"
},
"devDependencies": {
"@types/node": "^24.7.2"
},
"scripts": {
"auth": "twenty auth login",
"generate": "twenty app generate",
"dev": "twenty app dev",
"sync": "twenty app sync",
"uninstall": "twenty app uninstall",
"logs": "twenty app logs",
"create-entity": "twenty app add",
"help": "twenty --help"
}
}
@@ -1,454 +0,0 @@
import axios from 'axios';
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
const TWENTY_API_URL: string =
process.env.TWENTY_API_URL !== '' && process.env.TWENTY_API_URL !== undefined
? `${process.env.TWENTY_API_URL}/rest`
: 'https://api.twenty.com/rest';
const TWENTY_API_KEY: string = process.env.TWENTY_API_KEY ?? '';
const MAILCHIMP_API_URL: string =
process.env.MAILCHIMP_SERVER_PREFIX !== '' &&
process.env.MAILCHIMP_SERVER_PREFIX !== undefined
? `https://${process.env.MAILCHIMP_SERVER_PREFIX}.api.mailchimp.com/3.0/`
: '';
const MAILCHIMP_API_KEY: string = process.env.MAILCHIMP_API_KEY ?? '';
const MAILCHIMP_AUDIENCE_ID: string = process.env.MAILCHIMP_AUDIENCE_ID ?? '';
const IS_EMAIL_CONSTRAINT: boolean = process.env.IS_EMAIL_CONSTRAINT === 'true';
const IS_COMPANY_CONSTRAINT: boolean =
process.env.COMPANY_CONSTRAINT === 'true';
const IS_PHONE_CONSTRAINT: boolean = process.env.IS_PHONE_CONSTRAINT === 'true';
const IS_ADDRESS_CONSTRAINT: boolean =
process.env.IS_ADDRESS_CONSTRAINT === 'true';
const UPDATE_PERSON: boolean = process.env.UPDATE_PERSON === 'true';
type mailchimpAddress = {
street1: string;
street2: string;
city: string;
state: string;
zipCode: string;
country: string;
};
type mailchimpRecord = {
id?: string;
email_channel?: {
email: string;
marketing_consent?: {
status: string;
};
};
sms_channel?: {
sms_phone: string;
marketing_consent?: {
status: string;
};
};
mergeFields: {
FNAME: string;
LNAME: string;
ADDRESS: string | mailchimpAddress;
COMPANY: string;
PHONE: string;
};
};
type twentyAddress = {
addressStreet1: string;
addressStreet2: string;
addressCity: string;
addressState: string;
addressPostCode: string;
addressCountry: string;
};
type twentyCompany = {
name: string;
address: twentyAddress;
};
type twentyPerson = {
name: {
firstName: string;
lastName: string;
};
emails: {
primaryEmail: string;
};
phones: {
primaryPhoneNumber: string;
primaryPhoneCallingCode: string;
};
companyId: string | null;
};
const fetchCompanyData = async (companyId: string): Promise<twentyCompany> => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
url: `${TWENTY_API_URL}/company/${companyId}`,
};
try {
const response = await axios.request(options);
return response.status === 200
? ({
name: response.data.name as string,
address: response.data.address as twentyAddress,
} as twentyCompany)
: ({} as twentyCompany);
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
throw error;
}
};
const checkAddress = (address: twentyAddress): mailchimpAddress => {
if (
address.addressStreet1 !== '' &&
address.addressCity !== '' &&
address.addressPostCode !== '' &&
address.addressState !== ''
) {
return {
street1: address.addressStreet1,
street2: address.addressStreet2,
city: address.addressCity,
state: address.addressState,
zipCode: address.addressPostCode,
country: address.addressCountry,
} as mailchimpAddress;
}
throw new Error('Invalid address');
};
const checkAudiencePermissions = async (
audienceId: string,
): Promise<string[] | undefined> => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
},
url: `${MAILCHIMP_API_URL}/audiences/${audienceId}`,
};
try {
const temp = await axios.request(options);
return temp.data.enabled_channels;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const prepareData = (
firstName: string,
lastName: string,
email: string,
phoneNumber: string,
phoneCallingCode: string,
companyName: string,
address: mailchimpAddress | string,
): mailchimpRecord => {
let data = {
mergeFields: {},
} as mailchimpRecord;
data.mergeFields.FNAME = firstName;
data.mergeFields.LNAME = lastName;
if (IS_EMAIL_CONSTRAINT) {
data.email_channel = {
email: email,
marketing_consent: {
status: 'unknown',
},
};
}
if (IS_ADDRESS_CONSTRAINT) {
data.mergeFields.ADDRESS = address;
}
if (IS_PHONE_CONSTRAINT) {
const mergedPhoneNumber: string = phoneCallingCode.startsWith('+')
? phoneCallingCode.concat(phoneNumber)
: '+'.concat(phoneCallingCode, phoneNumber);
data['sms_channel'] = {
sms_phone: mergedPhoneNumber,
marketing_consent: {
status: 'unknown',
},
};
data['mergeFields']['PHONE'] = mergedPhoneNumber;
}
if (IS_COMPANY_CONSTRAINT) {
data['mergeFields']['COMPANY'] = companyName;
}
return data;
};
const addTwentyPersonToMailchimp = async (
convertedRecord: mailchimpRecord,
): Promise<boolean | undefined> => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
},
url: `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts`,
data: convertedRecord,
};
try {
const response = await axios.request(options);
return response.status === 200;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const checkIfTwentyPersonExistsInMailchimp = async (
email?: string,
phoneNumber?: string,
cursor?: string,
) => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
},
url: cursor
? `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts?count%3D1000%26cursor%3D${cursor}`
: `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts?count%3D1000`,
};
try {
const response = await axios.request(options);
const doesPersonExist: mailchimpRecord | undefined =
(response.data.contacts.find(
(contact: any) => contact.email_channel.email === email,
) as mailchimpRecord) ||
(response.data.contacts.find(
(contact: any) => contact.sms_channel.sms_phone === phoneNumber,
) as mailchimpRecord);
if (doesPersonExist !== undefined) {
return doesPersonExist;
}
if (response.data.next_cursor === undefined) {
return undefined;
} else {
await checkIfTwentyPersonExistsInMailchimp(
email,
phoneNumber,
response.data.next_cursor,
);
}
return undefined;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const compareTwoRecords = (
object1: mailchimpRecord,
object2: mailchimpRecord,
) => {
return (
object1.email_channel?.email === object2.email_channel?.email &&
object1.sms_channel?.sms_phone === object2.sms_channel?.sms_phone &&
object1.mergeFields.FNAME === object2.mergeFields.FNAME &&
object1.mergeFields.LNAME === object2.mergeFields.LNAME &&
object1.mergeFields.ADDRESS === object2.mergeFields.ADDRESS &&
object1.mergeFields.COMPANY === object2.mergeFields.COMPANY
);
};
const updateTwentyPersonInMailchimp = async (
mailchimpRecordId: string,
twentyConvertedRecord: mailchimpRecord,
): Promise<boolean | undefined> => {
const options = {
method: 'PATCH',
headers: {
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts/${mailchimpRecordId}`,
data: twentyConvertedRecord,
};
try {
const response = await axios.request(options);
return response.status === 200;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
export const main = async (params: {
properties: Record<string, any>;
recordId: string;
userId: string;
}): Promise<object | undefined> => {
if (!IS_EMAIL_CONSTRAINT && !IS_PHONE_CONSTRAINT) {
console.warn(
'Function exited as there are no constraints to email nor phone number',
);
return {};
}
if (
MAILCHIMP_API_URL === '' ||
MAILCHIMP_API_KEY === '' ||
MAILCHIMP_AUDIENCE_ID === ''
) {
console.warn('Missing Mailchimp required parameters');
return {};
}
if (IS_COMPANY_CONSTRAINT && TWENTY_API_KEY === '') {
console.warn('Missing Twenty related parameters');
return {};
}
try {
const { properties } = params;
const twentyRecord: twentyPerson = properties.after as twentyPerson;
if (
twentyRecord.name.firstName === '' ||
twentyRecord.name.lastName === ''
) {
throw new Error('First or last name is empty');
}
const audiencePermissions: string[] | undefined =
await checkAudiencePermissions(MAILCHIMP_AUDIENCE_ID);
if (
IS_EMAIL_CONSTRAINT &&
audiencePermissions?.includes('Email') &&
twentyRecord.emails.primaryEmail === ''
) {
throw new Error('Email is empty');
}
if (
IS_PHONE_CONSTRAINT &&
audiencePermissions?.includes('SMS') &&
(twentyRecord.phones.primaryPhoneNumber === '' ||
twentyRecord.phones.primaryPhoneCallingCode === '')
) {
throw new Error('Phone number is empty');
}
let companyName: string = '';
let address: mailchimpAddress | string = '';
if (IS_COMPANY_CONSTRAINT) {
if (twentyRecord.companyId === null) {
throw new Error('Missing relation to company record');
}
const company: twentyCompany = await fetchCompanyData(
twentyRecord.companyId,
);
companyName = company.name ?? ''; // either "" or name
address = IS_ADDRESS_CONSTRAINT ? checkAddress(company.address) : '';
}
const twentyPersonToMailchimpRecord: mailchimpRecord = prepareData(
twentyRecord.name.firstName,
twentyRecord.name.lastName,
twentyRecord.emails.primaryEmail,
twentyRecord.phones.primaryPhoneNumber,
twentyRecord.phones.primaryPhoneCallingCode,
companyName,
address,
);
console.log(twentyPersonToMailchimpRecord);
const isTwentyPersonInMailchimp: mailchimpRecord | undefined =
await checkIfTwentyPersonExistsInMailchimp(
twentyRecord.emails.primaryEmail,
twentyPersonToMailchimpRecord.sms_channel?.sms_phone,
);
if (isTwentyPersonInMailchimp !== undefined) {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} found in Mailchimp`,
);
if (UPDATE_PERSON) {
if (
!compareTwoRecords(
isTwentyPersonInMailchimp,
twentyPersonToMailchimpRecord,
) &&
isTwentyPersonInMailchimp.id
) {
const isTwentyPersonUpdatedInMailchimp: boolean | undefined =
await updateTwentyPersonInMailchimp(
isTwentyPersonInMailchimp.id,
twentyPersonToMailchimpRecord,
);
if (!isTwentyPersonUpdatedInMailchimp) {
throw new Error(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} update in Mailchimp failed`,
);
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} update in Mailchimp succeeded`,
);
}
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} wasn't updated in Mailchimp because they're the same`,
);
}
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} wasn't updated in Mailchimp because UPDATE_PERSON is set to false`,
);
}
} else {
console.log(
`${twentyRecord.name.firstName} ${twentyRecord.name.lastName} doesn't exist in Mailchimp, adding`,
);
const isTwentyPersonAddedToMailchimp: boolean | undefined =
await addTwentyPersonToMailchimp(twentyPersonToMailchimpRecord);
if (!isTwentyPersonAddedToMailchimp) {
throw new Error(
`Adding ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} person to Mailchimp failed`,
);
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} has been successfully added`,
);
}
}
return {};
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(error.response);
return {};
}
console.error(error);
return {};
}
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: '83319670-775b-4862-b133-5c353e594151',
name: 'mailchimp-synchronizer',
triggers: [
{
universalIdentifier: 'e627ff6f-0a0c-48b2-bdbb-31967489ec96',
type: 'databaseEvent',
eventName: 'person.created',
},
{
universalIdentifier: '657ece26-4478-4408-a257-4e9e16cce279',
type: 'databaseEvent',
eventName: 'person.updated',
},
],
};
@@ -0,0 +1,447 @@
import axios from 'axios';
import {
type DatabaseEventPayload,
type FunctionConfig,
type ObjectRecordCreateEvent,
type ObjectRecordUpdateEvent,
} from 'twenty-sdk';
import Twenty, { type Person } from '../generated';
const MAILCHIMP_API_URL: string =
process.env.MAILCHIMP_SERVER_PREFIX !== '' &&
process.env.MAILCHIMP_SERVER_PREFIX !== undefined
? `https://${process.env.MAILCHIMP_SERVER_PREFIX}.api.mailchimp.com/3.0/`
: '';
const MAILCHIMP_API_KEY: string = process.env.MAILCHIMP_API_KEY ?? '';
const MAILCHIMP_AUDIENCE_ID: string = process.env.MAILCHIMP_AUDIENCE_ID ?? '';
const IS_EMAIL_CONSTRAINT: boolean = process.env.IS_EMAIL_CONSTRAINT === 'true';
const IS_COMPANY_CONSTRAINT: boolean =
process.env.COMPANY_CONSTRAINT === 'true';
const IS_PHONE_CONSTRAINT: boolean = process.env.IS_PHONE_CONSTRAINT === 'true';
const IS_ADDRESS_CONSTRAINT: boolean =
process.env.IS_ADDRESS_CONSTRAINT === 'true';
const UPDATE_PERSON: boolean = process.env.UPDATE_PERSON === 'true';
type mailchimpAddress = {
street1: string;
street2: string;
city: string;
state: string;
zipCode: string;
country: string;
};
type mailchimpRecord = {
id?: string;
email_channel?: {
email: string;
marketing_consent?: {
status: string;
};
};
sms_channel?: {
sms_phone: string;
marketing_consent?: {
status: string;
};
};
mergeFields: {
FNAME: string;
LNAME: string;
ADDRESS: string | mailchimpAddress;
COMPANY: string;
PHONE: string;
};
};
type twentyAddress = {
addressStreet1: string;
addressStreet2: string;
addressCity: string;
addressState: string;
addressPostCode: string;
addressCountry: string;
};
type twentyCompany = {
name: string;
address: twentyAddress;
};
type twentyPerson = {
name: {
firstName: string;
lastName: string;
};
emails: {
primaryEmail: string;
};
phones: {
primaryPhoneNumber: string;
primaryPhoneCallingCode: string;
};
companyId: string | null;
};
type DatabaseEvent =
| DatabaseEventPayload<ObjectRecordCreateEvent<Person>>
| DatabaseEventPayload<ObjectRecordUpdateEvent<Person>>;
const fetchCompanyData = async (companyId: string): Promise<twentyCompany> => {
const { company } = await new Twenty().query({
company: {
__args: { filter: { id: { eq: companyId } } },
name: true,
address: {
addressStreet1: true,
addressStreet2: true,
addressState: true,
addressPostcode: true,
addressCity: true,
addressCountry: true,
},
},
});
return company as unknown as twentyCompany;
};
const checkAddress = (address: twentyAddress): mailchimpAddress => {
if (
address.addressStreet1 !== '' &&
address.addressCity !== '' &&
address.addressPostCode !== '' &&
address.addressState !== ''
) {
return {
street1: address.addressStreet1,
street2: address.addressStreet2,
city: address.addressCity,
state: address.addressState,
zipCode: address.addressPostCode,
country: address.addressCountry,
} as mailchimpAddress;
}
throw new Error('Invalid address');
};
const checkAudiencePermissions = async (
audienceId: string,
): Promise<string[] | undefined> => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
},
url: `${MAILCHIMP_API_URL}/audiences/${audienceId}`,
};
try {
const temp = await axios.request(options);
return temp.data.enabled_channels;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const prepareData = (
firstName: string,
lastName: string,
email: string,
phoneNumber: string,
phoneCallingCode: string,
companyName: string,
address: mailchimpAddress | string,
): mailchimpRecord => {
let data = {
mergeFields: {},
} as mailchimpRecord;
data.mergeFields.FNAME = firstName;
data.mergeFields.LNAME = lastName;
if (IS_EMAIL_CONSTRAINT) {
data.email_channel = {
email: email,
marketing_consent: {
status: 'unknown',
},
};
}
if (IS_ADDRESS_CONSTRAINT) {
data.mergeFields.ADDRESS = address;
}
if (IS_PHONE_CONSTRAINT) {
const mergedPhoneNumber: string = phoneCallingCode.startsWith('+')
? phoneCallingCode.concat(phoneNumber)
: '+'.concat(phoneCallingCode, phoneNumber);
data['sms_channel'] = {
sms_phone: mergedPhoneNumber,
marketing_consent: {
status: 'unknown',
},
};
data['mergeFields']['PHONE'] = mergedPhoneNumber;
}
if (IS_COMPANY_CONSTRAINT) {
data['mergeFields']['COMPANY'] = companyName;
}
return data;
};
const addTwentyPersonToMailchimp = async (
convertedRecord: mailchimpRecord,
): Promise<boolean | undefined> => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
},
url: `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts`,
data: convertedRecord,
};
try {
const response = await axios.request(options);
return response.status === 200;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const checkIfTwentyPersonExistsInMailchimp = async (
email?: string,
phoneNumber?: string,
cursor?: string,
) => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
},
url: cursor
? `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts?count%3D1000%26cursor%3D${cursor}`
: `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts?count%3D1000`,
};
try {
const response = await axios.request(options);
const doesPersonExist: mailchimpRecord | undefined =
(response.data.contacts.find(
(contact: any) => contact.email_channel.email === email,
) as mailchimpRecord) ||
(response.data.contacts.find(
(contact: any) => contact.sms_channel.sms_phone === phoneNumber,
) as mailchimpRecord);
if (doesPersonExist !== undefined) {
return doesPersonExist;
}
if (response.data.next_cursor === undefined) {
return undefined;
} else {
await checkIfTwentyPersonExistsInMailchimp(
email,
phoneNumber,
response.data.next_cursor,
);
}
return undefined;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const compareTwoRecords = (
object1: mailchimpRecord,
object2: mailchimpRecord,
) => {
return (
object1.email_channel?.email === object2.email_channel?.email &&
object1.sms_channel?.sms_phone === object2.sms_channel?.sms_phone &&
object1.mergeFields.FNAME === object2.mergeFields.FNAME &&
object1.mergeFields.LNAME === object2.mergeFields.LNAME &&
object1.mergeFields.ADDRESS === object2.mergeFields.ADDRESS &&
object1.mergeFields.COMPANY === object2.mergeFields.COMPANY
);
};
const updateTwentyPersonInMailchimp = async (
mailchimpRecordId: string,
twentyConvertedRecord: mailchimpRecord,
): Promise<boolean | undefined> => {
const options = {
method: 'PATCH',
headers: {
Authorization: `Bearer ${MAILCHIMP_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${MAILCHIMP_API_URL}/audiences/${MAILCHIMP_AUDIENCE_ID}/contacts/${mailchimpRecordId}`,
data: twentyConvertedRecord,
};
try {
const response = await axios.request(options);
return response.status === 200;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
export const main = async (
params: DatabaseEvent,
): Promise<object | undefined> => {
if (!IS_EMAIL_CONSTRAINT && !IS_PHONE_CONSTRAINT) {
console.warn(
'Function exited as there are no constraints to email nor phone number',
);
return {};
}
if (
MAILCHIMP_API_URL === '' ||
MAILCHIMP_API_KEY === '' ||
MAILCHIMP_AUDIENCE_ID === ''
) {
console.warn('Missing Mailchimp required parameters');
return {};
}
try {
const { properties } = params;
const twentyRecord: twentyPerson = properties.after as twentyPerson;
if (
twentyRecord.name.firstName === '' ||
twentyRecord.name.lastName === ''
) {
throw new Error('First or last name is empty');
}
const audiencePermissions: string[] | undefined =
await checkAudiencePermissions(MAILCHIMP_AUDIENCE_ID);
if (
IS_EMAIL_CONSTRAINT &&
audiencePermissions?.includes('Email') &&
twentyRecord.emails.primaryEmail === ''
) {
throw new Error('Email is empty');
}
if (
IS_PHONE_CONSTRAINT &&
audiencePermissions?.includes('SMS') &&
(twentyRecord.phones.primaryPhoneNumber === '' ||
twentyRecord.phones.primaryPhoneCallingCode === '')
) {
throw new Error('Phone number is empty');
}
let companyName: string = '';
let address: mailchimpAddress | string = '';
if (IS_COMPANY_CONSTRAINT) {
if (twentyRecord.companyId === null) {
throw new Error('Missing relation to company record');
}
const company: twentyCompany = await fetchCompanyData(
twentyRecord.companyId,
);
companyName = company.name ?? ''; // either "" or name
address = IS_ADDRESS_CONSTRAINT ? checkAddress(company.address) : '';
}
const twentyPersonToMailchimpRecord: mailchimpRecord = prepareData(
twentyRecord.name.firstName,
twentyRecord.name.lastName,
twentyRecord.emails.primaryEmail,
twentyRecord.phones.primaryPhoneNumber,
twentyRecord.phones.primaryPhoneCallingCode,
companyName,
address,
);
console.log(twentyPersonToMailchimpRecord);
const isTwentyPersonInMailchimp: mailchimpRecord | undefined =
await checkIfTwentyPersonExistsInMailchimp(
twentyRecord.emails.primaryEmail,
twentyPersonToMailchimpRecord.sms_channel?.sms_phone,
);
if (isTwentyPersonInMailchimp !== undefined) {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} found in Mailchimp`,
);
if (UPDATE_PERSON) {
if (
!compareTwoRecords(
isTwentyPersonInMailchimp,
twentyPersonToMailchimpRecord,
) &&
isTwentyPersonInMailchimp.id
) {
const isTwentyPersonUpdatedInMailchimp: boolean | undefined =
await updateTwentyPersonInMailchimp(
isTwentyPersonInMailchimp.id,
twentyPersonToMailchimpRecord,
);
if (!isTwentyPersonUpdatedInMailchimp) {
throw new Error(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} update in Mailchimp failed`,
);
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} update in Mailchimp succeeded`,
);
}
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} wasn't updated in Mailchimp because they're the same`,
);
}
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} wasn't updated in Mailchimp because UPDATE_PERSON is set to false`,
);
}
} else {
console.log(
`${twentyRecord.name.firstName} ${twentyRecord.name.lastName} doesn't exist in Mailchimp, adding`,
);
const isTwentyPersonAddedToMailchimp: boolean | undefined =
await addTwentyPersonToMailchimp(twentyPersonToMailchimpRecord);
if (!isTwentyPersonAddedToMailchimp) {
throw new Error(
`Adding ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} person to Mailchimp failed`,
);
} else {
console.log(
`Person ${twentyRecord.name.firstName} ${twentyRecord.name.lastName} has been successfully added`,
);
}
}
return {};
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(error.response);
return {};
}
console.error(error);
return {};
}
};
export const config: FunctionConfig = {
universalIdentifier: '83319670-775b-4862-b133-5c353e594151',
name: 'mailchimp-synchronizer',
triggers: [
{
universalIdentifier: 'e627ff6f-0a0c-48b2-bdbb-31967489ec96',
type: 'databaseEvent',
eventName: 'person.created',
},
{
universalIdentifier: '657ece26-4478-4408-a257-4e9e16cce279',
type: 'databaseEvent',
eventName: 'person.updated',
},
],
};
File diff suppressed because it is too large Load Diff
@@ -3,16 +3,15 @@
Synchronizes customers from Stripe to Twenty
## Requirements
- twenty-cli `npm install -g twenty-cli`
- an `apiKey`. Go to `https://twenty.com/settings/api-webhooks` to generate one
- an `apiKey` - go to Settings > API & Webhooks to generate one
- Stripe secret API key - available in Stripe workbench
## Setup
1. Synchronize app
```bash
twenty auth login
cd stripe-synchronizer
twenty app sync
cd packages/twenty-apps/community/stripe-synchronizer
yarn auth
yarn sync
```
2. Go to Stripe > Workbench > Webhooks and add webhook:
- events: customer.subscription.created and customer.subscription.updated
@@ -34,4 +33,5 @@ twenty app sync
## Todo
- add validation of signature key from Stripe to ensure that incoming request is valid
(possible once request headers are exposed to serverless functions)
(possible once request headers are exposed to serverless functions)
- update app so it'll use provided Twenty generated object with native types from workspace once extending objects is possible
@@ -1,4 +1,4 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
import { type ApplicationConfig } from 'twenty-sdk';
const config: ApplicationConfig = {
universalIdentifier: '0ed2bcb8-64ab-4ca1-b875-eeabf41b5f95',
@@ -10,9 +10,19 @@
"packageManager": "yarn@4.9.2",
"dependencies": {
"axios": "^1.13.2",
"twenty-sdk": "0.0.4"
"twenty-sdk": "0.2.4"
},
"devDependencies": {
"@types/node": "^24.7.2"
},
"scripts": {
"auth": "twenty auth login",
"generate": "twenty app generate",
"dev": "twenty app dev",
"sync": "twenty app sync",
"uninstall": "twenty app uninstall",
"logs": "twenty app logs",
"create-entity": "twenty app add",
"help": "twenty --help"
}
}
@@ -1,500 +0,0 @@
import axios from 'axios';
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
import { type stripeCustomer, type stripeEvent, type stripeStatus, type twentyObject } from './types';
const TWENTY_API_KEY: string = process.env.TWENTY_API_KEY ?? '';
const TWENTY_API_URL: string =
process.env.TWENTY_API_URL !== '' && process.env.TWENTY_API_URL !== undefined
? `${process.env.TWENTY_API_URL}/rest`
: 'https://api.twenty.com/rest';
const STRIPE_API_KEY: string = process.env.STRIPE_API_KEY ?? '';
const STRIPE_API_URL: string = 'https://api.stripe.com/v1/customers';
const getTwentyObjectData = async (
objectSingularName: string,
): Promise<twentyObject | undefined> => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
url: `${TWENTY_API_URL}/metadata/objects`,
};
try {
const response = await axios.request(options);
if (response.status === 200) {
const companyObject = response.data.data.objects.find(
(object: twentyObject) => object.nameSingular === objectSingularName,
);
return (companyObject as twentyObject) ?? ({} as twentyObject);
}
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const createFields = async (objectId: string, fieldName: string) => {
const data =
fieldName === 'seats'
? {
type: 'NUMBER',
objectMetadataId: objectId,
name: 'seats',
label: 'Seats',
icon: 'IconMan',
}
: {
type: 'SELECT',
objectMetadataId: objectId,
name: 'subStatus',
label: 'Sub Status',
icon: 'IconStatusChange',
options: [
{
color: 'iris',
label: 'Incomplete',
value: 'INCOMPLETE',
position: 1,
},
{
color: 'sky',
label: 'Incomplete (expired)',
value: 'INCOMPLETE_EXPIRED',
position: 2,
},
{
color: 'amber',
label: 'Trialing',
value: 'TRIALING',
position: 3,
},
{
color: 'green',
label: 'Active',
value: 'ACTIVE',
position: 4,
},
{
color: 'orange',
label: 'Past due',
value: 'PAST_DUE',
position: 5,
},
{
color: 'brown',
label: 'Canceled',
value: 'CANCELED',
position: 6,
},
{
color: 'red',
label: 'Unpaid',
value: 'UNPAID',
position: 7,
},
{
color: 'gray',
label: 'Paused',
value: 'PAUSED',
position: 8,
},
],
};
const options = {
method: 'POST',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${TWENTY_API_URL}/metadata/fields`,
data: data,
};
try {
const response = await axios(options);
return response.status === 201;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const getStripeCustomerData = async (
customerID: string,
): Promise<stripeCustomer | undefined> => {
const options = {
method: 'GET',
url: `${STRIPE_API_URL}/${customerID}`,
auth: {
username: STRIPE_API_KEY,
password: '',
},
};
try {
const response = await axios(options);
return response.status === 200
? ({
name: response.data.name,
businessName: response.data.business_name,
email: response.data.email,
} as stripeCustomer)
: ({} as stripeCustomer);
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const checkIfCompanyExistsInTwenty = async (
name: string | undefined,
): Promise<string | undefined> => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
},
url: `${TWENTY_API_URL}/companies?filter=name%5Beq%5D%3A%22${name}%22`,
};
try {
const response = await axios(options);
return response.status === 200 &&
response.data.data.companies[0].id !== undefined
? (response.data.data.companies[0].id as string)
: '';
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const updateTwentyCompany = async (
companyId: string | undefined,
seats: number | null,
subStatus: stripeStatus,
): Promise<boolean | undefined> => {
const options = {
method: 'PATCH',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${TWENTY_API_URL}/companies/${companyId}`,
data: {
seats: seats,
subStatus: subStatus,
},
};
try {
const response = await axios(options);
return response.status === 200;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const createTwentyCompany = async (
customerName: string | undefined,
seats: number | null,
subStatus: string,
): Promise<string | undefined> => {
const options = {
method: 'POST',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${TWENTY_API_URL}/companies`,
data: {
name: customerName,
seats: seats,
subStatus: subStatus,
},
};
try {
const response = await axios(options);
return response.status === 201 ? (response.data.data.id as string) : '';
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const checkIfStripePersonExistsInTwenty = async (email: string | null) => {
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${TWENTY_API_URL}/people?filter=emails.primaryEmail%5Beq%5D%3A%22${email}%22`, // mail is unique by default so there can be only 1 person with given mail
};
try {
const response = await axios.request(options);
return response.status === 200 &&
response.data.data.people[0].id !== undefined
? (response.data.data.people[0].id as string)
: '';
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const addTwentyPerson = async (
firstName: string,
lastName: string,
email: string,
companyId: string,
seats: number,
subStatus: stripeStatus,
): Promise<boolean | undefined> => {
const options = {
method: 'POST',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${TWENTY_API_URL}/people`,
data: {
firstName: firstName,
lastName: lastName,
emails: { primaryEmail: email },
companyId: companyId,
seats: seats,
subStatus: subStatus,
},
};
try {
const response = await axios.request(options);
return response.status === 201;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
const updateTwentyPerson = async (
id: string,
seats: number,
subStatus: stripeStatus,
): Promise<boolean | undefined> => {
const options = {
method: 'PATCH',
headers: {
Authorization: `Bearer ${TWENTY_API_KEY}`,
'Content-Type': 'application/json',
},
url: `${TWENTY_API_URL}/people/${id}`,
data: {
seats: seats,
subStatus: subStatus,
},
};
try {
const response = await axios.request(options);
return response.status === 200;
} catch (error) {
if (axios.isAxiosError(error)) {
throw error;
}
}
};
export const main = async (
params: Record<string, any>,
): Promise<object | undefined> => {
if (TWENTY_API_KEY === '' || STRIPE_API_KEY === '') {
throw new Error('Missing variables');
}
try {
// TODO: add validation of signature key from Stripe (not possible at the moment as headers aren't accessible in serverless functions)
const stripe = params as stripeEvent;
const allowed_types: string[] = [
'customer.subscription.created',
'customer.subscription.updated',
];
if (!allowed_types.includes(stripe.type)) {
throw new Error('Wrong type of webhook');
}
const stripeCustomer: stripeCustomer | undefined =
await getStripeCustomerData(stripe.data.object.customer);
if (
stripeCustomer?.businessName === undefined ||
stripeCustomer?.businessName === ''
) {
console.warn('Set customer business name in Stripe');
return {};
}
const companyObject = await getTwentyObjectData('company');
if (
companyObject?.fields.find((field) => field.name === 'seats') ===
undefined
) {
const seatsFieldCreated: boolean | undefined = companyObject?.id
? await createFields(companyObject?.id, 'seats')
: false;
if (!seatsFieldCreated) {
throw new Error('Seats field creation in Company object failed');
} else {
console.info('Seats field creation in Company object succeeded');
}
}
if (
companyObject?.fields.find((field) => field.name === 'subStatus') ===
undefined
) {
const subStatusFieldCreated: boolean | undefined = companyObject?.id
? await createFields(companyObject?.id, 'subStatus')
: false;
if (!subStatusFieldCreated) {
throw new Error('Sub status field creation in Company object failed');
} else {
console.info('Sub status field creation in Company object succeeded');
}
}
const personObject = await getTwentyObjectData('person');
if (
personObject?.fields.find((field) => field.name === 'seats') === undefined
) {
const seatsFieldCreated: boolean | undefined = personObject?.id
? await createFields(personObject?.id, 'seats')
: false;
if (!seatsFieldCreated) {
throw new Error('Seats field creation in People object failed');
} else {
console.info('Seats field creation in People object succeeded');
}
}
if (
personObject?.fields.find((field) => field.name === 'subStatus') ===
undefined
) {
const subStatusFieldCreated: boolean | undefined = personObject?.id
? await createFields(personObject?.id, 'subStatus')
: false;
if (!subStatusFieldCreated) {
throw new Error('Sub status field creation in People object failed');
} else {
console.info('Sub status field creation in People object succeeded');
}
}
const twentyCompanyId: string | undefined =
await checkIfCompanyExistsInTwenty(stripeCustomer?.businessName);
const seats: number =
stripe.data.object.quantity ??
stripe.data.object.items.data.reduce(
(acc, item) => acc + item.quantity,
0,
); // we don't know if subscription has only 1 item (product) or more
let updatedTwentyCompanyId: string | undefined;
if (twentyCompanyId === '') {
const twentyCompanyCreated: string | undefined =
await createTwentyCompany(
stripeCustomer?.businessName,
seats,
stripe.data.object.status.toUpperCase(),
);
if (twentyCompanyCreated === '') {
throw new Error('Creation of Stripe customer in Twenty failed');
} else {
console.log('Creation of Stripe customer in Twenty succeeded');
updatedTwentyCompanyId = twentyCompanyCreated;
}
} else {
const twentyCompanyUpdated: boolean | undefined =
await updateTwentyCompany(
twentyCompanyId,
seats,
stripe.data.object.status.toUpperCase() as stripeStatus,
);
if (!twentyCompanyUpdated) {
throw new Error('Update of Stripe customer in Twenty failed');
} else {
console.log('Update of Stripe customer in Twenty succeeded');
updatedTwentyCompanyId = twentyCompanyId;
}
}
if (updatedTwentyCompanyId === undefined || updatedTwentyCompanyId === '') {
throw new Error('TwentyCompanyId not found');
} else {
const stripeCustomerInTwenty: string | undefined =
await checkIfStripePersonExistsInTwenty(stripeCustomer.email);
if (stripeCustomerInTwenty === '') {
if (!stripeCustomer.name) {
throw new Error('Missing Stripe customer first or last name');
}
if (!stripeCustomer.email) {
throw new Error('Missing Stripe customer email');
}
const firstName: string = stripeCustomer.name?.split(' ')[0];
const lastName: string = stripeCustomer.name?.split(' ')[1];
const addedStripePersonToTwenty: boolean | undefined =
await addTwentyPerson(
firstName,
lastName,
stripeCustomer.email,
updatedTwentyCompanyId,
seats,
stripe.data.object.status.toUpperCase() as stripeStatus,
);
if (!addedStripePersonToTwenty) {
throw new Error('Adding Stripe person to Twenty failed');
} else {
console.log('Stripe person was added to Twenty');
}
} else if (stripeCustomerInTwenty !== undefined) {
const updatedStripePersonInTwenty: boolean | undefined =
await updateTwentyPerson(
stripeCustomerInTwenty,
seats,
stripe.data.object.status.toUpperCase() as stripeStatus,
);
if (!updatedStripePersonInTwenty) {
throw new Error('Update of Stripe person in Twenty failed');
} else {
console.log('Update of Stripe person in Twenty succeeded');
}
} else {
throw new Error('Twenty not found');
}
}
return {};
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(error.message);
return {};
}
console.error(error);
return {};
}
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: 'cd15a738-18a5-406e-8b83-959dc52ebe14',
name: 'stripe',
triggers: [
{
universalIdentifier: '55f58e19-d832-43c4-9f8b-3f29fc05c162',
type: 'route',
path: '/webhook/stripe',
httpMethod: 'POST',
isAuthRequired: false,
},
],
};

Some files were not shown because too many files have changed in this diff Show More