Repository navigation
Tags
Tags
test(apps): remove the unsupported icon from the function-execute fix… …ture (twentyhq#27008) The function-execute test fixture passes `icon` to `defineApplication`, but `ApplicationConfig` no longer has an `icon` field, so the fixture fails a type check: ```ts application.config.ts(9,3): error TS2353: Object literal may only specify known properties, and 'icon' does not exist in type 'ApplicationConfig'. ``` Nothing reads this value, and the tests that use this fixture don't type-check it, which is why it went unnoticed. This removes the line.
test(apps): remove the unsupported icon from the function-execute fix… …ture (twentyhq#27008) The function-execute test fixture passes `icon` to `defineApplication`, but `ApplicationConfig` no longer has an `icon` field, so the fixture fails a type check: ```ts application.config.ts(9,3): error TS2353: Object literal may only specify known properties, and 'icon' does not exist in type 'ApplicationConfig'. ``` Nothing reads this value, and the tests that use this fixture don't type-check it, which is why it went unnoticed. This removes the line.
feat(ai): link chat threads to workspace members (expand step) (twent… …yhq#26564) ## Problem Since 2.42, `agentChatThread` lives in the workspace schema, but its owner is still `userWorkspaceId`, a UUID that points at `core.userWorkspace`. That cross-schema reference led to the per-workspace FKs on core tables that twentyhq#26547 removed. Since then nothing enforces it. The owner should be the workspace-level equivalent, `workspaceMember`. ## Approach: expand now, contract next release On cloud, a new server runs before each workspace's upgrade command has reached it. A one-step switch would mean either downtime or a runtime that understands both shapes. An earlier version of this branch did the latter (owner mapping utils, catalog checks, an undefined-column retry). Those are removed here. The move is split instead: - **Expand (this PR)**: add the new relation next to the old column and backfill it. Runtime keeps using `userWorkspaceId`. - **Contract (next release)**: runtime switches to `workspaceMemberId` end to end, and a command drops the legacy column. Tracked with every other piece of transition code in twentyhq/core-team-issues#2925. ## Changes **Metadata** - New `agentChatThread.workspaceMember` MANY_TO_ONE relation (`workspaceMemberId`, `onDelete: CASCADE`), with inverse `workspaceMember.agentChatThreads` and `workspaceMemberIndex`. - The legacy `userWorkspaceId` field and `ownerIndex` are unchanged, so the public API only gains fields. - `ownerIndex` is a plain index on the workspace table's own column, not a cross-schema reference. It goes away with the column in the contract step. **Upgrade command** `upgrade:2-43:link-chat-threads-to-workspace-members` (last in 2.43) - Creates exactly the two relation fields and the index, by universal identifier, from the standard definition. Later changes to the agent history objects cannot change what it creates. - Backfills `workspaceMemberId` through `core.userWorkspace`, preferring members that are not deleted. Uses only its own SQL. - Idempotent and supports dry run. It skips workspaces without chat history objects, since the 2.42 move provisions those with the new shape. `down` is a no-op. - Threads whose owner left keep a null member. The contract step deletes them. **Runtime** - One shim, marked with the cleanup issue: when the workspace metadata already has the new field, `createThread` also writes the creator's member id, taken from the auth context with no lookup. - The dev seeder writes both columns. ## Validation - Command spec: skip and dry-run paths. - Chat integration test: a created thread stores its creator's member id. The test fails with the shim disabled. - Integration suites after a database reset: chat-thread-sharing (11), chat-sender-execution (4), admin-chat-threads (15), and the 2.42 agent history move. Agent history PostgreSQL spec 37/37. - Unit suites for ai, standard application and database commands pass. `tsgo` and oxlint are clean.
feat(ai): link chat threads to workspace members (expand step) (twent… …yhq#26564) ## Problem Since 2.42, `agentChatThread` lives in the workspace schema, but its owner is still `userWorkspaceId`, a UUID that points at `core.userWorkspace`. That cross-schema reference led to the per-workspace FKs on core tables that twentyhq#26547 removed. Since then nothing enforces it. The owner should be the workspace-level equivalent, `workspaceMember`. ## Approach: expand now, contract next release On cloud, a new server runs before each workspace's upgrade command has reached it. A one-step switch would mean either downtime or a runtime that understands both shapes. An earlier version of this branch did the latter (owner mapping utils, catalog checks, an undefined-column retry). Those are removed here. The move is split instead: - **Expand (this PR)**: add the new relation next to the old column and backfill it. Runtime keeps using `userWorkspaceId`. - **Contract (next release)**: runtime switches to `workspaceMemberId` end to end, and a command drops the legacy column. Tracked with every other piece of transition code in twentyhq/core-team-issues#2925. ## Changes **Metadata** - New `agentChatThread.workspaceMember` MANY_TO_ONE relation (`workspaceMemberId`, `onDelete: CASCADE`), with inverse `workspaceMember.agentChatThreads` and `workspaceMemberIndex`. - The legacy `userWorkspaceId` field and `ownerIndex` are unchanged, so the public API only gains fields. - `ownerIndex` is a plain index on the workspace table's own column, not a cross-schema reference. It goes away with the column in the contract step. **Upgrade command** `upgrade:2-43:link-chat-threads-to-workspace-members` (last in 2.43) - Creates exactly the two relation fields and the index, by universal identifier, from the standard definition. Later changes to the agent history objects cannot change what it creates. - Backfills `workspaceMemberId` through `core.userWorkspace`, preferring members that are not deleted. Uses only its own SQL. - Idempotent and supports dry run. It skips workspaces without chat history objects, since the 2.42 move provisions those with the new shape. `down` is a no-op. - Threads whose owner left keep a null member. The contract step deletes them. **Runtime** - One shim, marked with the cleanup issue: when the workspace metadata already has the new field, `createThread` also writes the creator's member id, taken from the auth context with no lookup. - The dev seeder writes both columns. ## Validation - Command spec: skip and dry-run paths. - Chat integration test: a created thread stores its creator's member id. The test fails with the shim disabled. - Integration suites after a database reset: chat-thread-sharing (11), chat-sender-execution (4), admin-chat-threads (15), and the 2.42 agent history move. Agent history PostgreSQL spec 37/37. - Unit suites for ai, standard application and database commands pass. `tsgo` and oxlint are clean.
fix(ai): stop creating per-workspace foreign keys to core tables for … …agent history (twentyhq#26547) ## Problem Moving agent history to workspace schemas (2.42) added two constraints on every workspace schema that point at core tables: - `<workspace>.agentMessagePart.fileId -> core.file(id) ON DELETE RESTRICT` - `<workspace>.agentChatThread.userWorkspaceId -> core.userWorkspace(id) ON DELETE CASCADE` With N workspaces: - `core.file` and `core.userWorkspace` each end up with 2N RI triggers. Every backend loads all of them into its relcache, and each `ADD CONSTRAINT` invalidates that cache everywhere, so the upgrade slows down as it goes. - Each `ADD CONSTRAINT` takes a `SHARE ROW EXCLUSIVE` lock on the shared core table, which blocks writes to it instance-wide and queues behind long transactions. - Deleting one `core.file` or `core.userWorkspace` row checks and locks N workspace tables. `fileId` is not indexed, so each check is a sequential scan, and taking N locks can hit `max_locks_per_transaction`. - Dropping a workspace schema now also needs locks on those core tables. These constraints were created in four places: the 2.42 migration, `initializeWorkspace` (every new workspace), and every twenty-standard application sync. ## Changes - Remove `prepareCoreReferences`/`addCoreReferences` and all their call sites. `validateReferences` still checks both references when history is copied, and file hydration already handles a missing file. - Replace the `userWorkspace` cascade with application code: the two member-removal flows (the workspace member delete-one post-query hook and `UserService`'s workspace member removal) delete the member's chat threads right after deleting the `userWorkspace`. Turns, messages, parts and evaluations cascade inside the workspace schema. Workspace deletion doesn't need this because it drops the whole schema. The constraints already created in production were dropped manually, and the 2.42 upgrade never shipped to self-hosted instances, so there is no cleanup command. ## Notes - Known limitation (agreed in review): if thread deletion fails after the membership is gone, for example while that workspace's history migration is fenced, the threads stay behind. Nobody can reach them because their `userWorkspace` no longer exists. A sweep for orphaned threads can come in a follow-up. - Not included here: copying from core sorts every row of the workspace on each batch (`WHERE "workspaceId" = $1 ORDER BY id` with only a `workspaceId` index). A temporary `(workspaceId, id)` index on the core history tables would help very large workspaces. ## Validation - Agent history PostgreSQL suite (`AGENT_HISTORY_TEST_DATABASE_URL`): 45/45 pass. This includes a new test that `initializeWorkspace` plus migration creates no constraint referencing `core`, which fails on the previous code. - User, workspace-member, ai-history and twenty-standard-application unit tests pass. - Server typecheck (`tsgo`) is clean for the changed files; oxlint and prettier pass.
Reload the enterprise validity token in the server process (twentyhq#… …26449) ## Problem A self-hosted customer reported that their license "stops renewing", and because SSO is their login method, expiry locks everyone out. Their workaround is to disable SSO, log in with a password, reload the license, then re-enable SSO. The token is renewing fine. The server process just never re-reads it. - `EnterprisePlanService` loads the validity token into memory at boot (`onModuleInit`). - The daily refresh cron runs in the **worker** process. It fetches a new token and writes it to `appToken`, refreshing the worker's own copy. - The server process reloads only on restart, on `getLicenseInfo()` (the Enterprise settings page) or after a refresh triggered from that page. - Tokens last 7 days since twentyhq#22464 (they used to last 30, and `isValid()` used to fall back to any `ENTERPRISE_KEY` before that fallback was removed). So a server up for more than 7 days without a restart or a settings visit reports the license as expired while a fresh token sits in the database next to it. `isValid()` gates the SSO endpoints, so SSO sign-in starts failing for everyone. It also silently affects row-level permissions, event logs, email group access and custom AI providers. ## Fix `hasValidEnterpriseValidityToken()` reloads the stored token when its copy is older than 15 minutes. The reload is kept off the read path: it runs in the background, stamped before its first await so concurrent readers don't each start one, and the next read picks the result up. That mirrors how `CustomAiProviderAccessService` refreshes its seat count. Reads stay synchronous, so no call site changes. Making `isValid()` async instead ripples into 17 call sites and collides with the sync `getCurrentDriver()` signature in `DynamicFactoryBase`, for no benefit here: the token is renewed daily and lasts 7 days, so a 15-minute reload keeps the server's copy days away from expiry. Three details worth a reviewer's attention: - **A failed read keeps the token in hand.** `loadValidityToken()` used to null the cache in its catch block, which was harmless when it only ran at boot but would let a brief database outage disable every enterprise gate for a whole interval. A failed read now leaves the payload alone and is retried after 1 minute instead of 15. - **Sign-in waits for a due reload.** The SSO guard calls `isValidWithFreshToken()`, which awaits the reload when the copy has aged out, so the first sign-in after a quiet period isn't turned away on a stale copy. Every other caller stays synchronous. - **The server now follows revocations too.** When the worker's refresh is rejected with `ENTERPRISE_KEY_BOUND_TO_ANOTHER_SERVER`, it revokes the stored token; the server picks that up on its next reload instead of holding its in-memory copy until a restart. A revocation landing while a read is in flight is not undone, guarded by a revocation counter. ## Testing - `is-validity-token-reload-due.util.spec.ts` covers the staleness rule: due before anything has been read, not due inside the interval, due once it elapses, and the shorter retry after a failed read. - Not covered by tests: that a reload actually swaps the cached payload, that a failed reload keeps the previous one, and the revocation race. All three need validity tokens signed with the enterprise private key, which is not in the repo, and the repo standard rules out unit-testing the service with a mocked DI graph. Worth a look if someone sees a seam I missed. - twenty-server enterprise tests pass, oxlint and oxfmt pass, no typecheck errors in the changed files. - Not reproduced end to end: it needs a licensed instance left running past the token expiry. ## Workaround for affected instances Restart the server container, or have an admin open Settings > Enterprise, which re-reads the token. Nothing outside the process can clear that cache. (cherry picked from commit dd6c74c)
fix(workflow): resolve the workspace version when a core version has … …no alias yet (twentyhq#26515) Hotfix for TWENTY-SERVER-K11 ("Workflow Run Invalid: Core workflow not found"). Since v2.42.2 reached prod at 09:15 UTC, no workflow run can be created in workspaces whose 2.42 workspace upgrade hasn't run yet: 4,694 events across 45 workspaces in the first 12 minutes. ## Cause Every run is created by `CoreWorkflowRunnerService.run`, whatever triggers it: webhook, core manual run, legacy `runWorkflowVersion`, or the trigger job (cron, database event). The runner requires the core version's `workspaceWorkflowVersionId` alias whenever the core workflow has a `workspaceWorkflowId`. The legacy entry points also go through that alias (`findCoreVersionByWorkspaceVersionId`) to translate a workspace version id into a core version. The alias is only filled by the 2.42 workspace command `backfill-workspace-workflow-version-id`. The deploy only runs instance commands, so until the workspace upgrade reaches a workspace, its aliases are empty and every run fails: "Core workflow not found" in the runner, "Workspace workflow version has no core execution mapping" on the legacy path. Dev showed the same pattern between Sept 19 and 22, before its upgrade. ## Change Both lookups fall back to the `coreWorkflowVersionId` link on the live workspace version, the same link the backfill copies into the alias: - `CoreWorkflowRunnerService.run`: when the alias is empty and the core workflow has a workspace workflow, resolve the workspace version whose `coreWorkflowVersionId` is this core version. The resolved id feeds the consistency check and the run projection, so runs keep a non-null `workflowVersionId` where that column is still required. - `findCoreVersionByWorkspaceVersionId`: when no core version carries the alias, follow the workspace version's `coreWorkflowVersionId`. It returns that core version only if the core version has no alias of its own. These lookups are transition scaffolding. They go away with the workspace projection, and after the 2.42 upgrade they never trigger, because every live version then has its alias. ## Verification On a local instance, put a workspace in the pre-upgrade state: every core-version alias set to NULL, and `workflowRun.workflowId` / `workflowVersionId` back to NOT NULL. Then, on an ACTIVE database-event workflow: - Database event (add a person): run created. - Legacy `runWorkflowVersion` with the workspace version id: run created. - `runCoreWorkflowVersion` with the core version id: run created. Each run has the core version id and the resolved workspace version id. The worker logged neither error, and the aliases stayed empty. Not exercised: webhook, cron, and legacy queued trigger payloads. They go through the same two methods. To ship as 2.42.3 (2.42.2 + this PR). Both files are identical on `main` and `twenty/v2.42.2`. (cherry picked from commit 98a123d)
fix(workflow): create missing core workflows in the 2.42 execution ba… …ckfill (twentyhq#26511) Follow-up to twentyhq#26435. The 2.42 upgrade on staging fails `upgrade:2-42:backfill-workflow-execution-core-ids` for workspace `8f7e1bcf` with "Missing or conflicting workflow version mapping". The two versions named in the error are that workspace's prefilled "Quick Lead" and "Create company when adding a new person". ## Cause (from staging data) Before twentyhq#23204 (2.24.0), prefill wrote the seeded workflows to the workspace schema only. Workspaces that already existed got their core rows from the one-shot 2.22 (versions) and 2.23 (workflows) rebuilds. This workspace was created on July 22 at 12:05, nine minutes after staging ran the 2.23 rebuild, and before 2.24. Its cursor started after both rebuilds, so it has no core workflow, no core version, and empty `coreWorkflowId` / `coreWorkflowVersionId` links. twentyhq#26435 already creates missing core versions, but only under an existing core workflow. That covers dev, where the 2.23 rebuild ran after the gap workspaces were created. Here nothing gets created and the mapping check fails. ## Change Before the version repair, the command creates the missing core workflow for each live workspace workflow with an empty `coreWorkflowId` and no core workflow pointing back at it. It copies the name and published pointer, sets `workspaceWorkflowId`, uses the workspace custom application, and writes the new id back. The existing repair then creates the core versions under it, and the published-pointer backfill links them. The count is logged per workspace. As with twentyhq#26435, the repaired prefill workflows keep their workspace status. So an ACTIVE "Create company when adding a new person" runs again after the upgrade. ## Verification Reproduced the staging shape on a local instance (Apple workspace, both prefill workflows with no core rows and empty links): - The command on `main` creates nothing, and the mapping check returns both versions, matching staging. - With this change, the dry run reports 2 core workflows and 2 core versions and writes nothing. The real run creates them, and every link, name, published pointer, content and application id matches. - Adding a person dispatches "Create company when adding a new person" on the new core workflow. - A second run creates nothing. After merge, a 2.42.2 patch tag (2.42.1 + this commit) is needed to unblock staging and prod. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/26511?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. --> (cherry picked from commit 7cd46b9)
Put the record creation form back behind a feature flag (twentyhq#26472) Puts the record creation form back behind `IS_RECORD_CREATION_FORM_ENABLED`, removed in twentyhq#25907. With the flag off, creating a record is the pre-form behaviour again: the record is created immediately, then opened (side panel or record page, label identifier in edit mode) as before. ## Changes - `FeatureFlagKey.IS_RECORD_CREATION_FORM_ENABLED` restored: shared enum, admin panel flag metadata, dev seed (on, so local dev and the e2e `create-record` spec keep using the form), generated front enums and the SDK metadata client. - `useRecordCreationForm` exposes `isRecordCreationFormEnabled`. `useCreateNewRecord` requests the form only when it is on, otherwise calls `createRecord` directly; the post-create flow after that is shared by both paths. - The global "Create <object>" command menu items are hidden again when the flag is off, as before twentyhq#25907. - `RecordCreationFlow` stories enable the flag, since they exercise the form. The provider stays mounted and the context stays required; only the entry point is gated. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/26472?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. --> (cherry picked from commit 2ae0934)
PreviousNext