902bc6db635f9c637601b5d496e039f45f6b101f
13964 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
902bc6db63 |
fix(ai-node) - scope AI agent node database tools to explicitly granted objects (#23400)
## Context An AI agent node scoped to a single object was still loading CRUD tools for the whole workspace, inflating every run's prompt to ~200k tokens (~110k on a standard seed workspace: 146 tools across 19 objects, 18 of them system objects). Two mechanisms caused this: the roles permissions cache force-grants every system object to every role (`isSystem ? true`), and blanket role flags (`canReadAllObjectRecords`, ...) grant all remaining objects. The per-object rows written by the agent Permissions tab were additive on top of that, so scoping an agent had almost no effect on its tool payload. ## What **Backend: explicit grants only for the agent node** - New opt-in flag `requireExplicitObjectGrants` on `ToolProviderContext`, set only by the workflow agent executor. - With the flag, `DatabaseToolProvider` generates CRUD tools exclusively from the role's explicit `objectPermission` rows: no row means no tools, and each verb gate reads the row directly (`canReadObjectRecords` for find tools, `canUpdateObjectRecords` for create/update/upsert, `canSoftDeleteObjectRecords` for delete). A verb left null is not granted; composed defaults and the system force-grant can no longer leak through. Composed permissions are still used for `restrictedFields`. - Explicit rows are read from the `flatObjectPermissionMaps` workspace cache key, fetched in the same `getOrRecompute` call as `rolesPermissions`: no extra query. - Without the flag (chat, MCP, tool index, workspace stats), behavior is unchanged: composed permissions, verified live (`getToolIndex` for an Admin returns the same 245 CRUD tools as before). - Removed the `CANNOT_ADD_OBJECT_PERMISSION_ON_SYSTEM_OBJECT` guard on `upsertObjectPermissions` so system objects can be granted explicitly. **Frontend: grant system objects from the agent Permissions tab** - The objects picker in the workflow agent side panel ends with a new "System objects" submenu listing all active system objects; picking one opens the same CRUD grant flow as regular objects. - Permissions granted on system objects now resolve their labels in the existing permission list and can be deleted (both previously looked up non-system objects only, which would have hidden such grants). Result: an agent granted one object ships ~10 tools instead of 146, cutting the prompt from ~110k tokens to a few thousand and the per-run cost accordingly. ## Notes - Removing the system-object guard affects the whole upsert path: user roles can also receive explicit system object rows via the API. A `canRead: false` row on a system object now takes effect at the query layer for that role. - The agent role is resolved as the first role of the permission config, matching `getObjectsPermissionsFromRolePermissionConfig` (multi-role is not supported yet). ## Tests - `database-tool.provider.spec.ts`: three new cases for the flag (object without a row emits nothing, partial row emits only granted verbs, absent flag keeps composed behavior even with zero rows, which guards the chat regression). - `object-permission.service.spec.ts`: the system-object case now asserts a successful upsert. - Integration: dropped the failing "system object" upsert case and its snapshot, added a successful system object upsert case. Both suites pass against a live server. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23400?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
dfea3af778 |
fix(ai-chat): enrich zero-output stream captures and keep client-error exceptions out of Sentry (#23426)
## What & why Two related fixes that clean up Sentry reporting for the AI chat flow. ### 1. Enriched zero-output stream captures The AI chat stream's rejection handler previously skipped only `AbortError` and captured everything else to Sentry as-is. Two problems: - The SDK's bare `NoOutputGeneratedError` carries no troubleshooting context, so the Sentry issues were unactionable (no model, provider, workspace, or conversation size). - Expected interruptions (user abort, `STREAM_INTERRUPTED`) still generated noise. The rejection handler now handles three cases inline: - `AbortError` and `STREAM_INTERRUPTED` are expected interruptions and are not captured. - `NoOutputGeneratedError` is replaced with a single error whose message carries the full context as plain JSON: model, provider, workspace, thread, stream, turn, message count, conversation size, elapsed time, and the underlying stream error - recorded via a new `onError` handler, which also keeps stream-level errors visible in the worker logs. - Anything else is captured unchanged. The stable message prefix and single capture site keep zero-output events grouped separately from raw provider errors in Sentry. ### 2. Keep client-error domain exceptions out of Sentry `BILLING_CREDITS_EXHAUSTED` (a 402, i.e. an expected "user out of credits" condition) was landing in Sentry. Root cause: `CustomException` carries no HTTP status, so the worker/BullMQ path hands the raw exception to `shouldCaptureException`, which can't tell a 4xx client error from a 5xx server error and captures everything. The GraphQL/REST edges convert exceptions first, but background jobs bypass those converters. Fix, mirroring how `HttpException.getStatus()` already works: - `CustomException` gains an intrinsic `statusCode`. - `shouldCaptureException` skips a `CustomException` whose `statusCode < 500`, as a branch symmetric to the existing `HttpException` check. This covers every path, including the worker. - `BillingException` populates `statusCode` from the existing `getBillingExceptionStatusCode` mapping, so credits-exhausted (402) stays out of Sentry while the 500-mapped billing codes are still captured. Exceptions that don't set `statusCode` default to undefined and are captured exactly as before, so other domains are unaffected until they opt in. ## Tests - ai-chat unit suite passes (13 suites, 76 tests). - Existing billing exception handler tests pass. - `typecheck` passes. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23426?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
ceb699c43f |
Message campaign backfill search field metadata (#23428)
<!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23428?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
b8e2a6e910 |
Unify remote element style declarations (#23263)
Front components run in a Web Worker with a fake DOM. Until now the worker had a hand-rolled `style` object for remote elements and the host had its own separate CSS-string parser: two implementations of the same parsing that kept drifting apart (several review rounds fixed edge cases in one copy but not the other). What changed: - One shared `createStyleProxy` now backs `element.style` in the worker, and one shared `parseCssDeclarations` feeds both the worker proxy and the host's `parseCssString`. Most of the diff is existing logic split out of `installStylePropertyOnRemoteElements` into small single-purpose utils (`splitCssDeclarations`, `stripImportantPriorityFromCssValue`, `normalizeCssPropertyName`, `formatCssValue`, ...), not new behavior. - `!important` is stripped from values instead of tracked. Nothing ever read priorities back, and the host applies styles through React inline styles, which cannot express `!important`. Rendering note: `color: red !important` used to reach React as an invalid value (property silently not applied); it now applies, without the priority. - Style writes flush to the host synchronously, exactly as on main. - The parser handles quotes, escapes and parentheses; CSS comments inside hand-written `cssText` are not supported. This shared proxy is also the base for the worker `getComputedStyle` stub in the geometry PR. Second of three PRs splitting the geometry mirror work. |
||
|
|
64001591f2 |
Fix numeric controlled input values in front components (#23421)
A front component rendering a numeric input never showed its value
because the caret-preserving path only accepted strings:
- controlled: `<input type="number" value={42}>` was rejected by the
value sync guard, so nothing was written to the host element
- uncontrolled: `defaultValue={42}` was dropped from the initial value
seeding
Numeric values are now stringified in both places. Also adds a test
asserting `createCaretPreservingElement` forwards its ref to the
rendered element.
The controlled case and the ref test were flagged by cubic on #23264
|
||
|
|
4c904aa44c |
fix(workflow): keep Limit and Offset when changing the Search Records object (#23423)
Fixes the second bug reported in #23387. ## Problem In the Search Records action, changing the Object silently reset `Limit` to `1`. A user who had set `Limit = 100` and then switched object (or switched away and back) ended up with a step that returns exactly one arbitrary record, with no indication beyond a small `1` in the side panel. Reproduced on `main` against a local instance, checking the persisted draft version: ```json { "limit": 1, "offset": 0, "objectName": "person" } ``` `handleOptionClick` rebuilt the entire form as `{ objectNameSingular, limit: 1, offset: 0 }`, discarding whatever the user had entered. `1` is the server-side default for a newly created `FIND_RECORDS` step, so this was effectively a revert-to-creation-default on every object change. ## Change Carry `limit` and `offset` over instead of hardcoding them. `filter` and `orderBy` are still dropped by omission, which is correct: they reference fields of the previous object. ## Test Added `KeepsLimitAndOffsetWhenObjectChanges` to the existing story file. It switches the object and asserts `onActionUpdate` receives `{ objectName: 'company', limit: 100, offset: 20 }`. Confirmed the test is not vacuous: reverting the fix makes it fail with exactly the reported symptom (`limit: 100 -> 1`, `offset: 20 -> 0`). ## Not addressed here The headline bug in #23387 (filters made only of value-less operators never persisting) does not reproduce on `main`. I ran the reporter's steps with `Is in past` OR `Is today (UTC)` and both rules plus the `OR` group were written to the draft version correctly. Persistence hangs off `useUpsertRecordFilter`, which fires the advanced-filter `onUpdate` on every upsert, so operand changes save just as value changes do. The reporter is on ~v2.18.x and did not re-test on a recent release. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23423?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
11447bd96f |
fix: make add-select-option work on record detail pages (#23420)
Fixes #23339 Follow-up to #23410, which fixed the neighbouring issue (#23341) for users *without* the `DATA_MODEL` permission. ## Problem In #23339 the reporter added a multiselect field to Person and then found the inline "create option" prompt unresponsive. They clearly have `DATA_MODEL` permission, since they just created the field, so the permission check isn't what's blocking them. The blocker is the *other* precondition. Both hooks read the object name from the router: ```ts const { objectNamePlural } = useParams(); ``` `objectNamePlural` only exists on record index routes (`/objects/:objectNamePlural`). Record **detail** pages are `/object/:objectNameSingular/:objectRecordId`, so on a record page the param is `undefined` and: - `useCanAddSelectOption` returns false via `isNonEmptyString(objectNamePlural)` - `useAddSelectOption` bails out at `if (!fieldName || !objectNamePlural) return;` So the action was dead on record pages for **every** user, admins included, and the navigation target it needed was never reachable from there. ## Fix Resolve the field and its object from `fieldMetadataId`, which `FieldDefinition` already carries, instead of reading the object name off the URL: ```ts const { fieldMetadataItem, objectMetadataItem } = useFieldMetadataItemById(fieldMetadataId); ``` This drops the route dependency entirely, so the action behaves the same wherever the field is rendered, and `canAddSelectOption` now reflects only the real permission check. It also lets both hooks take a single `fieldMetadataId` argument: `fieldMetadataItem.name` is the same value the callers were previously passing as `fieldName`, so that parameter is no longer needed. Resolving both values from one id means the guard and the action can't disagree about which field they're describing. `useFieldMetadataItemById` is used rather than `useFieldMetadataItemByIdOrThrow` because a lookup miss should disable the prompt, not crash the field input. ## Reproduction On the code the reporter was running (immediately before #23410), as an **admin** with full `DATA_MODEL`, on a company record page, typing a value matching no option: - `Add "…" to options` renders - clicking it does nothing — URL unchanged, no navigation - pressing <kbd>Enter</kbd> does nothing either which matches #23339 exactly, including the note about the Enter keypress. After #23410 the same root cause shows up differently: the prompt is no longer rendered at all on record pages, since the guard it's now gated on is false there. Still broken, just silent. ## Testing Verified manually on a local instance, swapping only these files between three states and re-running the identical steps on the same cell. | code state | user | route | result | |---|---|---|---| | before #23410 | Admin | `/object/company/:id` | prompt shown, click and Enter both do nothing | | current main | Admin | `/object/company/:id` | prompt not shown, action unreachable | | **this PR** | Admin | `/object/company/:id` | prompt shown, navigates to `/settings/objects/companies/workPolicy?newOption=…` | | **this PR** | Admin | `/objects/tasks` (`Status`, single select) | still works, navigates to `/settings/objects/tasks/status?newOption=…` | | **this PR** | Member (no `DATA_MODEL`) | `/object/company/:id` | prompt not shown | The settings form opens with the typed value prefilled alongside the existing options, so the end-to-end flow works from a record page for the first time. The Member row confirms #23341 stays fixed: dropping the route dependency doesn't weaken the permission gate. The single-select row covers `SelectFieldInput`, which takes the same change. `nx lint:diff-with-main twenty-front` and `nx typecheck twenty-front` both pass. |
||
|
|
7b46c3ed31 |
use legacy validate build and run for standard metadatas (#23419)
<!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23419?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
6c66d4c862 |
fix(ai-agent): use a non-workflow base system prompt for programmatic agent runs (#23394)
`AgentAsyncExecutorService` hardcoded `WORKFLOW_SYSTEM_PROMPTS.BASE`, so every caller was told "You are executing as part of a workflow automation" and "your output may be used by downstream workflow nodes". That is only true for the workflow AI-agent action. The `runAgent` API (used by apps such as the call recorder) and agent evaluations got the same framing, which does not describe how they run or where their output goes. The executor no longer asserts its own execution context: `executeAgent` now takes a required `baseSystemPrompt` and each caller supplies its own. - Workflow AI-agent action passes `WORKFLOW_SYSTEM_PROMPTS.BASE` (unchanged behavior) - `runAgent` and evaluations pass the new `AGENT_RUN_BASE_SYSTEM_PROMPT` The param is required rather than defaulted so every call site states its context and no future caller silently inherits the wrong one. Prompt constants are also split one export per file, with the shared tool-usage guidance extracted into `TOOL_USAGE_STRATEGY` so both bases compose it. No GraphQL schema, SDK, or database changes. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23394?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
3f0236b590 |
fix(page-layout): let the column surface win over the solo presentation (#23412)
## Why In the side panel and on mobile, a tab holding a single widget renders with no gutter at all: the field list sits flush against the panel border. Regression from #23109. `getWidgetCardVariant` checked the derived presentation before the surface: ```ts if (presentation === 'solo') return 'solo'; const isSideColumnContext = isInPinnedTab || isMobile || isInSidePanel; ``` So a single-widget tab resolved to `'solo'` even in the side panel or on mobile, and `'solo'` has no branch in `WidgetCard`'s padding switch, so it falls through to `0`. The same widget used to match `variant === 'side-column' && !isEditable` and get `spacing[3]` (12px). The pinned left panel escaped this only because `PageLayoutLeftPanel` hardcodes `presentation: 'stack'` — the rule was already there ("the pinned left panel is always a column, a surface rule not a widget rule"), just applied at one call site instead of being the rule. ## Why only the Home tab looks broken Every widget that used to live on a `CANVAS` tab carries its own gutter, so losing the card padding costs them nothing: | Widget | Own horizontal padding | |---|---| | Timeline | `spacing[6]` | | Notes | `spacing[6]` | | Files | `spacing[6]` | | Tasks | `spacing[6]` | | **Fields** | **none** | `Fields` was the only widget on a `VERTICAL_LIST` tab, so it was the only one relying on the card for its gutter, and the only one that ends up flush. ## What Resolve the surface first: a column surface (pinned panel, side panel, mobile) is always a column of cards, whatever the tab presentation is. Solo stays a main-tab-area concept. Header visibility is untouched: `showHeader` keys off `presentation`, not the variant, so a solo tab still shows no bare title row. The `Fields` widget does not regain the header it lost in #23109. ## Measured Side panel, custom object whose Home tab holds a single Fields widget (1600x1000, panel at x=1200): | | Card padding | First label x | |---|---|---| | main | `0px` | 1221 | | this PR | `12px` | 1233 | 12px restored, matching what the pinned left panel gives the same widget. ## Trade-off worth a second opinion In the side panel and on mobile, the activity widgets now resolve to `'side-column'` instead of `'solo'`, so they pick up the card's 12px on top of their own 24px, i.e. 36px instead of 24px. Nothing overlaps or clips, but it is a visible change on those tabs. If you would rather keep them at 24px, the follow-up is to drop the intrinsic `spacing[6]` from the activity cards and let the surface own the gutter everywhere. ## Test plan - `getWidgetCardVariant` tests extended: `'side-column'` now wins over `'solo'` for each of `isInPinnedTab` / `isMobile` / `isInSidePanel`. 13 tests pass. - 88 suites / 620 tests across `page-layout/widgets` pass. - `lint:diff-with-main twenty-front` clean. - Verified against a local stack: side panel on a single-widget Home tab, before and after. |
||
|
|
38e9d231bc |
fix: hide add-select-option prompt for users without data model permission (#23410)
Fixes #23341 ## Problem A user whose role lacks the `DATA_MODEL` permission flag still saw the `Add "…" to options` prompt when typing a value that matched no option in a multiselect. Clicking it did nothing. `MultiSelectInput` renders `AddSelectOptionMenuItem` based purely on whether the callback exists: ```tsx {onAddSelectOption && searchFilter && filteredOptionsInDropDown.length === 0 && ( ``` `MultiSelectFieldInput` always passed a callback, and did the permission check *inside* it: ```tsx const handleAddSelectOption = (optionName: string) => { if (!canAddSelectOption) { return; } addSelectOption(optionName); }; ``` So the guard suppressed the click but not the render, which is exactly the reported symptom: the prompt is visible and inert. ## Fix Gate at the prop instead of inside the handler, so the menu item is never rendered when the action is unavailable: ```tsx onAddSelectOption={canAddSelectOption ? addSelectOption : undefined} ``` The wrapper is now redundant and removed; `addSelectOption` already has the matching `(optionName: string) => void` signature. `SelectFieldInput` had the byte-identical bug (`SelectInput` gates on `onAddSelectOption &&` the same way), so it gets the same change. ## Note on scope `useCanAddSelectOption` requires `objectNamePlural` from the route in addition to the permission flag: ```ts const canAddSelectOption = userHasPermissionToEditDataModel && isNonEmptyString(fieldName) && isNonEmptyString(objectNamePlural); ``` Record *detail* pages (`/object/:objectNameSingular/:recordId`) have no `objectNamePlural`, so the prompt was dead there for **every** user, admins included. This change hides it in that case too, which is the correct behavior since the click could never have worked. ## Testing Verified manually against a local instance, toggling the patch in and out on the same cell so before/after is directly comparable. Company `Work Policy` (multiselect) in the Companies table view, typing a string that matches no option: | user | route | before | after | |---|---|---|---| | Member (no `DATA_MODEL`) | `/objects/companies` | prompt shown, click does nothing | prompt hidden | | Admin | `/objects/companies` | prompt shown, click works | prompt shown, click works (navigates to `/settings/objects/companies/workPolicy?newOption=…`) | | Admin | `/object/company/:id` | prompt shown, click does nothing | prompt hidden | `nx lint:diff-with-main twenty-front` and `nx typecheck twenty-front` both pass. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23410?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
1064ae835b |
Remove ugly page card top-left rounded corner on mobile (#23414)
On mobile the main page card kept the desktop styling that makes it look attached to the navigation drawer: a rounded top-left corner (`border-radius: lg 0 0 0`) and a 1px ring box-shadow. Since the drawer isn't rendered inline on mobile, the card is full-bleed and the rounded corner plus hairline border look out of place. Changes in `PageCardLayout`: - Card: `border-radius: 0` and `box-shadow: none` below `MOBILE_VIEWPORT`, including the `.dark` override which would otherwise win on specificity - Wrapper: drop the `-3px` margin-left / `4px` padding-left that reserved the drawer seam Verified in the running app at 390px width on both the record show page and the record index, in light and dark mode: no full-width element carries a shadow or top-left radius anymore. --- _Generated by [Claude Code](https://claude.ai/code/session_01N6LfZg7JZ2FiYiJ9QcNucj)_ <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23414?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
897d29b603 |
i18n - translations (#23417)
Created by Github action --------- Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
1e58c3073c |
Feat/email composer improvements (#23188)
- Move composer to dedicated page - Add test email option - Auto saved as draft can be revisited from `objects/messageCampaigns` later - Campaign stats component https://github.com/user-attachments/assets/9e523116-e79b-496d-9c9d-3887e0c9213f <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23188?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --------- Co-authored-by: Félix Malfait <felix.malfait@gmail.com> |
||
|
|
30bbf4149a |
i18n - translations (#23409)
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23409?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --------- Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
46cf4cebd1 |
Guard stale chunk auto-reload against loops (#23362)
AppErrorBoundary auto-reloads on stale chunk errors, but if the server keeps returning stale assets (cached index.html, bad deploy) the reload lands back on the same failure and loops forever with no user interaction. Follow-up to #23359, which broadens the errors that trigger this reload. - Reload at most once per 60s per tab (sessionStorage timestamp); within the cooldown the error fallback shows instead, with its manual Reload button still unguarded. - The auto-reload waits for the Sentry capture (`captureException` + `flush`), bounded by a 2s timeout so a broken network cannot stall the reload. |
||
|
|
2bd1ece952 |
Redesign the external link popup for front components (#23404)
<img width="3840" height="1866" alt="CleanShot 2026-07-28 at 11 52 15@2x" src="https://github.com/user-attachments/assets/de081951-6b1f-4194-8452-8395a90f3746" /> Applies the Figma design to the confirmation popup shown before a front component navigates to an external site. New copy: "Open external link?", the destination as a pill, "Always allow links to this domain", and "Open link" as the confirm button. The popup is now its own component built on `ModalStatefulWrapper` because `ConfirmationModal`'s fixed spacing cannot produce the design's layout. The "always allow" checkbox stays checked by default, as before. The pill is a non-interactive span rather than a `RoundedLink`, so the destination cannot be opened outside the confirm flow, and it ellipsizes the path so the domain stays readable. |
||
|
|
74260a161d |
fix(ai): stop double-counting cache-creation tokens in reported token totals (#23405)
## Context Under AI SDK v6 usage normalization, `usage.inputTokens` is the **full prompt**: fresh (noCache) + cache-read + cache-creation tokens. Our `totalTokens` formulas still added `cacheCreationTokens` (extracted from provider metadata) on top of `inputTokens` — a leftover from the pre-v6 SDK generation, where flat `inputTokens` excluded cache tokens. The v6 upgrade changed the semantics under the formula's feet, so every Claude run using prompt caching reported a `totalTokens` inflated by exactly `cacheCreationTokens`. ## Evidence, traced through AI SDK source **1. The Anthropic provider folds cache tokens into `inputTokens`.** The raw Anthropic API reports `input_tokens` *excluding* cache tokens; the provider sums all three components — [`convertAnthropicMessagesUsage`, `@ai-sdk/anthropic@3.0.84`](https://github.com/vercel/ai/blob/%40ai-sdk/anthropic%403.0.84/packages/anthropic/src/convert-anthropic-messages-usage.ts): ```ts inputTokens: { total: inputTokens + cacheCreationTokens + cacheReadTokens, noCache: inputTokens, cacheRead: cacheReadTokens, cacheWrite: cacheCreationTokens, } ``` **2. ai core surfaces that total as the app-visible `usage.inputTokens`** — [`asLanguageModelUsage`, `ai@6.0.97`](https://github.com/vercel/ai/blob/ai%406.0.97/packages/ai/src/types/usage.ts): ```ts inputTokens: usage.inputTokens.total, ... totalTokens: addTokenCounts(usage.inputTokens.total, usage.outputTokens.total), ``` So the SDK's own `totalTokens` is already "full prompt (incl. cache read + creation) + output". **3. The value we were adding on top is the same one already inside `inputTokens`.** The provider also exposes the raw API field in metadata (`@ai-sdk/anthropic` dist): ```ts const anthropicMetadata = { usage: response.usage, cacheCreationInputTokens: response.usage.cache_creation_input_tokens ?? null, ... ``` `extract-cache-creation-tokens.util.ts` reads exactly `providerMetadata.anthropic.cacheCreationInputTokens` — the same `cache_creation_input_tokens` that step 1 already folded into `inputTokens.total`. Adding it again counts it twice. **Worked example** (matches the new pinning test): API returns `input_tokens: 400, cache_read_input_tokens: 600, cache_creation_input_tokens: 200, output_tokens: 500` → app sees `usage.inputTokens = 1200`, `providerMetadata.anthropic.cacheCreationInputTokens = 200` → old formula reported `1200 + 500 + 200 = 1900`; actual tokens processed: `1700`. All snippets are verbatim from the version tags in `vercel/ai` and match the installed `node_modules` dists. ## Provider independence `inputTokens + outputTokens` is correct for every provider Twenty routes through, not just Anthropic: - The v3 provider spec (`@ai-sdk/provider`) defines `inputTokens.total` as "the total number of input (prompt) tokens used", with `noCache`/`cacheRead`/`cacheWrite` as its components — and all 8 installed provider packages comply (verified in dists): `anthropic` and `amazon-bedrock` sum the components explicitly ([`convertBedrockUsage`, `@ai-sdk/amazon-bedrock@4.0.117`](https://github.com/vercel/ai/blob/%40ai-sdk/amazon-bedrock%404.0.117/packages/amazon-bedrock/src/convert-bedrock-usage.ts): `total: inputTokens + cacheReadTokens + cacheWriteTokens`); `openai`, `azure`, `google`, `mistral`, and `openai-compatible` pass through wire values that already include cached tokens; `xai` even detects which wire convention the API used and normalizes either way. - The removed `cacheCreationTokens` term was already 0 for every provider except Anthropic/Bedrock (`extract-cache-creation-tokens.util.ts` only reads those two metadata namespaces), so this PR is a strict no-op for OpenAI-style providers and only removes the double-count where it existed. Caveat: a custom `AI_PROVIDERS` entry pointing at a legacy V2-spec provider package bypasses this normalization (ai core's shim passes flat usage through verbatim); that path could misreport under any formula, and none of the built-in providers use it. ## What changed Four sites computed the inflated total: - `ai-billing.service.ts` — `quantity` on the emitted AI token usage event - `chat-execution.service.ts` — chat-turn usage event - `agent-async-executor.service.ts` — workflow-agent usage event - `build-ai-agent-step-log.util.ts` — workflow step log (display) The first three now compute `totalTokens = inputTokens + outputTokens`; the step-log util uses the SDK's `usage.totalTokens` directly (it receives the `generateText` usage object, where the field is guaranteed). The explicit sum is used where usage objects are hand-assembled or merged — e.g. the streaming path in `stream-agent-chat.job.ts` builds usage literals with no `totalTokens` field at all, so `usage.totalTokens ?? 0` would silently emit 0. Both forms are definitionally identical where the SDK object exists, since ai core computes `totalTokens` as `input + output` (see evidence above). **Impact: reported/analytics quantities only.** Billed credits (`creditsUsedMicro`) come from `computeCostBreakdown`, which already handles the cache-inclusive convention correctly and is unchanged. **Ops note:** `usageEvent.quantity` for cache-heavy workspaces steps down on deploy — dashboards trending this metric may want an annotation. Historical rows are not backfilled (per-row component fields aren't stored, so mixed-era rows can't be reliably corrected). ## How tested - Updated `build-ai-agent-step-log.util.spec.ts` expectation (155 → 150 with `cacheCreationTokens: 5` still present) - New pinning test in `ai-billing.service.spec.ts`: emitted `quantity` is 1700 (not 1900) for inclusive Anthropic usage with `cacheCreationTokens: 200` - New pinning test in `agent-async-executor.service.spec.ts`: emitted total is 150 (not 180) when steps carry `providerMetadata.anthropic.cacheCreationInputTokens` - 3 suites / 20 tests pass; oxlint, oxfmt, and `nx typecheck twenty-server` clean <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23405?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
7fe59bf42d |
feat(website): send the referring partner with a client brief (#23351)
**Pairs with #23344** (`twenty-partners` v1.4.1), which adds the `referredByPartner` relation and the Discord notification. This PR is the sender; that one is the receiver. **Merge #23344 first.** Its schema is a non-strict `z.object`, so an unknown `partnerSlug` is stripped rather than rejected — shipping this one first degrades silently (attribution dropped) rather than breaking, but there is no reason to. Until #23344 is deployed, this field goes nowhere. No dependency in the other direction and no shared files: #23344 is entirely inside `packages/twenty-apps`, this is entirely inside `packages/twenty-website`. ## What this does A visitor can reach the client brief form from two places: the marketplace listing page, or a specific partner's profile. Until now both produced an identical payload, so the partner whose page drove the lead was lost. This sends the partner's slug along with the brief when the form was opened from a profile page. #23344 resolves it to a Partner record and links it to the created Opportunity. ## How it flows `PartnerProfileCtas` links to `/partners/brief?partner=<slug>` → `page.tsx` reads and normalizes the param → prop threaded through `ClientBriefPageContent` → `ClientBriefWizard` → `buildClientBriefRequestBody`. The slug is inert context, never a form field, so the wizard reducer and `ClientBriefState` are untouched. The three CTAs on `/partners/list` (`MarketplaceHeader`, `MarketplaceMatchCard`, `MarketplaceBriefPrompt`) stay bare — a brief from the listing page has no referring partner, and the notification labels it "Marketplace listing". ## Why `normalizePartnerSlug` exists `clientBriefRequestSchema` is a `z.strictObject`. Forwarding a malformed `?partner=` value straight into the body would fail validation for the **entire request** and lose the brief — a bad trade for an attribution field the visitor never saw. So the param is normalized at the boundary: array-valued params take the first entry, and anything not matching `[a-z0-9-]{1,100}` is dropped to `undefined` rather than passed on. The charset mirrors the app's `slugify` helper, which is what produced the slugs in the first place. ## Testing 8 new cases — 6 for the normalizer (well-formed, absent, empty, bad charset, over-long, repeated param) and 2 for the schema. Suite: 456 passing, up exactly 8 from a 448 baseline. `oxlint` and `oxfmt --check` clean; `next build` compiles with no type errors. Verified in a browser rather than asserted: opening a partner profile, clicking "Submit a brief", and completing the wizard produces ```json {"firstName":"Jane","lastName":"","email":"…","companyName":"NetZero Test Co","need":"…","partnerSlug":"netzero-systems"} ``` on `POST /api/client-brief` → 200. `LocalizedLink` preserves the query string across locale prefixing (`localize-href.test.ts:20` already covers this; confirmed live on the FR route). ## Deliberately not included - **CTA-level attribution.** Which of the three listing-page CTAs was used is not tracked. That is click analytics, a different concern from partner attribution. - **Length bounds on the other brief fields.** `country`, `seatCount`, `timeline`, `budgetRange` and `companyName` remain unbounded, as they were before this PR. Worth tightening, but pre-existing and out of scope here. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23351?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
fea06bdd4b |
v1.5.1 — partners: Discord notification for client briefs + referring-partner attribution (#23344)
**Merge after #23295.** Targets `main`, but must land second: #23295 bumps `1.3.2 → 1.4.0`, and this bumps `1.4.0 → 1.5.1`. Merging this first would leave `main` at 1.5.1 and make #23295's bump conflict and regress the version. `package.json` is the only file the two branches share. App version: **v1.5.1**. ## What this does Posts a Discord notification when a client brief is submitted through the public marketplace form, and records which partner's profile page the brief came from. A visitor can reach the brief form from the marketplace listing page or from a specific partner's profile. Until now that context was lost. This adds a `referredByPartner` relation on Opportunity so the attribution is a queryable CRM fact rather than a line in a chat message. ## How it works `submitClientBrief` resolves the incoming `partnerSlug` to a Partner, sets the relation on create, then posts the embed inline. Inline rather than an `opportunity.created` database trigger, because that event cannot distinguish a brief from a TFT import — both are created by logic functions and both carry `createdBy.source === 'APPLICATION'`. A trigger would need a discriminator like "source is APPLICATION and `tftOpportunityId` is empty", which silently breaks the day a third logic function creates an Opportunity. The cost of going inline is that the Discord call sits in the visitor's request, so it uses a 3s timeout rather than the trigger path's 8s, and every failure is swallowed — a dead webhook can never turn a submitted brief into a failed one. ## Notable decisions - **Slug resolution ignores `validationStage` and `availability`**, unlike the marketplace profile query. If someone submitted a brief from a partner's page, that partner referred it, even if they go unavailable a minute later. Filtering would silently drop real attribution. - **An unresolved slug never fails the brief.** It logs a warning, leaves the relation unset, and still notifies. A brief is a sales lead; losing one over an attribution field the visitor never saw would be a bad trade. - **`referredByPartner` is separate from the existing `partner` field.** One is who sent the lead, the other is who works it. - **The Discord connector moved to `modules/shared/connector/`.** Two domains now need it, and `AGENTS.md` forbids importing logic sideways between domains. `postWebhook` gained `label` and `timeoutMs` parameters; the transport is otherwise unchanged. - Reuses the existing `DISCORD_WEBHOOK_URL` and `PARTNER_APP_FRONTEND_URL` variables — no new configuration to set on prod. ## Permissions `partner.role.ts` locks the new Opportunity field. `configure-partner-rls.ts` treats its skip-list as a closed allowlist of system columns, so an unlocked new field is reported as a discrepancy. Note that Opportunity RLS for partners is `(partnerUser IS me) OR (isListed = true)`, so on a **listed** brief any partner can read `referredByPartner` — i.e. see that a competitor referred it. Called out deliberately; happy to restrict it if that's not wanted. ## Testing 8 unit tests for the embed mapper (partner present/absent, truncation, absent optionals, no email in the payload, inline-row padding) and 4 for the schema. Full suite: 188 passing, lint clean. Verified end to end against a local workspace with a real Discord webhook. All three paths return `ok: true`; the persisted relation was confirmed via GraphQL rather than inferred from the status code: | Submission | `referredByPartner` | |---|---| | valid slug | linked to the partner | | no slug | `null`, embed reads "Marketplace listing" | | unknown slug | `null`, brief still succeeds | ## Follow-up, not in this PR `yarn rls:configure` fails before reaching its field-lock check — its retry path strips `predicateGroups` but the predicates still carry `rowLevelPermissionPredicateGroupId`, so the retry fails identically. Pre-existing and unrelated to this change (`configure-partner-rls.ts` is untouched here), but it means the script cannot currently verify the lock on a fresh workspace. The website side that sends `partnerSlug` is #23351. Until it ships, this is inert: no caller sends the field, and briefs behave exactly as before. Merge this one first — #23351 is the sender, this is the receiver. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23344?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
1f55234d0b |
fix(call-recorder): leave call when only recording bots remain (#23053)
## Problem Fixes [core-team-issues#2689](https://github.com/twentyhq/core-team-issues/issues/2689). `everyone_left_timeout` only fires when the bot is the sole remaining participant, and Recall counts other recording bots as participants. So when several bots share a meeting, none of them sees itself as alone. Recall does enable `bot_detection` by default, but it ships an empty `matches` list, so the name-based check can never classify anyone. The only detector that actually runs is the behavioural one, at its default 20 minute grace plus 10 minute timeout. A meeting left with only bots therefore stays open for around 30 minutes, and two Twenty bots in the same call never recognise each other at all. This happens when several workspace members are invited to the same meeting and each has the recorder preference on, or when third-party notetakers stay behind after the humans leave. ## What this does Sends a full `automatic_leave.bot_detection` block plus `silence_detection`: - **`using_participant_names`** — the configured recorder name, so co-scheduled Twenty bots recognise each other, plus a list of common notetakers. `timeout: 10`, which is Recall's enforced minimum; their example config shows `5` and the API rejects it. - **`using_participant_events`** — a participant that never speaks nor shares screen is treated as a bot. - **`silence_detection`** — Recall's documented example values (`activate_after: 1200`, `timeout: 300`). Previously unset, so it fell back to Recall's 20 + 60 minute default. Both bot detectors activate 5 minutes after the **meeting start time**, not 5 minutes after the bot joins. The bot joins early by a configurable amount, so anchoring to join time spent the grace period before the meeting existed — at a 10 minute early join, detection would have gone live 5 minutes before the meeting began. `everyone_left_timeout` is unchanged and still covers the ordinary case. Effect: | | before | after | |---|---|---| | Only bots remain | ~30 min | ~5 min after meeting start | | Someone leaves the call open after talking | ~80 min | ~25 min | ## Deferred De-duplicating bots per meeting URL, so several `callRecording`s in one meeting share a single bot instead of each spawning one. `bot_detection` is still needed for third-party bots, so this ships first. --------- Co-authored-by: ehconitin <nitinkoche03@gmail.com> |
||
|
|
c7919673af |
fix: lift root postcss to 8.5.23 (Dependabot) (#23396)
## Summary Clears the root postcss alert [1851](https://github.com/twentyhq/twenty/security/dependabot/1851): **GHSA-r28c-9q8g-f849** (high) - path traversal in previous source map auto-loading (`sourceMappingURL`) leading to arbitrary `.map` file disclosure, vulnerable `<= 8.5.17`. The root lockfile carried **two** vulnerable copies, both behind exact pins with no fixed upstream release: | Copy | Pinner | Latest release still pins | |---|---|---| | 8.5.15 | `next` (8.4.31 exact) | 16.2.12 -> 8.4.31 | | 8.5.14 | `@mintlify/common` (8.5.14 exact) | 1.0.1051 -> 8.5.14 | So no parent upgrade reaches the fix. The existing `next/postcss` resolution moves **8.5.15 -> 8.5.23** and a matching **`@mintlify/common/postcss`** pin is added, placed alphabetically among the other `@mintlify/*` entries. The caret consumers (`^8.4.38`, `^8.4.47`, `^8.5.15`) dedupe onto the same version. ## Verification - The two copies **collapse into a single `postcss@8.5.23` entry**; nothing at or below 8.5.17 remains. - `yarn install --immutable` passes. - 8.5.23 published 2026-07-24, clears the 3-day npm age gate. - `//resolutions` updated with the advisory, both pinners (and their latest-version evidence) and the drop condition. The app-lockfile side of this advisory shipped separately in #23340. |
||
|
|
ae0ffb1373 |
perf: use cache for view entity lookups (#23384)
## Context View child mutation guards resolve a parent view before checking access. The lookup service queried PostgreSQL for a single `viewId`, even though the same relationship already exists in the workspace flat-map cache. With 15 guards using this service, each guarded mutation could add an unnecessary database round trip. ## What changed - Replace the five workspace-scoped repositories with `WorkspaceManyOrAllFlatEntityMapsCacheService` - Load only the flat map matching the requested child kind - Resolve view fields, filters, filter groups, groups, and sorts by ID - Preserve the existing `null` behavior for missing entities Each lookup is keyed by entity ID, no workspace-wide filtering is introduced. ## Expected impact On a warm workspace cache, permission guards resolve the parent `viewId` without querying PostgreSQL. Cold caches retain the normal workspace cache recomputation behavior. ## Validation - Typecheck reports no errors in the changed file - Existing lookup semantics are preserved for all supported entity kinds and missing IDs <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23384?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
19903f89e5 |
Add indexes for channel webhook subscription external IDs (#23386)
## Context Incoming Microsoft messaging, Microsoft calendar, and Google calendar webhook notifications resolve their channel through `webhookSubscriptionExternalId`. The column was added without an index, so PostgreSQL has to scan the corresponding channel table for every notification. Under sustained webhook traffic, these repeated scans add unnecessary database work and keep core database connections occupied longer. ## What changed - Add a partial B-tree index on `messageChannel.webhookSubscriptionExternalId` - Add the equivalent index on `calendarChannel.webhookSubscriptionExternalId` - Register both indexes in the TypeORM entity metadata - Add an idempotent 2.25 fast instance upgrade command to create and remove them The webhook handlers and their queries remain unchanged. ## Why this design - The indexes contain only non-null subscription IDs, channels without an active subscription do not add index entries - A single-column index supports both the equality lookup used by Google and the `IN` lookup used by Microsoft - The indexes are intentionally non-unique, this preserves existing behavior and avoids making the upgrade fail if historical duplicate values exist - Subscription IDs are read much more often than they are updated, so index maintenance overhead should be negligible ## Expected impact Webhook channel resolution should require a targeted index lookup instead of a table scan. This reduces database work, shortens connection occupancy, and improves latency on webhook notification paths. This is a targeted database optimization. It complements the database pool changes, but is not expected to resolve every source of API tail latency by itself. ## Validation - Server typecheck passes - Oxlint and formatting checks pass - Upgrade command uses idempotent `CREATE INDEX IF NOT EXISTS` and `DROP INDEX IF EXISTS` statements <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23386?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
cc5ff4869d |
perf: use cache for role validation (#23383)
## Context Role assignment validation queried PostgreSQL only to check whether a role exists and whether `canBeAssignedToUsers` is enabled. Both values already exist in `flatRoleMaps`. This validation runs when inviting users and assigning a role to a user workspace. ## What changed - Replace the role repository lookup with `flatRoleMaps` - Resolve the role through the existing keyed flat-map helper - Preserve the existing role-not-found and role-not-assignable errors - Replace unused TypeORM module wiring with the flat entity cache module ## Expected impact On a warm workspace cache, role assignment validation uses an O(1) map lookup and avoids a PostgreSQL round trip. Cold caches retain the normal workspace cache recomputation behavior. ## Validation - Typecheck reports no errors in the changed files - Existing validation outcomes and exception codes are preserved <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23383?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
8481c76bfb |
perf: use cache for webhook reads (#23382)
## Context Webhook reads queried both the webhook and application tables, then rebuilt the same flat webhook representation already maintained by the workspace cache. This affected REST, GraphQL, and the webhook listing tool. ## What changed - Read `findAll` and `findById` from `flatWebhookMaps` - Keep `findById` as a keyed ID lookup - Preserve `findAll` ordering by `createdAt` - Remove unused webhook and application repository wiring The flat webhook cache contains only active webhooks and already includes the application universal identifier needed by the DTO conversion. ## Expected impact On a warm workspace cache, webhook reads avoid queries to both the webhook and application tables. `findAll` still iterates over every returned webhook, matching the original query's result cardinality, while `findById` uses a keyed lookup. ## Validation - Typecheck reports no errors in the changed files - `findAll` ordering and `findById` missing-record behavior are preserved <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23382?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
30aee1dee5 |
i18n - docs translations (#23389)
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23389?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
49e2272fb9 |
fix(workspace-migration): stop leaking workspace ids in delete action payloads (#23377)
Closes https://github.com/twentyhq/core-team-issues/issues/2732 ## Problem Workspace migration delete actions embedded the raw workspace-cache flat entity as their `flatEntity` payload, leaking: - `id`, `workspaceId`, `applicationId` - raw many-to-one join columns (`objectMetadataId`, `relationTargetFieldMetadataId`, ...) - raw FK aggregators (`viewFieldIds`, ...) - raw jsonb properties containing serialized relations (`settings`, `overrides`, `configuration`) Create actions already expose universal identifiers only. The asymmetry made identical migrations non-portable across workspaces (payloads embed random workspace primary keys) and caused snapshot flakiness in integration suites. ## Fix - Add `deleteFlatEntityForeignKeyAggregators` (raw-side counterpart of `deleteUniversalFlatEntityForeignKeyAggregators`, following the `flatEntityForeignKeyAggregator` / `universalFlatEntityForeignKeyAggregator` naming of `ALL_ONE_TO_MANY_METADATA_RELATIONS`). It strips base workspace-scoped properties, every property registered with a `universalProperty` counterpart in `ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME` (covers raw join columns and serialized jsonb, including cases not modeled as many-to-one relations like `labelIdentifierFieldMetadataId`), and raw one-to-many `...Ids` aggregators. Its scope is disjoint from the universal-side util. - Apply it in the delete branch of `WorkspaceEntityMigrationBuilderService` — the single point where delete-action `flatEntity` is attached — so the payload matches its `MetadataUniversalFlatEntity<T>` type at runtime. Universal `...UniversalIdentifiers` aggregators are kept (they are portable), so `BaseUniversalDeleteWorkspaceMigrationAction` needs no type change. - Regenerate the affected `successful-sync-application-workspace-migration` snapshot: the delete payload now only carries universal identifiers. Safe downstream: the runner resolves delete targets via `universalIdentifier` lookups in current maps and metadata events fetch the deleted entity from maps by `entityId`; no consumer reads the stripped properties (only create handlers consume `action.flatEntity`). Note: the `normalizeIdCollections` mitigation flag mentioned in the issue does not exist on `main`, so there was nothing to remove. ## Tests - New snapshot-based unit spec for the strip util (objectMetadata and fieldMetadata shapes, plus input immutability). - Full twenty-server unit suite: 6922 passed. - Integration with live DB: full `metadata/suites/application` (50 suites), object/field/index/agent metadata suites, all 26 `graphql/suites/view` suites, `failing-agent-deletion`, `object-identifier-update-side-effect-on-view-field` — all green, no other snapshot changes. |
||
|
|
75e767f08b |
update exa twenty cli tools (#23379)
as ttitle |
||
|
|
bd5d5a3c4e |
i18n - docs translations (#23381)
Created by Github action Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
d7b1ccaa21 |
Cache field metadata while processing common query results (#23353)
## Context `CommonResultGettersService` post-processes API query results after they are loaded. It recursively walks records and relations, identifies field metadata, and runs result handlers such as file URL signing. Production profiling of tail-latency requests showed local CPU concentrated in this service when processing large nested result sets. Before this change: - Field name maps were rebuilt for each recursive record-array call. A repeated one-to-many relation rebuilt the same child-object map once per parent. - Every record's keys were scanned three times, once for handlers, once for relations, and once for the metadata passed to handlers. - Each scan resolved names through an ID lookup. ORM-only keys such as join columns have no matching field metadata, and the non-throwing lookup handled those misses by throwing and catching an exception internally. This work is small for one record, but multiplies across every nested record and can block the Node.js event loop for large responses. ## What changed - Create an invocation-local processing context from the metadata maps already supplied to the service. - Build a `field name -> field metadata` map once per distinct object type. - Share that context across root records and recursive relation processing. - Scan each record once and reuse the resolved metadata for handlers and relations. - Resolve record keys with direct `Map.get` calls, so keys without metadata are skipped without entering an exception path. For example, when the same child object type is visited under 200 parent records, field-map preparation drops from 201 builds to 2, one for each distinct object type. Per-record metadata scans drop from three to one. ## Why this is safe - The cache exists only for one public `processRecord` or `processRecordArray` invocation. It is not stored on the singleton service and cannot retain metadata across requests or workspaces. - Handler selection, execution order, and existing duplicate-handler behavior are preserved. - Relation traversal order and relation-type behavior are unchanged. - Record keys without field metadata remain in the returned object. - Query selection, database access, pagination, and response shape are unchanged. ## Expected impact This removes repeated metadata preparation, array allocation, and exception construction from the hot path. The improvement should be most visible in API tail latency and event-loop delay for wide nested responses. Small responses should see little change. This does not reduce database time or the size of large responses. Response fan-out remains a separate concern if those requests are still too expensive after this optimization. ## Tests - Verify field handlers still run and fields without metadata are preserved. - Verify nested one-to-many records keep their output and ordering. - Verify field metadata is resolved once per distinct object type within a single invocation, and rebuilt on the next invocation. |
||
|
|
975b5c256c |
Documentation update ( Legal FAQ and more ) (#23266)
New legal section and minor fixes <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23266?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
68b26f00ba |
Type PageLayout manifest type prop with PageLayoutType (#23375)
Closes #23373 `PageLayoutManifest.type` was typed as `string`, so `definePageLayout({ type: 'NOT_A_VALID_PAGE_LAYOUT_TYPE' })` compiled fine. It is now typed as `` `${PageLayoutType}` ``, which rejects arbitrary strings while keeping both forms assignable: ```ts type: PageLayoutType.STANDALONE_PAGE type: 'STANDALONE_PAGE' ``` A string enum member is assignable to its own literal type, so `` PageLayoutType | `${PageLayoutType}` `` would have been the same type as `` `${PageLayoutType}` `` alone. Going the other way (`type: PageLayoutType` on its own) is strictly narrower and would break every app manifest in `packages/twenty-apps` plus the `create-twenty-app` template, which all pass raw strings. |
||
|
|
24ccdb9b5d |
Replace Redis key scanning with sorted-set event stream tracking (#23326)
## Context The `twenty_event_streams_live_total` gauge counted live streams by SCANning every `workspace:*:activeStreams` key and summing set cardinalities. A full metric refresh walks the entire Redis keyspace, on every server instance, and its cost grows with unrelated cache data rather than with the number of streams. ## What changed Adds a metric-only sorted set, `activeStreamExpirations`. Members are `workspaceId:eventStreamChannelId`, scores are expiration timestamps: - Create and successful heartbeat refresh: `ZADD` with score `now + EVENT_STREAM_TTL_MS` - Destroy and stale cleanup: `ZREM` - Gauge read: `ZREMRANGEBYSCORE` + `ZCARD` in one transaction The scan-and-count cache helper is removed. Scores are written at the same moments the stream key TTL is set, so a member expires exactly when its stream key would. Any missed cleanup (crashed pod, failed heartbeat) resolves itself at the next gauge read. Metric writes are best effort: failures are logged and never affect stream creation, refresh, or cleanup. Existing stream keys and application behavior are unchanged, and no migration is needed. ## Tradeoffs - One extra `ZADD` per 30-second heartbeat - During a rolling deploy, streams owned by old pods appear in the gauge after their next heartbeat (undercount bounded by one heartbeat interval) - A destroy racing a concurrent refresh can leave one orphaned member until its score lapses (gauge over-counts by 1 for at most one TTL) ## Testing - Unit coverage for the sorted-set cache helpers and the stream lifecycle (create, refresh success/failure, destroy, stale cleanup) - `npx nx typecheck twenty-server`, targeted Oxlint, 14 tests passing |
||
|
|
a66aacfb82 |
perf: deduplicate tool permission role loads (#23366)
## Context Building the tool catalog asks every provider whether it is available for the current role configuration. Several providers perform multiple permission checks, so one catalog build can evaluate the same roles repeatedly. Previously, each `checkRolesPermissions` or `hasToolPermission` call loaded the configured roles and their permission flags from PostgreSQL. These queries returned data that already exists in the workspace cache: - `flatRoleMaps` contains role settings and the IDs of assigned permission flags - `flatRolePermissionFlagMaps` links those assignments to permission flag universal identifiers This created redundant database round trips on the latency-sensitive tool discovery path. ## What changed Permission checks now evaluate roles from the existing workspace cache instead of loading `RoleEntity` records and relations from PostgreSQL. The new flow: 1. Load `flatRoleMaps` and `flatRolePermissionFlagMaps` through `WorkspaceCacheService` 2. Resolve every role ID from `flatRoleMaps` 3. Check `canAccessAllTools` or `canUpdateAllSettings` 4. If needed, check explicit permission flags with `flatRoleHasPermissionFlag` 5. Apply the existing union or intersection rule This also benefits callers outside the tool registry, without adding provider parameters or request-scoped context plumbing. The direct agent-only role deletion path now invalidates and recomputes the two consumed cache maps after deleting a role. This prevents that path from leaving stale permission data behind. ## Why this is safe The authorization behavior remains unchanged: - `shouldBypassPermissionChecks` still grants access without loading permission data - A union grants access when at least one role grants it - An intersection grants access only when every role grants it - Base role permissions and explicitly assigned permission flags are both supported - Empty, duplicate, or missing role IDs fail closed - Cache failures fail closed This PR does not introduce a separate permission cache. It reuses the existing workspace metadata cache and its invalidation model. ## Expected impact On a warm workspace cache, these permission checks no longer query the role tables. Repeated checks during catalog and schema construction become in-memory cache lookups, reducing database pressure and avoiding repeated network round trips. A cold cache can still require its normal database recomputation. Subsequent permission checks reuse the populated workspace cache. ## Test coverage The permission service tests cover: - Union and intersection behavior - Base role grants - Explicit permission flag grants - Unrelated permission flags - Permission bypass - Empty, duplicate, and missing roles - Cache failures - No role repository query during cached evaluation The agent-role tests also verify that deleting an unused agent-only role refreshes the relevant cache maps, while a role that remains assigned does not trigger deletion or invalidation. |
||
|
|
48f4c1661b |
fix(sse): resync records on reconnect and recover from silent query listener errors (#23357)
## Context
Live updates stop working in prod in a way that only a page refresh
fixes. Two independent holes in the SSE self-healing path, both silent.
## 1. Reconnecting restored the stream but never the data
Events emitted while the stream was down are not replayed, so any record
change during the gap stayed missing from the UI indefinitely. On
reconnect `SSEClientEffect` called `resyncMetadataStore()` and
dispatched `SSE_CLIENT_RECONNECTED_EVENT_NAME`, but the only listeners
were `AgentChatMessagesFetchEffect` and
`AgentChatStreamKeepAliveEffect`. No record surface listened. Metadata
self-healed, records did not.
This fires on every deploy, laptop sleep and network blip, and the
reconnect backoff is a uniform random draw up to 2 minutes, so the gap
is routinely long.
The event was also incomplete. It was dispatched on graphql-sse
transport reconnects only. When the keep-alive watchdog or an error set
`shouldDestroyEventStream` and `SSEEventStreamEffect` built a
replacement stream, nothing was dispatched at all.
`useTriggerEventStreamCreation` now dispatches it from the creation path
too, for every stream that replaces an earlier one in the tab.
Each surface is wired to the resync path it already uses, through an
optional `onSseReconnected` on `useListenToEventsForQuery`. That hook is
the single funnel every SSE subscriber already goes through, so the tab
reloads exactly what it declared an interest in and nothing else:
- Record table: reset virtualization, plus
`useRefetchAggregateQueriesForObjectMetadataItem` for the header count,
which is served by a separate aggregate query that the row reset does
not touch.
- Record board: `triggerRecordBoardInitialQuery({ shouldResetScroll:
false })`. Scroll position preserved.
- Workflow versions: `shouldWorkflowRefetchRequest`.
These are the same resets each component already runs on every record
event, so the only new thing is the trigger. `SSEClientEffect` keeps the
metadata store resync, which is genuinely global; that also fixes the
matching gap on the metadata side, since `resyncMetadataStore()` used to
be called straight from the graphql-sse `connected` callback and so
never ran for a watchdog- or error-driven stream re-creation.
**Known gap:** the record show page and workflow run detail are not
covered. Both read through `useFindOneRecord`, but their subscription
lives in a sibling component with no access to `refetch`. Wiring them
needs either `refetch` exposed from `RecordShowEffect` /
`useWorkflowRun`, or the subscription moved into the data owner — the
latter changes subscription lifetime, and `useListenToEventsForQuery`
unregisters by `queryId` on unmount regardless of other consumers. Left
out pending a decision.
## 2. A network error on `addQueryToEventStream` silently unsubscribed a
view forever
`handleError` in `SSEQuerySubscribeEffect` only reacted to
`CombinedGraphQLErrors`. On Apollo Client v4 a network failure or a 5xx
from a rolling pod surfaces as `ServerError` or a plain `Error`, so the
handler was a complete no-op: no Sentry capture, no stream teardown, and
`syncAdditions` returned before recording the listener as active.
Since neither `requiredQueryListeners` nor `activeQueryListeners`
changed, the driving effect never re-ran. That query stayed unregistered
server-side for the rest of the session while the stream looked healthy
and every other view kept updating live. Recovery required remounting
the component or refreshing.
The recovery now runs for every error type.
`getGraphqlErrorExtensionsFromError` is called unconditionally: it
accepts `unknown` and reads `extensions` off any object-shaped error, so
an error carrying a gracefully-handled `code` is still recognised as one
whether or not it is a `CombinedGraphQLErrors`.
Note: errors without extensions now reach Sentry, since
`isGracefullyHandledEventStreamError` returns false for them. That is
new noise during outages, but this failure class is currently completely
invisible.
## Testing
- `nx typecheck twenty-front` and oxlint `--type-aware` + oxfmt pass.
- Verified on a local instance with an A/B/A run. A row inserted
straight into Postgres emits no SSE event, which is exactly the state
after a disconnect; restarting the server then forces a reconnect. With
the fix the row appears and the count updates with no page reload;
reverted to `main` it stays invisible indefinitely. Redis confirmed the
stream had reconnected and re-registered its queries in the negative
run, so that result is the missing resync rather than a dead stream.
- Fix 2 is **not** exercised at runtime — it needs a network-level
failure on the `addQueryToEventStream` mutation specifically. Reasoned
about only.
- There are no existing tests for the `sse-db-event` module.
## Known gap
A tab's very first stream is not treated as a reconnection, since
`isRecreatedEventStream` is derived from
`lastSseEventReceivedTimestampState` already being set. If that first
stream connects but never receives its first message and is then
replaced, no resync is dispatched. That is the separate issue of
`SSEKeepAliveEffect` being gated on `sseEventStreamReady`, which is
itself only set by the first message: a stream that never becomes ready
is never watched and never torn down. Not addressed here.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23357?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
|
||
|
|
b94a889bcb |
Organize public apps properly (#23376)
remove "twenty-" prefixes from public folders and package names <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23376?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
2c49c4169c |
feat(workflow): remove async workflowVersion core dual-write listener (#23374)
## What Removes `WorkflowVersionCoreDualWriteListener` (and its now-empty module), replacing the last async best-effort core writes for workflow versions with synchronous mirrors. Adds one missing synchronous funnel so nothing is left uncovered. ## Why After #23356, the listener's `handleRestored` / `handleDeleted` / `handleDestroyed` handlers are redundant with the synchronous lifecycle mirror, so the async path (which can silently drift on failure) can go. While removing it I found one path the listener was **not** redundant on: **direct `deleteOneWorkflowVersion` (discard draft)** is an allowed operation (discard a DRAFT version that isn't the only version, via the `DISCARD_DRAFT_WORKFLOW` command) and had **no** synchronous post-hook. The async listener was the sole thing deleting its core row. Removing the listener without a replacement would have drifted on every draft discard. So this PR also adds a `workflowVersion.deleteOne` post-hook that mirrors the deletion to core. ## Coverage after this change | version lifecycle path | synchronous coverage | | --- | --- | | `deleteOneWorkflowVersion` (discard draft) | **new** `workflowVersion.deleteOne` post-hook | | delete via workflow cascade | `handleWorkflowSubEntities` -> `deleteCoreVersionsByWorkflowIds` (#23356) | | restore via workflow cascade | `handleWorkflowSubEntities` -> `recreateCoreVersionsByWorkflowId` (#23356) | | destroy via workflow | `workflow.destroy*` post-hooks (#23356) | | `deleteMany` / `destroyOne|Many` / `restoreOne|Many` version | blocked by pre-hooks ("Method not allowed") | ## Notes - The new post-hook re-fetches the version (`withDeleted`) to resolve its `coreWorkflowVersionId`, because the delete post-hook payload only carries the columns the client selected (the delete `RETURNING` set is built from `selectedFieldsResult.select`), so `coreWorkflowVersionId` is not reliably present. - `deleteCoreVersionsByWorkspaceVersionIds` deletes precisely by `coreWorkflowVersionId` (not by `workflowId`), so discarding one draft does not touch the core rows of the workflow's other versions. - The workflow-side `WorkflowCoreSyncModule` listener is intentionally left in place (separate migration track). ## Verification - `nx typecheck twenty-server` green - `nx lint:diff-with-main twenty-server` green - Added integration test `workflow-version-discard-draft-core-mirror`: activate v1, create a draft, discard it, assert only the draft's core row is removed and the active version's core row remains. - Live run on a dev instance still pending. ## Merge gate Per the migration plan, removing the async backstop should land only after the drift cron reports zero drift over a soak period. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23374?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
3c48e27b2e |
Fix stuck onboarding route on failed chunk preload (#23359)
Fixes [Sentry 7604159654](https://sentry.io/issues/7604159654/) (v2.20.0, Mobile Safari). The onboarding router preloads 7 lazy chunks on entry; Vite's CSS preload for SyncEmails rejected and three defects compounded: - `void SomePage.preload()` discarded the promise, so it became an unhandled rejection and the user got a raw `Unable to preload CSS for /assets/...css` snackbar. - `lazyWithPreload` cached the *rejected* promise and rendered via `throw preload()`. React pings on the rejection, re-renders, the component throws the same settled rejected thenable, the ping listener de-dupes, and the route hangs on its loader forever. - `checkIfItsAViteStaleChunkLazyLoadingError` only matched Chrome's message, so `AppErrorBoundary`'s reload recovery never fired for the CSS-preload or Safari variants. `lazyWithPreload` now records the failure in state instead of rethrowing, so the thenable thrown into Suspense always fulfills, `preload()` returns void and can never reject, and the render path throws the real `Error` to the boundary, which reloads. Two things worth knowing for review: `React.lazy` is not a substitute here (its initializer has no synchronous fast path, so it suspends even when the module is already loaded, reintroducing the loader flash #22392 removed), and the failure is deliberately sticky because Vite marks the dep `seen` before attempting it, so an in-document retry loads the JS without its CSS and silently renders an unstyled page. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23359?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
79bf20515d |
feat(workflow): mirror version delete/restore/destroy to core transactionally (#23356)
Next step in the workflowVersion -> core soft-ref migration. The transactional mirror (#23243) made **content** writes (create/update) drift-free. This does the same for the **lifecycle** events (delete / restore / destroy), which were still handled only by the async best-effort listener. It's the prerequisite for dropping that listener. ## What changed `delete` and `restore` already soft-delete / restore the workflow's versions inside `handleWorkflowSubEntities` (twenty doesn't cascade soft-deletes, so it does each sub-entity explicitly). So the core delete/recreate just sits next to the existing version write: - **delete** — after `workflowVersionRepository.softDelete({ workflowId })`, `deleteCoreVersionsByWorkflowIds` removes the `core.workflowVersion` rows (`workflowId IN (...)`). (`deactivateVersionOnDelete` no longer re-mirrors the deactivated version — that was recreating the core row it just deleted; it only flips the workspace status to `DEACTIVATED` so a restore comes back deactivated.) - **restore** — after `workflowVersionRepository.restore({ workflowId })`, `recreateCoreVersionsByWorkflowId` re-reads the restored versions and reuses the existing `upsertToCore` (which reuses the stored `coreWorkflowVersionId` soft-ref, so rows come back with their original ids and current status). - **destroy** — version destroy isn't done in `handleWorkflowSubEntities` (it happens via the generic cascade), so there's no existing place to hang the core delete. New `workflow.destroyOne`/`destroyMany` **post**-hooks call `deleteCoreVersionsByWorkflowIds` (batched `IN`) only after the destroy commits, so a rejected destroy can't remove core rows while the workspace versions survive. No new transactional wrappers or raw SQL — the delete/recreate reuse the existing `WorkflowVersionCoreSyncService` methods (`deleteFromCore`-style delete, `upsertToCore`). The async listener stays as an idempotent backstop until the cron soaks zero drift. ## Async listener kept as backstop `handleRestored` / `handleDeleted` / `handleDestroyed` stay for now. Both paths are idempotent (delete-of-deleted is a no-op; upsert converges), so they don't conflict. Those handlers come out in a follow-up once the consistency cron soaks zero drift - which this PR unblocks. ## Verification Lifecycle integration test — creates a workflow, **activates** the version (the active path is where the delete re-mirror bug bit), then asserts the core row: present -> gone after delete -> back after restore (as `DEACTIVATED`, same id) -> gone after destroy. Plus the existing `workflow-resolver` delete/restore suite (regression, since `handleWorkflowSubEntities` is shared). Also verified **live** on a running instance against the real DB: the full active-version lifecycle above, plus a batched `destroyWorkflows` on two workflows removing both core rows in one `IN` delete. `nx typecheck` + oxlint + oxfmt clean. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23356?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
5c23ddb1ac |
Dedupe common result handlers (#23364)
## Context `CommonResultGettersService` selects field handlers by mapping every returned record field to the handler registered for its metadata type. Handlers are shared instances, and each handler already receives the complete field metadata list. This means that when multiple fields have the same handled type, the same handler is added and executed multiple times. For example, a record with two `FILES` fields previously produced this execution list: ```text [objectHandler, filesHandler, filesHandler] ``` Each `filesHandler` execution processes both `FILES` fields. As a result, both file URLs were signed twice. With several fields of the same type, this can make the work grow quadratically. The same duplication can affect rich-text processing, including JSON parsing, serialization, and embedded file URL signing. ## What changed Field handler instances are collected in an insertion-ordered `Set` before execution: ```text [objectHandler, filesHandler] ``` Each distinct field handler now runs once per record and continues to process every matching field. ## Why this is safe - The object-specific handler still runs first. - Different field-handler types keep their first-seen order. - No field is skipped, handlers still receive the complete field metadata list. - Requests with zero or one field for a handled type are unchanged. - No cache or cross-request state is introduced. ## Expected impact This removes repeated synchronous file-token signing and repeated rich-text transformations for records with multiple fields of the same handled type. It also reduces event-loop blocking when large result sets contain several file or rich-text fields. ## Tests Added a regression test with two `FILES` fields. It verifies that both fields are processed while `signFileByIdUrl` is called exactly once per file, two calls instead of the previous four. Validated with: ```bash yarn nx jest twenty-server --runInBand --runTestsByPath src/engine/api/common/common-result-getters/__tests__/common-result-getters.service.spec.ts ``` Touched files also pass type-aware Oxlint and Oxfmt. |
||
|
|
590ae069e8 |
Support workspace member Me filter for relation fields in dashboards (#23282)
<img width="3024" height="1484" alt="CleanShot 2026-07-27 at 15 04 22@2x" src="https://github.com/user-attachments/assets/a57797b7-dbe9-4748-aeff-18667f1f69bb" /> Fixes #20225 Workspace member "Me" filters worked for standard actor fields (Created by / Updated by) in dashboard widgets but not for relation fields pointing to a workspace member (e.g. "Account owner"). In the advanced-filter UI, picking such a relation forced a relation traversal and never produced a filter you could set to "Me". For a many-to-one relation targeting workspaceMember, the relation-target sub-menu now offers a "filter by record" entry that creates a direct relation filter with the same "Me" multi-select picker used by view filters. Traversal (e.g. "Account owner -> Name") is preserved. No backend change is needed: the stored value matches view filters and is already resolved server-side. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23282?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
0c57d7c108 |
perf: reuse Google webhook OAuth client (#23361)
## Context A new client currently downloads signing certificates for every webhook ## Fix reuse same OAuth client instance ## Impact Probably small but not really risky to merge imho |
||
|
|
dbbad1bffa |
i18n - translations (#23367)
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23367?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --------- Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
2899058b5f |
Warn users before front components navigate to an external site (#23270)
https://github.com/user-attachments/assets/af3fb042-d066-4e0c-9348-f86ea92a6fcd Front component anchors render a real host `<a>`, so clicking a link to another domain performed an uncontrolled full-page navigation. This adds a phishing-resistant "you're leaving Twenty" confirmation modal before navigating to an external origin (Fixes [#23260](https://github.com/twentyhq/twenty/issues/23260)). The renderer intercepts external anchor clicks in `createHtmlHostWrapper` and hands the destination to a host callback via context; twenty-front owns the modal (reuses `ConfirmationModal`) and a per-application list of trusted origins persisted in localStorage. A "Don't ask again for this site" checkbox (checked by default) skips the modal next time for that app. Scope is external cross-origin http(s) links only; same-origin links keep native behavior. External links always open in a new tab, so a component can never navigate the Twenty tab away, even once its origin is trusted. The modal is rendered by the trusted host, so components cannot style or suppress it. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23270?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
7804111e6c |
i18n - translations (#23360)
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23360?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> --------- Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
56245a35af |
Stop leaking the refresh token in the social SSO redirect URL (#23061)
The Google/Microsoft callback for a sign-in with no target workspace
redirected to `/sign-in-up?tokenPair={...}`, putting a 60-day refresh
token in a query string. Those persist in browser history, `Referer`
headers and access logs.
It now carries a single-use, 5-minute opaque token in the URL fragment,
which the frontend exchanges over POST. Browsers never send the fragment
on the wire, so the token stays out of access logs, proxies and
`Referer` headers entirely. Redemption claims the row with a `DELETE`
guarded on `revokedAt`/`deletedAt` being null, so concurrent requests
cannot each mint a refresh token and a revoked token cannot redeem.
Enterprise SSO (OIDC/SAML) already used a POST exchange and is
unchanged.
```mermaid
sequenceDiagram
participant Browser
participant Server
participant DB
Note over Browser,Server: before, the redirect carried access + 60-day refresh in ?tokenPair
Browser->>Server: GET /auth/google/redirect
Server->>DB: store sha256(token), expires in 5 min
Server-->>Browser: 302 /sign-in-up#ssoExchangeToken=opaque
Note over Browser: fragment never sent back to any server
Browser->>Server: POST getAuthTokensFromSSOExchangeToken
Server->>DB: guarded DELETE, single-use claim
Server-->>Browser: access + refresh token, in the response body
```
Since the token is single-use, the refresh token is minted at redemption
instead of at callback, so an abandoned redirect leaves an inert expired
hash rather than a live credential.
Redemption lives in its own `SignInUpSSOExchangeTokenEffect` +
`useRedeemSSOExchangeToken`, mirroring the existing
`VerifyLoginTokenEffect` + `useVerifyLogin` pair, so
`SignInUpGlobalScopeFormEffect` only loses the vulnerable branch. Like
`useVerifyLogin`, the hook clears any stale token pair before
exchanging. The effect reads `window.location.hash` live and strips it
synchronously, which doubles as the StrictMode double-invocation latch.
Remaining exposure is the browser itself (history until the synchronous
strip, client-side scripts), same as any fragment-based OAuth response.
`loginToken` on the workspace-targeted branch still travels as
`/verify?loginToken=` and is replayable for 15 minutes; moving it to the
fragment too is a separate change.
A fast instance command adds a unique partial index on `("type",
"value")` for live SSO exchange tokens, so redemption is an index lookup
instead of a full scan of the shared token table and at most one row can
ever match.
|
||
|
|
b81ca99162 |
fix(twenty-front): hide layout editor UI when SystemPermissionFlag.LAYOUTS is missing (#23303) (#23343)
## Description Fixes #23303. This PR ensures that the layout editor UI and customization entry points are hidden and protected when a user lacks the `SystemPermissionFlag.LAYOUTS` permission flag. ### Changes Made: 1. **`useEnterLayoutCustomizationMode.ts`**: Added `useHasPermissionFlag(PermissionFlagType.LAYOUTS)` check inside `enterLayoutCustomizationMode` to return `false` and prevent entering customization mode if the user lacks permission. 2. **`WorkspaceSection.tsx`**: Updated the sidebar `WorkspaceSection` component to render the layout edit button (`IconTool`) only when `hasLayoutsPermission` is `true`. 3. **`ObjectLayout.tsx`**: Disabled customize and reset layout controls in the Data Model Object Details settings page if the user lacks `LAYOUTS` permission. 4. **`useEnterLayoutCustomizationMode.test.tsx`**: Added unit tests to verify that `useEnterLayoutCustomizationMode` correctly guards layout customization initialization based on permission. ## Testing - Added unit tests for `useEnterLayoutCustomizationMode` permission checks. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23343?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |
||
|
|
22a01dc1c6 |
Fix: password reset link returns FORBIDDEN for logged-in users (#21248) (#23335)
## Problem Fixes #21248. After upgrading, workspace members who open a password reset link while a token pair still exists in local storage get a generic `You do not have permission to perform this action.` (FORBIDDEN) error, blocking account recovery. ## Root cause Every GraphQL request passes through `GraphQLHydrateRequestFromTokenMiddleware` before any resolver. If a token is present it validates it; if no token is present it short-circuits and lets the request through unauthenticated. The reset flow was only ever designed for the unauthenticated case (the user is logged out, so no token exists). Two intended changes broke that assumption: - A token pair now persists in local storage at reset time (unified `accessOrWorkspaceAgnosticToken` + tokenPair moved off session cookies into local storage). - The Apollo auth link attaches `authorization: Bearer <token>` whenever any token pair exists, regardless of the operation. So the public `validatePasswordResetToken` / `updatePasswordViaResetToken` operations now arrive with a token that the middleware rejects, producing FORBIDDEN before the resolver runs. Note: the `PublicEndpointGuard` / `NoPermissionGuard` on these resolvers both just `return true` — they do not inspect headers and are not the gate. The middleware is. ## Fix Add a generic `skipAuthToken` operation-context flag. The auth link omits the `Authorization` header when a request sets it, staying agnostic of any specific operation or endpoint. The two public reset operations opt in at their call site in `PasswordReset.tsx`. This restores the exact unauthenticated path the flow was designed for, regardless of whether a token pair happens to sit in local storage. Nothing is reverted; all authenticated traffic is unaffected. ## Testing Ran the built frontend against a local backend, logged in so a `tokenPairState` was present in local storage, then opened a reset link and inspected the outgoing `ValidatePasswordResetToken` request: - Request headers: `accept`, `content-type`, `x-locale` only. No `authorization` header, despite a token pair being present. - With an invalid token the response is the resolver-level `Token is invalid` error (it reaches the resolver) instead of the middleware's FORBIDDEN. - With a valid token the query succeeds (`validatePasswordResetToken` returns the email + `hasPassword`) and the Set/Change Password form renders, so the recovery flow completes. Lint and typecheck pass on the changed files. |
||
|
|
e631c986a1 |
v1.4.0 — partners: auto-link partner user on workspaceMember.created (#23295)
**App version:** `1.4.0` (partners app — `packages/twenty-apps/internal/twenty-partners`) ## What Adds partner onboarding auto-linking: when a `workspaceMember` is created (invite signup), a DB-event-triggered logic function resolves the partner by the member's email and stamps `partnerUser` across the partner and its cascade (person, company, links, services, content, applications). ## Key design decision — data-linking only, no role assignment The trigger **does not** assign the Partner role. A logic function runs as an app **agent**, with no user session; `updateWorkspaceMemberRole` is guarded by `UserAuthGuard` + `AuthWorkspaceMemberId` and is unreachable from an agent, so the mutation silently no-ops regardless of permission flags. The dead role code (`ensure-partner-role` service, its role query/mutation, and the role mocks) is removed so the trigger's responsibility is unambiguous: resolve partner by email → link `partnerUser` cascade with retry-on-partial-failure. Role assignment, if wanted, belongs on the invite path (`sendInvitations` accepts a `roleId`), not the trigger. ## Changes - `on-workspace-member-created.logic-function.ts` — DB-event trigger on `workspaceMember.created`; skips internal (`@twenty.com`) and unmatched emails - `resolve-partner-by-email` / `link-partner-user` services + typed `graphql/` operations for the cascade - `normalize-invite-email` util - `partnerUserLinkedAt` field on Partner - Seed: one contact `Person` (with `partnerId` + email) and one `Company` per partner so onboarding is testable via a seeded invite email; drops the `person.city` write removed in SDK 2.25 that broke `yarn seed` ## Verification - Unit: **173/173 pass** (27 files) · `tsc --noEmit` clean · `oxlint` 0 warnings/0 errors - End-to-end: invited + signed in a seeded partner (`lena@act-education.example`) on the workspace subdomain; the trigger linked the member to the **Act Education** partner and the self-service **My Profile** page rendered the linked profile (`POST /s/my-partner-profile → 200`) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23295?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> |