80fb91c033dfd367f17ba58e2095526faa016e70
5649 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
80fb91c033 |
Add List View lab icon and make lab feature flag icons mandatory (#23930)
## Context The List View toggle in Settings → Lab rendered without an icon: the front end kept a hardcoded `Partial<Record<FeatureFlagKey, IconComponent>>` map, so nothing caught a public feature flag added without an icon. ## What this PR does Moves the icon into the public feature flag metadata, next to `label` and `description`, as a **required** field — so a lab flag now registers in one place and can't be declared without an icon (server typecheck fails otherwise): - `twenty-server`: `FeatureFlagMetadata` gains required `icon: string`; each `PUBLIC_FEATURE_FLAGS` entry declares its icon (`IconList` for List View — the icon already used for the List view type). `PublicFeatureFlagMetadata` GraphQL entity exposes it. - `twenty-front`: `SettingsLabContent` renders `getIcon(flag.metadata.icon)` via `useIcons`, the same metadata-driven icon pattern used across the app; the hardcoded icon map is deleted. - `twenty-ui`: registers `IconCalendarWeek` in `AllIcons` — it was importable but not resolvable by name through `useIcons`, so it would have silently fallen back to the default icon. - Generated artifacts (`twenty-front/src/generated-metadata`, `twenty-client-sdk/src/metadata/generated`) updated for the new field. ## Verification - `nx run-many -t typecheck,lint -p twenty-front twenty-server twenty-shared twenty-client-sdk twenty-ui` passes (oxlint + oxfmt clean). - Negative case: removing `icon` from a `PUBLIC_FEATURE_FLAGS` entry fails `twenty-server:typecheck` with `TS2741: Property 'icon' is missing … but required in type 'FeatureFlagMetadata'`. |
||
|
|
d464065044 |
Add a list view type (#23829)
https://github.com/user-attachments/assets/45c11b5b-8da6-43ee-89de-f3fca0b64038 https://github.com/user-attachments/assets/a1b22a00-f6c8-4074-ae98-00a9a960e62f <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23829?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: neo773 <huzef@twenty.com> Co-authored-by: Félix Malfait <felix@twenty.com> |
||
|
|
43f11cdd3a |
Expire webhook subscriptions whose refresh token is dead (#23907)
Follow-up to #23707. Token errors thrown while building the OAuth client never reach the driver-exception mapping, so they landed in `handleUnknownException`: channel marked FAILED, captured to Sentry, rethrown (captured again by the queue explorer). The renewal cron re-selects FAILED channels every tick, so a dead refresh token looped forever. Routes REFRESH_TOKEN_NOT_FOUND and INVALID_REFRESH_TOKEN to the existing expiry path, matching the message and calendar import handlers. Sampled 160 events across [TWENTY-SERVER-J1F](https://twenty-v7.sentry.io/issues/7603992092/) (~5.9k/day) and [TWENTY-SERVER-JBZ](https://twenty-v7.sentry.io/issues/7617075015/) (~1.5k/day): 100% originate here. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23907?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: neo773 <huzef@twenty.com> |
||
|
|
6d4f03505b |
i18n - translations (#23916)
Created by Github action --------- Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
9e3c3131f7 |
feat(run-agent): let apps run an agent on behalf of a workspace member (#23470)
## Why `runAgent()` always runs with the agent's own role, so an app has no way to scope a run to the person who triggered it. Chat-style apps (Slack, Discord, Teams) need the opposite: the agent should never be able to do more than the member who asked. This is the server/SDK prerequisite for per-user permissions in the Slack app (#22984). It is self-contained and reviewable without any Slack context. > **Scope note.** Review surfaced two authorization problems adjacent to this code that are not part of the original feature — a cross-app agent hole (#21157) and two fail-open branches in application-token auth. Both are fixed here rather than deferred, since they sit directly on the path this PR changes. They are called out separately below so they can be reviewed on their own terms. ## The feature - **`runAsWorkspaceMemberId` (optional) on `RunAgentInput`** — shared type, DTO, and the generated GraphQL artifacts. - **`AgentActorContextService.buildRunAsWorkspaceMemberContext`** resolves member → userWorkspace → role and returns an actor context, a *user* auth context, and the role id. Mirrors what `WorkflowExecutionContextService` already does for acting on behalf of a user. - **`AgentRunService`** swaps the application auth context for the member's, passes their actor context, and attributes AI credit usage to them. - **`buildAgentRolePermissionConfig`** (new util) returns `intersectionOf: [agentRoleId, runAsRoleId]`, agent role first — explicit object grants in `database-tool.provider` resolve against the first role, so it defines which objects are in scope at all and later roles only narrow permissions on them. Collapses to a single entry when the member already holds the agent role, because the permission-flag checks reject an intersection listing the same role twice. - **`ToolContext`** gains an optional `rolePermissionConfig`. The lazy tool path resolved permissions from a single `roleId`, so without this the narrowing would not reach the tool catalog or call-time `execute_tool` — and lazy is the strategy `runAgent` uses. Falls back to the previous `unionOf: [roleId]` default when absent. - Docs: a "Running on behalf of a workspace member" section in `skills-and-agents.mdx`. Omitting the field preserves today's behavior exactly, which is what autonomous runs (scheduled jobs, database-event triggers) need. **Fails closed:** an unresolvable member errors rather than falling back to the agent role, which would grant more than the caller asked for. ## Who may name a member `runAsWorkspaceMemberId` names another person, so it needs an authorization rule of its own. An application token is not sufficient on its own: `frontComponent(id)` is guarded by `UserAuthGuard, NoPermissionGuard` and mints an `APPLICATION_ACCESS` token pair for the requesting user, so any authenticated user can obtain one for an installed app. Those tokens record who they were minted for, and the caller cannot strip that. The rule keys on that binding: | Token | May name | | --- | --- | | No application token | nothing — rejected | | Application token **with** a user binding | only that user's own member | | Application token with **no** user binding | any member | The third row is unattended app code — a database-event-triggered logic function is the Slack worker's path, and `client_credentials` or API-key-minted tokens land here too. ## Adjacent fixes **Cross-app agents** (pre-existing, #21157). The agent lookup was not scoped to the caller, so any app token could run any agent in the workspace, including one belonging to an app with wider permissions — while `skills-and-agents.mdx` promised an app can only run its own. Now rejected with `RUN_AGENT_NOT_ALLOWED`. Guarded on `isDefined(callerApplication)`, so callers without an app token are unaffected; `twenty-front` never calls `runAgent`. **Two fail-open branches in `validateApplicationToken`.** Both populated the auth context conditionally instead of failing closed, and both are now asserted, making the application path structurally identical to `validateAccessToken`: 1. An unresolvable user left the token presenting as *unbound*, so removing someone from a workspace widened their live token instead of revoking it, until it expired. 2. A missing workspace member let the token carry on with the application's own permissions after that member was removed or deactivated. Both mirror `validateAccessToken`, down to its `PENDING_CREATION` / `ONGOING_CREATION` escape hatch. **Behaviour change beyond this PR:** an application token whose user has been removed now 401s where it previously degraded to app-only. That is the point, and it matches access-token semantics, but it is shared auth and worth a careful look. ## Known limitation If the app's own agent role declares row-level predicates, those are not applied in run-as mode, because the query builders resolve row-level rules from a single role via the auth context. The member's own row-level rules do apply, which is the direction that matters here. Multi-role row-level support does not exist anywhere in the codebase today. ## Tests | Check | Result | | --- | --- | | ai-agent-execution, tool-provider, record-crud, user-workspace, full auth tree | 79 suites, 666 passed | | `nx typecheck twenty-server` | clean | | oxlint + oxfmt on the changed server files | clean | Both auth regression tests were verified against the pre-fix code — each fails when the fix is reverted, so they guard the behaviour rather than passing incidentally. ## Note for reviewers Rebased onto `main`, then merged `main` in once more after #23395 landed. The `getObjectsPermissionsFromRolePermissionConfig` intersection fix this PR originally carried has since landed on main independently, and main's version is stricter — it denies when an intersected role is missing from the cache rather than treating it as empty — so this PR takes main's and no longer touches that file. `RunAgentInput` now composes with the `prompt` | `messages` XOR from #23395: `runAsWorkspaceMemberId` sits on the base object, so it is available to both variants. |
||
|
|
569e178dbc |
chore: bump version to 2.30.0 (#23914)
## Summary - Moves current version to previous versions array - Sets TWENTY_CURRENT_VERSION to the new version - Updates TWENTY_NEXT_VERSIONS with the next minor version - Bumps twenty-client-sdk, twenty-sdk, and create-twenty-app to the same version ## Checklist - [ ] Verify version constants are correct - [ ] Verify npm package versions match <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23914?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 Action Deploy <github-action-deploy@twenty.com> |
||
|
|
7f0bae5b5f |
Add global admin panel chat list with onboarding filter and enriched transcript (#23757)
https://github.com/user-attachments/assets/ee22d0d7-6ea0-4d49-a3d2-41ce19089943 Adds a cross-workspace chat list to the admin panel (admin-panel/chats, linked from the AI tab) so we can analyze onboarding AI chats and improve the workspace-setup prompts. - Filters: onboarding only, has error, no user reply; search by workspace, user email or thread id; server-side sort by message count, replies, created or updated, with pagination. The list opens unfiltered so every chat is visible by default. - Onboarding threads are detected by fingerprint (hidden kickoff message OR deterministic uuid v5 id), so all existing setup chats are covered retroactively. The allowImpersonation gate is enforced in the query. - Replies count answered `ask_questions` cards as well as user messages: answering one writes no message row, only an in-place toolOutput update, so those chats used to look abandoned. - The admin transcript now returns the hidden kickoff prompt (collapsed in the UI) and enriched message parts: reasoning, tool input/output rendered as JSON trees, and errors. Reference chips are not navigable there since they would link into the reader's own workspace. - Fixes the workspace detail "Messages" column which displayed conversationSize (tokens) instead of the message count. |
||
|
|
4dbaafc65d |
Revert "Make subdomain minimum length configurable via env var" (#23871)
Instead, reduce the subdomain minimum length to 1 char <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23871?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. --> |
||
|
|
47f82b9121 |
Gate the workspace setup AI chat to workspace creators (#23881)
The server already refuses to start a workspace setup chat for anyone who isn't the workspace creator (`workspace-setup-chat.service.ts`, via `userWorkspaceService.isWorkspaceCreator`), but nothing on the client checked that. An invitee finishing onboarding was still routed to `/workspace-setup`, where the kickoff mutation returned `UNAVAILABLE` and the effect silently returned — leaving them on a dead-end page with the onboarding header and an empty chat that never starts. Exposes `isWorkspaceCreator` on `User` as a resolve field next to `onboardingStatus`, reusing the existing service method, and gates both the post-onboarding redirect and the page itself on it. Invitees now land on the default home page instead. |
||
|
|
3cbcf999d6 |
Add call recording transcript and summary widget types (#23864)
Registers two record-page widget types for call recordings: CALL_RECORDING_SUMMARY and CALL_RECORDING_TRANSCRIPT. - Widget type and configuration type enums, configuration DTOs, and creation/update validators - Core pageLayoutWidget_type_enum migration (2.29 fast instance command) - Shared configuration types and regenerated metadata client schemas Widget components and their placement on the callRecording record page layout come in a follow-up PR. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23864?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. --> |
||
|
|
a47f566eb1 |
fix(twenty-server): notify SSE subscribers when an update leaves their filtered view (#23858)
## Context Record tables subscribe to SSE with their query signature (object + filter) and the server pushes only matching DB events. `isQueryMatchingObjectRecordEvent` evaluated `after ?? before` — for UPDATED events that is always `after`, so an update moving a record **out** of a filtered view never matched: no event, and the open table keeps the stale row until a manual reload. Symptom on twenty-internal: a Sales Action Item marked Done by an AI-chat tool (or any API/workflow write) stays visible in the `status = OPEN` view. Records *entering* a view appear live; records *leaving* never disappear. UI edits mask the bug via the local Apollo cache. ## Fix For UPDATED events, view membership now matches on either snapshot (a before-only match = the record just left the view). Row-level authorization is unchanged: still evaluated against the delivered snapshot, so a before-state match cannot authorize a payload the subscriber lost RLS access to. A pre-existing, unrelated payload leak spotted during review (before values delivered when a record enters RLS scope) is fixed separately in the stacked #23870. ## Test plan - Unit: leave-view update publishes (fails on the old matcher — verified), neither-state-matches does not, RLS-failing delivered state does not even when before matched. 36/36 on the spec, full server suite green. - End-to-end on a local stack: companies table filtered `Name contains 'Open'`, `updateCompany` renamed a row out of the filter via the API → row disappeared from the open table within seconds, no reload. |
||
|
|
f5a42cdbae |
Give AWS SDK clients an explicit request timeout (#23857)
## Why The AWS SDK defaults `requestTimeout` to `0`, which means *no timeout* — see `DEFAULT_REQUEST_TIMEOUT` in `@smithy/node-http-handler`. None of our clients overrode it, so a request that never completes holds its socket forever. Once that happens to `maxSockets` requests (default 50), the client's connection pool is permanently exhausted and every subsequent call on that process queues indefinitely rather than failing. To the caller it is indistinguishable from a hang. This caused a production incident on 2026-08-06. A single `twenty-server` pod reached: ``` @smithy/node-http-handler:WARN - socket usage at capacity=50 and 1004 additional requests are enqueued. ``` and never recovered — the queue grew monotonically and the pod completed **zero** Lambda invocations over 12 hours while its six siblings completed dozens each. Egress was fine (a direct HTTPS call to the Lambda API returned in 53ms) and the pod was never OOM-killed or restarted, so nothing surfaced as an error anywhere. The user-visible effect was that workspace creation hung. Activation reached `synchronizeTwentyStandardApplicationOrThrow`, blocked on a Lambda call, and never returned or threw — so the `catch` in `activateWorkspace` that resets a workspace to `PENDING_CREATION` never ran, and the workspace was stranded in `ONGOING_CREATION`. Retrying didn't help because the pod was still poisoned. With one bad pod out of seven, roughly one signup in seven failed: | pod | activations started | completed | |---|---|---| | healthy × 5 | 13 | 13 | | poisoned | 3 | **0** | Nothing appeared in Sentry, because nothing ever threw. ## What this changes - **Every AWS SDK client now sets `connectionTimeout` and `requestTimeout`** via a shared `buildAwsRequestHandlerOptions()` helper. A saturated pool now surfaces as an ordinary error the caller can catch and retry instead of hanging forever. This is the fix that matters. - **The Lambda client gets a higher ceiling and a larger socket pool.** Synchronous invocations legitimately hold a socket for as long as the function runs, so its `requestTimeout` clears `EXECUTOR_LAMBDA_TIMEOUT_SECONDS` (900s) with a minute to spare, and `maxSockets` goes to 200 so long invocations cannot starve the control-plane calls (layer lookups, waiters) sharing that client. - **`S3Client` and `STSClient` in `LambdaAwsClientService` are now reused.** Both were constructed on every call and never destroyed, so each leaked its own agent and socket pool. They are invalidated alongside `lambdaClient` when assume-role credentials refresh. No new dependency: `requestHandler` already accepts a plain `NodeHttpHandlerOptions` object. ## Deliberately not in scope - **A timeout around `activateWorkspace` itself.** A hung activation still strands a workspace in `ONGOING_CREATION` until the 5-minute stale-lock reclaim, and that only fires if the user happens to retry. Worth fixing separately. - **Alerting on `socket usage at capacity`.** That warning was the only signal this was happening and nobody was watching it — an infra change rather than a code one. ## Testing - Unit tests for the helper, including that the timeout is always non-zero. - `tsc --noEmit` clean on the touched files; `oxlint` reports 0 warnings and 0 errors. - Not reproducible in a test environment — the leak needs a saturated pool — so the mechanism above is evidenced from production logs and the SDK's own defaults rather than from a regression test. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23857?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. --> |
||
|
|
5f9419589e |
i18n - translations (#23873)
Created by Github action --------- Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
a7324252fd |
fix(twenty-server): stop the yarn-install Lambda from running out of memory (#23805)
## Context Sentry issue [7438578272](https://twenty-v7.sentry.io/issues/7438578272/) (Logic Function Layer Build Failed, 7.9K events over 3 months): the yarn-install tool Lambda dies with `Runtime.OutOfMemory` / `signal: killed` while building an application's dependency layer. Every layer build for the affected application fails permanently, each database-event trigger re-attempts it, and one workspace produced ~2.5K events in the last week alone. ## Root cause The offending application declares `twenty-ui@1.0.0-alpha.0` (181MB unpacked, dragging in 141MB of `@tabler/icons*`) and dev tooling as production `dependencies` of server-side logic functions. Installing that tree needs just under 3GB during Yarn 4's fetch/link phase, so the 1024MB sandbox is OOM-killed. And even a successful install could never ship: AWS caps a function plus all its layers at 250MB unzipped. The user never sees any of this: the OOM is retried forever, and nothing tells them their dependencies are the problem. ## Fix 1. **Raise the yarn-install Lambda to 4096MB** so legitimate dependency trees install. Tool function names now include the memory/timeout/ephemeral-storage constants in their content hash, so a config change rotates the function name and the ensure path creates a fresh function with the new configuration — without this, the constant change would never reach already-deployed functions (their config is only applied at creation, and the ensure path early-returns when the function exists). 2. **Propagate Lambda's own errors to the user.** The install OOM (`Runtime.OutOfMemory` on the invoke) and the layer size rejection (`InvalidParameterValueException` at `PublishLayerVersion`) map to a new `LOGIC_FUNCTION_DEPENDENCIES_SIZE_EXCEEDED` code telling the user to move packages their logic functions don't import out of `dependencies`. Surfacing per API boundary: - **Sync / install (CLI)**: the workspace migration interceptor formats it into the same metadata validation error shape the SDK already renders, as one `logicFunction` entry carrying the remedy and the underlying AWS detail — no SDK rendering changes needed. - **`executeOneLogicFunction`**: mapped to `UserInputError` in the GraphQL handler. - **Route triggers**: HTTP 422 with the user-facing message, no Sentry capture. - **Background triggers**: skip instead of retrying, since no retry can succeed until the user changes their application. ## Test The error originates in AWS behavior, which CI (local driver, no AWS) cannot reproduce — so the chain is verified link by link: - **Real AWS, manual (not in CI)**: reproduced with the offending application's actual package.json against real Lambdas in the dev account — OOM-killed at 1024MB and 2048MB (exact prod error signature), install succeeds at 4096MB (~4min), and the resulting 292MB layer is rejected by `PublishLayerVersion` with the exact `InvalidParameterValueException` this PR matches. Same matrix reproduced in local cgroups beforehand. - **Server unit specs**: AWS error payload → exception mapping (`build-yarn-install-failure-exception`), exception → validation payload formatting (interceptor handler), `executeOneLogicFunction` GraphQL mapping, route filter 422 mapping, tool-function/layer name hashing. - **SDK integration spec (mocked server)**: runs the real `app dev` orchestrator on the minimal app with `syncApplication` mocked to return the validation-shaped failure, and asserts the CLI report renders the error code and remedy. It covers CLI rendering only — no test installs actual oversized dependencies, by design. - Docs updated (dependency size limits, sync failure taxonomy, route platform error responses). |
||
|
|
8699766303 |
chore: bump version to 2.29.0 (#23820)
## Summary - Moves current version to previous versions array - Sets TWENTY_CURRENT_VERSION to the new version - Updates TWENTY_NEXT_VERSIONS with the next minor version - Bumps twenty-client-sdk, twenty-sdk, and create-twenty-app to the same version ## Checklist - [ ] Verify version constants are correct - [ ] Verify npm package versions match <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23820?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 Action Deploy <github-action-deploy@twenty.com> |
||
|
|
829ef9d8b9 |
Revert AI chat chips to the [[kind:...:label]] syntax (#23852)
Removes the `[[kind:...:label[[/kind]]` closing-tag syntax and goes back
to the simpler `[[kind:...:label]]` form for all four chip kinds
(record, object, field, view).
The parser is now a single regex pass instead of a two-pass scan with a
per-reference closing-tag search, a legacy fallback and surplus-bracket
handling. That removes 11 files. The label pattern excludes `[`, `]` and
newlines, which is what keeps an unclosed marker from swallowing the
text (and the marker) that follows it.
```mermaid
flowchart LR
subgraph before ["Before — two passes"]
O1["scan for marker openings"] --> O2["window each opening<br/>up to the next one"]
O2 --> O3["find that kind's closing tag<br/>inside the window"]
O3 --> O4["record only:<br/>bare-terminator fallback"]
O4 --> O5["consume surplus<br/>closing brackets"]
end
subgraph after ["After — one pass"]
N1["matchAll, one regex:<br/>object · field · view · record"] --> N2["map each match<br/>to a chip"]
end
before -.->|"11 files deleted"| after
```
Two things to know:
- Messages already stored with closing tags render as raw text instead
of chips.
- Malformed model output is no longer compensated for: a surplus `]`
after a chip stays in the text, and a display name containing brackets
does not chip. The system prompt tells the model to avoid both.
Rendering cost is unchanged for normal messages and noticeably lower on
long bracket runs, since the old opening pattern had to scan them.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23852?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. -->
|
||
|
|
d8b494d530 |
Make subdomain minimum length configurable via env var (#23209)
## What Introduces a `SUBDOMAIN_MIN_LENGTH` environment variable (default `3`) controlling the minimum number of characters allowed for a workspace subdomain. Until now the minimum was hardcoded (`3`), baked into the shared `SUBDOMAIN_PATTERN` regex. ## How - Added the `SUBDOMAIN_MIN_LENGTH` config variable (default `3`) in `config-variables.ts`. - Relaxed `SUBDOMAIN_PATTERN` in `twenty-shared` to validate format and max length only, so the minimum length policy now lives with the caller instead of being embedded in the regex. - `isSubdomainValid` now takes a `minLength` argument (defaulting to `3`) and enforces it explicitly. - `SubdomainManagerService` reads `SUBDOMAIN_MIN_LENGTH` from config and passes it to every validation call, making the server the authoritative source. ## Scope Server-side only. The frontend validation schema keeps its default `.min(3)` UX check and is unchanged; the server remains the source of truth for what subdomains are accepted. ## Tests - Updated the shared `isValidTwentySubdomain` tests to reflect that the pattern no longer enforces a minimum length. - Added tests for the configurable minimum in `is-subdomain-valid.util.spec.ts`. - Updated the service spec config mock to return a numeric value for `SUBDOMAIN_MIN_LENGTH`. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23209?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. --> |
||
|
|
5278a47b55 |
refactor(front): move workflow run step logs into workflow-actions (#23841)
Follow-up on unapplied review feedback from #21142. ### Folder structure @thomtrp: > We now have a folder workflow-run/observability, but we have workflow-run related components in workflow-actions folder already. I would avoid that workflow-run/observability folder. The `workflow-run/` folder held nothing but `observability/`, so it is removed entirely and each step log detail component now sits with its action: | File | New location | | --- | --- | | `WorkflowRunStepLogsAiAgentDetail.tsx`, `WorkflowRunStepLogsToolCallRow.tsx` | `workflow-actions/ai-agent-action/components/` | | `WorkflowRunStepLogsCodeDetail.tsx` | `workflow-actions/code-action/components/` | | `WorkflowRunStepLogsHttpRequestDetail.tsx` | `workflow-actions/http-request-action/components/` | | `WorkflowRunStepLogsDetail.tsx`, `WorkflowRunStepLogsEntries.tsx`, `WorkflowRunStepLogsEmailDetail.tsx`, `workflowRunStepLogsStyles.ts` | `workflow-actions/components/` | | `formatDuration.ts`, `formatBytes.ts` | `workflow-actions/utils/` | The email detail stays in the shared `components/` folder since there is no dedicated send-email action folder on the front end (email editing lives at the root as `WorkflowEditActionEmailBase.tsx`). `workflowRunStepLogsStyles.ts` goes next to the shared components rather than `utils/`, since it is styled components and not utils. Also folds in @FelixMalfait's `2 export in 1 file` comment: `workflowRunStepLogsFormatters.ts` is split into `formatDuration.ts` and `formatBytes.ts`. ### AI comments @thomtrp: > same, let's not keep AI comments Removes every comment #21142 introduced, across the front end, server and shared packages: - `WorkflowRunStepLogsEntries.tsx` - the `onlyLatestIteration` prop block - `workflow-run-step-log-schema.ts` - the transport-failure note and the permissive-schema rationale - `strip-ansi-escapes.util.spec.ts`, `build-http-request-step-log.util.spec.ts`, `truncate-string-to-utf8-byte-budget.spec.ts`, `agent-async-executor.service.spec.ts` - the byte-vs-char and pre-fix-behaviour commentary No behaviour change. Locale catalogs are deliberately left untouched; the next i18n run picks up the new source paths. ### Still open from #21142, not covered here - `persistStepLog` try/catch duplicated across the code, tool-backed and ai-agent actions - `draft-email-tool` returning both `sanitizedHtmlBody` and `plainTextBody` - storing both `totalCostInDollars` and `creditsUsedMicro` - the byte-budget truncation utilities being over-engineered - `strip-ansi-escapes` being local to application logs |
||
|
|
ae235d3b24 |
Scope sessions and application authorizations to the workspace (#23843)
Settings / Profile / Devices listed every live session for the account, so a person who belongs to two workspaces saw all of them from either one, and "Log out all other devices" signed them out everywhere. Almost nothing in Twenty is account-wide, and a session belongs to the workspace its exchange selected, so neither the list nor the revocations are another workspace's business. ## What was wrong `currentUserSessions` called `findActiveSessionsForUser(user.id)` with no workspace filter. Both revoke paths were keyed on `userId` alone, so `revokeUserSession` could target another workspace's session by id and `revokeAllOtherUserSessions` cleared every workspace at once. Sweeping the other resolvers that take `@AuthUser()` turned up the same shape in the OAuth application authorizations added in #23678: `findActiveAuthorizationsForUser(userId)` and `revokeAuthorizationById({ authorizationId, userId })`. A grant made in one workspace was listed, and revocable, from another. Everything else already pairs `@AuthUser()` with `@AuthWorkspace()`. `client-config.resolver.ts` is the reference pattern. ## The fix Both resolvers now take the workspace from the auth context and pass it down, and the service methods are renamed to say so. `revokeAllSessionsForUser` keeps `workspaceId` optional on purpose: `auth.service.ts` uses it on password change, where clearing every workspace is the intended behaviour. Sessions with no workspace (the workspace-agnostic ones minted on the default subdomain, which exists to list workspaces and carry the auto-login window) now belong to no workspace's list and survive "log out all other devices". ## Verification - New integration spec built on Tim's membership of both apple and yc: the list stays disjoint, a cross-workspace revoke by id is refused and is a no-op, and revoking all other devices in one workspace leaves the other signed in - Mutation-checked by dropping the `workspaceId` from the query, which fails the isolation test while the two revoke tests still pass, confirming each assertion targets its own mechanism - 160 unit tests, 70 integration tests across the session and OAuth suites ## Also The devices button drops its danger accent for the plain small variant, matching Deactivate in `ObjectSettings.tsx`. ## Separate finding, not fixed here `request.ip` resolves to an internal address behind the Cloudflare / nginx chain, which is why every row in the screenshot that prompted this showed the same RFC1918 address. That is an ingress configuration issue rather than an application one. It does not affect ClickHouse audit logs, which store no IP, but it does affect the two OAuth rate limiters that key on `req.ip`. --- _Generated by [Claude Code](https://claude.ai/code/session_01C6nCVbcb5ZZrz67uvqvMWF)_ <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23843?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. --> |
||
|
|
26104d47a6 |
Report a sending domain as pending while SES waits for the DKIM records (#23818)
## Problem <img width="648" height="310" alt="image-1785940453654" src="https://github.com/user-attachments/assets/60362b8c-fed5-4ce3-af45-9aa064356f11" /> A sending domain that is simply waiting on its DKIM records is displayed as **Failed**, with every DKIM row marked **Error**, even when the DNS is correct and AWS has already published the key. Hit while setting up `twenty.dev` for a demo. All five CNAMEs resolve correctly from the authoritative nameserver and from a public resolver, none are proxied, the unsubscribe row is green, and the first DKIM token already resolves through to its published key at AWS: ``` $ dig +short TXT abbr…._domainkey.twenty.dev abbr….dkim.amazonses.com. "p=MIIBIjANBgkq…" ``` Yet all three DKIM rows read Error, which tells the user to go fix DNS that isn't broken. ## Cause `determineVerificationStatus` treats `VerifiedForSendingStatus === false` as terminal: ```ts if ( identityResponse.VerifiedForSendingStatus === false || dkimStatus === 'FAILED' ) { return EmailingDomainStatus.FAILED; } return EmailingDomainStatus.PENDING; ``` SES reports `VerifiedForSendingStatus: false` for the entire period it is waiting to detect the DKIM CNAMEs, which is the normal state of every domain between setup and verification. So a pending domain returns FAILED, and the PENDING branch is unreachable for any identity where the field is present at all. `TEMPORARY_FAILURE`, which SES documents as retryable, was also reported as Failed. The status is then stamped onto each DKIM row by `withRecordStatus`, which is why all three rows change together and none of them reflects its own record. |
||
|
|
692c0c8402 |
i18n - translations (#23844)
Created by Github action --------- Co-authored-by: github-actions <github-actions@twenty.com> |
||
|
|
647a6aec58 |
Add nested relation Field widgets on record page layouts (#23815)
## Context Record pages can show a list of directly related records (Field widget in Table display mode), but not records two relation hops away. The canonical ask: on a Client page, list the Transactions of the Client's Wallets. Stacked on #23814 (merged) and #23832 (merged); their commits are included in this branch. #23836 stacks on this PR to add many-to-one first hops. ## How it works The 2-hop case does not need any new query capability. It reuses the relation traversal filter shipped for advanced filters: the widget embeds a view on the terminal object (Transaction) with one seeded filter `inverse relation IS current record`, traversed one hop (`fieldMetadataId` = Transaction.wallet, `relationTargetFieldMetadataId` = Wallet.client, value `isCurrentRecordSelected`). At query time this compiles to `{ wallet: { clientId: { in: [currentRecordId] } } }`, which is within the backend's `MAX_RELATION_FILTER_DEPTH = 1` since the second hop lands on the join column. Records from all intermediate records (all wallets of the client) are listed, so one-to-many fan-out on the first hop works out of the box. ## Changes Configuration - `FieldConfiguration` gains an optional `nestedRelationFieldMetadataId` (shared type, DTO, GraphQL fragment, regenerated metadata types). Backward compatible: existing widgets are untouched. UI - The Field picker drills into one-to-many relation fields, mirroring the advanced filter submenu pattern: back header, an entry to select the relation itself (previous behavior), then the target object's one-to-many relations. Selecting a nested field creates a widget titled `First hop → Second hop` in Table display mode. First-level rows that open a submenu never show the checkmark; the selected chain is only visible inside the submenu, matching the chart group by field selection. - The layout dropdown, settings panel and renderer resolve the terminal object of the chain; a widget whose second hop was deleted or deactivated renders nothing instead of silently showing first-hop records. - Nested widgets only offer embedded view layouts (Table / Kanban / Calendar), since inline display modes would render the first hop's relation field. - The relation table view resolver regenerates the embedded view whenever the selection results in a table widget and the chain changed or the view id is missing, so a table widget can never carry a view belonging to a different chain. Server - `FieldConfigurationDTO` accepts the new optional field. - Both universal configuration mappers (to and from universal identifiers) carry it for app manifest sync. - New `validateFieldConfigurationNestedRelationOrThrow` enforces that both hops are active one-to-many relation fields on the right objects, wired next to the existing chart field reference validation. Record creation - `buildRecordInputFromFilter` skips relation-traversal filters: they constrain a related record's column, so prefilling the created record's own foreign key from them would link the wrong record (e.g. `walletId = clientId`). - Add New in a nested widget table instead prompts for the record to create through: the row opens a picker listing the current record's first-hop records (the client's wallets), scoped with a find filter on the relation join column, and creates the record with the picked id prefilled. Covers the plain table and per-group add rows. Board and calendar layouts hide their create buttons in nested widgets since they cannot know the record to create through. - Matching the created record against the widget's traversal filter client side is handled by #23832. Out of scope, deliberately: depth stays at exactly two levels (matches the backend filter depth cap), junction and morph relations are not drillable, and chart widgets on record pages are untouched. ## Tests - Unit: nested chain resolution util, draft view seeding with the traversal filter, view id change resolver, picker parameter derivation, server-side validation. Full `page-layout` and `record-filter` front suites pass (187 suites / 1233 tests), server `page-layout-widget` suites pass. - Manual, on seeded data: created a `People → Opportunities` widget on a Company page; it lists exactly the opportunities whose point of contact belongs to that company, persists across save and reload, and scopes per record. Add New opens a picker showing only that company's people; picking one creates an opportunity with `pointOfContactId` set (verified in DB) and the row appears in the widget immediately. --- _Generated by [Claude Code](https://claude.ai/code/session_01Xp3AgGtc4kSP8PpgpKMWLQ)_ <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23815?utm_source=github" rel="nofollow noreferrer noopener" target="_blank">``<img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg">``</a> |
||
|
|
9480513689 |
chore: sync AI model catalog from models.dev (#23839)
Automated daily sync of `ai-providers.json` from [models.dev](https://models.dev). This PR updates pricing, context windows, and model availability based on the latest data. New models meeting inclusion criteria (tool calling, pricing data, context limits) are added automatically. Deprecated models are detected based on cost-efficiency within the same model family. **Please review before merging** — verify no critical models were incorrectly deprecated. Co-authored-by: FelixMalfait <6399865+FelixMalfait@users.noreply.github.com> |
||
|
|
c35e364562 |
Fix AI campaign editing: tool auth context in workers and live editor resync (#23811)
Fixes two issues reported when creating an email campaign through the AI chat panel. ## 1. `save_campaign` failed with "Workspace auth context not set" The AI chat streams inside a queue worker job, where no HTTP middleware populates the async-local workspace auth context. The new `MessageCampaignDraftService.saveDraft()` relies on `executeInWorkspaceContext()`'s fallback to `getWorkspaceAuthContext()`, which throws outside HTTP requests. Database CRUD tools worked because `dispatchDatabaseCrud` builds an auth context explicitly; static tools had no equivalent. **Fix:** `ToolExecutorService.dispatch` (the single choke point for all tool executions: preloaded chat tools, `execute_tool`, MCP, workflow agents) now resolves the acting identity once, reusing a provided auth context or building a user context from `userId`/`userWorkspaceId`, and runs the dispatch inside `withWorkspaceAuthContext()`. This mirrors what `WorkspaceAuthContextMiddleware` does for HTTP requests, so tool code can rely on the async-local context on every transport. Side benefit: metadata tools executed from chat previously emitted metadata events with no user attribution (`MetadataEventEmitter` swallows the missing context); they are now attributed correctly. ## 2. AI changes to the open campaign required a page refresh The SSE pipeline delivers worker-originated record updates to the Apollo cache correctly. The campaign editor ignored them: `usePersistedCampaignDraft` seeds local draft state from the record once, and the subject/body/list inputs are uncontrolled (TipTap reads `defaultValue` on mount only). **Fix:** the draft hook now adopts upstream record values while the draft is pristine and exposes a `draftResyncKey` that remounts the `defaultValue`-seeded inputs. Unsaved local edits win over concurrent remote changes (last write wins on flush), and echoes of our own debounced persists never remount inputs mid-typing. ## Tests - `tool-executor.service.spec.ts`: auth context exposed to static tools, provided-context reuse, no-identity passthrough, no context leakage after dispatch, CRUD receives the resolved context, CRUD still rejects without identity. - `usePersistedCampaignDraft.test.tsx`: adopt-when-pristine, own-echo stability, dirty-draft-wins, adopt-after-persist. - `lint:diff-with-main` and `typecheck` clean on both packages. --- _Generated by [Claude Code](https://claude.ai/code/session_018nGvGhFahw1pcefb3P4iCk)_ <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23811?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. --> |
||
|
|
dc8c62a7a9 |
Add OpenTelemetry metrics to workspace migration build and run (#23797)
## Context ## AI generated graph goal example <img width="2078" height="914" alt="image" src="https://github.com/user-attachments/assets/14c760df-5ac8-4526-a5e0-40b57344be90" /> <img width="2158" height="1850" alt="image" src="https://github.com/user-attachments/assets/2324779e-9ab8-47fc-a014-78269a78823e" /> The workspace migration builder and runner already log phase timings via `logger.perfTime`, but those logs are only useful for local debugging: they're gated behind the `performance` log level and never leave the process. This PR routes the same timings into the existing `MetricsService` (OpenTelemetry) so migration performance can be tracked over time and regressions detected. ## What's recorded All metrics are histograms recorded via `MetricsService.recordHistogram`, which is a synchronous in-memory aggregation - export happens on the background OTel readers (Prometheus scrape or periodic OTLP push), so nothing is added to the migration hot path. When `METER_DRIVER` is unset, records are no-ops. | Metric | Where | Attributes | |---|---|---| | `workspace-migration/build-duration-ms` | `WorkspaceMigrationValidateBuildAndRunService` | `status`: `success`, `fail` (validation errors), `error` (builder threw) | | `workspace-migration/build-entity-duration-ms` | `WorkspaceEntityMigrationBuilderService.validateAndBuild` | `metadataName`, `status` | | `workspace-migration/build-entity-phase-duration-ms` | entity builder | `metadataName`, `phase`: `matrix-computation`, `deletion-validation`, `creation-validation`, `update-validation` | | `workspace-migration/run-duration-ms` | `WorkspaceMigrationRunnerService.run` | `status`: `success`, `fail` - recorded on every exit path, including pre-transaction failures (DDL locked, cache retrieval, application not found) | | `workspace-migration/run-phase-duration-ms` | runner | `phase`: `initial-cache-retrieval`, `action-execution`, `commit`, `cache-invalidation`; `status` - on failure the elapsed transaction time is recorded as `action-execution` with `status: 'fail'` (the action/commit split is unknowable mid-failure) | | `workspace-migration/action-duration-ms` | base action handler wrapper | `actionType`, `metadataName`, `step`, `status` - failed steps are recorded via try/finally | | `workspace-migration/action-count` | validate-build-and-run service | - | Phase notes: phases are disjoint (commit is subtracted from transaction time) but not exhaustive - connection setup, the application-map fetch, rollback, and after-commit side effects sit outside them, so the stack approximates rather than equals the run total. The `cache-invalidation` phase is recorded only at the run's post-commit call site, not inside the public `invalidateCache`, so standalone callers (upgrade backfill commands, `FlatCacheInvalidateCommand`) don't pollute the series. ## Implementation notes - Durations are measured with local `performance.now()` instead of reusing `perfTime`/`perfTimeEnd`, so metrics are recorded regardless of the `performance` log level and are immune to key collisions in the logger's shared timer map under concurrent migrations. Existing perf logs are untouched. - `WorkspaceMigrationRunnerService.run` is now a thin wrapper around the previous body (`executeRun`) so the total run duration and its success/fail status are recorded in one place for every throw path. - No `workspaceId` in attributes to keep cardinality bounded. - Two new bucket-boundary constants follow the existing `AI_LATENCY_MS_BUCKET_BOUNDARIES` pattern: durations 5ms-120s, action counts 1-5000. - `MetricsModule` imported into `WorkspaceMigrationModule`, `WorkspaceMigrationRunnerModule`, `WorkspaceMigrationBuilderModule`, and the action-handlers module. ## Test - `nx typecheck twenty-server` passes - oxlint + oxfmt clean on changed files - `workspace.service.spec.ts` passes |
||
|
|
b7e556bcfc |
fix(workflow): make core-consistency drift check trustworthy for rollout (#23807)
## Context Part of the workflow → core migration. Before enabling `IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED` per workspace, the drift signal that gates the rollout must be trustworthy. Two bugs in the (already merged) consistency cron made it lie in both directions. This PR fixes only those two; no new machinery. The actual pre-flight gate is a read-only SQL query run per batch of workspaces, so the heavier repair-command idea was dropped. ## What this does **1. Exclude soft-deleted trigger rows from the automated-trigger drift check.** `checkAutomatedTriggerSync` read the workspace `workflowAutomatedTrigger` table without a `deletedAt` filter (the sibling workflow/version checks have one). Workflow soft-delete soft-deletes the trigger row but removes the core-map entry, so every soft-deleted automated workflow emitted a permanent false `inTableNotCache` drift — inflating the exact metric meant to gate the flag. **2. Enumerate active workspaces in the consistency cron.** The scan was `SELECT DISTINCT "workspaceId" FROM core."workflow"`: a workspace whose mirror never succeeded has zero core rows and was therefore never checked — the worst-drifted tenants were invisible. It now enumerates ACTIVE workspaces and skips those with no (non-deleted) workflow rows, so cost stays close to actual workflow usage. No behavior change beyond the drift metrics themselves. |
||
|
|
6abeb7b5e5 |
feat(server): instrument the local metadata cache and cap heavy providers by entry count (#23778)
## What
Two related changes to the per-pod local workspace-metadata cache
(`WorkspaceCacheService`):
1. **Occupancy metrics** — per-pod gauges so we can measure how the
cache is actually used from prod instead of guessing:
- `twenty_workspace_cache_local_entries` — Map size
- `twenty_workspace_cache_local_workspaces` — distinct workspaces held
- `twenty_workspace_cache_local_versions_total` — total versions across
entries
- `twenty_workspace_cache_local_bytes_estimate` /
`..._bytes_by_provider{provider}` — sampled deep-size (circular-safe,
includes `localDataOnly` providers)
-
`twenty_workspace_cache_local_entries_by_version_count{versions=1|2|3|4|5+}`
— stale-version distribution
2. **Per-provider eviction budget (behavior change)** — a heavy provider
can override the global entry cap, and eviction now drops the
least-recently-read entry. `ORMEntityMetadatas` is capped at 128
entries.
## Why
Measured on a prod pod (with these gauges plus a live heap walk): the
local cache is ~1.5-2 GB of the pod's ~2.4 GB live heap, and the pod
sits at 85% of its 4 GB limit. Two providers own 89% of it:
- `orm:entity-metadatas` — **50%**, ~5 MB/entry (the full TypeORM
`EntityMetadata[]` graph), `localDataOnly` so it is pure per-pod RAM.
- `flat-maps:field-metadata` — 39%.
The pod held 434 ORM entries but served under one distinct workspace per
second, with 62% of entries idle for more than 5 minutes — it hoards.
Rebuilding an ORM entry is cheap (6-16 ms of synchronous CPU; the DB
read dominates the rest of a recompute), so bounding how many we retain
is nearly free.
## The eviction change
The only size control before this was a single global 6000-entry LRU,
which is byte-blind: a 5 MB ORM entry and a 760 B webhook entry each
count as "1", so "6000 entries" is anywhere from 300 MB to 3 GB.
This adds a **per-provider entry cap** and evicts the
**least-recently-read** entry, keyed on `version.lastReadAt` (replacing
the coarser `lastHashCheckedAt`, which was zeroed on invalidation and
only 100 ms-granular). `ORMEntityMetadatas` → 128 entries, down from 434
observed in prod: ≈640 MB at the measured ~1.0 versions/entry (worst
case bounded by `128 × MAX_LOCAL_STALE_VERSIONS`), against ~2.1 GB
today. The global 6000 cap remains as a coarse total backstop; providers
without an override are unchanged.
A cold miss (a workspace served again after its entry was evicted)
recomputes transparently. At the measured activation rate that is under
one rebuild per second per pod — well below 1% of a core. Cache
correctness is unchanged: entries are hash-versioned and disposable.
## Cost
- **Metrics**: stats are one pass over the local Map, memoized 5 s so
concurrent gauge callbacks reuse them. The byte estimate is a background
sampler (first run ~30 s after startup, then every 5 min) that
deep-sizes a few entries per provider, node-capped and yielding between
walks — off the request and scrape paths.
- **Eviction**: the per-provider cap is enforced on write; a cold-miss
rebuild is the 6-16 ms recompute above.
|
||
|
|
f7aab2e988 |
fix: allow app-manifest RECORD_TABLE widgets to reference a view by universal identifier (#23634)
## Context Fixes #23065. App-manifest dashboard `RECORD_TABLE` widgets could not reference a view by universal identifier. `RecordTableConfiguration.viewId` was typed as a plain `string`, so `FormatRecordSerializedRelationProperties` (which only renames properties branded with `SerializedRelation`) left it as `viewId` in the manifest type. As a result the manifest rejected `viewUniversalIdentifier`, and the widget could not be made portable across workspaces the way `FIELDS` widgets already are. ## Changes - `RecordTableConfiguration.viewId` is now `SerializedRelation | null` (was `string`), matching `FieldsConfiguration`. This makes the manifest type surface `viewUniversalIdentifier` instead of `viewId`. - `RecordTableConfigurationDTO.viewId` retyped to match. - Forward converter (`fromPageLayoutWidgetConfigurationToUniversalConfiguration`): the `RECORD_TABLE` case now emits the `viewUniversalIdentifier` key instead of `viewId`, since the branded property is renamed in the universal type. Now consistent with the `FIELDS` case (uses `| null`). - Reverse converter (`fromUniversalConfigurationToFlatPageLayoutWidgetConfiguration`): the `RECORD_TABLE` case now reads `viewUniversalIdentifier` and resolves it back to a concrete `viewId`. Frontend readers need no change: `SerializedRelation` is a runtime string, so the existing `typeof === 'string'` guards and `as string` casts still hold. ## Migration None needed. The persisted `pageLayoutWidget.configuration` still stores a concrete `viewId`; `universalConfiguration` (which carries `viewUniversalIdentifier`) is computed on the fly from it and never persisted. Only the manifest/universal representation changes, so there is no stored data in the old shape to backfill. ## Verification - `nx typecheck twenty-server` and `nx typecheck twenty-front`: pass - oxlint + oxfmt on the changed files: clean - End-to-end against a server built from this branch: built a minimal app declaring a view (by `universalIdentifier`) and a `DASHBOARD` page layout with a `RECORD_TABLE` widget referencing that view via `viewUniversalIdentifier`, then installed it. The manifest carried `viewUniversalIdentifier`, and the installed `pageLayoutWidget.configuration.viewId` resolved to the concrete workspace view id. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23634?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. --> |
||
|
|
6e30405489 |
Bump vulnerable dependencies flagged by ECR image scanning (#23813)
## Context The Oneleet monitor **"AWS ECR repository image vulnerabilities are remediated"** is alerting on `prod-twenty` images: 1 CRITICAL + 6 HIGH advisories breach their SLA in 7 days, plus a set of MEDIUMs. All of them are npm packages baked into the image. ## Changes | Package | Before | After | How | Advisories | |---|---|---|---|---| | undici | 7.28.0 / 6.27.0 | 8.9.0 | jsdom `^30` bump + node-gyp refresh; global `undici: ^8.9.0` resolution for @module-federation/dts-plugin, e2b and miniflare, which still pin 7.28.0 at latest (replaces the old scoped dts-plugin resolution) | CVE-2026-13697 (critical), CVE-2026-14643, CVE-2026-15157/16728/16729 | | sharp | 0.34.5 | 0.35.3 | direct bump in twenty-sdk; @argos-ci refresh; `next/sharp` resolution (next 16.3.0 with the fix is still quarantined by yarn's minimal-age gate) | GHSA-f88m-g3jw-g9cj | | axios | 1.17.0 | 1.19.0 | lockfile refresh | GHSA-gcfj-64vw-6mp9 + 10 medium | | ip-address | 10.2.0 | 10.4.0 | lockfile refresh | CVE-2026-69192, CVE-2026-54272, CVE-2026-69198 | | brace-expansion | 2.1.2 | 2.1.4 | lockfile refresh (backport exists; Inspector only lists 5.x) | CVE-2026-69152, CVE-2026-14257, CVE-2026-13149 | | typeorm | 0.3.29 | 0.3.31 | pin bump; the local yarn patch applies unchanged | GHSA-2rp8-mm9q-fp49 | ## Validation - `yarn.lock` contains no remaining vulnerable versions (undici resolves only to 8.9.0) - `yarn npm audit`: no remaining advisories among the bumped packages - `nx build` green for twenty-server, twenty-front (exercises module-federation dts-plugin on undici 8), twenty-sdk, twenty-website; twenty-server typecheck green (typeorm patch is type-level) - Runtime smoke: jsdom 30 DOM parse, sharp 0.35.3 png encode, undici 8.9.0 load ## Not covered - **react-router / react-router-dom 6.30.4** (medium, 1–3 month SLA): react-router-dom 6.x has **no fixed release**; the fix is the v7 migration (~225 files) — separate effort. - `prod-business-dash` body-parser 2.2.2 → 2.3.0 lives in its own repo. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23813?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. --> |
||
|
|
45cbdef930 |
i18n - translations (#23806)
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23806?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> |
||
|
|
29e68a7f87 |
Refactor outbound email content compilation (#23782)
## Integration status This is now the final landing PR for the reviewed editor/email architecture stack. | Order | Pull request | Scope | Status | | --- | --- | --- | --- | | 0 | #23657 | Advanced text editor capability presets | Merged into `main` | | 1 | **This PR** | Outbound email content compilation | Ready to land into `main` | | 2 | #23783 | Clean editor surface seam | Reviewed and merged into this branch | | 3 | #23790 | Shared editor block catalog | Reviewed and merged through #23783 | | 4 | #23791 | Canonical TipTap document persistence | Reviewed and merged through #23790 | The current branch tree contains the complete stack. Merging this PR lands all four follow-up layers. ## Architecture The stack establishes four reusable boundaries: 1. **Outbound compilation** — campaign, workflow, and one-to-one/tool email share one compiler, sanitizer policy, renderer, and plain-text derivation path. 2. **Editor surface profiles** — the generic editor owns rendering mechanics while each consuming surface declares chrome, extensions, and explicit compatibility readers. 3. **Shared block primitives** — sections, columns, HTML, images, buttons, and related commands live in the neutral advanced-editor catalog; email behavior is supplied by email schemas/rendering, not by relocating reusable blocks into an email editor. 4. **Canonical persistence** — Twenty-owned authoring persists complete, versioned TipTap JSON documents. HTML, Markdown, plain text, and BlockNote are projections or explicitly owned legacy boundaries. ## Compatibility boundaries Compatibility remains only where shipped data requires it: - workflow Send Email: versionless TipTap JSON, HTML, and plain text - inline email: HTML - AI instructions: Markdown - record rich text: BlockNote arrays and older Markdown/plain text Campaign is unshipped, so its editor, stored rows, sendability validation, and send-time compilation require the current canonical schema version. AI chat drafts are canonical-only local state; old or malformed drafts are rejected at hydration, and plain-text preprompts are converted at their entry point. ## Outbound compiler details The shared compiler owns: - strict structured email-document parsing - React-email rendering - one cached DOMPurify/JSDOM policy for structured and legacy HTML - plain-text derivation from sanitized HTML - single-pass structured-document binding resolution across text, variable tags, links, images, buttons, and raw HTML Resolved workflow values remain inert, legacy workflow and one-to-one HTML remain supported, and Campaign HTML/plain text come from the same compiled result. ## Verification - all automated standard/security reviews passed on the three merged upper PRs with no unresolved threads - shared TipTap/email codec tests: 20 passing - editor, AI draft, and workflow compatibility tests: 14 passing - campaign validation and compilation tests: 31 passing - full shared suite during development: 223 suites / 1,738 tests passing - twenty-front, twenty-shared, and twenty-server typechecks - changed-file type-aware lint and formatting checks |
||
|
|
76bf3651bb |
Fix stray bracket after AI chat chips (#23798)
Chips in the AI chat sometimes rendered with a leftover `]` after them. The reference marker is bracket-asymmetric: it opens with `[[` and closes with `[[/kind]]`, so a complete reference holds four `[` and only two `]`. The model balances that by writing `…[[/object]]]`, and the parser ended the match exactly at the close tag, leaving the extra bracket as prose next to the chip. The parser now absorbs up to as many surplus `]` as the reference opened with, and accepts an opener with extra `[` so an over-wrapped marker doesn't leak one either. The system prompt also tells the model the marker is complete as written. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23798?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. --> |
||
|
|
59672b71b8 |
Add a book-a-call onboarding step for qualified leads (#23521)
https://github.com/user-attachments/assets/76d5a14e-53bd-4195-963b-bf9bb265c8c1 Large-company signups either self-serve a small plan or drop off at the paywall without sales ever seeing them. This adds an embedded Cal.com booking step to onboarding, shown only to leads worth a call. The step sits between Invite Team and the plan step: the lead has built out a workspace by then, and sales gets a chance before checkout. It is always skippable, and a successful booking advances automatically. Qualification reuses the employee count from the People Data Labs enrichment added in #23199. `ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT` sets the bar; leaving it unset means the step never appears. `CALENDAR_BOOKING_PAGE_ID` must also be configured, so the step can never strand someone on an empty embed. Enrichment is no longer gated on `IS_ONBOARDING_AI_CHAT_ENABLED`, since the book-a-call step is now a second consumer of it. `PEOPLE_DATA_LABS_API_KEY` remains the instance-level switch. The existing `/book-call` page is reused: it moves into the onboarding shell and its footer switches between Skip (as a step) and the back link (when reached from the plan page). <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23521?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. --> |
||
|
|
1d755983ff |
Feat/advanced text editor capability presets (#23657)
# Email editor for Compose campaigns
## Short version
Campaign bodies are currently plain rich text. This PR turns the
composer into an email editor: a centered email canvas with section,
column, button, divider, image and raw-HTML blocks, each editable
through a settings side panel, rendered to email-safe HTML per recipient
at send time. Modelled on Resend's Broadcast editor.
**Product**
- Email canvas with page/body styling (background, width, padding,
corner radius, border, text colour, alignment)
- Blocks: section, 2/3 columns, button, divider, raw HTML, images —
insertable from a floating left rail or the slash menu
- A **section is a container whose typography cascades to its
contents**, so one part of an email can have its own look
- Block settings panel focuses whatever you select and shows its
effective values
- Per-recipient variables (`{{firstName}}`, `{{lastName}}`,
`{{fullName}}`, `{{email}}`, `{{personId}}`) usable in text,
button/link/image URLs, image labels and raw HTML
- Image upload by drag-drop, paste or file picker
**Technical**
- Presets now declare **capabilities** instead of surfaces forking the
editor; the UI derives itself from loaded extensions
- Editor behavior lives in `twenty-front`; the versioned email-document
schema and structural traversal live in `twenty-shared`; rendering lives
in `twenty-emails` — HTML is produced server-side per recipient
- Section typography cascade is **resolved at render time**, not left to
CSS: react-email hardcodes `fontSize`/`lineHeight` on every paragraph
and Outlook ignores `inherit`
- Logic vendored from Resend (MIT); all controls rebuilt on `twenty-ui`
+ Linaria
**Also fixes:** the unsubscribe footer was being appended *after*
`</html>`, outside the document, where Gmail strips it — legally
significant since unsubscribe is required.
---
## Detailed version
### Product requirements
**Problem.** The Compose campaign body was a single rich-text field.
Marketing email needs layout — banded sections, columns, call-to-action
buttons, images with links — and it needs that layout to survive
Outlook, which means table-based HTML rather than the divs a text editor
produces. It also needs per-recipient personalisation.
**Reference.** Resend's Broadcast editor, chosen because it solves the
same problem (TipTap authoring → react-email output) and is MIT
licensed.
#### What a user can now do
| Area | Capability |
|---|---|
| Canvas | Email renders as a centered page with its own background,
width, padding, corner radius and border |
| Blocks | Section, 2/3 columns, button, divider, raw HTML, image |
| Insertion | Floating left rail (pointer-first) or the `/` slash menu
(keyboard-first) |
| Sections | Own text colour, font size, line height, letter spacing and
alignment, cascading to everything inside |
| Images | Upload by drag-drop, paste or picker; link URL, alt text,
width, spacing, border |
| Raw HTML | Edited as source in the panel, previewed on the canvas with
scripts neutralised |
| Variables | `{{firstName}}`, `{{lastName}}`, `{{fullName}}`,
`{{email}}`, `{{personId}}` in text, button URLs, link hrefs and raw
HTML |
| Settings panel | Follows selection; shows effective values; opens
automatically when a block is clicked |
#### Deliberate product decisions
- **Variables display as literal placeholders**, not prose labels, so
the syntax is copyable into HTML blocks and button URLs by hand.
- **Sections inherit until they override.** The panel shows what
actually renders rather than blank fields, but writes nothing until you
edit — so changing the body text colour still flows into sections.
- **Headings keep their own scale** inside a styled section; only
colour, family and spacing cascade, otherwise every heading would
collapse to body size.
- **Clicking a block opens its settings**, but only on whole-node
selections, so typing inside a section does not reopen a panel you just
closed.
### Technical strategy
#### 1. Capability presets (the foundation)
Per-surface variation previously worked by **forking**: three separate
`useEditor` call sites with hardcoded extension arrays. Inside the
shared tree there was no variation at all — all five surfaces received a
byte-identical extension list, and presets controlled only sizing,
chrome and serialization format. Adding email blocks that way meant
either leaking section/column nodes into the record rich-text field and
workflow email body, or writing a fourth fork.
Now:
- a preset declares a **capability list** (`basicMarks`, `headings`,
`lists`, `links`, `images`, `campaignVariables`, `slashCommand`,
`blocks`, `mentions`)
- capabilities resolve to extensions through a factory registry
- the UI derives itself from the loaded extensions via
`hasEditorExtension` — no capability list is prop-drilled into a menu,
because the `Editor` already knows what it can do
The acceptance test was collapsing the AI chat fork into an `aiChat`
preset with no visible change to that composer. `campaignBody` is the
only preset opting into the shared `EMAIL_DOCUMENT_CAPABILITIES` today.
Workflow email keeps its current field UI, but can opt into the same
canvas, block settings and image uploader later without adding another
schema or renderer.
#### 2. Schema / renderer split
The hard constraint: **our HTML is produced server-side, per recipient,
at send time**, because variables substitute into nodes rather than into
a serialized string. That rules out Resend's
`renderToReactEmail`-on-the-extension pattern.
```
twenty-front TipTap extensions + node views + shared email settings UI
twenty-shared versioned email-document schema + structural traversal
twenty-emails react-email renderers (imported by twenty-server)
twenty-server surface-specific variable resolution, validation, send
```
Logic was **vendored, not depended on** — Resend's TipTap is 3.17
against our 3.4, and their UI is Radix. We copied the schema/serializer
approach and rebuilt every control on `twenty-ui` + Linaria.
#### 3. Section typography cascade
The subtle part, and the one that would have silently shipped broken.
Section typography *looks* like it should cascade via CSS. It does not:
```js
// react-email's Text
style: { fontSize: "14px", lineHeight: "24px", ...style, ...margins }
```
Every paragraph re-declares `fontSize` and `lineHeight`, overriding any
enclosing section. `inherit` is not a fix either — Outlook's Word engine
ignores it.
So the cascade is **resolved in the renderer**: the tree walk threads
the enclosing section's typography down and writes computed values
explicitly onto each text node. Nested sections refine what they
inherit.
Verified against real rendered output:
| | rendered |
|---|---|
| paragraph inside section | `font-size:22px; color:rgb(255,0,0);
letter-spacing:2px` |
| h1 inside section | `font-size:32px` (own scale) + section colour and
spacing |
| paragraph outside | `font-size:14px`, no colour — untouched |
#### 4. Storage
`bodyTemplate` stays serialized TipTap JSON in a `TEXT` column. Block
attributes are ProseMirror node attrs, so richer blocks add keys to JSON
already being serialized — no migration, and it flows into the existing
500 ms debounced draft save unchanged.
Since the feature has not shipped, the legacy HTML-string body path was
removed rather than maintained. That is a tightening, not just a
deletion: `bodyTemplate` is writable through the record API, and the old
fallback would interpolate an arbitrary string and email it as markup. A
body that is neither empty nor a valid TipTap document is now rejected
at the send gate.
#### 5. Image hosting
Inline assets use an `EmailImage` file folder with
`ignoreExpirationToken: true` and immutable cache headers, because
recipients' mail clients never authenticate and may open an email years
later. The shared uploader returns `{ fileId, url }`; the image node
keeps both the durable file identity and its delivery URL so
ownership/lifecycle or URL resolution can evolve later without a
document migration. The server verifies the uploaded bytes and only
accepts GIF, JPEG, PNG and WebP.
This is intentionally separate from workflow/email **attachments**.
Attachments remain private files that the server reads and embeds as
MIME parts at send time; inline images need a durable recipient-facing
URL. A future workflow canvas should reuse `useUploadEmailImage` for
inline content while keeping its existing attachment control unchanged.
Adding the folder requires three registrations — the folder config, the
route guard's `SUPPORTED_FILE_FOLDERS`, and `DIRECT_UPLOAD_FILE_FOLDERS`
in the upload service.
### Bugs fixed along the way
- **Unsubscribe footer was appended after `</html>`**, outside the
document, where Gmail strips it. Legally significant, since an
unsubscribe link is required. Now inserted before `</body>`.
- **Body text colour never reached the email.**
- **`onImageUpload` was declared but never passed** by any production
call site, so drag-drop and paste image upload were inert everywhere
outside Storybook.
- **Message lists were not user-facing**, so members could not be added
from the list page.
- **Image resize wrote an undeclared `width` attribute** that TipTap
silently dropped.
- **The text bubble menu appeared over selected atom blocks** with
nothing to format.
### Review notes / known limitations
**Security posture to check.** Anything in `EmailImage` is readable by
anyone holding the URL, forever. The server now enforces an image-only
MIME allowlist from sniffed bytes, but it cannot determine whether the
image itself is confidential. This remains a deliberate trade-off for
recipient-visible inline assets.
**Test gap.** The section typography cascade has no regression test:
react-email's `render()` hangs under Jest (tried 60s), and
`twenty-emails` has no test target at all. Verified by rendering through
the built package instead. Adding a test target there is worthwhile
follow-up.
**Sending needs configuration.** `EMAILING_DOMAIN_DRIVER` defaults to
`LOG`, which fakes a messageId, reports any domain as verified, and only
logs — a campaign reaches "sent" with nothing delivered. Real sending
needs `AWS_SES`.
**Unrelated platform bug found.** The pinned "Create new record" command
throws on viewless objects like `messageListMember`, because
`recordIndexId` derives from the current view.
**Not done.** Panel chrome from the reference: breadcrumb (`Page style /
Section`), collapsible groups, per-side spacing grid, and a
variable-insert button inside link fields. All presentation over the
same data.
**Deferred.** Drag-to-reorder blocks.
`@tiptap/extension-drag-handle-react@3.4.2` matches our pinned versions
exactly, so no upgrade is needed, but its behaviour around atom node
views (HTML block, image) is unverified and belongs in its own change.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23657?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>
Co-authored-by: Félix Malfait <felix@twenty.com>
|
||
|
|
13a2e3ebe8 |
fix(twenty-server): compose email from the caller's own connected account (#23793)
### The bug
`draft_email` and `send_email` take an optional `connectedAccountId`.
When an agent omits it — which it does whenever it has no way to know
the id — `EmailComposerService` resolved the account like this:
```ts
const allAccounts = await this.connectedAccountRepository.find({
where: { workspaceId, archivedAt: IsNull() },
});
return allAccounts[0].id;
```
The first connected account **in the workspace**, ignoring the
`userWorkspaceId` that `ToolExecutionContext` already carries — with no
`ORDER BY`, so "first" is whatever the planner returns.
We hit this on our own workspace: an agent chat drafted a customer email
on behalf of one user, and the draft landed in a different user's
mailbox. The tool reported `success: true` with a `connectedAccountId`
belonging to someone who was not in the conversation, so nothing
surfaced the mistake. `send_email` shares this composer, so the same
fallback sends mail from another person's address.
### The fix
- **No id supplied** → the caller's own account
(`context.userWorkspaceId`), else an account whose `visibility` is
`workspace`, else throw `CONNECTED_ACCOUNT_NOT_FOUND`. Never a
colleague's private mailbox by accident.
- **Id supplied** → used as given, whoever owns it. Blocking a member
from composing through another member's account is a product decision
this PR does not make; the mix-up above happens when no id is passed at
all.
- **No `userWorkspaceId`** (workflow run) → unchanged.
Ordering is `createdAt ASC, id ASC` so the no-caller path is
deterministic when rows share a `createdAt` — which the seed data does.
### Verified against a real workspace
Run locally against the seeded `test` database — 7 connected accounts in
one workspace, owned by four different members, **all sharing one
`createdAt`**. Same spec, composer swapped:
| Scenario | on `main` | with this PR |
|---|---|---|
| Phil's agent composes, no id | **tim@apple.dev's account** | phil's
own |
| explicit id (jony's), caller is phil | jony's | jony's |
| workflow run (no caller), explicit id | jony's | jony's |
| **workflow run (no caller), no id** | **first account, unordered** |
**first account, `createdAt`/`id` ordered** |
| caller with no account | silently resolved a colleague's | throws |
### What this does not fix
A workflow run carries no caller: `ToolBackedWorkflowAction` executes
the tool with `{ workspaceId }` and no `userWorkspaceId`. So when an
email step's sender resolves to nothing — `postprocessInput` guards for
it — the composer still falls back to the workspace's first account,
because there is no identity to attribute the mail to. The pick is at
least deterministic now. Giving workflow runs an owner is a separate
change.
Normal workflow steps are unaffected:
`EmailWorkflowActionBase.resolveSenderConnectedAccountId` resolves the
configured sender (a connected-account id, or a workspace member id from
a resolved variable) and passes it explicitly.
### Behaviour change to expect
A caller with no connected account of their own, in a workspace with no
shared account, now gets an error where the call previously "succeeded"
from a colleague's mailbox.
### Tests
Resolution is exercised by
`test/integration/email-tool/suites/email-composer-connected-account.integration-spec.ts`
against a real workspace — eight cases: supplied id honoured, supplied
id with no caller, invalid id, unknown id, caller's own account,
workspace-shared fallback (flips `visibility` in Postgres and restores
it), no usable account, and first-account-when-no-caller.
The service's unit spec is deleted: mocking the DI graph asserted the
mock rather than the resolution, and every case it covered now runs
against the database. The pure selection logic keeps unit specs —
`select-connected-account-id-for-caller.util.spec.ts` and
`is-connected-account-usable-by-caller.util.spec.ts`.
Not covered here: the workflow chain itself (`postprocessInput` →
`resolveSenderConnectedAccountId` → `DraftEmailWorkflowAction`), which
this PR does not change.
`npx nx typecheck twenty-server`, the email-tool and connected-account
suites, and the integration spec all pass; oxlint type-aware clean.
|
||
|
|
61c72942ac |
feat(workflow): dispatch automated triggers from core behind a flag (#23775)
## Context
Part of the workflow → core migration. Before we can stop writing
workspace `trigger`/`steps`, automated-trigger dispatch must read from
core. Dispatch currently reads the workspace `workflowAutomatedTrigger`
table (populated from the workspace trigger), so it would go blank once
those writes stop. This flips the dispatch reads behind a flag,
mirroring the version-content read switch.
## What this does
New flag `IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED` (per-workspace,
default off). At each dispatch read site, flag-on reads the core-derived
trigger map and flag-off keeps the current workspace query.
- **DB-event listener** (`workflow-database-event-trigger.listener.ts`):
extracted `getDatabaseEventListeners(workspaceId, eventName)`. Flag-on
filters the core map (`getOrRecompute → byWorkflowId`, `type ===
DATABASE_EVENT && settings.eventName === name`); flag-off keeps the repo
`find`. The evaluation type is broadened to the structural `{
workflowId, settings }` that both the entity and the map entry satisfy;
the enqueue loop and `shouldTriggerJob` are unchanged.
- **CRON job** (`workflow-cron-trigger-cron.job.ts`): extracted
`getWorkspaceCronTriggers(workspaceId)`. Flag-on filters the core map
for `type === CRON` → `{ workflowId, pattern }`; flag-off keeps the raw
SQL. The redis cron cache, dedup and dispatch loop are unchanged; only
the rebuild source swaps.
## Why it's safe
- The core map is keyed by the workspace `workflowId`, and both sites
enqueue `workflowId` only. Nothing consumes the map's core
`workflowVersionId`, so `workflow-trigger.job.ts` still re-derives the
version from workspace `lastPublishedVersionId` (no id translation).
- Flag defaults off, per-workspace rollout. The drift cron's
`checkAutomatedTriggerSync` already compares the core map against the
workspace table, so it's the soak signal for flipping the flag.
- The CRON source is only re-read on a cron-cache rebuild (cache miss),
so a flag flip takes effect on the next rebuild: bounded by the cache
TTL, or immediately on activation/deactivation, which invalidates the
cache. Both sources emit identical `{ workflowId, pattern }` for a
synced workspace, so the switch is a no-op in output.
## Prerequisite
- The orphan-ACTIVE core-version cleanup (#23739) must land first: the
core map is built from core ACTIVE versions, so a phantom orphan would
become a live phantom trigger the moment this flag flips.
## Verification
- Server unit specs cover both sites with the flag off (existing
behavior) and on (reads the core map).
- Live-verified on a dev instance: DB-event and CRON dispatch both fire
from the core map with the flag on, and from the workspace entity with
it off.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23775?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. -->
|
||
|
|
196a1945ff |
i18n - translations (#23794)
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23794?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> |
||
|
|
ded3f1efb3 |
Add messages support to runAgent for multi-turn bot conversations (#23395)
- Extend `runAgent` so callers can pass either a one-shot prompt or a multi-turn messages array (user / assistant text), matching AI SDK’s XOR shape — for Slack/Discord/Teams bots that need thread history. - Enforce exactly one of prompt | messages in AgentRunService; map messages 1:1 to AI SDK ModelMessages in AgentAsyncExecutorService - Update shared types, GraphQL/SDK inputs, docs (skills-and-agents), and regenerate metadata clients; existing prompt-only callers stay unchanged <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23395?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. --> |
||
|
|
0b817e3bc0 |
Restrict which workspace fields can be updated before activation (#23781)
## What `validateWorkspaceUpdatePermissions` returned early with no checks at all when the workspace was in `PENDING_CREATION`, so `updateWorkspace` accepted any field during that window. It now allows only the fields needed to set the workspace up (`displayName`, `subdomain`, `logo`) and rejects everything else until the workspace is activated. Note that `updateWorkspace`'s resolver guard is `CustomPermissionGuard`, which always returns true and only documents that the check lives in the resolver/service, so this service method is the actual enforcement point. ## Why A workspace stays in `PENDING_CREATION` from signup until onboarding completes, and the JWT strategy issues an authenticated context for it without resolving member permissions. During that window every field was writable with no permission check, including security relevant ones such as `allowImpersonation`, `isTwoFactorAuthenticationEnforced` and `isPublicInviteLinkEnabled`. In practice the only principal present before activation is the workspace creator, who is granted the Admin role (`canUpdateAllSettings`) the moment activation completes, so there is no privilege escalation over another user today. This is defense in depth: the early return was broader than it needed to be, and it becomes a real gap if the "only the creator exists before activation" assumption ever stops holding, for example a workspace left pending or a future flow that adds members before activation. The bypass exists because a pending workspace has no roles yet, so permissions cannot be resolved for it. Keeping a small explicit allowlist preserves that while removing the blanket skip. ## Scope Only the `updateWorkspace` path. `SettingsPermissionGuard` has a similar bypass for `PENDING_CREATION` / `ONGOING_CREATION`, but it covers 62 resolvers including billing endpoints that onboarding legitimately calls before activation, so narrowing it needs its own analysis and is deliberately left out. ## Tests `workspace-update-before-activation.integration-spec.ts`, run against a real database with the seeded workspace flipped to `PENDING_CREATION`: - a security sensitive field (`allowImpersonation`) is rejected and the stored value is unchanged - mixing a setup field with a security sensitive one rejects the whole update, and `displayName` is not persisted - setup fields (`displayName`) still apply, so the restriction does not break workspace setup Both rejection tests were verified to fail when the old blanket early return is put back, while the positive control keeps passing. The existing `settings-permissions/workspace*` suites still pass (38 tests total), confirming no change for activated workspaces. --- _Generated by [Claude Code](https://claude.ai/code/session_01Qf58T7Lm7PazNbS3UwaZPd)_ <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23781?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. --> |
||
|
|
8bfa9c4adb |
Proxy API routes through the vite dev server to keep local dev same-origin (#23779)
Replaces #23774 (closed), rebased on latest main. ## Problem Since the cookie-session migration (#23642), the front sends every request with `credentials: 'include'` and the server only reflects `Access-Control-Allow-Origin` for the exact origins in the credentialed allowlist (`SERVER_URL`, `FRONTEND_URL`, `AUTH_COOKIE_ALLOWED_ORIGINS`). Any other origin gets the `*` wildcard, which browsers reject for credentialed requests. Local dev is split-origin by default (front on `localhost:3001`, API on `localhost:3000`), and with `IS_MULTIWORKSPACE_ENABLED` every workspace subdomain (`apple.localhost:3001`, ...) is yet another origin. Each locally created workspace would need a manual `AUTH_COOKIE_ALLOWED_ORIGINS` entry. ## Solution Make local dev same-origin instead of widening the CORS policy: the vite dev server now proxies all top-level API route prefixes to the backend, and the front calls its own origin. - `vite.config.ts` adds a `server.proxy` covering the backend's top-level prefixes (`/graphql`, `/metadata`, `/admin-panel`, `/auth`, `/rest`, `/file`, `/client-config`, ...), defined in `src/config/apiProxyPrefixes.ts`. Keys are anchored regexes (`^/auth($|[/?])`) so SPA routes sharing a prefix (`/authorize`, `/settings`) are not swallowed. The target defaults to `http://localhost:3000` and follows `REACT_APP_SERVER_BASE_URL`. `changeOrigin` stays off so the backend sees the browser's Host: same-origin checks (CSRF, cookie issuance) and workspace resolution by subdomain work unchanged through the proxy. - `config/index.ts` collapses to `window._env_?.REACT_APP_SERVER_BASE_URL || window.location.origin`. Every supported production path injects `window._env_` (docker entrypoint fails hard without `REACT_APP_SERVER_BASE_URL`; a server-served front gets it from `generateFrontConfig()`), and in dev the current origin is correct on `localhost:3001` and every `*.localhost:3001` workspace subdomain thanks to the proxy. The removed `http://<hostname>:3000` fallback only served an un-injected production bundle browsed on localhost, a setup whose credentialed auth the cookie-session migration had already broken. The credentialed allowlist itself is unchanged and stays strict; since dev traffic is same-origin, the per-subdomain cookie-allowlist problem disappears without loosening any production CORS/CSRF policy. ## Tests - `src/config/__tests__/apiProxyPrefixes.test.ts` guards the proxy boundary in both directions: representative backend path shapes (including `/metadata?query=...` and `/auth/...`) must match, every SPA route from the `AppPath` enum and vite's own dev paths must not — so a future route collision fails unit tests instead of breaking dev. - Verified against running dev servers: API paths proxy to the backend from both `localhost:3001` and `apple.localhost:3001`, while SPA routes `/settings` and `/authorize` still serve the vite app; a same-origin POST from `apple.localhost:3001` goes through with no CORS involvement. - `lint:diff-with-main` and `typecheck` pass for twenty-front. --------- Co-authored-by: Félix Malfait <felix@twenty.com> |
||
|
|
0f35b5895a |
fix(workflow): reject if-else branches with a dangling filterGroupId (#23758)
## Summary An If/Else workflow step branch whose `filterGroupId` doesn't resolve to any entry in `stepFilterGroups` was matching unconditionally — before any of the step's real conditions were evaluated — instead of being rejected. This let a single stale or mistyped `filterGroupId` silently hijack the routing of an entire If/Else step. Fixes #23754 ## Problem Reproduced with a standalone unit test against `findMatchingBranch`: ```ts const branches = [ { id: 'branch-A', filterGroupId: 'group-id-that-does-not-exist', nextStepIds: ['wrong-step'] }, { id: 'branch-B', filterGroupId: 'real-group', nextStepIds: ['correct-step'] }, ]; const stepFilterGroups = [{ id: 'real-group', logicalOperator: 'AND' }]; const resolvedFilters = [{ /* branch-B's real filter, evaluates to false */ }]; findMatchingBranch({ branches, stepFilterGroups, resolvedFilters }).id; // => 'branch-A' (its condition was never evaluated at all) ``` `branch-A` wins even though its `filterGroupId` doesn't exist and `branch-B`'s actual (non-matching) filter was correctly evaluated to `false`. ## Root cause `find-matching-branch.util.ts` builds `branchFilterGroups` via `collectAllDescendantGroups(branch.filterGroupId, stepFilterGroups)`, which silently returns an empty `Set` when the root id isn't found. The resulting empty `branchFilterGroups`/`branchFilters` are passed to `evaluateFilterConditions`, which treats "both empty" as vacuously `true` — a rule that's correct for the real trailing else-branch (no `filterGroupId` at all, by design) but indistinguishable, at this call site, from "the referenced group doesn't exist." Since `Array.prototype.find` returns the first match, this branch wins over any later branch whose condition was actually evaluated. There was also no validation path that would catch this before execution: `validateBranchingStep` (`validate-workflow-graph.util.ts`) already checks If/Else branch count and `nextStepIds` connectivity, but had no check for `filterGroupId` referential integrity. ## Fix 1. `find-matching-branch.util.ts` — throw `WorkflowStepExecutorException` (`INVALID_STEP_INPUT`) when a branch's `filterGroupId` doesn't resolve to any group, instead of silently falling through to `evaluateFilterConditions({filterGroups: [], filters: []})`. This mirrors the sibling guard clauses already in this action for other malformed-input cases. 2. `validate-workflow-graph.util.ts` — extended the existing `IF_ELSE` branch checks in `validateBranchingStep` with the same check, surfaced as a new `IF_ELSE_BRANCH_FILTER_GROUP_NOT_FOUND` issue code, so `validate_workflow` catches this before a workflow ever runs. **Alternative considered:** fixing only at validation time. Rejected — validation can be skipped (e.g. the AI workflow-editing tool's `validate: false` option) or bypassed entirely by a direct API write, so the execution-time guard is the actual fix; the validation check is defense in depth, not a substitute. **Alternative considered:** silently skipping the malformed branch instead of throwing. Rejected — throwing immediately gives a specific, actionable error pointing at the exact misconfiguration, matching this file's existing error granularity (distinct messages for "not an if-else step", "no branches", "missing filter groups/filters", "no matching branch"). ## Tests - `find-matching-branch.util.spec.ts` (new) — real-condition match, else-branch fallback match, throws on a dangling `filterGroupId` (fails on `main`, passes here), throws when no branch matches and there's no else branch. - `validate-workflow-graph.util.test.ts` (+2) — flags `IF_ELSE_BRANCH_FILTER_GROUP_NOT_FOUND` for a dangling reference; does not false-positive on a correctly-configured branch. - Full module suites: `npx nx test twenty-server` scoped to `src/modules/workflow` → 68 suites / 626 tests passed. `npx jest packages/twenty-shared/src/workflow` → 30 suites / 248 tests passed. - `npx nx lint twenty-server twenty-shared` and `npx nx typecheck twenty-server twenty-shared` → clean. ## Compatibility / risk Internal-only change to workflow execution and validation logic — no GraphQL schema change, no public API signature change, no migration. A workflow that today relies (accidentally) on the silent "dangling group = always match" behavior would start throwing at execution time, but that was never intentional or documented behavior. ## Out of scope - Branch **ordering** invariants (e.g. asserting the group-less else branch is always last) — not needed for this fix; the defect reproduces purely from a dangling `filterGroupId`, independent of order. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23758?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: Thomas Trompette <thomas.trompette@sfr.fr> |
||
|
|
29aa6e85d6 |
fix(front): only show Discard Draft when workflow has a published version (#23756)
## Problem Draft workflows expose a **Discard Draft** action, but it fails when the draft is the *only* version of the workflow. The backend refuses the delete with `The initial version of a workflow can not be deleted` (guard in `validateWorkflowVersionForDeleteOne`), yet the action was still shown. The display condition and the delete-guard disagreed: - Display condition: `every(selectedRecords, "versions.length")` -> truthy when there is **at least one** version. - Delete guard: forbids deletion unless **another** non-deleted version exists. So a workflow whose only version is a draft showed the button, and clicking it hit a `FORBIDDEN` error. ## Fix Show the action only when the workflow has a published version to fall back to, which mirrors the backend guard: ``` every(selectedRecords, "lastPublishedVersionId") and everyEquals(selectedRecords, "currentVersion.status", "DRAFT") and noneDefined(selectedRecords, "deletedAt") ``` `lastPublishedVersionId` is a plain scalar already on the workflow. `every` (truthiness) is used rather than `everyDefined` because the field is an empty string for never-published workflows, and `everyDefined` would treat `""` as present. The command-menu evaluator reads records straight from the store, and the index/table view only fetches visible columns, so the enrichment provider now also backfills `lastPublishedVersionId` (already fetched by `useWorkflowsWithCurrentVersions`) to keep the condition reliable outside the record show page. ## Existing workspaces The standard-application full sync only runs at workspace creation, so editing the constant alone would fix new workspaces but leave existing ones showing the broken button. A `2.27.0` workspace upgrade command re-syncs the `discardDraftWorkflow` availability expression for existing workspaces, updating it only when it still equals the legacy `versions.length` value (so custom expressions are left untouched). Mirrors the existing 2-23 command-menu-item sync pattern. ## Notes - The `>`-style "more than one version" comparison is not expressible in the current `conditionalAvailabilityExpression` grammar (comparison operators only reach top-level scalars like `numberOfSelectedRecords`, not per-record paths). Gating on `lastPublishedVersionId` achieves the same intent without adding a parser helper. ## Test - Fresh workflow (single draft) -> Discard Draft hidden. - Publish, then edit to create a new draft -> Discard Draft shown and works. - Unit test on the sync-operations builder: updates the legacy expression, no-ops when already synced / custom / missing. |
||
|
|
3833015626 |
Ignore expired invitations in invitation lookups (#23749)
## What Invitation lookups did not filter on `expiresAt`, so expired invitations were still treated as active. This aligns them with the sibling `findInvitationsByEmail`, which already applied that filter. - `WorkspaceInvitationService.getOneWorkspaceInvitation` - added `deletedAt IS NULL` and `expiresAt > now` (also converted to a typed `findOne` so the column references are checked). - `AuthService.findInvitationForSignInUp` - added `expiresAt > now` (it already filtered `deletedAt`). - `throwIfOnboardingInvitationLimitReached` - expired tokens no longer count toward the onboarding invitation limit. - `createWorkspaceInvitation` - deletes the expired token for that email before issuing a replacement, so re-invites don't accumulate stale rows. ## Why Without the filter, an expired pending invitation behaved as if it were still active: - On sign-up with a personal invite token, an expired invitation still granted access to the workspace. - Re-inviting an email whose invitation had lapsed reported `INVITATION_ALREADY_EXIST` instead of sending a fresh invite. - Expired onboarding invitations still consumed quota, so the limit could be hit by invitations nobody could use. Once expired tokens are ignored on read, a re-invite would leave the old row behind, so `createWorkspaceInvitation` now removes it. The delete is scoped to the same workspace, invitation token types, that exact email, and `expiresAt <= now`, so it can only remove tokens that are already unusable. Closes twentyhq/private-issues#503 ## Tests Integration suites added, run against a real database: - `auth/sign-up/failing-sign-up-with-expired-invitation` - expired personal invitation is rejected (snapshot asserts the specific `FORBIDDEN` error). - `auth/sign-up/successful-sign-up-with-valid-invitation` - positive control: a valid invitation still grants access, so the rejection above cannot pass for an unrelated reason. - `expired-workspace-invitation` - re-invite over an expired invitation succeeds and leaves exactly one (fresh) token; a valid invitation is still reported as already existing. Each assertion was verified to fail when its corresponding filter is removed. Unit tests (`workspace-invitation.service.spec.ts`, `auth.service.spec.ts`), typecheck, and lint all pass. Not included: invitations that expire and are never re-invited still linger, since no cron reaps invitation tokens today. |
||
|
|
0379b537dd |
feat(workflow): repair orphan core workflow versions via upgrade command (#23739)
## Context Part of the workflow + workflowVersion in core migration. Before enabling `IS_WORKFLOW_VERSION_IN_CORE_ENABLED` on real workspaces, legacy drift between the workspace source-of-truth and the core mirror must be repaired. The dangerous category is orphan **ACTIVE** core `workflowVersion` rows: once dispatch reads core (later step), they become phantom triggers. ## The problem Some workspaces carry orphan `core."workflowVersion"` rows: core versions that no workspace version references via `coreWorkflowVersionId`. On one production workspace this was 57 rows, 5 of them ACTIVE `DATABASE_EVENT`. Root cause is pre-2.25 residue: - The v2.22 `backfill-workflow-version-core-links` command minted a core row per active workspace version, copying `status` verbatim. - The workflow delete/destroy cascade did not clean core until #23356 (first in v2.25.0): there was no `deleteCoreVersionsByWorkflowIds` and the deactivate-on-delete status flip was not mirrored. - Workflows deleted then destroyed in that window left their core rows behind, still ACTIVE, with every workspace referrer gone. Current code (>= v2.25) cleans core transactionally on delete/destroy, so this cannot recur. This command clears the historical residue. ## What this does A `@RegisteredWorkspaceCommand('2.28.0')` that, per provisioned workspace: - Deletes `core."workflowVersion"` rows with no workspace referrer, then `invalidateAndRecompute`s the automated trigger map. - `NOT EXISTS` does not filter `deletedAt`, so a soft-deleted (restorable) workspace version still protects its core row. - Scoped to `applicationId = workspaceCustomApplicationId OR NULL`, so future app-owned core versions are never touched. - Supports `--dry-run` and is idempotent (re-run is a no-op). ## Testing Run through the real upgrade harness on a dev instance: - Injected 2 synthetic orphans (1 ACTIVE `DATABASE_EVENT`, 1 ARCHIVED). `--dry-run` reported `Would delete 2 (1 ACTIVE)`; real run reported `Deleted 2 (1 ACTIVE)`. - The 5 legit linked core versions were untouched (referrer guard verified). Orphans remaining: 0. - Re-run logged `No orphan core workflowVersion rows` (idempotent). - typecheck, oxlint, oxfmt all clean. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23739?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. --> |
||
|
|
1ebcbdda42 |
feat(server): export event-loop delay and workspace-cache recompute metrics (#23751)
## What
Exports three sets of metrics to Prometheus to diagnose the recurring
"Slow DB Query" Sentry issues on `POST /graphql` (e.g. the
`fieldMetadata` select):
- `twenty_nodejs_eventloop_delay_seconds` (mean/p50/p99/max) +
`twenty_nodejs_eventloop_utilization`
- `twenty_workspace_cache_recompute_duration_seconds{cache_key}` — wall
time per provider `computeForCache`
- `twenty_workspace_cache_redis_write_duration_seconds` — serialize +
Redis write time for recomputed entries
## Why
Investigation of these issues showed:
- The flagged query executes in ~1ms (prod EXPLAIN), so it is not a
query/index problem.
- Event counts do **not** correlate with connection-pool acquire latency
(Pearson ~0 against both p99 and the direct count of >1s acquires), so
it is not pool contention.
- Event counts **do** correlate with pod CPU (Pearson +0.40).
The leading explanation is that the slow `db` span is inflated by
event-loop saturation during the workspace metadata cache recompute:
`Promise.all` parallelizes the I/O, but the synchronous work it cannot
parallelize (TypeORM entity hydration of JSONB-heavy result sets, then
`JSON.stringify` of the flat-map payloads into Redis) blocks the single
event-loop thread, so an awaiting query resolves ~1.3s late.
Node event-loop delay was only being collected by Sentry's
`nodeRuntimeMetricsIntegration`, never exported to Prometheus, so it
could not be graphed or correlated in Grafana. These metrics confirm (or
refute) the mechanism and give a before/after baseline for the fix.
Grafana panels land in a companion twenty-infra PR.
## Notes
- Metric-only change; no behavioral change to the cache.
- Uses the same OTel `MetricsService` / meter as the existing DB pool
metrics.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23751?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. -->
|
||
|
|
55707868cd |
Add IS_FEATURE_FLAG_MANAGEMENT_ENABLED to unlock feature flag toggling outside cloud (#23750)
The admin panel has a per-workspace Feature Flags tab that can toggle
any key in `FeatureFlagKey`, but it was hidden unless `NODE_ENV` was
`development` or billing was enabled:
```ts
canManageFeatureFlags:
this.twentyConfigService.get('NODE_ENV') === NodeEnvironment.DEVELOPMENT || isBillingEnabled,
```
Preview apps run `NODE_ENV=production` with billing off, so the tab
disappears and there is no way to flip a flag on a `trycloudflare.com`
app short of editing `core.featureFlag` by hand.
This is purely a client-side gate. `updateWorkspaceFeatureFlag` is
guarded server-side by `AdminPanelGuard` (`canAccessFullAdminPanel`) and
has no billing or cloud check, so unhiding the tab does not widen what
the server accepts. The gate has to be coarse because `/client-config`
is a public unauthenticated endpoint and cannot carry per-user state,
which is presumably why it ended up keyed on `NODE_ENV`/billing.
## Changes
- New `IS_FEATURE_FLAG_MANAGEMENT_ENABLED` config variable
(`ADVANCED_SETTINGS`), defaulting to `false`.
- `canManageFeatureFlags` now also honours it. Development mode and
billing-enabled instances behave exactly as before.
## Notes
- Deliberately not added to `docker-compose.yml` or `.env.example`, and
not documented in `feature-flags.mdx`. Anyone who needs it can set the
env var directly.
- `twentyhq/ci-public#3` sets it for preview apps by patching the
variable into the server service and the generated `.env`, so it does
not depend on the compose file carrying the entry.
- The seeded dev users already have `canAccessFullAdminPanel: true`, and
on a non-seeded instance the first user to sign up is granted it, so the
tab is reachable once the variable is on.
## Test
`client-config.service.spec.ts` covers the new variable unlocking
management in production with billing off, alongside the existing cases
for development mode, billing enabled, and both off.
---
_Generated by [Claude
Code](https://claude.ai/code/session_015ovxLQNTHxvBbhfrKq2aZt)_
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/23750?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. -->
|
||
|
|
453f3479ab |
Accept a singleton or filter in the GraphQL filter walker (#23738)
`RecordGqlOperationFilter` types `or` as `RecordGqlOperationFilter[] |
RecordGqlOperationFilter`, so both `{ or: [{ name: { ilike: '%acme%' }
}] }` and `{ or: { name: { ilike: '%acme%' } } }` are valid.
`applyLogicalGroup` went straight to `filters.forEach(...)`, so the
non-array form threw `TypeError: filters.forEach is not a function`
instead of returning records. Only `or` is affected: `and` is always an
array and `not` is always a single object.
This is not a new bug. The same assumption existed before the walker was
extracted, when `parseKeyFilter` did the `value.forEach` inline. Sentry
surfaced it on #23369, and it was left out of that PR to keep it scoped.
The fix mirrors `renderLogicalGroup` in the RLS SQL renderer, which
already normalizes a singleton to an array on its first line, so the two
walkers over this filter format now accept the same shapes.
|
||
|
|
0408816781 |
i18n - translations (#23746)
Created by Github action <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23746?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> |
||
|
|
8e5bdcc781 |
webhook subscriptions error handling (#23707)
A `subscriptionRemoved` lifecycle notification was routed to `renewSubscription`, which PATCHes a subscription Microsoft has already deleted and always 404s ([TWENTY-SERVER-J1N](https://twenty-v7.sentry.io/issues/7604034376/), 884 events). Every sampled webhook event on that issue was `subscriptionRemoved`. Each lifecycle event now gets its own path: `subscriptionRemoved` recreates and resyncs the gap, `reauthorizationRequired` renews in place, `missed` resyncs, unrecognised events are logged and ignored. Provider errors are parsed into driver exception codes following the message-import drivers. Max retry for the renewal cron is deliberately left out and will follow separately. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/23707?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: neo773 <huzef@twenty.com> |
||
|
|
997b2c38de |
Add cookie-session integration test suite (#23715)
Stacked on #23642. Integration suite for the cookie-session surface, organized as one successful/failing spec pair per stage of the session lifecycle. 14 spec files, ~36 tests, all over real HTTP against the booted app. ## Coverage by stage **1. Session creation on auth exchanges** (`successful-`/`failing-session-creation`) Flag gating (default off: tokens, no cookie, no row); httpOnly cookie snapshot with 180d expiry window; SHA-256 hash-at-rest with the row bound to the apple seed workspace; scripted sign-ins without an Origin header still get the cookie; login-CSRF refuses the cookie for disallowed origins while returning the token pair; sign-in over an existing session revokes it as `SUPERSEDED`; a failed credentials exchange mints nothing. **2. Cookie delivery** (`successful-session-cookie-delivery`, `secure-deployment-session-cookie`) The runtime side door (`AUTH_COOKIE_SAME_SITE=none` forces the secure path) pins the `__Host-`/`Secure`/`SameSite=None` variant in the default CI run. The exact production combination (`__Host-`, `Secure`, `SameSite=Lax`) is covered by a dedicated spec that requires the app to boot with an https `SERVER_URL`: the secure branch is decided by config, never the transport, so no TLS is needed. It skips itself on plain-http boots; CI runs it as an extra step on one shard with `SERVER_URL=https://localhost:3000`, including the `__Host-` round-trip and the plain-cookie-name downgrade refusal. **3. Per-request authentication and the CSRF read gate** (`successful-`/`failing-session-cookie-authentication`) A cookie-only request resolves the seeded user; a `sess_` token presented as Bearer is rejected; cookie-authenticated unsafe requests with a disallowed or missing Origin get 403 `CSRF_ORIGIN_MISMATCH`; an unknown session token is unauthenticated and its dead cookie is cleared. **3b. Workspace binding** (`successful-session-workspace-binding`) Tim signs into both seeded workspaces (apple and yc); each session row is bound to the workspace its exchange selected (`workspaceId` and `userWorkspaceId` pinned to the seed ids), and each cookie resolves to its own workspace context, with no request-side input able to pivot a session across workspaces. **3c. Credentialed CORS** (`cors-credentialed-origins`) Allowlisted origins get the reflected `Access-Control-Allow-Origin` plus `Access-Control-Allow-Credentials: true` and `Vary: Origin`, preflight included; other origins keep the public wildcard. See tooling notes: this surface was previously untestable. **4. Sessions API** (`successful-`/`failing-user-sessions-api`) `currentUserSessions` marks exactly the presented session as current; `revokeUserSession` revokes by id (`USER_REVOKED`) and drops it from the listing; `revokeAllOtherUserSessions` spares the presented session; cross-user revocation and unauthenticated listing are refused. **5. Exits** (`successful-sign-out`, `failing-session-expiration`) `signOut` revokes with `USER_SIGN_OUT`, clears the cookie, and reuse fails immediately (cache invalidated, not TTL-bound); a cookie-less sign-out clears nothing, so a cross-site POST cannot log a visitor out; absolute-lifetime and idle-timeout expiry both reject and clear the cookie. **7. Cleanup cron** (`user-session-cleanup-cron`) Both halves run in-process against fixtures spanning the 30d retention boundary. Sessions: expired/revoked-beyond-retention deleted; active, recently-expired, and idle-expired rows survive (the idle case pins the known predicate gap). Refresh tokens: old-expired and old-revoked deleted, fresh kept, and a long-expired token of another type survives, pinning the `type` filter that keeps the shared `appToken` table safe from the hard-delete. Not covered here by design: the impersonation park/restore sub-funnel (stage 6, follow-up) and the client-side funnel (stage 8, front-end scope). Password-change revocation and the renewal bridge are also left to follow-ups. ## How the flag is flipped `AUTH_COOKIE_SESSIONS_ENABLED` (and `AUTH_COOKIE_SAME_SITE` for the secure side door) are toggled at runtime through the admin panel config API, reusing the `twenty-config` test utils: `DatabaseConfigDriver.set` updates its cache synchronously and `TwentyConfigService` consults the DB driver before the env driver. No `.env.test` change, no app reboot, runs in the default CI environment without the `ci:auth-cookie-sessions` label. `SERVER_URL` is env-only, hence the dedicated CI step for the production secure-deployment spec. ## Shared tooling changes - **`applyCredentialedCors` extraction (src change)**: the integration harness booted with Nest's wildcard `cors: true`, not the credentialed-allowlist setup living in `main.ts`, so the CORS surface was untestable by construction. The setup moved into `applyCredentialedCors`, now called by both the production bootstrap and `createApp`, making the harness's CORS behavior the deployed one. Behavior-neutral for production. - `makeMetadataAPIRequest` accepts an explicit `null` token for unauthenticated requests. Passing `undefined` silently fell back to the default admin token (parameter defaults apply to `undefined`), which made supposedly public requests Bearer-authenticated, bypassing both the cookie auth path and the CSRF middleware. Existing call sites are unaffected. - The `GetLoginTokenFromCredentials` / `GetAuthTokensFromLoginToken` documents moved into shared query factories; the workspace-origin builder is extracted and generalized to any seeded subdomain (`buildWorkspaceOriginForSubdomain`, reused by `getAccessTokenForCredentials`). - Suite-local helpers: `signInWithCookieCapture` (full credentials exchange returning the raw supertest response, with a `workspaceSubdomain` option), `postMetadataOperationWithHeaders` (Origin/Cookie header control), cookie extraction for both cookie names, clearing-cookie detection, snapshot normalization (token and expiry redacted), and shared `ALLOWED_ORIGIN`/`DISALLOWED_ORIGIN` constants derived from `FRONTEND_URL`. Verified locally: full suite green in CI mode on both plain-http and https-`SERVER_URL` boots; oxlint and tsc clean. --------- Co-authored-by: Félix Malfait <felix.malfait@gmail.com> |