Commit Graph

13952 Commits

Author SHA1 Message Date
github-actions[bot] 897d29b603 i18n - translations (#23417)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-07-28 13:22:25 +02:00
neo773 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>
2026-07-28 13:13:00 +02:00
github-actions[bot] 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>
2026-07-28 12:20:55 +02:00
Raphaël Bosi 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.
2026-07-28 10:08:37 +00:00
Raphaël Bosi 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.
2026-07-28 10:08:17 +00:00
Etienne 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. -->
2026-07-28 09:59:57 +00:00
Rashad Karanouh 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. -->
2026-07-28 09:46:14 +00:00
Rashad Karanouh 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. -->
2026-07-28 09:42:23 +00:00
martmull 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>
2026-07-28 08:51:40 +00:00
Abdullah. 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.
2026-07-28 08:06:23 +00:00
Weiko 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. -->
2026-07-28 07:54:24 +00:00
Weiko 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. -->
2026-07-28 07:54:15 +00:00
Weiko 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. -->
2026-07-28 07:53:42 +00:00
Weiko 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. -->
2026-07-28 07:53:29 +00:00
github-actions[bot] 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>
2026-07-27 21:03:52 +02:00
Paul Rastoin 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.
2026-07-27 17:30:29 +00:00
martmull 75e767f08b update exa twenty cli tools (#23379)
as ttitle
2026-07-27 17:17:42 +00:00
github-actions[bot] bd5d5a3c4e i18n - docs translations (#23381)
Created by Github action

Co-authored-by: github-actions <github-actions@twenty.com>
2026-07-27 19:16:50 +02:00
Weiko 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.
2026-07-27 16:55:10 +00:00
BOHEUS 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. -->
2026-07-27 16:47:22 +00:00
Paul Rastoin 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.
2026-07-27 16:45:10 +00:00
Weiko 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
2026-07-27 16:35:54 +00:00
Weiko 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.
2026-07-27 16:32:54 +00:00
Thomas Trompette 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. -->
2026-07-27 16:21:08 +00:00
martmull 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. -->
2026-07-27 16:20:13 +00:00
Thomas Trompette 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. -->
2026-07-27 15:52:15 +00:00
Raphaël Bosi 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. -->
2026-07-27 14:47:58 +00:00
Thomas Trompette 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. -->
2026-07-27 14:43:59 +00:00
Weiko 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.
2026-07-27 14:02:55 +00:00
Raphaël Bosi 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. -->
2026-07-27 13:51:05 +00:00
Weiko 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
2026-07-27 13:42:59 +00:00
github-actions[bot] 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>
2026-07-27 15:30:31 +02:00
Raphaël Bosi 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. -->
2026-07-27 13:21:38 +00:00
github-actions[bot] 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>
2026-07-27 15:07:33 +02:00
Raphaël Bosi 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.
2026-07-27 12:58:42 +00:00
Shinu Cherian 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. -->
2026-07-27 12:57:24 +00:00
Thomas Trompette 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.
2026-07-27 12:32:51 +00:00
Rashad Karanouh 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. -->
2026-07-27 11:57:23 +00:00
Abdullah. 302f46f0ea fix: bump brace-expansion to 5.0.8 in app lockfiles (Dependabot) (#23346)
## Summary

Bumps **brace-expansion -> 5.0.8** in the three app lockfiles whose copy
sits on the 5.x line, clearing **GHSA-mh99-v99m-4gvg** (high, vulnerable
`<= 5.0.7`) on those manifests:

- `examples/hello-world` (`^5.0.2`)
- `examples/postcard` (`^5.0.5`)
- `internal/self-hosting` (`^5.0.5`)

All three are caret ranges, so a recursive `yarn up -R brace-expansion`
lifts them with **no resolution and no `package.json` change**.

## Why the fixtures are not included

This advisory declares a single vulnerable range, `<= 5.0.7`, which
spans **every** major line - so the `brace-expansion@2.1.2` copies in
`seed-dependencies` and `common-layer-dependencies` are flagged as well.
But **2.1.2 is the last 2.x release** (1.x likewise ends at 1.1.16), and
the only patched version is **5.0.8**. Those consumers declare `^2.0.1`
/ `^2.0.2`, which caps below 3.0.0, so there is no in-range fix:
clearing them would mean forcing a cross-major jump from 2.x to 5.x via
a resolution, which is a behavior risk rather than a mechanical lift.

Same situation for the root alert
([1765](https://github.com/twentyhq/twenty/security/dependabot/1765)),
where `nx` pins `brace-expansion` 5.0.6 exact.

## Verification

- brace-expansion resolves to **5.0.8** in all three lockfiles.
- `yarn install --immutable` passes in each.
- 5.0.8 published 2026-07-23, clears the 3-day npm age gate.
2026-07-27 11:33:38 +00:00
github-actions[bot] f834b020b6 i18n - website translations (#23348)
Created by Github action

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23348?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>
2026-07-27 11:30:09 +00:00
github-actions[bot] 88f20a3731 i18n - translations (#23352)
Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
2026-07-27 12:34:28 +02:00
nitin a6b36422f9 Fireflies: upgrade to twenty-sdk 2.23 (#23349)
Fireflies was skipped by both SDK bump sweeps (#23124, #23165) and sat
on `twenty-sdk ^2.18.0` with no `engines.twenty` floor, while the rest
of the published set moved to `2.23.0-alpha.2`.

- `twenty-sdk` / `twenty-client-sdk` `^2.18.0` -> `2.23.0-alpha.2`
- adds `engines.twenty: ">=2.23.0"`

No source changes needed: the 2.19 identifier migration (#22601) only
affected apps referencing a standard object's system-field identifier,
defining a relation into a standard object, or calling the field-UID
derivation helper. Fireflies does none of those.

The `engines.twenty` floor means the app integration job needs a server
image at 2.23+, so it may fail on version mismatch rather than an app
defect, as in #22601.
2026-07-27 10:31:20 +00:00
Weiko cdd78462b9 fix: block route triggers for suspended workspaces (#23347)
## Problem

Logic function route triggers (app HTTP endpoints served under `/s/*`
and public domains) kept serving traffic for suspended workspaces. A
workspace suspended for non-payment (`activationStatus = SUSPENDED`)
still served its route triggers for the entire suspension window until
soft-deletion removed it from domain lookup. Every other trigger path
gates on activation status — cron triggers only process `ACTIVE`
workspaces — but the route trigger path had no check at all.

## Fix

`RouteTriggerService.getLogicFunctionWithPathParamsOrFail` now rejects
requests when the resolved workspace has `activationStatus = SUSPENDED`,
throwing a `RouteTriggerException` with a new `WORKSPACE_SUSPENDED` code
mapped to `403 Forbidden` in the REST exception filter. Scope is
intentionally limited to `SUSPENDED`; other non-active statuses and the
DB event trigger path are untouched.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23347?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: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-07-27 10:25:34 +00:00
github-actions[bot] 5948c167a0 i18n - website translations (#23196)
Created by Github action

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23196?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>
2026-07-27 09:55:17 +00:00
Guillaume Flambard 710d4da4b1 fix(emails): bump @react-email/render to ^2.0.6 to fix empty transactional email bodies (#23323)
## Problem

Fixes #23307. Every transactional email (workspace invite, password
reset,
email verification, etc.) is delivered with an **empty body** — no
title, text,
or CTA.

## Root cause

`twenty-server` pins `@react-email/render` directly at `^1.2.3`:

```jsonc
// packages/twenty-server/package.json
"@react-email/render": "^1.2.3",
```

In 1.2.3, `render()` reads `renderToReadableStream` **before** the email
template's async Suspense boundary (i18n/locale load) has resolved. The
result
is the Suspense fallback marker instead of the real markup:

```html
<!DOCTYPE html ...><!--$!--><template></template><!--/$-->
```

This was fixed upstream in `@react-email/render@2.0.6`
(*"await stream.allReady before reading renderToReadableStream
output"*).
`twenty-emails` already resolves a 2.x render via `react-email@6.5.0`,
so the
server's direct pin was simply stale — the two were out of sync.

## Fix

Bump the direct pin to `^2.0.6` (resolves to `2.1.0`) and regenerate the
lockfile. The server's `render()` imports now use the fixed 2.x.

> Note: a `1.2.3` entry remains in `yarn.lock` — it is an internal
transitive
> pin of `@react-email/components@0.5.3`, not the server render path, so
it is
> expected and harmless.

## Verification

Rendering `SendInviteLinkEmail` through the real `render()` (Node 24)
now
returns full markup (5.7 kB) with no Suspense marker and the resolved
invite
link + workspace content, instead of the empty fallback.

A jest unit test was intentionally not added: `@react-email/render` 2.x
uses a
dynamic import that jest's CJS runtime rejects ("A dynamic import
callback was
invoked without --experimental-vm-modules") — which is exactly why the
existing
email specs mock `render`. The fix was verified with a standalone Node
script.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23323?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>
2026-07-27 11:37:09 +02:00
Thomas Trompette 44ed0d5498 Fix phantom targetId field in workflow triggers for morph relations (#23290)
## Problem

In a workflow **record-change trigger** on `noteTarget`, the output
variables offered a `targetId` field that doesn't exist. A morph
relation reaches the frontend as a single field named `target` (the
per-target morph fields are grouped by `morphId`), so the output-schema
generators synthesized its foreign-key column as `` `${field.name}Id` ``
→ `targetId`. But `noteTarget` has no `targetId` column; its FKs are one
per target type: `targetCompanyId`, `targetPersonId`,
`targetOpportunityId`, etc. The phantom `targetId` never matched
anything in the event payload.

## Fix

New helper `getRelationIdFieldNames` returns the actual FK id column(s)
for a relation field:
- normal relation → `[`${name}Id`]`
- morph relation → one column per `morphRelations` target, via the
existing `computeMorphRelationGqlFieldJoinColumnName`
(`targetCompanyId`, `targetPersonId`, ...).

Used by the two output-schema generators:
- `generateRecordEventOutputSchema` — the record-change trigger output
variables (the reported symptom).
- `generateRecordOutputSchema` — record output for
form/find/update-record output schemas.

Scoped strictly to the output schema; no workflow component changes.

## Testing

- Unit tests updated to assert per-target columns instead of the phantom
`targetId` (both generators). 28 passing.
2026-07-27 09:35:06 +00:00
Thomas Trompette 46a3a83866 feat(workflow): mirror all workflowVersion writes to core in-transaction, drop async create/update dual-write (#23243)
Switches the workflowVersion -> core dual-write from the async,
best-effort listener to a **transactional mirror**, wires every
content-write funnel through it, and drops the async create/update
handlers. Core can no longer drift from the workspace on any covered
path: the core copy commits or rolls back atomically with the workspace
write.

## Helper (`WorkflowVersionCoreSyncService`)
Two entry points, both writing `core.workflowVersion` and stamping the
`coreWorkflowVersionId` soft-ref on the **caller's transaction
manager**:

- `writeWorkflowVersionAndMirror(workspaceId, write)` - for funnels that
don't own a transaction. Opens a workspace queryRunner, runs the
caller's workspace write on that manager, re-reads the row, mirrors to
core in the same tx, commits, then invalidates the trigger-map cache
post-commit.
- `mirrorWorkflowVersionWrite({ workspaceId, entityManager,
workflowVersion })` - for funnels that already own a queryRunner tx
(activation / deactivation / delete-cascade); they just gain this one
call on their existing manager before commit.

`invalidateAutomatedTriggerMaps` is public so tx-owning callers run it
post-commit.

## Funnels wired (all content writes now mirror in-transaction)
- `updateWorkflowVersionStepsAndTrigger` (central builder step/trigger
edit)
- edge create/delete (4 trigger/step writes)
- `createDraftFromWorkflowVersion` (update + insert),
`duplicateWorkflow` (content update), `updateWorkflowVersionPositions`
- iterator / if-else empty-node step writes
- `workflow.createOne` / `createMany` post-hooks (v1 draft insert)
- AI `create_complete_workflow` tool (v1 insert)
- activation / deactivation status writes (ACTIVE / ARCHIVED /
DEACTIVATED) on their existing tx
- `deactivateVersionOnDelete` cascade (ACTIVE -> DEACTIVATED) on its
existing tx

Direct `workflowVersion.createOne/createMany` is forbidden by a
pre-hook, so there is no un-funneled create path.

## Async listener trimmed
`handleCreated` and `handleUpdated` are removed: every create/update now
mirrors in-transaction, so the post-commit handlers were redundant and
were the source of the rollback-drift (an edit that rolls back still
emitted an `UPDATED` event carrying the uncommitted payload, which the
async listener wrote to core).

`handleRestored`, `handleDeleted`, `handleDestroyed` are **kept**.
Soft-delete/restore go through the generic ORM (not a funnel):
`handleDeleted` drops the core row on soft-delete, and `handleRestored`
recreates it on restore (the restore path just calls
`workflowVersionRepository.restore()`). Removing the restore handler
would leave restored versions with no core row, so the delete/restore
pair stays async.

## Why the core write is raw SQL
`core.workflowVersion` is on the core DataSource, not the workspace
DataSource, so a repository can't be pointed at it from the workspace
queryRunner's manager. But both schemas are one Postgres DB and a
queryRunner is a single connection, so a schema-qualified `INSERT INTO
core."workflowVersion" ... ON CONFLICT` on that manager participates in
the workspace transaction (the prefill util's pattern). The workspace
write and soft-ref write-back go through the ORM's
`repository.update(criteria, data, undefined, queryRunner.manager)`, so
the source-of-truth workspace write keeps its ORM machinery (actor
stamping, search vector, events); only the dumb core mirror is raw,
confined to the helper.

**jsonb:** the raw insert has no entity transformer, so
`triggers`/`steps` are passed as JSON strings (Postgres parses them) -
the inverse of the prefill core insert (the #23204 double-encode trap),
covered by the test. `universalIdentifier` is minted only for a new
link; on conflict only `triggers`/`steps`/`status` are updated.

## Test
In-process integration test: opens a workspace queryRunner, calls the
helper, asserts the core row is visible inside the tx with correct
native jsonb, rolls back, asserts the core row is gone - empirically
confirming one workspace queryRunner writes `core.*` in the same tx.

## Review feedback addressed
- **Duplicate atomicity:** `duplicateWorkflow` now inserts the draft
version with its final steps/trigger inside
`writeWorkflowVersionAndMirror`, so a mirror failure rolls back the
whole version instead of leaving an unmirrored empty draft.
- **Delete cascade:** `deactivateVersionOnDelete` moved its command-menu
cleanup after commit, so a rolled-back deactivation can no longer strip
the menu item from a still-active version.
- **Rollback drift / unlinked rows:** resolved structurally by the
in-transaction mirror + removal of the async CREATED/UPDATED handlers,
and by the soft-ref-field guard that skips mirroring (returns null) on
workspaces without `coreWorkflowVersionId`.
- **Unit suites:** the step-helpers, step-operations and edge suites now
provide a `WorkflowVersionCoreSyncService` mock whose
`writeWorkflowVersionAndMirror` runs the write callback against the test
repo; all three pass (35 tests).

## Verification
Rebased onto `origin/main`. `nx typecheck twenty-server` is green, the
three affected unit suites pass (35 tests), and every changed file
passes type-aware oxlint + oxfmt. Integration suites were failing only
on behind-main DB-init drift (`core.keyValuePair` / data-migration),
which the rebase resolves. Live end-to-end test on a running instance
still pending.
2026-07-27 09:17:17 +00:00
Weiko a96dc335ab fix: apply configured pool size to core database (#23322)
## Context

`PG_POOL_MAX_CONNECTIONS` is the server setting for the maximum number
of PostgreSQL clients in a connection pool. The workspace primary and
replica data sources already apply this setting, but the core TypeORM
data source did not.

Without an explicit `poolSize`, `node-postgres` uses its default limit
of 10. As a result, deployments configured with a larger pool still kept
the core pool at 10 connections per server process.

During bursts of core database work, requests could therefore wait for a
local pool connection even when PostgreSQL itself still had available
capacity. That acquisition queue adds latency before the query starts,
so database-level utilization alone does not reveal the bottleneck.

## What changes

The core data source now applies:

```ts
poolSize: Number(process.env.PG_POOL_MAX_CONNECTIONS ?? 10)
```

This makes the core data source consistent with the workspace data
sources and with the documented meaning of `PG_POOL_MAX_CONNECTIONS`.

## Expected impact

Deployments that configure a value above 10 can use that capacity for
core database operations instead of queueing behind the driver's default
limit. This targets short acquisition spikes affecting operations backed
by the core database.

The pool remains lazy, so this changes the maximum number of connections
available to each process, it does not eagerly open every configured
connection.

## Safety

- Deployments without `PG_POOL_MAX_CONNECTIONS` keep the previous limit
of 10.
- Query behavior, transaction behavior, and timeouts are unchanged.
- Workspace pool configuration is unchanged.
- Operators remain responsible for choosing a value compatible with
their total PostgreSQL connection budget and maximum server replica
count.

## Scope

This removes an unintended local connection-pool bottleneck. It does not
address the source of synchronized database bursts, which should be
handled separately by reducing unnecessary work.

## Testing

Added a regression test that loads the core data source with
`PG_POOL_MAX_CONNECTIONS=40` and verifies that TypeORM receives
`poolSize: 40`.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23322?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. -->
2026-07-27 08:58:41 +00:00
Weiko 42c598a33a Filter stale sync workspaces by active channels (#23321)
## Context

The hourly calendar and messaging stale-sync crons currently load every
active workspace and enqueue one recovery job per workspace. Each
recovery job then enters the workspace context and queries its channels,
even when that workspace has no stale sync.

As the number of workspaces grows, the cost of this check grows with
every workspace rather than with the number of syncs that actually need
recovery. Because both crons run on the hour, this also creates a
synchronized burst of mostly unnecessary queue, database, and
workspace-context work.

## What changes

The crons now use TypeORM repository `find` operations on
`calendarChannel` and `messageChannel` before enqueueing recovery jobs:

- Select only `workspaceId` from matching channels.
- Keep only active, non-deleted workspaces.
- Keep only the scheduled and ongoing stages handled by the existing
recovery jobs.
- Treat a sync as stale when `syncStageStartedAt` is null or older than
the existing 30-minute timeout.
- Deduplicate workspace IDs in memory before enqueueing.
- Enqueue the existing recovery job only for matching workspaces.
- Share the stage definitions between candidate selection and recovery
so they cannot drift independently.

## Before and after

Before:

1. Load every active workspace.
2. Enqueue a calendar job and a messaging job for each workspace.
3. Enter every workspace context.
4. Query its channels.
5. Usually find nothing to recover.

After:

1. Run one candidate lookup for calendar channels and one for message
channels.
2. Return only the workspace ID for each potentially stale channel.
3. Deduplicate those IDs and enqueue one job per affected workspace.
4. Let the existing recovery jobs recheck and recover those channels.

Database reads now scale with stale channel candidates, while queue and
workspace-context work scale with affected workspaces rather than the
total workspace count.

## Why deduplicate in memory

TypeORM repository find options do not provide `DISTINCT`, so these
lookups can return the same workspace ID once per stale channel. A `Set`
removes those duplicates before jobs are created.

This is a deliberate tradeoff:

- The database returns only UUIDs, not full channel records.
- The scans run hourly against channel tables, and stale candidates
should remain sparse.
- It keeps the query expressed through the typed repository API.
- It avoids adding a database sort or hash aggregation for `DISTINCT`.

If candidate volume becomes large enough for result transfer or
in-process deduplication to matter, database-side deduplication can be
moved into a dedicated repository query. A practical signal would be
tens of thousands of candidates per run, a high duplicate ratio, or
measurable lookup and event-loop latency.

## Safety

- The recovery jobs and sync-state transitions are unchanged.
- The candidate lookup uses the same stage lists and timeout constants
as the recovery jobs.
- Recovery jobs still recheck staleness after dequeueing, which protects
against a channel recovering between candidate selection and execution.
- Jobs are still enqueued sequentially with per-workspace exception
handling.
- Disabled and group channels are not newly excluded, preserving the
previous recovery behavior.

## Scope

This only changes hourly stale-sync detection. It does not change normal
calendar or messaging scheduling, imports, retry policies, or recovery
state transitions.

## Testing

Added unit coverage for:

- active and non-deleted workspace filtering,
- selecting only workspace IDs,
- scheduled and ongoing stage filtering,
- null or expired `syncStageStartedAt`,
- the configured stale timeout,
- application-side workspace deduplication,
- enqueueing one recovery job per affected workspace.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23321?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. -->
2026-07-27 08:56:28 +00:00
Abdullah. ed95b8cfde fix: bump postcss to 8.5.22 across app lockfiles (Dependabot) (#23340)
## Summary

Bumps **postcss -> 8.5.22** in the 13 twenty-apps lockfiles that carry
it transitively, clearing **GHSA-r28c-9q8g-f849** (high) on those
manifests: path traversal in previous source map auto-loading
(`sourceMappingURL`) leading to arbitrary `.map` file disclosure,
vulnerable `<= 8.5.17`.

Apps covered: document-generator, hello-world, postcard, self-hosting,
twenty-partners, call-recorder, people-data-labs, twenty-discord,
twenty-exa, twenty-fireflies, twenty-last-contact, twenty-linear,
twenty-slack.

Every app reaches postcss through a caret range (`^8.5.15`), so a
recursive `yarn up -R postcss` lifts it in each project with **no
resolution and no `package.json` change** - the diff is 13 `yarn.lock`
files and nothing else. Yarn resolves to **8.5.22**, the latest in range
(above the 8.5.18 fix floor).

## Not included

The **root lockfile** carries the same advisory but its postcss copies
are held by exact pins - `next` (8.4.31 in every stable release,
including 16.2.11) and `@mintlify/common` (8.5.14, unchanged in its
latest) - so no `yarn up` reaches it. That one needs a scoped resolution
and is handled separately.

## Verification

- postcss resolves to **8.5.22** in all 13 lockfiles; nothing at or
below 8.5.17 remains.
- `yarn install --immutable` passes in each of the 13 projects.
- 8.5.22 published 2026-07-22, clears the 3-day npm age gate.
2026-07-27 08:50:00 +00:00