Compare commits

..
451 Commits
Author SHA1 Message Date
WeikoandGitHub da626f70b7 optimize buildFieldMapsFromFlatObjectMetadata usages (#16132)
This newly introduced util can be a bit expensive especially when done
recursively.
This PR improves that


File | Pattern Fixed | Impact
-- | -- | --
format-result.util.ts | Recursive array/object processing | N array
items → 1 call
format-data.util.ts | Recursive array processing | N array items → 1
call
process-nested-relations-v2.helper.ts | Duplicate call in call chain | 2
calls → 1 call
common-result-getters.service.ts | Per-record processing in array | N
records → 1 call
compute-relation-connect-query-configs.util.ts | Nested loop (entities ×
connect fields) | N×M calls → 1 call
2025-11-27 15:01:51 +01:00
nitinandGitHub 27547fd445 restore color on pie chart item and populate it on data transformation (#16131) 2025-11-27 13:41:30 +00:00
EtienneandGitHub 57ae12ff7c Null equivalence - update filter (#16123) 2025-11-27 13:31:39 +00:00
76ed82b598 i18n - translations (#16130)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-27 14:23:42 +01:00
ca5bd76c6a Null equivalence - migration command (#16018)
Awaiting https://github.com/twentyhq/twenty/pull/15926 approval, before
un-drafting it

---------

Co-authored-by: prastoin <paul@twenty.com>
2025-11-27 13:18:56 +00:00
nitinandGitHub 97a8beb3f9 on pie chart, slice should not be clickable when in edit mode (#16129) 2025-11-27 13:05:24 +00:00
Abdullah.andGitHub 46ce9eca3f fix: node-forge is vulnerable to ASN.1 OID integer truncation (#16124)
Resolves [Dependabot Alert
328](https://github.com/twentyhq/twenty/security/dependabot/328).

Used `yarn up node-forge --recursive` to bump up the patch version from
1.3.1 to 1.3.2.
2025-11-27 17:49:10 +05:00
WeikoandGitHub 1607aebcc6 Deprecate object metadata maps in favor of flat entities (#16080)
## Context
Deprecating the old objectMetadataMap type in favour of split flat
entities to match with our new caching.
In the long run, trying to achieve:
- Better performance through caching
- Consistent data access patterns across the codebase
- Reduced database queries

Now that everything is based on flat entities, which are cached, we can
finish the refactoring of workspace context cache which should already
improve performances.
Then the last step will be to consume that new cache in the new global
datasource to get rid of the many workspace datasources stored in the
server
2025-11-27 13:43:34 +01:00
Abdullah.andGitHub 978c0acb90 fix: sentry's sensitive headers are leaked when sendDefaultPii is set to true (#16122)
Resolves [Dependabot Alert
323](https://github.com/twentyhq/twenty/security/dependabot/323),
[Dependabot Alert
324](https://github.com/twentyhq/twenty/security/dependabot/324) and
[Dependabot Alert
325](https://github.com/twentyhq/twenty/security/dependabot/325).

It updates Sentry's packages on the server from 10.21.0 to 10.27.0.

I also moved @sentry/react to twenty-front package.json and updated the
version from 9.26.0 to 10.27.0 - no breaking changes were introduced in
the major upgrade in regards to the API exposed by the dependency.

Since @sentry/profiling-node was redundant in the root package.json, I
removed it - twenty-server has it already and is the only package
dependent on @sentry/profiling-node.
2025-11-27 17:28:59 +05:00
Abdullah.andGitHub afd5ccc775 fix: body-parser is vulnerable to denial of service when url encoding is used (#16126)
Resolves [Dependabot Alert
326](https://github.com/twentyhq/twenty/security/dependabot/326).

Used `yarn up body-parser --recursive` to bump up the patch version from
2.2.0 to 2.2.1.
2025-11-27 17:28:33 +05:00
f3a796e17e i18n - docs translations (#16127)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-27 13:23:11 +01:00
44f4203d58 i18n - translations (#16125)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-27 13:01:57 +01:00
Raphaël BosiandGitHub 20e6f130d1 Update pie chart inner padding (#16121)
## Before

<img width="2548" height="1024" alt="CleanShot 2025-11-27 at 12 13
24@2x"
src="https://github.com/user-attachments/assets/f2182821-1398-4f29-a5ee-2ffc5653d416"
/>

## After

<img width="2558" height="1034" alt="CleanShot 2025-11-27 at 12 13
04@2x"
src="https://github.com/user-attachments/assets/147ba875-0432-4525-b847-e1f2426849ed"
/>
2025-11-27 11:24:59 +00:00
nitinandGitHub db6456b1af fix legend toggle for line and bar charts (#16120) 2025-11-27 11:21:55 +00:00
d7f8c2d338 Center metric layer on pie chart + cleanup (#16105)
https://github.com/user-attachments/assets/bb48bebe-d0be-4006-8f63-e686c70c0011

---------

Co-authored-by: bosiraphael <raphael.bosi@gmail.com>
2025-11-27 11:15:48 +00:00
1a45576990 Morph-add-new-object-destination (#16027)
Add new object target to an existing morph relation (backend only)

Fixes https://github.com/twentyhq/core-team-issues/issues/1898

---------

Co-authored-by: prastoin <paul@twenty.com>
2025-11-27 11:10:13 +00:00
7001c91a7d i18n - translations (#16119)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-27 12:01:05 +01:00
MarieandGitHub 9c9a01d55a [groupBy][Requires cache flush] Add WEEK date granularity (#16099)
Closes https://github.com/twentyhq/core-team-issues/issues/1921

https://github.com/user-attachments/assets/bf400ec1-ce25-4d9e-b875-774168452514
2025-11-27 10:22:57 +00:00
7e90dd888c i18n - docs translations (#16114)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-27 09:22:02 +01:00
9f939eb4c3 i18n - translations (#16113)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-27 09:01:26 +01:00
Félix MalfaitandGitHub 4f20fd35c5 feat: Add Agent Evaluation System and Refactor AI Modules (#16111)
## Summary

This PR introduces a comprehensive agent evaluation system and refactors
the AI module structure for better organization.

## Key Changes

### 🎯 Agent Evaluation System
- Added **Agent Turn Evaluation** entities, DTOs, and database schema
- New GraphQL mutations: `evaluateAgentTurn` and `runEvaluationInput`
- Added `evaluationInputs` field to Agent entity for storing test inputs
- New `AgentTurnGraderService` for automatic turn evaluation
- Added evaluation UI with new **Evals** and **Logs** tabs in agent
detail pages

### 🏗️ Entity & Module Refactoring
- Renamed `AgentChatMessage` → `AgentMessage` for clarity
- Consolidated chat entities: `AgentMessage`, `AgentTurn`, and
`AgentChatThread`
- Reorganized AI modules under `ai/` subdirectory structure
- Updated imports across codebase to reflect new module paths

### 🤖 New Agents & Roles
- Added **Dashboard Builder Agent** for dashboard creation and
management
- Added **Dashboard Manager Role** with appropriate permissions
- Updated role permissions to be more granular (users vs agents vs API
keys)

### 🔐 Permission System Updates
- Added `HTTP_REQUEST_TOOL` permission flag
- Updated Workflow Manager role permissions (restricted tool access)
- Enhanced permission flag types to differentiate between user/agent/API
key contexts
- Added `isRelevantForAgents`, `isRelevantForApiKeys`,
`isRelevantForUsers` to permission flags

### 📨 Message Role Enhancement
- Added `system` role to `AgentMessageRole` enum (alongside
user/assistant)
- Updated message handling to support system prompts

### 🎨 UI/UX Improvements
- New tabs in agent detail: **Evals** and **Logs**
- Added turn detail page: `/ai/agents/:agentId/turns/:turnId`
- Fixed text overflow in `SettingsListItemCardContent`
- Updated role applicability labels ("Assignable to Workspace Members")

### 🛠️ Technical Improvements
- Fixed Zod schema validation for UUID and Date fields (use string
validators)
- Updated `ToolRegistryService` to properly register HTTP tool with
permission flag
- Enhanced error handling in agent execution services
- Updated database migrations for new entity schema

## Database Migrations
- `1764210000000-add-system-role-to-agent-message.ts`
- `1764220000000-add-evaluation-inputs-to-agent.ts`
- `1764200000000-add-agent-turn-evaluation.ts`
- `1764100000000-refactor-agent-chat-entities.ts`

## Testing
- [ ] Agent evaluation flow tested
- [ ] Dashboard Builder agent tested
- [ ] Permission system validated
- [ ] UI tabs and navigation tested
- [ ] Database migrations run successfully

## Breaking Changes
⚠️ **Entity Rename**: `AgentChatMessage` renamed to `AgentMessage` -
GraphQL queries need updating

## Related Issues
<!-- Link any related issues here -->

## Screenshots
<!-- Add screenshots if applicable -->
2025-11-27 08:25:40 +01:00
Thomas des FrancsandGitHub 35f81805b8 Fix options menu button height in side panel footer (#16107)
## Description
Fixed the height of the options menu button in the side panel footer to
be 24px instead of 32px, matching the height of other buttons in the
footer.

## Changes
- Added `size="small"` prop to the `Button` component in
`OptionsDropdownMenu.tsx`
- This ensures consistent button sizing across the side panel footer

## Before
The options menu button was 32px high (medium size), making it larger
than other footer buttons.

<img width="543" height="421" alt="image"
src="https://github.com/user-attachments/assets/3c4fdfd0-73d1-4884-a639-3382090dfe15"
/>


## After
The options menu button is now 24px high (small size), consistent with
other side panel footer buttons.

<img width="1000" height="824" alt="CleanShot 2025-11-26 at 18 50 43@2x"
src="https://github.com/user-attachments/assets/798e7975-a7a8-4c00-b2e7-c0d1261249f8"
/>
2025-11-27 09:43:42 +05:30
Charles BochetandGitHub b1d1bcb712 Fix messaging import (#16112) 2025-11-26 23:13:12 +01:00
Thomas des FrancsandGitHub 5d1c2a3348 Let single notes take the full width (both side panel & desktop) (#16108)
# Current behavior

<img width="932" height="1040" alt="CleanShot 2025-11-26 at 19 10 32@2x"
src="https://github.com/user-attachments/assets/309fc2f4-b9ef-481c-b550-74c1c5cfeaf4"
/>

<img width="2618" height="1352" alt="CleanShot 2025-11-26 at 19 10
56@2x"
src="https://github.com/user-attachments/assets/f57348e9-2e09-4c91-bcf6-e776aa26598a"
/>


# Desired Behavior

<img width="2634" height="1304" alt="CleanShot 2025-11-26 at 19 11
32@2x"
src="https://github.com/user-attachments/assets/d8e13ab5-65d7-4449-9d8d-7a2356f71160"
/>

<img width="1048" height="1146" alt="CleanShot 2025-11-26 at 19 11
50@2x"
src="https://github.com/user-attachments/assets/8a062717-18c1-41c7-a52c-1904738cd145"
/>
2025-11-26 22:34:44 +01:00
ee6ac6bb4c i18n - docs translations (#16109)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-26 19:22:05 +01:00
3c658b209d i18n - translations (#16106)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-26 18:46:23 +01:00
EtienneandGitHub 70f48ba445 Security - Add complexity max on gql queries (#16069)
closes https://github.com/twentyhq/private-issues/issues/348
closes https://github.com/twentyhq/private-issues/issues/352
closes https://github.com/twentyhq/private-issues/issues/353
closes https://github.com/twentyhq/private-issues/issues/354
2025-11-26 18:36:21 +01:00
Charles BochetandGitHub 5202e2b2db Refactor error messages messaging (#16094)
We should try catch locally gmail errors when:
- fetching message list
- fetching messages
- refreshing aliases
- fetching folders
2025-11-26 18:03:44 +01:00
Raphaël BosiandGitHub fc4dbb80de [DASHBOARDS] Create display legend setting + animations (#16089)
## PR Description
- Create display legend setting
- Create pagination inside the legend
- Animate the legend on enter/exit
- Animate the transition between pages

## Video QA


https://github.com/user-attachments/assets/a68a4ea3-195f-4399-88f7-f83bc1a39cc4
2025-11-26 17:03:23 +00:00
GuillimandGitHub 7f441d741b Timelineactivites-views-seeder (#16103)
seeder for Timelineactivites views

Fixes https://github.com/twentyhq/core-team-issues/issues/1904


<img width="850" height="348" alt="CleanShot 2025-11-26 at 17 30 32"
src="https://github.com/user-attachments/assets/41a311c1-0b60-4201-885f-d0e8400dd6d5"
/>
2025-11-26 18:00:06 +01:00
Raphaël BosiandGitHub 60e69f92d9 [DASHBOARDS] Add pie chart empty state (#16100)
When no data is available, we display a gray circle instead of nothing.



https://github.com/user-attachments/assets/54db403b-739c-43fb-b422-8dcdfb6281fb
2025-11-26 17:23:52 +01:00
c82c4a4507 i18n - translations (#16101)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-26 17:21:44 +01:00
neo773andGitHub 4120c191f8 fix scheduling after folder actions are processed (#16097) 2025-11-26 17:09:06 +01:00
Raphaël BosiandGitHub 8dc182d659 Add New Widget page layout header information (#16098)
## Before

<img width="822" height="384" alt="CleanShot 2025-11-26 at 16 22 12@2x"
src="https://github.com/user-attachments/assets/014e2efc-c4e4-4140-b473-f09ac56855b5"
/>

## After

<img width="818" height="352" alt="CleanShot 2025-11-26 at 16 21 53@2x"
src="https://github.com/user-attachments/assets/5aa961a9-7d06-47b7-ad5d-6b5b9714a0d8"
/>
2025-11-26 16:38:36 +01:00
Raphaël BosiandGitHub c34f798a9c Reorder colors to have a proper gradient (#16096)
## Before

<img width="638" height="1712" alt="CleanShot 2025-11-26 at 15 28 47@2x"
src="https://github.com/user-attachments/assets/a8ebadf7-a642-46c1-bb96-067e8b451059"
/>


## After

<img width="638" height="1712" alt="CleanShot 2025-11-26 at 15 26 15@2x"
src="https://github.com/user-attachments/assets/d276240c-4b34-4ea3-954d-2a20a94ddf60"
/>
2025-11-26 14:40:45 +00:00
nitinandGitHub 6fcb05d9b3 part 3 of on click bar to filters: add sort plus some normalizations (#16075) 2025-11-26 19:48:48 +05:30
Baptiste DevessierandGitHub dc2c2c413c [Workflows] Fix filtering on relative date (#16087)
https://github.com/user-attachments/assets/4079d59e-0550-401f-a29b-b235edd8ed48

Closes https://github.com/twentyhq/twenty/issues/16054
2025-11-26 14:45:05 +01:00
Paul RastoinandGitHub 996ccd8353 Non composite and non morph or relation field update fix (#16091) 2025-11-26 11:54:04 +00:00
Paul RastoinandGitHub 74eab77539 Refactor upgrade devx to allow configuring workspaces status to pass over (#16066)
# Introduction
We need to be able to create custom workspace application on all
workspaces, even pending and ongoing etc
Right now the upgrade devx only allows and expect active or suspended
workspace to be passed to runOnWorkspace.

## WorkspacesMigrationRunner
Created an intermediate class `WorkspacesMigrationRunner` that expect an
array `WorkspaceStatus` to be fetched for the current command to be run
on
The `ActiveOrSuspendedCommandRunner` statically passes both `SUSPENDED`
and `ACTIVE`, whereas the create workspace custom application passed all
the enum values

## DataSource
Workspace that are not fully init don't have a `workspace_schema` so
they don't have `dataSource`
Made a not very elegant check to see if current workspace we're about to
create dataSource on has one historically
Which means that dataSource is now optional, it had only one impact on
an existing command and the desired devx will become consuming existing
services that do not expect dataSource ( or at least yet )
2025-11-26 12:53:33 +01:00
nitinandGitHub 0d34651d5e pie chart data labels, slice gap and initial animate presence on widget card header (#16084)
closes:
https://discord.com/channels/1130383047699738754/1442899090047373463
https://discord.com/channels/1130383047699738754/1438537119248285758

pie chart labels:


https://github.com/user-attachments/assets/d8f8e164-745f-4601-bee7-11a655ccd9b6



fixed header animations:


https://github.com/user-attachments/assets/76587a6d-53c4-4a11-a546-b4c83754870a
2025-11-26 15:02:48 +05:30
4d0c469157 Fix message import scheduled (#16071)
Co-authored-by: neo773 <neo773@protonmail.com>
2025-11-26 08:54:53 +01:00
MarieandGitHub 6c1c78ea3d [fix] User have no firstName nor lastName (#16057)
Closes https://github.com/twentyhq/twenty/issues/15692, fixes
https://github.com/twentyhq/twenty/issues/14678

The issue was:
- When a user is signing up, they are asked for their first name and
last name with which we fulfill their workspaceMember entity for the
workspace they are signing up to (which is the one they are creating if
they are not joining an existing workspace). user.firstName and
user.lastName remain empty
- When we create a record, we are using user.firstName and user.lastName
to fulfill the text field "createdByName", which intends to save the
name of the creator at the moment of the creation. This field is then
use 1) when filtering on createdBy (as a trick to be able to filter by
this, since we don't have filters on nested fields, ie we dont have
filters on person.createdByWorkspaceMember) 2) to display the user
creator when a user has left a workspace - otherwise we rely on the
dynamic createdByWorkspaceMember.firstName and lastName
- So filtering on createdBy was not working as createdByName is empty.
We did not see that in dev mode because we have seeded users with names

The fix
- When we create a record, we use workspaceMember.firstName and
workspaceMember.lastName as we should.
- When an existing user joins a workspace, they are asked to give their
name again so that we set their workspaceMember name
- This will not fix the history of the records (they will still have
createdByName empty so the filter will not work properly), but a command
to fix it would be very long as it would iterate over all the records of
each active workspace

The long-term view is to get rid of user and to store the name in
userWorkspace
2025-11-25 17:23:43 +00:00
Charles BochetandGitHub b1c03b533f Fix upgrade command messaging (#16067) 2025-11-25 18:14:51 +01:00
neo773andGitHub f3416d435c move folder cron to message-list-fetch (#16062) 2025-11-25 18:06:38 +01:00
neo773andGitHub 1740a2217a Update channel sync service to immediately enqueue jobs (#16064) 2025-11-25 18:05:32 +01:00
Baptiste DevessierandGitHub 0bf2d13832 [Side Panel V2] Bring back old container (#16065)
## Before

<img width="1446" height="780" alt="image"
src="https://github.com/user-attachments/assets/fa25f22d-b979-4a8f-9989-004d07f862d7"
/>

## After

<img width="3456" height="2160" alt="CleanShot 2025-11-25 at 17 35
59@2x"
src="https://github.com/user-attachments/assets/a87880c4-3faa-47c3-9215-34afc36270a3"
/>
2025-11-25 18:04:56 +01:00
Baptiste DevessierandGitHub 21543b6803 Don't recompute output schema when moving trigger (#16061)
Position changes don't affect the trigger's output schema, so
recomputing it is unnecessary. For webhook triggers specifically, the
backend can't reconstruct the schema (it returns `{}`), which overwrites
the frontend-built schema from `expectedBody`. Passing `{
computeOutputSchema: false }` prevents this data loss while avoiding
wasteful computation.

## Demo


https://github.com/user-attachments/assets/116af221-0d09-4dda-ad40-3301fa610bcd

Closes https://github.com/twentyhq/twenty/issues/15982
2025-11-25 17:37:32 +01:00
EtienneandGitHub 71724de7dd Security - disable gql introspection for non-auth user (#16047)
closes https://github.com/twentyhq/private-issues/issues/351
closes https://github.com/twentyhq/private-issues/issues/350

Before, introspection query works without token. After, fails.

```

query IntrospectionQuery {
  __schema {
    queryType {
      name
    }
    mutationType {
      name
    }
    subscriptionType {
      name
    }
    types {
      ...FullType
    }
    directives {
      name
      description
      locations
      args {
        ...InputValue
      }
    }
  }
}

fragment FullType on __Type {
  kind
  name
  description
  fields(includeDeprecated: true) {
    name
    description
    args {
      ...InputValue
    }
    type {
      ...TypeRef
    }
    isDeprecated
    deprecationReason
  }
  inputFields {
    ...InputValue
  }
  interfaces {
    ...TypeRef
  }
  enumValues(includeDeprecated: true) {
    name
    description
    isDeprecated
    deprecationReason
  }
  possibleTypes {
    ...TypeRef
  }
}

fragment InputValue on __InputValue {
  name
  description
  type {
    ...TypeRef
  }
  defaultValue
}

fragment TypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
              }
            }
          }
        }
      }
    }
  }
}
```
2025-11-25 15:39:29 +01:00
Raphaël BosiandGitHub 42bba3de52 Fix chart limits for two-dimensional group by (#16056)
The limit wasn't working properly for two dimensional stacked charts.
This PR fixes this.
2025-11-25 15:31:25 +01:00
Charles BochetandGitHub 8455ecc3e8 Add import scheduled status to messaging sync (#16058)
We have introduced to new syncStage statuses:
`messageChannel.MESSAGES_IMPORT_SCHEDULED` and
`calendarChannel.CALENDAR_EVENTS_IMPORT_SCHEDULED`

We need to make sure all existing workspaces have it
2025-11-25 15:27:58 +01:00
825728b1c4 i18n - translations (#16059)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-25 15:20:59 +01:00
Raphaël BosiandGitHub 6d141c2439 [DASHBOARDS] Pie Chart (#16048)
## Description

- Connect Pie Chart to the backend
- Update from the old design to the new design
- Switch seamlessly from/to other types of chart from the Pie Chart by
converting the configuration

Note: There are a couple things to implement before the pie chart is
ready to go live:
- Add a new setting on Bar, Line and Pie chart to hide and display
legends (toggle)
- Add data labels next to each slice

## Video QA


https://github.com/user-attachments/assets/b1561e32-0434-43ad-8855-d617b209ce27
2025-11-25 14:30:16 +01:00
BOHEUSandGitHub 88fbe6c51d Updated by leftover nitpick (#16040)
Nitpicks from #15937
2025-11-25 14:28:37 +01:00
nitinandGitHub 3be3c4e965 part 2 of filter/sort drill down from charts (#16013)
in this PR, we will handle simple filter translations (ie, fields that
use the contains operand)
2025-11-25 18:56:55 +05:30
EtienneandGitHub 2028a8f9be Null equivalence - Fix (#16050)
@charlesBochet 
In workflow codebase, NULL (instead of empty object) is expected on
workflow version object step field, when a new workflow is created for
example.
(packages/twenty-front/src/modules/workflow/workflow-diagram/utils/generateWorkflowDiagram.ts
- 42)
This case is not isolated and it creates many issues.

We decided to format NULL value to equivalent (empty string for text
field, empty object for raw_json) but it seems it complicates the dev x.

To unlock @Devessier I prefer revert the logic, the time we discuss how
to solve this cases.
2025-11-25 14:07:32 +01:00
nitinandGitHub ab3d48383b dashboards fast follows: tabs border changed to outline and legends factorization (#16049)
closes
https://discord.com/channels/1130383047699738754/1440633019042889828
https://discord.com/channels/1130383047699738754/1442819106880356363
2025-11-25 18:08:09 +05:30
53509360ff i18n - docs translations (#16053)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-25 13:23:06 +01:00
26169a2136 i18n - translations (#16052)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-25 12:46:03 +01:00
Félix MalfaitandGitHub e7ebf51e50 Replace agent handoff system with planning-based router (#16003)
## Overview

This PR replaces the dynamic agent handoff system with a more
predictable planning-based router that decides upfront how to handle
multi-agent coordination.

## Major Changes

### 🔄 Architecture Shift: Handoffs → Planning

**Removed:**
- `AgentHandoffEntity` and handoff tracking system
- `AgentHandoffService` and `AgentHandoffExecutorService`
- Dynamic agent-to-agent transfers during execution
- Handoff tool generation and description templates

**Added:**
- `AiRouterService` with two strategies: `simple` (single agent) and
`planned` (multi-agent)
- `AgentPlanExecutorService` for executing multi-step plans
- Plan validation (cycle detection, dependency resolution)
- `UnifiedRouterResult` type with discriminated union

### 🤖 New Standard Agents

Added two new specialized agents:
- **Researcher Agent**: Web search, fact-finding, competitive
intelligence
- **Code Agent**: TypeScript function generation for serverless
workflows

### 🏗️ Router Refactoring (Latest)

Split router responsibilities into focused services:
- `AiRouterStrategyDeciderService`: Decides simple vs planned strategy
- `AiRouterPlanGeneratorService`: Generates and validates execution
plans
- `AiRouterService`: Coordinates between services (reduced from 426→275
lines)

### ⚙️ Configuration Improvements

- Added `outputStrategy` to agent definitions (`direct` vs `synthesize`)
- Removed hardcoded special cases for workflow-builder
- Added `plannerModel` field to workspace entity
- Increased `MAX_STEPS` from 10 to 25 for complex workflows

### 📝 Agent Prompt Refinements

Significantly simplified prompts for better clarity:
- Workflow Builder: 51→36 lines
- Helper: 49→28 lines
- Data Manipulator: Enhanced with sorting guidance

### 🔍 Enhanced Debugging

- Plan reasoning and step count in data message parts
- Router debug info with token usage tracking
- Better logging throughout execution pipeline

## Benefits

1. **Simpler Mental Model**: Router decides upfront vs dynamic transfers
2. **Better Predictability**: Users see the plan before execution
3. **Cleaner Architecture**: SRP with focused services
4. **Configuration Over Code**: Agent behavior via config, not hardcoded
logic
5. **Plan Validation**: Catches invalid dependencies and cycles

## Migration Notes

- Database migration removes `agentHandoff` table
- Adds `plannerModel` column to workspace table
- No API breaking changes (agent endpoints unchanged)

## Testing

- Integration tests updated to remove handoff dependencies
- Agent tool test utilities simplified
- Plan validation covered by new logic

## Next Steps (Future PRs)

- Parallel execution of independent plan steps
- Dynamic re-planning based on results
- Plan caching for common routing patterns
- Error recovery strategies in plan executor
2025-11-25 12:10:14 +01:00
Abdullah.andGitHub 3c0ae49a23 Clicking outside inline fields on record page saves the value. (#16042)
Closes #15957

The core problem: `handleChange` calls `setDraftValue`, but when blur
fires, `handleClickOutside` runs in the same event turn and uses
the `draftValue` captured in its closure from the last render. React
hasn’t re-rendered yet, so that captured `draftValue` is stale. Recoil
atom writes are synchronous, but the render that would update the
closure happens on the next turn.

I considered deferring `handleClickOutside` to the next tick
(setTimeout/Promise), but that’s a timing hack: it makes focus/blur
ordering unpredictable (inline cells, tables, other listeners), risks
double triggers, and can fire after unmount. Another option was to
duplicate the `handleChange` logic inside `handleClickOutside`
(screenshot), but that defeats having draft state in one place.

<p align="center">
<img width="496" height="332" alt="const nextSecondaryLinks =
updatedLinks slice (1);"
src="https://github.com/user-attachments/assets/638e2bcf-871b-4b53-9124-c8489c5db530"
/>
</p>

The clean solution is to read the current draft from a Recoil snapshot
at call time inside `handleClickOutside`. Snapshot reads pull the latest
atom value (including synchronous `setDraftValue` that just ran) even
before a re-render occurs, so they’re not subject to the stale closure.
That way, blur uses the up-to-date draft without timing hacks or
duplicated logic.

MultiItemFieldInput is used in four places. Each of them contains the
updated code.
2025-11-25 11:37:37 +01:00
3e584c3d5f i18n - docs translations (#16044)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-25 11:21:42 +01:00
a47b7dfed0 i18n - translations (#16041)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-25 10:36:15 +01:00
MarieandGitHub 46d1ea6505 [groupBy] groupBy relation fields (#15951)
Example query
Here person has 
- a N - 1 relationship with company
- a N - 1 morph relationship with pet or company

<img width="862" height="374" alt="image"
src="https://github.com/user-attachments/assets/59bc9b82-c943-43de-ad82-d3393b76904b"
/>
<img width="415" height="629" alt="image"
src="https://github.com/user-attachments/assets/9a3176bc-99cd-4983-8611-68ca3a2cf527"
/>

truncated response
<img width="299" height="447" alt="image"
src="https://github.com/user-attachments/assets/45af0322-9e66-4eae-8353-6c0dda487bbe"
/>

We don't allow grouping by relations of relations.

Left to do
- rest api
- tests on permissions
2025-11-25 09:03:16 +00:00
neo773andGitHub 316aec3c40 fix: prevent NUMERIC field type creation via API (#16038)
Block users from creating NUMERIC, POSITION, and TS_VECTOR fields via
the API as these are system-only types. Users should use NUMBER instead
of NUMERIC.

/closes #16023
2025-11-25 09:51:48 +01:00
7109abc311 fix: Invisible content after closing the settings on mobile (#15971)
## Description

- This PR address https://github.com/twentyhq/twenty/issues/15958
- updated settings and main with condition to navigate to
defaultHomePagePath for main page
- updated search with context before opening search hence it resolve the
issue of search showing blank on settings page


## Before


https://github.com/user-attachments/assets/26eb50a0-fb59-4f70-9647-b8150dfdfa40




## After



https://github.com/user-attachments/assets/436fd869-fc0f-4921-98b9-d5eafa67a07f

---------

Co-authored-by: Marie Stoppa <marie.stoppa@essec.edu>
2025-11-24 19:51:04 +01:00
WeikoandGitHub 04562b11fb Migrate metadata cache (#16030)
## Context
Deprecating legacy ObjectMetadata from cache in favor of flat entities.
Introducing utils to build byName/byNameSingular/byNamePlural in
isolated cases

## Next
- I had to introduce a util to build from flat to legacy
objectMetadataMaps, we should instead use flat maps directly when needed
(datasource, schema generation, etc)
- Deprecate metadata version in the cache
- Use the new cache strategy for flat entities with permissions and
feature flags and inject in the global datasource context
2025-11-24 19:50:47 +01:00
Raphaël BosiandGitHub 26e2fe349f Fix page layout widget deletion (#16035)
With the new side panel, we are able to delete a widget with the side
panel still open. This caused the app to crash because we threw when the
widget id wasn't defined.

This PR fixes this by closing the side panel in the delete action and by
returning null instead of throwing.

## Before



https://github.com/user-attachments/assets/092bfe62-82dc-4d83-9967-1cc753ecf55e



## After


https://github.com/user-attachments/assets/8bed6cc5-961b-4112-8cf5-e587865d14da
2025-11-24 19:50:10 +01:00
Charles BochetandGitHub b2472b30c4 Add logs to debug user being disconnected randomly (#16037)
As per title, just adding logs to troubleshoot:
https://github.com/twentyhq/twenty/issues/13103
2025-11-24 19:49:02 +01:00
30b6907c44 i18n - docs translations (#16036)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-24 19:22:22 +01:00
EtienneandGitHub 208c0857ee common api - null equivalence (#15926)
closes https://github.com/twentyhq/core-team-issues/issues/1629

To do before requesting review : 
- filter update

Migration to come in an other PR


Strat : 
1/  Null transformation

- [x] Transform NULL equivalent value to NULL in field validation in
common api - pre-query - with feature flag
- [ ] Same logic in ORM (Not done, complex to handle feature flag here)
- [x] Transform NULL value to equivalent in data formatting in ORM -
post-query

2/ Migration (in other PR) for fieldMetadata not nullable with default
defaultValue (empty string, ...)

- [ ] Remove NOT NULL db constraint
- [ ] Update record value to NULL
- [ ] Update field metadata : isNullable:true
- [ ] Update uniqueIndex whereClause (also for standard uniqueIndex) 
- [ ] Activate feature flag

3/ Update metadata creation

- [x] No more default default value
- [x] Update standard field nullability
- [x] Remove index default whereClause for standard field

4/ Update filter

- [x] When filtering on NULL or empty string, be sure all records are
returned (the one with NULL + the one with "")

5/ Test

- [ ] Strat. to do
2025-11-24 18:57:47 +01:00
3ed6d2a16b i18n - translations (#16034)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-24 18:20:39 +01:00
Paul RastoinandGitHub 439adc6ac0 Restore transaction on WorkspaceCustomApplicationIdNonNullable1763977334519 failure (#16032)
# Introduction
When a transaction query fails it gets aborted, even if we catch the js
exception typeorm ack it and fails
By adding a save point we isolate the issue and restore the transaction
🥷

## Through database:migrate:prod
Tested but lost logs

## Upgrade
```ts

➜  twenty-server git:(fix-migration-runner) ✗ npx nx command twenty-server upgrade

   ✔  3/3 dependent project tasks succeeded [3 read from cache]

   Hint: you can run the command with --verbose to see the full dependent project outputs

———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————


> nx run twenty-server:build  [existing outputs match the cache, left as is]

> rimraf dist

> nest build --path ./tsconfig.build.json

>  SWC  Running...
Successfully compiled: 3747 files with swc (65.82ms)

> nx run twenty-server:command upgrade

query: SELECT * FROM current_schema()
query: SELECT version();
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [NestFactory] Starting Nest application...
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [InstanceLoader] CommandRootModule dependencies initialized
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [InstanceLoader] CommandModule dependencies initialized
// ...
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [InstanceLoader] WorkflowApiModule dependencies initialized
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [InstanceLoader] AuthModule dependencies initialized
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [PgPoolSharedService] Pool sharing will use max 10 connections per pool with 600000ms idle timeout and allowExitOnIdle=true
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [PgPoolSharedService] pg.Pool patched successfully by this service instance.
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [PgPoolSharedService] Pg pool sharing initialized - pools will be shared across tenants
[Nest] 82844  - 11/24/2025, 6:05:11 PM   DEBUG [PgPoolSharedService] No active pg pools to log stats for
[Nest] 82844  - 11/24/2025, 6:05:11 PM   DEBUG [PgPoolSharedService] Pool statistics logging enabled (30s interval)
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [PgPoolSharedService] Created new shared pg Pool for key "localhost|5432|postgres||no-ssl" with 10 max connections and 600000 ms idle timeout. Total pools: 1
[Nest] 82844  - 11/24/2025, 6:05:11 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: New connection established
[Nest] 82844  - 11/24/2025, 6:05:11 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
[Nest] 82844  - 11/24/2025, 6:05:11 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
[Nest] 82844  - 11/24/2025, 6:05:11 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [DatabaseConfigDriver] [INIT] Loading initial config variables from database
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [DatabaseConfigDriver] [INIT] Config variables loaded: 0 values found in DB, 59 falling to env vars/defaults
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [UpgradeCommand] Initialized upgrade context with:
   - currentVersion (migrating to): 1.12.0
   - fromWorkspaceVersion: 1.11.0
   - 3 commands
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [UpgradeCommand] Running global database migrations
[Nest] 82844  - 11/24/2025, 6:05:11 PM     LOG [UpgradeCommand] Running core datasource migrations...
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [UpgradeCommand] query: SELECT * FROM current_schema()
query: CREATE EXTENSION IF NOT EXISTS "uuid-ossp"
query: SELECT version();
query: SELECT * FROM "information_schema"."tables" WHERE "table_schema" = 'core' AND "table_name" = '_typeorm_migrations'
query: SELECT * FROM "core"."_typeorm_migrations" "_typeorm_migrations" ORDER BY "id" DESC
46 migrations are already loaded in the database.
47 migrations were found in the source code.
AddCanBeUninstalledColumnToApplication1763731277403 is the last executed migration. It was executed on Fri Nov 21 2025 14:21:17 GMT+0100 (Central European Standard Time).
1 migrations are new migrations must be executed.
query: START TRANSACTION
query: SAVEPOINT sp_workspace_custom_application_id_non_nullable
query: ALTER TABLE "core"."workspace" DROP CONSTRAINT "FK_3b1acb13a5dac9956d1a4b32755"
query: ALTER TABLE "core"."workspace" ALTER COLUMN "workspaceCustomApplicationId" SET NOT NULL
query failed: ALTER TABLE "core"."workspace" ALTER COLUMN "workspaceCustomApplicationId" SET NOT NULL
error: error: column "workspaceCustomApplicationId" of relation "workspace" contains null values
query: ROLLBACK TO SAVEPOINT sp_workspace_custom_application_id_non_nullable
query: RELEASE SAVEPOINT sp_workspace_custom_application_id_non_nullable
query: INSERT INTO "core"."_typeorm_migrations"("timestamp", "name") VALUES ($1, $2) -- PARAMETERS: [1763977334519,"WorkspaceCustomApplicationIdNonNullable1763977334519"]
Migration WorkspaceCustomApplicationIdNonNullable1763977334519 has been  executed successfully.
query: COMMIT

[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [UpgradeCommand] Database migrations completed successfully
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [UpgradeCommand] Running command on workspace 20202020-1c25-4d02-bf25-6aeccf7ea419 1/2
Computing new Datasource for cacheKey: 20202020-1c25-4d02-bf25-6aeccf7ea419-10 out of 0
[Nest] 82844  - 11/24/2025, 6:05:12 PM   DEBUG [PgPoolSharedService] Reusing existing pg Pool for key "localhost|5432|postgres||no-ssl"
[Nest] 82844  - 11/24/2025, 6:05:12 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
[Nest] 82844  - 11/24/2025, 6:05:12 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
query: SELECT * FROM current_schema()
[Nest] 82844  - 11/24/2025, 6:05:12 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
query: SELECT version();
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [UpgradeCommand] Upgrading workspace 20202020-1c25-4d02-bf25-6aeccf7ea419 from=1.11.0 to=1.12.0 1/2
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [CreateWorkspaceCustomApplicationCommand] Checking standard applications for workspace 20202020-1c25-4d02-bf25-6aeccf7ea419
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [CreateWorkspaceCustomApplicationCommand] 20202020-1c25-4d02-bf25-6aeccf7ea419 skipping custom workspace application creation as already exists
query failed: ALTER TABLE "core"."workspace" ALTER COLUMN "workspaceCustomApplicationId" SET NOT NULL
error: error: column "workspaceCustomApplicationId" of relation "workspace" contains null values
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceCustomApplicationIdNonNullableCommand] Rollbacking WorkspaceCustomApplicationIdNonNullableCommand: column "workspaceCustomApplicationId" of relation "workspace" contains null values
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [SyncWorkspaceMetadataCommand] Running workspace sync for workspace: 20202020-1c25-4d02-bf25-6aeccf7ea419 (0 out of 2)
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncMetadataService] Syncing standard objects and fields metadata
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncMetadataService] Syncing standard objects and fields metadata
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncObjectMetadataService] Comparing standard objects and fields metadata
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncObjectMetadataService] Updating workspace metadata
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncObjectMetadataService] Generating migrations
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncObjectMetadataService] Saving migrations
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncMetadataService] Workspace object migrations took 50.206083000000035ms
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncFieldMetadataService] Updating workspace metadata
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncFieldMetadataService] Generating migrations
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncFieldMetadataService] Saving migrations
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncMetadataService] Workspace field migrations took 79.43987500000003ms
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncFieldMetadataRelationService] Updating workspace metadata
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncFieldMetadataRelationService] Generating migrations
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncFieldMetadataRelationService] Saving migrations
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncMetadataService] Workspace relation migrations took 91.85295899999983ms
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncIndexMetadataService] Syncing index metadata
[Nest] 82844  - 11/24/2025, 6:05:12 PM     LOG [WorkspaceSyncMetadataService] Workspace index migrations took 153.78104199999962ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace object metadata identifiers took 130.9623330000004ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncRoleService] Syncing standard role metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace role migrations took 2.154790999999932ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncAgentService] Syncing standard agent.
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace agent migrations took 2.3623329999991256ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace migrations save took 5.95837500000016ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Executing pending migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Execute migrations took 66.94295799999963ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [SyncWorkspaceMetadataCommand] Finished synchronizing workspace.
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [SetStandardApplicationNotUninstallableCommand] Checking workspace applications for workspace 20202020-1c25-4d02-bf25-6aeccf7ea419
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [SetStandardApplicationNotUninstallableCommand] Successfully updated workspace application
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [UpgradeCommand] Upgrade for workspace 20202020-1c25-4d02-bf25-6aeccf7ea419 completed.
PromiseMemoizer Event: A WorkspaceDataSource for workspace 20202020-1c25-4d02-bf25-6aeccf7ea419 is being cleared. Actual pool closure managed by PgPoolSharedService. Not calling dataSource.destroy().
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [UpgradeCommand] Running command on workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db 2/2
Computing new Datasource for cacheKey: 3b8e6458-5fc1-4e63-8563-008ccddaa6db-6 out of 0
[Nest] 82844  - 11/24/2025, 6:05:13 PM   DEBUG [PgPoolSharedService] Reusing existing pg Pool for key "localhost|5432|postgres||no-ssl"
[Nest] 82844  - 11/24/2025, 6:05:13 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
[Nest] 82844  - 11/24/2025, 6:05:13 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
query: SELECT * FROM current_schema()
[Nest] 82844  - 11/24/2025, 6:05:13 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Client acquired from pool
query: SELECT version();
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [UpgradeCommand] Upgrading workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db from=1.11.0 to=1.12.0 2/2
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [CreateWorkspaceCustomApplicationCommand] Checking standard applications for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [CreateWorkspaceCustomApplicationCommand] Successfully create workspace custom application
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceCustomApplicationIdNonNullableCommand] Successfully run WorkspaceCustomApplicationIdNonNullableCommand
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [SyncWorkspaceMetadataCommand] Running workspace sync for workspace: 3b8e6458-5fc1-4e63-8563-008ccddaa6db (1 out of 2)
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Syncing standard objects and fields metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Syncing standard objects and fields metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncObjectMetadataService] Comparing standard objects and fields metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncObjectMetadataService] Updating workspace metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncObjectMetadataService] Generating migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncObjectMetadataService] Saving migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace object migrations took 19.26008400000046ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncFieldMetadataService] Updating workspace metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncFieldMetadataService] Generating migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncFieldMetadataService] Saving migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace field migrations took 31.371917000000394ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncFieldMetadataRelationService] Updating workspace metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncFieldMetadataRelationService] Generating migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncFieldMetadataRelationService] Saving migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace relation migrations took 36.84983300000022ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncIndexMetadataService] Syncing index metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace index migrations took 43.85666599999968ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace object metadata identifiers took 74.27345799999966ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncRoleService] Syncing standard role metadata
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace role migrations took 1.3081249999995634ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncAgentService] Syncing standard agent.
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace agent migrations took 0.7992909999993572ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Workspace migrations save took 2.1899590000002718ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Executing pending migrations
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [WorkspaceSyncMetadataService] Execute migrations took 33.817165999999816ms
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [SyncWorkspaceMetadataCommand] Finished synchronizing workspace.
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [SetStandardApplicationNotUninstallableCommand] Checking workspace applications for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [SetStandardApplicationNotUninstallableCommand] Successfully updated workspace application
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [UpgradeCommand] Upgrade for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db completed.
PromiseMemoizer Event: A WorkspaceDataSource for workspace 3b8e6458-5fc1-4e63-8563-008ccddaa6db is being cleared. Actual pool closure managed by PgPoolSharedService. Not calling dataSource.destroy().
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [UpgradeCommand] Command completed!
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [PgPoolSharedService] pg Pool for key "localhost|5432|postgres||no-ssl" has been closed. Remaining pools: 0
[Nest] 82844  - 11/24/2025, 6:05:13 PM   DEBUG [PgPoolSharedService] Pool[localhost|5432|postgres||no-ssl]: Connection removed from pool
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [PgPoolSharedService] onApplicationShutdown called in PgPoolSharedService
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [PgPoolSharedModule] Shutting down PgPoolSharedModule
[Nest] 82844  - 11/24/2025, 6:05:13 PM     LOG [PgPoolSharedService] onApplicationShutdown called in PgPoolSharedService

———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

 NX   Successfully ran target command for project twenty-server and 4 tasks it depends on (7s)

      With additional flags:
        upgrade
```
2025-11-24 17:20:07 +00:00
Baptiste DevessierandGitHub ee761a2594 Keep workflow nodes selected unless side panel is closed (#16029)
This PR no longer relies on Reactflow's `selected` property to determine
whether a node is selected. Instead, we rely on the pre-existing
`workflowSelectedNodeComponentState` state. It makes it easier to to
synchronize what's displayed in the side panel and which node is styled
as being selected.

## Demo - workflows


https://github.com/user-attachments/assets/3848c5f9-df51-48e2-8b9c-f083d25d14ed

## Demo - workflow versions


https://github.com/user-attachments/assets/9ac9ec6c-e6b1-4f24-a817-a7349e1b70d6

## Demo - workflow runs


https://github.com/user-attachments/assets/54f955cf-dacc-43f8-b684-01e8a6c15f3b
2025-11-24 18:02:13 +01:00
Raphaël BosiandGitHub 86aff36035 Fix and improve chart type selection (#16033)
The new version of the side panel is smaller so it introduced a
regression on the chart type selection because there was not enough
space for all the chart types to fit with the label.

This PR removes the label to gain some space and display the chart type
label in a tooltip.

## Before

<img width="834" height="1406" alt="CleanShot 2025-11-24 at 17 33 45@2x"
src="https://github.com/user-attachments/assets/76bbea54-af16-4643-9de6-ab3da6741e11"
/>


## After

### Without disabled charts


https://github.com/user-attachments/assets/74d62b86-e440-41f5-a3e6-c5754940c28e

### With disabled charts


https://github.com/user-attachments/assets/f4ce3a3a-5dee-4f41-8b96-5f671794197d
2025-11-24 16:44:28 +00:00
Charles BochetandGitHub d526b07078 Add ability to discard Information Banner (#16019)
Fixes https://github.com/twentyhq/twenty/issues/14028

<img width="1917" height="965" alt="image"
src="https://github.com/user-attachments/assets/eeb5eab7-2c50-48be-8218-af6052b30777"
/>
2025-11-24 17:34:10 +01:00
42fef6e09b add is operand on number field (#16022)
Co-authored-by: martmull <martmull@hotmail.fr>
2025-11-24 16:04:41 +00:00
Paul RastoinandGitHub a735e3dfef Dirty fix twenty cli ci build order issue (#16024)
# Introduction
- fix twenty-apps hello world deps lockfile 
- improve error response format in application resolver
- fixed tests by adding applicationId back to serverless function
service v2

## New log format
We should have a tmp logs folder where we write the errors so the user
can see the whole of them such as what's done in yarn logs
```ts
    console.log
      ✓ Client generated successfully!

      at GenerateService.generateClient (src/services/generate.service.ts:58:13)

    console.log
      Generated files at: /Users/paulrastoin/ws/twenty/packages/twenty-apps/hello-world/generated

      at GenerateService.generateClient (src/services/generate.service.ts:59:13)

    console.error
       Serverless functions Sync failed: {
        message: 'Multiple validation errors occurred while creating serverless function',
        extensions: {
          code: 'METADATA_VALIDATION_FAILED',
          errors: {
            fieldMetadata: [],
            objectMetadata: [],
            view: [],
            viewField: [],
            viewGroup: [],
            index: [],
            serverlessFunction: [Array],
            cronTrigger: [],
            databaseEventTrigger: [],
            routeTrigger: [],
            viewFilter: []
          },
          summary: {
            invalidViewFilter: 0,
            invalidObjectMetadata: 0,
            invalidView: 0,
            invalidViewField: 0,
            invalidIndex: 0,
            invalidServerlessFunction: 0,
            invalidDatabaseEventTrigger: 0,
            invalidCronTrigger: 0,
            invalidRouteTrigger: 0,
            invalidFieldMetadata: 0,
            invalidViewGroup: 0,
            totalErrors: 0
          },
          message: 'Validation failed for 0 object(s) and 0 field(s)',
          userFriendlyMessage: 'Validation failed for 0 object(s) and 0 field(s)'
        }
      }

      63 |         JSON.stringify(serverlessSyncResult.error, null, 2),
      64 |       );
    > 65 |       console.error(
         |               ^
      66 |         chalk.red(' Serverless functions Sync failed:'),
      67 |         serverlessSyncResult.error,
      68 |       );

      at AppSyncCommand.synchronize (src/commands/app-sync.command.ts:65:15)
      at async AppSyncCommand.execute (src/commands/app-sync.command.ts:21:14)
      at async Object.<anonymous> (src/__tests__/e2e/applications-install-delete-reinstall.e2e-spec.ts:28:22)

```
2025-11-24 15:49:58 +00:00
338e5cf74b i18n - docs translations (#16026)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-24 15:21:05 +01:00
Paul RastoinandGitHub 8299488f21 Fix front data model edition + non nullable workspaceCustom application migration (#16016)
# Introduction
Two things:
- Enforcing non nullable workspace custom application Id for any
workspace
- Fixing front non editable data models following
https://github.com/twentyhq/twenty/pull/15911 that associate any custom
entities to an applicationId. The front was putting everything as
readonly when under an app ( we will have to handle the twenty standard
application in the future too )

## Fallback
### Migration
The non nullable migration will fail when released, that's why it's
being swallowed and re-run in an upgrade command post workspace custom
application creation for those that miss one. Allowing the migration to
pass in the end
The typeorm migration still need to exists for any new workspaces

### GetCurrentUser
In order to dynamically display isReadOnly in data model settings we're
fetching the workspaceCustomApplicationId through the `getCurrentUser`
If not fallback this endpoint would throw until we're handling existing
workspaces that do not have a custom workspace application
The fallback should be removed post release
2025-11-24 13:39:04 +00:00
Raphaël BosiandGitHub 2b80d9e015 [DASHBOARDS] Widget duplication (#15979)
## Widget duplication

- Created a shared component for the option menu shared by the record
page, the dashboards and the workflows
- Fix arrow selection in the option menu in workflows, which wasn't
working
- Scroll to the new widget after creation and open the new widget
settings


https://github.com/user-attachments/assets/47b8dade-44bd-4ba2-a81c-01b09e8718d3
2025-11-24 14:38:18 +01:00
8923d2fa0a i18n - docs translations (#16021)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-24 13:23:07 +01:00
b9355ea5a7 i18n - translations (#16020)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-24 12:32:07 +01:00
85b17a5059 i18n - translations (#16017)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-24 12:01:00 +01:00
Baptiste DevessierandGitHub f2df456588 Refactor Widget components (#15996)
## Demo

All components look the same as before.


https://github.com/user-attachments/assets/ddaf49f7-0e78-4755-af88-19d43b349078

## Catalog of all states of WidgetRenderer

Went really complete on all the states of the component.


https://github.com/user-attachments/assets/303f773a-254d-4469-b904-f5cd9831a823
2025-11-24 11:51:32 +01:00
99d60cd48b Adding system objects to workflow search node (v2) (#15965)
This PR adds support for selecting system objects in the workflow Find
Records action.

The implementation includes extracting duplicated dropdown code into a
reusable component and fixing several code quality issues identified in
previous PR feedback.

All code quality concerns have been addressed: proper TypeScript types,
utility function usage, correct memoization, and improved variable
naming.



https://github.com/user-attachments/assets/8d0bd052-d3dd-4e3e-8379-35bfcb18babc

<img width="514" height="812" alt="CleanShot 2025-11-20 at 16 55 14"
src="https://github.com/user-attachments/assets/4b3617e6-628f-4368-be0c-fc87ef4c4ea9"
/>

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-24 11:48:55 +01:00
834d354d46 Command menu follow up improvements (#16007)
Co-authored-by: Devessier <baptiste@devessier.fr>
2025-11-24 11:23:08 +01:00
607dc283d2 i18n - translations (#16014)
Created by Github action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-24 11:21:30 +01:00
0e16b939c5 i18n - translations (#16010)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-23 23:20:27 +01:00
0be228fc85 Attest standard object isActive update regression + TDD tests (#15976)
# Introduction
Related https://github.com/twentyhq/twenty/issues/15846

The root cause is that universalIdentifier is still optional in database
and fallbacked when extracted out of database to standardId. But all
`BaseWorkspaceEntity` and `CustomWorkspaceEntity` share the same
standardId for their default standard fields `createdAt` `deletedAt`
resulting in such compare result in dispatcher

```ts
{
  "initialDispatcher": {
    "createdFlatEntityMaps": {
      "byId": {},
      "idByUniversalIdentifier": {},
      "universalIdentifiersByApplicationId": {}
    },
    "deletedFlatEntityMaps": {
      "byId": {},
      "idByUniversalIdentifier": {},
      "universalIdentifiersByApplicationId": {}
    },
    "updatedFlatEntityMaps": {
      "byId": {
        "55e1568c-eb87-4b8a-9f1b-19bbf6042f3e": {
          "updates": [
            {
              "from": "Deletion date",
              "to": "Date when the record was deleted",
              "property": "description"
            },
            {
              "from": "IconCalendarClock",
              "to": "IconCalendarMinus",
              "property": "icon"
            },
            {
              "from": false,
              "to": true,
              "property": "isLabelSyncedWithName"
            },
            {
              "from": null,
              "to": {
                "displayFormat": "RELATIVE"
              },
              "property": "settings"
            }
          ]
        }
      }
    }
  },
  "fromFlatEntity": {
    "universalIdentifier": "20202020-b9a7-48d8-8387-b9a3090a50ec",
    "applicationId": null,
    "id": "9c97c8bf-1f64-463c-915c-f68f41d3cd60",
    "standardId": "20202020-b9a7-48d8-8387-b9a3090a50ec",
    "objectMetadataId": "e9565126-8351-457b-b003-3ea4c6d253bc",
    "type": "DATE_TIME",
    "name": "deletedAt",
    "label": "Deleted at",
    "defaultValue": null,
    "description": "Deletion date",
    "icon": "IconCalendarClock",
    "standardOverrides": null,
    "options": null,
    "settings": null,
    "isCustom": false,
    "isActive": true,
    "isSystem": false,
    "isUIReadOnly": true,
    "isNullable": true,
    "isUnique": false,
    "workspaceId": "20202020-1c25-4d02-bf25-6aeccf7ea419",
    "isLabelSyncedWithName": false,
    "relationTargetFieldMetadataId": null,
    "relationTargetObjectMetadataId": null,
    "morphId": null,
    "createdAt": "2025-11-20T17:28:45.474Z",
    "updatedAt": "2025-11-20T17:28:45.474Z",
    "kanbanAggregateOperationViewIds": [],
    "calendarViewIds": [],
    "viewGroupIds": [],
    "viewFieldIds": [],
    "viewFilterIds": []
  },
  "toFlatEntity": {
    "universalIdentifier": "20202020-b9a7-48d8-8387-b9a3090a50ec",
    "applicationId": null,
    "id": "55e1568c-eb87-4b8a-9f1b-19bbf6042f3e",
    "standardId": "20202020-b9a7-48d8-8387-b9a3090a50ec",
    "objectMetadataId": "37263f48-6858-4d28-a6e1-5f7321e49c24",
    "type": "DATE_TIME",
    "name": "deletedAt",
    "label": "Deleted at",
    "defaultValue": null,
    "description": "Date when the record was deleted",
    "icon": "IconCalendarMinus",
    "standardOverrides": null,
    "options": null,
    "settings": {
      "displayFormat": "RELATIVE"
    },
    "isCustom": false,
    "isActive": true,
    "isSystem": false,
    "isUIReadOnly": true,
    "isNullable": true,
    "isUnique": false,
    "workspaceId": "20202020-1c25-4d02-bf25-6aeccf7ea419",
    "isLabelSyncedWithName": true,
    "relationTargetFieldMetadataId": null,
    "relationTargetObjectMetadataId": null,
    "morphId": null,
    "createdAt": "2025-11-20T17:28:44.267Z",
    "updatedAt": "2025-11-21T17:17:55.057Z",
    "kanbanAggregateOperationViewIds": [],
    "calendarViewIds": [],
    "viewGroupIds": [],
    "viewFieldIds": [],
    "viewFilterIds": []
  }
}
```

## Impact
- This might be corrupting label and description of an other standard
field of an other object
- Race condition on latest universalIdentifier assigned in cache making
the update sometime accurate sometimes not

## Fix
Will be fixed by the in coming work on applicationId and
universalIdentifier as required in database + upgrade command that will
handle retro-comp. ( won't handle description corruption though, should
be anecdotical )
https://github.com/twentyhq/twenty/pull/15911 ( handling this only for
new workspace, retro comp upgrade command will be coming just after )

## PR scope
- Introduce TDD integration tests as failing
- Added unit test to critical methods that might have been involved in
the root cause ( still worth it to keep )

---------

Co-authored-by: guillim <guigloo@msn.com>
2025-11-23 22:37:28 +01:00
Paul RastoinandGitHub f9ab09c404 Metadata api create entity in workspace custom app (#15911)
# Introduction
Cleaner and fewer scope version of
https://github.com/twentyhq/twenty/pull/15745 ( removed sync-metadata
hack through, too ambitious migration and upgrade )

Please note that this PR won't have any interaction with the existing
sync-metadata
Which mean that the sync metadata does not update the standard entities
applicationId and universalIdentifier, and it won't we will deprecate it
on favor of a workspace migration aka twenty-standard app installation

## API Metadata
Any operation going through the api metadata nows automatically scope
the related entity to the workspace custom application instance. (
optionally passing an applicationId to allow current hacky implem of app
sync service )

We need to either ignore the tests or remove the cli status check from
the blocking status badges for a PR to be merged

## New workspace
Already handled in previous
https://github.com/twentyhq/twenty/pull/15625, when a workspace is
created it gets created a twenty standard and custom workspace instance

All his views and permissions will be prefilled to the its twenty
standard app instance with a specific universalIdentifier

## New universalIdentifier
At the contrary as before with standardIds, universalIdentifier are
unique for a given workspace
This means that createdAt field of both object company and opportunity
will have a unique universalIdentifier whereas they share the same
standardId

## FlatApplication
Introduced the flatApplication and cache. Will migrate existing
`MetadataName` to be `SyncableMetadataName` in a following PR

## What's next
Next we will describe a twenty standard app configuration as json that
will be used to generate a workspace migration that will be run instead
of the sync metadata, in a nutshell we aim to deprecated the sync
metadata
So we can standardize any entity to have a non nullable applicationId
and universalIdentifier

## Upgrade command
Introduced an upgrade command that will create a custom workspace
instance for any workspace that do not have one in order to align with
the new behavior when creating a new workspace
2025-11-23 22:35:17 +01:00
4848bc03f3 Update Name of relation fieldMetadata (#15749)
UpdateOne of a Relation that involves a CustomObject, because the
nameSingular needs to be updated in the fieldMetadata
- nameSingular and namePlural must be provided since they are necessary
for morph name computation
  - label sync should be false


Interesting files to look at:

-
packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/build-default-relation-flat-field-metadatas-for-custom-object.util.ts

- UPDATE =>
packages/twenty-server/src/engine/metadata-modules/flat-object-metadata/utils/rename-related-morph-field-on-object-names-update.util.ts
( also update relation indexes ) needs v2 refactor to handle field
relation name update
- CREATE =>
packages/twenty-server/src/engine/metadata-modules/object-metadata/utils/build-default-relation-flat-field-metadatas-for-custom-object.util.ts
( handle morph instead of previous classic relation )
- DELETE => DONE

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

---------

Co-authored-by: prastoin <paul@twenty.com>
2025-11-23 21:45:30 +01:00
6203b7b3e6 i18n - translations (#16008)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-23 21:21:05 +01:00
neo773andGitHub f2a0b0517a fix ci (#16006) 2025-11-23 21:14:21 +01:00
neo773andGitHub 44c0dcde5b Message channel change 3 fix (#15986) 2025-11-23 20:56:02 +01:00
Lucas BordeauandGitHub 061cc897af Improve record group aggregate query performance (#15828)
This PR is a first step for improving the performance on boards and
table with groups.

It is related to :
https://github.com/twentyhq/core-team-issues/issues/1870

Here we implement only a groupBy query for aggregate values in the group
section.

This also allows to improve the DX of aggregate computing and group by
query creation and parsing.

## Demo 

Main : 



https://github.com/user-attachments/assets/5d2a8077-5322-4928-a551-f03583bcfb87



This PR : 



https://github.com/user-attachments/assets/d0e82b28-72c3-40f0-b5cb-045f1a736ffb



## Aggregate update bug fix

This PR also solves a bug with aggregate update that was already present
on main.

The bug is linked to core views not being updated properly during a
modification of the aggregate operation on a view.

We should probably improve the view lifecycle and state management
because it is a bit too complex right now.

Main : 


https://github.com/user-attachments/assets/10dbfb8b-dfa0-4f21-8698-d222871a43e7

This PR : 


https://github.com/user-attachments/assets/bac41890-5191-4e4c-b82b-19b1039e9ab5

## Miscellaneous 

- Fixed optimistic rendering of group by queries, when adding a new
record, the aggregate recomputes well.

## TODO 

- We might want to improve the optimistic for group by queries that
don't have records nor more than one dimension.
2025-11-23 20:40:23 +01:00
4d55fef874 i18n - docs translations (#16002)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-22 15:20:14 +01:00
e209793e2d i18n - translations (#16001)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-22 13:56:45 +01:00
Charles BochetandGitHub 30e504628c Fix ORM event mixing records in batch updates (#15985)
While investigating the issue a customer was facing, I discovered that
before records and after records could be in different order, making the
orm event and timeline activity engine mix records
2025-11-22 13:16:04 +01:00
b711c11431 message channel change 4 (#15936)
Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-22 07:49:47 +01:00
martmullandGitHub aa5d30a911 Fix twenty cli (#15997)
As title

fixes "app add" and "app init" commands
adds tests
2025-11-21 19:21:30 +01:00
3b5949ec3c i18n - translations (#15994)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-21 17:21:42 +01:00
a87263e88a i18n - translations (#15993)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-21 16:27:15 +01:00
04b0a65e73 feat: fix Command Menu Side Panel Layout (#15883)
[Figma
Design](https://www.figma.com/design/xt8O9mFeLl46C5InWwoMrN/Twenty?node-id=81380-344641&t=FpjWNOK2gZuDQQfr-0)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Adds a side panel layout for the Command Menu, routes modals into a
local container, updates the top bar and context chips, and standardizes
small button sizes.
> 
> - **Command Menu**:
> - **Side Panel Layout**: Introduces `CommandMenuSidePanelLayout` with
animated width, hosts `CommandMenuRouter`, and provides a modal
container via `ModalContainerContext`.
> - **Top Bar**: Redesign (`CommandMenuTopBar`) with back icon, optional
AI sparkles action, compact height
(`COMMAND_MENU_SEARCH_BAR_HEIGHT=40`), and updated placeholder.
> - **Context Chips**: Adds `CommandMenuLastContextChip` and
`CommandMenuRecordInfo`; extends `CommandMenuContextChip` with `page`
prop; updates `CommandMenuContextChipGroups` to render last chip as
record info when applicable.
> - **Container Simplification**: `CommandMenuContainer` simplified to
just provide contexts and `AgentChatProvider`.
> - **Modal System**:
> - Adds `ModalContainerContext` and updates `Modal` to portal into
provided container; `Modal.Backdrop` supports `isInContainer`.
> - Updates usages (e.g., `UserOrMetadataLoader`, `ActionModal`) to
align with new modal behavior.
> - **Page Integration**:
> - Replaces `PageBody` with `CommandMenuSidePanelLayout` in
`RecordShowPage` and `RecordIndexContainerGater`.
> - Removes global `CommandMenuRouter` from `DefaultLayout` (keeps
keyboard shortcuts).
> - **UI/Styling**:
> - Standardizes several buttons to `size="small"` (e.g., command
actions, open record, options, reply, workflow footer).
> - Adjusts `ShowPageSubContainer` styling when rendered inside command
menu.
>   - Storybook tests updated for new placeholder text.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
81fcaa1456. 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>
Co-authored-by: Devessier <baptiste@devessier.fr>
Co-authored-by: Aman Raj <92664006+araj00@users.noreply.github.com>
Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
Co-authored-by: Paul Rastoin <45004772+prastoin@users.noreply.github.com>
2025-11-21 16:12:41 +01:00
martmullandGitHub 28b8a4f7ec Fix yarn lock (#15992)
as title
2025-11-21 15:53:56 +01:00
martmullandGitHub 445b76fa26 Add uninstall button to application setting (#15988)
As title

<img width="878" height="668" alt="image"
src="https://github.com/user-attachments/assets/b0c9ae1e-036f-4bdd-9bd2-a2a37c2e3b99"
/>
2025-11-21 14:45:07 +00:00
martmullandGitHub 1fa9c45879 Fix twenty sdk (#15991)
As title
2025-11-21 14:28:15 +00:00
Raphaël BosiandGitHub 0b241cc805 Fix widget resize handles intersecting with top bar buttons (#15990)
Fixes https://github.com/twentyhq/core-team-issues/issues/1881 and
https://github.com/twentyhq/twenty/issues/15946



https://github.com/user-attachments/assets/da89f5b3-e977-4a5d-8e8f-4a903eaa7db6
2025-11-21 15:14:15 +01:00
WeikoandGitHub a21d58f43d Add entitySchemas to workspace context and cache (#15966) 2025-11-21 15:07:46 +01:00
Félix MalfaitandGitHub f77fcdcc63 Disable telemetry in tests (#15989)
As per title
2025-11-21 14:32:02 +01:00
Félix MalfaitandGitHub d85785e380 Twenty self hosting app (#15987)
App to manage telemetry/billing (twenty for twenty!)
2025-11-21 14:10:51 +01:00
nitinandGitHub 793119b117 part 1 of filter/sort drill down from charts (#15983)
This Pr handles basic navigation on bar/slice click to the chart's
source objects index view
2025-11-21 12:54:36 +00:00
Baptiste DevessierandGitHub 3e187b4ce3 [Page Layouts] Focus specific tabs on mobile and side panel (#15984)
## On mobile


https://github.com/user-attachments/assets/4a8017b2-56a9-4759-bc18-8d99fed9f80a

## In side panel


https://github.com/user-attachments/assets/f36f0827-699a-4f76-8e84-a8ceaeb71396

## Dashboards

Untouched, but keep working.


https://github.com/user-attachments/assets/fe583f80-ea8d-453e-95ea-6b99175d1899

## Other Record Page Layouts

Untouched, but keep working.


https://github.com/user-attachments/assets/c64f731f-5d28-4585-8cb5-c3940fb1ab6f
2025-11-21 13:39:17 +01:00
WeikoandGitHub 0a2d42e79f Implement workspace cache storage (#15962)
## Context
Implementing a single service managing all the cache scoped to a
workspace, this will be dynamically injected as a WorkspaceContext in
the app during a request lifetime (ingested by the future global
datasource for example).

Usage:

```typescript
this.globalWorkspaceOrmManager.executeInWorkspaceContext(
        authContext,
        async () => {
           // Everything here will have access to a workspaceContext, containing all the cache data + a ready to use datasource with workspace scoped metadata, permissions, feature flags, etc...
           // Internally will call loadWorkspaceContext
        }
```
Note: executeInWorkspaceContext will probably be owned by a higher level
service later and not only the ORM.

```typescript
  private async loadWorkspaceContext(
    authContext: WorkspaceAuthContext,
  ): Promise<WorkspaceContext> {
    const workspaceId = authContext.workspace.id;

    const cache =
      await this.workspaceContextCacheService.get<WorkspaceContextData>(
        workspaceId,
        [
          'objectMetadataMaps',
          'metadataVersion',
          'featureFlagsMap',
          'permissionsPerRoleId',
        ],
      );

    return {
      authContext,
      objectMetadataMaps: cache.objectMetadataMaps,
      metadataVersion: cache.metadataVersion,
      featureFlagsMap: cache.featureFlagsMap,
      permissionsPerRoleId: cache.permissionsPerRoleId,
    };
  }
  ```
  
  The cache retrieval strategy is as followed:
```
- Check if there is an ongoing promise fetching data from the cache =>
return the promise.
- Check in the local cache entry if lastCheckedAt has expired. If not,
return as it is without querying redis.
- Check in redis the cache entry hash and compare with local cache entry
hash, if they are the same return the local cache entry data
- Check in redis the cache entry data, if it's there return it and store
it into the local cache entry data and update local cache entry hash. If
it's not there recompute the data by querying the DB and update both
redis and local cache
```
2025-11-21 12:44:24 +01:00
a95fff82cc i18n - docs translations (#15981)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-21 11:15:42 +01:00
Abdullah.andGitHub 991bb6dbbf fix: crash in HeaderParser in dicer. (#15963)
Resolves [Dependabot Alert
74](https://github.com/twentyhq/twenty/security/dependabot/74).

Upgraded `graphql-upload` from `13.0.0` to `16.0.2`. Type exports
changed. API remains the same.

Tested the following upload flows:
- profile picture
- workspace logo
- rich text editor (image, video, file)
- record profile picture
- file associated to record.

They all work as intended, nothing breaks.
2025-11-21 11:09:47 +01:00
neo773andGitHub f82325b66b handle HTTP 410,404 in GmailMessagesImportErrorHandler (#15969)
Noticed this in prod, we currently return `undefined` instead of
handling it.
2025-11-21 11:06:21 +01:00
neo773andGitHub dc3e30b115 message channel change 5 (#15964) 2025-11-21 11:05:12 +01:00
31ca2a46c5 i18n - translations (#15980)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-21 10:56:57 +01:00
a3c0d274ea Updated by extension (#15937)
Working updated by extension which shows the workspace member behind the
newest change

---------

Co-authored-by: Charles Bochet <charlesBochet@users.noreply.github.com>
2025-11-21 10:28:44 +01:00
fdb4e4ef10 [DASHBOARDS] Use a time scale when the primary axis is a date on the Bar Chart (#15932)
Closes https://github.com/twentyhq/core-team-issues/issues/1891

Create empty buckets according to the date granularity

Video QA:


https://github.com/user-attachments/assets/86c0f817-35b3-4bab-b093-d11491684b82

Note: We would also need to create empty buckets for cyclic
granularities (DAY_OF_THE_WEEK, MONTH_OF_THE_YEAR, QUARTER_OF_THE_YEAR).
TODO:
- Always order the cyclic granularities Monday -> Sunday (take
firstDayOfTheWeek into account), January -> December, Q1 -> Q4. For now
they are returned by the backend in alphabetical order, which doesn't
make much sense
- Remove the translation into the user's locale of these granularities
from the backend because otherwise we can't reconstruct the missing days
or month in the frontend since they will be translated

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-21 10:24:19 +01:00
c737042209 i18n - translations (#15967)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-20 19:22:24 +01:00
8d021d2719 i18n - docs translations (#15945)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-20 18:33:17 +01:00
Félix MalfaitandGitHub a281f2a773 feat: add configurable response format for AI agents (text/JSON) (#15953)
## Summary
This PR adds configurable response format support for AI agents,
allowing them to return either plain text or structured JSON data based
on a defined schema.

## Key Features

### 1. Agent Response Format Configuration
- Added `AgentResponseFormat` type supporting:
  - `text`: Returns plain text responses (default)
  - `json`: Returns structured JSON based on defined schema
- New `AgentResponseSchema` type moved to `twenty-shared/ai` for sharing
between frontend/backend

### 2. Settings UI
- New `SettingsAgentResponseFormat` component for configuring response
format
- Visual schema builder for defining JSON output structure
- Real-time validation and preview
- Integrated into agent settings tab

### 3. Workflow Integration
- AI Agent workflow action automatically uses agent's configured
response format
- Output schema dynamically generated from agent's response format
- Workflow variable picker shows structured fields for JSON responses
- Backward compatible with existing text-only agents

### 4. Backend Implementation
- Added `convertAgentSchemaToZod` utility to validate JSON responses
- Agent executor service handles both text and JSON generation
- Automatic agent creation/cloning when adding AI agent steps to
workflows
- Unique agent naming with conflict resolution

### 5. Database Migration
- Migration `1763622159656-update-agent-response-format.ts` 
- Sets default `responseFormat` to `{"type":"text"}` for existing agents
- Updated all standard agents with proper response format

## Changes by Module

### Frontend (`twenty-front`)
- 🆕 `AgentResponseFormat` type
- 🆕 `SettingsAgentResponseFormat` component
- ✏️ Updated `WorkflowEditActionAiAgent` to support response format
configuration
- 🗑️ Removed deprecated `useAiAgentOutputSchema` hook and
`AiAgentOutputSchema` type

### Backend (`twenty-server`)
- 🆕 `AgentResponseFormat` type in agent entity
- 🆕 `convertAgentSchemaToZod` utility for schema validation
- ✏️ Updated `AiAgentExecutorService` to handle both text and JSON
generation
- ✏️ Updated `WorkflowSchemaWorkspaceService` to generate output schema
from agent config
- ✏️ Enhanced `WorkflowVersionStepOperationsWorkspaceService` with agent
creation/cloning
- 🆕 Agent naming constants for conflict resolution

### Shared (`twenty-shared`)
- 🆕 `AgentResponseSchema` type
- 🆕 `ModelConfiguration` type moved to shared package
- Updated exports in `ai/index.ts`

## Code Quality
- Removed useless comments following code style guidelines
- All linter checks passed
- Type-safe implementation with proper TypeScript types

## Testing
-  Database migration tested
-  Agent creation/cloning in workflows verified
-  Response format switching (text ↔ JSON) validated
-  Backward compatibility with existing agents confirmed

## Migration Notes
- Existing agents will have `responseFormat: {type: 'text'}` set
automatically
- No breaking changes - all existing functionality preserved
- Agents can be updated to use JSON format through settings UI
2025-11-20 18:32:44 +01:00
neo773andGitHub 5476879f77 Handle Microsoft calendar sync cursor error (#15938)
Resolves https://twenty-v7.sentry.io/issues/6567295627
2025-11-20 16:32:44 +01:00
Paul RastoinandGitHub e5255df1a1 Fix and refactor relation field name collision validation (#15920)
# Introduction
Fixes https://github.com/twentyhq/private-issues/issues/371
We weren't strictly validating relation field collision on join column
name availability of the target field object

## Refactor
Extracted morph or relation specific condition out of the common flat
field metadata name validate availability to be located in the dedicated
morph or relation flat field validator

## Tests
Added two tests, ONE_TO_MANY and MANY_TO_ONE in order to cover the use
case
2025-11-20 15:10:35 +00:00
Baptiste DevessierandGitHub 9c6d8330df Bring back companies focused actions (#15961)
We want to release the readonly mode of record page layouts before the
edit mode. We will think about adding actions related to page layout
edition later.


https://github.com/user-attachments/assets/2c2213d2-80b8-4d6f-b4bf-e023ac9d2906

Closes https://github.com/twentyhq/core-team-issues/issues/1818
2025-11-20 15:53:34 +01:00
Abdullah.andGitHub c7783de930 Introduce Dependabot config for SOC2 compliance. (#15956) 2025-11-20 15:24:26 +01:00
c7aa59491b Fix merge button (#15899)
Fixes https://github.com/twentyhq/private-issues/issues/362

**How to reproduce**
Link a person that has a duplicate to an opportunity. (you can create a
duplicate by giving two people the same linkedin link).
Open the opportunity record from opportunity table. 
Click on the related person (in "Point of contact").
In front of "Duplicates", click on the merge button (two arrows becoming
one).
You should here see an empty "Merge preview" and an error when clicking
"First" tab.

**Issue**
The issue is that CommandMenuMergeRecordPage is getting the referenced
objectMetadataItem from useContextStoreObjectMetadataItemOrThrow without
an instance id. contextStoreObjectMetadataItem is still "opportunity" as
it should be, being on an opportunity view.
So further down it attempts to display the record page according the
label identifier field from opportunity, which is a text field, "name",
and it breaks because the record is actually a person for who the "name"
field is not a text but a full_name type.

**Fix**
I suggested a fix that offers the possibility to find the referenced
objectMetadataItem from the MergeRecords instanceId. But I still gave
flexibility to avoid having to set that state everytime we open the
merge tab, by falling back to the default
contextStoreObjectMetadataItem. (this is used when we merge records from
ticking two records from a view and open the command menu).
Im not sure this is the best option. Open to suggestions !

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-20 13:58:40 +01:00
martmullandGitHub 6607fe0504 Fix wrong empty string formatting (#15949)
As title, solves this kind of issues
https://twentyfortwenty.twenty.com/object/workflowRun/d6aca50e-68ba-4715-8835-ea22bd44fb88

Solves null currencyDisplay when null currencyCode and null amountMicros

### Before
<img width="147" height="81" alt="image"
src="https://github.com/user-attachments/assets/d250d65e-b984-43f4-ad67-1397a684cf6a"
/>

 ### After
 
<img width="128" height="74" alt="image"
src="https://github.com/user-attachments/assets/4f9c9d80-f8bb-495a-9be0-ecfb984ded81"
/>
2025-11-20 12:11:16 +01:00
CopilotGitHubcopilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>Devessier
a1bfab82df Remove VITE_DISABLE_ESLINT_CHECKER environment variable (#15943)
The `VITE_DISABLE_ESLINT_CHECKER` environment variable is removed from
the codebase. ESLint checker no longer runs during Vite builds
(equivalent to the previous `VITE_DISABLE_ESLINT_CHECKER=true`
behavior).

**Configuration**
- Removed from `.env.example` (active and commented lines)
- Removed from `vite.config.ts` destructuring and conditional logic
- Removed from build scripts in `package.json` and `nx.json`

**Code change in vite.config.ts:**
```diff
- if (VITE_DISABLE_ESLINT_CHECKER !== 'true') {
-   checkers['eslint'] = {
-     lintCommand: 'eslint ../../packages/twenty-front --max-warnings 0',
-     useFlatConfig: true,
-   };
- }
```

**Documentation**
- Updated main English troubleshooting guide to remove references to the
variable
- Translated documentation files are intentionally not modified and will
be handled by a separate workflow

> [!NOTE]
> ESLint will not run in the background via Vite's checker plugin.
Developers will need to run `npx nx lint twenty-front` manually or rely
on their IDE's ESLint extension for real-time feedback on open files.

Created from VS Code via the <a
href="https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-pull-request-github">GitHub
Pull Request</a> extension.

<!-- START COPILOT CODING AGENT SUFFIX -->



<details>

<summary>Original prompt</summary>

> Your job is to delete everything related to
VITE_DISABLE_ESLINT_CHECKER in the codebase.
> 
> We mention this env var in documentation: drop the content talking
about it.
> 
> We use it in the vite config: drop the check and keep the code paths
that used to run when `VITE_DISABLE_ESLINT_CHECKER=true`.
> 
> User has selected text in file packages/twenty-front/.env.example from
3:1 to 3:28


</details>

Created from VS Code via the [GitHub Pull
Request](https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-pull-request-github)
extension.

<!-- START COPILOT CODING AGENT TIPS -->
---

 Let Copilot coding agent [set things up for
you](https://github.com/twentyhq/twenty/issues/new?title=+Set+up+Copilot+instructions&body=Configure%20instructions%20for%20this%20repository%20as%20documented%20in%20%5BBest%20practices%20for%20Copilot%20coding%20agent%20in%20your%20repository%5D%28https://gh.io/copilot-coding-agent-tips%29%2E%0A%0A%3COnboard%20this%20repo%3E&assignees=copilot)
— coding agent works faster and does higher quality work when set up for
your repo.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Devessier <29370468+Devessier@users.noreply.github.com>
2025-11-20 11:38:43 +01:00
98e44ed92a feat: use relative and absolute dates in email (#15827)
Closes #15322

Used `formatToHumanReadableDate` to show absolute dates, rather than
only relative dates. When the date is clicked, it flips between relative
and absolute. The click on the date, doesn't show or hide the email
body. Attaching a recording of the same below.



https://github.com/user-attachments/assets/77adcd3e-8efe-4af9-a57e-6317c93bcf22



https://github.com/user-attachments/assets/0731de02-60bb-42b1-a28c-55a94cff24b8

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-20 10:09:44 +00:00
EtienneandGitHub 8998f3bd84 Fix int tests - update snapshots (#15944)
because of integration tests not working yesterday,
[PR](https://github.com/twentyhq/twenty/pull/15931) has been merged with
not updated snapshots
2025-11-20 10:05:49 +00:00
Raphaël BosiandGitHub 3c3d837cb7 Introduce primary actions (#15826)
- These actions are displayed in the accent color
- Added new context store state
`contextStoreIsPageInEditModeComponentState`
- Reverted the order in which the actions are displayed (the first
action should appear to the right of the top bar action menu)



https://github.com/user-attachments/assets/3a0769cf-61ed-4619-8c4d-e3a01765b63c
2025-11-20 10:57:33 +01:00
martmullandGitHub 3190ca5b9e 1858 extensibility create relation metadata decorator in thwenty sdkapplications (#15907)
as title

First PR 
I will update the twenty-cli in another PR
2025-11-20 10:22:42 +01:00
Paul RastoinandGitHub 89d166ece6 fix(server): ssr front (#15934) 2025-11-19 19:16:46 +01:00
EtienneandGitHub 674ddbd525 Fix raw json validation (#15931)
Before validation in common layer, stringified json were accepted in raw
json field. Fix regression

related to
https://discord.com/channels/1130383047699738754/1130383048173682821/1440723288090218636
2025-11-19 19:05:02 +01:00
Aman RajandGitHub 0223851620 Fixed eslint warnings on changed files (#15928) 2025-11-19 17:13:07 +01:00
neo773andGitHub 67846c05bf revert PR 12884 (#15922)
this PR never really addressed the root cause which was later addressed
in the auth refactor PR so reverting this as it's also causing some
errors.
2025-11-19 14:28:00 +01:00
Félix MalfaitandGitHub bf638c3a4e Fix file controller route parameter extraction (#15924)
## Problem
When accessing file URLs like `/files/attachment/{token}/{filename}`,
the server was returning 500 errors with no logs. The issue was that the
route pattern `*path/:filename` was not properly extracting parameters,
causing `request.params[0]` to be undefined.

## Solution
- Changed route from `@Get('*path/:filename')` to
`@Get(':folder/:token/:filename')` for explicit parameter extraction
- Simplified `extractFileInfoFromRequest` to use named route parameters
directly instead of complex path parsing
- Removed unnecessary logging that was added during debugging
- Added test to verify route parameters are correctly extracted and
passed to FileService

## Testing
- Added unit test that verifies folder, token, and filename parameters
are correctly passed to the service
- Test will catch any future regressions where route parameters are not
properly extracted
2025-11-19 14:12:34 +01:00
ca29357d37 i18n - docs translations (#15923)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-19 13:22:56 +01:00
9ad3b7be84 i18n - translations (#15919)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-19 11:36:58 +01:00
Félix MalfaitandGitHub 783fe8d387 Agent role edition (#15914)
## 🐛 Issues Fixed

### 1. Role Editing Not Working for New Agents
When creating a new agent and then creating a role for it, the role
permissions appeared as non-editable. This was caused by:
- In create mode, `agentId = ''` (empty string from `useParams`)
- Empty string is **falsy** but `isDefined('')` returns **true**
- This caused incorrect behavior in role exclusivity checks and API
calls

### 2. Missing Role Data Loading
The agent form wasn't loading role data needed for permission editing
because it was missing the `SettingsRolesQueryEffect` component.

### 3. Navigation Conflicts
The `useSaveDraftRoleToDB` hook contained navigation logic that caused
conflicts when used from different contexts (role detail page vs agent
form).

### 4. Linting Errors
Unused `useIcons` import in `SettingsAgentRoleTab.tsx`.

---

## 🔧 Changes Made

### Agent Role Tab (`SettingsAgentRoleTab.tsx`)
-  Use `isNonEmptyString(agentId)` to validate agentId (follows
codebase patterns)
-  Improved role exclusivity logic to handle both create and edit
modes:
  - **Edit mode**: Role must be assigned exclusively to this agent
  - **Create mode**: Role must not be assigned to anyone yet
-  Only call `assignRoleToAgent` when a valid agentId exists
-  Pass `undefined` instead of empty string for `fromAgentId` prop

### Role Hook (`useSaveDraftRoleToDB.ts`)
-  Removed navigation logic from the hook (better separation of
concerns)
-  Removed `useNavigateSettings` and `SettingsPath` dependencies
-  Hook now only handles data persistence, not navigation

### Role Component (`SettingsRole.tsx`)
-  Added navigation after successful role creation in create mode
-  Navigation now handled by the component using the hook

### Agent Form (`SettingsAgentForm.tsx`)
-  Added `SettingsRolesQueryEffect` to ensure role data is loaded
-  Agent form handles its own navigation after save

---

##  Testing Scenarios

All these scenarios now work correctly:
1.  Create new agent → Create role → Edit permissions → Save agent
2.  Edit existing agent → Create role → Edit permissions → Save
3.  Edit existing agent → Try to edit shared role (shows warning
message)
4.  Navigate to object-level permissions from agent form with proper
breadcrumbs

---

## 📝 Technical Details

### Root Cause Analysis
The main issue was that empty string was being treated differently in
different checks:
- `agentId &&` → evaluates to `false` (empty string is falsy)
- `isDefined(agentId)` → returns `true` (empty string is defined)

This inconsistency caused the role to appear as non-editable and
attempted invalid API calls.

### Solution
Used `isNonEmptyString()` from `@sniptt/guards` which properly checks
both that the value is defined AND not empty, following codebase
conventions.

---

## 🎯 Impact

- Fixes critical bug preventing role permission configuration for new
agents
- Improves code quality with better separation of concerns
- Makes navigation logic more predictable and maintainable
- Follows codebase patterns and guidelines
2025-11-19 11:26:05 +01:00
92fb4c708b i18n - docs translations (#15917)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-19 11:21:41 +01:00
4b0d1cd848 Fixed immediate UI update after Enter on single-item fields (#15825)
Previously, single-item fields `maxItemCount: 1` didn’t show updated
values after pressing `Enter` the UI only refreshed on click outside.
This happened because the items list was hidden while
`shouldAutoEditSingleItem` remained true.

This PR updates the render condition to also check `!isInputDisplayed`,
ensuring the items list re-renders immediately after editing.

**Result:** Instant UI updates on Enter with no impact on multi-item
fields.

Fixes #15792

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-19 11:15:17 +01:00
nitinandGitHub eab123f999 Custom data point labels for line chart (#15793)
https://github.com/user-attachments/assets/a3074292-acc7-4117-add4-8b3f8d00673e
2025-11-19 11:00:30 +01:00
Raphaël BosiandGitHub 5b52ac992e [DASHBOARDS] Tab duplication (#15906)
Closes https://github.com/twentyhq/core-team-issues/issues/1878

- Allow tab duplication
- Add autofocus on the tiltle input upon the creation and duplication of
tabs and the creation of widgets
- Fix a bug where cancelling the edition while on a new tab, by
resetting the active tab id if it's not in the persisted tabs


https://github.com/user-attachments/assets/a4dc2f0b-1a56-406a-bde7-cca17f9cdbc1
2025-11-19 10:57:37 +01:00
d4e85376ea i18n - docs translations (#15913)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-18 19:22:08 +01:00
bcb097256b fix-15838 (#15898)
I know you did this change in order to make the frontend faster and less
resource eating. However it broke this optimistic rendering part
@lucasbordeau.

I suggest this quick fix, but I am open to a sharper one as well

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

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-18 18:49:18 +01:00
f6cd51ba97 feat: Support custom fields in calendar event detail panel (#15853)
## Overview
This PR refactors the `CalendarEventDetails` component to dynamically
display both standard and custom fields added via the metadata API,
instead of using a hardcoded field list.

## Changes
- Replaced hardcoded `fieldsToDisplay` array with dynamic field fetching
using `useFieldListFieldMetadataItems` hook
- Split fields into `standardFields` (maintaining original order) and
`customFields`
- Introduced `renderField` helper function to eliminate code duplication
- Custom fields now automatically appear at the bottom of the detail
panel after standard fields
- Maintained exact field order and all existing functionality including
participant response status display

## Technical Details
- Uses existing `useFieldListFieldMetadataItems` pattern already
established in the codebase
- Standard field order explicitly defined: startsAt, endsAt,
conferenceLink, location, description
- Participant response status (Yes/Maybe/No) correctly positioned
between first 2 and last 3 standard fields
- All fields respect permissions and visibility settings from metadata

## Testing
-  Verified all standard fields display in correct order
-  Added custom field `mycustomfieldtest` via metadata API - displays
correctly at bottom
-  Participant responses (Yes/Maybe/No) render correctly with avatars
-  Event title, creation date, and event chip display properly
-  Canceled event styling (strikethrough) works
-  No console errors or regressions detected
-  Read-only behavior maintained (calendar events sync from external
sources)

## Screenshots

<img width="1401" height="746" alt="CleanShot 2025-11-17 at 11 23 57"
src="https://github.com/user-attachments/assets/3d967ec5-6d31-4fc3-b971-c73ea521c87d"
/>


## Related
This enables users to extend calendar events with custom metadata fields
that will automatically display in the UI without code changes.

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-18 18:11:07 +01:00
6fa75e1360 i18n - translations (#15908)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-18 18:01:56 +01:00
Abdullah.andGitHub 9c61b625a1 Remove the redundant nx/js package from twenty-server since root has it. (#15905)
There was an extra definition of @nx/js inside twenty-server, which was
not recognized during upgrade by the CLI. This caused two versions of
@nx/js in the repo - 22.0.3 from root and 21.3.11 from the twenty-server
package.

Removed the one inside twenty-server to maintain a single source of
truth.
2025-11-18 17:41:45 +01:00
MarieandGitHub 5bb4abc23d Add optional limit variable to groupBy queries (#15885)
Closes https://github.com/twentyhq/core-team-issues/issues/1600.

Two remarks 
- This `limit` variable does not reduce postgre's work at it still needs
to scan the whole table. It did not seem possible to me to optimize this
as we cannot foresee which dimensions will be used by the user, and an
optimization could only result from an index on the dimension(s) (e.g.:
group companies by addressCity limit 50 can be optimized if we have an
index on companies.addressCity + we had a default orderBy on
adressCity). But this will still optimize the FE which at the moment
receives all groups and truncates the result.
- I have not done the work on the FE as the addition of limit is a
breaking change, and will break until the workspaces' schema is rebuilt,
so we need to flush the cache. I think this could be acceptable as the
feature is in the lab but I preferred not doing it yet as it would have
no impact since in the BE I added a default limit to 50 groups, and I
expect more FE work will be done to allow the user to choose their own
limit
2025-11-18 17:25:33 +01:00
Ali IlmanandGitHub be7c2ad40a [ENHANCEMENT] [ACTIVITY-SUMMARY] Improvisations post-hacktoberfest (#15882)
## Background
Team Comfortably Summed had submitted Activity Summary for Twenty's
Hacktoberfest. This is a follow-up PR post-Hacktoberfest.

## Changes
### Purpose
>_What is the objective?_

To improve the code based on human and bot comments from the initial
Hacktoberfest PR, and to improve the robustness of task completion
calculation.
>_Are we solving a problem or making necessary changes to support an
existing and / or a new feature?_

Making changes to improve existing features.
### Summary
> _Are there files we can ignore?_

None.
> _Please provide a high-level summary of the changes._

- Corrects `README.md` by removing irrelevant commands and unnecessary
configuration notes
- Updates `people-creation-summariser.ts`
- Replaces requesting of company for each person by including `depth=1`
as query parameter in GET /people request as suggested by Martin Muller
– link to comment:
[link](https://github.com/twentyhq/twenty/pull/15510#discussion_r2486019035)
- Updates `senders.ts`
  - Renames `formattedMesage` to `formattedMessage`
- Updates `task-creation-summariser.ts`
- Improves calculation of completed task percentage by relying only on
list of completed tasks and total list of tasks
- The initial implementation includes relying on pending tasks and
pending overdue tasks which can result in undesired calculation outcome
2025-11-18 17:23:11 +01:00
e02c24bd3a i18n - docs translations (#15904)
Created by Github action

---------

Co-authored-by: Abdul Rahman <ar5438376@gmail.com>
Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
Co-authored-by: github-actions <github-actions@twenty.com>
Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-18 17:21:48 +01:00
neo773andGitHub 46149cdb14 add case for calendar revoked refresh token (#15837) 2025-11-18 17:14:31 +01:00
Abdullah.andGitHub 222feb90b4 fix: update glob version to 11.1.0 (#15884)
Some Glob CLI related alerts were generated last night. I believe
they're safe to dismiss since I do not expect us to use the Glob CLI in
production environment, and those alerts do not impact the API, but
still updating the dependency version just in case.

Not sure if this would resolve all/any of the alerts since glob is a
dependency for many other dependencies, so a good number of dependency
variants are pulled in.

The alert that confirms it's just a CLI related vulnerability:
[Dependabot Alert
307](https://github.com/twentyhq/twenty/security/dependabot/307)
2025-11-18 17:12:53 +01:00
neo773andGitHub cbb5bce500 expose imap username field (#15866)
Had an edge with a customer where they had a custom username.
2025-11-18 17:12:02 +01:00
neo773andGitHub 347e855b1f update default message folder import policy to ALL_FOLDERS (#15858) 2025-11-18 16:59:15 +01:00
EtienneandGitHub db48059bea Fix test (#15895) 2025-11-18 16:55:54 +01:00
Thomas des FrancsandGitHub c38f34df26 Release 1.11.0 (#15900)
## Release 1.11.0

This release includes:

- Unlisted Views

Changelog file:
`packages/twenty-website/src/content/releases/1.11.0.mdx`
Release date: 2025-11-18
2025-11-18 16:51:12 +01:00
martmullandGitHub f131a86cc5 Update lock parameters (#15901)
as title
2025-11-18 15:40:42 +00:00
martmullandGitHub ee648197df Set TTL >> max await + increase max await from 1s to 2s (#15892)
- set TTL >> max await
- increase max await from 1s to 2s
2025-11-18 16:25:04 +01:00
Abdullah.andGitHub 47ea2b53d3 fix: bump up js-yaml patch number inside fireflies app (#15890)
Resolves the last remaining js-yaml alert: [Dependabot Alert
304](https://github.com/twentyhq/twenty/security/dependabot/304).

Updates version of js-yaml from 3.14.1 to 3.14.2.
2025-11-18 16:03:56 +01:00
14d3866439 fix: hotkey visibility in buttons with blue accent (#15764)
Closes #15728

## Problem
The `color` of `ButtonHotKeys` was set to `theme.border.color.blue` when
the button accent was blue. This led to poor visibility of the hotkey.

## Solution
The `color` is now set to `GRAY_SCALE_LIGHT.gray7`

## Screenshots
### Before
<img width="278" height="54" alt="image"
src="https://github.com/user-attachments/assets/7dd2c8a4-1230-4b57-9a1d-62564ab15337"
/>
<img width="280" height="52" alt="image"
src="https://github.com/user-attachments/assets/21cc62fb-e1eb-47ce-925c-3658389d24d8"
/>


### After
<img width="274" height="54" alt="image"
src="https://github.com/user-attachments/assets/cfbed222-a807-4af2-ab11-839ef5274186"
/>
<img width="275" height="52" alt="image"
src="https://github.com/user-attachments/assets/602274d8-3af6-4de8-9504-2cb0fe30d5dc"
/>

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-18 14:56:00 +00:00
martmullandGitHub bbe104c27b Fix asset path (#15888)
As title
Fix workflow code step creation error
2025-11-18 13:55:34 +01:00
Abdullah.andGitHub 7d74e17bfc fix: js-yaml has prototype pollution in merge (#15886)
Resolves [Dependabot Alert
309](https://github.com/twentyhq/twenty/security/dependabot/309) and
maybe also a few others.

Bumped up the version for js-yaml to 4.1.1 and 3.14.2 across transitive
dependencies using `yarn up js-yaml --recursive`.
2025-11-18 13:45:15 +01:00
Abdullah.andGitHub d6d7f1bb20 fix: koa related dependabot alerts (#15868)
Resolves [Dependabot Alert
256](https://github.com/twentyhq/twenty/security/dependabot/256) and
[Dependabot Alert
296](https://github.com/twentyhq/twenty/security/dependabot/296).

This is a major bump for `nx` and related packages. Used the CLI to run
nx migrations as recommended by the maintainers. Tested building,
testing and linting packages after resetting the daemon, and did not
come across a breaking issue.
2025-11-18 13:44:45 +01:00
nitinandGitHub 8434610f18 seperate v1 and v2 seeds, make groupMode to add default in case its not provided through api but primary groupBy is present (#15815)
Context - 
- refactoring v1 and v2 seeds to test v2 dashboard flag both on and off
Right now, the db reset command fails if the feature flag is off

- whenever there is a groupBy field -- we should add a default groupMode
- we already do that on the front -- but implementing the same on server
so that api users get the same response

This is also the reason why the second seed on dashboards lags a lot --
because on that particular dashboard's widget -- we set groupBy but no
groupMode (in seeding util) -- and the effect of limiting the bars to
fifty runs depending on the groupMode
2025-11-18 11:29:12 +00:00
Baptiste DevessierandGitHub 6209ba539b Add icons to Record Page Layout tabs (#15871)
## Demo


https://github.com/user-attachments/assets/71ce776a-8d59-4b2c-8579-185fdd749f8f

Closes https://github.com/twentyhq/core-team-issues/issues/1812
2025-11-18 12:25:18 +01:00
76cc07a5f7 Revert x2 - Common - Field validation (#15491) (#15879)
Revert https://github.com/twentyhq/twenty/pull/15821

Should not have been reverted. Conflicting with this
[PR](https://github.com/twentyhq/twenty/pull/15742),
[reverted](https://github.com/twentyhq/twenty/pull/15875)

Co-authored-by: Weiko <corentin@twenty.com>
2025-11-18 12:04:00 +01:00
GuillimandGitHub 9e425ee684 preventing the last item to be unselected (#15873)
Fix https://github.com/twentyhq/twenty/issues/15867
2025-11-18 11:17:49 +01:00
f86c5e78b1 fix(workflow): UUID filter in "Search Records" action (#15817)
## Summary
- add a regression test that reproduces the workflow "Search Records →
ID is <UUID>" failure (issue #15067 / #15746)
- adjust `turnRecordFilterIntoRecordGqlOperationFilter` so UUID filters
fall back to the literal value when no `recordIdsForUuid` context is
provided, always emitting an `in` clause

## Testing
- npx nx test twenty-shared --
--testPathPattern=computeRecordGqlOperationFilter.test.ts
--coverage=false
- Manual: workflow "Search Records" with filter "ID is <UUID>" now
returns the correct record

Fixes #15067
Fixes #15746

---------

Co-authored-by: remi <remi@labox-apps.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-18 10:14:38 +00:00
Baptiste DevessierandGitHub e0d1f74648 Page layout conditional display (#15802)
- Allow widgets to be hidden based on device's type conditions: desktop
or mobile
- Create two widgets for rich text fields on tasks and notes. One widget
is displayed below fields on mobile (and in the right drawer); the other
is displayed on a separate tab on desktop
- In read mode, hide tabs if they contain no visible widgets. If there
is no tab left to display, display at least the first one with no
widgets.
- In edit mode, display all tabs and all widgets.

## Demo


https://github.com/user-attachments/assets/65ef1261-3902-4432-a420-48983b763b2c

Closes https://github.com/twentyhq/core-team-issues/issues/1811
2025-11-18 10:35:38 +01:00
martmullandGitHub d0d90735cb Revert "refactor: Simplify CRUD services to leverage Common API (#157… (#15875)
This reverts commit 11e07f90d2.
2025-11-18 09:44:15 +01:00
Félix MalfaitandGitHub 0fa2a4524a feat: Add filter button to objects table and enable system objects access (#15856)
## Summary
This PR replaces the Active/Inactive accordion sections with a modern
filter dropdown button and enables full access to system objects in
advanced mode.

## Changes

### UI Improvements
-  Replaced accordion sections with a filter button dropdown (matching
the design pattern from the Group filter)
-  Added 'Deactivated' toggle filter (hidden by default, uses
IconArchive)
-  Added 'System objects' toggle filter (only visible in advanced mode,
uses IconSettings)
-  Fixed search input width to properly fill available space
-  Proper button sizing and alignment

### System Objects Support
-  Made system objects visible when 'System objects' filter is toggled
on
-  System objects are now fully clickable and accessible
-  Updated object detail page to support system objects
-  Updated field creation/edit pages to support system objects
-  System objects can now have custom fields added

### Architecture
-  Implemented scalable filter architecture using a single filtered
list
-  Easy to add more filters in the future (e.g., show remote objects)
-  All filters work independently and can be combined

## Testing
- [x] Tested deactivated objects toggle
- [x] Tested system objects toggle (only shows in advanced mode)
- [x] Tested clicking on system objects
- [x] Tested adding custom fields to system objects
- [x] No linter errors

## Screenshots
See attached screenshots in the conversation for the new filter UI.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Adds a filter dropdown to the Settings Objects table (incl.
deactivated/system toggles), enables system objects across
settings/field flows, seeds core views (workspace members, messages,
threads, calendar events), and adds actions for Workspace Members.
> 
> - **Settings UI**
> - **Objects Table**: Replaces Active/Inactive sections with a single
filterable list and dropdown (`Deactivated`, `System objects` in
advanced mode); updates props to `objectMetadataItems` and removes
accordion sections.
> - **Search/UX**: Search input fills available space; inactive rows
show activation/delete menu; active rows remain navigable.
> - **Pages Updated**: `SettingsObjects`,
`SettingsApplicationDetailContentTab` switch to new table API; object
detail and new-field flows use `findObjectMetadataItemByNamePlural`
(works with system objects).
> - **Action Menu**
> - **Workspace Members**: Adds `WORKSPACE_MEMBERS_ACTIONS_CONFIG` with
"Manage members in settings" action; wired into `getActionConfig` for
`WorkspaceMember`.
> - **Server (Core Views Seed)**
> - Adds default views: `workspaceMembersAllView`, `messagesAllView`,
`messageThreadsAllView`, `calendarEventsAllView`; included in
`prefillCoreViews`.
> - Marks workflow entities as system (`WorkflowRun`,
`WorkflowVersion`).
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
6a2856df85. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2025-11-17 19:10:19 +01:00
Abdullah.andGitHub 60ed9b53f4 fix: vercel’s AI SDK's filetype whitelists can be bypassed when uploading files (#15874)
Resolves [Dependabot Alert
301](https://github.com/twentyhq/twenty/security/dependabot/301).

Locked the version of "ai" at 5.0.52 in order to stop it from bumping to
5.0.93 directly when the ^ is introduced since it breaks the code across
multiple files.
2025-11-17 18:03:45 +00:00
Félix MalfaitandGitHub 19ca93b954 Fix auth connection (#15869)
Better to do auth this way than in module
2025-11-17 18:12:48 +01:00
8d7ee47ec5 fix: custom-cron-ui (#15786)
Fixes #14723 

### Summary
Fixes a UI while creating a custom CRON

### Changes Made
- updated `WorkflowEditTriggerCronForm.tsx` to use the predefined
`FormSelectFieldInput.tsx` instead of using `Select.tsx`
- added `hint` prop to `FormSelectFieldInput.tsx`
- updated styling for showing `Upcoming execution time`
- added conditional render for `Schedule` and `Upcoming Execution Time` 
- `Schedule`  section is not rendered in Custom Cron

### Steps to Reproduce (Before Fix)
1. Navigate to - /object/workflow/xxxx
2. Try adding a new Trigger
3. Set Trigger Interval to Cron (Custom)


### Before 

![Screenshot 2025-11-13 at 4 00
29 PM](https://github.com/user-attachments/assets/f85ab0fa-cb71-4257-9659-10e1404f17ed)


### After

![Screenshot 2025-11-13 at 4 00
55 PM](https://github.com/user-attachments/assets/db1d54ef-e5d5-42e2-9de5-c1f91f46088e)

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-17 18:03:41 +01:00
2a44bde848 Dynamic grql api wrapper on application sync (#15791)
# Introduction

Important note: for the moment testing this locally will require some
hack due to latest twenty-sdk not being published.
You will need to build twenty-cli and `cd packages/twenty-cli && yarn
link`
To finally sync the app in your app folder as `cd app-folder && twenty
app sync`

close https://github.com/twentyhq/core-team-issues/issues/1863

In this PR is introduced the generate sdk programmatic call to
[genql](https://genql.dev/) exposed in a `client` barrel of `twenty-sdk`
located in this package as there's high chances that will add a codegen
layer above it at some point ?

The cli calls this method after a sync application and writes a client
in a generated folder. It will make a graql introspection query on the
whole workspace. We should later improve that and only filter by current
applicationId and its dependencies ( when twenty-standard application is
introduced )

Fully typesafe ( input, output, filters etc ) auto-completed client

## Hello-world app serverless refactor

<img width="2480" height="1326" alt="image"
src="https://github.com/user-attachments/assets/b18ea372-b21d-4560-8fbc-1dc348427a95"
/>

---------

Co-authored-by: martmull <martmull@hotmail.fr>
2025-11-17 14:46:59 +01:00
Paul RastoinandGitHub a39efeb1ab [BREAKING_CHANGE/GRAPHQL/OBJECT_METADATA_CREATE_ONE] Remove object/fields/view-fields v1 implementation (#15823)
# Introduction
Remove the v2 feature flag for view-field field-metadata and
object-metadata metadata entities

## Some details
- Disabled nestjs-query for object metadata creation and explicitly
calling it
- removed all v1 integration tests files

## Remarks
Not remove v2 referencing in both filenaming right now will handle that
globally later

## Breaking change
Due to object metadata resolver createOne standardization had to rename
the input from `CreateObjectInput` to `CreateOneObjectInput`
2025-11-17 10:55:19 +01:00
Abdullah.andGitHub c1dcda6475 fix: cookie accepts cookie name, path, and domain with out of bounds characters (#15845)
Resolves [Dependabot Alert
143](https://github.com/twentyhq/twenty/security/dependabot/143).

Used `yarn up @bundled-es-modules/cookie --recursive` to move from
version `2.0.0` to `2.0.1` so that the underlying cookie dependency
version moves from `0.5.0` to `0.7.2`.
2025-11-17 07:36:14 +00:00
Abdullah.andGitHub 321a2bec53 fix: babel has inefficient regexp complexity in generated code with .replace when transpiling named capturing groups (#15844)
Resolves [Dependabot Alert
199](https://github.com/twentyhq/twenty/security/dependabot/199) and
[Dependabot Alert
200](https://github.com/twentyhq/twenty/security/dependabot/200).

Used `yarn up @babel/runtime --recursive` and `yarn up
@babel/runtime-corejs3 --recursive` to move from `7.26.7` to `7.28.4`.

Changelogs do not list any breaking changes when moving between minor
versions, only improvements. The parent dependencies also allow minor
version upgrades.
2025-11-17 08:17:25 +01:00
Abdullah.andGitHub 7a68aa7f48 fix: playwright downloads and installs browsers without verifying the authenticity of the SSL certificate (#15843)
Resolves [Dependabot Alert
293](https://github.com/twentyhq/twenty/security/dependabot/293).

Updates the playwright version used to `1.56.1`. The alert could have
also been ignored since the playwright download only happens in CI and
local environments, not the production environment. However, it's an
easy fix instead of just ignoring the alert.
2025-11-17 08:16:56 +01:00
Paul RastoinandGitHub 48031a7ce2 Runner v2 on cascade delete_field/object + refactor workspace deletion side effect (#15830)
# Introduction
While removing the v1 https://github.com/twentyhq/twenty/pull/15823 I've
encountered the method `objectMetadataService.deleteObjectsMetadata`
that I didn't wanted to migrate as it is and if it's not challenging its
existence legitimacy.

## Motivations
In a nutshell on a workspace deletion object metadata and field metadata
cascading deletion is correclty handled
But that's not the case for all of a workspaces entities ( roles,
workspaceMigrations ) I suspect that we did not defined the foreignKey
explicitly through `typeorm`

## Battle testing v2
I still decided to give a try to a complex operation in the v2 such as a
workspace all object metadata deletion.
Spoiler it failed due to object being interdependent between them and
not being topologically sorted ( morph relation can introduce circular
dep anw ).
Note: Even after removing the delete field on delete object aggregator
we end up with an equivalent circular dep error which an object and its
field metadata identifier connection.

## Elegant `DEFERRED` and `DEFERRABLE` foreign keys
The most safe, low level solution would be to make all field relations
deferrable and start the runner transaction as deferred. But this
requires a quite invasive migration of existing FK

## On cascade solution
I've opted for the quick fix, on object or field deletion spread
cacasde.
It's pretty safe as the builder priorly validates the deletion and and
its related entities integrity
Only for both field and object deletion action types in v2 runner

## Integration coverage
Added a test that will scan a new workspace database core schema tables
and expect now result after workspace deletion through its only user
deletion
2025-11-16 22:03:50 +01:00
Abdullah.andGitHub baa1a1e52f fix: babel vulnerable to arbitrary code execution when compiling specifically crafted malicious code (#15840)
Resolves [Dependabot Alert
95](https://github.com/twentyhq/twenty/security/dependabot/95) - babel
vulnerable to arbitrary code execution when compiling specifically
crafted malicious code.

These were the few options we had for a direct drop-in replacement.
- [x-var](https://www.npmjs.com/package/x-var?activeTab=readme)
- [cross-let](https://www.npmjs.com/package/cross-let)
- [cross-var-no-babel](https://www.npmjs.com/package/cross-var-no-babel)

x-var has the most weekly downloads among the three and it is also the
most actively maintained fork of the original cross-var package that
introduced the vulnerability. There is no syntax difference per the
documentation, but I do not have a windows machine to test.

`cross-var-no-babel` offers the most minimal changes, but is also
abandoned without a public-facing repo.
2025-11-16 20:12:25 +01:00
Félix MalfaitandGitHub 5dfb66917c Upgrade NestJS from 10.x to 11.x (#15836)
## Overview
This PR upgrades all NestJS dependencies from version 10.x to 11.x,
following the [official migration
guide](https://docs.nestjs.com/migration-guide). This builds on top of
the v9 to v10 upgrade completed in PR #15835.

## Changes

### Dependencies Updated
**Core packages (10.x → 11.x):**
- `@nestjs/common`: 10.4.16 → 11.0.8
- `@nestjs/core`: 10.4.16 → 11.0.8
- `@nestjs/platform-express`: 10.4.16 → 11.0.8
- `@nestjs/config`: 3.2.3 → 3.3.0
- `@nestjs/passport`: 10.0.3 → 11.0.0
- `@nestjs/axios`: 3.0.2 → 3.1.2
- `@nestjs/schedule`: ^3.0.0 → ^4.1.1
- `@nestjs/serve-static`: 4.0.2 → 5.0.1
- `@nestjs/cache-manager`: ^2.2.1 → ^2.3.0
- `@nestjs/jwt`: 10.2.0 → 11.0.0
- `@nestjs/typeorm`: 10.0.2 → 11.0.0
- `@nestjs/terminus`: 11.0.0 (already on v11)
- `@nestjs/event-emitter`: 2.1.0 (compatible)

**DevDependencies:**
- `@nestjs/testing`: ^10.4.16 → ^11.0.8
- `@nestjs/schematics`: ^10.1.0 → ^11.0.2
- `@nestjs/cli`: 10.3.0 → 11.0.0

### Code Changes
**Fixed: TwentyConfigModule conditional imports**
- Updated `TwentyConfigModule.forRoot()` to use spread operator for
conditional imports
- Fixes TypeScript error with NestJS 11's stricter DynamicModule type
checking

**Cleanup: Removed unused package**
- Removed `@revertdotdev/revert-react` (not being used anywhere in the
codebase)

## Breaking Changes Addressed

### 1.  Reflector Type Inference
- **Impact**: None - codebase only uses `reflector.get()` method
- **Analysis**: Does not use `getAllAndMerge()` or `getAllAndOverride()`
(the methods with breaking changes)
- **Files reviewed**: feature-flag.guard.ts,
message-queue-metadata.accessor.ts,
workspace-query-hook-metadata.accessor.ts

### 2.  Lifecycle Hooks Execution Order
- **Change**: Termination hooks (`OnModuleDestroy`,
`BeforeApplicationShutdown`, `OnApplicationShutdown`) now execute in
REVERSE order
- **Analysis**: Reviewed all lifecycle hook implementations
  - Redis client cleanup
  - Database connection cleanup (GlobalWorkspaceDataSource)
  - BullMQ queue/worker cleanup
  - Cache storage cleanup
- **Result**: Dependency order is safe - services using connections
clean up before the connections themselves

### 3.  Middleware Registration Order
- **Change**: Global middleware now executes first regardless of import
order
- **Analysis**: Middleware is not registered as global, so execution
order remains consistent
- **Files reviewed**: app.module.ts, middleware.module.ts

## Testing

All tests passing and build successful:

**Unit Tests (283+ tests):**
-  Health module: 38 tests passed
-  Auth module: 115 tests passed (passport v11 integration)
-  REST API: 90 tests passed (middleware and express platform)
-  Feature flags: 17 tests passed (Reflector usage)
-  Workspace: 23 tests passed

**Build & Quality:**
-  Type checking: Passed
-  Linting: Passed
-  Build: 3,683 files compiled successfully

## Verification

Tested critical NestJS functionality:
-  Authentication & Security (JWT, OAuth, guards)
-  HTTP Platform (Express integration, REST endpoints)
-  Dependency Injection (Services, factories, providers)
-  Cache Management (Redis with @nestjs/cache-manager)
-  GraphQL (Query runners, resolvers)
-  Configuration (Environment config)
-  Scheduling (Cron jobs with @nestjs/schedule v4)
-  Lifecycle Hooks (Module initialization and cleanup)
-  Reflector (Metadata reflection in guards)

## Related PRs
- #15835 - Upgrade NestJS from 9.x to 10.x (completed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Upgrades NestJS to v11 and updates routing patterns, auth strategies,
GraphQL schema options, and build/dist paths (scripts, Docker, Nx,
migrations, assets), plus enables Devtools in development.
> 
> - **Backend (NestJS 11 upgrade)**:
> - Bump `@nestjs/*` packages (core, platform-express, jwt, passport,
typeorm, serve-static, schedule, cli/testing/schematics) to v11.
> - Update REST/route-trigger/file controllers to new wildcard syntax
(`*path`).
> - Refactor OAuth (Google/Microsoft) and SAML strategies (abstract base
+ explicit `validate`); minor typings.
>   - Enable `DevtoolsModule` in development.
> - **GraphQL**:
> - Add `buildSchemaOptions.orphanedTypes` for client-config types; keep
Yoga/Sentry setup.
> - **Build/Runtime & Config**:
> - Standardize dist layout (remove `src` in paths): update scripts,
Docker `CMD`, Nx `project.json`, render scripts, TypeORM migration
paths, asset resolution.
> - Adjust `nest-cli.json` (watchOptions, asset globs, migrations
outDir, monorepo/root).
> - Improve config module imports (spread conditional); tsconfig
excludes `node_modules`.
>   - Minor Nx default: `start` target caching disabled.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
1139fd85a9. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2025-11-16 18:20:06 +01:00
Félix MalfaitandGitHub a2a7ff8b4b Upgrade NestJS from 9.x to 10.x (#15835)
## Overview
This PR upgrades all NestJS dependencies from version 9.x to 10.x,
following the [official migration
guide](https://docs.nestjs.com/v10/migration-guide). This is the first
step before upgrading to NestJS 11.x in a future PR.

## Changes

### Dependencies Updated
- `@nestjs/common`: 9.4.3 → 10.4.16
- `@nestjs/core`: 9.4.3 → 10.4.16
- `@nestjs/passport`: 9.0.3 → 10.0.3
- `@nestjs/platform-express`: 9.4.3 → 10.4.16
- `@nestjs/config`: 2.3.4 → 3.2.3
- `@nestjs/event-emitter`: 2.0.4 → 2.1.0
- `@nestjs/testing`: ^9.0.0 → ^10.4.16
- `@nestjs/schematics`: ^9.0.0 → ^10.1.0

### Code Changes
- Fixed `CacheModuleOptions` import from `@nestjs/common` to
`@nestjs/cache-manager` in cache-storage.module-factory.ts

## Breaking Changes Addressed
 **CacheModule Migration**: Already using `@nestjs/cache-manager`
package
 **TypeScript Version**: Using 5.9.2 (requires 4.8+)  
 **Node.js Version**: Using 24.5.0 (requires 16+)  
 **Deprecated APIs**: All v9 deprecations removed in v10 - standard
patterns in use

## Testing
All tests passing and build successful:
-  Health module: 38 tests passed
-  Auth module: 115 tests passed (critical - uses @nestjs/passport)
-  Admin panel: 30 tests passed
-  REST API: 90 tests passed (uses @nestjs/platform-express)
-  Feature flags: 17 tests passed
-  Workspace: 23 tests passed
-  GraphQL query runner: 17 tests passed
-  **Total: 330+ tests passing**
-  Build: 3,683 files compiled successfully
-  Type checking: Passed
-  Linting: Passed

## Verification
Tested critical NestJS functionality:
- Authentication & Security (JWT, OAuth, guards)
- HTTP Platform (Express integration, REST endpoints)
- Dependency Injection (Services, factories, providers)
- Cache Management (Redis with @nestjs/cache-manager)
- GraphQL (Query runners, resolvers)
- Configuration (Environment config)
- Event Emitters (Event-driven architecture)

## Next Steps
This upgrade positions the codebase for the next upgrade to NestJS 11.x,
which will be handled in a separate PR.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Upgrades NestJS to v10, fixes cache module import, and narrows CI
GraphQL generation diff to generated directories.
> 
> - **Backend**
> - **Dependencies**: Upgrade `@nestjs/common`, `@nestjs/core`,
`@nestjs/platform-express`, `@nestjs/passport`, `@nestjs/config`,
`@nestjs/event-emitter`, `@nestjs/testing`, and `@nestjs/schematics` to
v10-compatible versions in `packages/twenty-server/package.json`.
> - **Code**: Update `CacheModuleOptions` import to
`@nestjs/cache-manager` in
`src/engine/core-modules/cache-storage/cache-storage.module-factory.ts`.
> - **CI**
> - **GraphQL**: Restrict schema change detection to
`packages/twenty-front/src/generated` and
`packages/twenty-front/src/generated-metadata` in
`.github/workflows/ci-server.yaml`.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
f621230fcf. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2025-11-15 23:06:13 +01:00
Abdul RahmanandGitHub c0bae491e1 docs: localize navigation tabs and groups for supported locales (#15811) 2025-11-14 22:03:54 +01:00
Baptiste DevessierandGitHub 54f74b2a5a Properly interpret advanced filters boolean values in workflows (#15829) 2025-11-14 19:01:53 +01:00
martmullandGitHub f13c36234f Fix workspace-member-id missing from database events (#15819)
As title
2025-11-14 14:03:49 +00:00
martmullandGitHub b3d85623e6 Remove unexisting mock value (#15822)
removes when signup

<img width="975" height="324" alt="image"
src="https://github.com/user-attachments/assets/93184788-81b9-4a7d-b572-d3bce594444f"
/>
2025-11-14 13:56:01 +00:00
martmullandGitHub 867422627c Revert "Common - Field validation (#15491)" (#15821)
This reverts commit 261cba40ef.
2025-11-14 13:47:22 +01:00
martmullandGitHub df58f4102e Fix typo in command (#15818)
as title
2025-11-14 10:42:26 +00:00
WeikoandGitHub 4dd6edb35a Fix authContext missing in ALS WorkspaceContext for global datasource (#15810)
Fixes https://github.com/twentyhq/twenty/issues/15809

## Context
We recently introduced a global datasource now consuming workspace
context from ALS store however the authContext was missing (only the
workspaceId was there) which "broke" event emission, now missing the
workspaceMemberId

This PR adds the missing authContext so we can access from anywhere in
the datasource. We are still passing it as a parameters on repository
level for legacy but in theory we should be able to remove it from
everywhere and consume the context

<img width="929" height="253" alt="Screenshot 2025-11-13 at 18 58 16"
src="https://github.com/user-attachments/assets/3e04f264-95e6-4831-94f3-fc01603f19bd"
/>
2025-11-14 10:59:15 +01:00
Abdul RahmanandGitHub bff079d3b5 Fix AI chat scroll behavior (#15686) 2025-11-14 01:20:25 +01:00
Lucas BordeauandGitHub 9d43058e50 Fixed hovering of kanban cards (#15808)
This PR fixes the record inline cells that disappeared on board card due
to recent refactors.
2025-11-13 17:49:52 +00:00
WeikoandGitHub 998365457e Improve infer deletion from entities (#15807)
## Context
inferDeletionFromEntities only accepts a set of keys for each entities
that needs deletion. This could be error-prone if tmr we want to add a
new side effect and forget to add the entity when in practice you want
to delete all entities that are in the fromToAllFlatEntityMaps (this is
the case for applications for example)
2025-11-13 18:18:27 +01:00
Raphaël BosiandGitHub 56b3a0e8a5 Fix REST API Delete and Destroy (#15806)
Fixes https://github.com/twentyhq/twenty/issues/15801
2025-11-13 18:14:32 +01:00
9bc5486d0d i18n - translations (#15803)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-13 17:12:39 +01:00
Paul RastoinandGitHub 0fdc7ba834 Twenty-shared tests parses decorator (#15765)
## Introduction
Since we've moved some class validator instances from twenty-server to
twenty-shared tests are red because they do not know how to parse
decorators declarations

We've fixed this by explicitly installing `class-validator` in
`twenty-shared` and configuring jest swc accordingly

## Twenty-server class validator patch
I don't even know if that's something we need anymore
Seems to be a patch either fixing or introducing credit card and phone
number validation
Would prefer discussing the need or not to either before merging this as
it could introduce regression at runtime:
- Centralize the patch to be consumed in both `twenty-server` and
`twenty-shared`
- Remove the patch

We should also document every patch motivations we do as it's quite
though to iterate over a such huge one
2025-11-13 16:06:04 +00:00
8cadd00d34 i18n - translations (#15799)
Created by Github action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-13 16:34:00 +01:00
Félix MalfaitandGitHub cd5d0f9eac Introduce agent hints to reduce context bloat (#15763)
Introducing a new pattern that should reduce token consumption by 90%
for the most common use-cases
2025-11-13 16:15:01 +01:00
261cba40ef Common - Field validation (#15491)
Closes : https://github.com/twentyhq/core-team-issues/issues/1622

To do in other PR : 
- Add migration command for non nullable text, raw_json & array fields
- Add null transformation

---------

Co-authored-by: Weiko <corentin@twenty.com>
2025-11-13 15:45:35 +01:00
Félix MalfaitandGitHub f6ed1e8295 Merge data navigator and manipulator agents (#15761)
Merge data manipulator and navigator agents
2025-11-13 15:25:52 +01:00
Charles BochetandGitHub 9bbe0e7f8e Add message folders control in seed by default (#15789)
As per title
2025-11-13 15:09:13 +01:00
martmullandGitHub ab967bf81f Add profile to twenty-cli authentication (#15778)
As title
Eg: 
<img width="641" height="45" alt="image"
src="https://github.com/user-attachments/assets/0ac159db-ebcf-4c21-af1b-b089ee3b39f8"
/>

Not breaking
2025-11-13 15:08:53 +01:00
0cab2b49fc (breaking change) Allow users with a single workspace to update their email. (#15736)
- Users with a single workspace are allowed to update their email across
`core.user` and `workspace_xyz.workspaceMember`.
- The latter happens asynchronously (built it like this for non-blocking
with multiple workspaces), but since we restrict the email update
functionality to a single user, we can also update the email in
workspaceMember synchronously - I left asynchronous there to receive
feedback on whether we should move to synchronous or not.
- Merged main and resolved conflicts to ensure we use the
`SettingsPermissionGuard` and the updated `workspace.service.ts` code.

One edge-case that I was trying to communicate on Discord: 

Say that an admin is a member of multiple workspaces. Therefore, they
can allow roles with PROFILE_INFORMATION permission to update their
email.

<p align="center">
<img width="553" height="115" alt="image"
src="https://github.com/user-attachments/assets/80382b1f-a9e3-4dac-b606-c2defeb2c330"
/>
</p>

However, since the admin is part of multiple workspaces, he/she cannot
even update own email - the field stays disabled, leading to some
confusion.

<p align="center">
<img width="545" height="255" alt="image"
src="https://github.com/user-attachments/assets/5e6d27db-c9a8-4d5e-9ab6-65c77beae5b4"
/>
</p>

However, the workspace can have another member with admin role or some
other role that has PROFILE_INFORMATION permission flag. That user will
be and should be allowed to update email, so we cannot hide `email` from
dropdown options.

<p align="center">
<img width="585" height="283" alt="image"
src="https://github.com/user-attachments/assets/a670d3ac-cf48-4865-a425-b909093d8420"
/>
</p>

The behavior is fine imo, just a little confusing for members with more
than one workspace.

I have also tested the flow by signing up to YC workspace with my org
google account (twenty.com), then changing email to my personal address.
- After changing, I need to login using Google with my personal account
to access YC workspace again.
- If I login using Google with org google account (twenty.com), a new
user account is created.

This behavior is consistent with Notion and Linear. 

Finally, as for the verification of email, the user is asked to verify
email while they're logged in, but just in case they logout without
verifying, the next login would force them to verify their email in the
email/password flow.

However, for Social/SSO, they must verify before they logout or else
they'd have to contact support for assistance. I have not looked into
how to show verification screen while logging in via Social/SSO yet, but
if that's something critical for completeness here, I shall revisit it.

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2025-11-13 15:00:02 +01:00
Lucas BordeauandGitHub dd0601ab6f Fix phone not empty filter (#15790)
This PR fixes the filter on not empty phones.

We can end up with phone numbers that only have a country code, but it
makes no sense to consider this special edge case "not empty".

If we have no phone number, then it's empty, so this PR applies this
particular use case for NOT EMPTY filter on phone fields.

Fixes https://github.com/twentyhq/twenty/issues/15638
2025-11-13 13:38:56 +00:00
3ef9be6622 message channel change #3 (#15757)
Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-13 14:12:20 +01:00
GuillimandGitHub a3b78f080b removing the picture of morph in the lab (#15787)
cleaning unsued image following a nitpick from another PR
2025-11-13 13:35:27 +01:00
Félix MalfaitandGitHub f9c61833ec Add debug info in AI chat (#15758)
## 🐛 Critical Bug Fix

### Cost Calculation Error (1000x undercharge)
- **Fixed**: Cost conversion utility was calculating credits at 1/1000th
of actual value
- **Before**: `cents * 10` 
- **After**: `(cents / 100) * DOLLAR_TO_CREDIT_MULTIPLIER` 
- **Impact**: Users were being undercharged by 1000x
  - Example: 0.75 cents should = 7,500 credits
  - Bug calculated it as 7.5 credits

---

## 🎯 Code Centralization & DRY

### Unified Cost Calculation
- Centralized all cost conversions to use `convertCentsToBillingCredits`
utility
- Refactored 3 different implementations into 1 single source of truth
- Files updated:
  - `ai-billing.service.ts`
  - `agent-streaming.service.ts` (2 usages)

**Before** (multiple implementations):
```typescript
// Wrong implementation
const credits = cents * 10;

// Verbose implementation  
const costInDollars = costInCents / 100;
const creditsUsed = Math.round(costInDollars * DOLLAR_TO_CREDIT_MULTIPLIER);
```

**After** (unified):
```typescript
const creditsUsed = Math.round(convertCentsToBillingCredits(costInCents));
```

---

##  UI Component Refactoring

### RoutingDebugDisplay.tsx
- **Reduced from 118 lines to 34 lines** (71% reduction)
- Extracted `renderTimingRow` helper to eliminate 15 repetitive JSX
blocks
- Added `formatTokenBreakdown` helper for token display logic
- Much easier to add new debug metrics

**Before**: 15 nearly-identical blocks of repetitive JSX  
**After**: Clean, DRY implementation with reusable helpers

---

## 🧹 Code Quality Improvements

### Removed Debug Code
- Removed `console.log` accidentally left in `RoutingStatusDisplay.tsx`

### Cleaned Up Comments (18+ removed)
Removed redundant comments that stated the obvious:
-  "Calculate routing cost if we have token usage"
-  "Send the updated routing status with execution metrics to the
client"
-  "Count tool calls in the response"
-  "AI SDK's LanguageModelUsage uses inputTokens/outputTokens"
- And 14+ more...

Kept meaningful comments:
-  "Timing is optional, ignore errors" (explains catch block)
-  Type definition grouping comments

---

## 📊 Statistics

**Files Modified**: 10
- `convert-cents-to-billing-credits.util.ts` (fixed formula)
- `ai-billing.service.ts` (use centralized utility)
- `agent-streaming.service.ts` (use utility, remove comments)
- `agent-execution.service.ts` (remove comments)
- `ai-router.service.ts` (remove comments)
- `RoutingStatusDisplay.tsx` (remove debug code)
- `RoutingDebugDisplay.tsx` (major refactor) 
- `isDebugModeState.ts` (new file)
- `DataMessagePart.ts` (type extensions)
- `useClientConfig.ts` (debug mode support)

**Impact**:
- Lines removed: ~130 (redundant code + comments)
- Lines added: ~45 (helper functions)
- **Net reduction**: ~85 lines
- **Bug fixes**: 1 critical (1000x cost error)
- **Centralizations**: 3 locations now using shared utility
- **Major refactors**: 1 UI component (71% reduction)

---

##  Verification

-  All linter checks pass
-  All tests pass (`ai-billing.service.spec.ts` verified)
-  No `any` types in affected code
-  No TODO/FIXME markers

---

## 🎯 Principles Applied

1.  **Fix Root Causes, Not Symptoms** - Fixed utility function, then
used it everywhere
2.  **DRY (Don't Repeat Yourself)** - Centralized cost calculation and
UI rendering
3.  **Single Source of Truth** - One place for cost conversion formula
4.  **Code as Documentation** - Removed comments that repeated what
code says
5.  **Composability** - Created reusable helper functions
6.  **Type Safety** - Maintained strict typing throughout
2025-11-13 13:34:46 +01:00
nitinandGitHub fddac24e7f connect line chart to backend (#15657)
https://github.com/user-attachments/assets/b797c5a8-32a8-4d3e-9fb1-7541d107a19f

optimizations:
before: 


https://github.com/user-attachments/assets/bf45a3f1-5f89-40c1-9ce4-c2d912b77d63


after:


https://github.com/user-attachments/assets/61bfd603-7b63-4695-8ae8-68fe7d3bfea0
2025-11-13 11:35:08 +00:00
eee35e5e25 Surface record selection limit in Workflow Manual Trigger and in Search Node (#15785)
fixes https://github.com/twentyhq/twenty/issues/15704

Take over: https://github.com/twentyhq/twenty/pull/15738

based on [KhademOHAli1](https://github.com/KhademOHAli1) work

---------

Co-authored-by: Ali Khadem <ali.kh@pitant.de>
2025-11-13 12:11:48 +01:00
GuillimandGitHub 0389fcf00d removing feature flag IS_MORPH_RELATION_ENABLED (#15783)
releasing the morph feature for all workspaces
2025-11-13 12:03:25 +01:00
Raphaël BosiandGitHub cb759aa22e Fix concurrent page layout edition bug (#15740)
This PR fixes a bug which could happen if two people were editing a page
layout at the same time.
If one person deletes a widget or a tab and saves first, and the second
person saves after but doesn't delete this widget or tab, an error is
raised.

This is because, in the backend, a diff is computed to know which tab or
widget to create, update or delete. But the logic was maid without
considering soft deletion. So, when the second person saves, the diff
tries to create the widget or tab which had been soft deleted by the
first use. Since they have the same id, a duplicate primary key error is
raised.

Now we always consider that the last user to save has the truth. So we
restore the tab/widget and update it.
2025-11-13 12:01:11 +01:00
Lucas BordeauandGitHub a453d53656 Fix Snackbar crashing the whole app (#15774)
This PR fixes a crash of the app when a Snackbar tries to render an
object.

<img width="3002" height="754" alt="image"
src="https://github.com/user-attachments/assets/988f97eb-5c8a-44f8-ac8e-e2953b872bac"
/>

What happened : the backend sent a MessageDescriptor in
`extensions.userFriendlyMessage` while it should have sent a translated
string.

But it is a problem that the Snackbar can end up rendering objects and
crashing the whole app because it is a the highest level in the tree.

So this PR hardens many points to avoid future bugs : 
- Sanitize what is rendered by the Snackbar to avoid any crash
- Translate any MessageDescriptor object that could end up in the
frontend
- Fix the places in the backend where a MessageDescriptor wasn't
translated and sent directly to the frontend in
`use-graphql-error-handler.hook.ts`

Fixes https://github.com/twentyhq/twenty/issues/15685
Fixes https://github.com/twentyhq/core-team-issues/issues/1869
2025-11-13 12:01:06 +01:00
b82d38bb13 fix(ui): layout-shift-on-tasks (#15775)
Fixes #12090 

### Summary
Fixes a UI layout shift issue in table rows in Tasks page, where bottom
borders appeared inconsistently across rows.
The problem occurred because `shouldDisplayBorderBottom` conditionally
applied the bottom border, which caused slight height differences
between rows and visual "jumping" when rendering focused styling.

### Changes Made
- Ensured consistent `border-bottom` rendering
- Removed conditional rendering prop to always display bottom border

### Steps to Reproduce (Before Fix)
1. Navigate to - /objects/tasks?viewId=xxxx
2. Interact with row elements
3. Notice a slight layout shift when first row is active/focused


### Before 

https://github.com/user-attachments/assets/ab95db5d-0922-4460-a086-a03f58375824

### After


https://github.com/user-attachments/assets/a6b4d50c-b6f0-456b-90d4-fc3f0cde42bc

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-13 10:56:18 +00:00
ec7e49c8bb fix: minor color changes (#15616)
Closes #15597

The `color` of `OnBoardingModalCircularIcon` was set to `gray`. Now it
is set to `inverted` and it is displayed properly. I couldn't figure out
how to reach the onboarding screen, so I created a temporary path and
rendered the element there to verify the changes. Attaching screenshots
of the same.
<img width="398" height="393" alt="Screenshot from 2025-11-05 00-11-05"
src="https://github.com/user-attachments/assets/25efc790-92a3-42b5-8298-5128a3f1a466"
/>

<img width="398" height="418" alt="Screenshot from 2025-11-05 00-10-32"
src="https://github.com/user-attachments/assets/af52c695-4b01-40e9-a873-39d491c633cc"
/>

Additionally, a border has been added to the color picker icons.
<img width="573" height="383" alt="Screenshot from 2025-11-05 00-12-23"
src="https://github.com/user-attachments/assets/03d967aa-8c6f-4dfd-be3d-a2e16fe12b9a"
/>

I noticed that the dropdown after clicking on the icon also renders a
bunch of colors. Do let me know if these need the same border as well.
<img width="571" height="366" alt="Screenshot from 2025-11-05 00-12-37"
src="https://github.com/user-attachments/assets/a13bf253-6765-4d7a-9f0f-17cb7375a515"
/>

---------

Co-authored-by: bosiraphael <raphael.bosi@gmail.com>
2025-11-13 10:00:28 +00:00
BOHEUSandGitHub 3c58ed233b Add missing color changes in workflow steps with no data (#14967)
Fixes #14888
2025-11-13 10:39:38 +01:00
martmullandGitHub 1b308a7b74 Fix can't save empty env variables values (#15773) 2025-11-12 15:48:55 +01:00
Félix MalfaitandGitHub 09e89334c6 Fix Tool permissionn guard issue (#15770)
Fix a critical issue on the permission guard for tools which led to
users being denied access when they should have had access
2025-11-12 11:51:54 +01:00
martmullandGitHub f4663038b6 Rename sdk utils (#15769)
Follow ups
2025-11-12 11:20:59 +01:00
Raphaël BosiandGitHub ea56586766 Fix horizontal bar chart spacing between ticks (#15702)
This PR fixes a bug where the spacing between ticks on the Y axis was
adjusted according to the width of the widget where it should have been
adjusted according to the height. Same for the X axis.

**Before**:
Works for the vertical layout but not for the horizontal layout


https://github.com/user-attachments/assets/f0b94103-1ba6-4dbe-bbc6-c47541c1b5fa


**After**:
Works for both


https://github.com/user-attachments/assets/165faada-2943-4e05-92d6-a31def569500
2025-11-12 10:19:32 +00:00
065923d724 feat: Add Workflow duplicate step (#15622)
## Description

- This PR address issue
https://github.com/twentyhq/core-team-issues/issues/1800
- Added workflow duplicate option in workflow sidepanel
- Introduced DuplicateWorkflow.ts mutuation
- Updated graphql generated metadata with new duplicate type




## Visual Appearanc

<img width="1792" height="1031" alt="Screenshot 2025-11-07 at 4 46
22 PM"
src="https://github.com/user-attachments/assets/d75f99df-ae18-4b41-a5f4-21c50010cdbc"
/>


https://github.com/user-attachments/assets/3dbf73cf-f4dd-484c-94a3-29577cfbac25

---------

Co-authored-by: Devessier <baptiste@devessier.fr>
2025-11-12 10:53:25 +01:00
12e2820715 fix(docs): Use content instead of props for Card titles to enable translation (#15756)
Co-authored-by: Félix Malfait <felix@twenty.com>
2025-11-12 10:44:04 +01:00
martmullandGitHub 534a2bf647 Rename sdk utils (#15766)
As title
2025-11-12 10:42:55 +01:00
fcf66bc881 update Notes & Tasks to display the first-letter icon (#15729)
Closes https://github.com/twentyhq/twenty/issues/15630

## Description
I've updated the Notes & Tasks to display the first-letter icon.

I only applied this change to the SummaryCard component to avoid
conflict with the content of
https://github.com/twentyhq/twenty/issues/6486.

## Test
<img width="1155" height="178" alt="スクリーンショット 2025-11-09 19 02 41"
src="https://github.com/user-attachments/assets/3b065f94-7bb8-4ba9-a0f0-3c32fb556e7e"
/>
<img width="1158" height="229" alt="スクリーンショット 2025-11-09 19 02 23"
src="https://github.com/user-attachments/assets/884ff3b6-2c48-4557-8b45-64f94a8fd6a1"
/>

Co-authored-by: Takuya Kurimoto <takuya004869@gmail.com>
2025-11-12 10:38:22 +01:00
Lucas BordeauandGitHub 5f3253d5a5 Fix issues with one to many activity targets (#15656)
This PR fixes issues with one to many activity target bugs described
here :
https://github.com/twentyhq/twenty/issues/14280#issuecomment-3490170714

It also improves the request that fetches notes and tasks in index
pages, to only fetch the notes and tasks identifier fields, thus
reducing the amount of network load.

Fixes https://github.com/twentyhq/twenty/issues/14280
2025-11-11 17:19:20 +01:00
de978960d0 [FIx] shouldBypassPermissionChecks for workspaceMember repository (#15706)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> Pass `shouldBypassPermissionChecks: true` to
`getRepositoryForWorkspace('workspaceMember')` in
`1-11-clean-orphaned-user-workspaces.command.ts` to ensure member lookup
during orphan cleanup ignores permissions.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
543fd9fc01. 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-11-11 17:17:42 +01:00
Lucas BordeauandGitHub 703d9cb08d Improved Kanban performance (#15714)
This PR improves Kanban performance to attain the stock library speed.

There are still some performance issues at load time and drop, but they
are harder to address.

Before, everything is re-rendering at every card move, full re-render at
drop :



https://github.com/user-attachments/assets/7a1cf419-c8d8-4d56-a1a3-4269dce7b5a9


After, only the columns and card outer containers get re-rendered for
d&d, only two columns re-render at drop :



https://github.com/user-attachments/assets/d2dea914-5cc3-4693-9c2d-c7c789ae3452



We can still improve performance and re-render but that would represent
a global effort on D&D on general, table has the same problem currently,
but since we implemented virtualization it is bearable for now.
2025-11-11 17:07:40 +01:00
Thomas des FrancsandGitHub e5b88f2bb2 Update changelog process to require user approval (#15760)
Adds a mandatory user approval step before committing and creating PRs
in the changelog creation process.

This ensures the AI always shows the full changelog content and waits
for user approval before proceeding.
2025-11-11 16:50:04 +01:00
561297436e Anchored tooltip (#15568)
Issue - 
- tooltip gets too long when groupby has too much data points
- we need max height on tooltips
- we need to be able to scroll inside the tooltip
- not possible if the tooltip is following the cursor (which library
enforces)
- its not easy to customize Nivo's own tooltip to make it work how we
want it

what we want - 
- let the tooltip anchor to the bar in such a way -- that the top of the
bar aligns with the vertical middle of the tooltip
- add max height to the tooltip

what I did - 
- use floating portal from floating-ui/react
- get the hover datum (ie hovered bars) dimensions on mouse enter to
render the tooltip
- anchor the tooltip at the calculated position
- floating-ui handles the basic things like flipping/offset/shift
- clear the states as required

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-11 16:47:41 +01:00
Thomas des FrancsandGitHub 652c8673e0 Release 1.10.0 (#15759)
## Release 1.10.0

This release includes:

- Calendar View for Objects - visualize records in a monthly calendar
view
- Dashboards in Labs (Beta) - create custom charts and visualizations
with workspace data

Changelog file:
`packages/twenty-website/src/content/releases/1.10.0.mdx`
Release date: 2025-11-11
2025-11-11 16:43:55 +01:00
Abdul RahmanandGitHub 2e359f5585 Fix AI table scroll overflow and tool input display (#15753)
- Fixed horizontal scroll overflow when tables appear in AI responses
- Fixed tool call input display to show only user-relevant input instead
of internal metadata (loadingMessage)

### Before

https://github.com/user-attachments/assets/870bf52d-7ffd-464e-9240-bd482ab19077


### After


https://github.com/user-attachments/assets/40a19fc0-6989-437f-b712-8141368179dc
2025-11-11 11:08:26 +01:00
Félix MalfaitandGitHub 11e07f90d2 refactor: Simplify CRUD services to leverage Common API (#15742)
## Summary

This PR refactors all Record CRUD services to use the Common API
(CommonQueryRunners) instead of directly accessing TwentyORM, achieving
**77% code reduction** while maintaining full functionality.

## Changes

### Code Reduction: -547 net lines (77%)
- **Before**: 901 lines across 5 services
- **After**: 354 lines (services + utility)
- **Deleted**: 547 lines of redundant code

### Services Simplified

| Service | Before | After | Reduction |
|---------|--------|-------|-----------|
| CreateRecordService | 142 | 59 | -83 lines |
| UpdateRecordService | 177 | 51 | -126 lines |
| DeleteRecordService | 137 | 51 | -86 lines |
| FindRecordsService | 233 | 68 | -165 lines |
| UpsertRecordService | 212 | 129 | -83 lines |

### Architecture Change

**Before:**
```
CRUD Services → TwentyORM
- Manual query building
- Manual permission checking
- Manual transformations
- Duplicated logic
```

**After:**
```
CRUD Services → CommonQueryRunners → TwentyORM
- Common API handles queries
- Common API handles permissions
- Common API handles transformations
- Single source of truth
```

### Module Dependencies Simplified

**Removed:**
- TwentyORMModule
- RecordPositionModule
- RecordTransformerModule
- WorkflowCommonModule

**Added:**
- CoreCommonApiModule
- WorkspaceMetadataCacheModule

**From 4 heavy dependencies → 2 clean dependencies**

## What Changed

### New Code
- `common-api-context-builder.util.ts` - Single shared utility (68
lines)

### Refactored Services
All services now follow a simple pattern:
1. Build Common API context
2. Call appropriate CommonQueryRunner
3. Return formatted result

Each service is now 50-120 lines instead of 140-230 lines.

### Type Fixes
- Fixed `FindRecordsParams.orderBy` type (was
`Partial<ObjectRecordOrderBy>`, now `ObjectRecordOrderBy`)
- Fixed `FindRecordsInput.gqlOperationOrderBy` type (same fix)

## Benefits

###  Code Quality
- 77% less code to maintain
- No code duplication
- Simpler, clearer logic
- Proper TypeScript types (no hacks)

###  Common API Integration
All services now get Common API benefits:
- Consistent permission checking
- Query hooks (before/after execution)
- Automatic input transformation
- Automatic position handling
- Result processing and enrichment
- Same behavior as REST/GraphQL

###  Safety Preserved
- createdBy actor metadata preserved for workflows
- All field validation maintained
- All transformations maintained
- All error handling maintained

###  No Breaking Changes
- Same external API for all services
- Workflows continue to work
- AI operations continue to work
- MCP operations continue to work

## Testing

-  TypeScript compiles
-  All files pass linting
-  No type casting hacks
-  Proper type safety throughout
- ⚠️ Integration tests recommended

## What Common API Handles For Us

1. **Record Position** - Automatic via `RecordPositionService`
2. **Input Transformation** - Automatic for NUMBER, RICH_TEXT, PHONES,
EMAILS, LINKS
3. **createdBy Actor** - Injected via `CreatedByCreateOnePreQueryHook` +
explicit workflow actor
4. **Field Validation** - Only processes valid fields
5. **Permissions** - Validates permissions before execution
6. **Query Hooks** - Before/after execution hooks work
7. **Error Handling** - Consistent exception handling

## Files Modified (12)

**Services (6):**
- create-record.service.ts
- update-record.service.ts
- delete-record.service.ts
- find-records.service.ts
- upsert-record.service.ts
- record-crud.module.ts

**Types (2):**
- find-records-params.type.ts
- record-crud-input.type.ts

**Workflows (1):**
- find-records.workflow-action.ts

**New Files (3):**
- common-api-context-builder.util.ts
- REFACTORING_COMPLETE.md
- REFACTORING_ANALYSIS.md

## Verification Checklist

- [x] TypeScript compiles
- [x] Linter passes
- [x] No type hacks (`as unknown as` removed)
- [x] createdBy preserved for workflows
- [x] Module dependencies simplified
- [x] Common API integration complete
- [ ] Integration tests pass (recommended)
- [ ] Workflow execution tested (recommended)

## Related Issues

This refactoring establishes the pattern for making CRUD operations
consistent across all presentation layers (REST, GraphQL,
Tools/Workflows/AI/MCP).
2025-11-11 11:07:36 +01:00
martmullandGitHub 9880f192a5 Move composite types to twenty-shared (#15741) 2025-11-10 22:11:52 +01:00
Charles BochetandGitHub 7099b1c174 Fix export CSV not using right columns (#15752)
Fixes https://github.com/twentyhq/twenty/issues/15575
2025-11-10 22:00:39 +01:00
Abdul RahmanandGitHub 194a579a03 fix: Replace angle bracket placeholders with curly braces in docs to fix crowdin's tags mismatch errors (#15751) 2025-11-11 02:20:48 +05:30
Shantanu GuptaandGitHub 06b8ea7c36 FIX: export view not exporting all records (#15509)
Fixes #15508 
Addresses the issue where the "Export View" functionality was not
exporting all records from a view. Users reported that only a subset of
records were exported, even when the view contained more. This led to
incomplete data exports.

The core of the problem was found within the `useLazyFetchAllRecords`
hook. The `fetchMoreRecordsLazy` function, which is responsible for
fetching subsequent pages of data during the export process, was
inadvertently using a default page limit (`DEFAULT_SEARCH_REQUEST_LIMIT`
of 60 records) instead of the intended `pageSize` (200 records). This
discrepancy caused the export process to prematurely stop fetching
records.

The PR modifies
`packages/twenty-front/src/modules/object-record/hooks/useLazyFetchAllRecords.ts`
to explicitly pass the `limit` parameter (which correctly reflects the
`pageSize`) to the `fetchMoreRecordsLazy` function. This ensures that
all subsequent data fetches during an export operation adhere to the
configured page size, allowing for the complete retrieval of all
records.
2025-11-10 21:25:39 +01:00
neo773andGitHub 39017f43b8 handle invalid/expired syncCursor (#15715) 2025-11-10 18:18:17 +01:00
WeikoandGitHub 22a81f705b Add global datasource to seeded feature flags (#15748) 2025-11-10 17:05:25 +00:00
WeikoandGitHub 02fda92a93 Global workspace datasource poc (#15744)
## Context
This PR introduces a Global Workspace DataSource that consolidates
workspace-specific database access through a single TypeORM DataSource
instance with AsyncLocalStorage-based context management instead of N
workspace datasources.

- Created GlobalWorkspaceDataSource extending TypeORM's DataSource to
manage multiple workspaces with entity metadata caching (1-hour TTL)
- Implemented AsyncLocalStorage for workspace context propagation
(WorkspaceContextForStorage) containing workspace ID, metadata,
permissions, and feature flags
- Modified query execution flow to wrap operations in workspace context
via GlobalWorkspaceOrmManager.executeInWorkspaceContext()
- Added schema name to entity schemas for proper multi-tenant database
separation

Next: 
- use the new global workspace datasource everywhere and deprecate
workspace datasource factory
- improve metadata caching using a short TTL to avoid multiple calls to
redis
- Leverage the new WorkspaceContextALS and put it higher in the request
hierarchy to have access to permission, metadata and featureflag
everywhere --- build it manually for commands --- find a way to
propagate it in jobs?
- Remove PG_POOL patch once we have a unique datasource and increase
global datasource pool size

## Implementation
Why ALS:

1. Automatic Per-Request Isolation

With schema-based multi-tenancy, each workspace has its own PostgreSQL
schema
(e.g. workspace_20202020-1c25-4d02-bf25-6aeccf7ea419).
The critical challenge is ensuring that concurrent requests from
different tenants don't interfere with each other.
```typescript
// Request A (Workspace 1) and Request B (Workspace 2) executing concurrently

// Without ALS: Race condition — they'd share the same global state!
// With ALS: Each request has isolated context ✓
```
ALS automatically isolates context per async execution chain, so:
- Request from Tenant A → ALS stores workspaceId: "tenant-a" → Queries
hit workspace_tenant_a schema
- Request from Tenant B → ALS stores workspaceId: "tenant-b" → Queries
hit workspace_tenant_b schema

 No interference, even when executing simultaneously on the same
Node.js event loop.

2. No Manual Context Passing

Before ALS, you'd need to pass workspaceId through every function call:
```typescript
//  Without ALS - Context threading nightmare
getRepository(workspaceId, entity)
  → createEntityManager(workspaceId)
    → getMetadata(workspaceId, target)
      → findInCache(workspaceId, cacheKey)
```
With ALS:
```typescript
//  With ALS - Clean, implicit context
getRepository(entity)          // Reads workspaceId from ALS
  → createEntityManager()      // Reads workspaceId from ALS
    → getMetadata(target)      // Reads workspaceId from ALS
      → findInCache(cacheKey)  // Reads workspaceId from ALS
```
example
```typescript
override findMetadata(target: EntityTarget<ObjectLiteral>): EntityMetadata | undefined {
  const context = getWorkspaceContext(); // 👈 Automatically gets the right workspace!
  const { workspaceId, metadataVersion } = context;
  const cacheKey = `${workspaceId}-${metadataVersion}`;
  // ... returns metadata for THIS workspace's schema
}
```

3. Async Chain Propagation

Node.js operations are heavily async. ALS automatically propagates
context through:

- async/await chains
- Promise chains
- Callbacks

```typescript
executeInWorkspaceContext(workspaceId, async () => {
  await prepareContext();           // Has context ✓
  const results = await run();      // Has context ✓
  await enrichResults();            // Has context ✓

  // Even nested async operations maintain context!
  await Promise.all([
    saveToCache(),   // Has context ✓
    emitEvent(),     // Has context ✓
    logMetrics(),    // Has context ✓
  ]);
});
```
5. Schema-Specific Metadata Caching

The implementation caches entity metadata per workspace + version:
```typescript
// Cache key format: "workspaceId-metadataVersion"
const cacheKey = `${workspaceId}-${metadataVersion}`;
```
Why this matters with schemas:

- Each workspace has different table structures (custom fields, objects)
- EntitySchema includes schema: "workspace_xxx" property
- Each cached metadata points to the correct schema

ALS ensures getWorkspaceContext() returns the right workspaceId,
so you always get the correct schema's metadata from cache.

6. Single DataSource for All Tenants

The key change here:
```typescript
//  Old approach: One DataSource per tenant
const dataSourceTenantA = new DataSource({ schema: 'workspace_a' });
const dataSourceTenantB = new DataSource({ schema: 'workspace_b' });
// Problem: Hundreds of DB connection pools!
```
```typescript
//  New approach: One shared DataSource + ALS context
const globalDataSource = new GlobalWorkspaceDataSource();

// ALS determines which schema to use at runtime
```
When you call:
```typescript
globalDataSource.getRepository('person');
```
It internally does:
```typescript
const context = getWorkspaceContext();  // Gets current tenant from ALS
const metadata = this.findMetadata('person'); // Finds metadata for THIS tenant's schema
// EntityMetadata includes: schema: "workspace_20202020-1c25..."
// TypeORM automatically queries: SELECT * FROM "workspace_20202020-1c25...".person
```
7. Request Lifecycle Example

```typescript
// 1. GraphQL request arrives: "query people { ... }"
// 2. Middleware extracts authContext.workspace.id = "tenant-a"
// 3. Query runner wraps execution in ALS:
executeInWorkspaceContext("tenant-a", async () => {
  // 4. Everything inside has access to workspace context:
  const repo = getRepository('person');      // ALS → tenant-a
  const metadata = getMetadata('person');    // ALS → tenant-a → cache["tenant-a-v5"]

  // 5. TypeORM builds query with correct schema:
  // SELECT * FROM "workspace_tenant_a"."person" WHERE ...

  // 6. Even nested calls work:
  await saveAuditLog();  // ALS → tenant-a → correct audit schema
  await emitWebhook();   // ALS → tenant-a → correct tenant webhook
});
// 7. Request completes, ALS context automatically cleaned up
```

8. Safety & Error Prevention

```typescript
// If you forget to set context:
const context = getWorkspaceContext();
//  Throws: "Workspace context not set..."
// Fails fast rather than querying wrong schema!

// Can't accidentally query wrong tenant:
// Context is immutable within execution scope
```
2025-11-10 17:32:49 +01:00
Paul RastoinandGitHub 7a1e699fc8 Twenty standard and workspace custom applications 1/3 (#15625)
# Introduction
related to https://github.com/twentyhq/core-team-issues/issues/1833
In this PR we're starting the sync-metadata and standardIds deprecation
by introducing `twenty-standard` application that will regroup every
standard object such as company and opportunities. But also the
`custom-workspace-application` which is an app created at the same time
as a workspace and that will regroup everything configure within the
workspace ( custom objects fields etc )

## What's done
On both new workspace and seeded workspace creation:
- Creating a custom workspace app
- Creating a twenty standard app
- Refactored the seed core schema and workspace creation to be run
within a transaction in order to handle circular dependency foreignkey
requirements ( which is deferred for app toward workspace )
- Updated workspace entity to have a custom workspace relation (
nullable for the moment until we implem an upgrade command to handle
retro comp )
- Integration testing on user, workspace creation deletion and expected
default apps creation
- ~~Soft deleted user on `deleteUser`~~ Done by marie and rebased on it

## What's next
- Update seeder to propagate the `twenty-standard` workspace
`applicationId` to every standard synchronized entities ( cheap and fast
iteration through the about to be deprecated sync-metadata as an easy
way to synchronize standards metadata entities ).
- Update seeder to propagate the `custom-workspace-application`
workspace `applicationId` to anything custom ( `pets` and `rockets` )
- Prepend `custom-workspace-application` `applicationId` to every
metadata API operations ( create a specific cache etc )
- Upgrade command on all existing workspace to create a custom app and
associate its applicationId to any existing custom entities
- Make `universalIdentifier` and `applicationId` required for any
syncable entity
2025-11-10 16:13:12 +01:00
Félix MalfaitandGitHub 9a80164cf3 Add comprehensive permission guard coverage across GraphQL and REST endpoints (#15739)
This PR enhances our security model by ensuring all GraphQL resolvers
and REST API endpoints have appropriate permission guards.

## Changes

### ESLint Rules
- Enhanced `graphql-resolvers-should-be-guarded` to require permission
guards on all resolvers (Query, Mutation, Subscription), not just
mutations
- Enhanced `rest-api-methods-should-be-guarded` to require permission
guards on all REST endpoints (GET, POST, PUT, PATCH, DELETE), not just
mutating methods
- Both rules now enforce consistent security: authentication guards +
permission guards for all endpoints

### Permission Guards Added

**Public Endpoints** - Added `NoPermissionGuard`:
- Auth-related queries (checkUserExists, findWorkspaceFromInviteHash,
validatePasswordResetToken)
- Billing webhooks (Stripe callbacks)
- SSO callbacks (SAML authentication)
- Workflow webhooks
- Cloudflare webhooks
- Route trigger endpoints
- GraphQL subscriptions
- Current workspace queries
- Geo-map address autocomplete
- View-related read operations (view-field, view-filter, view-group,
view-sort, view-filter-group)

**Settings Permission Guards** - Added `SettingsPermissionGuard`:
- API Keys management: `PermissionFlagType.API_KEYS_AND_WEBHOOKS`
- Webhooks management: `PermissionFlagType.API_KEYS_AND_WEBHOOKS`
- Page Layouts (write operations): `PermissionFlagType.LAYOUTS`
- REST Metadata API: `PermissionFlagType.DATA_MODEL`
- Agent operations: `PermissionFlagType.AI`
- Remote servers: `PermissionFlagType.DATA_MODEL`
- Remote tables: `PermissionFlagType.DATA_MODEL`
- Serverless functions: `PermissionFlagType.WORKFLOWS`

**Custom Permission Guards** - Added `CustomPermissionGuard`:
- REST Core API (permissions checked at query execution layer)
- Timeline calendar events (permission checks in service layer)
- Timeline messaging (permission checks in service layer)
- Search operations (permission checks in service layer)
- View operations (permission checks via dedicated view permission
guards)

### View Permission Guards
- Created dedicated `FindManyViewsPermissionGuard` and
`FindOneViewPermissionGuard` for reading views
- Created `CreateViewPermissionGuard` for view creation with
visibility-based permission checks
- All view child entities (view-field, view-filter, view-sort,
view-group, view-filter-group) use `NoPermissionGuard` for reads
- Write operations on view child entities use dedicated permission
guards that check parent view access

### Page Layout Permissions
- Read operations (GET/Query) now use `NoPermissionGuard` - users can
view layouts without LAYOUTS permission
- Write operations (POST/PATCH/DELETE/Mutation) require
`SettingsPermissionGuard(PermissionFlagType.LAYOUTS)`
- Applied consistently across page-layout, page-layout-tab, and
page-layout-widget endpoints

## Security Model
All endpoints now follow a consistent pattern:
1. **Authentication**: `UserAuthGuard`, `WorkspaceAuthGuard`, or
`PublicEndpointGuard`
2. **Authorization**: One of:
- `SettingsPermissionGuard(PermissionFlagType.XXX)` - for settings/admin
operations
- `CustomPermissionGuard` - when permissions are checked in service/data
layer
   - `NoPermissionGuard` - for public or non-sensitive read operations

The ESLint rules automatically enforce this pattern going forward.

## Stats
- 47 files changed
- 603 insertions, 163 deletions
- 3 new guard files created
2025-11-10 12:17:38 +01:00
BOHEUSandGitHub ae2d399d6e Hacktober apps fix (#15733)
- update dependencies in mailchimp, stripe and last email interaction
apps
- fix logic in mailchimp integration, now it's triggered by update of
People records and allows for update Mailchimp records
- fix logic in stripe integration, now properly reads data from webhook
- update READMEs to make it more understandable to non-technical users
2025-11-10 09:37:09 +01:00
912c668eb5 i18n - docs translations (#15735)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-09 23:20:15 +01:00
2c0df3ca99 i18n - translations (#15734)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-09 21:32:52 +01:00
9f594cda1c Slash Command Implementation in Advanced Text Editor (#15488)
Part of Fixing Issue #14976 

### Pull Request Summary: SlashCommand Integration in Advanced Text
Editor

This pull request introduces **SlashCommand functionality** within the
Advanced Text Editor, specifically used in the **Workflow node** of
**Send Email body** components. The implementation leverages the
`@tiptap/suggestion` extension from the TipTap ecosystem, enabling
dynamic styling and command execution via a custom dropdown triggered by
typing `/`.

---

### Implementation Overview

#### 1. **Custom Extension & Dropdown Rendering**
- A new extension was created to handle SlashCommand interactions.
- This extension renders a **Dropdown component** that displays
available commands with relevant styles, icons etc.

#### 2. **Command Configuration**
- Each command includes:
  - Visibility and active state logic
  - Execution behavior upon selection
- All commands are initialized and configured centrally.

#### 3. **Search & Filtering**
- As users type after the `/`, the command list is **filtered based on
the query**.
- For example, typing `/car` filters and displays matching commands in
the dropdown.

#### 4. **Dropdown Lifecycle & Positioning**
- The dropdown is rendered using React lifecycle hooks provided by
`SuggestionTip`:
- `onStart`: Initializes state, sets selected command, and captures
cursor position via `DOMRect`.
- `onUpdate`, `onKeyDown`, `onExit`: Manage dropdown updates and
interactions.
- Positioning is handled via a **`useFloating` hook**, which aligns the
dropdown relative to the cursor and editor bounds.
- The dropdown is rendered in a **react-portal**, wrapped in the current
theme for consistent styling and animation.


#### 6. **State Management**
- A dedicated `SlashCommandState.ts` file manages:
  - Callback functions
  - Current command and selected item
  - Cleanup utilities for event listeners
  - Dropdown navigation (arrow keys, enter key)

#### 7. **Integration Points**
- SlashCommand functionality is now **enabled in Send Email body of the
Workflow**.
- Relevant changes have been applied to support this components in
Storybook as well.

[slash command
test.webm](https://github.com/user-attachments/assets/5c537844-8987-4ce5-9fca-b29ea93d8063)


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Updates Portuguese (Brazil and Portugal) generated locale files,
including a new editor hint string for “Enter text or type '/' for
commands,” plus assorted translation tweaks.
> 
> - **i18n/locales**:
> - **Portuguese (Brazil) `src/locales/generated/pt-BR.ts`**: Add new
editor hint message (`"Enter text or Type '/' for commands"`) and adjust
multiple translations/wording.
> - **Portuguese (Portugal) `src/locales/generated/pt-PT.ts`**: Add the
same editor hint message and refine numerous translations/labels.
> - No functional code changes; translation files regenerated/updated.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
b3d7407525. 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-11-09 21:18:56 +01:00
1aa9df1d2d i18n - docs translations (#15731)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-09 15:19:56 +01:00
Abdul RahmanandGitHub 4182209ee1 Docs/organize locales under l (#15730) 2025-11-09 14:02:21 +01:00
Abdul RahmanandGitHub 4a15cbc97c Add token renewal to agent chat transport (#15727) 2025-11-09 13:57:24 +01:00
a21680d6a3 refactor: Move translated docs to /l/{locale}/ directory structure (#15726)
Co-authored-by: Félix Malfait <felix@twenty.com>
2025-11-09 12:22:38 +00:00
Abdul RahmanandGitHub 7993e14d0a docs: Fix French navigation labels and translated internal links (#15723)
## Summary
Fixes French documentation navigation labels and internal link redirects
to English pages.

## Changes
1. **Translated French navigation** - All tab/group labels in
`docs.json` now display in French
2. **Automated link fixing** - Created `fix-translated-links.sh` script
that adds `/fr/` prefix to internal links
3. **CI Integration** - Script runs automatically after Crowdin syncs
translations
2025-11-09 13:16:37 +01:00
a4ac66cb4e i18n - docs translations (#15725)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-08 23:20:14 +01:00
1bd1165d2e i18n - docs translations (#15724)
Created by Github action

---------

Co-authored-by: Abdul Rahman <ar5438376@gmail.com>
Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-08 21:20:40 +01:00
Abdul RahmanandGitHub 06d8c8c76a Fix find tool filters by mapping many-to-one relations to fieldId (#15716)
**Root Cause**  
Many-to-one relation filters were being exposed under the relation name
(e.g., `company`) instead of the corresponding foreign-key attribute
(e.g., `companyId`).

**Change**  
- Detect many-to-one relation metadata and remap those filter keys to
`<fieldName>Id`.
- Removed some unused code unrelated to this fix.
2025-11-08 14:32:06 +01:00
4c4eeef5ae i18n - docs translations (#15721)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-08 13:22:29 +01:00
f740bac988 add documentation i18n workflows for Crowdin (#15538)
Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
Co-authored-by: Félix Malfait <felix@twenty.com>
2025-11-08 11:24:07 +01:00
154fb4665e i18n - docs translations (#15720)
Created by Github action

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Adds a full French documentation set covering developers (API,
webhooks, backend/frontend, self‑hosting) and user guide (CRM
essentials, data model, workflows, settings, integrations, pricing,
reporting).
> 
> - **Docs (FR i18n)**:
> - **Developers**: Add `API`, `Webhooks`, backend (best practices,
custom objects, feature flags, architecture, commands, Zapier), frontend
(best practices, architecture, commands, hotkeys, style guide,
Storybook, Figma), self‑hosting (Docker Compose, upgrade guide, cloud
providers), introduction.
> - **User Guide**: Add getting started (what is Twenty,
create/configure workspace, migration, import/export), CRM essentials
(contacts/accounts, pipelines, views), data model (objects, fields,
relations, table views), collaboration (emails/calendars, notes, tasks),
integrations API (overview, integrations), workflows (getting started,
features, credits, internal automations, services), settings (profile,
permissions, members, domains, releases, email/calendar setup), pricing
(billing/FAQ), reporting overview, resources (GitHub, glossary),
introduction.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
9ba8c24571. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: github-actions <github-actions@twenty.com>
Co-authored-by: Félix Malfait <felix@twenty.com>
2025-11-08 10:20:29 +01:00
0fc538ac09 i18n - docs translations (#15719)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-08 10:01:06 +01:00
136289562e i18n - translations (#15718)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-08 07:48:39 +01:00
caecf2d0c2 i18n - translations (#15717)
Created by Github action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-08 07:43:59 +01:00
0ca0cce9a2 i18n - translations (#15713)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-07 18:33:14 +01:00
Félix MalfaitandGitHub b7f5445926 fix: rename SettingsPermissionsGuard to SettingsPermissionGuard for consistency (#15712)
## Problem

The ESLint rule `graphql-resolvers-should-be-guarded` introduced in
#15392 was failing on main because the guard `SettingsPermissionsGuard`
had inconsistent naming.

## Root Cause

The guard was named `SettingsPermissionsGuard` (with an 's') which was
inconsistent with other permission guards:
-  `CustomPermissionGuard`  
-  `NoPermissionGuard`
-  `ImpersonatePermissionGuard`
-  `SettingsPermissionsGuard` (inconsistent!)

The ESLint rule checks if guard names end with `PermissionGuard`, but
`SettingsPermissionsGuard` ends with `sGuard`, so it wasn't recognized
as a permission guard.

## Solution

Renamed the guard to be consistent with the naming convention:

1.  Renamed file: `settings-permissions.guard.ts` →
`settings-permission.guard.ts`
2.  Renamed export: `SettingsPermissionsGuard` →
`SettingsPermissionGuard`
3.  Renamed internal class: `SettingsPermissionsMixin` →
`SettingsPermissionMixin`
4.  Updated all 122 references across 44 files in the codebase
5.  Renamed test file: `settings-permissions.guard.spec.ts` →
`settings-permission.guard.spec.ts`

## Testing

-  `npx nx run twenty-server:lint` passes
-  `npx nx run twenty-server:typecheck` passes
-  No references to the old name remain in the codebase
-  All previously failing resolver files now pass ESLint validation

## Related

Fixes issues introduced in #15392
2025-11-07 18:22:28 +01:00
martmullandGitHub bce1bcf1fa Fix workflow run updates real time (#15701)
as title

## after


https://github.com/user-attachments/assets/34239b6e-16d6-4afd-9a54-cb4767179bea
2025-11-07 15:54:13 +01:00
neo773andGitHub f91c2bb729 fix exceptionHandlerService.captureExceptions in MessageImportExceptionHandlerService (#15703) 2025-11-07 15:53:26 +01:00
65014cbf8d i18n - translations (#15705)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-07 15:47:00 +01:00
Félix MalfaitandGitHub cff17db6cb Enhance role-check system with stricter checks (#15392)
## Overview

This PR strengthens our permission system by introducing more granular
role-based access control across the platform.

## Changes

### New Permissions Added
- **Applications** - Control who can install and manage applications
- **Layouts** - Control who can customize page layouts and UI structure
- **AI** - Control access to AI features and agents
- **Upload File** - Separate permission for file uploads
- **Download File** - Separate permission for file downloads (frontend
visibility)

### Security Enhancements
- Implemented whitelist-based validation for workspace field updates
- Added explicit permission guards to core entity resolvers
- Enhanced ESLint rule to enforce permission checks on all mutations
- Created `CustomPermissionGuard` and `NoPermissionGuard` for better
code documentation

### Affected Components
- Core entity resolvers: webhooks, files, domains, applications,
layouts, postgres credentials
- Workspace update mutations now use whitelist validation
- Settings UI updated with new permission controls

### Developer Experience
- ESLint now catches missing permission guards during development
- Explicit guard markers make permission requirements clear in code
review
- Comprehensive test coverage for new permission logic

## Testing
-  All TypeScript type checks pass
-  ESLint validation passes
-  New permission guards properly enforced
-  Frontend UI displays new permissions correctly

## Migration Notes
Existing workspaces will need to assign the new permissions to roles as
needed. By default, all new permissions are set to `false` for non-admin
roles.
2025-11-07 15:37:17 +01:00
Raphaël BosiandGitHub 44d6ec2594 Widget: Allow resizing from all corners and sides (#15680)
https://github.com/user-attachments/assets/3e4e1da2-87e6-440e-8371-835ef6eccf59
2025-11-07 15:28:39 +01:00
GuillimandGitHub 2274a937bd first step (#15687)
TODO : 

-> for test integreation for this connect 
-> add validation in common API

Fixes https://github.com/twentyhq/core-team-issues/issues/1278
2025-11-07 13:49:57 +00:00
Paul RastoinandGitHub f50d9bfa43 Activate IS_WORKSPACE_MIGRATION_V2_ENABLED for new workspaces (#15700) 2025-11-07 13:41:25 +00:00
MarieandGitHub 0992d8031b [Fix] fix command dry run (#15697) 2025-11-07 13:32:23 +01:00
Abdul RahmanandGitHub 54815196c1 Improve AI Tool Step Renderer Layout and JSON Tree Scrolling (#15698)
### Before


https://github.com/user-attachments/assets/a222a6ff-550c-453b-bc0b-ee9bdb925956


### After



https://github.com/user-attachments/assets/249b7097-8dc1-4611-8205-2a43cb015a33
2025-11-07 13:31:05 +01:00
martmullandGitHub 196a75ec0c Fix typing error (#15699)
Fix typing error
2025-11-07 13:29:16 +01:00
martmullandGitHub aa48a68a34 Increase packages versions (#15694)
As title
2025-11-07 10:46:43 +01:00
MarieandGitHub 66ef867cf5 Do not revert isSystem update for workspaceMember (#15691)
Until this is done: [Make workspaceMembers
non-system](https://github.com/twentyhq/twenty/issues/15688)

Let's make that update to allow us to have workspaces with
workspaceMember not being system object, to allow user to customize
their data model.
2025-11-07 10:04:10 +01:00
c9d7361e7c i18n - translations (#15689)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-06 19:40:28 +01:00
MarieandGitHub 4ce93aee52 Fix user deletion flows (#15614)
**Before**
- any user with workpace_members permission was able to remove a user
from their workspace. This triggered the deletion of workspaceMember +
of userWorkspace, but did not delete the user (even if they had no
workspace left) nor the roleTarget (acts as junction between role and
userWorkspace) which was left with a userWorkspaceId pointing to
nothing. This is because roleTarget points to userWorkspaceId but the
foreign key constraint was not implemented
- any user could delete their own account. This triggered the deletion
of all their workspaceMembers, but not of their userWorkspace nor their
user nor the roleTarget --> we have orphaned userWorkspace, not
technically but product wise - a userWorkspace without a workspaceMember
does not make sense

So the problems are
- we have some roleTargets pointing to non-existing userWorkspaceId
(which caused https://github.com/twentyhq/twenty/issues/14608 )
- we have userWorkspaces that should not exist and that have no
workspaceMember counterpart
- it is not possible for a user to leave a workspace by themselves, they
can only leave all workspaces at once, except if they are being removed
from the workspace by another user

**Now**
- if a user has multiple workspaces, they are given the possibility to
leave one workspace while remaining in the others (we show two buttons:
Leave workspace and Delete account buttons). if a user has just one
workspace, they only see Delete account
- when a user leaves a workspace, we delete their workspaceMember,
userWorkspace and roleTarget. If they don't belong to any other
workspace we also soft-delete their user
- soft-deleted users get hard deleted after 30 days thanks to a cron
- we have two commands to clean the orphans roleTarget and userWorkspace
(TODO: query db to see how many must be run)

**Next**
- once the commands have been run, we can implement and introduce the
foreign key constraint on roleTarget


Fixes https://github.com/twentyhq/twenty/issues/14608
2025-11-06 18:29:12 +00:00
bfe1f47065 Create old fields design widget (#15645)
In this PR:

- Pass `layoutMode` and `tabId` via PageLayoutContentContext provider
- Getting `pageLayoutType` from the current page layout
- Getting isInPinnedTab through `useIsInPinnedTab` hook

## Before

<img width="3456" height="2160" alt="CleanShot 2025-11-06 at 14 22
44@2x"
src="https://github.com/user-attachments/assets/763bb413-5739-45ef-85ed-82a72415886f"
/>

## After

<img width="3456" height="2162" alt="CleanShot 2025-11-06 at 14 20
38@2x"
src="https://github.com/user-attachments/assets/eee6cccd-9d36-426e-a22f-400e8f7f9413"
/>

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-06 18:16:42 +01:00
Thomas TrompetteandGitHub 33c08ad437 Edit workflow and serverless throttling (#15648)
Serverless:  1000 / min.

Workflows: 100 / min. This is a security in case of infinite loops.
2025-11-06 17:47:27 +01:00
Raphaël BosiandGitHub 931d12c77b Add animations on widget buttons and on action buttons (#15631)
Animated:
- Grip
- Trash can
- Action buttons


https://github.com/user-attachments/assets/1cac7a5e-2036-4308-9622-3b4809ae90a3
2025-11-06 17:38:05 +01:00
Paul RastoinandGitHub 137aba049d Fix tsconfigpaths root (#15683)
# Introduction
We've facing facing intra package build error for a moment such as:
```ts
vite v7.1.12 building for production...
src/components/BaseEmail.tsx:20:19 - error TS2719: Type 'import("/Users/paulrastoin/ws/twenty/node_modules/@lingui/core/dist/index").I18n' is not assignable to type 'import("/Users/paulrastoin/ws/twenty/node_modules/@lingui/core/dist/index").I18n'. Two different types with this name exist, but they are unrelated.
  Types have separate declarations of a private property '_locale'.

20     <I18nProvider i18n={i18nInstance}>
                     ~~~~

  node_modules/@lingui/react/dist/shared/react.b2b749a9.d.ts:42:5
    42     i18n: I18n;
           ~~~~
    The expected type comes from property 'i18n' which is declared here on type 'IntrinsicAttributes & Omit<I18nContext, "_"> & { children?: ReactNode; }'
```

and now since hacktoberfest merge getting even more such as:
```ts
➜  twenty git:(main) ✗ npx nx build twenty-emails

   ✔  2/2 dependent project tasks succeeded [2 read from cache]

   Hint: you can run the command with --verbose to see the full dependent project outputs

——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

[tsconfig-paths] An error occurred while parsing "/Users/paulrastoin/ws/twenty/packages/twenty-apps/hacktoberfest-2025/linkedin-browser-extension/browser-extension/tsconfig.json". See below for details. To disable this message, set the `ignoreConfigErrors` option to true.
TSConfckParseError: failed to resolve "extends":"./.wxt/tsconfig.json" in /Users/paulrastoin/ws/twenty/packages/twenty-apps/hacktoberfest-2025/linkedin-browser-extension/browser-extension/tsconfig.json
    at resolveExtends (file:///Users/paulrastoin/ws/twenty/node_modules/tsconfck/src/parse.js:261:8)
    at parseExtends (file:///Users/paulrastoin/ws/twenty/node_modules/tsconfck/src/parse.js:196:24)
    ... 5 lines matching cause stack trace ...
    at async createBuilder (file:///Users/paulrastoin/ws/twenty/node_modules/vite/dist/node/chunks/config.js:34104:19)
    at async CAC.<anonymous> (file:///Users/paulrastoin/ws/twenty/node_modules/vite/dist/node/cli.js:629:10) {
  code: 'EXTENDS_RESOLVE',
  cause: Error: Cannot find module './.wxt/tsconfig.json'
  Require stack:
  - /Users/paulrastoin/ws/twenty/packages/twenty-apps/hacktoberfest-2025/linkedin-browser-extension/browser-extension/tsconfig.json
      at Module._resolveFilename (node:internal/modules/cjs/loader:1410:15)
      at require.resolve (node:internal/modules/helpers:163:19)
      at resolveExtends (file:///Users/paulrastoin/ws/twenty/node_modules/tsconfck/src/parse.js:249:14)
      at parseExtends (file:///Users/paulrastoin/ws/twenty/node_modules/tsconfck/src/parse.js:196:24)
      at Module.parse (file:///Users/paulrastoin/ws/twenty/node_modules/tsconfck/src/parse.js:54:23)
      at async Promise.all (index 21)
      at async BasicMinimalPluginContext.configResolved (/Users/paulrastoin/ws/twenty/node_modules/vite-tsconfig-paths/dist/index.js:134:9)
      at async Promise.all (index 0)
      at async resolveConfig (file:///Users/paulrastoin/ws/twenty/node_modules/vite/dist/node/chunks/config.js:35892:2)
      at async createBuilder (file:///Users/paulrastoin/ws/twenty/node_modules/vite/dist/node/chunks/config.js:34104:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
      '/Users/paulrastoin/ws/twenty/packages/twenty-apps/hacktoberfest-2025/linkedin-browser-extension/browser-extension/tsconfig.json'
    ]
  },
  tsconfigFile: '/Users/paulrastoin/ws/twenty/packages/twenty-apps/hacktoberfest-2025/linkedin-browser-extension/browser-extension/tsconfig.json'
}
vite v7.1.12 building for production...
src/components/BaseEmail.tsx:20:19 - error TS2719: Type 'import("/Users/paulrastoin/ws/twenty/node_modules/@lingui/core/dist/index").I18n' is not assignable to type 'import("/Users/paulrastoin/ws/twenty/node_modules/@lingui/core/dist/index").I18n'. Two different types with this name exist, but they are unrelated.
  Types have separate declarations of a private property '_locale'.

20     <I18nProvider i18n={i18nInstance}>
                     ~~~~

  node_modules/@lingui/react/dist/shared/react.b2b749a9.d.ts:42:5
    42     i18n: I18n;
           ~~~~
    The expected type comes from property 'i18n' which is declared here on type 'IntrinsicAttributes & Omit<I18nContext, "_"> & { children?: ReactNode; }'

✓ 492 modules transformed.

[vite:dts] Start generate declaration files...
computing gzip size (31)...[vite:dts] Declaration files built in 981ms.

dist/locales/generated/zh-CN.mjs        4.16 kB │ gzip:   2.02 kB
dist/locales/generated/zh-TW.mjs        4.21 kB │ gzip:   2.05 kB
dist/locales/generated/en.mjs           4.34 kB │ gzip:   1.28 kB
dist/locales/generated/fi-FI.mjs        4.45 kB │ gzip:   1.90 kB
dist/locales/generated/af-ZA.mjs        4.50 kB │ gzip:   1.88 kB
dist/locales/generated/no-NO.mjs        4.52 kB │ gzip:   1.85 kB
dist/locales/generated/da-DK.mjs        4.52 kB │ gzip:   1.84 kB
dist/locales/generated/pt-BR.mjs        4.54 kB │ gzip:   1.89 kB
dist/locales/generated/sv-SE.mjs        4.54 kB │ gzip:   1.88 kB
dist/locales/generated/nl-NL.mjs        4.55 kB │ gzip:   1.87 kB
dist/locales/generated/pt-PT.mjs        4.56 kB │ gzip:   1.88 kB
dist/locales/generated/it-IT.mjs        4.59 kB │ gzip:   1.87 kB
dist/locales/generated/pl-PL.mjs        4.66 kB │ gzip:   2.04 kB
dist/locales/generated/cs-CZ.mjs        4.67 kB │ gzip:   2.05 kB
dist/locales/generated/es-ES.mjs        4.70 kB │ gzip:   1.90 kB
dist/locales/generated/tr-TR.mjs        4.70 kB │ gzip:   2.02 kB
dist/locales/generated/de-DE.mjs        4.71 kB │ gzip:   1.97 kB
dist/locales/generated/ca-ES.mjs        4.73 kB │ gzip:   1.92 kB
dist/locales/generated/ko-KR.mjs        4.73 kB │ gzip:   2.14 kB
dist/locales/generated/ro-RO.mjs        4.73 kB │ gzip:   1.95 kB
dist/locales/generated/fr-FR.mjs        4.74 kB │ gzip:   1.92 kB
dist/locales/generated/hu-HU.mjs        4.82 kB │ gzip:   2.09 kB
dist/locales/generated/he-IL.mjs        4.88 kB │ gzip:   1.99 kB
dist/locales/generated/ja-JP.mjs        4.95 kB │ gzip:   2.19 kB
dist/locales/generated/vi-VN.mjs        5.19 kB │ gzip:   2.14 kB
dist/locales/generated/ar-SA.mjs        5.35 kB │ gzip:   2.21 kB
dist/locales/generated/pseudo-en.mjs    5.68 kB │ gzip:   2.27 kB
dist/locales/generated/sr-Cyrl.mjs      5.82 kB │ gzip:   2.32 kB
dist/locales/generated/uk-UA.mjs        6.11 kB │ gzip:   2.41 kB
dist/locales/generated/el-GR.mjs        6.47 kB │ gzip:   2.53 kB
dist/locales/generated/ru-RU.mjs        6.62 kB │ gzip:   2.55 kB
dist/index.mjs                        822.22 kB │ gzip: 179.78 kB
dist/locales/generated/zh-CN.js        4.23 kB │ gzip:   2.08 kB
dist/locales/generated/zh-TW.js        4.28 kB │ gzip:   2.10 kB
dist/locales/generated/en.js           4.41 kB │ gzip:   1.33 kB
dist/locales/generated/fi-FI.js        4.52 kB │ gzip:   1.95 kB
dist/locales/generated/af-ZA.js        4.56 kB │ gzip:   1.93 kB
dist/locales/generated/no-NO.js        4.58 kB │ gzip:   1.90 kB
dist/locales/generated/da-DK.js        4.59 kB │ gzip:   1.89 kB
dist/locales/generated/pt-BR.js        4.60 kB │ gzip:   1.94 kB
dist/locales/generated/sv-SE.js        4.61 kB │ gzip:   1.93 kB
dist/locales/generated/nl-NL.js        4.62 kB │ gzip:   1.92 kB
dist/locales/generated/pt-PT.js        4.63 kB │ gzip:   1.93 kB
dist/locales/generated/it-IT.js        4.66 kB │ gzip:   1.92 kB
dist/locales/generated/pl-PL.js        4.73 kB │ gzip:   2.09 kB
dist/locales/generated/cs-CZ.js        4.74 kB │ gzip:   2.10 kB
dist/locales/generated/es-ES.js        4.77 kB │ gzip:   1.95 kB
dist/locales/generated/tr-TR.js        4.77 kB │ gzip:   2.07 kB
dist/locales/generated/de-DE.js        4.77 kB │ gzip:   2.02 kB
dist/locales/generated/ca-ES.js        4.80 kB │ gzip:   1.97 kB
dist/locales/generated/ko-KR.js        4.80 kB │ gzip:   2.20 kB
dist/locales/generated/ro-RO.js        4.80 kB │ gzip:   2.00 kB
dist/locales/generated/fr-FR.js        4.81 kB │ gzip:   1.97 kB
dist/locales/generated/hu-HU.js        4.89 kB │ gzip:   2.14 kB
dist/locales/generated/he-IL.js        4.95 kB │ gzip:   2.04 kB
dist/locales/generated/ja-JP.js        5.02 kB │ gzip:   2.24 kB
dist/locales/generated/vi-VN.js        5.26 kB │ gzip:   2.19 kB
dist/locales/generated/ar-SA.js        5.42 kB │ gzip:   2.26 kB
dist/locales/generated/pseudo-en.js    5.75 kB │ gzip:   2.32 kB
dist/locales/generated/sr-Cyrl.js      5.89 kB │ gzip:   2.37 kB
dist/locales/generated/uk-UA.js        6.18 kB │ gzip:   2.47 kB
dist/locales/generated/el-GR.js        6.54 kB │ gzip:   2.58 kB
dist/locales/generated/ru-RU.js        6.69 kB │ gzip:   2.60 kB
dist/index.js                        606.48 kB │ gzip: 160.10 kB
✓ built in 2.45s

——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

 NX   Successfully ran target build for project twenty-emails and 2 tasks it depends on (5s)

Nx read the output from the cache instead of running the command for 2 out of 3 tasks.
```

Fixing folder to search for tsconfig from
2025-11-06 16:28:01 +00:00
GuillimandGitHub 373399fadc Settings of morph needs a CSS fix (#15681)
adding margin auto for morph preview card in order to vertically align
the box, as per figma

Before
<img width="467" height="331" alt="Screenshot 2025-11-06 at 16 36 00"
src="https://github.com/user-attachments/assets/23543cdc-d0f3-4bbf-8dc1-4ac5f26f786e"
/>

After
<img width="576" height="362" alt="Screenshot 2025-11-06 at 16 36 16"
src="https://github.com/user-attachments/assets/8530d59f-53a2-4eaa-834a-68b801bba3c8"
/>

Fixes https://github.com/twentyhq/core-team-issues/issues/1846
2025-11-06 17:06:04 +01:00
martmullandGitHub d1224e1c78 Fix wrong serverless handelrPath (#15675)
as title

After a sync hellp-world from twenty:
- before:

<img width="1052" height="321" alt="image"
src="https://github.com/user-attachments/assets/e008f2fd-f01e-405f-9ce0-1f14659157c6"
/>

- after:

<img width="1089" height="190" alt="image"
src="https://github.com/user-attachments/assets/3c9e301f-eabc-46e7-89e7-baf770dc0bc0"
/>
2025-11-06 16:31:29 +01:00
EtienneandGitHub 037663ddcd RichText editor fixes (#15678)
closes https://github.com/twentyhq/twenty/issues/15474
closes https://github.com/twentyhq/twenty/issues/15677
2025-11-06 16:21:57 +01:00
Abdullah.andGitHub 47a9b4ce9d fix: formidable relies on hexoid to prevent guessing of filenames for untrusted executable content (#15672)
Resolves [Dependabot Alert
224](https://github.com/twentyhq/twenty/security/dependabot/224) -
formidable relies on hexoid to prevent guessing of filenames for
untrusted executable content.

Used `yarn up formidable --recursive` to upgrade the version from 2.1.2
to 2.1.5.
2025-11-06 16:18:32 +01:00
neo773andGitHub 546fba7d05 [MESSAGING] Calendar check syncStatus in jobs (#15658) 2025-11-06 16:14:21 +01:00
neo773andGitHub dc57f00e26 register relaunch channels cron (#15662) 2025-11-06 16:14:06 +01:00
Baptiste DevessierandGitHub 9ec0a7b969 fix: use default trigger name if step name isn't defined (#15676)
## Before


https://github.com/user-attachments/assets/68427ca7-6523-4acc-bec3-7d98f3ae7840

## After


https://github.com/user-attachments/assets/8a998a52-29fc-450e-a92e-1cadc78e3856
2025-11-06 15:48:37 +01:00
Thomas TrompetteandGitHub e4ae792225 Allow rich text v2 in workflows (#15674)
Rich text V2 is supported and has probably been removed by mistake

Fix https://github.com/twentyhq/twenty/issues/15660
2025-11-06 14:33:06 +00:00
martmullandGitHub b00c36af16 Fix workspaceLogo in invite-email signed twice (#15673)
as title
2025-11-06 14:13:10 +00:00
Abdul RahmanandGitHub e518f03031 Fix: AI Agent tool errors and relation field handling (#15668)
### Problems Fixed

1. **Tool execution errors broke conversations**
- Failed tool executions showed "Processing..." indefinitely instead of
error messages
- Tool errors with `input: null` caused subsequent messages to fail with
`Missing required parameter: 'input[X].arguments'`

2. **Relation fields not saved in AI Agent**
- AI Agent couldn't save relation fields (e.g., `companyId`) when
creating/upserting records
   - Join column names weren't recognized during field validation

### Solutions

**Tool Error Handling:**
- Display error messages in UI with expandable error details
- Ensure tool parts always have valid `input` field (`input:
part.toolInput ?? {}`)
- Refactored `ToolStepRenderer` to accept complete `toolPart` object

**Relation Field Support:**
- Updated field validation in `create-record.service.ts` and
`upsert-record.service.ts`
- Check both `fieldIdByName` and `fieldIdByJoinColumnName` mappings

### Changes
- `packages/twenty-front/src/modules/ai/`
  - `ToolStepRenderer.tsx` - Error state handling
  - `AIChatAssistantMessageRenderer.tsx` - Pass complete toolPart
  - `mapDBPartToUIMessagePart.ts` - Prevent null tool input
- `packages/twenty-server/src/engine/core-modules/record-crud/services/`
  - `create-record.service.ts` - Add join column validation
  - `upsert-record.service.ts` - Add join column validation
2025-11-06 12:28:00 +01:00
Thomas TrompetteandGitHub 027e9dddd3 Increase main chunk size to 6.1MB (#15667)
As title
2025-11-06 10:38:08 +00:00
MarieandGitHub 3bb0eccf58 [Fix] fix getRoles for demo (#15666)
following https://github.com/twentyhq/twenty/pull/15547
2025-11-06 10:22:08 +00:00
8be56ee0cb i18n - translations (#15665)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-06 11:21:42 +01:00
Thomas TrompetteandGitHub 259c8cde08 Remove automated trigger update (#15663)
Automated triggers are duplicated on version update.
2025-11-06 10:01:24 +00:00
WeikoandGitHub 051a226b6f Fix display currency amount if currency code is empty string (#15654)
## Before
<img width="1306" height="841" alt="Screenshot 2025-11-05 at 18 40 05"
src="https://github.com/user-attachments/assets/964f5771-bd91-4cb2-9684-52073b845580"
/>


## After
<img width="1297" height="795" alt="Screenshot 2025-11-05 at 18 39 55"
src="https://github.com/user-attachments/assets/4ae99265-7459-4579-9f65-e2d8225e8306"
/>
2025-11-05 23:55:57 +01:00
MarieandGitHub 982964efbf Fix scroll to start when resize or move around columns (#15655)
Fixes https://github.com/twentyhq/private-issues/issues/361

There's room for more improvement here -
triggerInitialRecordTableDataLoad does a lot of things, should not be
triggered so much. actually even
RecordTableVirtualizedInitialDataLoadEffect should not be triggered when
there's just a metadata field change (if we trust the name
initialDataLoad)
2025-11-05 18:58:35 +01:00
martmullandGitHub abde3c04ac 1630 extensibility twenty cli ability to create edit and delete fields (#15501)
As title

- adds decorators in twenty-sdk
- update twenty-cli load-manifest to it gets @FieldMetadata infos +
testing
- update twenty-server so it CRUD fields properly, using
universalIdentifier
- Fix UI so we can update managed objects records
- move FieldMetadata items from twenty-server to twenty-shared
2025-11-05 17:50:06 +01:00
EtienneandGitHub 9fef0752a1 Fix subdomain generation at workspace creation (#15649) 2025-11-05 15:16:26 +00:00
f0aac163bd i18n - translations (#15644)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-05 14:49:51 +01:00
636c564168 Add shortcut on dashboard workspace entity + add shortcuts (#15603)
syncmetadata required!
closes
https://discord.com/channels/1130383047699738754/1435260594176393256

---------

Co-authored-by: bosiraphael <raphael.bosi@gmail.com>
Co-authored-by: Raphaël Bosi <71827178+bosiraphael@users.noreply.github.com>
2025-11-05 13:42:37 +00:00
5dfb0dfc4b i18n - translations (#15642)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-05 14:39:49 +01:00
Abdullah.andGitHub da1399afcf fix: brace-expansion regular expression denial of service vulnerability (#15637)
Resolves [Dependabot Alert
238](https://github.com/twentyhq/twenty/security/dependabot/238) -
brace-expansion regular expression denial of service vulnerability.

This alert was closed yesterday, but `yarn.lock` went back to the
previous versions somehow when an unrelated PR was reverted. Therefore,
creating a PR again.

Versions on main:
<p align="center">
<img width="470" height="385" alt="image"
src="https://github.com/user-attachments/assets/69fb6519-21c0-4f69-9412-a7b05451cf57"
/>
</p>

Updated versions in the PR:
<p align="center">
<img width="472" height="383" alt="image"
src="https://github.com/user-attachments/assets/69f2a7c4-8015-4a92-8e25-1b8953f329da"
/>
</p>
2025-11-05 14:34:41 +01:00
1b0c158c88 i18n - translations (#15635)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-05 14:23:12 +01:00
Alex GaleyandGitHub 583d490cd7 feat: [Fireflies] log cleanly (#15618)
## [0.2.2] - 2025-11-04

### Added
- **Enhanced logging system**: Introduced configurable `AppLogger` class
with log level support (debug, info, warn, error, silent)
- Environment-based log level configuration via `LOG_LEVEL` environment
variable
  - Test environment detection to prevent log noise during testing
  - Context-aware logging with proper prefixes for better debugging
- **Improved error handling**: Enhanced webhook signature verification
with detailed debug logging
- **Better debugging capabilities**: Added comprehensive logging
throughout webhook processing pipeline

### Enhanced
- **Webhook signature verification**: Improved signature validation with
detailed logging for troubleshooting
- **Error messages**: More descriptive error logging for failed
operations and security violations
- **Development experience**: Better debugging information for webhook
processing and API interactions
2025-11-05 14:16:18 +01:00
Thomas TrompetteandGitHub f21b862d52 Set lambda timeout in service (#15632)
Some functions keep running without a timeout being thrown. Doing it in
service directly.
2025-11-05 12:43:23 +00:00
c294af2944 i18n - translations (#15634)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-05 11:36:35 +01:00
nitinandGitHub 3f52102e18 fix groupMode regression caused due to default value flip (#15627) 2025-11-05 16:04:09 +05:30
0fcfcec426 (Breaking change) Switch between set password and change password on the settings page. (#15582)
Here is what the PR does:

- Surface password state in validatePasswordResetToken, returning
hasPassword so the client can tell whether a user is setting or changing
their password.
- Consume that flag throughout the front end (mock data, stories,
GraphQL types) and update the Reset/Set Password modal to swap the
heading/button label and success toast accordingly.
- After a successful password set/reset, immediately update the
logged-in user’s hasPassword flag so the Settings screen reflects the
new state without a reload.

Modal has two states now - reset password modal uses change password
state since it made intuitive sense.

<p align="center">
<img width="404" height="397" alt="image"
src="https://github.com/user-attachments/assets/c54cc581-1248-4395-833d-0202758e1947"
/>
</p>

<p align="center">
<img width="403" height="393" alt="image"
src="https://github.com/user-attachments/assets/d8a39a95-27e6-4037-86f2-1f74176002ba"
/>
</p>

---------

Co-authored-by: Félix Malfait <felix.malfait@gmail.com>
2025-11-05 11:29:37 +01:00
Abdul RahmanandGitHub cc7343a8f2 Revert: Agent chat umbrella hook refactoring due to streaming issue on thread switch (#15621)
## Summary

Reverts commits afc518a, ae22e64, and 800b5b5 that refactored
`useAgentChat` to address umbrella hook pattern feedback.

## Issues Introduced by Refactoring

The refactoring broke several critical functionalities:

1. **Streaming fails on thread switch** - Messages don't stream properly
when switching between threads
2. **Messages lost on tab close** - When the Ask AI tab is closed, the
request is lost instead of continuing in the background
3. **Blank chat requiring force-reload** - Chats often appear blank and
require switching to another chat to force a reload (closes
[#1771](https://github.com/twentyhq/core-team-issues/issues/1771))

## Root Cause

After extensive debugging, it appears **multiple instances of `useChat`
don't work well together**. The refactored architecture inadvertently
created scenarios where multiple `useChat` instances interfere with each
other.

## Resolution

Reverting to restore functionality. The umbrella hook pattern
optimization needs a different architectural approach that doesn't rely
on multiple `useChat` instances.

## Follow-up

While the umbrella hook feedback is valid, we need to rethink the
implementation strategy:
- Find an alternative to multiple `useChat` instances
- Possibly consolidate chat state management differently
2025-11-05 10:50:50 +01:00
003b04e9ae fix: removeuseMergeRecordRelatationship and simplify dry run response (#15486)
## Description

- This PR addresses issue
https://github.com/twentyhq/twenty/issues/15201
- Removed
[useMergeRecordRelationships.ts](https://github.com/twentyhq/twenty/compare/main...harshit078:fix-merge-frontend?expand=1#diff-5d0366f814ff0c0e8961f40120690206a7acd3f7b66135cfb8c4ad8d3f6bc681)
- now backend returns populated result and frontend just shows it
without refetching relations.
- to be merged after PR- https://github.com/twentyhq/twenty/pull/15484


## Visual Appearance

 


https://github.com/user-attachments/assets/09d7548a-74a9-4742-af49-e98b4174f68c

---------

Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2025-11-05 10:33:24 +01:00
martmullandGitHub 642e0c882a Fix missing creation attributes (#15624) 2025-11-05 08:29:23 +00:00
neo773andGitHub 5d5999b80a fix useTriggerProviderReconnect (#15620) 2025-11-05 00:51:25 +01:00
6a8dcf8d8b i18n - translations (#15619)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-05 00:32:12 +01:00
neo773andGitHub 0b7271ad13 refactor reconnect account logic (#15584) 2025-11-05 00:26:23 +01:00
martmullandGitHub 5c3eaf7a10 Fix dependencies (#15617)
As title
2025-11-05 00:13:39 +01:00
martmullandGitHub 86a6e04d78 Fix hacktoberfest applications (#15613)
As title, make them syncable with twenty-cli:0.2.0
<img width="1025" height="693" alt="image"
src="https://github.com/user-attachments/assets/a18f8ba3-b6fc-40e9-84dd-446ff8deeb04"
/>
2025-11-04 18:40:06 +01:00
nitinandGitHub b5064e88f6 Fix groupMode toggle (#15585)
groupMode should be undefined if no groupby is set on the secondary
axis!
This default value is also the reason -- all the logic -- where
groupMode was checked for conditional rendering -- for eg
, negative data labels when there is no groupby -- the labels should
appear below wasn't happening -- since there was always a default to
groupMode!
changes - 
- getting rid of the default value on the bar chart DTO for groupMode
- on front -- make sure groupMode is only set when the secondary axis
gets groupBy id and proper cleanup
2025-11-04 18:28:20 +01:00
GuillimandGitHub e64603e61a release 1.10 flush cache command (#15610) 2025-11-04 17:29:06 +01:00
Raphaël BosiandGitHub 05a28a8ec2 Create a feature flag for dashboards v2 (#15601)
Prevent users from creating v2 chart types via the api.
Only created unit tests and not integration tests (since it's not that
important, and the v2 will be released soon), but tested via the api
playground.
2025-11-04 16:29:08 +01:00
martmullandGitHub 59f3f03539 Move browser-extension to proper folder (#15608)
As title
- move all applications and browser extension into a
`packages/twenty-apps/hacktoberfest-2025` folder
2025-11-04 15:28:09 +00:00
Thomas TrompetteandGitHub bff7901678 Set default run limit in cache (#15606)
Will be used when there are too many workflow runs to enqueue in
workspace
2025-11-04 16:23:46 +01:00
Nabhag MotivarasandGitHub e09b67158e [HACKTOBERFEST] LINKEDIN EXTENSION (#15521)
# Twenty Browser Extension


A Chrome browser extension for capturing LinkedIn profiles (people and
companies) directly into Twenty CRM. This is a basic **v0** focused
mostly on establishing a architectural foundation.

## Overview

This extension integrates with LinkedIn to extract profile information
and create records in Twenty CRM. It uses **WXT** as the framework -
initially tried Plasmo, but found WXT to be significantly better due to
its extensibility and closer alignment with the Chrome extension APIs,
providing more control and flexibility.

## Architecture

### Package Structure

The extension consists of two main packages:

1. **`twenty-browser-extension`** - The main extension package (WXT +
React)
2. **`twenty-apps/browser-extension`** - Serverless functions for API
interactions

### Extension Components

#### Entrypoints

- **Background Script** (`src/entrypoints/background/index.ts`)
  - Handles extension messaging protocol
  - Manages API calls to serverless functions
  - Coordinates communication between content scripts and popup

- **Content Scripts**
- **`add-person.content`** - Injects UI button on LinkedIn person
profiles
- **`add-company.content`** - Injects UI button on LinkedIn company
profiles
- Both scripts use WXT's `createIntegratedUi` for seamless DOM injection
  - Extract profile data from LinkedIn DOM

- **Popup** (`src/entrypoints/popup/`)
  - React-based popup UI
  - Displays extracted profile information
  - Provides buttons to save person/company to Twenty

#### Messaging System

Uses `@webext-core/messaging` for type-safe communication between
extension components:

```typescript
// Defined in src/utils/messaging.ts
- getPersonviaRelay() - Relays extraction from content script
- getCompanyviaRelay() - Relays extraction from content script
- extractPerson() - Extracts person data from LinkedIn DOM
- extractCompany() - Extracts company data from LinkedIn DOM
- createPerson() - Creates person record via serverless function
- createCompany() - Creates company record via serverless function
- openPopup() - Opens extension popup
```

#### Serverless Functions

Located in
`packages/twenty-apps/browser-extension/serverlessFunctions/`:

- **`/s/create/person`** - Creates a new person record in Twenty
- **`/s/create/company`** - Creates a new company record in Twenty
- **`/s/get/person`** - Retrieves existing person record (placeholder)
- **`/s/get/company`** - Retrieves existing company record (placeholder)

## Development Guide

### Prerequisites

- Twenty CLI installed globally: `npm install -g twenty-cli`
- API key from Twenty: https://twenty.com/settings/api-webhooks

### Setup
   ```
1. **Configure environment variables:**
   - Set `TWENTY_API_URL` in the serverless function configuration
- Set `TWENTY_API_KEY` (marked as secret) in the serverless function
configuration
- For local development, create a `.env` file or configure via
`wxt.config.ts`

### Development Commands

```bash
# Start development server with hot reload
npx nx run dev twenty-browser-extension

# Build for production
npx nx run build twenty-browser-extension

# Package extension for distribution
npx nx run package twenty-browser-extension
```

### Development Workflow

1. **Start the dev server:**
   ```bash
   npx nx run dev twenty-browser-extension
   ```
   This starts WXT in development mode with hot module reloading.

2. **Load extension in Chrome:**
   - Navigate to `chrome://extensions/`
   - Enable "Developer mode"
   - Click "Load unpacked"
   - Select `packages/twenty-browser-extension/dist/chrome-mv3-dev/`

3. **Test on LinkedIn:**
- Navigate to a LinkedIn person profile:
`https://www.linkedin.com/in/...`
- Navigate to a LinkedIn company profile:
`https://www.linkedin.com/company/...`
   - The "Add to Twenty" button should appear in the profile header
   - Click the button to open the popup and save to Twenty

### Project Structure

```
packages/twenty-browser-extension/
├── src/
│   ├── common/
│   │   └── constants/      # LinkedIn URL patterns
│   ├── entrypoints/
│   │   ├── background/     # Background service worker
│   │   ├── popup/          # Extension popup UI
│   │   ├── add-person.content/  # Content script for person profiles
│   │   └── add-company.content/ # Content script for company profiles
│   ├── ui/                 # Shared UI components and theme
│   └── utils/              # Messaging utilities
├── public/                 # Static assets (icons)
├── wxt.config.ts          # WXT configuration
└── project.json            # Nx project configuration
```

## Current Status (v0)

This is a foundational version focused on architecture. Current
features:

 Inject UI buttons into LinkedIn profiles
 Extract person and company data from LinkedIn
 Display extracted data in popup
 Create person records in Twenty
 Create company records in Twenty

## Planned Features

- [ ] Provide a way to have API key and custom remote URLs.
- [ ] Detect if record already exists and prevent duplicates
- [ ] Open existing Twenty record when clicked (instead of creating
duplicate)
- [ ] Sidepanel Overlay UI for rich profile viewing/editing
- [ ] Enhanced data extraction (email, phone, etc.)
- [ ] Better error handling

# Demo


https://github.com/user-attachments/assets/0bbed724-a429-4af0-a0f1-fdad6997685e



https://github.com/user-attachments/assets/85d2301d-19ee-43ba-b7f9-13ed3915f676
2025-11-04 15:52:06 +01:00
Raphaël BosiandGitHub 06f5ac63dc Add dashboards lab image (#15605)
<img width="800" height="500" alt="is-dashboard-enabled"
src="https://github.com/user-attachments/assets/9b7f09ff-54f2-4026-b2a8-8d0a9ea1a98b"
/>
2025-11-04 15:44:46 +01:00
cd05470e99 i18n - translations (#15602)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-04 15:36:08 +01:00
Paul RastoinandGitHub 8dd43be9a2 Create many view groups (#15591)
# Introduction
Same as https://github.com/twentyhq/twenty/pull/15576 but for view
groups creation

When creating a kanban view with v2 flag activated in production result
in race condition due to request being slow and //.
That's why we're introducing a batch create on view group here
closing https://github.com/twentyhq/core-team-issues/issues/1847

## In v2
- batch create view group endpoint is available
- frontend will target the new endpoint

## In v1
- batch create view group endpoint is not available
- frontend will stick to old fake batch view group creation loop


## Gallery
### v2
<img width="1796" height="486" alt="image"
src="https://github.com/user-attachments/assets/932cfe9f-85f1-41cc-a1c4-72a4b5d5a256"
/>

### v1
<img width="1852" height="966" alt="image"
src="https://github.com/user-attachments/assets/8aa9df11-cdea-4b12-ae60-118cdf5e257b"
/>
2025-11-04 15:17:55 +01:00
558990fbdd i18n - translations (#15600)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-04 15:13:13 +01:00
martmullandGitHub 89c8d89330 Revert "Revert "[hacktoberfest] feat: add fireflies"" (#15595)
Reverts twentyhq/twenty#15589

Add back without the breaking change
2025-11-04 15:07:30 +01:00
nitinandGitHub 186dbb8aca fast-follows: fix placeholder not appearing when no widgets in a tab (#15599)
closes -
https://discord.com/channels/1130383047699738754/1435261256251605053

before:


https://github.com/user-attachments/assets/fbbfd6b0-6c25-48c3-9367-efbf47efd34a

after:


https://github.com/user-attachments/assets/87105c4e-cf79-43c0-83bb-ebb4c32a64fc
2025-11-04 14:05:02 +00:00
neo773andGitHub e3076328dd Child folders followup (#15526) 2025-11-04 15:04:03 +01:00
15a6ca64da i18n - translations (#15598)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-04 14:40:04 +01:00
Paul RastoinandGitHub 1472eb3cda [Twenty-front] Jest maxWorkers 50% as if not result to cpu halt (#15594) 2025-11-04 14:35:35 +01:00
Raphaël BosiandGitHub 7256abad3a Dashboard: Deactivate delete and navigation actions in edit mode (#15590)
https://github.com/user-attachments/assets/74256232-dfb1-4cb5-9fd8-854e0b3b7c09
2025-11-04 18:43:36 +05:30
Paul RastoinandGitHub 3514054235 V2 centralize relation optimistic logic (#15552)
# Introduction
This PR aims to deprecate having to manually handle optimistic side
effect foreign key addition in the whole v2 experience.
This PR implements the strong basis + builder refactor of the optimistic
computation of a given flat entity maps with its related flat entity
maps ( runner needs a small refactor on actions type definition first )
Flat entity maps updates through mutations are now only scoped to the
generic entity builder ( very isolated )

## What's next
- Refactor actions v2 type definition to gain grain over `metadataName`
and action operation ( `create` `delete` `update` ).
from `{type: 'create_view_field'}` to `{metadataName: 'view_field',
type: 'create' }`
- Use new optimistic tool computation tools
- Only invalidate impacted flat maps cache

## New tools
Strictly dynamically typed new flat entity maps tools
- `addFlatEntityToFlatEntityAndRelatedEntityMapsThroughMutationOrThrow`
-
`deleteFlatEntityFromFlatEntityAndRelatedEntityMapsThroughMutationOrThrow`

## Unit test
Adding basic unit testing coverage to introduced tools

## `FlatEntityValidationArgs`
From 
```ts
export type FlatEntityValidationArgs<T extends AllMetadataName> = {
  flatEntityToValidate: MetadataFlatEntity<T>;
  optimisticFlatEntityMaps: MetadataFlatEntityMaps<T>;
  mutableDependencyOptimisticFlatEntityMaps: MetadataValidationRelatedFlatEntityMaps<T>;
  workspaceId: string;
  remainingFlatEntityMapsToValidate: MetadataFlatEntityMaps<T>;
  buildOptions: WorkspaceMigrationBuilderOptions;
};

```

To
```ts
export type FlatEntityValidationArgs<T extends AllMetadataName> = {
  flatEntityToValidate: MetadataFlatEntity<T>;
  optimisticFlatEntityMapsAndRelatedFlatEntityMaps: MetadataFlatEntityAndRelatedFlatEntityMapsForValidation<T>;
  workspaceId: string;
  remainingFlatEntityMapsToValidate: MetadataFlatEntityMaps<T>;
  buildOptions: WorkspaceMigrationBuilderOptions;
};

```
2025-11-04 12:28:28 +01:00
WeikoandGitHub 281070423f Revert "[hacktoberfest] feat: add fireflies" (#15589)
Reverts twentyhq/twenty#15527 due to tsconfig base update
2025-11-04 12:25:23 +01:00
Yannik SüßandGitHub ad80a50354 feat: add Webmetic Visitor Intelligence (#15551)
# Webmetic Visitor Intelligence

Automatically sync B2B website visitor data into Twenty CRM. Identify
anonymous companies visiting your website and track their engagement
without forms or manual entry. Every hour, Webmetic enriches your CRM
with actionable sales intelligence about who's researching your product
before they ever fill out a contact form.

## Features

- 🔄 **Hourly Automatic Sync**: Fetches visitor data every hour via cron
trigger
- 🏢 **Company Enrichment**: Creates and updates company records with
visitor intelligence
- 📊 **Website Lead Tracking**: Records individual visits with detailed
engagement metrics
- 📈 **Engagement Scoring**: Webmetic's proprietary scoring algorithm
(0-100) identifies warm leads
- 🎯 **Sales Intelligence**: See which companies are actively researching
your product
- 🌍 **Geographic Data**: Captures visitor city and country information
- 🔗 **UTM Parameter Tracking**: Full campaign attribution with
utm_source, utm_medium, utm_campaign, utm_term, and utm_content
- 📄 **Page Journey Mapping**: Records complete navigation paths and
scroll depth
-  **Smart Deduplication**: Prevents duplicate records using
session-based identification
- 🔐 **Production-Ready**: Built with rate limiting, error handling, and
idempotent operations

## Requirements

- `twenty-cli` — `npm install -g twenty-cli`
- A Twenty API key (create one at
`https://twenty.com/settings/api-webhooks` and name it **"Webmetic"**)
- A Webmetic account with API access. Sign up at
[webmetic.de](https://webmetic.de)
- Node 18+ (for local development)

## Metadata prerequisites

The app automatically creates the `websiteLead` custom object with all
required fields on first run. No manual field provisioning is needed.

**Created automatically:**
- `websiteLead` object with 14 custom fields (TEXT, NUMBER, DATE_TIME
types)
- Company relation field (Many-to-One from websiteLead to Company)
- All fields are idempotent — safe to re-run without errors

## Quick start

### 1. Deploy the app

```bash
twenty auth login
cd packages/twenty-apps/webmetic
twenty app sync
```

### 2. Configure environment variables

- **First, create a Twenty API key**:
  - Go to **Settings → API & Webhooks → API Keys**
  - Click **+ Create API Key**
  - Name it **"Webmetic"**
  - Copy the generated key
- **Then configure the app**:
- Open **Settings → Apps → Webmetic Visitor Intelligence →
Configuration**
  - Provide values for the required keys:
- `TWENTY_API_KEY` (required secret; paste the API key you just created)
- `TWENTY_API_URL` (optional; defaults to `http://localhost:3000` for
local dev, set to your production URL)
- `WEBMETIC_API_KEY` (required secret; get from
[app.webmetic.de/?menu=api_details](https://app.webmetic.de/?menu=api_details))
- `WEBMETIC_DOMAIN` (required; your website domain to track, e.g.,
`example.com`)
  - Save the configuration

### 3. Test the function

- On the app page, select **Test your function**
- Click **Run**
- You should see a success summary showing companies and leads created
- Check **Settings → Data Model → Website Leads** to verify the custom
object was created
- Navigate to **Website Leads** from the sidebar to view synced visitor
data

### 4. Automatic hourly sync begins

The cron trigger (`0 * * * *`) runs every hour on the hour, continuously
syncing new visitor data.

## How it works

### Data flow

```
Webmetic API ─[hourly]→ sync-visitor-data ─[create/update]→ Twenty CRM
                              │
                              ├─→ Company records (with enrichment data)
                              └─→ Website Lead records (linked to companies)
```

### Sync process

1. **Cron Trigger**: Every hour at :00 (e.g., 1:00, 2:00, 3:00)
2. **Schema Validation**: Ensures `websiteLead` object and all fields
exist (creates if missing)
3. **Fetch Visitors**: Queries Webmetic API `/company-sessions` endpoint
for last hour
4. **Process Companies**: For each visitor's company:
   - Searches for existing company by domain
- Creates new company or updates existing with latest data from Webmetic
   - Extracts employee count from ranges (e.g., "11-50" → 50)
5. **Create Website Leads**: For each session:
   - Checks for duplicate (by name: "Company - Date")
   - Creates lead record with engagement metrics
   - Links to company via relation field
6. **Rate Limiting**: 800ms delay between API calls (75 requests/minute
max)

### Data captured

**Company enrichment (from Webmetic):**
- Name, domain, address (street, city, postcode, country)
- Employee count (parsed from ranges)
- LinkedIn URL (if available)
- Tagline/short description

**Website Lead tracking:**
- Visit date and session duration
- Page views count and pages visited (full navigation path)
- Traffic source (Direct, or utm_source/utm_medium combination)
- UTM campaign parameters (campaign, term, content)
- Visitor location (city, country)
- Engagement score (Webmetic's 0-100 scoring)
- Average scroll depth percentage
- Total user interaction events (clicks, etc.)

## Configuration reference

| Variable | Required | Description |
|----------|----------|-------------|
| `TWENTY_API_KEY` |  Yes | Your Twenty API key for authentication |
| `TWENTY_API_URL` |  No | Base URL of your Twenty instance (defaults
to `http://localhost:3000`) |
| `WEBMETIC_API_KEY` |  Yes | Your Webmetic API key from
[app.webmetic.de/?menu=api_details](https://app.webmetic.de/?menu=api_details)
|
| `WEBMETIC_DOMAIN` |  Yes | Website domain to track (e.g.,
`example.com` without protocol) |

## API integration

This app uses multiple Twenty CRM APIs:

**REST API** (data operations):
- `GET /rest/metadata/objects` — Fetch object metadata with fields
- `GET /rest/companies` — Find existing companies by domain
- `POST /rest/companies` — Create new companies
- `PATCH /rest/companies/:id` — Update company data
- `POST /rest/websiteLeads` — Create website lead records

**GraphQL Metadata API** (schema management):
- `createOneObject` mutation — Creates custom objects (if needed)
- `createOneField` mutation — Creates custom fields and relations

## Website Lead object structure

The app creates a custom `websiteLead` object with the following fields:

| Field | Type | Description |
|-------|------|-------------|
| `name` | TEXT | Lead identifier (Company Name - Date) |
| `company` | RELATION | Many-to-One relation to Company object |
| `visitDate` | DATE_TIME | When the visit occurred |
| `pageViews` | NUMBER | Number of pages viewed during session |
| `sessionDuration` | NUMBER | Visit length in seconds |
| `trafficSource` | TEXT | Where visitor came from
(utm_source/utm_medium or Direct) |
| `pagesVisited` | TEXT | List of page URLs visited (→ separated, max
1000 chars) |
| `utmCampaign` | TEXT | UTM campaign parameter |
| `utmTerm` | TEXT | UTM term parameter (keywords for paid search) |
| `utmContent` | TEXT | UTM content parameter (for A/B testing) |
| `visitorCity` | TEXT | Geographic city of visitor |
| `visitorCountry` | TEXT | Geographic country of visitor |
| `visitCount` | NUMBER | Total number of visits from this company |
| `engagementScore` | NUMBER | Webmetic engagement score (0-100) |
| `averageScrollDepth` | NUMBER | Average scroll percentage (0-100) |
| `totalUserEvents` | NUMBER | Total count of user interactions (clicks,
etc.) |

## Troubleshooting

**Issue**: No data syncing after setup
- **Solution**: Run "Test your function" to manually trigger a sync and
check logs. Verify your `WEBMETIC_API_KEY` and `WEBMETIC_DOMAIN` are
correct.

**Issue**: "Duplicate Domain Name" error
- **Solution**: This occurs if you previously deleted a company. Twenty
maintains unique constraints on soft-deleted records. Either restore the
company from trash or contact support.

**Issue**: Missing fields on websiteLead object
- **Solution**: The sync function recreates missing fields
automatically. Run "Test your function" once to repair the schema.

**Issue**: Empty linkedinLink on companies
- **Solution**: Webmetic doesn't have LinkedIn data for that specific
company. The mapping is working correctly; data availability depends on
Webmetic's enrichment coverage.

**Issue**: Employee count not matching Webmetic
- **Solution**: Webmetic returns ranges (e.g., "11-50"). The app uses
the maximum value (50) to better represent company size.

**Issue**: Test shows "No new visitors in the last hour"
- **Solution**: Normal if you have no traffic in the last 60 minutes.
Wait for actual traffic or manually adjust the time range in code for
testing.

## Rate limiting and performance

- **Webmetic API**: No pagination used; fetches all visitors from last
hour
- **Twenty API**: 800ms delay between requests (75 requests/minute)
- **Processing**: Handles 14+ companies with full enrichment in under 30
seconds
- **Cron schedule**: `0 * * * *` (every hour on the hour)
- **Duplicate prevention**: Checks existing leads by name before
creating

## Development

### Local testing

```bash
cd packages/twenty-apps/webmetic
yarn install

# Set up .env file
cp .env.example .env
# Edit .env with your credentials

# Sync to local Twenty instance
npx twenty-cli app sync

# Watch for changes
npx twenty-cli app dev
```

### Manual trigger

Use the Twenty UI test panel or trigger via API:

```bash
curl -X POST http://localhost:3000/functions/sync-visitor-data \
  -H "Authorization: Bearer YOUR_API_KEY"
```

## Architecture notes

- **100% programmatic schema**: Fields created via GraphQL Metadata API,
not manifests
- **Idempotent operations**: Safe to re-run without duplicates or errors
- **Smart domain matching**: Normalizes domains (strips www, protocols)
for matching
- **Error resilience**: Individual company failures don't stop the
entire sync
- **Detailed logging**: Returns full execution log in response for
debugging

## Contributing

Built with 🍺 and ❤️ in Munich by [Team Webmetic](https://webmetic.de)
for Twenty CRM Hacktoberfest 2025.

For issues or questions:
- Webmetic API: [webmetic.de](https://webmetic.de)
- Twenty CRM: [twenty.com/developers](https://twenty.com/developers)

## License

MIT
2025-11-04 12:10:11 +01:00
Alex GaleyandGitHub 995f5b3b3f [hacktoberfest] feat: add fireflies (#15527) 2025-11-04 12:09:53 +01:00
BOHEUSandGitHub 6065fa61c7 Stripe synchronizer extension (#15515)
Challenge 7 from "Call for projects" list
2025-11-04 12:09:26 +01:00
Raphaël BosiandGitHub 98180c263d Filter out null values in tooltip (#15588)
Before:
<img width="356" height="330" alt="CleanShot 2025-11-04 at 11 44 14@2x"
src="https://github.com/user-attachments/assets/924f8623-3961-411c-9763-800fd9491224"
/>

After:
<img width="418" height="242" alt="CleanShot 2025-11-04 at 11 43 49@2x"
src="https://github.com/user-attachments/assets/54cf5fa4-1146-43b4-8cff-59817bcbe6a4"
/>
2025-11-04 11:09:12 +00:00
BOHEUSandGitHub ff1a87080a Mailchimp synchronizer extension (#15512)
Challenge 10 from "Call for projects" list
2025-11-04 12:05:51 +01:00
BOHEUSandGitHub e4dbe87fa1 Last email interaction extension (#15511)
Challenge 4 from "Call for projects" list
2025-11-04 12:05:22 +01:00
Ali IlmanandGitHub 1957f839ff [HACKTOBERFEST] [FEATURE] Create activity summary application (#15510)
## Background
This is team Comfortably Summed's submission for Twenty's Hacktoberfest.
We built an activity summary application that can periodically send
messages to the following platforms: Slack; Discord; and WhatsApp.
### Features
- 🧑‍💻 **People & Company Tracking**: Summarizes newly created people and
companies
- 🎯 **Opportunity Monitoring**: Reports on new opportunities created,
broken down by stage
-  **Task Analytics**:
  - Tracks task creation
  - Calculates on-time completion rates
  - Identifies team members with the most overdue tasks (the "slackers")
- 🔔 **Multi-Platform Notifications**: Send reports to Slack, Discord,
and/or WhatsApp
-  **Configurable Time Range**: Look back any number of days
### Summary of Changes
- Adds a new Twenty app called Activity Summary
- Contains a single index.ts file which utilises exported functions from
opportunity-creation-summariser.ts, people-creation-summariser.ts,
task-creation-summariser.ts, and senders.ts
- Implementation of sending a message to Slack, Discord, and WhatsApp
can be found in senders.ts
- Retrieval and summarising of Opportunity creation can be found in
opportunity-creation-summariser.ts
- Retrieval and summarising of People creation can be found in
people-creation-summariser.ts
- Retrieval and summarising of Task creation can be found in
task-creation-summariser.ts
## Screenshots
### Message to our Slack channel
<details>
<summary>Screenshot</summary>

<img width="326" height="242" alt="Screenshot 2025-11-01 at 22 05 30"
src="https://github.com/user-attachments/assets/57c5d50b-959d-4c3f-bd7d-00f42bf545b2"
/>
</details>

### Message to our Discord server's channel
<details>
<summary>Screenshot</summary>

<img width="472" height="386" alt="Screenshot 2025-11-01 at 22 06 44"
src="https://github.com/user-attachments/assets/f4a38d7f-e82d-47b0-a4b3-7bcf063fa575"
/>
</details>

### Message to our WhatsApp number
<details>
<summary>Screenshot</summary>
<img width="972" height="548" alt="IMG_2024"
src="https://github.com/user-attachments/assets/5533fc4d-a3ee-4e11-a9e7-9cc6a96316fc"
/>

</details>

### App-level configuration
<details>
<summary>Screenshot</summary>

<img width="442" height="385" alt="Screenshot 2025-11-01 at 22 02 14"
src="https://github.com/user-attachments/assets/c9948f57-f22c-42a0-972f-3348f480aa30"
/>
</details>

### Serverless functions
<details>
<summary>Screenshot</summary>

<img width="413" height="378" alt="Screenshot 2025-11-01 at 22 03 48"
src="https://github.com/user-attachments/assets/d297967b-52ce-4690-bb04-a16d89729d94"
/>
</details>

### Cron configuration
Default value in place due to Cron having a non-editable text input.
<details>
<summary>Screenshot</summary>

<img width="395" height="386" alt="Screenshot 2025-11-01 at 22 08 03"
src="https://github.com/user-attachments/assets/a95a708c-7136-4512-99c3-a6723adc0da5"
/>
</details>

## Testing
Sync the application to your Twenty instance and ensure the following
variables have values:
- `TWENTY_API_KEY` - Your Twenty CRM API key
- `DAYS_AGO` - Number of days to look back for the report

Choose any of the supported platforms and you shall see a summary being
sent!
2025-11-04 12:04:59 +01:00
7f3af243c7 [Hacktoberfest] AI-Powered Meeting Transcript Analysis Extension for Twenty CRM (#15507)
# 🧠 AI-Powered Meeting Transcript to CRM Data Integration

## **Overview**
This feature automatically transforms meeting transcripts into
structured CRM data using AI.
When unstructured meeting notes are received via a **webhook**, the
system processes them and creates organized **notes, tasks, and
assignments** directly in **Twenty CRM**.

---

## **Key Features**

- **🤖 AI-Powered Analysis:**  
Extracts **summaries, action items, assignees, and due dates** from
natural language transcripts.

- **📋 Smart Task Consolidation:**  
  Merges related sub-tasks into unified deliverables  
  *(e.g., `"draft" + "review" + "present"` → one consolidated task).*

- **👥 Intelligent Assignment:**  
Uses **GraphQL member lookup** to match extracted assignee names to
workspace member IDs with flexible string matching.

- **🔗 Automatic Linking:**  
Links generated **notes and tasks** to relevant contacts using
`noteTargets` and `taskTargets`.

- **🗓️ Date Parsing:**  
Converts **relative date expressions** (e.g., “next Monday”, “end of
week”) into **ISO-formatted dates** for accurate scheduling.

---

## **Technical Stack**

| Component | Description |
|------------|-------------|
| **AI Provider** | Groq (via OpenAI SDK) using the `GPT-OSS-20B` model
|
| **APIs** | Twenty CRM REST API + GraphQL (for member resolution) |
| **Runtime** | Webhook-triggered **serverless function** written in
**TypeScript** |

---

## **Example Input**

```json
{
  "transcript": "During the Project Phoenix Kick-off on November 1st, 2025, we discussed securing the Series B funding. ACTION: Dylan Field is designated to finalize the investor deck layout and needs to present it next Monday, November 4th. Irfan Hussain will review the deck before the presentation by Monday morning. COMMITMENT: Dario Amodei confirmed he would personally review the security protocols for the AI model before the end of this week, by Friday November 7th. Iqra Khan will coordinate the security review process and ensure completion by the Friday deadline.",
  "meetingTitle": "Project Phoenix Kick-off",
  "meetingDate": "2025-11-01",
  "participants": [
    "Brian Chesky",
    "Dario Amodei",
    "Iqra Khan",
    "Irfan Hussain",
    "Dylan Field"
  ],
  "token": "e6d9d54e51953fd5a451cca933c63e7f8783b001f0c45be95be9d09ee06c6cda",
  "relatedPersonId": "6c4b0e98-b69e-42a4-ba0c-fd2eeafca642"
}
```
---

## **Example Output**

```json
{
  "success": true,
  "noteId": "9cc3b4fc-ae37-4b3e-a343-a4c69cf6b1e8",
  "taskIds": [
    "0f408062-0dcc-49f0-9866-1ea05392661d",
    "2b3739bf-0653-4101-9419-6a44ea5135cd"
  ],
  "summary": {
    "noteCreated": true,
    "tasksCreated": 2,
    "actionItemsProcessed": 2,
    "commitmentsProcessed": 0
  },
  "executionLogs": [
    " Validation passed",
    "📝 RelatedPersonId: 6c4b0e98-b69e-42a4-ba0c-fd2eeafca642",
    "🤖 Starting transcript analysis...",
    " Analysis complete: 2 action items, 0 commitments",
    "📄 Creating note in Twenty CRM...",
    " Note created: 9cc3b4fc-ae37-4b3e-a343-a4c69cf6b1e8",
    "📋 Creating tasks from action items...",
    " Action item tasks created: 2",
    "📋 Creating tasks from commitments...",
    " Commitment tasks created: 0"
  ]
}
```
---

Variable Name | Description
-- | --
GROQ_API_KEY | API key for authenticating requests to the Groq AI
service.
TWENTY_API_KEY | Authentication token used to access the Twenty CRM API.
TWENTY_API_URL | Base URL for the Twenty CRM REST API.
WEBHOOK_SECRET | Secret key used to validate incoming webhook requests
for security.
NODE_ENV | Defines the runtime environment (development, production,
etc.).
LOG_LEVEL | Controls verbosity of logs (info, debug, error).

---

## **Attachments**
<img width="649" height="863" alt="swappy-20251103-035128"
src="https://github.com/user-attachments/assets/2f0390af-9538-4fe2-bba8-f38e558935ad"
/>

---




https://github.com/user-attachments/assets/88620035-67ed-4150-b0be-46131083e2c5



---

Co-authored-by: iqra77818 <iqra77818@gmail.com>
2025-11-04 12:04:00 +01:00
Harshit VashishtandGitHub 0cdc61c211 [HACKTOBERFEST] feat: Add AI meeting transcript integration with Twenty CRM (#15498)
This PR introduces an end-to-end workflow to automatically process
meeting transcripts and create structured notes and tasks in Twenty CRM.
It leverages OpenAI to extract summaries, key points, action items, and
participant commitments from transcripts.

Key features include:
1. AI-powered transcript analysis: Uses OpenAI GPT‑4o-mini to extract a
concise summary, key discussion points, action items, and commitments.
2. Automated note creation: Generates a rich Markdown note in Twenty CRM
with summary and key points.
3. Task automation: Automatically creates tasks in Twenty CRM from
extracted action items and commitments, linking them to the meeting
note.
4. Custom field support: Supports optional metadata from transcript
payloads, which can be included in note/task content or mapped to custom
fields in Twenty CRM if supported.
5. Webhook-ready: Designed to process Granola-style (or similar) webhook
payloads, making it easy to integrate with any AI meeting tool.





Sumbission for Hacktoberfest 
Team Name : One for All
2025-11-04 12:03:32 +01:00
James BryantandGitHub 7ec56433c7 [HACKTOBERFEST] Add rollup engine app with UI-driven configuration (#15482)
## Summary

- add packages/twenty-apps/rollup-engine: a parameterised rollup engine
that ships a default Opportunity → Company
    aggregation.
- declare runtime config in package.json (TWENTY_API_KEY, optional
TWENTY_API_BASE_URL, and ROLLUP_ENGINE_CONFIG) so
app configuration lives entirely in Settings → Apps → [App] →
Configuration.
- document the workflow in README.md: deploy via twenty app sync,
populate env vars in the UI, use the Test panel with
    a ready JSON payload, and reference troubleshooting tips.
- adjust the function entry point to a named async export and add
fallback logic for blank base URLs, matching the
    UI’s env behaviour.
- prune legacy templates and examples so
config/templates/opportunity-to-company.json is the single copy/paste
    starting point.

  ## UI / UX impact

  After syncing the app:

- the Configuration screen shows the three env keys with helpful
descriptions (API key, optional base URL, JSON
    override),
  - the built-in Test your function panel works immediately
- and the default JSON config is available from
config/templates/opportunity-to-company.json for users who need to
    customise rollups.

  ## Testing

  - Out-of-the-box deploy to the hosted workspace (Opportunity update) ✓
  - “Test your function” with the default config ✓
- Override example: point debugOpportunityCount at a scratch field via
ROLLUP_ENGINE_CONFIG ✓
  - Optional: local smoke test (yarn install && yarn smoke) still passes
2025-11-04 12:03:00 +01:00
WeikoandGitHub fd5c39b4da Remove default feature flag feature (#15587)
## Context
Having rollout feature for new workspaces creates bad experience for new
users and doesn't bring as much value as existing ones anyway. Removing
migration v2 from default feature flag and the whole concept of default
feature flag
2025-11-04 11:40:49 +01:00
Paul RastoinandGitHub a3dc6e5c59 View field create many mutation (#15576)
# Introduction
When creating a view with v2 flag activated in production result in race
condition due to request being slow and //.
That's why we're introducing a batch create on view field here
closing https://github.com/twentyhq/core-team-issues/issues/1836

## In v2
- batch create view field endpoint is available
- frontend will target the new endpoint

## In v1
- batch create view field endpoint is not available
- frontend will stick to old fake batch view field creation loop

## Polish
- use persist view field is quite verbose as contains two data model we
could aim to create an update many view fields in order to standardize
new pattern
2025-11-04 11:36:08 +01:00
nitinandGitHub 106c33abec fix inconsistent widget placeholder placement (#15580)
fixes -
https://github.com/twentyhq/twenty/pull/15496#issuecomment-3481636780

and https://discord.com/channels/1130383047699738754/1434971632539009055

- make the pending placeholder to be non-static -- so that it behaves
similarly to compact behavior like other widgets do
- make sure users can't set dashboards to be opened in the side panel --
similar to workflows

before- 


https://github.com/user-attachments/assets/d991db56-1388-4e4b-b743-a63f56b6187a

after- 


https://github.com/user-attachments/assets/9031f2c6-1e3b-4604-a5a0-3124d14484ce
2025-11-04 11:07:57 +01:00
Abdullah.andGitHub 77f04e7306 fix: brace-expansion regular expression denial of service vulnerability (#15558)
Resolves [Dependabot Alert
236](https://github.com/twentyhq/twenty/security/dependabot/236) and
[Dependabot Alert
237](https://github.com/twentyhq/twenty/security/dependabot/237).

Used `yarn up brace-expansion --recursive` to move versions from 1.1.11
and 2.0.1 to 1.1.12 and 2.0.2.
2025-11-04 08:53:57 +01:00
Abdullah.andGitHub 14c66c942f fix: update tmp to a safer version. (#15554)
@charlesBochet had a conversation with Felix and he said we don't need
to spend time upgrading `zapier-platform-core` and `zapier-platform-cli`
since `twenty-zapier` will be deprecated anyway, making those packages
irrelevant.

I have updated tmp to a safer version elsewhere using `yarn up tmp
--recursive`. Also added `yarn.lock` to both server and front ci.

The massive changes in `yarn.lock` were introduced by
`zapier-platform-cli` version 17x - not sure if they caused those
breaking changes, but if they did and we still want update
zapier-related packages, I will take that up in another PR.
2025-11-04 08:53:33 +01:00
Charles BochetandGitHub 7ff91a61c6 Add dashboard rollout commands (#15567)
## Tests

### makeSureDashboardNamingAvailableCommand

Case 1: no dashboard custom object
Case 2: with dashboard custom object

### SeedDashboardViewCommand

Case 1: no existing view
Case 2: with existing view
2025-11-03 18:35:57 +01:00
nitinandGitHub 5bc876e4b4 IFrame widget improvements (#15483)
changes - 
- make iframe side panel to match others -- ie use SidePanelHeader for
title
- make url optional in configuration to match that of the other widgets
(allow partial saves) - render No data status when error or no url
- split widget sizes into two -- graph widget sizes and widget sizes
(graph widgets are a subset of chart widgets)
2025-11-03 17:30:06 +00:00
902eb2c5d2 Instant widget placeholder placement on drag end (#15496)
closes -
https://discord.com/channels/1130383047699738754/1430596561137700957

fixed a bug - where on chart type change in side panel -- wont update
the widgets minimum size

---------

Co-authored-by: Raphaël Bosi <71827178+bosiraphael@users.noreply.github.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-03 17:08:13 +00:00
Thomas TrompetteandGitHub 9c695cfed5 Remove relations from manual trigger output schema (#15578)
Fixes https://github.com/twentyhq/twenty/issues/15319
Fixes https://github.com/twentyhq/twenty/issues/15255

On index page, we load record with only a few relation fields. So record
selected on manual trigger do not contain all the fields. To match that
behavior, let's remove relations from output schema. The user will do a
search on relation id if needed.
2025-11-03 16:54:13 +00:00
Raphaël BosiandGitHub 711cf819e9 Fix date granularity saving issue (#15579)
The date granularities were missing in the fragment
2025-11-03 16:53:44 +00:00
Lucas BordeauandGitHub b33b38cb02 Follow-up high fixes on date refactor (#15553)
This PR fixes important bugs on date filter handling following-up date
refactor.

Fixes : https://github.com/twentyhq/core-team-issues/issues/1814
2025-11-03 17:51:42 +01:00
nitinandGitHub bafc0496b1 add inner padding on bar chart (#15577)
before:

<img width="602" height="407" alt="CleanShot 2025-11-03 at 22 06 45"
src="https://github.com/user-attachments/assets/3553d3a0-2626-4f88-9adc-7d472fde2b26"
/>

after:

<img width="628" height="392" alt="CleanShot 2025-11-03 at 22 06 08"
src="https://github.com/user-attachments/assets/d5cf2b68-c5eb-4ce7-be27-c685ccd81109"
/>
2025-11-03 17:48:57 +01:00
a64d4dbe71 Various font styling fixes on chart (#15572)
- Fix axis legends styling
- Fix legends styling
- Fix tooltip legends

---------

Co-authored-by: ehconitin <nitinkoche03@gmail.com>
2025-11-03 16:43:28 +00:00
6675931100 i18n - translations (#15574)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-03 17:36:59 +01:00
Raphaël BosiandGitHub 4a87706d0b Fix chart filter settings back button behavior (#15573)
Before:


https://github.com/user-attachments/assets/23881978-3234-4a0b-95ec-15470d26026d


After:


https://github.com/user-attachments/assets/80d222f6-585a-4fff-8476-dae327e34699
2025-11-03 16:25:59 +00:00
Thomas TrompetteandGitHub d1330a4a8c Improve workflow performances (#15528)
- on draft creation, do not fetch the full version. Avoid the fetch of
steps and trigger
- on activation, we were performing 8 queries/mutations synchronously +
2 additional for automated triggers. I refacto the call it it gets
reduced to 4 queries/mutations + 2 additional for automated triggers
2025-11-03 17:23:01 +01:00
nitinGitHubgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
c2d8fd495a fix: trash button centering + gap between forbidden display and trashbutton (#15571)
<img width="247" height="73" alt="CleanShot 2025-11-03 at 21 24 18"
src="https://github.com/user-attachments/assets/c0287919-be18-4dfa-96b8-5bbdeaab6693"
/>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2025-11-03 16:21:17 +00:00
d72aae86cb Graph margins vary depending on presence of labels (#15559)
https://github.com/user-attachments/assets/3c27fa7b-78a3-49eb-9795-53571662cf12

---------

Co-authored-by: Raphaël Bosi <71827178+bosiraphael@users.noreply.github.com>
2025-11-03 17:06:41 +01:00
06feee91f0 i18n - translations (#15570)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-03 16:47:03 +01:00
Weiko 464f80ed9b fix front lint 2025-11-03 16:38:55 +01:00
454114932a fix: ai settings page crash (#15455)
Fixes - https://github.com/twentyhq/twenty/issues/14995

---------

Co-authored-by: prastoin <paul@twenty.com>
Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
2025-11-03 16:36:27 +01:00
WeikoandGitHub a5e53d74dc fix calendar view when switched from other layout type bis (#15569) 2025-11-03 16:35:30 +01:00
WeikoandGitHub 0b21ac7dd8 Add permission check on calendar view drag and add new (#15556)
## Context
If selected date field of the calendar view has readonly, we should not
allow users to drag/drop cards nor allow them to add a new record
(resulting in a permission error on the BE due to the FE updating the
said field)
2025-11-03 16:33:59 +01:00
Paul RastoinandGitHub 17acfe1d2a [REQUIRED_FOR_1_10] Fix kanban foreign key migration (#15557)
# Introduction
We introduced a foreign key addition that will fail in production due to
orphan views targetting non existing fields

## Migration
The migration will be run for any new workspace successfully or any
twenty instance without corrupted data

## Upgrade command
The upgrade command will at some point allow the migration to be run
manually after removing any corrupted data

## Release note
We should remove the migration we've manually set as being run in
production
2025-11-03 15:08:35 +00:00
Charles BochetandGitHub 20576f2ee7 Add Dashboard in Lab, make Calendar available out of lab (#15560)
As per title!
2025-11-03 15:40:26 +01:00
b32ab35db9 i18n - translations (#15563)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-03 15:32:38 +01:00
WeikoandGitHub 82ac642d73 Fix calendar view when switched from other layout type not updating state (#15562)
## Context
Switching from kanban layout to calendar was not displaying records
properly. Adding the missing state update (similar to kanban case a few
lines above)
2025-11-03 15:32:23 +01:00
Raphaël BosiandGitHub 1739ee0595 Add date granularity and timezone and first day of the week to graphs (#15543)
- Allow users to choose the date granularity of the x axis and the group
by of the y axis on a bar chart
- Display those options conditionally
- Store timezones in graphs: each graph has its own timezone, defaults
to the user timezone. There will be a picker in the v2 to choose the
timezone. For now the timezone is not used by the backend, but it will
be used in filters and in group by queries.
- Store first day of the week



https://github.com/user-attachments/assets/66a5d156-dd93-4ebe-8c8f-d172f93e25be
2025-11-03 15:27:47 +01:00
MarieandGitHub 0975b06a9b [demo] Allow workspace to work with a non-system workspaceMember object (#15547)
For demo purposes, we want to work with workspaceMember has a non-system
object, allowing it to be displayed on the product, to be added custom
fields etc.
It is something we may want to do later anyway. 
This PR adds a bypassPermissionChecks on workspaceMember repository
calls. This does not provide more permissions than before for other
workspaces: workspaceMember being a system object, permissions are
already bypassed for this one. (Note that actions such inviting a new
workspaceMember, updating a workspaceMember are protected by a system
permission checked in the relevant places).

This work does **not** allow any workspace to switch their
workspaceMember object to non-system, the switch is still manual.
2025-11-03 14:57:37 +01:00
9e1c854b27 fix: updated dryrun to return correct populated record (#15484)
## Description

- This PR approaches to solve
https://github.com/twentyhq/twenty/issues/15201
- updated `createDryRunResponse` to return fully populated merged record
- this way the frontend can render the populated data it as-is without
recomputing relations
- Dry-run now uses the same nested-relations population path as the
non-dryRun flow

---------

Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2025-11-03 13:50:14 +01:00
GuillimandGitHub 120cec9885 fix migration command - workflow runs (#15540)
fix migration command to enable the id addition in the fieldmetadata
options of workflow runs

Isues was on the workfluw rin (xurrently in produciton) if we filter by
status: clicking "Stopped" also selects "Stoppping" automatically.

<img width="735" height="436" alt="Screenshot 2025-11-03 at 12 26 40"
src="https://github.com/user-attachments/assets/20fd8b71-f7be-4115-acae-9b36f53e6d5f"
/>
2025-11-03 12:38:14 +01:00
Charles BochetandGitHub 50eb8c5558 Add command to make sure v1.8 workspaces are not using FULL or PARTIAL sync stages (that should be already deprecated) (#15545)
In v1.8, we have already run a command to deprecate FULL or PARTIAL sync
stages.

However the code was fully deprecated in v1.10 and some workspaces might
still have this status used. This is to double check
2025-11-03 12:36:46 +01:00
0480ea048c i18n - translations (#15542)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-03 12:01:05 +01:00
GuillimandGitHub 4f4a13edf5 switch migrationActionsWithParent to migrationActionsWithParentTmp temporary (#15478)
The removal of views from the workspaces schema implies the deletion of 
```
view
viewFilter
viewFilterGroup
viewGroup
viewSort
```
Before it is created again in the core schema.

However, the syncmetadata that executes the pending migration fails
because it will try to
`query failed: DROP TABLE "workspace_xxxx"."view"`
before the removal of the other view related tables that contains a view
foreign key with this kind of message
> constraint FK_c5ab40cd4debb51d588752a4857 on table "viewField" depends
on table view
2025-11-03 11:50:22 +01:00
3dac899741 i18n - translations (#15541)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-03 11:48:30 +01:00
Charles BochetandGitHub 08d475b229 Revert "fix: tmp allows arbitrary temporary file / directory write via symbolic link dir parameter" (#15539)
Reverts twentyhq/twenty#15452
2025-11-03 11:42:28 +01:00
5b2950c43a Introduce SSO bypass permission. (#15417)
Closes [Core Issue
#1772](https://github.com/twentyhq/core-team-issues/issues/1772).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Introduces SSO bypass with a new permission flag and workspace-level
provider toggles, enabling permitted users to log in via
Google/Microsoft/Password when SSO-only, with backend enforcement and
frontend UI/hooks/queries.
> 
> - **Backend**:
> - **Permission & Enforcement**: Add `PermissionFlagType.SSO_BYPASS`;
update `AuthService` to allow login via non-SSO providers when workspace
bypass is enabled and user has `SSO_BYPASS`.
> - **Workspace Model**: Add `isGoogleAuthBypassEnabled`,
`isMicrosoftAuthBypassEnabled`, `isPasswordAuthBypassEnabled`
(migration, entity, update input, service validation).
> - **Public API**: Extend `PublicWorkspaceDataOutput` with
`authBypassProviders`; resolver computes it; permissions defaults
include `SSO_BYPASS`.
> - **Frontend**:
> - **GraphQL/State**: Generate new types/fields; add
`authBypassProviders` to `GetPublicWorkspaceDataByDomain`; new states
`workspaceAuthBypassProvidersState`, `workspaceBypassModeState`.
> - **Auth UI/Logic**: Add `useWorkspaceBypass`; update sign-in form and
footer to offer "Bypass SSO" and use merged providers when enabled;
remove auto-redirect when single SSO.
> - **Settings**: Add Security section to toggle bypass methods per
provider; conditionally show Change Password via `useCanChangePassword`.
> - **Tests/Mocks**: Update mocks and tests to include bypass
flags/providers.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
8c393b2bad. 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-11-03 11:40:09 +01:00
604b3e50de i18n - translations (#15531)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-03 10:36:14 +01:00
e462f191d0 fix: tmp allows arbitrary temporary file / directory write via symbolic link dir parameter (#15452)
Resolves [Dependabot Alert
255](https://github.com/twentyhq/twenty/security/dependabot/255) - fix:
tmp allows arbitrary temporary file / directory write via symbolic link
`dir` parameter.

Updated the dev-dependency `zapier-platform-cli` for it to depend on tmp
0.2.4 and also ran `yarn up tmp --recursive` to update the version of
tmp elsewhere.

Not expecting any breaking changes to twenty-zapier since
`zapier-platform-cli` is marked as a development dependency.

Co-authored-by: martmull <martmull@hotmail.fr>
2025-11-03 10:17:08 +01:00
Félix MalfaitandGitHub 7c854ba816 Remove Hacktoberfest from README (#15530)
As per title
2025-11-03 10:03:03 +01:00
neo773andGitHub f9eb06f015 fix IMAP onboarding (#15444) 2025-11-02 13:33:03 +01:00
GuillimandGitHub 53bb534af8 MORPH for relationDecorator (#15420)
# Adding MORPH support  to the relationDecorator

Extends the @WorkspaceRelation decorator to support morph relations by
adding isMorphRelation and morphId options

The implementation enforces type safety through TypeScript discriminated
unions, ensuring morphId is required when isMorphRelation: true, and
includes runtime validation that throws a descriptive error if morphId
is missing.

The morph relation metadata is properly stored in metadataArgsStorage
and integrates seamlessly with the existing StandardFieldRelationFactory
to convert decorated fields into FieldMetadataType.MORPH_RELATION
entities with appropriate database constraints.



To test :
in person entity, add
```ts
  @WorkspaceRelation({
    standardId: PERSON_STANDARD_FIELD_IDS.testRelatedRecordCompany,
    type: RelationType.MANY_TO_ONE,
    label: msg`Test Related Record of Company`,
    description: msg`Test relation to company`,
    icon: 'IconLink',
    inverseSideTarget: () => CompanyWorkspaceEntity,
    inverseSideFieldKey: 'testRelatedPeople',
    onDelete: RelationOnDeleteAction.CASCADE,
    isMorphRelation: true,
    morphId: PERSON_STANDARD_FIELD_IDS.testRelatedRecordMorphId,
  })
  @WorkspaceIsNullable()
  @WorkspaceIsSystem()
  testRelatedRecordCompany: Relation<CompanyWorkspaceEntity> | null;

  @WorkspaceJoinColumn('testRelatedRecordCompany')
  testRelatedRecordCompanyId: string | null;

  @WorkspaceRelation({
    standardId: PERSON_STANDARD_FIELD_IDS.testRelatedRecordOpportunity,
    type: RelationType.MANY_TO_ONE,
    label: msg`Test Related Record of Opportunity`,
    description: msg`Test relation to opportunity`,
    icon: 'IconLink',
    inverseSideTarget: () => OpportunityWorkspaceEntity,
    inverseSideFieldKey: 'testRelatedPeople',
    onDelete: RelationOnDeleteAction.CASCADE,
    isMorphRelation: true,
    morphId: PERSON_STANDARD_FIELD_IDS.testRelatedRecordMorphId,
  })
  @WorkspaceIsNullable()
  @WorkspaceIsSystem()
  testRelatedRecordOpportunity: Relation<OpportunityWorkspaceEntity> | null;

  @WorkspaceJoinColumn('testRelatedRecordOpportunity')
  testRelatedRecordOpportunityId: string | null;
```

in opportunity,
```ts
@WorkspaceRelation({
    standardId: OPPORTUNITY_STANDARD_FIELD_IDS.testRelatedPeople,
    type: RelationType.ONE_TO_MANY,
    label: msg`Test Related People`,
    description: msg`People linked to the opportunity via Test Related Record`,
    icon: 'IconUsers',
    inverseSideTarget: () => PersonWorkspaceEntity,
    inverseSideFieldKey: 'testRelatedRecordOpportunity',
    onDelete: RelationOnDeleteAction.SET_NULL,
  })
  @WorkspaceIsNullable()
  @WorkspaceIsSystem()
  testRelatedPeople: Relation<PersonWorkspaceEntity[]>;
  ```

in company,
```ts
  @WorkspaceRelation({
    standardId: COMPANY_STANDARD_FIELD_IDS.testRelatedPeople,
    type: RelationType.ONE_TO_MANY,
    label: msg`Test Related People`,
description: msg`People linked to the company via Test Related Record`,
    icon: 'IconUsers',
    inverseSideTarget: () => PersonWorkspaceEntity,
    inverseSideFieldKey: 'testRelatedRecordCompany',
    onDelete: RelationOnDeleteAction.SET_NULL,
  })
  @WorkspaceIsNullable()
  @WorkspaceIsSystem()
  testRelatedPeople: Relation<PersonWorkspaceEntity[]>;
```

In constants/standard-field-ids.ts, add the standard fields ids
```ts
// COMPANY_STANDARD_FIELD_IDS
testRelatedPeople: '20202020-7a90-47e9-b31f-916a716fd212',

// OPPORTUNITY_STANDARD_FIELD_IDS
testRelatedPeople: '20202020-7a90-47e9-b31f-916a716fd213',

// PERSON_STANDARD_FIELD_IDS
testRelatedRecordOpportunity: '20202020-5a90-47e9-b31f-916a716fd211',
testRelatedRecordCompany: '20202020-1eb2-4298-910b-66b015b36d72',
testRelatedRecordMorphId: '20202020-6ccf-48e3-bb92-bc9961bc011e',
```
2025-11-02 13:31:48 +01:00
Charles BochetandGitHub 498d89633c Fix view favorite making the app crash (#15517)
On new workspaces, as they come without the "view" object which not part
of engine metadata, favorites pointing to views make the app crashes.

This fixes it
2025-11-01 20:05:17 +01:00
neo773andGitHub 44c0b9f94b refactor messaging error handling (#15416) 2025-11-01 20:03:41 +01:00
c42c2590de i18n - translations (#15516)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-11-01 18:45:55 +01:00
afeb505eed [Breaking Change] Implement reliable date picker utils to handle all timezone combinations (#15377)
This PR implements the necessary tools to have `react-datepicker`
calendar and our date picker components work reliably no matter the
timezone difference between the user execution environment and the user
application timezone.

Fixes https://github.com/twentyhq/core-team-issues/issues/1781

This PR won't cover everything needed to have Twenty handle timezone
properly, here is the follow-up issue :
https://github.com/twentyhq/core-team-issues/issues/1807

# Features in this PR

This PR brings a lot of features that have to be merged together.

- DATE field type is now handled as string only, because it shouldn't
involve timezone nor the JS Date object at all, since it is a day like a
birthday date, and not an absolute point in time.
- DATE_TIME field wasn't properly handled when the user settings
timezone was different from the system one
- A timezone abbreviation suffix has been added to most DATE_TIME
display component, only when the timezone is different from the system
one in the settings.
- A lot of bugs, small features and improvements have been made here :
https://github.com/twentyhq/core-team-issues/issues/1781

# Handling of timezones

## Essential concepts

This topic is so complex and easy to misunderstand that it is necessary
to define the precise terms and concepts first. It resembles character
encoding and should be treated with the same care.

- Wall-clock time : the time expressed in the timezone of a user, it is
distinct from the absolute point in time it points to, much like a
pointer being a different value than the value that it points to.
- Absolute time : a point in time, regardless of the timezone, it is an
objective point in time, of course it has to be expressed in a given
timezone, because we have to talk about when it is located in time
between humans, but it is in fact distinct from any wall clock time, it
exists in itself without any clock running on earth. However, by
convention the low-level way to store an absolute point in time is in
UTC, which is a timezone, because there is no way to store an absolute
point in time without a referential, much like a point in space cannot
be stored without a referential.
- DST : Daylight Save Time, makes the timezone shift in a specific
period every year in a given timezone, to make better use of longer days
for various reasons, not all timezones have DST. DST can be 1 hour or 30
min, 45 min, which makes computation difficult.
- UTC : It is NOT an “absolute timezone”, it is the wall-clock time at
0° longitude without DST, which is an arbitrary and shared human
convention. UTC is often used as the standard reference wall-clock time
for talking about absolute point in time without having to do timezone
and DST arithmetic. PostgreSQL stores everything in UTC by convention,
but outputs everything in the server’s SESSION TIMEZONE.

## How should an absolute point in time be stored ?

Since an absolute point in time is essentially distinct from its
timezone it could be stored in an absolute way, but in practice it is
impossible to store an absolute point in time without a referential. We
have to say that a rocket launched at X given time, in UTC, EST, CET,
etc. And of course, someone in China will say that it launched at 10:30,
while in San Francisco it will have launched at 19:30, but it is THE
SAME absolute point in time.

Let’s take a related example in computer science with character
encoding. If a text is stored without the associated encoding table, the
correct meaning associated to the bits stored in memory can be lost
forever. It can become impossible for a program to guess what encoding
table should be used for a given text stored as bits, thus the glitches
that appeared a lot back in the early days of internet and document
processing.

The same can happen with date time storing, if we don’t have the
timezone associated with the absolute point in time, the information of
when it absolutely happened is lost.

It is NOT necessary to store an absolute point in time in UTC, it is
more of a standard and practical wall-clock time to be associated with
an absolute point in time. But an absolute point in time MUST be store
with a timezone, with its time referential, otherwise the information of
when it absolutely happened is lost.

For example, it is easier to pass around a date as a string in UTC, like
`2024-01-02T00:00:00Z` because it allows front-end and back-end code to
“talk” in the same standard and DST-free wall-clock time, BUT it is not
necessary. Because we have date libraries that operate on the standard
ISO timezone tables, we can talk in different timezone and let the
libraries handle the conversion internally.

It is false to say that UTC is an absolute timezone or an absolute point
in time, it is just the standard, conventional time referential, because
one can perfectly store every absolute points in time in UTC+10 with a
complex DST table and have the exactly correct absolute points in time,
without any loss of information, without having any UTC+0 dates
involved.

Thus storing an absolute point in time without a timezone associated,
for example with `timestamp` PostgreSQL data type, is equivalent to
storing a wall-clock time and then throwing away voluntarily the
information that allows to know when it absolutely happened, which is a
voluntary data-loss if the code that stores and retrieves those
wall-clock points in time don’t store the associated timezone somewhere.

This is why we use `timestamptz` type in PostgreSQL, so that we make
sure that the correct absolute point in time is stored at the exact time
we send it to PostgreSQL server, no matter the front-end, back-end and
SQL server's timezone differences.

## The JavaScript Date object

The native JavaScript Date object is now officially considered legacy
([source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)),
the Date object stores an absolute point in time BUT it forces the
storage to use its execution environment timezone, and one CANNOT modify
this timezone, this is a legacy behavior.

To obtain the desired result and store an absolute point in time with an
arbitrary timezone there are several options :

- The new Temporal API that is the successor of the legacy Date object.
- Moment / Luxon / @date-fns/tz that expose objects that allow to use
any timezone to store an absolute point in time.

## How PostgreSQL stores absolute point in times

PostgreSQL stores absolute points in time internally in UTC
([source](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-INPUT-TIME-STAMPS)),
but the output date is expressed in the server’s session timezone
([source](https://www.postgresql.org/docs/current/sql-set.html)) which
can be different from UTC.

Example with the object companies in Twenty seed database, on a local
instance, with a new “datetime” custom column :

<img width="374" height="554" alt="image"
src="https://github.com/user-attachments/assets/4394cb43-d97e-4479-801d-ca068f800e39"
/>

<img width="516" height="524" alt="image"
src="https://github.com/user-attachments/assets/b652f36a-d2e2-47a4-8950-647ca688cbbd"
/>

## Why can’t I just use the JavaScript native Date object with some
manual logic ?

Because the JavaScript Date object does not allow to change its internal
timezone, the libraries that are based on it will behave on the
execution environment timezone, thus leading to bugs that appear only on
the computers of users in a timezone but not for other in another
timezone.

In our case the `react-datepicker` library forces to use the `Date`
object, thus forcing the calendar to behave in the execution environment
system timezone, which causes a lot of problems when we decide to
display the Twenty application DATE_TIME values in another timezone than
the user system one, the bugs that appear will be of the off-by-one date
class, for example clicking on 23 will select 24, thus creating an
unreliable feature for some system / application timezone combinations.

A solution could be to manually compute the difference of minutes
between the application user and the system timezones, but that’s not
reliable because of DST which makes this computation unreliable when DST
are applied at different period of the year for the two timezones.

## Why can’t I compute the timezone difference manually ?

Because of DST, the work to compute the timezone difference reliably,
not just for the usual happy path, is equivalent to developing the
internal mechanism of a date timezone library, which is equivalent to
use a library that handles timezones.

## Using `@date-fns/tz` to solve this problem

We could have used `luxon` but it has a heavy bundle size, so instead we
rely here on `@date-fns/tz` (~1kB) which gives us a `TZDate` object that
allows to use any given timezone to store an absolute point-in-time.

The solution here is to trick `react-datepicker` by shifting a Date
object by the difference of timezone between the user application
timezone and the system timezone.

Let’s take a concerte example.

System timezone : Midway,  ⇒ UTC-11:00, has no DST.

User application timezone : Auckland, NZ ⇒ UTC+13:00, has a DST.

We’ll take the NZ daylight time, so that will make a timezone difference
of 24 hours !

Let’s take an error-prone date : `2025-01-01T00:00:00` . This date is
usually a good test-case because it can generate three classes of bugs :
off-by-one day bugs, off-by-one month bugs and off-by-one year bugs, at
the same time.

Here is the absolute point in time we take expressed in the different
wall-clock time points we manipulate


Case | In system timezone ⇒ UTC-11 | In UTC | In user application
timezone ⇒ UTC+13
-- | -- | -- | --
Original date | `2024-12-31T00:00:00-11:00` | `2024-12-31T11:00:00Z` |
`2025-01-01T00:00:00+13:00`
Date shifted for react-datepicker | `2025-01-01T00:00:00-11:00` |
`2025-01-01T11:00:00Z` | `2025-01-02T00:00:00+13:00`

We can see with this table that we have the number part of the date that
is the same (`2025-01-01T00:00:00`) but with a different timezone to
“trick” `react-datepicker` and have it display the correct day in its
calendar.

You can find the code in the hooks
`useTurnPointInTimeIntoReactDatePickerShiftedDate` and
`useTurnReactDatePickerShiftedDateBackIntoPointInTime` that contain the
logic that produces the above table internally.

## Miscellaneous

Removed FormDateFieldInput and FormDateTimeFieldInput stories as they do
not behave the same depending of the execution environment and it would
be easier to put them back after having refactored FormDateFieldInput
and FormDateTimeFieldInput

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-11-01 18:31:24 +01:00
EtienneandGitHub 3a203040f7 Fix - Multiple banners issue (#15506)
Done : 
- Fix multiple banners issue
- Lift impersonation banner


After 
<img width="800" height="400" alt="Screenshot 2025-10-31 at 18 05 02"
src="https://github.com/user-attachments/assets/7d5949d4-1c8b-4a4f-91c1-c115e53436fb"
/>
2025-10-31 19:17:31 +01:00
Baptiste DevessierandGitHub 5f0d24798a Support workflows in record page layouts (#15471)
https://github.com/user-attachments/assets/275a02a3-7054-45d1-9423-75bb5223a8ba
2025-10-31 18:45:58 +01:00
WeikoandGitHub 09c704c8bd Add useGroupBy hook + update calendar view to use groupBy (#15439)
## Context
Took inspiration from findMany + kanban => Implemented a hook for the
new groupBy API endpoints
Fixed an issue when DnD to an empty day
2025-10-31 18:39:22 +01:00
Raphaël BosiandGitHub bb471cb8a5 Bar chart: Prevent left tick labels to overlap on label (#15499)
Prevent left tick labels to overlap on label by truncating the tick
label
2025-10-31 22:50:22 +05:30
cd4a151a21 i18n - translations (#15504)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-10-31 17:47:12 +01:00
Thomas TrompetteandGitHub 71e7063fc4 Move http node to backend (#15424)
Fixes https://github.com/twentyhq/twenty/issues/14491

Also adding an url validator.
2025-10-31 17:46:58 +01:00
Abdul RahmanandGitHub 9f97be67b1 Migrate documentation to Mintlify and configure 301 redirects (#15502)
## Summary
Completes the migration of all documentation from twenty-website to a
new Mintlify-powered documentation site at docs.twenty.com.

## Changes Made

### New Package: `twenty-docs`
-  Created new Mintlify documentation package
-  Migrated 95 content pages (user-guide, developers, twenty-ui)
-  Migrated 81 images
-  Converted all custom components to Mintlify native components
-  Configured navigation with 2 tabs and 94 pages
-  Added Helper AI Agent with searchArticles tool for docs search

### Updated: `twenty-website`
-  Added 11 redirect rules (301 permanent) in next.config.js
-  Removed all documentation content (111 files)
-  Removed documentation routes (user-guide, developers, twenty-ui)
-  Removed documentation components (9 files)
-  Updated keystatic.config.ts
-  Preserved all marketing/release pages

### Updated: Core Files
-  Updated README.md - docs links point to docs.twenty.com
-  Updated CONTRIBUTING.md - code quality link updated
-  Updated SupportDropdown.tsx - user guide link updated
-  Updated Footer.tsx - user guide link updated
2025-10-31 17:44:14 +01:00
Thomas TrompetteandGitHub 5f13e6fcf4 Put delete button on step footer + add unique fields on upsert action (#15497)
<img width="491" height="823" alt="Capture d’écran 2025-10-31 à 14 54
38"
src="https://github.com/user-attachments/assets/8058a6a3-8a6c-4cdd-93d9-2af71208dc5a"
/>
2025-10-31 16:39:45 +00:00
Paul RastoinandGitHub d640b93096 Improve v2 and cache invalidation perfs (#15467)
# Introduction
Log are debug logs of
`packages/twenty-server/test/integration/metadata/suites/object-metadata/create-delete-and-create-object-metadata-v2.integration-spec.ts`run
ten times in a row on clean db reset

## Next
Will improve cache computation to lighter invalidation.
RelationLoad `query` does not seem to work with typeorm so I'll continue
the custom integration i've started in
https://github.com/twentyhq/twenty/tree/optimize-cache-read-v2

## Integration tests duration
Significant test duration improvement too
### Before
<img width="2632" height="1402" alt="image"
src="https://github.com/user-attachments/assets/2f1f0ccf-44de-4856-bfe1-4f45a351763a"
/>

### After
<img width="2632" height="1402" alt="image"
src="https://github.com/user-attachments/assets/4bc9e6db-3046-48b9-b903-1464053936c4"
/>


## What's next
- The legacy cache invalidation removal
- Factorizing redis calls in only one operation

## Autogenerated performance comparison ( including mutation refactor
too )

[Before](https://gist.github.com/prastoin/3c1e21fa9e3b3ce4b0716902ff4a2dd6)

[After](https://gist.github.com/prastoin/7bfddd14bfded2e4991a9378970a026d)

The optimized implementation shows **dramatic performance improvements**
across all metrics:

- 🚀 **Cache Invalidation**: 156.3ms → 76.8ms (**50.9% faster**)
- 🚀 **Builder Operations**: 21.3ms → 14.2ms (**33.3% faster**)
-  **Consistency**: 16.4% more predictable performance

---

## 1. Overall Performance Summary

| Component | Before (avg) | After (avg) | Best (After) | Worst (After)
| Improvement |

|-----------|-------------|-------------|--------------|---------------|-------------|
| **Total Execution Time** | 180.2ms | 110.5ms | 52.3ms | 585.9ms |
**38.7% faster**  |
| **Cache Invalidation** | 156.3ms | 76.8ms | 47.8ms | 285.1ms | **50.9%
faster**  |
| **Transaction Execution** | 22.4ms | 22.1ms | 0.99ms | 314.2ms |
Similar |
| **Initial Cache Retrieval** | 0.81ms | 2.08ms | 0.21ms | 8.24ms |
Similar |
| **Entity Builder (total)** | 21.3ms | 14.2ms | 0.36ms | 42.5ms |
**33.3% faster**  |

### Total Execution Time Distribution

#### Before (Legacy Sequential)
```
Time (ms)    Count  Percentage  Visualization
< 150         18      16%       ████
150-180       32      29%       ███████
180-210       35      32%       ████████
210-250       17      15%       ████
250-350        6       5%       █
> 350          2       2%       ▌
```

#### After (Optimized Parallel)
```
Time (ms)    Count  Percentage  Visualization
< 70          28      31%       ████████
70-100        31      34%       █████████
100-150       18      20%       █████
150-200        8       9%       ██
200-300        4       4%       █
> 300          2       2%       ▌
```
---

## 2. Builder Performance Breakdown

### Field Metadata Builder

| Operation | Before (avg) | After (avg) | Improvement |
|-----------|-------------|-------------|-------------|
| Matrix computation | 3.5ms | 3.4ms | Similar |
| Creation validation | 15.2ms | 2.1ms | **86% faster**  |
| Deletion validation | 0.08ms | 0.06ms | Similar |
| Update validation | 1.3ms | 0.09ms | **93% faster**  |
| Entity processing | 18.6ms | 11.8ms | **37% faster**  |
| **Total validateAndBuild** | **21.3ms** | **14.2ms** | **33% faster**
 |

#### Performance Distribution
```
Before:  ▁▂▄█████▆▄▂▁     (wide spread, 15-28ms range)
After:   ▁▁▃█████▃▁▁       (tight clustering, 10-18ms range)
```

## 4. Cache Invalidation Performance Breakdown

### Cache Invalidation Summary

| Metric | Before (Legacy) | After (Optimized) | Improvement |
|--------|-----------------|-------------------|-------------|
| **Best Time** | 131.965ms | 47.833ms | **63.7% faster**  |
| **10th Percentile** | 140.2ms | 51.7ms | **63.1% faster**  |
| **25th Percentile** | 146.1ms | 54.4ms | **62.7% faster**  |
| **Median (50th)** | 155.1ms | 63.4ms | **59.1% faster**  |
| **Average** | 156.3ms | 76.8ms | **50.9% faster**  |
| **75th Percentile** | 160.2ms | 90.2ms | **43.7% faster**  |
| **90th Percentile** | 191.7ms | 100.2ms | **47.7% faster**  |
| **95th Percentile** | 235.6ms | 110.3ms | **53.2% faster**  |
| **99th Percentile** | 278.2ms | 224.9ms | **19.1% faster**  |
| **Worst Time** | 383.914ms | 285.102ms | **25.7% faster**  |

### Cache Invalidation Time Distribution

#### Before (Legacy Sequential)
```
Time (ms)    Count  Percentage  Visualization
130-140       3       3%        ▊
140-150      15      14%        ████
150-160      48      44%        ███████████
160-180      31      28%        ███████
180-220       8       7%        ██
220-280       3       3%        ▊
> 280         2       2%        ▌
```

#### After (Optimized Parallel + Intersection)
```
Time (ms)    Count  Percentage  Visualization
< 50          3       3%        ▊
50-60        27      25%        ███████
60-70        25      23%        ██████
70-90        25      23%        ██████
90-100       15      14%        ████
100-120       8       7%        ██
120-150       3       3%        ▊
> 150         4       4%        █
```

## 6. Performance Consistency Analysis

### Standard Deviation & Variance

| Metric | Before | After | Improvement |
|--------|--------|-------|-------------|
| **Cache Invalidation Std Dev** | 42.1ms | 35.2ms | **16.4% more
consistent**  |
| **Total Execution Std Dev** | 68.3ms | 89.1ms | Slightly more variable
|
| **Coefficient of Variation (Cache)** | 26.9% | 45.8% | More variance |
| **Outliers (> 2σ)** | 5 cases | 3 cases | **40% fewer outliers**  |

---
2025-10-31 16:20:51 +00:00
Raphaël BosiandGitHub 2d1a89c4c2 Update minimum chart sizes (#15500)
Update minimum chart sizes
2025-10-31 21:29:04 +05:30
MarieandGitHub bcdc07273e Fix orderBy, groupBy, and orderByForRecords on foreignKey (#15480)
For the variables orderBy (for findMany and groupBy), groupBy (for
groupBy) and orderByForRecords (for groupBy), we were wrongfully adding
the foreign key field (eg: pointOfContact) by its joinColumnName (eg:
pointOfContactId) as the variable key (eg. `orderBy: { pointOfContactId:
"AscNullsFirst" } }`. That broke because then this key is used to
identify the field in the parsers.

This went unnoticed because this order / group option is not very
interesting as it is limited to the id for now, but it s still better to
have it work than crash!

before (on findMany)
<img width="1841" height="674" alt="flawn_order_by_pocId"
src="https://github.com/user-attachments/assets/3ccd7604-041d-4b7e-8b6a-c1d268440a45"
/>

after (on findMany)
<img width="1182" height="805" alt="image"
src="https://github.com/user-attachments/assets/e9253683-bcbe-429e-bbef-e334c7cc76af"
/>
2025-10-31 15:13:49 +01:00
Abdullah.andGitHub 4224a46854 fix: regular expression denial of service (ReDoS) in cross-spawn (#15495)
Resolves [Dependabot Alert
#161](https://github.com/twentyhq/twenty/security/dependabot/161) -
regular expression denial of service (ReDoS) in cross-spawn.

Ran `yarn up cross-spawn --recursive` to move the version of cross-spawn
used from 7.0.3 to 7.0.6.
2025-10-31 15:06:31 +01:00
nitinandGitHub 809791a4a8 fix: Orderby secondary dimension sum (#15493)
before:


https://github.com/user-attachments/assets/6919c45b-1435-408f-87e3-0452dd70fbdb

after:


https://github.com/user-attachments/assets/efa60d28-ac04-4219-831a-92aada13fa9c
2025-10-31 13:54:13 +01:00
3d21ffb4d1 i18n - translations (#15494)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-10-31 13:01:39 +01:00
Raphaël BosiandGitHub cf382ccdd9 Fix maximum number of bars for stacked bars (#15481)
The maximum number of bars feature has been implemented before the
stacked bar one, so it didn't support it.
Now, the same number of bars is displayed with and without group by when
we are in stacked mode.
2025-10-31 17:25:47 +05:30
nitinandGitHub 1b02bc7cc4 remove values/formatted values from chart legends (#15490)
before:

<img width="639" height="385" alt="Screenshot 2025-10-31 at 15 29 01"
src="https://github.com/user-attachments/assets/5769a160-205d-4a03-ab7b-e037c65dd743"
/>


after:

<img width="667" height="371" alt="Screenshot 2025-10-31 at 15 27 51"
src="https://github.com/user-attachments/assets/12a4e034-6262-43a9-b257-894d74462d73"
/>
2025-10-31 17:18:55 +05:30
Ranjeet BaraikandGitHub 6ed1fd841d fix: composite field label retrieval in spreadsheet import utility (#15489)
Fixes - https://github.com/twentyhq/twenty/issues/15368

Seems like the sub field was not being used for the actual label lookup
part

<img width="1302" height="354" alt="image"
src="https://github.com/user-attachments/assets/444f76be-117b-4b8b-91fe-dedd293e09af"
/>
2025-10-31 11:39:39 +01:00
nitinandGitHub d6bfbcc5ab add max widths on bars (#15487)
closes
https://discord.com/channels/1130383047699738754/1433444230176440560
before:


https://github.com/user-attachments/assets/db93c705-7c0a-407b-99d8-ecf8fd9eac1b


after:


https://github.com/user-attachments/assets/cb2a5e74-ea41-4381-9fbc-04efee12a50e
2025-10-31 11:15:53 +01:00
Abdul RahmanandGitHub 2c39fc04c2 feat: Migrate documentation to Mintlify and implement Helper Agent with search functionality (#15443) 2025-10-31 10:17:54 +01:00
nitinandGitHub 5211d6ac7e fix: make $groupBy parameter required in group-by queries (#15485)
before:

<img width="953" height="692" alt="Screenshot 2025-10-31 at 12 16 22"
src="https://github.com/user-attachments/assets/d2ec2a49-256d-4f17-baa7-6fb541e6e691"
/>

after:

<img width="960" height="718" alt="Screenshot 2025-10-31 at 12 16 34"
src="https://github.com/user-attachments/assets/39843363-8f77-40cc-8203-ed9895efa57e"
/>
2025-10-31 14:10:01 +05:30
769ce95cde Data labels improvements (#15475)
Create custom total component and display the total instead of each
group separately



https://github.com/user-attachments/assets/4e3edde8-9675-4bb1-834a-98dbff016063



https://github.com/user-attachments/assets/294555cc-a64b-4148-b1b9-f1dc0f0322ae

---------

Co-authored-by: ehconitin <nitinkoche03@gmail.com>
2025-10-30 23:47:37 +05:30
nitinandGitHub 4c35cf305f Add support for negative bars on bar chart (#15418)
in app:

<img width="580" height="591" alt="Screenshot 2025-10-29 at 01 47 51"
src="https://github.com/user-attachments/assets/9e16a597-6367-454d-a726-668beac90e04"
/>

<img width="747" height="582" alt="Screenshot 2025-10-29 at 02 30 15"
src="https://github.com/user-attachments/assets/d06eb443-16ac-4394-bf4f-e6063f1ac12f"
/>

new stories: 

<img width="569" height="359" alt="Screenshot 2025-10-29 at 01 46 50"
src="https://github.com/user-attachments/assets/a4cd33e2-3f15-4b8d-8849-c2d990246dec"
/>
<img width="564" height="360" alt="Screenshot 2025-10-29 at 01 46 45"
src="https://github.com/user-attachments/assets/014a2110-53e4-4f99-afda-1d8c5412a815"
/>
<img width="604" height="372" alt="Screenshot 2025-10-29 at 01 46 40"
src="https://github.com/user-attachments/assets/bf7a73b4-fe29-40b7-b1a0-2894d5cbeccf"
/>
<img width="635" height="395" alt="Screenshot 2025-10-29 at 01 46 34"
src="https://github.com/user-attachments/assets/3cdfd3b9-dc76-4cf2-98e5-8e2a74e02ac6"
/>
<img width="652" height="408" alt="Screenshot 2025-10-29 at 01 46 30"
src="https://github.com/user-attachments/assets/c2837d8d-371f-44ac-b66b-8f41ba69245e"
/>
2025-10-30 17:40:34 +01:00
0cbd1e8ec5 fix: login redirection to active objects (#15366)
Fixes - https://github.com/twentyhq/twenty/issues/15364

- Removed `activeNonSystemObjectMetadataItems` from the hook as it was
not necessary. Hook use `alphaSortedActiveNonSystemObjectMetadataItems`
now.
- Correctly check for read permissions.

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2025-10-30 17:31:26 +01:00
Baptiste DevessierandGitHub 51fdaf2731 Some fixes for colors (#15479)
Please note the background colors of the tags and of the nodes

## Before

<img width="3456" height="2161" alt="CleanShot 2025-10-30 at 16 03
21@2x"
src="https://github.com/user-attachments/assets/09cbd1bd-26e2-4e05-88bc-f7d96de8a004"
/>

## After

<img width="3456" height="2160" alt="CleanShot 2025-10-30 at 17 03
25@2x"
src="https://github.com/user-attachments/assets/dc4fe113-1489-4476-a8b6-4cb446addcd5"
/>
2025-10-30 16:23:22 +00:00
Paul RastoinandGitHub a16fcebe67 Activate v2 for new workspaces (#15472) 2025-10-30 17:14:14 +01:00
428822f52d i18n - translations (#15477)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2025-10-30 16:35:23 +01:00
ab0cb67686 Render depends on menu items conditionally in chart settings + fix min max values (#15391)
closes
https://discord.com/channels/1130383047699738754/1430894689317294152

---------

Co-authored-by: Lucas Bordeau <bordeau.lucas@gmail.com>
Co-authored-by: Raphaël Bosi <71827178+bosiraphael@users.noreply.github.com>
2025-10-30 20:56:37 +05:30
nitinandGitHub 2510cbf614 Add lock on dashboard restricted charts (#15476)
closes
https://discord.com/channels/1130383047699738754/1433452994132840478
2025-10-30 14:59:34 +00:00
nitinandGitHub 33eaa4f2a2 Fix bar chart X-axis labels when groupBy matches aggregate field (#15473)
closes -
https://discord.com/channels/1130383047699738754/1430899754728030309
2025-10-30 15:53:17 +01:00
nitinandGitHub abcc891aed overflown tabs should be selected upon clicking edit right button (#15469)
as per title
2025-10-30 19:23:00 +05:30
26039d491f i18n - translations (#15468)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-10-30 14:38:52 +01:00
nitinandGitHub 28333815d5 update chart tooltip designs (#15426)
closes
https://discord.com/channels/1130383047699738754/1430845815634657320

~~TODO: add truncation~~
2025-10-30 19:07:59 +05:30
EtienneandGitHub 2461296158 Common - fixes (#15463)
Fixes https://github.com/twentyhq/twenty/issues/15435
Fixes https://github.com/twentyhq/private-issues/issues/338
Fixes https://github.com/twentyhq/twenty/issues/15457
2025-10-30 14:29:57 +01:00
d6d9ebf6eb i18n - translations (#15466)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-10-30 14:23:40 +01:00
nitinandGitHub 369b1b19af Tabs sidepanel settings on dashboards (#15454)
question -- should we have confirmation modal on delete -- if yes --
should it appear on save -- or on delete?
figma -
https://www.figma.com/design/xt8O9mFeLl46C5InWwoMrN/Twenty?node-id=79469-817497&t=5gFTRiI5f8nPyzc6-0
Note - Figma has a new side panel header, which is unavailable for now,
so I used the existing one

In a follow-up, we could even have icons for tabs -- would be cool --
and an icon picker for the icons?

followups which could be addressed in separate PRs - 
- ~~tabs being edited state (select state?) -- this would have blue
border around tab~~ done
- add icons on tabs -- need to update the entity to add icon -- and set
a default (dashboard) -- at least
- icon picker in the sidepanel header

closes -
https://discord.com/channels/1130383047699738754/1430204556884836532

video QA





https://github.com/user-attachments/assets/a4ad4b93-911d-46ce-9b68-347fd48fe933
2025-10-30 18:45:31 +05:30
Abdullah.andGitHub f367bd6072 fix: vite related dependabot alerts (#15464)
Resolves [14 Dependabot
Alerts](https://github.com/twentyhq/twenty/security/dependabot?q=is%3Aopen+package%3Avite+manifest%3Ayarn.lock+has%3Apatch)
simultaneously.

Vitest 1.4.0 was imported in root package.json, which further imported
Vite 5. However, Vitest solved no purpose at the moment since we still
rely on Jest for testing. Therefore, removed the package and we can
import the latest 4x version when we move from Jest to Vitest.

For the rest of the use-cases of Vite, ran `yarn up vite --recursive`
for the version used to be greater than 7.0.8.

<p align="center">
<img width="403" height="132" alt="image"
src="https://github.com/user-attachments/assets/a4ff7a75-2e3f-4dea-9f40-9cfdf07d6252"
/>
</p>
2025-10-30 14:00:28 +01:00
Charles BochetandGitHub eba3b0ca88 Simplify Code on FetchMore (#15465)
Simplifying a bit more fetchMore / lazyQuery api
2025-10-30 13:36:30 +01:00
Thomas TrompetteandGitHub a82b74c1ff Make upsert action body common with create record instead of update record (#15442)
We do not want the fields to update multiselect for upsert record
action. We want all available fields displayed by default.
This makes upsert record action closer to create record than update
record.

This PR: 
- deletes WorkflowUpdateRecordBody that was common between update and
upsert and put back content into update
- creates WorkflowCreateRecordBody that is now common between create and
upsert
- simplifies shouldDisplayFormField

Before - using fields to update as update record action
<img width="546" height="823" alt="Capture d’écran 2025-10-30 à 10 00
24"
src="https://github.com/user-attachments/assets/9206bc8b-75c2-40fa-a8de-e708b6b2cd05"
/>

After - displaying all fields as create record action
<img width="546" height="823" alt="Capture d’écran 2025-10-30 à 10 00
04"
src="https://github.com/user-attachments/assets/87141a47-946f-4604-be55-f4c21ff4a3d8"
/>
2025-10-30 13:36:16 +01:00
martmullandGitHub 8edb2c5520 Stop using .env variables to authenticate with cli (#15461)
- as title, solves our user facing authentication issues using the
twenty-cli
- update twenty-cli version (breaking change from previous PR)
2025-10-30 11:18:25 +00:00
65a329e900 Fix grip size on widgets (#15460)
Fix grip size on widgets

---------

Co-authored-by: ehconitin <nitinkoche03@gmail.com>
2025-10-30 11:38:02 +01:00
1929605fd9 fix: password reset redirection (#15421)
Fixes - https://github.com/twentyhq/twenty/issues/15131

Replace navigate with redirect in PasswordReset component to prevent
race conditions

---------

Co-authored-by: Etienne <45695613+etiennejouan@users.noreply.github.com>
2025-10-30 10:24:06 +00:00
MarieandGitHub 1ad8c05fbc groupBy fix + typeMapper fix (#15433)
groupBy fix: when a group's dimension value is NULL, we need to adapt
the raw sql (stage: NULL -> stage IS NULL)

typeMapper fix: a graphql type should be made non-nullable if was
indicated so + does not have a default value. our check on not having a
default value was limited to having a null defaultValue instead of
having a null or undefined defaultValue. This is a breaking change, but
all the queries that were providing a null value for these args were not
functioning anyway, and luckily in the FE we declared all queries adding
a `!` already.
2025-10-30 10:14:56 +00:00
Raphaël BosiandGitHub 19ea9fff97 Set default graph axis display to NONE (#15459)
Set default graph axis display to NONE
2025-10-30 10:14:25 +00:00
WeikoandGitHub 736fac021d Add contextMenu actions to calendar view (#15451)
<img width="432" height="307" alt="Screenshot 2025-10-29 at 19 31 38"
src="https://github.com/user-attachments/assets/61965305-3a20-46de-b47f-7ac78cb1228c"
/>
2025-10-30 10:59:11 +01:00
Abdullah.andGitHub 3401216cc8 fix: validator.js has a URL validation bypass vulnerability in its isURL function. (#15437)
Resolves [Dependabot Alert
299](https://github.com/twentyhq/twenty/security/dependabot/299) -
validator has a URL validation bypass vulnerability in its isURL
function.

Used `yarn up validator --recursive` to update the version in yarn.lock
file.
2025-10-29 20:34:59 +01:00
Abdullah.andGitHub 9a0ce141d4 chore: next.js may leak x-middleware-subrequest-id to external hosts. (#15438)
Resolves [Dependabot Alert
298](https://github.com/twentyhq/twenty/security/dependabot/298) -
next.js may leak x-middleware-subrequest-id to external hosts.

Updated the version of react-email used to update the version of
Next.js.
2025-10-29 20:34:14 +01:00
Abdullah.andGitHub f2d9262e6a fix: on-headers is vulnerable to http response header manipulation (#15453)
Resolves [Dependabot Alert
245](https://github.com/twentyhq/twenty/security/dependabot/245) -
on-headers is vulnerable to http response header manipulation.

Updated the version of express-session from `1.18.1` to `1.18.2`.
2025-10-29 20:32:15 +01:00
Raphaël BosiandGitHub 198bf5a333 Complete color refactoring (#15414)
# Complete color refactoring

Closes https://github.com/twentyhq/core-team-issues/issues/1779

- Updated all colors to use Radix colors with P3 color space allowing
for brighter colors
- Created our own gray scale interpolated on Radix's scale to have the
same values for grays as the old ones in the app
- Introduced dark and light colors as well as there transparent versions
- Added many new colors from radix that can be used in the tags or in
the graphs
- Updated multiple color utilities to match new behaviors
- Changed the computation of Avatar colors to return only colors from
the theme (before it was random hsl)

These changes allow the user to use new colors in tags or charts, the
colors are brighter and with better contrast. We have a full range of
color variations from 1 to 12 where before we only had 4 adaptative
colors.
All these changes will allow us to develop custom themes for the user
soon, where users can choose their accent colors, background colors and
there contrast.
2025-10-29 18:08:51 +00:00
Paul RastoinandGitHub f6f52d676f Explicitly set workspaceId column as uuid type to ease pg LEFT JOIN (#15430)
Pg scan was redundant because historically the workspaceId was
`varchar`, even though below migration won't change that we had a look
to workspaceId col declaration across the codebase
2025-10-29 19:08:44 +01:00
WeikoandGitHub 33545a072c Fix creating kanban view when no select field (#15441)
Adding an early return when no select field exists and you are
redirected to the setting page otherwise it tries to call
setAndPersistViewType with kanban and fails with "No fields for kanban -
should not happen"
2025-10-29 19:04:18 +01:00
martmullandGitHub a6cc80eedd 1751 extensibility twenty sdk v2 use twenty sdk to define a serverless function trigger (#15347)
This PR adds 2 columns handlerPath and handlerName in serverlessFunction
to locate the entrypoint of a serverless in a codebase

It adds the following decorators in twenty-sdk:
- ServerlessFunction
- DatabaseEventTrigger
- RouteTrigger
- CronTrigger
- ApplicationVariable

It still supports deprecated entity.manifest.jsonc 

Overall code needs to be cleaned a little bit, but it should work
properly so you can try to test if the DEVX fits your needs

See updates in hello-world application

```typescript
import axios from 'axios';
import {
  DatabaseEventTrigger,
  ServerlessFunction,
  RouteTrigger,
  CronTrigger,
  ApplicationVariable,
} from 'twenty-sdk';

@ApplicationVariable({
  universalIdentifier: 'dedc53eb-9c12-4fe2-ba86-4a2add19d305',
  key: 'TWENTY_API_KEY',
  description: 'Twenty API Key',
  isSecret: true,
})
@DatabaseEventTrigger({
  universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
  eventName: 'person.created',
})
@RouteTrigger({
  universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
  path: '/post-card/create',
  httpMethod: 'GET',
  isAuthRequired: false,
})
@CronTrigger({
  universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
  pattern: '0 0 1 1 *', // Every year 1st of January
})
@ServerlessFunction({
  universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
})
class CreateNewPostCard {
  main = async (params: { recipient: string }): Promise<string> => {
    const { recipient } = params;

    const options = {
      method: 'POST',
      url: 'http://localhost:3000/rest/postCards',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
      },
      data: { name: recipient ?? 'Unknown' },
    };

    try {
      const { data } = await axios.request(options);

      console.log(`New post card to "${recipient}" created`);

      return data;
    } catch (error) {
      console.error(error);
      throw error;
    }
  };
}

export const createNewPostCardHandler = new CreateNewPostCard().main;

```


### [edit] V2 

After the v1 proposal, I see that using a class method to define the
serverless function handler is pretty confusing. Lets leave
serverlessFunction configuration decorators on the class, but move the
handler like before. Here is the v2 hello-world serverless function:

```typescript
import axios from 'axios';
import {
  DatabaseEventTrigger,
  ServerlessFunction,
  RouteTrigger,
  CronTrigger,
  ApplicationVariable,
} from 'twenty-sdk';

@ApplicationVariable({
  universalIdentifier: 'dedc53eb-9c12-4fe2-ba86-4a2add19d305',
  key: 'TWENTY_API_KEY',
  description: 'Twenty API Key',
  isSecret: true,
})
@DatabaseEventTrigger({
  universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
  eventName: 'person.created',
})
@RouteTrigger({
  universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
  path: '/post-card/create',
  httpMethod: 'GET',
  isAuthRequired: false,
})
@CronTrigger({
  universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
  pattern: '0 0 1 1 *', // Every year 1st of January
})
@ServerlessFunction({
  universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
})
export class ServerlessFunctionDefinition {}

export const main = async (params: { recipient: string }): Promise<string> => {
  const { recipient } = params;

  const options = {
    method: 'POST',
    url: 'http://localhost:3000/rest/postCards',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
    },
    data: { name: recipient ?? 'Unknown' },
  };

  try {
    const { data } = await axios.request(options);

    console.log(`New post card to "${recipient}" created`);

    return data;
  } catch (error) {
    console.error(error);
    throw error;
  }
};

```


### [edit] V3

After the v2 proposal, we don't really like decorators on empty classes.
We decided to go with a Vercel approach with a config constant

```typescript
import axios from 'axios';
import { ServerlessFunctionConfig } from 'twenty-sdk';

export const main = async (params: { recipient: string }): Promise<string> => {
  const { recipient } = params;

  const options = {
    method: 'POST',
    url: 'http://localhost:3000/rest/postCards',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
    },
    data: { name: recipient ?? 'Unknown' },
  };

  try {
    const { data } = await axios.request(options);

    console.log(`New post card to "${recipient}" created`);

    return data;
  } catch (error) {
    console.error(error);
    throw error;
  }
};

export const config: ServerlessFunctionConfig = {
  universalIdentifier: 'e56d363b-0bdc-4d8a-a393-6f0d1c75bdcf',
  routeTriggers: [
  {
    universalIdentifier: 'c9f84c8d-b26d-40d1-95dd-4f834ae5a2c6',
    path: '/post-card/create',
    httpMethod: 'GET',
    isAuthRequired: false,
  }
  ],
  cronTriggers: [
    {
      universalIdentifier: 'dd802808-0695-49e1-98c9-d5c9e2704ce2',
      pattern: '0 0 1 1 *', // Every year 1st of January
    }
  ],
  databaseEventTriggers: [
  {
    universalIdentifier: '203f1df3-4a82-4d06-a001-b8cf22a31156',
    eventName: 'person.created',
   }
  ]
}

```
2025-10-29 16:51:43 +00:00
Thomas TrompetteandGitHub 75ed5cb3a2 Fix email editor-email discrepancies (#15436)
Fix https://github.com/twentyhq/twenty/issues/15346

- email not centered
- reduced title sizes
- made paragraph line height and margin consistent with editor
- display line jumps

Editor
<img width="1505" height="701" alt="Capture d’écran 2025-10-29 à 16 46
20"
src="https://github.com/user-attachments/assets/5f6c6377-62b2-4697-861e-39a648cd48bb"
/>

Email
<img width="1505" height="648" alt="Capture d’écran 2025-10-29 à 16 46
36"
src="https://github.com/user-attachments/assets/a596acd8-567f-4726-996c-248519b250c5"
/>
2025-10-29 16:10:21 +00:00
Harshit SinghandGitHub be3ceca0a3 Add listkit to tiptap extension in workflow node (#15363)
## Description

- This PR address issue -
https://github.com/twentyhq/core-team-issues/issues/1768
- Added listkit bundle from tiptap which includes BulletList,
orderedList, ListItem and ListKeymap in one single import
- This bundle also includes keyboards shortcuts - `Cmd + Shift + 7` and
`Cmd + Shift + 8` for ordered and bullet list

## Visual Appearance



https://github.com/user-attachments/assets/7eff1233-8503-4854-bad2-2521898bc568


## Why this Approach

- our current version of tiptap is 3.4.2 while the latest is 3.8.0 hence
installing these versions manually would install the latest version of
3.8.0. The issue when downgrading to 3.4.2 was that Version 3.8.0 of
`@tiptap/extension-list` requires `renderNestedMarkdownContent` from
@tiptap/core
but our `@tiptap/core` version 3.4.2 doesn't export this function.
2025-10-29 16:01:54 +01:00
Paul RastoinandGitHub 0070fc10f8 Debug sentry redis integration (#15431) 2025-10-29 15:34:47 +01:00
8f009e66f1 i18n - translations (#15432)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-10-29 15:20:58 +01:00
Paul RastoinandGitHub c19a799973 Fix view rest api in v2 (#15398)
# Introduction
Initially wanted to reactive the test introduced in
https://github.com/twentyhq/twenty/pull/15393, that was failing because
of direct data source access removing all views ( even seeded one )
which was making the test fail

While doing so discovered a lot of issue with the rest API:
- Rest api wasn't consuming the v2 at all
- Rest api wasn't prepared to handle v2 exceptions
- Rest api did not handled unknown exceptions ( timeout )

Refactored the cleanup of each test to follow black box pattern and
avoid test leakage
2025-10-29 15:07:08 +01:00
nitinandGitHub 28c6edfa1f add validation on widgets grid position and sizing (#15397)
closes https://github.com/twentyhq/core-team-issues/issues/1606

As discussed in DMS -- overlapping is not a concern since the library
handles the collision and handles overlapping widgets (if created
through api) using the compact type vertical (ie, move the widget
vertically to create space)
2025-10-29 14:05:26 +00:00
MarieandGitHub 473efb5dc5 [groupBy] Order by within records (#15404)
Closes https://github.com/twentyhq/core-team-issues/issues/1727

<img width="1415" height="625" alt="image"
src="https://github.com/user-attachments/assets/cd132582-4a95-463c-8946-87b77670e023"
/>
2025-10-29 14:49:10 +01:00
ab10aa356d i18n - translations (#15429)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2025-10-29 12:31:42 +01:00
6835 changed files with 476598 additions and 103891 deletions
+319
View File
@@ -0,0 +1,319 @@
---
description: Process and guidelines for creating release changelogs for Twenty CRM
globs: ["**/releases/*.mdx", "**/releases/**"]
alwaysApply: false
---
# Twenty Release Changelog Process
Complete guide for creating release changelogs, including codebase research, file structure, and content guidelines.
## Prerequisites
Before starting, gather the following information:
### Required Information
**Version Number**: `{VERSION}` (e.g., 1.9.0, 2.0.0, 2.1.0)
**Release Date**: Use today's date in format: YYYY-MM-DD
### Changes/Features to Document
List the features and changes to include in this release:
1. **Feature Name**: ______________________________
- Brief description: ______________________________
- Related area (workflow, UI, backend, etc.): ______________________________
2. **Feature Name**: ______________________________
- Brief description: ______________________________
- Related area: ______________________________
3. **Feature Name**: ______________________________
- Brief description: ______________________________
- Related area: ______________________________
## Codebase Research Guide
If feature descriptions are not provided or need enhancement, research the codebase:
### Where to Look
**For Workflow Features:**
- Frontend: `packages/twenty-front/src/modules/workflow/`
- Backend: `packages/twenty-server/src/modules/workflow/`
- Components: `packages/twenty-front/src/modules/workflow/components/`
**For UI/UX Changes:**
- Components: `packages/twenty-front/src/modules/ui/`
- Layout: `packages/twenty-front/src/modules/layout/`
- Design system: `packages/twenty-ui/src/`
**For Backend/API Features:**
- Server modules: `packages/twenty-server/src/modules/`
- Entities: `packages/twenty-server/src/entities/`
- Services: Look for `*.service.ts` files
**For Database/ORM Changes:**
- Migrations: `packages/twenty-server/src/database/typeorm/`
- Entities: `packages/twenty-server/src/entities/`
### Research Commands
```bash
# Find recent merged PRs (adjust date as needed)
gh pr list --search "merged:>2025-10-01" --limit 50 --state merged
# View recent commits
git log --since="2 weeks ago" --oneline --no-merges
# View commits between releases (replace with actual release tags)
git log v1.7.0..v1.8.0 --oneline
# Search for specific feature keywords in code
grep -r "iterator" packages/twenty-front/src/modules/workflow/
grep -r "bulk select" packages/twenty-front/src/modules/workflow/
# Find recent changes in specific directory
git log --since="2 weeks ago" --oneline -- packages/twenty-front/src/modules/workflow/
```
### Using Codebase Search
Use the AI codebase search to find:
- "How does the workflow iterator node work?"
- "Where is bulk select implemented for workflows?"
- "What changes were made to the search node limit?"
## Step-by-Step Process
### 1. Setup Git Branch
```bash
cd /Users/thomascolasdesfrancs/code/twenty
git checkout main
git pull origin main
git checkout -b {VERSION}
```
Replace `{VERSION}` with the actual version number (e.g., `1.9.0`)
### 2. Create File Structure
**Create changelog file:**
- Path: `packages/twenty-website/src/content/releases/{VERSION}.mdx`
- Example: `packages/twenty-website/src/content/releases/1.9.0.mdx`
**Create image folder:**
- Path: `packages/twenty-website/public/images/releases/{MINOR_VERSION}/`
- Example for version 1.9.0: `packages/twenty-website/public/images/releases/1.9/`
- Example for version 2.0.0: `packages/twenty-website/public/images/releases/2.0/`
```bash
# Create the image folder
mkdir -p packages/twenty-website/public/images/releases/{MINOR_VERSION}
```
### 3. Move Illustration Files
**Source:** `/Users/thomascolasdesfrancs/Downloads/🆕`
**Destination:** `packages/twenty-website/public/images/releases/{MINOR_VERSION}/`
**Naming Convention:** `{VERSION}-descriptive-name.png`
Examples:
- `1.9.0-feature-name.png`
- `1.9.0-another-feature.png`
```bash
# Move and rename files
cp ~/Downloads/🆕/source-file.png packages/twenty-website/public/images/releases/{MINOR_VERSION}/{VERSION}-feature-name.png
```
### 4. Research Features (if needed)
If descriptions are not provided:
1. Use the research commands above to find recent PRs and commits
2. Search the codebase for feature-related code
3. Read PR descriptions for context
4. Check component comments and documentation
### 5. Write Changelog Content
Create the MDX file with this structure:
```markdown
---
release: {VERSION}
Date: {YYYY-MM-DD}
---
# Feature 1 Name
Short description explaining what the feature does and why it's useful. Keep it user-focused and concise (1-2 sentences).
![](/images/releases/{MINOR_VERSION}/{VERSION}-feature-1.png)
# Feature 2 Name
Another short description of the second feature.
![](/images/releases/{MINOR_VERSION}/{VERSION}-feature-2.png)
# Feature 3 Name
Description of the third feature.
![](/images/releases/{MINOR_VERSION}/{VERSION}-feature-3.png)
```
**Style Guidelines:**
- Use H1 (`#`) for feature names
- Keep descriptions to 1-2 sentences
- Focus on user benefits, not technical implementation
- Use active voice
- Start with what the user can now do
**Reference Previous Changelogs:**
- Check `packages/twenty-website/src/content/releases/` for examples
- Recent releases: 1.7.0.mdx, 1.6.0.mdx, 1.5.0.mdx
### 6. Review
Open the changelog file for review:
```bash
# Open in Cursor
cursor packages/twenty-website/src/content/releases/{VERSION}.mdx
# Open image folder to verify illustrations
open packages/twenty-website/public/images/releases/{MINOR_VERSION}
```
Review checklist:
- [ ] Version number is correct in frontmatter
- [ ] Date is today's date
- [ ] All features are documented
- [ ] Image paths are correct
- [ ] Image files exist in the folder
- [ ] Descriptions are clear and user-focused
- [ ] Spelling and grammar are correct
### 7. Present Changelog for User Approval
**IMPORTANT**: Before committing and creating the PR, always show the complete changelog content to the user and wait for explicit approval.
**What to show:**
1. Display the full MDX content of the changelog file
2. Confirm that illustration files were moved to the correct location
3. List the image file names and paths
**What to say:**
```
I've created the changelog for version {VERSION}. Here's the content for your review:
[Show full MDX content]
Images moved to:
- packages/twenty-website/public/images/releases/{MINOR_VERSION}/{VERSION}-feature-1.png
- packages/twenty-website/public/images/releases/{MINOR_VERSION}/{VERSION}-feature-2.png
Please review the content. Once you approve, I'll commit the changes and create the pull request.
```
**Wait for user approval before proceeding to step 8.**
Possible user responses:
- "Looks good" / "Approve" / "Create the PR" → Proceed to step 8
- Requests changes → Make the requested edits, then show content again
- Asks questions → Answer them, then wait for approval
### 8. Commit Changes
```bash
# Check status
git status
# Add files
git add packages/twenty-website/src/content/releases/{VERSION}.mdx
git add packages/twenty-website/public/images/releases/{MINOR_VERSION}/
# Commit
git commit -m "Add {VERSION} release changelog"
# Push branch
git push -u origin {VERSION}
```
### 9. Create Pull Request
```bash
# Create PR using GitHub CLI
gh pr create \
--title "Release {VERSION}" \
--body "## Release {VERSION}
This release includes:
- Feature 1
- Feature 2
- Feature 3
Changelog file: \`packages/twenty-website/src/content/releases/{VERSION}.mdx\`
Release date: {DATE}" \
--base main \
--head {VERSION}
```
Or visit: `https://github.com/twentyhq/twenty/pull/new/{VERSION}`
## File Naming Conventions
### Changelog Files
- **Format**: `{MAJOR}.{MINOR}.{PATCH}.mdx`
- **Convention**: One file per complete version
- **Examples**: `1.6.0.mdx`, `1.7.0.mdx`, `2.0.0.mdx`
- **Location**: `packages/twenty-website/src/content/releases/`
### Image Folders
- **Format**: `{MAJOR}.{MINOR}/`
- **Convention**: One folder per minor version (shared across patches)
- **Examples**: `1.6/`, `1.7/`, `2.0/`
- **Location**: `packages/twenty-website/public/images/releases/`
### Image Files
- **Format**: `{VERSION}-descriptive-name.png`
- **Convention**: Kebab-case descriptive names
- **Examples**:
- `1.8.0-workflow-iterator.png`
- `1.8.0-bulk-select.png`
- `1.9.0-new-feature.png`
## Quick Reference Template
Copy and fill this for each release:
```
VERSION: ___________
DATE: ___________
MINOR_VERSION: ___________
Features to document:
1. ___________________________
2. ___________________________
3. ___________________________
Branch name: {VERSION}
Changelog path: packages/twenty-website/src/content/releases/{VERSION}.mdx
Images path: packages/twenty-website/public/images/releases/{MINOR_VERSION}/
```
## Tips
- **Start early**: Begin documenting features as they're developed
- **User perspective**: Write for users, not developers
- **Be concise**: 1-2 sentences per feature
- **Visual first**: Illustrations should showcase the feature clearly
- **Consistent style**: Match tone and structure of previous changelogs
- **Test links**: Verify all image paths work before committing
- **Research thoroughly**: Use codebase search to understand features deeply
+58 -3
View File
@@ -30,6 +30,18 @@ type ButtonProps = {}; // Component props suffix with 'Props'
// ✅ Files and directories - kebab-case
// user-profile.component.tsx
// user-profile.styles.ts
// ❌ NEVER use abbreviations in variable names
// Bad
const users = data.map((u) => u.name);
const field = items.find((f) => f.id === id);
// Good
const users = data.map((user) => user.name);
const field = items.find((item) => item.id === id);
const fieldMetadata = inlineFields.find(
(fieldMetadataItem) => fieldMetadataItem.name === fieldName,
);
```
## Import Organization
@@ -59,11 +71,11 @@ const processUserData = (
): ProcessedUser => {
const processedUser = transformUserData(user);
applyOptions(processedUser, options);
if (callback) {
callback(processedUser);
}
return processedUser;
};
```
@@ -71,7 +83,7 @@ const processUserData = (
## Comments
```typescript
// ✅ Use short-form comments, NOT JSDoc blocks
// ✅ Explain business logic and non-obvious intentions
// ✅ Explain business logic and non-obvious intentions (WHY, not WHAT)
// Apply 15% discount for premium users with orders > $100
const discount = isPremiumUser && orderTotal > 100 ? 0.15 : 0;
@@ -85,12 +97,55 @@ const calculateTotalPrice = (basePrice: number): number => {
// Implementation
};
// ❌ AVOID obvious comments that just describe what code does
// Bad: Get all inline fields dynamically
const { inlineFieldMetadataItems } = useFieldListFieldMetadataItems({...});
// Bad: Define standard fields in display order
const standardFieldOrder = ['startsAt', 'endsAt', 'conferenceLink'];
// Bad: Split fields into standard and custom
const standardFields = standardFieldOrder.map(...)
// ✅ GOOD: Only comment if explaining non-obvious business logic
// Calendar events display standard fields first, then custom fields after participants
// to maintain consistency with the legacy UI behavior
const standardFields = standardFieldOrder.map(...)
// ❌ AVOID JSDoc blocks - use short comments instead
/**
* This style is NOT preferred in this codebase
*/
```
**Comment Guidelines:**
- **DO** comment complex business rules or domain-specific logic
- **DO** comment non-obvious algorithmic decisions
- **DO** add TODOs for future improvements
- **DON'T** comment obvious variable declarations or function calls
- **DON'T** comment what is already clear from well-named variables/functions
- **DON'T** add comments that just repeat what the code says
## Utility Helpers
```typescript
// ✅ Use existing utility helpers instead of manual checks
import { isDefined } from 'twenty-shared/utils';
import { isNonEmptyString, isNonEmptyArray } from '@sniptt/guards';
// ❌ Manual type guards
const validItems = items.filter((item): item is Item => item !== undefined);
const hasValue = value !== null && value !== undefined;
// ✅ Use utility helpers
const validItems = items.filter(isDefined);
const hasValue = isDefined(value);
// Other useful helpers:
// - isDefined(value) - checks !== null && !== undefined
// - isNonEmptyString(value) - checks string is defined and not empty
// - isNonEmptyArray(value) - checks array is defined and has items
```
## Security Patterns
```typescript
// ✅ CSV Export: Always apply security first, then formatting
+8
View File
@@ -0,0 +1,8 @@
{
"setup-worktree": [
"nvm use",
"yarn",
"cp $ROOT_WORKTREE_PATH/packages/twenty-server/.env packages/twenty-server/.env || true",
"cp $ROOT_WORKTREE_PATH/packages/twenty-front/.env packages/twenty-front/.env || true"
]
}
+4 -4
View File
@@ -1,21 +1,21 @@
# Contributing to Twenty
Thanks for considering contributing to Twenty!
Thanks for considering contributing to Twenty!
Please make sure to go through the [documentation](https://docs.twenty.com) before.
Please make sure to go through the [documentation](https://docs.twenty.com) before.
<br>
## Good first issues
Good first issues are a great way to start contributing and get familiar with the codebase. You can find them on by filtering on the [good first issue](https://github.com/twentyhq/twenty/labels/good%20first%20issue) label.
Good first issues are a great way to start contributing and get familiar with the codebase. You can find them on by filtering on the [good first issue](https://github.com/twentyhq/twenty/labels/good%20first%20issue) label.
## Issue assignment
To avoid conflicts, we follow these guidelines:
1. For `Good First Issue` and `Experienced Contributor` issues without `size: long` labels, we'll merge the first PRs that meet our [code quality standards](https://twenty.com/developers). **We don't assign contributors to these issues**. For `priority: high` issues, our core team will step in within days if no adequate contributions are received.
1. For `Good First Issue` and `Experienced Contributor` issues without `size: long` labels, we'll merge the first PRs that meet our [code quality standards](https://docs.twenty.com/developers). **We don't assign contributors to these issues**. For `priority: high` issues, our core team will step in within days if no adequate contributions are received.
2. For `size: long` Issues, assigned contributors have one week to submit their first draft PR.
## How to Contribute
+15
View File
@@ -0,0 +1,15 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
versioning-strategy: "lockfile-only"
assignees:
- "mabdullahabaid"
ignore:
- dependency-name: "@graphql-yoga/nestjs"
- dependency-name: "@nestjs/graphql"
- dependency-name: "@ptc-org/nestjs-query-graphql"
- dependency-name: "typeorm"
+47
View File
@@ -0,0 +1,47 @@
name: CI Docs
on:
push:
branches:
- main
pull_request:
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: |
package.json
packages/twenty-docs/**
eslint.config.mjs
docs-lint:
needs: changed-files-check
if: needs.changed-files-check.outputs.any_changed == 'true'
timeout-minutes: 10
runs-on: ubuntu-latest
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.11.0
with:
access_token: ${{ github.token }}
- name: Fetch local actions
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dependencies
uses: ./.github/workflows/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
+1
View File
@@ -24,6 +24,7 @@ jobs:
with:
files: |
package.json
yarn.lock
packages/twenty-front/**
packages/twenty-ui/**
packages/twenty-shared/**
+4 -3
View File
@@ -23,6 +23,7 @@ jobs:
with:
files: |
package.json
yarn.lock
packages/twenty-server/**
packages/twenty-front/src/generated/**
packages/twenty-front/src/generated-metadata/**
@@ -125,13 +126,13 @@ jobs:
npx nx run twenty-front:graphql:generate
npx nx run twenty-front:graphql:generate --configuration=metadata
# Check if any files were modified
if ! git diff --quiet; then
# Check if GraphQL generated files were modified
if ! git diff --quiet -- packages/twenty-front/src/generated packages/twenty-front/src/generated-metadata; then
echo "::error::GraphQL schema changes detected. Please run 'npx nx run twenty-front:graphql:generate' and 'npx nx run twenty-front:graphql:generate --configuration=metadata' and commit the changes."
echo ""
echo "The following GraphQL schema changes were detected:"
echo "==================================================="
git diff
git diff -- packages/twenty-front/src/generated packages/twenty-front/src/generated-metadata
echo "==================================================="
echo ""
echo "Please run 'npx nx run twenty-front:graphql:generate' and 'npx nx run twenty-front:graphql:generate --configuration=metadata' and commit the changes."
+155
View File
@@ -0,0 +1,155 @@
name: 'Pull docs translations from Crowdin'
permissions:
contents: write
pull-requests: write
on:
schedule:
- cron: '0 */2 * * *' # Every two hours
workflow_dispatch:
inputs:
force_pull:
description: 'Force pull translations regardless of status'
required: false
type: boolean
default: false
workflow_call:
inputs:
force_pull:
description: 'Force pull translations regardless of status'
required: false
type: boolean
default: false
pull_request:
paths:
- 'packages/twenty-docs/**'
- 'crowdin.yml'
- '.github/workflows/docs-i18n-pull.yaml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
pull_docs_translations:
name: Pull docs translations
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
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
- 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
if: github.event_name != 'pull_request'
run: |
git fetch origin i18n || true
git checkout -B i18n origin/i18n || git checkout -b i18n
- name: Configure git
run: |
git config --global user.name 'github-actions'
git config --global user.email 'github-actions@twenty.com'
- name: Stash any changes before pulling translations
if: github.event_name != 'pull_request'
run: |
git add .
git stash || true
- 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
env:
GITHUB_TOKEN: ${{ github.token }}
CROWDIN_PROJECT_ID: '1'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: Fix file permissions
if: github.event_name != 'pull_request'
run: sudo chown -R runner:docker . || true
- name: Fix translated documentation links
run: bash packages/twenty-docs/scripts/fix-translated-links.sh
- name: Regenerate navigation template
if: github.event_name == 'pull_request'
run: yarn docs:generate-navigation-template
- name: Regenerate docs.json
run: yarn docs:generate
- name: Commit artifacts to pull request branch
if: github.event_name == 'pull_request'
run: |
git add packages/twenty-docs/docs.json packages/twenty-docs/navigation/navigation.template.json
if git diff --staged --quiet --exit-code; then
echo "No navigation/doc changes to commit."
exit 0
fi
git commit -m "chore: sync docs artifacts"
git push origin HEAD:${{ github.head_ref }}
- name: Check for changes and commit
if: github.event_name != 'pull_request'
id: check_changes
run: |
git add .
if ! git diff --staged --quiet --exit-code; then
git commit -m "chore: update docs translations from Crowdin and fix internal links"
echo "changes_detected=true" >> $GITHUB_OUTPUT
else
echo "changes_detected=false" >> $GITHUB_OUTPUT
fi
- name: Push changes
if: github.event_name != 'pull_request' && steps.check_changes.outputs.changes_detected == 'true'
run: git push origin HEAD:i18n
- 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
else
echo "No file differences between branches, skipping PR creation"
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+68
View File
@@ -0,0 +1,68 @@
name: 'Push docs to Crowdin'
permissions:
contents: write
on:
workflow_dispatch:
workflow_call:
push:
branches: ['main', 'docs-localized-navigation']
paths:
- 'packages/twenty-docs/**/*.mdx'
- '!packages/twenty-docs/fr/**'
- 'crowdin.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
push_docs:
name: Push documentation to Crowdin
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
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
- name: Generate navigation template for Crowdin
run: yarn docs:generate-navigation-template
- name: Upload docs to Crowdin
uses: crowdin/github-action@v2
with:
upload_sources: true
upload_translations: false
download_translations: false
localization_branch_name: i18n
base_url: 'https://twenty.api.crowdin.com'
env:
CROWDIN_PROJECT_ID: 1
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
+4 -2
View File
@@ -74,6 +74,8 @@ jobs:
upload_sources: false
upload_translations: false
download_translations: true
source: '**/en.po'
translation: '%original_path%/%locale%.po'
export_only_approved: false
localization_branch_name: i18n
base_url: 'https://twenty.api.crowdin.com'
@@ -91,7 +93,7 @@ jobs:
GITHUB_TOKEN: ${{ github.token }}
CROWDIN_PROJECT_ID: '1'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
# As the files are extracted from a Docker container, they belong to root:root
# We need to fix this before the next steps
- name: Fix file permissions
@@ -103,7 +105,7 @@ jobs:
# if: inputs.force_pull || steps.compile_translations_strict.outcome == 'failure'
run: |
npx nx run twenty-server:lingui:compile
npx nx run twenty-emails:lingui:compile
npx nx run twenty-emails:lingui:compile
npx nx run twenty-front:lingui:compile
git status
git config --global user.name 'github-actions'
+1 -1
View File
@@ -65,7 +65,7 @@ npx nx run twenty-server:database:init:prod # Initialize database
npx nx run twenty-server:database:migrate:prod # Run migrations
# Generate migration
npx nx run twenty-server:typeorm migration:generate src/database/typeorm/core/migrations/[name] -d src/database/typeorm/core/core.datasource.ts
npx nx run twenty-server:typeorm migration:generate src/database/typeorm/core/migrations/common/[name] -d src/database/typeorm/core/core.datasource.ts
# Sync metadata
npx nx run twenty-server:command workspace:sync-metadata
+9 -11
View File
@@ -1,5 +1,3 @@
[![Hacktoberfest 2025](packages/twenty-website/public/images/readme/hacktoberfest2025.png)](https://twentycrm.notion.site/)
<p align="center">
<a href="https://www.twenty.com">
<img src="./packages/twenty-website/public/images/core/logo.svg" width="100px" alt="Twenty logo" />
@@ -8,7 +6,7 @@
<h2 align="center" >The #1 Open-Source CRM </h2>
<p align="center"><a href="https://twenty.com">🌐 Website</a> · <a href="https://twenty.com/developers">📚 Documentation</a> · <a href="https://github.com/orgs/twentyhq/projects/1"><img src="./packages/twenty-website/public/images/readme/planner-icon.svg" width="12" height="12"/> Roadmap </a> · <a href="https://discord.gg/cx5n4Jzs57"><img src="./packages/twenty-website/public/images/readme/discord-icon.svg" width="12" height="12"/> Discord</a> · <a href="https://www.figma.com/file/xt8O9mFeLl46C5InWwoMrN/Twenty"><img src="./packages/twenty-website/public/images/readme/figma-icon.png" width="12" height="12"/> Figma</a></p>
<p align="center"><a href="https://twenty.com">🌐 Website</a> · <a href="https://docs.twenty.com">📚 Documentation</a> · <a href="https://github.com/orgs/twentyhq/projects/1"><img src="./packages/twenty-website/public/images/readme/planner-icon.svg" width="12" height="12"/> Roadmap </a> · <a href="https://discord.gg/cx5n4Jzs57"><img src="./packages/twenty-website/public/images/readme/discord-icon.svg" width="12" height="12"/> Discord</a> · <a href="https://www.figma.com/file/xt8O9mFeLl46C5InWwoMrN/Twenty"><img src="./packages/twenty-website/public/images/readme/figma-icon.png" width="12" height="12"/> Figma</a></p>
<br />
@@ -24,11 +22,11 @@
<br />
# Installation
# Installation
See:
🚀 [Self-hosting](https://twenty.com/developers/section/self-hosting)
🖥️ [Local Setup](https://twenty.com/developers/local-setup)
See:
🚀 [Self-hosting](https://docs.twenty.com/developers/self-hosting/docker-compose)
🖥️ [Local Setup](https://docs.twenty.com/developers/local-setup)
# Does the world need another CRM?
@@ -44,7 +42,7 @@ We built Twenty for three reasons:
# What You Can Do With Twenty
Please feel free to flag any specific needs you have by creating an issue.
Please feel free to flag any specific needs you have by creating an issue.
Below are a few features we have implemented to date:
@@ -131,7 +129,7 @@ Below are a few features we have implemented to date:
- Star the repo
- Subscribe to releases (watch -> custom -> releases)
- Follow us on [Twitter](https://twitter.com/twentycrm) or [LinkedIn](https://www.linkedin.com/company/twenty/)
- Follow us on [Twitter](https://twitter.com/twentycrm) or [LinkedIn](https://www.linkedin.com/company/twenty/)
- Join our [Discord](https://discord.gg/cx5n4Jzs57)
- Improve translations on [Crowdin](https://twenty.crowdin.com/twenty)
- [Contributions](https://github.com/twentyhq/twenty/contribute) are, of course, most welcome!
- Improve translations on [Crowdin](https://twenty.crowdin.com/twenty)
- [Contributions](https://github.com/twentyhq/twenty/contribute) are, of course, most welcome!
+33 -1
View File
@@ -27,5 +27,37 @@ files: [
# 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",
}
]
]
+38 -10
View File
@@ -4,6 +4,7 @@ import typescriptEslint from '@typescript-eslint/eslint-plugin';
import typescriptParser from '@typescript-eslint/parser';
import importPlugin from 'eslint-plugin-import';
import linguiPlugin from 'eslint-plugin-lingui';
import * as mdxPlugin from 'eslint-plugin-mdx';
import preferArrowPlugin from 'eslint-plugin-prefer-arrow';
import prettierPlugin from 'eslint-plugin-prettier';
import unicornPlugin from 'eslint-plugin-unicorn';
@@ -19,27 +20,28 @@ export default [
// Global ignores
{
ignores: [
'**/node_modules/**',
],
ignores: ['**/node_modules/**'],
},
// Base configuration for all files
{
files: ['**/*.{js,jsx,ts,tsx}'],
plugins: {
'prettier': prettierPlugin,
'lingui': linguiPlugin,
prettier: prettierPlugin,
lingui: linguiPlugin,
'@nx': nxPlugin,
'prefer-arrow': preferArrowPlugin,
'import': importPlugin,
import: importPlugin,
'unused-imports': unusedImportsPlugin,
'unicorn': unicornPlugin,
unicorn: unicornPlugin,
},
rules: {
// General rules
'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
'no-console': ['warn', { allow: ['group', 'groupCollapsed', 'groupEnd'] }],
'no-console': [
'warn',
{ allow: ['group', 'groupCollapsed', 'groupEnd'] },
],
'no-control-regex': 0,
'no-debugger': 'error',
'no-duplicate-imports': 'error',
@@ -53,9 +55,13 @@ export default [
enforceBuildableLibDependency: true,
allow: [],
depConstraints: [
{
sourceTag: 'scope:apps',
onlyDependOnLibsWithTags: ['scope:apps', 'scope:sdk'],
},
{
sourceTag: 'scope:sdk',
onlyDependOnLibsWithTags: ['scope:sdk'],
onlyDependOnLibsWithTags: ['scope:sdk', 'scope:shared'],
},
{
sourceTag: 'scope:shared',
@@ -129,7 +135,7 @@ export default [
'error',
{
prefer: 'type-imports',
fixStyle: 'inline-type-imports'
fixStyle: 'inline-type-imports',
},
],
'@typescript-eslint/explicit-function-return-type': 'off',
@@ -186,4 +192,26 @@ export default [
parser: jsoncParser,
},
},
// MDX files
{
...mdxPlugin.flat,
plugins: {
...mdxPlugin.flat.plugins,
'@nx': nxPlugin,
},
},
mdxPlugin.flatCodeBlocks,
{
files: ['**/*.mdx'],
rules: {
'no-unused-vars': 'off',
'unused-imports/no-unused-imports': 'off',
'unused-imports/no-unused-vars': 'off',
// Enforce JSX tags on separate lines to prevent Crowdin translation issues
'@nx/workspace-mdx-component-newlines': 'error',
// Disallow angle bracket placeholders to prevent Crowdin translation errors
'@nx/workspace-no-angle-bracket-placeholders': 'error',
},
},
];
+4 -4
View File
@@ -36,7 +36,7 @@
"dependsOn": ["^build"]
},
"start": {
"cache": true,
"cache": false,
"dependsOn": ["^build"]
},
"lint": {
@@ -133,7 +133,7 @@
"outputs": ["{projectRoot}/{options.output-dir}"],
"options": {
"cwd": "{projectRoot}",
"command": "VITE_DISABLE_TYPESCRIPT_CHECKER=true VITE_DISABLE_ESLINT_CHECKER=true storybook build --test",
"command": "VITE_DISABLE_TYPESCRIPT_CHECKER=true storybook build --test",
"output-dir": "storybook-static",
"config-dir": ".storybook"
},
@@ -234,7 +234,7 @@
"command": "nx storybook:build {projectName}",
"forwardAllArgs": false
},
"cross-var chromatic --project-token=$CHROMATIC_PROJECT_TOKEN --storybook-build-dir=storybook-static {args.ci}"
"chromatic --storybook-build-dir=storybook-static {args.ci}"
],
"parallel": false
},
@@ -280,7 +280,7 @@
}
},
"installation": {
"version": "21.3.11"
"version": "22.0.3"
},
"generators": {
"@nx/react": {
+16 -17
View File
@@ -2,13 +2,13 @@
"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",
"@linaria/core": "^6.2.0",
"@linaria/react": "^6.2.1",
"@sentry/profiling-node": "^9.26.0",
"@sentry/react": "^9.26.0",
"@radix-ui/colors": "^3.0.0",
"@sniptt/guards": "^0.2.0",
"@tabler/icons-react": "^3.31.0",
"@wyw-in-js/vite": "^0.7.0",
@@ -73,15 +73,14 @@
"@graphql-codegen/typescript": "^3.0.4",
"@graphql-codegen/typescript-operations": "^3.0.4",
"@graphql-codegen/typescript-react-apollo": "^3.3.7",
"@nx/eslint": "21.3.11",
"@nx/eslint-plugin": "21.3.11",
"@nx/jest": "21.3.11",
"@nx/js": "21.3.11",
"@nx/react": "21.3.11",
"@nx/storybook": "21.3.11",
"@nx/vite": "21.3.11",
"@nx/web": "21.3.11",
"@playwright/test": "^1.46.0",
"@nx/eslint": "22.0.3",
"@nx/eslint-plugin": "22.0.3",
"@nx/jest": "22.0.3",
"@nx/js": "22.0.3",
"@nx/react": "22.0.3",
"@nx/storybook": "22.0.3",
"@nx/vite": "22.0.3",
"@nx/web": "22.0.3",
"@sentry/types": "^8",
"@storybook/addon-actions": "8.6.14",
"@storybook/addon-coverage": "^1.0.0",
@@ -144,11 +143,9 @@
"@typescript-eslint/parser": "^8.39.0",
"@typescript-eslint/utils": "^8.39.0",
"@vitejs/plugin-react-swc": "3.11.0",
"@vitest/ui": "1.4.0",
"@yarnpkg/types": "^4.0.0",
"chromatic": "^6.18.0",
"concurrently": "^8.2.2",
"cross-var": "^1.1.0",
"danger": "^13.0.4",
"dotenv-cli": "^7.4.4",
"esbuild": "^0.25.10",
@@ -157,6 +154,7 @@
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-lingui": "^0.9.0",
"eslint-plugin-mdx": "^3.6.2",
"eslint-plugin-prefer-arrow": "^1.2.3",
"eslint-plugin-prettier": "^5.1.2",
"eslint-plugin-project-structure": "^3.9.1",
@@ -175,8 +173,7 @@
"jsdom": "~22.1.0",
"msw": "^2.0.11",
"msw-storybook-addon": "^2.0.5",
"nx": "21.3.11",
"playwright": "^1.46.0",
"nx": "22.0.3",
"prettier": "^3.1.1",
"raw-loader": "^4.0.2",
"rimraf": "^5.0.5",
@@ -194,8 +191,7 @@
"vite-plugin-checker": "^0.10.2",
"vite-plugin-cjs-interop": "^2.2.0",
"vite-plugin-dts": "3.8.1",
"vite-plugin-svgr": "^4.2.0",
"vitest": "1.4.0"
"vite-plugin-svgr": "^4.2.0"
},
"engines": {
"node": "^24.5.0",
@@ -216,6 +212,8 @@
"version": "0.2.1",
"nx": {},
"scripts": {
"docs:generate": "tsx packages/twenty-docs/scripts/generate-docs-json.ts",
"docs:generate-navigation-template": "tsx packages/twenty-docs/scripts/generate-navigation-template.ts",
"start": "npx concurrently --kill-others 'npx nx run-many -t start -p twenty-server twenty-front' 'npx wait-on tcp:3000 && npx nx run twenty-server:worker'"
},
"workspaces": {
@@ -227,6 +225,7 @@
"packages/twenty-utils",
"packages/twenty-zapier",
"packages/twenty-website",
"packages/twenty-docs",
"packages/twenty-e2e-testing",
"packages/twenty-shared",
"packages/twenty-sdk",
+1
View File
@@ -0,0 +1 @@
generated
@@ -0,0 +1,6 @@
TWENTY_API_KEY=<SET_YOUR_TWENTY_API>
DAYS_AGO=<SET_YOUR_DAYS_AGO>
DISCORD_WEBHOOK_URL=<SET_YOUR_DISCORD_WEBHOOK_URL>
FB_GRAPH_TOKEN=<SET_YOUR_FB_GRAPH_TOKEN>
WHATSAPP_RECIPIENT_PHONE_NUMBER=<SET_YOUR_WHATSAPP_RECIPIENT_PHONE_NUMBER>
SLACK_HOOK_URL=<SET_YOUR_SLACK_HOOK_URL>
@@ -0,0 +1,2 @@
.yarn/install-state.gz
.env
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -0,0 +1,108 @@
# Twenty CRM Activity Reporter
A TypeScript-based reporting bot that summarizes activity from your Twenty CRM workspace and sends daily/periodic reports to Slack, Discord, and WhatsApp. Meet Kylian Mbaguette, your friendly CRM activity reporter!
## Features
- 🧑‍💻 **People & Company Tracking**: Summarizes newly created people and companies
- 🎯 **Opportunity Monitoring**: Reports on new opportunities created, broken down by stage
-**Task Analytics**:
- Tracks task creation
- Calculates on-time completion rates
- Identifies team members with the most overdue tasks (the "slackers")
- 🔔 **Multi-Platform Notifications**: Send reports to Slack, Discord, and/or WhatsApp
-**Configurable Time Range**: Look back any number of days
## Prerequisites
- Node.js (v14 or higher recommended)
- TypeScript
- A [Twenty CRM](https://twenty.com) account with API access
- Optional: Slack webhook, Discord webhook, and/or WhatsApp Business API access
## Installing dependencies
```bash
# Install dependencies
yarn install
```
### Environment Variables
| Variable | Required | Description |
|----------|----------|-------------|
| `TWENTY_API_KEY` | ✅ Yes | Your Twenty CRM API key |
| `DAYS_AGO` | ✅ Yes | Number of days to look back for the report |
| `SLACK_HOOK_URL` | ❌ No | Slack incoming webhook URL |
| `DISCORD_WEBHOOK_URL` | ❌ No | Discord webhook URL |
| `FB_GRAPH_TOKEN` | ❌ No | Facebook Graph API token for WhatsApp |
| `WHATSAPP_RECIPIENT_PHONE_NUMBER` | ❌ No | WhatsApp recipient phone number (with country code) |
## Project Structure
```
.
├── index.ts # Main entry point
├── people-creation-summariser.ts # Summarizes people/company creation
├── opportunity-creation-summariser.ts # Summarizes opportunity creation
├── task-creation-summariser.ts # Summarizes task creation & completion
├── senders.ts # Handles sending to Slack/Discord/WhatsApp
├── utils.ts # API request utility
└── README.md
```
## How It Works
1. **Data Collection**: The bot queries the Twenty CRM API for activities within the specified time range
2. **Analysis**:
- Counts new people and companies
- Categorizes opportunities by stage
- Calculates task completion rates and identifies overdue tasks
3. **Reporting**: Formats the data into friendly messages
4. **Distribution**: Sends reports to configured platforms (Slack, Discord, WhatsApp)
## Report Format
Each report includes:
```
Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last X days:
🧑‍💻 People & Companies
- X People and Y Companies were added
🎯 Opportunities
- X Opportunities were added: Y in NEW, Z in PROPOSAL
📋 Tasks
- X Tasks were created
- Y% Tasks were completed on time
- [Name] slacked the most with Z Tasks overdue
```
## API Integration
This bot uses the [Twenty CRM REST API](https://api.twenty.com/rest/). The following endpoints are used:
- `GET /people` - Fetch people data
- `GET /opportunities` - Fetch opportunity data
- `GET /tasks` - Fetch task data
- `GET /workspaceMembers/{id}` - Fetch workspace member details
## Notes
- The "slacker" detection is lighthearted and identifies team members with the most overdue tasks
- At least one messaging platform must be configured for the bot to send reports
- The bot uses ISO date format (YYYY-MM-DD) for date filtering
- Task completion percentage only considers incomplete tasks (excludes already completed tasks from the calculation)
## Troubleshooting
**Issue**: No messages being sent
- **Solution**: Ensure at least one messaging platform is configured with valid credentials
**Issue**: API authentication errors
- **Solution**: Verify your `TWENTY_API_KEY` is correct and has necessary permissions
**Issue**: WhatsApp messages not sending
- **Solution**: Ensure both `FB_GRAPH_TOKEN` and `WHATSAPP_RECIPIENT_PHONE_NUMBER` are set correctly
## Contributing
Built with ❤️ and 🥖 by Azmat, Ali and Mike from 9dots
@@ -0,0 +1,45 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
const config: ApplicationConfig = {
universalIdentifier: 'b53627f5-ca60-478c-bc43-c7ab4904e34a',
displayName: 'Activity Summary',
description:
'A TypeScript-based reporting bot that summarizes activity from your Twenty CRM workspace and sends daily/periodic reports to Slack, Discord, and WhatsApp. Meet Kylian Mbaguette, your friendly CRM activity reporter!',
applicationVariables: {
TWENTY_API_KEY: {
universalIdentifier: '304b7d5d-e2bb-4444-9b04-6b3ae8b73730',
description: 'Twenty API Key',
isSecret: true,
},
DAYS_AGO: {
universalIdentifier: '040a3097-9cee-4f74-b957-c2f9bf636c3f',
description:
'How far back into the past we want to summarise defaults to the past 7 days',
value: '7',
isSecret: false,
},
SLACK_HOOK_URL: {
universalIdentifier: 'fd16e370-934c-4267-83b4-7d88259bf7e1',
description: 'Slack hook URL for sending message to channel',
isSecret: true,
},
DISCORD_WEBHOOK_URL: {
universalIdentifier: 'f3741075-d525-4988-ba42-55d519c6fd76',
description:
'Discord webhook URL for sending message to channel of a server',
isSecret: true,
},
FB_GRAPH_TOKEN: {
universalIdentifier: 'fb907f49-74ac-4aa5-ba45-cfc9250ecc44',
description: 'For Facebook auth',
isSecret: true,
},
WHATSAPP_RECIPIENT_PHONE_NUMBER: {
universalIdentifier: 'c856ee5d-44bf-42f4-9a39-2553a94af518',
description: 'Phone number for receiving WhatsApp message',
isSecret: true,
},
},
};
export default config;
@@ -0,0 +1,17 @@
{
"name": "activity-summary",
"version": "0.0.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"dependencies": {
"twenty-sdk": "0.0.3"
},
"devDependencies": {
"@types/node": "^24.7.2"
}
}
@@ -0,0 +1,80 @@
import { summariseOpportunityCreation } from './opportunity-creation-summariser';
import { summarisePeopleCreation } from './people-creation-summariser';
import { sendToDiscord, sendToSlack, sendToWhatsApp } from './senders';
import { summariseTaskCreation } from './task-creation-summariser';
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
export const main = async (): Promise<object> => {
let date: string | Date = new Date();
date.setDate(new Date().getDate() - Number(process.env.DAYS_AGO));
date = date.toISOString().substring(0, 10);
const peopleCreationSummary = await summarisePeopleCreation(date);
const opportunityCreationSummary = await summariseOpportunityCreation(date);
const taskCreationSummary = await summariseTaskCreation(date);
let body = {
daysAgo: Number(process.env.DAYS_AGO),
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
discord: {},
whatsapp: {},
slack: {},
};
if (process.env.SLACK_HOOK_URL) {
const slackBody = await sendToSlack({
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
});
body = {
...body,
slack: slackBody,
};
}
if (process.env.DISCORD_WEBHOOK_URL) {
const discordBody = await sendToDiscord({
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
});
body = {
...body,
discord: discordBody,
};
}
if (
process.env.FB_GRAPH_TOKEN &&
process.env.WHATSAPP_RECIPIENT_PHONE_NUMBER
) {
const whatsappBody = await sendToWhatsApp({
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
});
body = {
...body,
whatsapp: whatsappBody,
};
}
return body;
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: 'c5b0e3f7-cbbd-4bd6-b01c-150d52cf2ce9',
name: 'summarise-and-send',
triggers: [
{
universalIdentifier: '36e1c4c7-8664-4d6d-a88f-ac56f1bd0651',
type: 'cron',
pattern: '0 9 * * *',
},
],
};
@@ -0,0 +1,28 @@
import { request } from "./utils"
type Opportunity = {
stage: 'NEW' | 'PROPOSAL'
}
export const summariseOpportunityCreation = async (date: string) => {
const { opportunities }: { opportunities: Opportunity[] } = await request(
`opportunities?filter=createdAt[gte]:${date}`,
)
if (opportunities.length === 0) {
return `- No Opportunities were added`
}
const stageSummary = Object.entries(
opportunities.reduce((hash: Record<string,number>, opportunity) => {
if (!hash[opportunity.stage]) {
hash[opportunity.stage] = 0
}
hash[opportunity.stage] += 1
return hash
}, {})
).map(([stage, value]) => `${value} in ${stage}`).join(', ')
return `- ${opportunities.length} Opportunities were added: ${stageSummary}`
}
@@ -0,0 +1,38 @@
import { request } from "./utils"
type Person = {
companyId: string
company: Company
}
type Company = {
id: string
accountOwnerId: string
}
export const summarisePeopleCreation = async (date: string) => {
const { people }: { people: Person[] } = await request(
`people?depth=1&filter=createdAt[gte]:${date}`,
)
if (people.length === 0) {
return '- No People were added'
}
let createdForCompanies: Record<string, Company> = {}
let numberOfAccountOwnerlessCompanies = 0
for (const person of people) {
const isCompanyTracked = createdForCompanies[person.companyId]
if (person.companyId && !isCompanyTracked) {
createdForCompanies[person.company.id] = person.company
if (!person?.company?.accountOwnerId) {
numberOfAccountOwnerlessCompanies += 1
}
}
}
return `- ${people.length} People were added for ${Object.keys(createdForCompanies).length} Companies
- Out of those, ${numberOfAccountOwnerlessCompanies} Companies don't have account owners yet`
}
@@ -0,0 +1,172 @@
export const sendToSlack = async (params: {
peopleCreationSummary: string;
opportunityCreationSummary: string;
taskCreationSummary: string;
}) => {
const {
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
} = params;
const slackMessage = {
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: `Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last ${process.env.DAYS_AGO} days`,
emoji: true,
},
},
{
type: 'header',
text: {
type: 'plain_text',
text: '🧑‍💻 People & Companies',
emoji: true,
},
},
{
type: 'section',
text: {
type: 'plain_text',
text: peopleCreationSummary,
emoji: true,
},
},
{
type: 'header',
text: {
type: 'plain_text',
text: '🎯 Opportunities',
emoji: true,
},
},
{
type: 'section',
text: {
type: 'plain_text',
text: opportunityCreationSummary,
emoji: true,
},
},
{
type: 'header',
text: {
type: 'plain_text',
text: '📋 Tasks',
emoji: true,
},
},
{
type: 'section',
text: {
type: 'plain_text',
text: taskCreationSummary,
emoji: true,
},
},
],
};
const response = await fetch(process.env.SLACK_HOOK_URL ?? '', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(slackMessage),
});
return {
formattedMessage: slackMessage,
webhookStatus: response.status,
};
};
export const sendToDiscord = async (params: {
peopleCreationSummary: string;
opportunityCreationSummary: string;
taskCreationSummary: string;
}) => {
const {
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
} = params;
const formattedMessage = `Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last ${process.env.DAYS_AGO} days:
**🧑‍💻 People & Companies**
${peopleCreationSummary}
**🎯 Opportunities**
${opportunityCreationSummary}
**📋 Tasks**
${taskCreationSummary}`;
const body = {
username: 'Twenty Bot',
content: formattedMessage,
};
const response = await fetch(process.env.DISCORD_WEBHOOK_URL ?? '', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return {
formattedMessage,
webhookStatus: response.status,
};
};
export const sendToWhatsApp = async (params: {
peopleCreationSummary: string;
opportunityCreationSummary: string;
taskCreationSummary: string;
}): Promise<object> => {
const {
peopleCreationSummary,
opportunityCreationSummary,
taskCreationSummary,
} = params;
const formattedMessage = `Bonjour! 🥖 Je m'appelle Kylian Mbaguette. Over the last ${process.env.DAYS_AGO} days:
*🧑‍💻 People & Companies*
${peopleCreationSummary}
*🎯 Opportunities*
${opportunityCreationSummary}
*📋 Tasks*
${taskCreationSummary}`;
const response = await fetch(
'https://graph.facebook.com/v22.0/828771160324576/messages',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.FB_GRAPH_TOKEN}`,
},
body: JSON.stringify({
messaging_product: 'whatsapp',
recipient_type: 'individual',
to: process.env.WHATSAPP_RECIPIENT_PHONE_NUMBER,
type: 'text',
text: {
preview_url: true,
body: formattedMessage,
},
}),
},
);
const responseBody = await response.json();
return {
formattedMessage,
webhookStatus: response.status,
webhookResponse: responseBody,
};
};
@@ -0,0 +1,89 @@
import { request } from "./utils"
type Task = {
status: string
dueAt: string
createdBy: {
workspaceMemberId: string
}
}
export const summariseTaskCreation = async (date: string) => {
const { tasks }: { tasks: Task[] } = await request(
`tasks?filter=createdAt[gte]:${date}`,
)
if (tasks.length === 0) {
return '- No Tasks were added'
}
const presentDateISOString = new Date().toISOString()
const workspaceMemberIdsDueDateCounter: Record<string, number> = {}
let workspaceMembers = []
tasks.forEach((task) => {
if (task.status === 'DONE') {
return
}
if (presentDateISOString >= task.dueAt) {
if (!workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId]) {
workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId] = 0
}
workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId] += 1
}
})
for (const { userId, count } of findMaxIncompleteKeys(workspaceMemberIdsDueDateCounter)) {
const data = await request(`workspaceMembers/${userId}`)
if (data.workspaceMember) {
workspaceMembers.push({
...data.workspaceMember,
slackCount: count
})
}
}
let slackerMessage = workspaceMembers.length > 0 ? workspaceMembers.reduce((text, member, index) => {
if (index === 0 && workspaceMembers.length === 1) {
return `${member.name.firstName} slacked the most with ${member.slackCount} Tasks overdue`
}
if (index !== workspaceMembers.length - 1) {
return text.concat(`, ${member.name.firstName}`)
}
if (index === workspaceMembers.length - 1) {
return text.concat(`, and ${member.name.firstName} slacked the most with ${member.slackCount} Tasks overdue`)
}
}, '') : 'No one was caught slacking!'
const tasksCompletedOnTime = tasks.filter(
task => task.status === 'DONE' && task.dueAt >= presentDateISOString
)
const taskCompletionPercentage = tasksCompletedOnTime.length > 0
? (tasksCompletedOnTime.length / tasks.length) * 100
: NaN
const taskCompletionMessage = isNaN(taskCompletionPercentage)
? 'No completed Tasks yet'
: `${taskCompletionPercentage.toFixed(2)}% of Tasks were completed on time`
return `- ${tasks.length} Tasks were created
- ${taskCompletionMessage}
- ${slackerMessage}`
}
/**
* @description This is generated by AI
*/
const findMaxIncompleteKeys = (workspaceMemberIdsDueDateCounter: Record<string,number>) => {
// Get the maximum incomplete count
const max = Math.max(...Object.values(workspaceMemberIdsDueDateCounter));
// Filter keys that match the maximum value
return Object.entries(workspaceMemberIdsDueDateCounter)
.filter(([_, count]) => count === max)
.map(([userId, count]) => ({ userId, count }))
};
@@ -0,0 +1,13 @@
export const request = async (route: string, authToken?: string) => {
const response = await fetch(
`https://api.twenty.com/rest/${route}`,
{
headers: {
Authorization: `Bearer ${process.env.TWENTY_API_KEY}`
},
}
)
const json = await response.json()
return json.data
}
@@ -0,0 +1,26 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
@@ -0,0 +1,38 @@
# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!
__metadata:
version: 8
cacheKey: 10c0
"@types/node@npm:^24.7.2":
version: 24.9.2
resolution: "@types/node@npm:24.9.2"
dependencies:
undici-types: "npm:~7.16.0"
checksum: 10c0/7905d43f65cee72ef475fe76316e10bbf6ac5d08a7f0f6c38f2b6285d7ca3009e8fcafc8f8a1d2bf3f55889c9c278dbb203a9081fd0cf2d6d62161703924c6fa
languageName: node
linkType: hard
"activity-summary@workspace:.":
version: 0.0.0-use.local
resolution: "activity-summary@workspace:."
dependencies:
"@types/node": "npm:^24.7.2"
twenty-sdk: "npm:0.0.3"
languageName: unknown
linkType: soft
"twenty-sdk@npm:0.0.3":
version: 0.0.3
resolution: "twenty-sdk@npm:0.0.3"
checksum: 10c0/0a3c85c27edb22fb50f7eb0da4f9770e85729fce05e9e0118ad0cdfc36e42425c93340a6cd1c276daf30aeeaa612db0cd905831c0a8287a31bff3da5be9b0562
languageName: node
linkType: hard
"undici-types@npm:~7.16.0":
version: 7.16.0
resolution: "undici-types@npm:7.16.0"
checksum: 10c0/3033e2f2b5c9f1504bdc5934646cb54e37ecaca0f9249c983f7b1fc2e87c6d18399ebb05dc7fd5419e02b2e915f734d872a65da2e3eeed1813951c427d33cc9a
languageName: node
linkType: hard
@@ -0,0 +1,19 @@
# Set environment values for your application here.
# Use the format: KEY=value
#
# These variables are automatically loaded when running your serverless functions.
# You can access them directly in your code using:
# const myValue = process.env.KEY;
#
# To make these variables available to your application,
# add them to package.json "env" key. This "env" key defines all
# environment variables that will be provided to your serverless
# functions at runtime.
#
# Example:
# API_TOKEN=your-api-token
# TIMEOUT_MS=3000
TWENTY_API_URL=
TWENTY_API_KEY=
OPENAI_API_KEY=
@@ -0,0 +1,2 @@
.yarn/install-state.gz
.env
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -0,0 +1,159 @@
# AI Meeting Transcript
Automatically process meeting transcripts to extract insights, action items, and follow-ups using AI.
## Features
- **Automatic Transcript Processing**: Receives meeting transcripts via webhook from Granola or similar transcription tools
- **AI-Powered Analysis**: Uses OpenAI to extract:
- Meeting summary
- Key discussion points
- Action items with assignees and due dates
- Commitments made by participants
- **Rich Note Creation**: Creates formatted notes in Twenty with summary and key points
- **Task Generation**: Automatically creates tasks for action items and commitments, linked to the meeting note
## Requirements
- `twenty-cli` - Install globally: `npm install -g twenty-cli`
- `apiKey` - Go to `https://twenty.com/settings/api-webhooks` to generate one
- `OpenAI API Key` - Get your API key from [OpenAI](https://platform.openai.com/api-keys)
## Installation
1. Copy the environment file:
```bash
cp .env.example .env
```
2. Edit `.env` and replace the placeholders:
- `<SET_YOUR_TWENTY_API>` with your Twenty API key
- `<SET_YOUR_OPENAI_API_KEY>` with your OpenAI API key
3. Install dependencies:
```bash
yarn install
```
4. Sync the app to your Twenty workspace:
```bash
twenty auth login
twenty app sync
```
## Configuration
After syncing, configure the environment variables in your Twenty workspace:
1. Go to Settings → Apps → AI Meeting Transcript
2. Set the following environment variables:
- `TWENTY_API_KEY` - Your Twenty API key
- `TWENTY_API_URL` - Your Twenty instance URL (e.g., `https://api.twenty.com` or `http://localhost:3000` for local development)
- `OPENAI_API_KEY` - Your OpenAI API key
**Important**: `TWENTY_API_URL` is required and must be set to your Twenty instance URL. For local development, use `http://localhost:3000`. For production, use your actual Twenty instance URL.
## Usage
### Webhook Endpoint
The app exposes a public serverless route trigger.
```
POST /s/webhook/transcript
```
Examples:
- Local: `POST http://localhost:3000/s/webhook/transcript`
- Hosted: `POST https://your-twenty-instance.com/s/webhook/transcript`
### Webhook Payload Format
Send a POST request with the following JSON structure:
```json
{
"transcript": "Full meeting transcript text here...",
"meetingTitle": "Q4 Planning Meeting",
"meetingDate": "2024-01-15",
"participants": ["John Doe", "Jane Smith"],
"metadata": {
"duration": "45 minutes",
"location": "Conference Room A"
}
}
```
**Required Fields:**
- `transcript` (string): The full meeting transcript text
**Optional Fields:**
- `meetingTitle` (string): Title of the meeting
- `meetingDate` (string): Date of the meeting (ISO format or readable date)
- `participants` (string[]): List of meeting participants
- `metadata` (object): Additional metadata about the meeting
### Example Webhook Call
```bash
curl -X POST https://your-twenty-instance.com/s/webhook/transcript \
-H "Content-Type: application/json" \
-d '{
"transcript": "John: Let'\''s start the meeting. Today we need to discuss Q4 goals. Jane: I agree. We should focus on customer retention. John: Great point. Can you prepare a report by Friday? Jane: Yes, I will have it ready.",
"meetingTitle": "Q4 Planning Meeting",
"meetingDate": "2024-01-15"
}'
```
### What Happens
1. **Transcript Analysis**: The transcript is sent to OpenAI for analysis
2. **Note Creation**: A formatted note is created in Twenty with:
- Meeting summary
- Key discussion points
- Reference to the transcript source
3. **Task Creation**: Tasks are automatically created for:
- Each action item identified
- Each commitment made by participants
- Tasks include a reference to the meeting note ID in their description
## Development
Run dev mode to see application updates on your workspace instantly:
```bash
twenty app dev
```
## Integration with Granola
To integrate with Granola or similar transcription tools:
1. Set up a webhook in your transcription service
2. Configure it to POST to: `https://your-twenty-instance.com/s/webhook/transcript`
3. Map the transcription service's payload format to the expected format above
### Granola Webhook Setup
If using Granola, configure the webhook to send:
- `transcript` field with the transcript text
- Optionally include meeting metadata fields
## API Response
The webhook returns a JSON response:
```json
{
"success": true,
"noteId": "uuid-of-created-note",
"taskIds": ["uuid-of-task-1", "uuid-of-task-2"],
"summary": {
"noteCreated": true,
"tasksCreated": 2,
"actionItemsProcessed": 1,
"commitmentsProcessed": 1
}
}
```
@@ -0,0 +1,30 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
const config: ApplicationConfig = {
universalIdentifier: '028754f1-3235-43b9-9427-fa6a62dbd473',
displayName: 'AI Meeting Transcript',
description:
'Automatically process meeting transcripts to extract insights, action items, and follow-ups',
applicationVariables: {
TWENTY_API_KEY: {
universalIdentifier: '1359d05c-4947-4673-809f-abd55bede365',
isSecret: true,
value: '',
description: 'Twenty API key',
},
TWENTY_API_URL: {
universalIdentifier: 'dbe83355-b574-445c-92c0-5c2b94a61ddb',
isSecret: true,
value: '',
description: 'Twenty API URL',
},
OPENAI_API_KEY: {
universalIdentifier: '9559470d-15eb-4bc2-9cbc-3bc5c869d1fd',
isSecret: true,
value: '',
description: 'OpenAI API key for transcript analysis',
},
},
};
export default config;
@@ -0,0 +1,19 @@
{
"name": "ai-meeting-transcript",
"version": "0.0.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"dependencies": {
"axios": "^1.12.2",
"openai": "^4.28.0",
"twenty-sdk": "0.0.3"
},
"devDependencies": {
"@types/node": "^24.7.2"
}
}
@@ -0,0 +1,306 @@
import axios from 'axios';
import OpenAI from 'openai';
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
type TranscriptWebhookPayload = {
transcript: string;
meetingTitle?: string;
meetingDate?: string;
participants?: string[];
metadata?: Record<string, unknown>;
};
type ActionItem = {
title: string;
description: string;
assignee?: string;
dueDate?: string;
};
type Commitment = {
person: string;
commitment: string;
dueDate?: string;
};
type AnalysisResult = {
summary: string;
keyPoints: string[];
actionItems: ActionItem[];
commitments: Commitment[];
};
type RichTextV2Data = {
markdown: string;
blocknote: null;
};
type TwentyApiResponse = {
id: string;
};
const OPENAI_MODEL = 'gpt-4o-mini';
const OPENAI_TEMPERATURE = 0.3;
const analyzeTranscript = async (
transcript: string,
openaiApiKey: string,
): Promise<AnalysisResult> => {
const openai = new OpenAI({ apiKey: openaiApiKey });
const prompt = `Analyze the following meeting transcript and extract:
1. A concise summary (2-3 sentences)
2. Key discussion points (bullet list)
3. Action items with titles, descriptions, and any mentioned assignees or due dates
4. Commitments made by participants with names and any mentioned due dates
Return the response as a JSON object with this structure:
{
"summary": "string",
"keyPoints": ["string"],
"actionItems": [{"title": "string", "description": "string", "assignee": "string (optional)", "dueDate": "string (optional)"}],
"commitments": [{"person": "string", "commitment": "string", "dueDate": "string (optional)"}]
}
Transcript:
${transcript}`;
const completion = await openai.chat.completions.create({
model: OPENAI_MODEL,
messages: [
{
role: 'system',
content:
'You are a meeting analysis assistant. Extract key insights, action items, and commitments from meeting transcripts. Always return valid JSON.',
},
{
role: 'user',
content: prompt,
},
],
response_format: { type: 'json_object' },
temperature: OPENAI_TEMPERATURE,
});
const content = completion.choices[0]?.message?.content;
if (!content) {
throw new Error('No response from OpenAI');
}
return JSON.parse(content) as AnalysisResult;
};
const getTwentyApiConfig = () => {
const apiKey = process.env.TWENTY_API_KEY;
if (!apiKey) {
throw new Error('TWENTY_API_KEY environment variable is not set');
}
const baseUrl = process.env.TWENTY_API_URL;
return { apiKey, baseUrl };
};
const formatNoteBody = (summary: string, keyPoints: string[]): string => {
const keyPointsList = keyPoints.map((point) => `- ${point}`).join('\n');
return `## Summary\n\n${summary}\n\n## Key Points\n\n${keyPointsList}\n\n*Generated from meeting transcript*`;
};
const createNoteInTwenty = async (
summary: string,
keyPoints: string[],
meetingTitle?: string,
meetingDate?: string,
): Promise<TwentyApiResponse> => {
const { apiKey, baseUrl } = getTwentyApiConfig();
const noteTitle =
meetingTitle ||
`Meeting Notes - ${meetingDate || new Date().toLocaleDateString()}`;
const noteBodyMarkdown = formatNoteBody(summary, keyPoints);
const requestData = {
title: noteTitle,
bodyV2: {
markdown: noteBodyMarkdown,
blocknote: null,
} satisfies RichTextV2Data,
};
try {
const { data } = await axios.post<TwentyApiResponse>(
`${baseUrl}/rest/notes`,
requestData,
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
},
);
return data;
} catch (error) {
if (axios.isAxiosError(error)) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message;
const status = error.response?.status;
throw new Error(
`Failed to create note: ${errorMessage}. Status: ${status}`,
);
}
throw error;
}
};
const createTaskInTwenty = async (
actionItem: ActionItem,
): Promise<TwentyApiResponse> => {
const { apiKey, baseUrl } = getTwentyApiConfig();
const taskData: {
title: string;
bodyV2: RichTextV2Data;
dueAt?: string;
} = {
title: actionItem.title,
bodyV2: {
markdown: actionItem.description,
blocknote: null,
},
};
if (actionItem.dueDate) {
taskData.dueAt = new Date(actionItem.dueDate).toISOString();
}
try {
const { data } = await axios.post<TwentyApiResponse>(
`${baseUrl}/rest/tasks`,
taskData,
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
},
);
return data;
} catch (error) {
if (axios.isAxiosError(error)) {
const errorMessage = error.response?.data
? JSON.stringify(error.response.data, null, 2)
: error.message;
const status = error.response?.status;
throw new Error(
`Failed to create task "${actionItem.title}": ${errorMessage}. Status: ${status}`,
);
}
throw error;
}
};
const createTasksFromActionItems = async (
actionItems: ActionItem[],
noteId: string,
): Promise<string[]> => {
const taskIds: string[] = [];
for (const actionItem of actionItems) {
try {
const taskDescription = `${actionItem.description}\n\n*Related to meeting note: ${noteId}*`;
const task = await createTaskInTwenty({
...actionItem,
description: taskDescription,
});
taskIds.push(task.id);
} catch (error) {
// Task creation failed, continue with next task
}
}
return taskIds;
};
const createTasksFromCommitments = async (
commitments: Commitment[],
noteId: string,
): Promise<string[]> => {
const taskIds: string[] = [];
for (const commitment of commitments) {
try {
const taskDescription = `Commitment from ${commitment.person}: ${commitment.commitment}\n\n*Related to meeting note: ${noteId}*`;
const task = await createTaskInTwenty({
title: `Follow up: ${commitment.commitment}`,
description: taskDescription,
dueDate: commitment.dueDate,
});
taskIds.push(task.id);
} catch (error) {
// Commitment task creation failed, continue with next commitment
}
}
return taskIds;
};
export const main = async (
params: TranscriptWebhookPayload,
): Promise<object> => {
const { transcript, meetingTitle, meetingDate } = params;
if (!transcript || typeof transcript !== 'string') {
throw new Error('Transcript is required and must be a string');
}
const openaiApiKey = process.env.OPENAI_API_KEY;
if (!openaiApiKey) {
throw new Error('OPENAI_API_KEY environment variable is not set');
}
const analysis = await analyzeTranscript(transcript, openaiApiKey);
const note = await createNoteInTwenty(
analysis.summary,
analysis.keyPoints,
meetingTitle,
meetingDate,
);
const actionItemTaskIds = await createTasksFromActionItems(
analysis.actionItems,
note.id,
);
const commitmentTaskIds = await createTasksFromCommitments(
analysis.commitments,
note.id,
);
const allTaskIds = [...actionItemTaskIds, ...commitmentTaskIds];
return {
success: true,
noteId: note.id,
taskIds: allTaskIds,
summary: {
noteCreated: true,
tasksCreated: allTaskIds.length,
actionItemsProcessed: analysis.actionItems.length,
commitmentsProcessed: analysis.commitments.length,
},
};
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: 'dae52ab2-174f-4f81-a031-604ee2e81eba',
name: 'ai-meeting-transcriptor',
triggers: [
{
universalIdentifier: 'b011303d-2c24-44d4-9923-55eb060a1ff6',
type: 'route',
path: '/webhook/transcript',
httpMethod: 'POST',
isAuthRequired: false,
},
],
};
@@ -0,0 +1,26 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
@@ -0,0 +1,435 @@
# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!
__metadata:
version: 8
cacheKey: 10c0
"@types/node-fetch@npm:^2.6.4":
version: 2.6.13
resolution: "@types/node-fetch@npm:2.6.13"
dependencies:
"@types/node": "npm:*"
form-data: "npm:^4.0.4"
checksum: 10c0/6313c89f62c50bd0513a6839cdff0a06727ac5495ccbb2eeda51bb2bbbc4f3c0a76c0393a491b7610af703d3d2deb6cf60e37e59c81ceeca803ffde745dbf309
languageName: node
linkType: hard
"@types/node@npm:*, @types/node@npm:^24.7.2":
version: 24.9.2
resolution: "@types/node@npm:24.9.2"
dependencies:
undici-types: "npm:~7.16.0"
checksum: 10c0/7905d43f65cee72ef475fe76316e10bbf6ac5d08a7f0f6c38f2b6285d7ca3009e8fcafc8f8a1d2bf3f55889c9c278dbb203a9081fd0cf2d6d62161703924c6fa
languageName: node
linkType: hard
"@types/node@npm:^18.11.18":
version: 18.19.130
resolution: "@types/node@npm:18.19.130"
dependencies:
undici-types: "npm:~5.26.4"
checksum: 10c0/22ba2bc9f8863101a7e90a56aaeba1eb3ebdc51e847cef4a6d188967ab1acbce9b4f92251372fd0329ecb924bbf610509e122c3dfe346c04dbad04013d4ad7d0
languageName: node
linkType: hard
"abort-controller@npm:^3.0.0":
version: 3.0.0
resolution: "abort-controller@npm:3.0.0"
dependencies:
event-target-shim: "npm:^5.0.0"
checksum: 10c0/90ccc50f010250152509a344eb2e71977fbf8db0ab8f1061197e3275ddf6c61a41a6edfd7b9409c664513131dd96e962065415325ef23efa5db931b382d24ca5
languageName: node
linkType: hard
"agentkeepalive@npm:^4.2.1":
version: 4.6.0
resolution: "agentkeepalive@npm:4.6.0"
dependencies:
humanize-ms: "npm:^1.2.1"
checksum: 10c0/235c182432f75046835b05f239708107138a40103deee23b6a08caee5136873709155753b394ec212e49e60e94a378189562cb01347765515cff61b692c69187
languageName: node
linkType: hard
"ai-meeting-transcript@workspace:.":
version: 0.0.0-use.local
resolution: "ai-meeting-transcript@workspace:."
dependencies:
"@types/node": "npm:^24.7.2"
axios: "npm:^1.12.2"
openai: "npm:^4.28.0"
twenty-sdk: "npm:^0.0.2"
languageName: unknown
linkType: soft
"async-function@npm:^1.0.0":
version: 1.0.0
resolution: "async-function@npm:1.0.0"
checksum: 10c0/669a32c2cb7e45091330c680e92eaeb791bc1d4132d827591e499cd1f776ff5a873e77e5f92d0ce795a8d60f10761dec9ddfe7225a5de680f5d357f67b1aac73
languageName: node
linkType: hard
"async-generator-function@npm:^1.0.0":
version: 1.0.0
resolution: "async-generator-function@npm:1.0.0"
checksum: 10c0/2c50ef856c543ad500d8d8777d347e3c1ba623b93e99c9263ecc5f965c1b12d2a140e2ab6e43c3d0b85366110696f28114649411cbcd10b452a92a2318394186
languageName: node
linkType: hard
"asynckit@npm:^0.4.0":
version: 0.4.0
resolution: "asynckit@npm:0.4.0"
checksum: 10c0/d73e2ddf20c4eb9337e1b3df1a0f6159481050a5de457c55b14ea2e5cb6d90bb69e004c9af54737a5ee0917fcf2c9e25de67777bbe58261847846066ba75bc9d
languageName: node
linkType: hard
"axios@npm:^1.12.2":
version: 1.13.1
resolution: "axios@npm:1.13.1"
dependencies:
follow-redirects: "npm:^1.15.6"
form-data: "npm:^4.0.4"
proxy-from-env: "npm:^1.1.0"
checksum: 10c0/de9c3c6de43d3ee1146d3afe78645f19450cac6a5d7235bef8b8e8eeb705c2e47e2d231dea99cecaec4dae1897c521118ca9413b9d474063c719c4d94c5b9adc
languageName: node
linkType: hard
"call-bind-apply-helpers@npm:^1.0.1, call-bind-apply-helpers@npm:^1.0.2":
version: 1.0.2
resolution: "call-bind-apply-helpers@npm:1.0.2"
dependencies:
es-errors: "npm:^1.3.0"
function-bind: "npm:^1.1.2"
checksum: 10c0/47bd9901d57b857590431243fea704ff18078b16890a6b3e021e12d279bbf211d039155e27d7566b374d49ee1f8189344bac9833dec7a20cdec370506361c938
languageName: node
linkType: hard
"combined-stream@npm:^1.0.8":
version: 1.0.8
resolution: "combined-stream@npm:1.0.8"
dependencies:
delayed-stream: "npm:~1.0.0"
checksum: 10c0/0dbb829577e1b1e839fa82b40c07ffaf7de8a09b935cadd355a73652ae70a88b4320db322f6634a4ad93424292fa80973ac6480986247f1734a1137debf271d5
languageName: node
linkType: hard
"delayed-stream@npm:~1.0.0":
version: 1.0.0
resolution: "delayed-stream@npm:1.0.0"
checksum: 10c0/d758899da03392e6712f042bec80aa293bbe9e9ff1b2634baae6a360113e708b91326594c8a486d475c69d6259afb7efacdc3537bfcda1c6c648e390ce601b19
languageName: node
linkType: hard
"dunder-proto@npm:^1.0.1":
version: 1.0.1
resolution: "dunder-proto@npm:1.0.1"
dependencies:
call-bind-apply-helpers: "npm:^1.0.1"
es-errors: "npm:^1.3.0"
gopd: "npm:^1.2.0"
checksum: 10c0/199f2a0c1c16593ca0a145dbf76a962f8033ce3129f01284d48c45ed4e14fea9bbacd7b3610b6cdc33486cef20385ac054948fefc6272fcce645c09468f93031
languageName: node
linkType: hard
"es-define-property@npm:^1.0.1":
version: 1.0.1
resolution: "es-define-property@npm:1.0.1"
checksum: 10c0/3f54eb49c16c18707949ff25a1456728c883e81259f045003499efba399c08bad00deebf65cccde8c0e07908c1a225c9d472b7107e558f2a48e28d530e34527c
languageName: node
linkType: hard
"es-errors@npm:^1.3.0":
version: 1.3.0
resolution: "es-errors@npm:1.3.0"
checksum: 10c0/0a61325670072f98d8ae3b914edab3559b6caa980f08054a3b872052640d91da01d38df55df797fcc916389d77fc92b8d5906cf028f4db46d7e3003abecbca85
languageName: node
linkType: hard
"es-object-atoms@npm:^1.0.0, es-object-atoms@npm:^1.1.1":
version: 1.1.1
resolution: "es-object-atoms@npm:1.1.1"
dependencies:
es-errors: "npm:^1.3.0"
checksum: 10c0/65364812ca4daf48eb76e2a3b7a89b3f6a2e62a1c420766ce9f692665a29d94fe41fe88b65f24106f449859549711e4b40d9fb8002d862dfd7eb1c512d10be0c
languageName: node
linkType: hard
"es-set-tostringtag@npm:^2.1.0":
version: 2.1.0
resolution: "es-set-tostringtag@npm:2.1.0"
dependencies:
es-errors: "npm:^1.3.0"
get-intrinsic: "npm:^1.2.6"
has-tostringtag: "npm:^1.0.2"
hasown: "npm:^2.0.2"
checksum: 10c0/ef2ca9ce49afe3931cb32e35da4dcb6d86ab02592cfc2ce3e49ced199d9d0bb5085fc7e73e06312213765f5efa47cc1df553a6a5154584b21448e9fb8355b1af
languageName: node
linkType: hard
"event-target-shim@npm:^5.0.0":
version: 5.0.1
resolution: "event-target-shim@npm:5.0.1"
checksum: 10c0/0255d9f936215fd206156fd4caa9e8d35e62075d720dc7d847e89b417e5e62cf1ce6c9b4e0a1633a9256de0efefaf9f8d26924b1f3c8620cffb9db78e7d3076b
languageName: node
linkType: hard
"follow-redirects@npm:^1.15.6":
version: 1.15.11
resolution: "follow-redirects@npm:1.15.11"
peerDependenciesMeta:
debug:
optional: true
checksum: 10c0/d301f430542520a54058d4aeeb453233c564aaccac835d29d15e050beb33f339ad67d9bddbce01739c5dc46a6716dbe3d9d0d5134b1ca203effa11a7ef092343
languageName: node
linkType: hard
"form-data-encoder@npm:1.7.2":
version: 1.7.2
resolution: "form-data-encoder@npm:1.7.2"
checksum: 10c0/56553768037b6d55d9de524f97fe70555f0e415e781cb56fc457a68263de3d40fadea2304d4beef2d40b1a851269bd7854e42c362107071892cb5238debe9464
languageName: node
linkType: hard
"form-data@npm:^4.0.4":
version: 4.0.4
resolution: "form-data@npm:4.0.4"
dependencies:
asynckit: "npm:^0.4.0"
combined-stream: "npm:^1.0.8"
es-set-tostringtag: "npm:^2.1.0"
hasown: "npm:^2.0.2"
mime-types: "npm:^2.1.12"
checksum: 10c0/373525a9a034b9d57073e55eab79e501a714ffac02e7a9b01be1c820780652b16e4101819785e1e18f8d98f0aee866cc654d660a435c378e16a72f2e7cac9695
languageName: node
linkType: hard
"formdata-node@npm:^4.3.2":
version: 4.4.1
resolution: "formdata-node@npm:4.4.1"
dependencies:
node-domexception: "npm:1.0.0"
web-streams-polyfill: "npm:4.0.0-beta.3"
checksum: 10c0/74151e7b228ffb33b565cec69182694ad07cc3fdd9126a8240468bb70a8ba66e97e097072b60bcb08729b24c7ce3fd3e0bd7f1f80df6f9f662b9656786e76f6a
languageName: node
linkType: hard
"function-bind@npm:^1.1.2":
version: 1.1.2
resolution: "function-bind@npm:1.1.2"
checksum: 10c0/d8680ee1e5fcd4c197e4ac33b2b4dce03c71f4d91717292785703db200f5c21f977c568d28061226f9b5900cbcd2c84463646134fd5337e7925e0942bc3f46d5
languageName: node
linkType: hard
"generator-function@npm:^2.0.0":
version: 2.0.1
resolution: "generator-function@npm:2.0.1"
checksum: 10c0/8a9f59df0f01cfefafdb3b451b80555e5cf6d76487095db91ac461a0e682e4ff7a9dbce15f4ecec191e53586d59eece01949e05a4b4492879600bbbe8e28d6b8
languageName: node
linkType: hard
"get-intrinsic@npm:^1.2.6":
version: 1.3.1
resolution: "get-intrinsic@npm:1.3.1"
dependencies:
async-function: "npm:^1.0.0"
async-generator-function: "npm:^1.0.0"
call-bind-apply-helpers: "npm:^1.0.2"
es-define-property: "npm:^1.0.1"
es-errors: "npm:^1.3.0"
es-object-atoms: "npm:^1.1.1"
function-bind: "npm:^1.1.2"
generator-function: "npm:^2.0.0"
get-proto: "npm:^1.0.1"
gopd: "npm:^1.2.0"
has-symbols: "npm:^1.1.0"
hasown: "npm:^2.0.2"
math-intrinsics: "npm:^1.1.0"
checksum: 10c0/9f4ab0cf7efe0fd2c8185f52e6f637e708f3a112610c88869f8f041bb9ecc2ce44bf285dfdbdc6f4f7c277a5b88d8e94a432374d97cca22f3de7fc63795deb5d
languageName: node
linkType: hard
"get-proto@npm:^1.0.1":
version: 1.0.1
resolution: "get-proto@npm:1.0.1"
dependencies:
dunder-proto: "npm:^1.0.1"
es-object-atoms: "npm:^1.0.0"
checksum: 10c0/9224acb44603c5526955e83510b9da41baf6ae73f7398875fba50edc5e944223a89c4a72b070fcd78beb5f7bdda58ecb6294adc28f7acfc0da05f76a2399643c
languageName: node
linkType: hard
"gopd@npm:^1.2.0":
version: 1.2.0
resolution: "gopd@npm:1.2.0"
checksum: 10c0/50fff1e04ba2b7737c097358534eacadad1e68d24cccee3272e04e007bed008e68d2614f3987788428fd192a5ae3889d08fb2331417e4fc4a9ab366b2043cead
languageName: node
linkType: hard
"has-symbols@npm:^1.0.3, has-symbols@npm:^1.1.0":
version: 1.1.0
resolution: "has-symbols@npm:1.1.0"
checksum: 10c0/dde0a734b17ae51e84b10986e651c664379018d10b91b6b0e9b293eddb32f0f069688c841fb40f19e9611546130153e0a2a48fd7f512891fb000ddfa36f5a20e
languageName: node
linkType: hard
"has-tostringtag@npm:^1.0.2":
version: 1.0.2
resolution: "has-tostringtag@npm:1.0.2"
dependencies:
has-symbols: "npm:^1.0.3"
checksum: 10c0/a8b166462192bafe3d9b6e420a1d581d93dd867adb61be223a17a8d6dad147aa77a8be32c961bb2f27b3ef893cae8d36f564ab651f5e9b7938ae86f74027c48c
languageName: node
linkType: hard
"hasown@npm:^2.0.2":
version: 2.0.2
resolution: "hasown@npm:2.0.2"
dependencies:
function-bind: "npm:^1.1.2"
checksum: 10c0/3769d434703b8ac66b209a4cca0737519925bbdb61dd887f93a16372b14694c63ff4e797686d87c90f08168e81082248b9b028bad60d4da9e0d1148766f56eb9
languageName: node
linkType: hard
"humanize-ms@npm:^1.2.1":
version: 1.2.1
resolution: "humanize-ms@npm:1.2.1"
dependencies:
ms: "npm:^2.0.0"
checksum: 10c0/f34a2c20161d02303c2807badec2f3b49cbfbbb409abd4f95a07377ae01cfe6b59e3d15ac609cffcd8f2521f0eb37b7e1091acf65da99aa2a4f1ad63c21e7e7a
languageName: node
linkType: hard
"math-intrinsics@npm:^1.1.0":
version: 1.1.0
resolution: "math-intrinsics@npm:1.1.0"
checksum: 10c0/7579ff94e899e2f76ab64491d76cf606274c874d8f2af4a442c016bd85688927fcfca157ba6bf74b08e9439dc010b248ce05b96cc7c126a354c3bae7fcb48b7f
languageName: node
linkType: hard
"mime-db@npm:1.52.0":
version: 1.52.0
resolution: "mime-db@npm:1.52.0"
checksum: 10c0/0557a01deebf45ac5f5777fe7740b2a5c309c6d62d40ceab4e23da9f821899ce7a900b7ac8157d4548ddbb7beffe9abc621250e6d182b0397ec7f10c7b91a5aa
languageName: node
linkType: hard
"mime-types@npm:^2.1.12":
version: 2.1.35
resolution: "mime-types@npm:2.1.35"
dependencies:
mime-db: "npm:1.52.0"
checksum: 10c0/82fb07ec56d8ff1fc999a84f2f217aa46cb6ed1033fefaabd5785b9a974ed225c90dc72fff460259e66b95b73648596dbcc50d51ed69cdf464af2d237d3149b2
languageName: node
linkType: hard
"ms@npm:^2.0.0":
version: 2.1.3
resolution: "ms@npm:2.1.3"
checksum: 10c0/d924b57e7312b3b63ad21fc5b3dc0af5e78d61a1fc7cfb5457edaf26326bf62be5307cc87ffb6862ef1c2b33b0233cdb5d4f01c4c958cc0d660948b65a287a48
languageName: node
linkType: hard
"node-domexception@npm:1.0.0":
version: 1.0.0
resolution: "node-domexception@npm:1.0.0"
checksum: 10c0/5e5d63cda29856402df9472335af4bb13875e1927ad3be861dc5ebde38917aecbf9ae337923777af52a48c426b70148815e890a5d72760f1b4d758cc671b1a2b
languageName: node
linkType: hard
"node-fetch@npm:^2.6.7":
version: 2.7.0
resolution: "node-fetch@npm:2.7.0"
dependencies:
whatwg-url: "npm:^5.0.0"
peerDependencies:
encoding: ^0.1.0
peerDependenciesMeta:
encoding:
optional: true
checksum: 10c0/b55786b6028208e6fbe594ccccc213cab67a72899c9234eb59dba51062a299ea853210fcf526998eaa2867b0963ad72338824450905679ff0fa304b8c5093ae8
languageName: node
linkType: hard
"openai@npm:^4.28.0":
version: 4.104.0
resolution: "openai@npm:4.104.0"
dependencies:
"@types/node": "npm:^18.11.18"
"@types/node-fetch": "npm:^2.6.4"
abort-controller: "npm:^3.0.0"
agentkeepalive: "npm:^4.2.1"
form-data-encoder: "npm:1.7.2"
formdata-node: "npm:^4.3.2"
node-fetch: "npm:^2.6.7"
peerDependencies:
ws: ^8.18.0
zod: ^3.23.8
peerDependenciesMeta:
ws:
optional: true
zod:
optional: true
bin:
openai: bin/cli
checksum: 10c0/c4f2e837684ed96b8cec58c65a584646d667c69918f29052775e2e8c05ff5c860d8b58214a7770bc6895ca8602480420c1db6a5392dd250179eb0b91c2b19a2f
languageName: node
linkType: hard
"proxy-from-env@npm:^1.1.0":
version: 1.1.0
resolution: "proxy-from-env@npm:1.1.0"
checksum: 10c0/fe7dd8b1bdbbbea18d1459107729c3e4a2243ca870d26d34c2c1bcd3e4425b7bcc5112362df2d93cc7fb9746f6142b5e272fd1cc5c86ddf8580175186f6ad42b
languageName: node
linkType: hard
"tr46@npm:~0.0.3":
version: 0.0.3
resolution: "tr46@npm:0.0.3"
checksum: 10c0/047cb209a6b60c742f05c9d3ace8fa510bff609995c129a37ace03476a9b12db4dbf975e74600830ef0796e18882b2381fb5fb1f6b4f96b832c374de3ab91a11
languageName: node
linkType: hard
"twenty-sdk@npm:^0.0.2":
version: 0.0.2
resolution: "twenty-sdk@npm:0.0.2"
checksum: 10c0/99e6fe86059d847b548c1f03e0f0c59a4d540caf1d28dd4500f1f5f0094196985ded955801274de9e72ff03e3d1f41e9a509b4c2c5a02ffc8a027277b1e35d8e
languageName: node
linkType: hard
"undici-types@npm:~5.26.4":
version: 5.26.5
resolution: "undici-types@npm:5.26.5"
checksum: 10c0/bb673d7876c2d411b6eb6c560e0c571eef4a01c1c19925175d16e3a30c4c428181fb8d7ae802a261f283e4166a0ac435e2f505743aa9e45d893f9a3df017b501
languageName: node
linkType: hard
"undici-types@npm:~7.16.0":
version: 7.16.0
resolution: "undici-types@npm:7.16.0"
checksum: 10c0/3033e2f2b5c9f1504bdc5934646cb54e37ecaca0f9249c983f7b1fc2e87c6d18399ebb05dc7fd5419e02b2e915f734d872a65da2e3eeed1813951c427d33cc9a
languageName: node
linkType: hard
"web-streams-polyfill@npm:4.0.0-beta.3":
version: 4.0.0-beta.3
resolution: "web-streams-polyfill@npm:4.0.0-beta.3"
checksum: 10c0/a9596779db2766990117ed3a158e0b0e9f69b887a6d6ba0779940259e95f99dc3922e534acc3e5a117b5f5905300f527d6fbf8a9f0957faf1d8e585ce3452e8e
languageName: node
linkType: hard
"webidl-conversions@npm:^3.0.0":
version: 3.0.1
resolution: "webidl-conversions@npm:3.0.1"
checksum: 10c0/5612d5f3e54760a797052eb4927f0ddc01383550f542ccd33d5238cfd65aeed392a45ad38364970d0a0f4fea32e1f4d231b3d8dac4a3bdd385e5cf802ae097db
languageName: node
linkType: hard
"whatwg-url@npm:^5.0.0":
version: 5.0.0
resolution: "whatwg-url@npm:5.0.0"
dependencies:
tr46: "npm:~0.0.3"
webidl-conversions: "npm:^3.0.0"
checksum: 10c0/1588bed84d10b72d5eec1d0faa0722ba1962f1821e7539c535558fb5398d223b0c50d8acab950b8c488b4ba69043fd833cc2697056b167d8ad46fac3995a55d5
languageName: node
linkType: hard
@@ -0,0 +1,109 @@
# Fireflies Integration Environment Variables
# Copy this file to .env and fill in your actual values
# =============================================================================
# REQUIRED: Authentication & API Keys
# =============================================================================
# Secret key for HMAC signature verification of Fireflies webhooks
# This must match the secret configured in your Fireflies webhook settings
# Get this from: https://app.fireflies.ai/settings#DeveloperSettings
FIREFLIES_WEBHOOK_SECRET=your_webhook_secret_here
# Fireflies API key for fetching meeting data from GraphQL API
# Get this from: https://app.fireflies.ai/settings#DeveloperSettings
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
# Twenty CRM API key for authentication
# Generate this from your Twenty instance: Settings > Developers > API Keys
TWENTY_API_KEY=your_twenty_api_key_here
# =============================================================================
# Server Configuration
# =============================================================================
# Twenty CRM server URL
# Use http://localhost:3000 for local development
# Use your production URL for deployed instances
SERVER_URL=http://localhost:3000
# =============================================================================
# Contact Management
# =============================================================================
# Automatically create contacts for unknown participants (true/false)
# If true, new Person records will be created for meeting participants not found in CRM
# If false, only meetings with existing contacts will be fully processed
AUTO_CREATE_CONTACTS=true
# =============================================================================
# Summary Processing Configuration
# =============================================================================
# Strategy for handling async summary generation
# Options:
# - immediate_with_retry: Attempts immediate fetch with retry logic (RECOMMENDED)
# - delayed_polling: Schedules background polling for summaries
# - basic_only: Creates records without waiting for summaries
FIREFLIES_SUMMARY_STRATEGY=immediate_with_retry
# Number of retry attempts when fetching summary data
# Used with immediate_with_retry strategy
# Recommended: 3-5 attempts (summaries can take up to 10 minutes but rate limit is low)
FIREFLIES_RETRY_ATTEMPTS=5
# Delay in milliseconds between retry attempts (with exponential backoff)
# Each retry will wait: RETRY_DELAY * attempt_number
# Example: 120000ms means 2min, 4min, 6min... for extended backoff
# Total max time with 5 attempts: ~15 minutes
FIREFLIES_RETRY_DELAY=120000
# Polling interval in milliseconds for delayed_polling strategy
# How often to check if summary is ready
# Recommended: 60000 (60 seconds) for extended processing
FIREFLIES_POLL_INTERVAL=120000
# Maximum number of polling attempts for delayed_polling strategy
# Total max time = POLL_INTERVAL * MAX_POLLS
# Example: 2min * 5 = 10 minutes maximum
FIREFLIES_MAX_POLLS=5
# =============================================================================
# Debugging & Logging
# =============================================================================
# Log level: silent, error, warn, info, debug (default: error)
# Controls verbosity of console output
# - silent: No console output
# - error: Only errors (production default)
# - warn: Warnings and errors
# - info: Info, warnings, and errors
# - debug: All logs including detailed debugging
LOG_LEVEL=error
# =============================================================================
# Configuration Notes
# =============================================================================
#
# Webhook Setup:
# 1. Configure your Fireflies webhook at: https://app.fireflies.ai/settings#DeveloperSettings
# 2. Webhook URL: https://your-twenty-instance.com/s/webhook/fireflies
# 3. Event Type: "Transcription completed"
# 4. Secret: Same value as FIREFLIES_WEBHOOK_SECRET above, genereate it there
#
# Summary Strategy Guide:
# - immediate_with_retry: Best for most use cases - fast with reliability
# - delayed_polling: Use if your server is heavily loaded
# - basic_only: Use if you only need transcript links without AI summaries
#
# Performance Tuning:
# - Fireflies summaries can take 5-15 minutes to generate after transcription
# - Use 30+ retry attempts with 30s delay for 15-minute coverage
# - Consider delayed_polling strategy for heavily loaded servers
# - Monitor DEBUG_LOGS to tune timing for your Fireflies account
#
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -0,0 +1,96 @@
# Changelog
## [0.2.2] - 2025-11-04
### Added
- **Enhanced logging system**: Introduced configurable `AppLogger` class with log level support (debug, info, warn, error, silent)
- Environment-based log level configuration via `LOG_LEVEL` environment variable
- Test environment detection to prevent log noise during testing
- Context-aware logging with proper prefixes for better debugging
- **Improved error handling**: Enhanced webhook signature verification with detailed debug logging
- **Better debugging capabilities**: Added comprehensive logging throughout webhook processing pipeline
### Enhanced
- **Webhook signature verification**: Improved signature validation with detailed logging for troubleshooting
- **Error messages**: More descriptive error logging for failed operations and security violations
- **Development experience**: Better debugging information for webhook processing and API interactions
## [0.2.1] - 2025-11-03
### Added
- **Import status tracking**: Added four new meeting fields to track import status and failure handling:
- `importStatus` (SELECT) - Tracks SUCCESS, FAILED, PENDING, RETRYING states
- `importError` (TEXT) - Stores error messages when imports fail
- `lastImportAttempt` (DATE_TIME) - Timestamp of the last import attempt
- `importAttempts` (NUMBER) - Counter for number of import attempts
- **Automatic failure tracking**: Enhanced webhook handler to automatically create failed meeting records when processing fails
- **Failed meeting formatter**: Added `toFailedMeetingCreateInput()` method to create standardized failed meeting records
### Enhanced
- **Meeting type definition**: Extended `MeetingCreateInput` type with import tracking fields
- **Success status tracking**: Successful meeting imports now automatically set `importStatus: 'SUCCESS'` and track timestamps
- **Error handling**: Webhook processing failures are now captured and stored as meeting records for visibility and potential retry
## [0.2.0] - 2025-11-03
### Changed
- **Major refactoring**: Split monolithic `receive-fireflies-notes.ts` into modular architecture:
- `fireflies-api-client.ts` - Fireflies GraphQL API integration with retry logic
- `twenty-crm-service.ts` - Twenty CRM operations (contacts, notes, meetings)
- `formatters.ts` - Meeting and note body formatting
- `webhook-handler.ts` - Main webhook orchestration
- `webhook-validator.ts` - HMAC signature verification
- `utils.ts` - Shared utility functions
- `types.ts` - Centralized type definitions
- **Schema update**: Changed Meeting `notes` field from `RICH_TEXT` to `RELATION` type linking to Note object
- Enhanced participant extraction from multiple Fireflies API data sources (participants, meeting_attendees, speakers, meeting_attendance)
- Improved organizer email matching with name-based heuristics
- Updated note creation to use `bodyV2.markdown` format instead of legacy `body` field
- Modernized Meeting object schema with proper link field types for transcriptUrl and recordingUrl
- Enhanced test suite with improved mocking for new modular structure
- **Configuration optimization**: Reduced default retry attempts from 30 to 5 with increased delay (120s) to better respect Fireflies API rate limits (50 requests/day for free/pro plans)
- Updated field setup script to support relation field creation with Note object
- Restructured exports: types now exported from `types.ts`, runtime functions from `index.ts`
- Updated import paths in action handlers to use centralized index exports
- Added TypeScript path mappings for `twenty-sdk` in workspace configuration
### Added
- `createNoteTarget` method for linking notes to multiple participants
- Support for extracting participants from extended Fireflies API response formats
- Better organizer identification logic matching email usernames to speaker names
- `axios` dependency for improved HTTP client capabilities
- API subscription plan documentation highlighting rate limit differences (50/day vs 60/minute)
- Enhanced README with rate limiting guidance and configuration documentation
- Relation field creation support in field provisioning script
### Fixed
- Note linking now properly associates a single note with multiple participants in 1:1 meetings
- Participant extraction handles missing email addresses gracefully
- Improved handling of various Fireflies participant data structures
- Test mocks updated to use string format for participants (`"Name <email>"`) matching Fireflies API response format
- Test assertions updated to validate `bodyV2.markdown` instead of deprecated `body` field
## [0.1.0] - 2025-11-02
### Added
- HMAC SHA-256 signature verification for incoming Fireflies webhooks
- Fireflies GraphQL client with retry logic, timeout handling, and summary readiness detection
- Summary-focused meeting processing that extracts action items, sentiment, keywords, and transcript/recording links
- Scripted custom field provisioning via `yarn setup:fields`
- Local webhook testing workflow via `yarn test:webhook`
- Comprehensive Jest suite (15 tests) covering authentication, API integration, summary strategies, and error handling
### Changed
- Replaced legacy JSON manifests with TypeScript configuration:
- `application.config.ts` now declares app metadata and configuration variables
- `src/objects/meeting.ts` defines the Meeting object via `@ObjectMetadata`
- `src/actions/receive-fireflies-notes.ts` exports the Fireflies webhook action plus its runtime config
- Updated documentation (README, Deployment Guide, Testing) to reflect the new project layout and workflows
- Switched utility scripts to `tsx` and aligned package management with the hello-world example
### Fixed
- Resolved real-world Fireflies payload mismatch by adopting the minimal webhook schema
- Replaced body-based secrets with header-driven HMAC verification
- Ensured graceful degradation when summaries are pending or Fireflies is temporarily unavailable
@@ -0,0 +1,277 @@
# Fireflies
Automatically captures meeting notes with AI-generated summaries and insights from Fireflies.ai into your Twenty CRM.
## Integration Overview
**Fireflies webhook → Fireflies API → Twenty CRM with summary-focused insights**
- **Summary-first approach** - Prioritizes action items, keywords, and sentiment over raw transcripts
- **HMAC signature verification** - Secure webhook authentication
- **Two-phase architecture** - Webhook notification → API data fetch → CRM record creation
- **Contact identification** - Matches participants to existing contacts or creates new ones
- **One-on-one meetings** (2 people) → Individual notes linked to each contact
- **Multi-party meetings** (3+ people) → Meeting records with all attendees
- **Business intelligence extraction** - Action items, sentiment scores, topics, meeting types
- **Smart retry logic** - Handles async summary generation with exponential backoff
- **Links transcripts and recordings** - Easy access to full Fireflies content
- **Duplicate prevention** - Checks for existing meetings by title
## API Access by Subscription Plan
Fireflies API access varies significantly by subscription tier:
| 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 |
**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.
**Pro Plan Limitation:** Despite "unlimited" AI summaries, the 50 requests/day limit severely constrains production usage for meeting-heavy organizations.
## What Gets Captured
### Summary & Insights
- **Action Items** - Concrete next steps and commitments
- **Keywords** - Key topics and themes discussed
- **Overview** - Executive summary of the meeting
- **Topics Discussed** - Main discussion points
- **Meeting Type** - Context (sales call, standup, demo, etc.)
### Analytics
- **Sentiment Analysis** - Positive/negative/neutral percentages for deal health
- **Engagement Metrics** - Participation levels (future)
### Resources
- **Transcript Link** - Quick access to full Fireflies transcript
- **Recording Link** - Video/audio recording when available
## Quick Start
### Installation
```bash
# Step 1: Authenticate with Twenty
npx twenty-cli auth login
# Step 2: Sync the app to create Meeting object
npx twenty-cli app sync packages/twenty-apps/fireflies
# Step 3: Install dependencies
yarn install
# Step 4: Add custom fields
yarn setup:fields
```
(TODO: change when fields setup internal support)
### Configuration
⚠️ **Important**: The integration uses **conservative retry settings** to respect Fireflies' 50 requests/day API limit with free/pro plans. You may increase for more reactivity with higher plans.
**Required Environment Variables:**
```bash
FIREFLIES_API_KEY=your_api_key # From Fireflies settings
TWENTY_API_KEY=your_api_key # From Twenty CRM settings
SERVER_URL=https://your-domain.twenty.com
```
**Optional (Recommended):**
```bash
FIREFLIES_WEBHOOK_SECRET=your_secret # For webhook security
```
📖 **For detailed configuration, troubleshooting, and rate limit management**, see [WEBHOOK_CONFIGURATION.md](./WEBHOOK_CONFIGURATION.md)
### What Gets Created
#### Basic Installation (Step 2)
The `app sync` command creates:
- ✅ Meeting object with basic `name` field
- ✅ Webhook endpoint at `/s/webhook/fireflies`
#### After Custom Fields Setup (Step 4)
The `setup:fields` script adds 13 custom fields to store rich Fireflies data:
| Field Name | Type | Label | Description |
|------------|------|-------|-------------|
| `notes` | RICH_TEXT | Meeting Notes | AI-generated summary with overview, topics, action items, and insights |
| `meetingDate` | DATE_TIME | Meeting Date | Date and time when the meeting occurred |
| `duration` | NUMBER | Duration (minutes) | Meeting duration in minutes |
| `meetingType` | TEXT | Meeting Type | Type of meeting (e.g., Sales Call, Sprint Planning, 1:1) |
| `keywords` | TEXT | Keywords | Key topics and themes discussed (comma-separated) |
| `sentimentScore` | NUMBER | Sentiment Score | Overall meeting sentiment (0-1 scale, 1 = most positive) |
| `positivePercent` | NUMBER | Positive % | Percentage of positive sentiment in conversation |
| `negativePercent` | NUMBER | Negative % | Percentage of negative sentiment in conversation |
| `actionItemsCount` | NUMBER | Action Items | Number of action items identified |
| `transcriptUrl` | LINKS | Transcript URL | Link to full transcript in Fireflies |
| `recordingUrl` | LINKS | Recording URL | Link to video/audio recording in Fireflies |
| `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
### Required Environment Variables
Check [.env.example](./.env.example)
### Summary Processing Strategies
| Strategy | Description | Use Case |
|----------|-------------|----------|
| `immediate_only` | Single fetch attempt, no retries | Fast processing, accept missing summaries if not ready |
| `immediate_with_retry` | Attempts immediate fetch, retries with backoff | **Recommended** - Balances speed and reliability |
| `delayed_polling` | Schedules background polling | For heavily loaded systems |
| `basic_only` | Creates records without waiting for summaries | For basic transcript archival only |
## Webhook Setup
### Step 1: Get Your Webhook URL
Your webhook endpoint will be:
```
https://your-twenty-instance.com/s/webhook/fireflies
```
### Step 2: Configure Fireflies Webhook
1. Log into Fireflies.ai
2. https://app.fireflies.ai/settings#DeveloperSettings
4. Enter your webhook URL
5. Set **Secret**: Generate from there and set value of `FIREFLIES_WEBHOOK_SECRET`
6. Save configuration
### Step 3: Verify Webhook
The integration uses **HMAC SHA-256 signature verification**:
- Fireflies sends `x-hub-signature` header
- Twenty verifies signature using your webhook secret
- Invalid signatures are rejected immediately
## Development
```bash
# Run tests
npm test
# Run tests in watch mode
npm run test -- --watch
# Development mode with live sync
npx twenty-cli app dev
# Type checking
npx tsc --noEmit
```
## Testing
The integration includes comprehensive test coverage:
```bash
# Run all tests
npm test
# Run specific test suite
npm test -- fireflies-webhook.spec.ts
# Run with coverage
npm test -- --coverage
```
### Test Coverage
- HMAC signature verification
- Fireflies GraphQL API integration
- Summary processing with retry logic
- Summary-focused CRM record creation
- One-on-one vs multi-party meeting detection
- Contact matching and creation
- Duplicate prevention
- Error handling and resilience
## CRM Record Structure
### One-on-One Meeting Note Example
```markdown
# Meeting: Product Demo with Client (Sales Call)
**Date:** Monday, November 2, 2024, 02:00 PM
**Duration:** 30 minutes
**Participants:** Sarah Sales, John Client
## Overview
Successful product demonstration with positive client feedback.
Client expressed strong interest in the enterprise plan.
## Key Topics
- product features
- pricing discussion
- integration capabilities
- support options
## Action Items
- Follow up with pricing proposal by Friday
- Schedule technical deep-dive next week
- Share case studies from similar clients
## Insights
**Keywords:** product demo, pricing, technical requirements, integration
**Sentiment:** 75% positive, 10% negative, 15% neutral
**Meeting Type:** Sales Call
## Resources
[View Full Transcript](https://app.fireflies.ai/transcript/xxx)
[Watch Recording](https://app.fireflies.ai/recording/xxx)
```
### Multi-Party Meeting Record
- Meeting object with title, date, and all attendees
- Summary stored as meeting notes (structure same as above)
- Action items potentially converted to separate tasks (future)
- Keywords as tags/categories (future)
## 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:
### AI-Powered Insights
- **Extract pain points, objections & buying signals** automatically from transcripts
- **Calculate deal health scores** based on conversation sentiment trends
- **Auto-create contextualized tasks** with AI-suggested next steps and priorities
- **Proactively flag at-risk deals** when negative signals appear
- **Track conversation patterns** that correlate with deal success
### Enhanced Analytics
- **Action item completion tracking** across deals
- **Sentiment trend analysis** over time for account health
- **Speaking time analysis** for meeting engagement insights
- **Topic clustering** for product/feature interest patterns
### Workflow Automation
- **Auto-assign follow-up tasks** based on action items
- **Smart notifications** for urgent follow-ups
- **Deal stage progression** based on meeting outcomes
- **Competitive intelligence** extraction from conversations
**Integration**: Fireflies webhook → AI processing layer → Enhanced Twenty records
*This would require the current MVP to be stabilized and discussions about intelligence layer architecture and data privacy considerations.*
@@ -0,0 +1,68 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
const config: ApplicationConfig = {
universalIdentifier: 'a4df0c0f-c65e-44e5-8436-24814182d4ac',
displayName: 'Fireflies',
description: 'Sync Fireflies meeting summaries, sentiment, and action items into Twenty.',
icon: 'IconMicrophone',
applicationVariables: {
FIREFLIES_WEBHOOK_SECRET: {
universalIdentifier: 'f51f7646-be9f-4ba9-9b75-160dd288cd0c',
description: 'Secret key for verifying Fireflies webhook signatures',
isSecret: true,
},
FIREFLIES_API_KEY: {
universalIdentifier: 'faa41f07-b28e-4500-b1c0-ce4b3d27924c',
description: 'Fireflies GraphQL API key used to fetch meeting summaries',
isSecret: true,
},
TWENTY_API_KEY: {
universalIdentifier: '02756551-5bf7-4fb2-8e08-1f622008d305',
description: 'Twenty API key used when running scripts locally',
isSecret: true,
},
SERVER_URL: {
universalIdentifier: '9b3a5e8e-5973-4e6b-a059-2966075652aa',
description: 'Base URL for the Twenty workspace (default: http://localhost:3000)',
value: 'http://localhost:3000',
},
AUTO_CREATE_CONTACTS: {
universalIdentifier: 'c4fa946e-e06b-4d54-afb6-288b0ac75bdf',
description: 'Whether to auto-create contacts for unknown participants',
value: 'true',
},
LOG_LEVEL: {
universalIdentifier: '2b019cf1-d198-48dd-943e-110571aa541e',
description: 'Log level: silent, error, warn, info, debug (default: error)',
value: 'error',
},
FIREFLIES_SUMMARY_STRATEGY: {
universalIdentifier: '562b43d9-cd47-4ec1-ae16-5cc7ebc9729b',
description: 'Summary fetch strategy: immediate_only, immediate_with_retry, delayed_polling, or basic_only',
value: 'immediate_with_retry',
},
FIREFLIES_RETRY_ATTEMPTS: {
universalIdentifier: '670ca203-01ce-4ae8-8294-eb38b29434f2',
description: 'Number of retry attempts when fetching summaries',
value: '3',
},
FIREFLIES_RETRY_DELAY: {
universalIdentifier: '2e8ccb82-9390-47ba-b628-ca2726931bce',
description: 'Delay in milliseconds between retry attempts',
value: '5000',
},
FIREFLIES_POLL_INTERVAL: {
universalIdentifier: '904538f7-7bec-4ee6-9bac-5d43c619b667',
description: 'Polling interval (ms) when using delayed polling strategy',
value: '30000',
},
FIREFLIES_MAX_POLLS: {
universalIdentifier: '84d54c97-5572-4c01-9039-764ab3aa87b8',
description: 'Maximum number of polling attempts when waiting for summaries',
value: '10',
},
},
};
export default config;
@@ -0,0 +1,23 @@
const jestConfig = {
displayName: 'fireflies',
preset: 'ts-jest',
testEnvironment: 'node',
moduleFileExtensions: ['ts', 'js'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
testMatch: [
'<rootDir>/src/**/__tests__/**/*.(test|spec).{js,ts}',
'<rootDir>/src/**/?(*.)(test|spec).{js,ts}',
],
setupFilesAfterEnv: [
'<rootDir>/src/__tests__/setup.ts'
],
collectCoverageFrom: [
'src/**/*.{ts,js}',
'!src/**/*.d.ts',
],
coverageDirectory: './coverage',
};
export default jestConfig;
@@ -0,0 +1,29 @@
{
"name": "fireflies",
"version": "0.2.2",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"scripts": {
"test": "jest",
"setup:fields": "tsx scripts/add-meeting-fields.ts",
"test:webhook": "tsx scripts/test-webhook.ts"
},
"dependencies": {
"axios": "^1.13.1",
"dotenv": "^16.3.1",
"twenty-sdk": "0.0.3"
},
"devDependencies": {
"@types/jest": "^29.5.5",
"@types/node": "^24.9.2",
"jest": "^29.7.0",
"ts-jest": "^29.1.1",
"tsx": "^4.19.3",
"typescript": "^5.9.3"
}
}
@@ -0,0 +1,49 @@
{
"name": "fireflies",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "packages/twenty-apps/fireflies/src",
"projectType": "application",
"tags": [
"scope:apps"
],
"targets": {
"test": {
"executor": "@nx/jest:jest",
"outputs": [
"{workspaceRoot}/coverage/{projectRoot}"
],
"options": {
"jestConfig": "packages/twenty-apps/fireflies/jest.config.mjs",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"coverageReporters": ["text"]
}
}
},
"typecheck": {
"executor": "nx:run-commands",
"options": {
"command": "tsc --noEmit --project {projectRoot}/tsconfig.json"
}
},
"lint": {
"executor": "@nx/eslint:lint",
"outputs": [
"{options.outputFile}"
],
"options": {
"lintFilePatterns": [
"packages/twenty-apps/fireflies/**/*.{ts,tsx,js,jsx}"
]
},
"configurations": {
"fix": {
"fix": true
}
}
}
}
}
@@ -0,0 +1,437 @@
/**
* Migration script to add custom fields to the Meeting object
* Run this after: npx twenty-cli app sync packages/twenty-apps/fireflies
*
* Usage: yarn setup:fields
*/
/* 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);
// Load environment variables
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;
if (!API_KEY) {
console.error('❌ Error: TWENTY_API_KEY not found in .env file');
process.exit(1);
}
interface RelationCreationPayload {
targetObjectMetadataId: string;
targetFieldLabel: string;
targetFieldIcon: string;
type: 'ONE_TO_MANY' | 'MANY_TO_ONE';
}
interface FieldOption {
value: string;
label: string;
position: number;
color: string;
}
interface FieldDefinition {
type: string;
name: string;
label: string;
description: string;
icon?: string;
isNullable?: boolean;
relationCreationPayload?: RelationCreationPayload;
options?: FieldOption[];
}
const MEETING_FIELDS: FieldDefinition[] = [
{
type: 'RELATION',
name: 'note',
label: 'Meeting Note',
description: 'Related note with detailed meeting content',
icon: 'IconNotes',
isNullable: true,
},
{
type: 'DATE_TIME',
name: 'meetingDate',
label: 'Meeting Date',
description: 'Date and time when the meeting occurred',
icon: 'IconCalendar',
isNullable: true,
},
{
type: 'NUMBER',
name: 'duration',
label: 'Duration (minutes)',
description: 'Meeting duration in minutes',
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',
isNullable: true,
},
{
type: 'TEXT',
name: 'keywords',
label: 'Keywords',
description: 'Key topics and themes discussed (comma-separated)',
icon: 'IconTags',
isNullable: true,
},
{
type: 'NUMBER',
name: 'sentimentScore',
label: 'Sentiment Score',
description: 'Overall meeting sentiment (0-1 scale, where 1 is most positive)',
icon: 'IconMoodSmile',
isNullable: true,
},
{
type: 'NUMBER',
name: 'positivePercent',
label: 'Positive %',
description: 'Percentage of positive sentiment in conversation',
icon: 'IconThumbUp',
isNullable: true,
},
{
type: 'NUMBER',
name: 'negativePercent',
label: 'Negative %',
description: 'Percentage of negative sentiment in conversation',
icon: 'IconThumbDown',
isNullable: true,
},
{
type: 'NUMBER',
name: 'actionItemsCount',
label: 'Action Items',
description: 'Number of action items identified',
icon: 'IconCheckbox',
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',
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,
},
{
type: 'SELECT',
name: 'importStatus',
label: 'Import Status',
description: 'Status of the meeting import from Fireflies',
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' },
],
},
{
type: 'TEXT',
name: 'importError',
label: 'Import Error',
description: 'Error message if meeting import failed',
icon: 'IconAlertTriangle',
isNullable: true,
},
{
type: 'DATE_TIME',
name: 'lastImportAttempt',
label: 'Last Import Attempt',
description: 'Date and time of the last import attempt',
icon: 'IconClock',
isNullable: true,
},
{
type: 'NUMBER',
name: 'importAttempts',
label: 'Import Attempts',
description: 'Number of times import has been attempted',
icon: 'IconRepeat',
isNullable: true,
},
];
const graphqlRequest = async (query: string, variables: Record<string, unknown> = {}) => {
const response = await fetch(`${SERVER_URL}/metadata`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GraphQL request failed (${response.status}): ${errorText}`);
}
const json = await response.json();
if (json.errors) {
throw new Error(`GraphQL errors: ${JSON.stringify(json.errors, null, 2)}`);
}
return json.data;
};
const findMeetingObject = async () => {
const query = `
query FindMeetingObject {
objects(paging: { first: 200 }) {
edges {
node {
id
nameSingular
labelSingular
labelPlural
fields {
edges {
node {
id
name
label
type
}
}
}
}
}
}
}
`;
const data = await graphqlRequest(query);
const edges = data.objects?.edges || [];
const meetingEdge = edges.find(
(edge: any) => edge?.node?.nameSingular === 'meeting',
);
if (!meetingEdge) {
throw new Error('Meeting object not found. Please run "npx twenty-cli app sync" first.');
}
return meetingEdge.node;
};
const findNoteObject = async () => {
const query = `
query FindObjects {
objects(paging: { first: 100 }) {
edges {
node {
id
nameSingular
labelSingular
}
}
}
}
`;
const data = await graphqlRequest(query);
const edges = data.objects?.edges || [];
const noteEdge = edges.find(
(edge: any) => edge?.node?.nameSingular === 'note',
);
if (!noteEdge) {
throw new Error('Note object not found.');
}
return noteEdge.node;
};
const createField = async (objectId: string, field: FieldDefinition) => {
const mutation = `
mutation CreateField($input: CreateOneFieldMetadataInput!) {
createOneField(input: $input) {
id
name
label
type
description
}
}
`;
const input = {
field: {
type: field.type,
name: field.name,
label: field.label,
description: field.description,
icon: field.icon || 'IconAbc',
isNullable: field.isNullable !== false,
isActive: true,
isCustom: true,
objectMetadataId: objectId,
...(field.relationCreationPayload && {
relationCreationPayload: field.relationCreationPayload,
}),
...(field.options && {
options: field.options,
}),
},
};
try {
const data = await graphqlRequest(mutation, { input });
return data.createOneField;
} catch (error) {
if (error instanceof Error) {
const message = error.message;
if (
message.includes('already exists') ||
message.includes('not available') ||
message.includes('Duplicating')
) {
return null;
}
}
throw error;
}
};
const main = async () => {
console.log('🚀 Adding custom fields to Meeting object...\n');
try {
// Step 1: Find Meeting and Note objects
console.log('📋 Finding Meeting object...');
const meetingObject = await findMeetingObject();
console.log(`✅ Found Meeting object: ${meetingObject.labelSingular ?? meetingObject.nameSingular ?? 'Meeting'} (ID: ${meetingObject.id})\n`);
console.log('📋 Finding Note object...');
const noteObject = await findNoteObject();
console.log(`✅ Found Note object: ${noteObject.labelSingular ?? noteObject.nameSingular ?? 'Note'} (ID: ${noteObject.id})\n`);
// Step 2: Update note field with relationCreationPayload
const fieldsToCreate = MEETING_FIELDS.map(field => {
if (field.name === 'note' && field.type === 'RELATION') {
return {
...field,
relationCreationPayload: {
targetObjectMetadataId: noteObject.id,
targetFieldLabel: 'Meeting',
targetFieldIcon: 'IconCalendarEvent',
type: 'MANY_TO_ONE' as const,
},
};
}
return field;
});
// Step 3: Check existing fields
const existingFields = meetingObject.fields?.edges?.map((edge: any) => edge.node.name) || [];
console.log(`📌 Existing fields: ${existingFields.join(', ')}\n`);
// Step 4: Create custom fields
console.log(' Creating custom fields...\n');
let createdCount = 0;
let failedCount = 0;
let skippedCount = 0;
for (const field of fieldsToCreate) {
try {
if (existingFields.includes(field.name)) {
console.log(` ⏭️ ${field.name} - already exists`);
skippedCount++;
continue;
}
const result = await createField(meetingObject.id, field);
if (result) {
console.log(`${field.name} - created successfully`);
createdCount++;
} else {
console.log(` ⏭️ ${field.name} - skipped (already exists)`);
skippedCount++;
}
} catch (error) {
console.error(`${field.name} - failed: ${error instanceof Error ? error.message : String(error)}`);
failedCount++;
}
}
// Step 4: Summary
console.log('\n' + '='.repeat(60));
console.log('📊 Summary:');
console.log(` ✅ Created: ${createdCount} fields`);
console.log(` ⏭️ Skipped: ${skippedCount} fields`);
console.log(` ❌ Failed: ${failedCount} fields`);
console.log('='.repeat(60));
if (failedCount > 0) {
console.log('\n⚠️ Some fields failed to create. Please check the errors above.');
process.exit(1);
}
if (createdCount === 0 && skippedCount === MEETING_FIELDS.length) {
console.log('\n✨ All fields already exist. Nothing to do!');
} 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');
}
} catch (error) {
console.error('\n❌ Error:', error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
// Run the script
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});
@@ -0,0 +1,208 @@
/* eslint-disable no-console */
/**
* Test script for Fireflies webhook against local Twenty instance
*
* Usage:
* yarn test:webhook
* # or
* npx tsx scripts/test-webhook.ts
*
* Prerequisites:
* 1. Twenty server running on http://localhost:3000
* 2. Fireflies app synced: npx twenty-cli app sync
* 3. Custom fields created: yarn setup:fields
* 4. API key configured (get from Settings > Developers > API Keys)
* 5. Environment variables set (copy .env.example to .env and fill values)
*/
import * as crypto from 'crypto';
import * as dotenv from 'dotenv';
import { existsSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
// Get __dirname equivalent for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load environment variables
const envPath = join(__dirname, '..', '.env');
if (existsSync(envPath)) {
dotenv.config({ path: envPath });
} else {
console.warn('⚠️ .env file not found, using environment variables');
}
// Configuration
const SERVER_URL = process.env.SERVER_URL || 'http://localhost:3000';
const TWENTY_API_KEY = process.env.TWENTY_API_KEY;
const FIREFLIES_WEBHOOK_SECRET = process.env.FIREFLIES_WEBHOOK_SECRET || 'test_secret';
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_WEBHOOK_PAYLOAD = {
meetingId: TEST_MEETING_ID,
eventType: 'Transcription completed',
clientReferenceId: 'test-client-ref',
};
// Mock Fireflies GraphQL API response
const MOCK_FIREFLIES_RESPONSE = {
data: {
meeting: {
id: TEST_MEETING_ID,
title: 'Local Test Meeting',
date: new Date().toISOString(),
duration: 1800, // 30 minutes
participants: [
{ email: 'test1@example.com', name: 'Test User One' },
{ email: 'test2@example.com', name: 'Test User Two' },
],
organizer_email: 'organizer@example.com',
summary: {
action_items: ['Complete integration testing', 'Review webhook logs'],
keywords: ['testing', 'integration', 'webhook'],
overview: 'This is a test meeting to verify the Fireflies webhook integration.',
gist: 'Quick test summary',
topics_discussed: ['Webhook testing', 'Integration verification'],
meeting_type: 'Test',
},
analytics: {
sentiments: {
positive_pct: 75,
negative_pct: 5,
neutral_pct: 20,
},
},
transcript_url: 'https://app.fireflies.ai/transcript/' + TEST_MEETING_ID,
recording_url: 'https://app.fireflies.ai/recording/' + TEST_MEETING_ID,
summary_status: 'ready',
},
},
};
// Generate HMAC signature
const generateHMACSignature = (body: string, secret: string): string => {
const signature = crypto
.createHmac('sha256', secret)
.update(body, 'utf8')
.digest('hex');
return `sha256=${signature}`;
};
// Mock Fireflies API fetch (currently unused but kept for reference)
// In production, you'd need to mock this at the network level
const _mockFirefliesFetch = async (url: string, options?: RequestInit) => {
if (url.includes('graphql.fireflies.ai')) {
// Return mock Fireflies API response
return new Response(JSON.stringify(MOCK_FIREFLIES_RESPONSE), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
// For Twenty API calls, use real fetch
return fetch(url, options);
};
const main = async () => {
console.log('🧪 Testing Fireflies Webhook Against Local Twenty Instance\n');
console.log(`📍 Server URL: ${SERVER_URL}`);
console.log(`🔑 API Key: ${TWENTY_API_KEY ? '✅ Configured' : '❌ Missing'}`);
console.log(`🔐 Webhook Secret: ${FIREFLIES_WEBHOOK_SECRET ? '✅ Configured' : '⚠️ Using test secret'}\n`);
// Validation
if (!TWENTY_API_KEY) {
console.error('❌ Error: TWENTY_API_KEY is required');
console.error(' Get your API key from: Settings > Developers > API Keys');
process.exit(1);
}
// Prepare webhook payload
const body = JSON.stringify(TEST_WEBHOOK_PAYLOAD);
const signature = generateHMACSignature(body, FIREFLIES_WEBHOOK_SECRET);
console.log('📤 Sending webhook payload:');
console.log(JSON.stringify(TEST_WEBHOOK_PAYLOAD, null, 2));
console.log(`\n🔐 HMAC Signature: ${signature}\n`);
// Check if server is reachable
try {
const healthCheck = await fetch(`${SERVER_URL}/api/health`);
if (!healthCheck.ok) {
throw new Error(`Server health check failed: ${healthCheck.status}`);
}
console.log('✅ Server is reachable\n');
} catch {
console.error(`❌ Cannot reach server at ${SERVER_URL}`);
console.error(' Make sure Twenty is running: cd twenty && yarn dev');
process.exit(1);
}
// Note: In a real test, we'd intercept fetch calls
// For now, we'll make a direct request to the webhook endpoint
// The actual serverless function will call Fireflies API
// This test validates the endpoint is accessible
// Webhook endpoint: The route path from manifest is /webhook/fireflies
// Routes are matched after removing /s/ prefix
// So /s/webhook/fireflies should match the route /webhook/fireflies
const webhookUrl = `${SERVER_URL}/s/webhook/fireflies`;
console.log(`📡 Calling webhook endpoint: ${webhookUrl}\n`);
try {
// Note: This will fail because the serverless function needs to call
// Fireflies API, which we can't easily mock at the endpoint level.
// In development, you might want to set FIREFLIES_API_KEY to a test value
// and mock the Fireflies API endpoint separately.
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${TWENTY_API_KEY}`,
'x-hub-signature': signature,
},
body: body,
});
const responseText = await response.text();
let responseData;
try {
responseData = JSON.parse(responseText);
} catch {
responseData = responseText;
}
console.log(`📥 Response Status: ${response.status} ${response.statusText}`);
console.log('📥 Response Body:');
console.log(JSON.stringify(responseData, null, 2));
if (response.ok) {
console.log('\n✅ Webhook test completed successfully!');
console.log('\n📋 Next steps:');
console.log(' 1. Check Twenty CRM for new Meeting/Note records');
console.log(' 2. Verify custom fields are populated');
console.log(' 3. Check server logs for any errors');
} else {
console.log('\n⚠️ Webhook returned an error status');
console.log(' This might be expected if Fireflies API key is not configured');
console.log(' or if the meeting data fetch fails.');
}
} catch (error) {
console.error('\n❌ Error calling webhook:');
console.error(error instanceof Error ? error.message : String(error));
console.error('\n💡 Troubleshooting:');
console.error(' 1. Ensure Twenty server is running');
console.error(' 2. Ensure app is synced: npx twenty-cli app sync');
console.error(' 3. Check API key is valid');
console.error(' 4. Verify webhook endpoint exists');
process.exit(1);
}
};
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});
@@ -0,0 +1,426 @@
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,
};
}
}
@@ -0,0 +1,227 @@
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,
};
}
}
@@ -0,0 +1,10 @@
export { config, main } from './receive-fireflies-notes';
export type {
FirefliesMeetingData,
FirefliesParticipant,
FirefliesWebhookPayload,
ProcessResult,
SummaryFetchConfig,
SummaryStrategy
} from './types';
@@ -0,0 +1,95 @@
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);
};
@@ -0,0 +1,28 @@
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,
},
],
};
@@ -0,0 +1,570 @@
import { createLogger } from './logger';
import type {
Contact,
CreateMeetingResponse,
CreateNoteResponse,
CreatePersonResponse,
FindMeetingResponse,
FindPeopleResponse,
FirefliesParticipant,
GraphQLResponse,
IdNode,
MeetingCreateInput,
} from './types';
const logger = createLogger('20 CRM Service');
export class TwentyCrmService {
private apiKey: string;
private apiUrl: string;
private isTestEnvironment: boolean;
constructor(apiKey: string, apiUrl: string) {
if (!apiKey) {
logger.critical('TWENTY_API_KEY is required but not provided - this is a critical configuration error');
throw new Error('TWENTY_API_KEY is required');
}
this.apiKey = apiKey;
this.apiUrl = apiUrl;
this.isTestEnvironment = process.env.NODE_ENV === 'test' || process.env.JEST_WORKER_ID !== undefined;
}
async findExistingMeeting(title: string): Promise<IdNode | undefined> {
const query = `
query FindMeeting($title: String!) {
meetings(filter: { name: { eq: $title } }) {
edges { node { id } }
}
}
`;
const variables = { title };
const response = await this.gqlRequest<FindMeetingResponse>(query, variables);
return response.data?.meetings?.edges?.[0]?.node;
}
async matchParticipantsToContacts(
participants: FirefliesParticipant[],
): Promise<{
matchedContacts: Contact[];
unmatchedParticipants: FirefliesParticipant[];
}> {
if (participants.length === 0) {
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);
unmatchedParticipants.push(...nameMatches.unmatchedParticipants);
}
return { matchedContacts, unmatchedParticipants };
}
private async matchByEmail(participants: FirefliesParticipant[]): Promise<{
matchedContacts: Contact[];
unmatchedParticipants: FirefliesParticipant[];
}> {
const emails = participants.map(({ email }) => email).filter(Boolean);
const query = `
query FindPeople($emails: [String!]!) {
people(filter: { emails: { primaryEmail: { in: $emails } } }) {
edges { node { id emails { primaryEmail } } }
}
}
`;
const variables = { emails };
const response = await this.gqlRequest<FindPeopleResponse>(query, variables);
const people = response.data?.people;
if (!people?.edges) {
return { matchedContacts: [], unmatchedParticipants: participants };
}
const matchedContacts = people.edges.map(({ node }) => ({
id: node.id,
email: node.emails?.primaryEmail || ''
}));
const matchedEmails = new Set(
matchedContacts
.map(({ email }) => email)
.filter((email) => Boolean(email)),
);
const unmatchedParticipants = participants.filter(
({ email }) => !matchedEmails.has(email)
);
return { matchedContacts, unmatchedParticipants };
}
private async matchByName(
participants: FirefliesParticipant[],
alreadyMatchedContacts: Contact[]
): Promise<{
matchedContacts: Contact[];
unmatchedParticipants: FirefliesParticipant[];
}> {
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) {
const nameMatch = await this.findContactByName(participant.name);
if (nameMatch && !alreadyMatchedIds.has(nameMatch.id)) {
matchedContacts.push(nameMatch);
alreadyMatchedIds.add(nameMatch.id);
} else {
unmatchedParticipants.push(participant);
}
}
return { matchedContacts, unmatchedParticipants };
}
private async findContactByName(name: string): Promise<Contact | null> {
if (!name || !name.trim()) {
return null;
}
const nameParts = name.trim().split(/\s+/);
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 } } }
}
}
`;
let variables: any = { firstName };
if (lastName) {
variables.lastName = lastName;
}
try {
const response = await this.gqlRequest<any>(query, variables);
const people = response.data?.people?.edges;
if (people && people.length > 0) {
const person = people[0].node;
return {
id: person.id,
email: person.emails?.primaryEmail || ''
};
}
// If no exact match and we have a last name, try fuzzy matching
if (lastName) {
query = `
query FindPeopleByNameFuzzy($firstName: String!) {
people(filter: { name: { firstName: { ilike: $firstName } } }) {
edges { node { id emails { primaryEmail } name { firstName lastName } } }
}
}
`;
const fuzzyResponse = await this.gqlRequest<any>(query, { 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 personLastName = edge.node.name?.lastName || '';
return personLastName.toLowerCase().includes(lastName.toLowerCase());
});
if (bestMatch) {
const person = bestMatch.node;
return {
id: person.id,
email: person.emails?.primaryEmail || ''
};
}
}
}
return null;
} catch {
// Silently fail - don't break the entire process for a single contact lookup
return null;
}
}
async createContactsForUnmatched(
participants: FirefliesParticipant[],
): 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);
}
return newContactIds;
}
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) {
unique.push(participant);
} else {
logger.warn(`Duplicate participant email detected: ${participant.email}. Using first occurrence.`);
}
return unique;
}, []);
for (const participant of uniqueParticipants) {
const [firstName, ...lastNameParts] = participant.name.trim().split(/\s+/);
const lastName = lastNameParts.join(' ');
const mutation = `
mutation CreatePerson($data: PersonCreateInput!) {
createPerson(data: $data) { id }
}
`;
const variables = {
data: {
name: { firstName, lastName },
emails: { primaryEmail: participant.email },
},
};
try {
const response = await this.gqlRequest<CreatePersonResponse>(mutation, variables);
if (!response.data?.createPerson?.id) {
throw new Error(`Failed to create contact for ${participant.email}`);
}
newContactIds.push(response.data.createPerson.id);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
if (errorMessage.includes('Duplicate Emails') || errorMessage.includes('BAD_USER_INPUT')) {
logger.warn(`Skipping contact creation for ${participant.email} due to duplicate email constraint: ${errorMessage}`);
continue;
}
throw error;
}
}
return newContactIds;
}
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()
);
if (!existing) {
unique.push(participant);
} else {
logger.warn(`Duplicate participant name detected: ${participant.name}. Using first occurrence.`);
}
return unique;
}, []);
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.`);
continue;
}
const [firstName, ...lastNameParts] = participant.name.trim().split(/\s+/);
const lastName = lastNameParts.join(' ');
const mutation = `
mutation CreatePerson($data: PersonCreateInput!) {
createPerson(data: $data) { id }
}
`;
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
},
};
try {
const response = await this.gqlRequest<CreatePersonResponse>(mutation, variables);
if (!response.data?.createPerson?.id) {
throw new Error(`Failed to create contact for ${participant.name}`);
}
newContactIds.push(response.data.createPerson.id);
logger.debug(`Created contact for name-only participant: ${participant.name}`);
} 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;
}
}
return newContactIds;
}
async createNote(
contactId: string,
title: string,
body: string
): Promise<string> {
const noteId = await this.createNoteOnly(title, body);
await this.createNoteTarget(noteId, contactId);
return noteId;
}
async createNoteOnly(
title: string,
body: string
): Promise<string> {
const mutation = `
mutation CreateNote($data: NoteCreateInput!) {
createNote(data: $data) { id }
}
`;
const variables = {
data: {
title,
bodyV2: {
markdown: body.trim()
},
},
};
const response = await this.gqlRequest<CreateNoteResponse>(mutation, variables);
if (!response.data?.createNote?.id) {
throw new Error(`Failed to create note`);
}
return response.data.createNote.id;
}
async createNoteTarget(noteId: string, contactId: string): Promise<void> {
const mutation = `
mutation CreateNoteTarget($data: NoteTargetCreateInput!) {
createNoteTarget(data: $data) {
id
noteId
personId
}
}
`;
const variables = {
data: {
noteId,
personId: contactId,
},
};
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);
}
async createMeeting(meetingData: MeetingCreateInput): Promise<string> {
const mutation = `
mutation CreateMeeting($data: MeetingCreateInput!) {
createMeeting(data: $data) { id }
}
`;
const variables = { data: meetingData };
// Debug: log the variables being sent
if (!this.isTestEnvironment) {
logger.debug('createMeeting variables:', JSON.stringify(variables, null, 2));
}
const response = await this.gqlRequest<CreateMeetingResponse>(mutation, variables);
if (!response.data?.createMeeting?.id) {
throw new Error('Failed to create meeting: Invalid response from server');
}
return response.data.createMeeting.id;
}
private async gqlRequest<T>(
query: string,
variables?: Record<string, unknown>
): Promise<GraphQLResponse<T>> {
const url = `${this.apiUrl}/graphql`;
try {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ query, variables }),
});
if (!res.ok) {
let errorMessage = `GraphQL request failed with status ${res.status}`;
try {
const errorText = await res.text();
if (errorText) {
errorMessage += `: ${errorText}`;
}
} catch {
// Ignore error when reading response body
}
throw new Error(errorMessage);
}
const json = await res.json() as GraphQLResponse<T> & {
errors?: Array<{ message?: string; extensions?: Record<string, unknown> }>
};
if (json?.errors && Array.isArray(json.errors) && json.errors.length > 0) {
const firstError = json.errors[0];
const errorMessage = firstError?.message || 'GraphQL error';
const errorCode = firstError?.extensions?.code as string | undefined;
if (errorCode) {
throw new Error(`${errorMessage} (Code: ${errorCode})`);
}
throw new Error(errorMessage);
}
return json;
} catch (error) {
logger.error('GraphQL request error:', error);
throw error;
}
}
async createFailedMeeting(meetingData: MeetingCreateInput): Promise<string> {
const mutation = `
mutation CreateMeeting($data: MeetingCreateInput!) {
createMeeting(data: $data) { id }
}
`;
const variables = { data: meetingData };
if (!this.isTestEnvironment) {
logger.debug('createFailedMeeting variables:', JSON.stringify(variables, null, 2));
}
const response = await this.gqlRequest<CreateMeetingResponse>(mutation, variables);
if (!response.data?.createMeeting?.id) {
throw new Error('Failed to create failed meeting record: Invalid response from server');
}
return response.data.createMeeting.id;
}
async findFailedMeetings(): Promise<any[]> {
const query = `
query FindFailedMeetings {
meetings(filter: { importStatus: { eq: "FAILED" } }) {
edges {
node {
id
name
firefliesMeetingId
importError
lastImportAttempt
importAttempts
createdAt
}
}
}
}
`;
const response = await this.gqlRequest<any>(query);
return response.data?.meetings?.edges?.map((edge: any) => edge.node) || [];
}
async retryFailedMeeting(meetingId: string, updatedData: Partial<MeetingCreateInput>): Promise<void> {
const mutation = `
mutation UpdateMeeting($where: MeetingWhereUniqueInput!, $data: MeetingUpdateInput!) {
updateMeeting(where: $where, data: $data) { id }
}
`;
const variables = {
where: { id: meetingId },
data: {
...updatedData,
lastImportAttempt: new Date().toISOString(),
importAttempts: { increment: 1 }
}
};
await this.gqlRequest<any>(mutation, variables);
}
}
@@ -0,0 +1,130 @@
// 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;
};
@@ -0,0 +1,30 @@
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);
};
@@ -0,0 +1,345 @@
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'}`);
}
}
}
@@ -0,0 +1,54 @@
import { createHash, createHmac } from 'crypto';
import type { FirefliesWebhookPayload } from './types';
export type SignatureVerificationResult = {
isValid: boolean;
computedSignature?: string;
};
export const verifyWebhookSignature = (
body: string,
signature: string | undefined,
secret: string
): SignatureVerificationResult => {
if (!signature) {
return { isValid: false };
}
try {
const hmac = createHmac('sha256', secret);
hmac.update(body, 'utf8');
const computed = hmac.digest('hex');
const computedSignature = `sha256=${computed}`;
const isValid = signature === computedSignature;
return { isValid, computedSignature };
} catch {
return { isValid: false };
}
};
export const getWebhookSecretFingerprint = (secret: string): string => {
return createHash('sha256').update(secret).digest('hex').substring(0, 8);
};
export const isValidFirefliesPayload = (
params: unknown
): params is FirefliesWebhookPayload => {
if (!params || typeof params !== 'object') {
return false;
}
const payload = params as Record<string, unknown>;
return (
typeof payload['meetingId'] === 'string' &&
payload['meetingId'].length > 0 &&
typeof payload['eventType'] === 'string' &&
payload['eventType'].length > 0 &&
(payload['clientReferenceId'] === undefined ||
typeof payload['clientReferenceId'] === 'string')
);
};
@@ -0,0 +1,712 @@
import * as crypto from 'crypto';
import {
main,
type FirefliesMeetingData,
type FirefliesWebhookPayload,
} from '../actions/receive-fireflies-notes';
// Helper to generate HMAC signature
const generateHMACSignature = (body: string, secret: string): string => {
const signature = crypto
.createHmac('sha256', secret)
.update(body, 'utf8')
.digest('hex');
return `sha256=${signature}`;
};
// Mock raw Fireflies API response with full summary (before transformation)
const mockFirefliesApiResponseWithSummary = {
id: 'test-meeting-001',
title: 'Product Demo with Client',
date: '2024-11-02T14:00:00Z',
duration: 1800,
participants: [
'Sarah Sales <sales@company.com>',
'John Client <client@customer.com>',
],
organizer_email: 'sales@company.com',
summary: {
action_items: [
'Follow up with pricing proposal by Friday',
'Schedule technical deep-dive next week',
'Share case studies from similar clients',
],
keywords: ['product demo', 'pricing', 'technical requirements', 'integration'],
overview: 'Successful product demonstration with positive client feedback. Client expressed strong interest in the enterprise plan and requested technical documentation for their IT team.',
gist: 'Product demo went well, client interested in enterprise plan, next steps identified',
topics_discussed: ['product features', 'pricing discussion', 'integration capabilities', 'support options'],
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,
},
transcript_url: 'https://app.fireflies.ai/transcript/test-001',
video_url: 'https://app.fireflies.ai/recording/test-001',
summary_status: 'completed',
};
// Transformed meeting data (after fetchFirefliesMeetingData processes it)
const mockMeetingWithFullSummary: FirefliesMeetingData = {
id: 'test-meeting-001',
title: 'Product Demo with Client',
date: '2024-11-02T14:00:00Z',
duration: 1800,
participants: [
{ email: 'sales@company.com', name: 'Sarah Sales' },
{ email: 'client@customer.com', name: 'John Client' },
],
organizer_email: 'sales@company.com',
summary: {
action_items: [
'Follow up with pricing proposal by Friday',
'Schedule technical deep-dive next week',
'Share case studies from similar clients',
],
keywords: ['product demo', 'pricing', 'technical requirements', 'integration'],
overview: 'Successful product demonstration with positive client feedback. Client expressed strong interest in the enterprise plan and requested technical documentation for their IT team.',
gist: 'Product demo went well, client interested in enterprise plan, next steps identified',
topics_discussed: ['product features', 'pricing discussion', 'integration capabilities', 'support options'],
meeting_type: 'Sales Call',
bullet_gist: '• Demonstrated core product features\n• Discussed enterprise pricing\n• Addressed integration questions',
},
analytics: {
sentiments: {
positive_pct: 75,
negative_pct: 10,
neutral_pct: 15,
},
},
transcript_url: 'https://app.fireflies.ai/transcript/test-001',
recording_url: 'https://app.fireflies.ai/recording/test-001',
summary_status: 'completed',
};
// Mock raw API response without summary (processing)
const mockFirefliesApiResponseWithoutSummary = {
id: 'test-meeting-002',
title: 'Team Standup',
date: '2024-11-02T15:00:00Z',
duration: 900,
participants: [
'Alice Developer <dev1@company.com>',
'Bob Developer <dev2@company.com>',
],
organizer_email: 'dev1@company.com',
summary: {
action_items: [],
keywords: [],
overview: '',
gist: '',
topics_discussed: [],
},
transcript_url: 'https://app.fireflies.ai/transcript/test-002',
summary_status: 'processing',
};
// Mock meeting data without summary (processing) - currently unused but kept for reference
const _mockMeetingWithoutSummary = {
id: 'test-meeting-002',
title: 'Team Standup',
date: '2024-11-02T15:00:00Z',
duration: 900,
participants: [
{ email: 'dev1@company.com', name: 'Alice Developer' },
{ email: 'dev2@company.com', name: 'Bob Developer' },
],
organizer_email: 'dev1@company.com',
summary: {
action_items: [],
keywords: [],
overview: '',
gist: '',
topics_discussed: [],
},
transcript_url: 'https://app.fireflies.ai/transcript/test-002',
summary_status: 'processing',
};
// Mock raw API response for team meeting
const mockFirefliesApiResponseTeamMeeting = {
...mockFirefliesApiResponseWithSummary,
id: 'test-team-003',
title: 'Sprint Planning',
participants: [
'Alice Scrum <scrum@company.com>',
'Bob Developer <dev1@company.com>',
'Carol Coder <dev2@company.com>',
'David QA <qa@company.com>',
],
summary: {
...mockFirefliesApiResponseWithSummary.summary,
meeting_type: 'Sprint Planning',
},
};
// Mock team meeting with multiple participants (transformed) - currently unused but kept for reference
const _mockTeamMeeting = {
...mockMeetingWithFullSummary,
id: 'test-team-003',
title: 'Sprint Planning',
participants: [
{ email: 'scrum@company.com', name: 'Alice Scrum' },
{ email: 'dev1@company.com', name: 'Bob Developer' },
{ email: 'dev2@company.com', name: 'Carol Coder' },
{ email: 'qa@company.com', name: 'David QA' },
],
summary: {
...mockMeetingWithFullSummary.summary,
meeting_type: 'Sprint Planning',
},
};
// Mock environment variables
const originalEnv = process.env;
beforeEach(() => {
process.env = {
...originalEnv,
FIREFLIES_WEBHOOK_SECRET: 'test_webhook_secret',
FIREFLIES_API_KEY: 'test_fireflies_api_key',
TWENTY_API_KEY: 'test_twenty_api_key',
SERVER_URL: 'http://localhost:3000',
AUTO_CREATE_CONTACTS: 'true',
DEBUG_LOGS: 'false',
FIREFLIES_SUMMARY_STRATEGY: 'immediate_with_retry',
FIREFLIES_RETRY_ATTEMPTS: '3',
FIREFLIES_RETRY_DELAY: '1000',
};
});
afterEach(() => {
process.env = originalEnv;
jest.clearAllMocks();
});
describe('Fireflies Webhook Integration v2', () => {
describe('Webhook Authentication', () => {
it('should verify HMAC SHA-256 signature from x-hub-signature header', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
// Mock Fireflies API
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
transcript: mockFirefliesApiResponseWithSummary, // Use raw API format
},
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
});
it('should reject requests with invalid signature', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const invalidSignature = 'sha256=invalid_signature_here';
const result = await main(payload, { 'x-hub-signature': invalidSignature, body });
expect(result.success).toBe(false);
expect(result.errors).toContain('Invalid webhook signature');
});
it('should reject requests without signature header', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const result = await main(payload, {});
expect(result.success).toBe(false);
expect(result.errors).toContain('Invalid webhook signature');
});
it('should reject requests with missing webhook secret env var', async () => {
delete process.env.FIREFLIES_WEBHOOK_SECRET;
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const result = await main(payload, {});
expect(result.success).toBe(false);
});
});
describe('Fireflies GraphQL Integration', () => {
it('should fetch meeting data from Fireflies API', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
const firefliesApiMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
firefliesApiMock();
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
transcript: mockFirefliesApiResponseWithSummary, // Use raw API format
},
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(firefliesApiMock).toHaveBeenCalled();
expect(result.success).toBe(true);
});
it('should handle Fireflies API fetch failures gracefully', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.reject(new Error('Fireflies API unavailable'));
}
return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: {} }) });
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(false);
expect(result.errors?.[0]).toContain('Fireflies API');
});
it('should handle malformed GraphQL responses', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { malformed: 'response' },
}),
});
}
return Promise.resolve({ ok: true, json: () => Promise.resolve({ data: {} }) });
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(false);
expect(result.errors?.[0]).toContain('Invalid response from Fireflies API');
});
});
describe('Summary Processing', () => {
it('should create complete records when summary is ready', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithSummary }, // Use raw API format
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
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.meetingType).toBe('Sales Call');
expect(result.keyTopics).toEqual(['product features', 'pricing discussion', 'integration capabilities', 'support options']);
});
it('should create basic records when summary is pending', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-002',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithoutSummary }, // Use raw API format
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
expect(result.summaryPending).toBe(true);
expect(result.noteIds || result.meetingId).toBeDefined();
});
it('should retry summary fetch with exponential backoff', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-003',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
let attemptCount = 0;
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
attemptCount++;
// First two attempts return no summary, third returns full summary
if (attemptCount < 3) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithoutSummary }, // Use raw API format
}),
});
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithSummary }, // Use raw API format
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(attemptCount).toBe(3);
expect(result.success).toBe(true);
expect(result.summaryReady).toBe(true);
});
it('should handle immediate_only strategy with single fetch attempt', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-004',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
let fetchCount = 0;
global.fetch = jest.fn().mockImplementation((url: string) => {
if (url === 'https://api.fireflies.ai/graphql') {
fetchCount++;
// Return summary not ready
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithoutSummary },
}),
});
}
// Twenty API mocks
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createNote: { id: 'new-note-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
// Override strategy for this test
process.env.FIREFLIES_SUMMARY_STRATEGY = 'immediate_only';
const result = await main(payload, { 'x-hub-signature': signature, body });
// Should only fetch once with immediate_only strategy
expect(fetchCount).toBe(1);
expect(result.success).toBe(true);
expect(result.summaryPending).toBe(true);
// Reset to default
process.env.FIREFLIES_SUMMARY_STRATEGY = 'immediate_with_retry';
});
});
describe('CRM Record Creation', () => {
it('should create summary-focused notes for 1-on-1 meetings', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-meeting-001',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
const createNoteMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string, options?: any) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseWithSummary }, // Use raw API format
}),
});
}
// Twenty API
const body = options?.body ? JSON.parse(options.body) : {};
if (body.query?.includes('createNote')) {
createNoteMock(body.variables);
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { createNote: { id: 'new-note-id' } },
}),
});
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
createMeeting: { id: 'new-meeting-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
expect(createNoteMock).toHaveBeenCalled();
const noteData = createNoteMock.mock.calls[0][0];
expect(noteData.data.title).toContain('Meeting:');
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]');
});
it('should create meeting records for multi-party meetings', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-team-003',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
const createMeetingMock = jest.fn();
global.fetch = jest.fn().mockImplementation((url: string, options?: any) => {
if (url === 'https://api.fireflies.ai/graphql') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { transcript: mockFirefliesApiResponseTeamMeeting }, // Use raw API format
}),
});
}
// Twenty API
const body = options?.body ? JSON.parse(options.body) : {};
if (body.query?.includes('createMeeting')) {
createMeetingMock(body.variables);
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { createMeeting: { id: 'new-meeting-id' } },
}),
});
}
if (body.query?.includes('createNote')) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: { createNote: { id: 'new-note-id' } },
}),
});
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve({
data: {
meetings: { edges: [] },
people: { edges: [] },
createPerson: { id: 'new-person-id' },
},
}),
});
});
const result = await main(payload, { 'x-hub-signature': signature, body });
expect(result.success).toBe(true);
expect(result.meetingId).toBeDefined();
expect(createMeetingMock).toHaveBeenCalled();
});
});
describe('Error Handling & Resilience', () => {
it('should never throw uncaught exceptions', async () => {
const payload: FirefliesWebhookPayload = {
meetingId: 'test-critical-error',
eventType: 'Transcription completed',
};
const body = JSON.stringify(payload);
const signature = generateHMACSignature(body, 'test_webhook_secret');
global.fetch = jest.fn().mockImplementation(() => {
throw new Error('Critical failure');
});
await expect(main(payload, { 'x-hub-signature': signature, body })).resolves.toEqual(
expect.objectContaining({ success: false, errors: expect.any(Array) })
);
});
it('should handle missing payload gracefully', async () => {
const result = await main(null as any, {});
expect(result.success).toBe(false);
expect(result.errors).toBeDefined();
});
it('should handle invalid payload structure', async () => {
const invalidPayload = { invalid: 'data' };
const result = await main(invalidPayload as any, {});
expect(result.success).toBe(false);
expect(result.errors).toBeDefined();
});
});
});
@@ -0,0 +1,16 @@
// Test setup for Fireflies app
// Mock global fetch for all tests
global.fetch = jest.fn();
// Setup test environment variables
process.env.FIREFLIES_WEBHOOK_SECRET = 'testsecret';
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';
// Reset mocks before each test
beforeEach(() => {
jest.clearAllMocks();
});
@@ -0,0 +1,11 @@
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,14 @@
import { ObjectMetadata } from 'twenty-sdk/application';
@ObjectMetadata({
universalIdentifier: 'd1831348-b4a4-4426-9c0b-0af19e7a9c27',
nameSingular: 'meeting',
namePlural: 'meetings',
labelSingular: 'Meeting',
labelPlural: 'Meetings',
description:
'Meetings imported from Fireflies with AI-generated summaries, sentiment, and action items.',
icon: 'IconVideo',
})
export class Meeting {}
@@ -0,0 +1,26 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -0,0 +1,21 @@
# Last email interaction
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
## Setup
1. Add and synchronize app
```bash
twenty auth login
cd last_email_interaction
twenty app 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
@@ -0,0 +1,22 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
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',
applicationVariables: {
TWENTY_API_KEY: {
universalIdentifier: 'aae3f523-4c1f-4805-b3ee-afeb676c381e',
isSecret: true,
description: 'Required to send requests to Twenty',
},
TWENTY_API_URL: {
universalIdentifier: '6d19bb04-45bb-46aa-a4e5-4a2682c7b19d',
isSecret: false,
description: 'Optional, defaults to cloud API URL',
},
},
};
export default config;
@@ -0,0 +1,18 @@
{
"name": "last-email-interaction",
"version": "0.0.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"dependencies": {
"axios": "^1.12.2",
"twenty-sdk": "0.0.4"
},
"devDependencies": {
"@types/node": "^24.7.2"
}
}
@@ -0,0 +1,277 @@
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,26 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
@@ -0,0 +1,273 @@
# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!
__metadata:
version: 8
cacheKey: 10c0
"@types/node@npm:^24.7.2":
version: 24.10.0
resolution: "@types/node@npm:24.10.0"
dependencies:
undici-types: "npm:~7.16.0"
checksum: 10c0/f82ed7194e16f5590ef7afdc20c6d09068c76d50278b485ede8f0c5749683536e3064ffa8def8db76915196afb3724b854aa5723c64d6571b890b14492943b46
languageName: node
linkType: hard
"async-function@npm:^1.0.0":
version: 1.0.0
resolution: "async-function@npm:1.0.0"
checksum: 10c0/669a32c2cb7e45091330c680e92eaeb791bc1d4132d827591e499cd1f776ff5a873e77e5f92d0ce795a8d60f10761dec9ddfe7225a5de680f5d357f67b1aac73
languageName: node
linkType: hard
"async-generator-function@npm:^1.0.0":
version: 1.0.0
resolution: "async-generator-function@npm:1.0.0"
checksum: 10c0/2c50ef856c543ad500d8d8777d347e3c1ba623b93e99c9263ecc5f965c1b12d2a140e2ab6e43c3d0b85366110696f28114649411cbcd10b452a92a2318394186
languageName: node
linkType: hard
"asynckit@npm:^0.4.0":
version: 0.4.0
resolution: "asynckit@npm:0.4.0"
checksum: 10c0/d73e2ddf20c4eb9337e1b3df1a0f6159481050a5de457c55b14ea2e5cb6d90bb69e004c9af54737a5ee0917fcf2c9e25de67777bbe58261847846066ba75bc9d
languageName: node
linkType: hard
"axios@npm:^1.12.2":
version: 1.12.2
resolution: "axios@npm:1.12.2"
dependencies:
follow-redirects: "npm:^1.15.6"
form-data: "npm:^4.0.4"
proxy-from-env: "npm:^1.1.0"
checksum: 10c0/80b063e318cf05cd33a4d991cea0162f3573481946f9129efb7766f38fde4c061c34f41a93a9f9521f02b7c9565ccbc197c099b0186543ac84a24580017adfed
languageName: node
linkType: hard
"call-bind-apply-helpers@npm:^1.0.1, call-bind-apply-helpers@npm:^1.0.2":
version: 1.0.2
resolution: "call-bind-apply-helpers@npm:1.0.2"
dependencies:
es-errors: "npm:^1.3.0"
function-bind: "npm:^1.1.2"
checksum: 10c0/47bd9901d57b857590431243fea704ff18078b16890a6b3e021e12d279bbf211d039155e27d7566b374d49ee1f8189344bac9833dec7a20cdec370506361c938
languageName: node
linkType: hard
"combined-stream@npm:^1.0.8":
version: 1.0.8
resolution: "combined-stream@npm:1.0.8"
dependencies:
delayed-stream: "npm:~1.0.0"
checksum: 10c0/0dbb829577e1b1e839fa82b40c07ffaf7de8a09b935cadd355a73652ae70a88b4320db322f6634a4ad93424292fa80973ac6480986247f1734a1137debf271d5
languageName: node
linkType: hard
"delayed-stream@npm:~1.0.0":
version: 1.0.0
resolution: "delayed-stream@npm:1.0.0"
checksum: 10c0/d758899da03392e6712f042bec80aa293bbe9e9ff1b2634baae6a360113e708b91326594c8a486d475c69d6259afb7efacdc3537bfcda1c6c648e390ce601b19
languageName: node
linkType: hard
"dunder-proto@npm:^1.0.1":
version: 1.0.1
resolution: "dunder-proto@npm:1.0.1"
dependencies:
call-bind-apply-helpers: "npm:^1.0.1"
es-errors: "npm:^1.3.0"
gopd: "npm:^1.2.0"
checksum: 10c0/199f2a0c1c16593ca0a145dbf76a962f8033ce3129f01284d48c45ed4e14fea9bbacd7b3610b6cdc33486cef20385ac054948fefc6272fcce645c09468f93031
languageName: node
linkType: hard
"es-define-property@npm:^1.0.1":
version: 1.0.1
resolution: "es-define-property@npm:1.0.1"
checksum: 10c0/3f54eb49c16c18707949ff25a1456728c883e81259f045003499efba399c08bad00deebf65cccde8c0e07908c1a225c9d472b7107e558f2a48e28d530e34527c
languageName: node
linkType: hard
"es-errors@npm:^1.3.0":
version: 1.3.0
resolution: "es-errors@npm:1.3.0"
checksum: 10c0/0a61325670072f98d8ae3b914edab3559b6caa980f08054a3b872052640d91da01d38df55df797fcc916389d77fc92b8d5906cf028f4db46d7e3003abecbca85
languageName: node
linkType: hard
"es-object-atoms@npm:^1.0.0, es-object-atoms@npm:^1.1.1":
version: 1.1.1
resolution: "es-object-atoms@npm:1.1.1"
dependencies:
es-errors: "npm:^1.3.0"
checksum: 10c0/65364812ca4daf48eb76e2a3b7a89b3f6a2e62a1c420766ce9f692665a29d94fe41fe88b65f24106f449859549711e4b40d9fb8002d862dfd7eb1c512d10be0c
languageName: node
linkType: hard
"es-set-tostringtag@npm:^2.1.0":
version: 2.1.0
resolution: "es-set-tostringtag@npm:2.1.0"
dependencies:
es-errors: "npm:^1.3.0"
get-intrinsic: "npm:^1.2.6"
has-tostringtag: "npm:^1.0.2"
hasown: "npm:^2.0.2"
checksum: 10c0/ef2ca9ce49afe3931cb32e35da4dcb6d86ab02592cfc2ce3e49ced199d9d0bb5085fc7e73e06312213765f5efa47cc1df553a6a5154584b21448e9fb8355b1af
languageName: node
linkType: hard
"follow-redirects@npm:^1.15.6":
version: 1.15.11
resolution: "follow-redirects@npm:1.15.11"
peerDependenciesMeta:
debug:
optional: true
checksum: 10c0/d301f430542520a54058d4aeeb453233c564aaccac835d29d15e050beb33f339ad67d9bddbce01739c5dc46a6716dbe3d9d0d5134b1ca203effa11a7ef092343
languageName: node
linkType: hard
"form-data@npm:^4.0.4":
version: 4.0.4
resolution: "form-data@npm:4.0.4"
dependencies:
asynckit: "npm:^0.4.0"
combined-stream: "npm:^1.0.8"
es-set-tostringtag: "npm:^2.1.0"
hasown: "npm:^2.0.2"
mime-types: "npm:^2.1.12"
checksum: 10c0/373525a9a034b9d57073e55eab79e501a714ffac02e7a9b01be1c820780652b16e4101819785e1e18f8d98f0aee866cc654d660a435c378e16a72f2e7cac9695
languageName: node
linkType: hard
"function-bind@npm:^1.1.2":
version: 1.1.2
resolution: "function-bind@npm:1.1.2"
checksum: 10c0/d8680ee1e5fcd4c197e4ac33b2b4dce03c71f4d91717292785703db200f5c21f977c568d28061226f9b5900cbcd2c84463646134fd5337e7925e0942bc3f46d5
languageName: node
linkType: hard
"generator-function@npm:^2.0.0":
version: 2.0.1
resolution: "generator-function@npm:2.0.1"
checksum: 10c0/8a9f59df0f01cfefafdb3b451b80555e5cf6d76487095db91ac461a0e682e4ff7a9dbce15f4ecec191e53586d59eece01949e05a4b4492879600bbbe8e28d6b8
languageName: node
linkType: hard
"get-intrinsic@npm:^1.2.6":
version: 1.3.1
resolution: "get-intrinsic@npm:1.3.1"
dependencies:
async-function: "npm:^1.0.0"
async-generator-function: "npm:^1.0.0"
call-bind-apply-helpers: "npm:^1.0.2"
es-define-property: "npm:^1.0.1"
es-errors: "npm:^1.3.0"
es-object-atoms: "npm:^1.1.1"
function-bind: "npm:^1.1.2"
generator-function: "npm:^2.0.0"
get-proto: "npm:^1.0.1"
gopd: "npm:^1.2.0"
has-symbols: "npm:^1.1.0"
hasown: "npm:^2.0.2"
math-intrinsics: "npm:^1.1.0"
checksum: 10c0/9f4ab0cf7efe0fd2c8185f52e6f637e708f3a112610c88869f8f041bb9ecc2ce44bf285dfdbdc6f4f7c277a5b88d8e94a432374d97cca22f3de7fc63795deb5d
languageName: node
linkType: hard
"get-proto@npm:^1.0.1":
version: 1.0.1
resolution: "get-proto@npm:1.0.1"
dependencies:
dunder-proto: "npm:^1.0.1"
es-object-atoms: "npm:^1.0.0"
checksum: 10c0/9224acb44603c5526955e83510b9da41baf6ae73f7398875fba50edc5e944223a89c4a72b070fcd78beb5f7bdda58ecb6294adc28f7acfc0da05f76a2399643c
languageName: node
linkType: hard
"gopd@npm:^1.2.0":
version: 1.2.0
resolution: "gopd@npm:1.2.0"
checksum: 10c0/50fff1e04ba2b7737c097358534eacadad1e68d24cccee3272e04e007bed008e68d2614f3987788428fd192a5ae3889d08fb2331417e4fc4a9ab366b2043cead
languageName: node
linkType: hard
"has-symbols@npm:^1.0.3, has-symbols@npm:^1.1.0":
version: 1.1.0
resolution: "has-symbols@npm:1.1.0"
checksum: 10c0/dde0a734b17ae51e84b10986e651c664379018d10b91b6b0e9b293eddb32f0f069688c841fb40f19e9611546130153e0a2a48fd7f512891fb000ddfa36f5a20e
languageName: node
linkType: hard
"has-tostringtag@npm:^1.0.2":
version: 1.0.2
resolution: "has-tostringtag@npm:1.0.2"
dependencies:
has-symbols: "npm:^1.0.3"
checksum: 10c0/a8b166462192bafe3d9b6e420a1d581d93dd867adb61be223a17a8d6dad147aa77a8be32c961bb2f27b3ef893cae8d36f564ab651f5e9b7938ae86f74027c48c
languageName: node
linkType: hard
"hasown@npm:^2.0.2":
version: 2.0.2
resolution: "hasown@npm:2.0.2"
dependencies:
function-bind: "npm:^1.1.2"
checksum: 10c0/3769d434703b8ac66b209a4cca0737519925bbdb61dd887f93a16372b14694c63ff4e797686d87c90f08168e81082248b9b028bad60d4da9e0d1148766f56eb9
languageName: node
linkType: hard
"last-email-interaction@workspace:.":
version: 0.0.0-use.local
resolution: "last-email-interaction@workspace:."
dependencies:
"@types/node": "npm:^24.7.2"
axios: "npm:^1.12.2"
twenty-sdk: "npm:^0.0.4"
languageName: unknown
linkType: soft
"math-intrinsics@npm:^1.1.0":
version: 1.1.0
resolution: "math-intrinsics@npm:1.1.0"
checksum: 10c0/7579ff94e899e2f76ab64491d76cf606274c874d8f2af4a442c016bd85688927fcfca157ba6bf74b08e9439dc010b248ce05b96cc7c126a354c3bae7fcb48b7f
languageName: node
linkType: hard
"mime-db@npm:1.52.0":
version: 1.52.0
resolution: "mime-db@npm:1.52.0"
checksum: 10c0/0557a01deebf45ac5f5777fe7740b2a5c309c6d62d40ceab4e23da9f821899ce7a900b7ac8157d4548ddbb7beffe9abc621250e6d182b0397ec7f10c7b91a5aa
languageName: node
linkType: hard
"mime-types@npm:^2.1.12":
version: 2.1.35
resolution: "mime-types@npm:2.1.35"
dependencies:
mime-db: "npm:1.52.0"
checksum: 10c0/82fb07ec56d8ff1fc999a84f2f217aa46cb6ed1033fefaabd5785b9a974ed225c90dc72fff460259e66b95b73648596dbcc50d51ed69cdf464af2d237d3149b2
languageName: node
linkType: hard
"proxy-from-env@npm:^1.1.0":
version: 1.1.0
resolution: "proxy-from-env@npm:1.1.0"
checksum: 10c0/fe7dd8b1bdbbbea18d1459107729c3e4a2243ca870d26d34c2c1bcd3e4425b7bcc5112362df2d93cc7fb9746f6142b5e272fd1cc5c86ddf8580175186f6ad42b
languageName: node
linkType: hard
"twenty-sdk@npm:^0.0.4":
version: 0.0.4
resolution: "twenty-sdk@npm:0.0.4"
checksum: 10c0/550f1d85bf0701396c9dd2d4c6bc55ba1b067fce13636f8540eec60ab6a4257c6d7cd86cb3f62e0974bf99467bc31270d92b17b9681a1b7a6281b7ef97224080
languageName: node
linkType: hard
"undici-types@npm:~7.16.0":
version: 7.16.0
resolution: "undici-types@npm:7.16.0"
checksum: 10c0/3033e2f2b5c9f1504bdc5934646cb54e37ecaca0f9249c983f7b1fc2e87c6d18399ebb05dc7fd5419e02b2e915f734d872a65da2e3eeed1813951c427d33cc9a
languageName: node
linkType: hard
@@ -0,0 +1,2 @@
TWENTY_API_URL=
TWENTY_API_KEY=
@@ -0,0 +1,2 @@
.yarn/install-state.gz
.env
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
yarnPath: .yarn/releases/yarn-4.9.2.cjs
nodeLinker: node-modules
@@ -0,0 +1,113 @@
# Browser Extension Serverless Functions
Serverless functions for the Twenty browser extension. These functions handle API interactions between the browser extension and the Twenty backend.
## Overview
This package contains serverless functions that are deployed to your Twenty workspace. The browser extension calls these functions to create and retrieve records in Twenty CRM.
## Functions
### Create Person
**Endpoint:** `/s/create/person`
Creates a new person record in Twenty from LinkedIn profile data.
**Parameters:**
- `firstName` (string) - Person's first name
- `lastName` (string) - Person's last name
**Response:** Created person object
### Create Company
**Endpoint:** `/s/create/company`
Creates a new company record in Twenty from LinkedIn company profile data.
**Parameters:**
- `name` (string) - Company name
**Response:** Created company object
### Get Person
**Endpoint:** `/s/get/person`
Retrieves an existing person record from Twenty (placeholder implementation).
### Get Company
**Endpoint:** `/s/get/company`
Retrieves an existing company record from Twenty (placeholder implementation).
## Setup
### Prerequisites
- **Twenty CLI** installed globally:
```bash
npm install -g twenty-cli
```
- **API Key** from your Twenty workspace:
- Go to https://twenty.com/settings/api-webhooks
- Generate an API key
### Configuration
1. **Authenticate with Twenty CLI:**
```bash
twenty auth login
```
2. **Sync serverless functions to your workspace:**
```bash
twenty app sync
```
3. **Configure environment variables:**
- `TWENTY_API_URL` - Your Twenty API URL (e.g., `https://your-workspace.twenty.com`)
- `TWENTY_API_KEY` - Your Twenty API key (marked as secret)
Environment variables can be configured via the Twenty CLI or the Twenty web interface after syncing.
## How It Works
1. The browser extension extracts data from LinkedIn profiles
2. The extension calls the serverless functions via the background script
3. Serverless functions authenticate with your Twenty API using the configured API key
4. Functions create or retrieve records in your Twenty workspace
5. Response is sent back to the extension for user feedback
## File Structure
```
serverlessFunctions/
├── create-person/
│ ├── serverlessFunction.manifest.jsonc # Function configuration
│ └── src/
│ └── index.ts # Function implementation
├── create-company/
│ ├── serverlessFunction.manifest.jsonc
│ └── src/
│ └── index.ts
├── get-person/
│ ├── serverlessFunction.manifest.jsonc
│ └── src/
│ └── index.ts
└── get-company/
├── serverlessFunction.manifest.jsonc
└── src/
└── index.ts
```
## Development
These functions are managed by the Twenty CLI and are deployed to your workspace. After making changes:
1. Update the function code in `src/index.ts`
2. Run `twenty app sync` to deploy changes to your workspace
3. Test the functions via the browser extension or Twenty API directly
## Related Packages
- **`twenty-browser-extension`** - The main browser extension that calls these functions
- See `packages/twenty-browser-extension/README.md` for the complete extension documentation
@@ -0,0 +1,23 @@
import { type ApplicationConfig } from 'twenty-sdk/application';
const config: ApplicationConfig = {
universalIdentifier: '627280a0-cb5b-40d3-a2e3-3e34b92926c8',
displayName: 'Browser Extension',
description: '',
applicationVariables: {
TWENTY_API_URL: {
universalIdentifier: '6cf6a57a-9708-4995-b6a5-65222ee1baf1',
isSecret: false,
value: '',
description: 'Twenty API URL',
},
TWENTY_API_KEY: {
universalIdentifier: '05d12575-e96e-4e45-b019-80dcdb67dc80',
isSecret: true,
value: '',
description: 'Twenty API Key',
},
},
};
export default config;
@@ -0,0 +1,17 @@
{
"name": "browser-extension",
"version": "0.0.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
"npm": "please-use-yarn",
"yarn": ">=4.0.2"
},
"packageManager": "yarn@4.9.2",
"dependencies": {
"twenty-sdk": "0.0.3"
},
"devDependencies": {
"@types/node": "^24.7.2"
}
}
@@ -0,0 +1,34 @@
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
export const main = async (params: { name: string }): Promise<object> => {
const response = await fetch(`${process.env.TWENTY_API_URL}/rest/companies`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
},
body: JSON.stringify({
name: params.name,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return (await response.json()) as object;
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: 'cead3d1e-1fbd-4b09-86a9-f0bedf4d54fa',
name: 'create-company',
triggers: [
{
universalIdentifier: '57ff5ea2-c4b7-458c-9296-27bad6acdaf9',
type: 'route',
path: '/create/company',
httpMethod: 'POST',
isAuthRequired: true,
},
],
};
@@ -0,0 +1,40 @@
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
export const main = async (params: {
firstName: string;
lastName: string;
}): Promise<object> => {
const response = await fetch(`${process.env.TWENTY_API_URL}/rest/people`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.TWENTY_API_KEY}`,
},
body: JSON.stringify({
name: {
firstName: params.firstName,
lastName: params.lastName,
},
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return (await response.json()) as object;
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: '7d38261b-99c5-43e7-83d8-bdcedc2dffdb',
name: 'create-person',
triggers: [
{
universalIdentifier: 'ecf261b8-183b-4323-ab95-3b11009a0eae',
type: 'route',
path: '/create/person',
httpMethod: 'POST',
isAuthRequired: true,
},
],
};
@@ -0,0 +1,28 @@
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
export const main = async (params: {
a: string;
b: number;
}): Promise<object> => {
const { a, b } = params;
// Rename the parameters and code below with your own logic
// This is just an example
const message = `Hello, input: ${a} and ${b}`;
return { message };
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: '8e43b96b-49a1-4e21-b257-e432a757b09f',
name: 'get-company',
triggers: [
{
universalIdentifier: '7a2bb8ad-6366-49ac-9f73-db9c4713c5af',
type: 'route',
path: '/get/company',
httpMethod: 'GET',
isAuthRequired: true,
},
],
};
@@ -0,0 +1,28 @@
import { type ServerlessFunctionConfig } from 'twenty-sdk/application';
export const main = async (params: {
a: string;
b: number;
}): Promise<object> => {
const { a, b } = params;
// Rename the parameters and code below with your own logic
// This is just an example
const message = `Hello, input: ${a} and ${b}`;
return { message };
};
export const config: ServerlessFunctionConfig = {
universalIdentifier: '87ea9816-c9e5-4860-b49f-a5f0759800f7',
name: 'get-person',
triggers: [
{
universalIdentifier: '54aec609-0518-4fb0-bd90-7cd21507fe11',
type: 'route',
path: '/get/person',
httpMethod: 'GET',
isAuthRequired: true,
},
],
};
@@ -0,0 +1,26 @@
{
"compileOnSave": false,
"compilerOptions": {
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"rootDir": ".",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"strict": true,
"target": "es2018",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true
},
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
@@ -0,0 +1,30 @@
# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!
__metadata:
version: 8
cacheKey: 10c0
"@types/node@npm:^24.7.2":
version: 24.10.0
resolution: "@types/node@npm:24.10.0"
dependencies:
undici-types: "npm:~7.16.0"
checksum: 10c0/f82ed7194e16f5590ef7afdc20c6d09068c76d50278b485ede8f0c5749683536e3064ffa8def8db76915196afb3724b854aa5723c64d6571b890b14492943b46
languageName: node
linkType: hard
"browser-extension@workspace:.":
version: 0.0.0-use.local
resolution: "browser-extension@workspace:."
dependencies:
"@types/node": "npm:^24.7.2"
languageName: unknown
linkType: soft
"undici-types@npm:~7.16.0":
version: 7.16.0
resolution: "undici-types@npm:7.16.0"
checksum: 10c0/3033e2f2b5c9f1504bdc5934646cb54e37ecaca0f9249c983f7b1fc2e87c6d18399ebb05dc7fd5419e02b2e915f734d872a65da2e3eeed1813951c427d33cc9a
languageName: node
linkType: hard
@@ -0,0 +1,2 @@
WXT_TWENTY_API_URL=
WXT_TWENTY_API_KEY=
@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.output
stats.html
stats-*.json
.wxt
web-ext.config.ts
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
@@ -0,0 +1,158 @@
# Twenty Browser Extension
A Chrome browser extension for capturing LinkedIn profiles (people and companies) directly into Twenty CRM. This is a basic **v0** focused mostly on establishing a solid architectural foundation.
## Overview
This extension integrates with LinkedIn to extract profile information and create records in Twenty CRM. It uses **WXT** as the framework - initially tried Plasmo, but found WXT to be significantly better due to its extensibility and closer alignment with the Chrome extension APIs, providing more control and flexibility.
## Architecture
### Package Structure
The extension consists of two main packages:
1. **`twenty-browser-extension`** - The main extension package (WXT + React)
2. **`twenty-apps/browser-extension`** - Serverless functions for API interactions
### Extension Components
#### Entrypoints
- **Background Script** (`src/entrypoints/background/index.ts`)
- Handles extension messaging protocol
- Manages API calls to serverless functions
- Coordinates communication between content scripts and popup
- **Content Scripts**
- **`add-person.content`** - Injects UI button on LinkedIn person profiles
- **`add-company.content`** - Injects UI button on LinkedIn company profiles
- Both scripts use WXT's `createIntegratedUi` for seamless DOM injection
- Extract profile data from LinkedIn DOM
- **Popup** (`src/entrypoints/popup/`)
- React-based popup UI
- Displays extracted profile information
- Provides buttons to save person/company to Twenty
#### Messaging System
Uses `@webext-core/messaging` for type-safe communication between extension components:
```typescript
// Defined in src/utils/messaging.ts
- getPersonviaRelay() - Relays extraction from content script
- getCompanyviaRelay() - Relays extraction from content script
- extractPerson() - Extracts person data from LinkedIn DOM
- extractCompany() - Extracts company data from LinkedIn DOM
- createPerson() - Creates person record via serverless function
- createCompany() - Creates company record via serverless function
- openPopup() - Opens extension popup
```
#### Serverless Functions
Located in `packages/twenty-apps/browser-extension/serverlessFunctions/`:
- **`/s/create/person`** - Creates a new person record in Twenty
- **`/s/create/company`** - Creates a new company record in Twenty
- **`/s/get/person`** - Retrieves existing person record (placeholder)
- **`/s/get/company`** - Retrieves existing company record (placeholder)
## Development Guide
### Prerequisites
- Twenty CLI installed globally: `npm install -g twenty-cli`
- API key from Twenty: https://twenty.com/settings/api-webhooks
### Setup
```
1. **Configure environment variables:**
- Set `TWENTY_API_URL` in the serverless function configuration
- Set `TWENTY_API_KEY` (marked as secret) in the serverless function configuration
- For local development, create a `.env` file or configure via `wxt.config.ts`
### Development Commands
```bash
# Start development server with hot reload
npx nx run dev twenty-browser-extension
# Build for production
npx nx run build twenty-browser-extension
# Package extension for distribution
npx nx run package twenty-browser-extension
```
### Development Workflow
1. **Start the dev server:**
```bash
npx nx run dev twenty-browser-extension
```
This starts WXT in development mode with hot module reloading.
2. **Load extension in Chrome:**
- Navigate to `chrome://extensions/`
- Enable "Developer mode"
- Click "Load unpacked"
- Select `packages/twenty-browser-extension/dist/chrome-mv3-dev/`
3. **Test on LinkedIn:**
- Navigate to a LinkedIn person profile: `https://www.linkedin.com/in/...`
- Navigate to a LinkedIn company profile: `https://www.linkedin.com/company/...`
- The "Add to Twenty" button should appear in the profile header
- Click the button to open the popup and save to Twenty
### Project Structure
```
packages/twenty-browser-extension/
├── src/
│ ├── common/
│ │ └── constants/ # LinkedIn URL patterns
│ ├── entrypoints/
│ │ ├── background/ # Background service worker
│ │ ├── popup/ # Extension popup UI
│ │ ├── add-person.content/ # Content script for person profiles
│ │ └── add-company.content/ # Content script for company profiles
│ ├── ui/ # Shared UI components and theme
│ └── utils/ # Messaging utilities
├── public/ # Static assets (icons)
├── wxt.config.ts # WXT configuration
└── project.json # Nx project configuration
```
## Current Status (v0)
This is a foundational version focused on architecture. Current features:
✅ Inject UI buttons into LinkedIn profiles
✅ Extract person and company data from LinkedIn
✅ Display extracted data in popup
✅ Create person records in Twenty
✅ Create company records in Twenty
## Planned Features
- [ ] Provide a way to have API key and custom remote URLs.
- [ ] Detect if record already exists and prevent duplicates
- [ ] Open existing Twenty record when clicked (instead of creating duplicate)
- [ ] Sidepanel Overlay UI for rich profile viewing/editing
- [ ] Enhanced data extraction (email, phone, etc.)
- [ ] Better error handling
## Why WXT?
We initially evaluated **Plasmo** but chose **WXT** for several reasons:
1. **Extensibility** - WXT provides more flexibility for custom extension patterns
2. **Chrome API Proximity** - Closer to native Chrome extension APIs, giving more control
3. **Type Safety** - Better TypeScript support for extension messaging
4. **Architecture** - More transparent build process and entrypoint management
## Contributing
This extension is in early development. The architecture is designed to be extensible, but the current implementation is intentionally minimal to establish solid foundations.
@@ -0,0 +1,69 @@
import typescriptParser from '@typescript-eslint/parser';
import path from 'path';
import { fileURLToPath } from 'url';
import reactConfig from '../../eslint.config.react.mjs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default [
// Extend shared React configuration
...reactConfig,
// Global ignores
{
ignores: [
'**/node_modules/**',
],
},
// TypeScript project-specific configuration
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: typescriptParser,
parserOptions: {
project: [path.resolve(__dirname, 'tsconfig.*.json')],
ecmaFeatures: {
jsx: true,
},
},
},
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
enforceBuildableLibDependency: true,
allow: [],
depConstraints: [
{
sourceTag: 'scope:sdk',
onlyDependOnLibsWithTags: ['scope:sdk'],
},
{
sourceTag: 'scope:shared',
onlyDependOnLibsWithTags: ['scope:shared'],
},
{
sourceTag: 'scope:backend',
onlyDependOnLibsWithTags: ['scope:shared', 'scope:backend'],
},
{
sourceTag: 'scope:frontend',
onlyDependOnLibsWithTags: ['scope:shared', 'scope:frontend'],
},
{
sourceTag: 'scope:zapier',
onlyDependOnLibsWithTags: ['scope:shared'],
},
{
sourceTag: 'scope:browser-extension',
onlyDependOnLibsWithTags: ['scope:twenty-ui', 'scope:browser-extension']
}
],
},
],
}
},
];
@@ -0,0 +1,22 @@
{
"name": "twenty-browser-extension",
"description": "Twenty Lead capture extension",
"private": true,
"version": "0.0.1",
"type": "module",
"dependencies": {
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@webext-core/messaging": "^2.3.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"twenty-ui": "workspace:*"
},
"devDependencies": {
"@types/react": "^18.2.39",
"@types/react-dom": "^18.2.15",
"@wxt-dev/module-react": "^1.1.3",
"typescript": "^5.9.2",
"wxt": "^0.20.6"
}
}
@@ -0,0 +1,48 @@
{
"name": "twenty-browser-extension",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "packages/twenty-browser-extension/src",
"projectType": "application",
"tags": ["scope:browser-extension"],
"targets": {
"dev": {
"executor": "nx:run-commands",
"options": {
"command": "wxt --mode development",
"cwd": "packages/twenty-browser-extension",
"color": true
},
"configurations": {
"development": {
"command": "wxt --mode development"
}
}
},
"build": {
"executor": "nx:run-commands",
"options": {
"command": "wxt build",
"cwd": "packages/twenty-browser-extension",
"color": true
},
"configurations": {
"production": {
"command": "wxt build"
}
}
},
"package": {
"executor": "nx:run-commands",
"options": {
"command": "wxt zip",
"cwd": "packages/twenty-browser-extension",
"color": true
},
"configurations": {
"production": {
"command": "wxt zip"
}
}
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Some files were not shown because too many files have changed in this diff Show More