Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit): cap an application's credits across all usage (#27998)

Etienneb54a36f831cd
diff --git a/packages/twenty-apps/public/call-recorder/SETUP.md b/packages/twenty-apps/public/call-recorder/SETUP.md
index 28ca325753f..0bae73926b5 100644
--- a/packages/twenty-apps/public/call-recorder/SETUP.md
+++ b/packages/twenty-apps/public/call-recorder/SETUP.md
@@ -98,7 +98,7 @@ webhook update is missed.
| Symptom | Likely cause | Fix |
|---|---|---|
| No bot joined a meeting | **Recording** was off, the event had no conference link, it wasn't synced from a connected calendar, or `RECALL_API_KEY` isn't set | Confirm the event is on, upcoming, has a video link, and came from a synced calendar; confirm `RECALL_API_KEY` is set |
-| Recording is `NOT_RECORDED` with reason `workspace_out_of_credits`, `workspace_without_subscription` or `workspace_suspended` | The workspace could not spend credits about ten minutes before the bot would have joined, so the bot was canceled or never created | Top up credits or fix the subscription in **Settings → Billing**; later meetings are recorded again, the skipped meeting is not retried |
+| Recording is `NOT_RECORDED` with reason `workspace_out_of_credits`, `workspace_without_subscription` or `workspace_suspended` | The workspace could not spend credits about ten minutes before the bot would have joined, or a usage limit on Call Recorder was reached, so the bot was canceled or never created | Top up credits or fix the subscription in **Settings → Billing**, or raise the limit in **Settings → Billing → Limits**; later meetings are recorded again, the skipped meeting is not retried |
| Recording never reaches `COMPLETED` | A Recall webhook was missed, or only one of audio/video was produced | The reconciliation job pulls the latest status from Recall within a few minutes; if it is marked `FAILED`, inspect the bot in the Recall dashboard |
| Transcript empty, or marked pending/failed | Recall hasn't finished async transcription yet, or transcription failed for that call | Wait for the reconciliation job to ingest the transcript; a persistent failure leaves a marker in the transcript |
| Webhook rejected with `500` (`Invalid webhook signature`, Recall keeps retrying) | `RECALL_WEBHOOK_SECRET` doesn't match the Recall endpoint's signing secret | Re-copy the `whsec_…` secret from the Recall webhook endpoint into the `RECALL_WEBHOOK_SECRET` server variable |
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 2b70b5560c7..cb52312a6ec 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -5392,6 +5392,7 @@ type UsageQuotaWithConsumption {
enum UsageResourceType {
AI
+ ALL
API
APP
EMAIL
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index bde07e7a6c8..7e58eb6fffb 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -3459,7 +3459,7 @@ export interface UsageQuotaWithConsumption {
__typename: 'UsageQuotaWithConsumption'
}
-export type UsageResourceType = 'AI' | 'API' | 'APP' | 'EMAIL' | 'LOGIC_FUNCTION' | 'RECORD' | 'STORAGE' | 'WEBHOOK' | 'WORKFLOW'
+export type UsageResourceType = 'AI' | 'ALL' | 'API' | 'APP' | 'EMAIL' | 'LOGIC_FUNCTION' | 'RECORD' | 'STORAGE' | 'WEBHOOK' | 'WORKFLOW'
export interface UsageTimeSeries {
creditsUsed: Scalars['Float']
@@ -11980,6 +11980,7 @@ export const enumUsageOperationType = {
export const enumUsageResourceType = {
AI: 'AI' as const,
+ ALL: 'ALL' as const,
API: 'API' as const,
APP: 'APP' as const,
EMAIL: 'EMAIL' as const,
diff --git a/packages/twenty-docs/developers/extend/apps/logic/credits.mdx b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
index 2202605b302..9914fa81e9d 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
@@ -140,14 +140,14 @@ if (!hasAvailableCredits) {
}
```
-When credits are unavailable a `reason` comes with it: `no-credits`, `no-subscription`, or `workspace-suspended`.
+When credits are unavailable a `reason` comes with it: `no-credits`, `no-subscription`, or `workspace-suspended`. `no-credits` also covers an **All usage** limit an admin set on your app under **Settings → Billing → Limits**: the workspace may still have credits, but your app may not spend them.
Notes:
-- It answers whether the workspace may spend, not how much it has left. Your app does not see the balance or the plan.
+- It answers whether your app may spend in this workspace, not how much it has left. Your app does not see the balance, the plan or its limits.
- It fails open. If the check times out or the server is unreachable it reports credits available, so an infrastructure hiccup does not stop your app. Treat it as a hint worth honouring, not as an authorization decision.
- It is a snapshot. Credits can run out between the check and the work — including because of your own charges, since every charge you make moves the same counter this reads.
-- The gate is not applied uniformly. Not every outbound email path is credit-gated, so a `false` here tells you the workspace is out of credits rather than predicting exactly which calls will fail.
+- The gate is not applied uniformly. Not every outbound email path is credit-gated, so a `false` here tells you your app should not spend right now rather than predicting exactly which calls will fail.
## Telling people what it costs
diff --git a/packages/twenty-docs/user-guide/billing/capabilities/usage-limits.mdx b/packages/twenty-docs/user-guide/billing/capabilities/usage-limits.mdx
index e699e646531..a00c4f56cfc 100644
--- a/packages/twenty-docs/user-guide/billing/capabilities/usage-limits.mdx
+++ b/packages/twenty-docs/user-guide/billing/capabilities/usage-limits.mdx
@@ -15,11 +15,14 @@ Viewing and changing limits requires the **Workspace** settings permission.
| **Workflows** | Workflow Execution | Credits or runs | Workspace, app |
| **Logic functions** | Code Execution | Credits or runs | Workspace, app, logic function |
| **Email** | Email Send | Credits or emails | Workspace, member |
+| **All usage** | Everything above, plus app charges | Credits | App |
<Note>
**All operations** caps everything the usage spends, whichever operation it came from. It is available wherever the usage can be measured in credits.
</Note>
+**All usage** puts one cap on everything an app spends: its logic functions, workflows, agents, AI calls and the credits it charges directly. It is the way to cap what an app costs you in total. It is not offered for the whole workspace, whose total is already capped by its credits.
+
## Meters and Periods
A limit counts either **credits**, the same unit as your balance, or **operations**, a raw count of messages, searches, runs or emails. Cap credits to control cost, operations to control volume.
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index a8b9b84b8d8..9cc11eb3591 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -1080,6 +1080,7 @@ export enum UsageOperationType {
export enum UsageResourceType {
AI = 'AI',
+ ALL = 'ALL',
API = 'API',
APP = 'APP',
EMAIL = 'EMAIL',
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 7ca0436e385..e6e9b08473f 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -7507,6 +7507,7 @@ export type UsageQuotaWithConsumption = {
export enum UsageResourceType {
AI = 'AI',
+ ALL = 'ALL',
API = 'API',
APP = 'APP',
EMAIL = 'EMAIL',
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx
index b11817c0d56..b36f6217878 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx
@@ -8,9 +8,9 @@ import { useLingui } from '@lingui/react/macro';
import { isDefined } from 'twenty-shared/utils';
import { Dropdown } from 'twenty-ui/components/navigation';
import {
- type UsageOperationType,
+ UsageOperationType,
type UsageQuotaDefinitionsQuery,
- type UsageResourceType,
+ UsageResourceType,
} from '~/generated-metadata/graphql';
const USAGE_DROPDOWN_ID = 'usage-limit-usage';
@@ -33,19 +33,37 @@ export const SettingsBillingLimitUsageSelect = ({
}: SettingsBillingLimitUsageSelectProps) => {
const { t } = useLingui();
- const operationLabel = isDefined(operationType)
- ? t(USAGE_OPERATION_TYPE_LABELS[operationType])
- : t`All operations`;
+ const getSelectedLabel = (): string => {
+ if (!isDefined(resourceType)) {
+ return t`Choose a usage`;
+ }
- const selectedLabel = isDefined(resourceType)
- ? `${t(USAGE_LIMIT_RESOURCE_TYPE_LABELS[resourceType])} · ${operationLabel}`
- : t`Choose a usage`;
+ const resourceLabel = t(USAGE_LIMIT_RESOURCE_TYPE_LABELS[resourceType]);
+
+ if (resourceType === UsageResourceType.ALL) {
+ return resourceLabel;
+ }
+
+ const operationLabel = isDefined(operationType)
+ ? t(USAGE_OPERATION_TYPE_LABELS[operationType])
+ : t`All operations`;
+
+ return `${resourceLabel} · ${operationLabel}`;
+ };
+
+ const hasAllUsageDefinition = definitions.definitions.some(
+ (definition) => definition.resourceType === UsageResourceType.ALL,
+ );
+
+ const operationDefinitions = definitions.definitions.filter(
+ (definition) => definition.resourceType !== UsageResourceType.ALL,
+ );
return (
<SettingsBillingLimitNestedSelect
dropdownId={USAGE_DROPDOWN_ID}
label={t`Usage`}
- selectedLabel={selectedLabel}
+ selectedLabel={getSelectedLabel()}
SelectedIcon={
isDefined(resourceType)
? USAGE_LIMIT_RESOURCE_TYPE_ICONS[resourceType]
@@ -54,7 +72,25 @@ export const SettingsBillingLimitUsageSelect = ({
>
<Dropdown.Page id="root">
<Dropdown.Section>
- {definitions.definitions.map((definition) => (
+ {hasAllUsageDefinition && (
+ <Dropdown.OptionItem
+ selected={resourceType === UsageResourceType.ALL}
+ onSelect={() =>
+ onChange({
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ })
+ }
+ startIcon={
+ <SelectOptionIcon
+ Icon={USAGE_LIMIT_RESOURCE_TYPE_ICONS[UsageResourceType.ALL]}
+ />
+ }
+ >
+ {t(USAGE_LIMIT_RESOURCE_TYPE_LABELS[UsageResourceType.ALL])}
+ </Dropdown.OptionItem>
+ )}
+ {operationDefinitions.map((definition) => (
<Dropdown.ActionItem
key={definition.resourceType}
page={definition.resourceType}
@@ -71,7 +107,7 @@ export const SettingsBillingLimitUsageSelect = ({
))}
</Dropdown.Section>
</Dropdown.Page>
- {definitions.definitions.map((definition) => (
+ {operationDefinitions.map((definition) => (
<Dropdown.Page
key={definition.resourceType}
id={definition.resourceType}
diff --git a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx
index 8196d37f2da..94860c1e0cb 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx
@@ -12,6 +12,19 @@ import {
const DEFINITIONS = {
__typename: 'UsageQuotaDefinitions' as const,
definitions: [
+ {
+ __typename: 'UsageQuotaDefinition' as const,
+ resourceType: UsageResourceType.ALL,
+ allowedOperations: [
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.ALL,
+ allowedUnits: [UsageUnit.CREDIT],
+ },
+ ],
+ allowedSpenderTypes: ['application'],
+ operatorOnlyScopes: [],
+ },
{
__typename: 'UsageQuotaDefinition' as const,
resourceType: UsageResourceType.AI,
@@ -95,6 +108,34 @@ export const AllOperations: Story = {
},
};
+export const AllUsage: Story = {
+ args: {
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ },
+};
+
+export const SelectAllUsage: Story = {
+ args: {
+ onChange: fn(),
+ },
+ play: async ({ canvasElement, args }) => {
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(within(canvasElement).getByRole('button'));
+ const popup = await body.findByRole('dialog', { name: 'Usage' });
+
+ await userEvent.click(
+ within(popup).getByRole('button', { name: 'All usage' }),
+ );
+ await waitFor(() => expect(popup).not.toBeInTheDocument());
+ expect(args.onChange).toHaveBeenCalledWith({
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ });
+ },
+};
+
export const NavigateAndSelect: Story = {
args: {
resourceType: UsageResourceType.AI,
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts
index 3a2ee100a89..2de20e14005 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeIcons.ts
@@ -2,6 +2,7 @@ import {
IconAddressBook,
IconApi,
IconApps,
+ IconCoins,
IconFiles,
type IconComponent,
IconMail,
@@ -16,6 +17,7 @@ export const USAGE_LIMIT_RESOURCE_TYPE_ICONS: Record<
UsageResourceType,
IconComponent
> = {
+ [UsageResourceType.ALL]: IconCoins,
[UsageResourceType.AI]: IconSparkles,
[UsageResourceType.API]: IconApi,
[UsageResourceType.APP]: IconApps,
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts
index 38af87a6813..aeea87310b6 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitResourceTypeLabels.ts
@@ -7,6 +7,7 @@ export const USAGE_LIMIT_RESOURCE_TYPE_LABELS: Record<
UsageResourceType,
MessageDescriptor
> = {
+ [UsageResourceType.ALL]: msg`All usage`,
[UsageResourceType.AI]: msg`AI`,
[UsageResourceType.API]: msg`API`,
[UsageResourceType.APP]: msg`Apps`,
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts
index e8afb58b67e..13fa137e437 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts
@@ -17,6 +17,7 @@ import { getUsageLimitSpenderName } from '@/settings/billing/utils/getUsageLimit
import { isKeyOfRecord } from '@/settings/billing/utils/isKeyOfRecord';
import { getUsageOperationTypeLabel } from '@/settings/usage/utils/getUsageOperationTypeLabel';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { UsageResourceType } from '~/generated-metadata/graphql';
export const useUsageLimitRows = (
quotas: UsageQuotaWithConsumption[],
@@ -42,6 +43,11 @@ export const useUsageLimitRows = (
const resourceText = t(
USAGE_LIMIT_RESOURCE_TYPE_LABELS[quota.resourceType],
);
+
+ if (quota.resourceType === UsageResourceType.ALL) {
+ return resourceText;
+ }
+
const operationText = isDefined(operationLabel)
? t(operationLabel)
: quota.operationType;
@@ -73,12 +79,11 @@ export const useUsageLimitRows = (
return {
id: quota.id,
name: getName(quota),
- NameIcon: isKeyOfRecord(
- USAGE_LIMIT_OPERATION_TYPE_ICONS,
- quota.operationType,
- )
- ? USAGE_LIMIT_OPERATION_TYPE_ICONS[quota.operationType]
- : IconCoins,
+ NameIcon:
+ quota.resourceType !== UsageResourceType.ALL &&
+ isKeyOfRecord(USAGE_LIMIT_OPERATION_TYPE_ICONS, quota.operationType)
+ ? USAGE_LIMIT_OPERATION_TYPE_ICONS[quota.operationType]
+ : IconCoins,
spenderName: getSpenderName(quota),
spenderAvatarUrl: isDefined(quota.spenderId)
? (avatarUrlBySpenderId.get(quota.spenderId) ?? null)
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
index 0a725676789..ee0956b1d51 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-workflow-step-manifest-to-action-or-throw.util.ts
@@ -43,15 +43,11 @@ export const fromWorkflowStepManifestToActionOrThrow = ({
const { agentUniversalIdentifier, ...rest } = step.input;
input = {
...rest,
- ...(isDefined(agentUniversalIdentifier)
- ? {
- agentId: resolve(
- references.agentIdByUniversalIdentifier,
- agentUniversalIdentifier,
- 'application agent',
- ),
- }
- : {}),
+ agentId: resolve(
+ references.agentIdByUniversalIdentifier,
+ agentUniversalIdentifier,
+ 'application agent',
+ ),
};
break;
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.ts
index aaf64afd850..b50c4c12437 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/compute-workflow-manifest-output-schema.util.spec.ts
@@ -18,7 +18,11 @@ const buildAiAgentStep = (
name: 'Summarize',
type: 'AI_AGENT',
nextStepIds: [],
- input: { prompt: 'Summarize the deal', ...input },
+ input: {
+ agentUniversalIdentifier: AGENT_UNIVERSAL_IDENTIFIER,
+ prompt: 'Summarize the deal',
+ ...input,
+ },
});
const references = {
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
index 1a68b67c7e5..9e8bb053313 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
@@ -29,6 +29,8 @@ import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing
import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
@@ -37,13 +39,12 @@ import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
const APP_BILLING_CHARGE_THROTTLE_LIMIT = 1000;
const APP_BILLING_CHARGE_THROTTLE_TTL_MS = 60_000;
-const CREDIT_UNAVAILABLE_REASON_BY_SERVER_REASON: Record<
- SubscriptionInactiveReason | 'NO_CREDITS',
+const CREDIT_UNAVAILABLE_REASON_BY_SUBSCRIPTION_INACTIVE_REASON: Record<
+ SubscriptionInactiveReason,
CreditUnavailableReason
> = {
WORKSPACE_SUSPENDED: 'workspace-suspended',
NO_SUBSCRIPTION: 'no-subscription',
- NO_CREDITS: 'no-credits',
};
@Controller(`${ApiPath.App}/billing`)
@@ -81,20 +82,30 @@ export class AppBillingController {
APP_BILLING_CHARGE_THROTTLE_TTL_MS,
);
- const creditAvailability =
- await this.usageQuotaAdmissionService.getCreditAvailability(
- request.workspace.id,
- );
+ const usageRefusal = await this.usageQuotaAdmissionService.findUsageRefusal(
+ {
+ workspaceId: request.workspace.id,
+ resourceType: UsageResourceType.APP,
+ operationType: UsageOperationType.ALL,
+ spenders: { applicationId: request.application.id },
+ },
+ );
+
+ if (!isDefined(usageRefusal)) {
+ return { hasAvailableCredits: true };
+ }
+
+ if (usageRefusal.kind === 'subscriptionInactive') {
+ return {
+ hasAvailableCredits: false,
+ reason:
+ CREDIT_UNAVAILABLE_REASON_BY_SUBSCRIPTION_INACTIVE_REASON[
+ usageRefusal.reason
+ ],
+ };
+ }
- return creditAvailability.hasAvailableCredits
- ? { hasAvailableCredits: true }
- : {
- hasAvailableCredits: false,
- reason:
- CREDIT_UNAVAILABLE_REASON_BY_SERVER_REASON[
- creditAvailability.reason
- ],
- };
+ return { hasAvailableCredits: false, reason: 'no-credits' };
}
@Post('charge')
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
index db935ba02f9..2f02a350ec2 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
@@ -4,6 +4,18 @@ import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-res
import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export const USAGE_LIMIT_DEFINITIONS = {
+ [UsageResourceType.ALL]: {
+ quota: {
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.ALL,
+ allowedUnits: [UsageUnit.CREDIT],
+ },
+ ],
+ allowedSpenderTypes: ['application'],
+ defaults: [],
+ },
+ },
[UsageResourceType.API]: {
speed: {
allowedOperations: [
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
index 28ad730081b..6bceffccef8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
@@ -37,6 +37,7 @@ import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-li
import { computeCreditAllowanceMicro } from 'src/engine/core-modules/usage-limit/utils/compute-credit-allowance-micro.util';
import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';
+import { findLimitsForResource } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-resource.util';
import { findSuppressedUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
import { isQuotaLimit } from 'src/engine/core-modules/usage-limit/utils/is-quota-limit.util';
@@ -546,15 +547,6 @@ export class UsageLimitQuotaService {
operationType,
spenders,
}: QuotaConsumeArgs): Promise<LimitQuotaCounter[]> {
- const definition = findUsageLimitDefinition({
- resourceType,
- limitKind: 'quota',
- });
-
- if (!isDefined(definition)) {
- return [];
- }
-
const quotaLimitDefaults = await this.buildQuotaLimitDefaults({
workspaceId,
resourceType,
@@ -694,9 +686,10 @@ export class UsageLimitQuotaService {
['usageLimits'],
);
- const quotaLimits = (usageLimits.byResourceType[resourceType] ?? []).filter(
- isQuotaLimit,
- );
+ const quotaLimits = findLimitsForResource({
+ usageLimits,
+ resourceType,
+ }).filter(isQuotaLimit);
return this.usageLimitEntitlementService.findEnforceableLimits({
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
index 6bd24f291be..6e56c7b2808 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
@@ -123,6 +123,49 @@ describe('buildQuotaCounters', () => {
]);
});
+ it('ranks an every-resource limit after the resource and every-operation ones', () => {
+ const applicationLimit = {
+ spenderType: 'application',
+ spenderId: 'app-1',
+ } as const;
+
+ const counters = buildQuotaCounters({
+ limits: [
+ buildLimit({
+ ...applicationLimit,
+ id: 'every-resource',
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ }),
+ buildLimit({
+ ...applicationLimit,
+ id: 'every-operation',
+ operationType: UsageOperationType.ALL,
+ }),
+ buildLimit({ ...applicationLimit, id: 'chat' }),
+ ],
+ quotaLimitDefaults: [],
+ usageSpenders: { applicationId: 'app-1' },
+ workspaceId: 'workspace-1',
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ periodByUnit: { month: MONTH_PERIOD },
+ });
+
+ expect(
+ counters.map(({ resourceType, operationType }) => [
+ resourceType,
+ operationType,
+ ]),
+ ).toEqual([
+ [UsageResourceType.AI, UsageOperationType.AI_CHAT_TOKEN],
+ [UsageResourceType.AI, UsageOperationType.ALL],
+ [UsageResourceType.ALL, UsageOperationType.ALL],
+ ]);
+ expect(counters[2].key).toContain(
+ ':quota-consumed:ALL:ALL:application:app-1:',
+ );
+ });
+
it('ranks a named user counter before workspace counters', () => {
const counters = buildCounters({
limits: [
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
index 0146373592a..7099af958f4 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
@@ -61,6 +61,38 @@ describe('buildQuotaDebits', () => {
).toEqual([{ counter: creditCounter, amount: 100 }]);
});
+ it('debits an every-resource counter with its spender events from all resources', () => {
+ const applicationId = '20202020-0000-4000-8000-000000000001';
+ const allResourcesCounter: LimitQuotaCounter = {
+ ...buildLimitCounter(UsageUnit.CREDIT),
+ resourceType: UsageResourceType.ALL,
+ spenderType: 'application',
+ spenderId: applicationId,
+ };
+
+ expect(
+ buildQuotaDebits({
+ counters: [allResourcesCounter],
+ events: [
+ { ...logicFunctionEvent, spenders: { applicationId } },
+ { ...workflowEvent, spenders: { applicationId } },
+ {
+ resourceType: UsageResourceType.APP,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro: 5_000,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ spenders: { applicationId },
+ },
+ {
+ ...workflowEvent,
+ spenders: { applicationId: '20202020-0000-4000-8000-000000000002' },
+ },
+ ],
+ }),
+ ).toEqual([{ counter: allResourcesCounter, amount: 5_400 }]);
+ });
+
it('debits the allowance with the credits of every event', () => {
expect(
buildQuotaDebits({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
index 3905ff1a89c..9946134ee13 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
@@ -16,6 +16,7 @@ describe('buildQuotaDefinitions', () => {
limitKind,
]),
).toEqual([
+ [UsageResourceType.ALL, 'quota'],
[UsageResourceType.AI, 'quota'],
[UsageResourceType.WORKFLOW, 'quota'],
[UsageResourceType.LOGIC_FUNCTION, 'quota'],
@@ -24,9 +25,7 @@ describe('buildQuotaDefinitions', () => {
});
it('carries the allow lists a form needs to offer a scope', () => {
- const quota = buildQuotaDefinitions().find(
- (definition) => definition.limitKind === 'quota',
- );
+ const quota = findQuotaDefinition(UsageResourceType.AI);
expect(quota?.allowedOperations.length).toBeGreaterThan(0);
expect(quota?.allowedSpenderTypes).toContain('workspace');
@@ -74,6 +73,18 @@ describe('buildQuotaDefinitions', () => {
).toEqual([]);
});
+ it('offers every resource as one credit scope for an application', () => {
+ const allResources = findQuotaDefinition(UsageResourceType.ALL);
+
+ expect(allResources?.allowedOperations).toEqual([
+ {
+ operationType: UsageOperationType.ALL,
+ allowedUnits: [UsageUnit.CREDIT],
+ },
+ ]);
+ expect(allResources?.allowedSpenderTypes).toEqual(['application']);
+ });
+
it('offers credits and runs on code execution, with no every-operation entry', () => {
expect(
findQuotaDefinition(UsageResourceType.LOGIC_FUNCTION)?.allowedOperations,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
index 9c77200bf31..f7dd1f89a1c 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
@@ -68,6 +68,23 @@ describe('buildQuotaExhaustedScope', () => {
});
});
+ it('names every resource when the exhausted limit spans them all', () => {
+ expect(
+ buildQuotaExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ counter: buildLimitCounter({
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ spenderType: 'application',
+ spenderId: 'application-1',
+ }),
+ }),
+ ).toMatchObject({
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ });
+ });
+
it('marks a scope built from a default counter', () => {
expect(
buildQuotaExhaustedScope({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-resource.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-resource.util.spec.ts
new file mode 100644
index 00000000000..ddd8c868b0a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-resource.util.spec.ts
@@ -0,0 +1,82 @@
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { findLimitsForResource } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-resource.util';
+
+const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+ id: 'limit-id',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.ALL,
+ spenderType: 'application',
+ spenderId: 'application-1',
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ unit: UsageUnit.CREDIT,
+ limitValue: 1_000_000,
+ burstValue: null,
+ isInstanceOverride: false,
+ ...overrides,
+});
+
+describe('findLimitsForResource', () => {
+ const aiLimit = buildLimit({ id: 'ai' });
+ const workflowLimit = buildLimit({
+ id: 'workflow',
+ resourceType: UsageResourceType.WORKFLOW,
+ });
+ const allUsageLimit = buildLimit({
+ id: 'all-usage',
+ resourceType: UsageResourceType.ALL,
+ });
+
+ it('returns the resource limits followed by the all-usage limits', () => {
+ expect(
+ findLimitsForResource({
+ usageLimits: {
+ byResourceType: {
+ [UsageResourceType.AI]: [aiLimit],
+ [UsageResourceType.WORKFLOW]: [workflowLimit],
+ [UsageResourceType.ALL]: [allUsageLimit],
+ },
+ },
+ resourceType: UsageResourceType.AI,
+ }),
+ ).toEqual([aiLimit, allUsageLimit]);
+ });
+
+ it('applies the all-usage limits to a resource with no limit of its own', () => {
+ expect(
+ findLimitsForResource({
+ usageLimits: {
+ byResourceType: { [UsageResourceType.ALL]: [allUsageLimit] },
+ },
+ resourceType: UsageResourceType.APP,
+ }),
+ ).toEqual([allUsageLimit]);
+ });
+
+ it('returns only the resource limits when no all-usage limit exists', () => {
+ expect(
+ findLimitsForResource({
+ usageLimits: {
+ byResourceType: {
+ [UsageResourceType.AI]: [aiLimit],
+ [UsageResourceType.WORKFLOW]: [workflowLimit],
+ },
+ },
+ resourceType: UsageResourceType.WORKFLOW,
+ }),
+ ).toEqual([workflowLimit]);
+ });
+
+ it('returns nothing when neither the resource nor all usage has a limit', () => {
+ expect(
+ findLimitsForResource({
+ usageLimits: { byResourceType: {} },
+ resourceType: UsageResourceType.EMAIL,
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
index 21793e0bf4e..449e91df6e1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
@@ -49,6 +49,14 @@ const validCodeExecutionQuotaLimit: CreateUsageLimitInput = {
operationType: UsageOperationType.CODE_EXECUTION,
};
+const validAllUsageQuotaLimit: CreateUsageLimitInput = {
+ ...validQuotaLimit,
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ spenderType: 'application',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+};
+
const rejects = (input: CreateUsageLimitInput, message?: string) =>
expect(() => validateUsageLimitAgainstDefinition(input)).toThrow(
expect.objectContaining({
@@ -81,6 +89,14 @@ describe('validateUsageLimitAgainstDefinition', () => {
});
});
+ it('accepts a credit quota on every resource for an application', () => {
+ accepts(validAllUsageQuotaLimit);
+ });
+
+ it('accepts a credit quota on every resource for every application', () => {
+ accepts({ ...validAllUsageQuotaLimit, spenderId: null });
+ });
+
it.each([UsageUnit.CREDIT, UsageUnit.INVOCATION])(
'accepts a code execution quota counted in %s',
(unit) => {
@@ -123,6 +139,28 @@ describe('validateUsageLimitAgainstDefinition', () => {
});
});
+ it('rejects a quota on every resource for the workspace, which the credit allowance already caps', () => {
+ rejects(
+ { ...validAllUsageQuotaLimit, spenderType: 'workspace', spenderId: null },
+ 'ALL quota limits cannot be scoped to workspace',
+ );
+ });
+
+ it('rejects a quota on every resource for a member', () => {
+ rejects({ ...validAllUsageQuotaLimit, spenderType: 'userWorkspace' });
+ });
+
+ it('rejects a quota on every resource narrowed to one operation', () => {
+ rejects({
+ ...validAllUsageQuotaLimit,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ });
+ });
+
+ it('rejects a quota on every resource counted in anything but credits', () => {
+ rejects({ ...validAllUsageQuotaLimit, unit: UsageUnit.INVOCATION });
+ });
+
it('rejects a quota on a spender type the resource does not allow', () => {
rejects({ ...validQuotaLimit, spenderType: 'workflow' });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
index acd782ef955..5f8de14ca98 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
@@ -11,12 +11,14 @@ import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-li
import { doesUsageLimitRowSuppressDefault } from 'src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util';
import { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
const counterSpecificity = (counter: LimitQuotaCounter): number =>
- SPENDER_TYPE_SPECIFICITY[counter.spenderType] * 4 +
- (isDefined(counter.spenderId) ? 0 : 2) +
+ SPENDER_TYPE_SPECIFICITY[counter.spenderType] * 8 +
+ (isDefined(counter.spenderId) ? 0 : 4) +
+ (counter.resourceType === UsageResourceType.ALL ? 2 : 0) +
(counter.operationType === UsageOperationType.ALL ? 1 : 0);
export const buildQuotaCounters = ({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
index 19b167d309f..e61413d44b0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
@@ -5,6 +5,7 @@ import {
type QuotaConsumptionScope,
} from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
import { fromRecordUsageInputToUsageConsumptionRow } from 'src/engine/core-modules/usage/utils/from-record-usage-input-to-usage-consumption-row.util';
@@ -29,7 +30,11 @@ export const buildQuotaDebits = ({
counter.kind === 'limit'
? computeQuotaConsumed({
rows: events
- .filter((event) => event.resourceType === counter.resourceType)
+ .filter(
+ (event) =>
+ counter.resourceType === UsageResourceType.ALL ||
+ event.resourceType === counter.resourceType,
+ )
.map(fromRecordUsageInputToUsageConsumptionRow),
scope: counter,
})
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
index 2b07753dc9d..297e0f21ae7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
@@ -14,7 +14,7 @@ export const buildQuotaExhaustedScope = ({
if (counter.kind === 'limit') {
return {
- resourceType,
+ resourceType: counter.resourceType,
limitKind: 'quota',
exhaustedKind: 'limit',
spenderType: counter.spenderType,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-limits-for-resource.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-limits-for-resource.util.ts
new file mode 100644
index 00000000000..cf111c7169a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-limits-for-resource.util.ts
@@ -0,0 +1,14 @@
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.type';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export const findLimitsForResource = ({
+ usageLimits,
+ resourceType,
+}: {
+ usageLimits: UsageLimits;
+ resourceType: UsageResourceType;
+}): FlatUsageLimit[] => [
+ ...(usageLimits.byResourceType[resourceType] ?? []),
+ ...(usageLimits.byResourceType[UsageResourceType.ALL] ?? []),
+];
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts
index e600ddb3058..e141fb6ff50 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-resource-type.enum.ts
@@ -3,6 +3,7 @@
import { registerEnumType } from '@nestjs/graphql';
export enum UsageResourceType {
+ ALL = 'ALL',
AI = 'AI',
WORKFLOW = 'WORKFLOW',
APP = 'APP',
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
index 91b23bd17f2..90d110c3a79 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
@@ -17,6 +17,7 @@ import { type UsageConsumptionTotals } from 'src/engine/core-modules/usage/types
import { type UsagePeriodAnchor } from 'src/engine/core-modules/usage/types/usage-period-anchor.type';
import { buildRecurringChargeKey } from 'src/engine/core-modules/usage/utils/build-recurring-charge-key.util';
import { buildUsagePeriodClause } from 'src/engine/core-modules/usage/utils/build-usage-period-clause.util';
+import { buildUsageResourceTypeFilter } from 'src/engine/core-modules/usage/utils/build-usage-resource-type-filter.util';
import { buildUsageScopeFilter } from 'src/engine/core-modules/usage/utils/build-usage-scope-filter.util';
import { fillUsageTimeSeriesGaps } from 'src/engine/core-modules/usage/utils/fill-usage-time-series-gaps.util';
import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
@@ -88,6 +89,7 @@ export class UsageAnalyticsService {
periodAnchor: UsagePeriodAnchor;
}): Promise<UsageConsumptionRow[]> {
const periodClause = buildUsagePeriodClause(periodAnchor);
+ const resourceTypeFilter = buildUsageResourceTypeFilter(resourceType);
// Grouped again so the shape matches the consumption_by_scope projection, which is picked only on a full key match.
return this.clickHouseService.selectOrThrow<UsageConsumptionRow>(
@@ -97,13 +99,13 @@ export class UsageAnalyticsService {
sum(quantity) AS quantity
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
- AND resourceType = {resourceType:String}
+ ${resourceTypeFilter.clause}
${periodClause}
GROUP BY operationType, unit, userWorkspaceId, apiKeyId, applicationId,
agentId, workflowId, logicFunctionId`,
{
workspaceId,
- resourceType,
+ ...resourceTypeFilter.params,
periodStart: formatDateTimeForClickHouse(periodStart),
periodEnd: formatDateTimeForClickHouse(periodEnd),
},
@@ -131,6 +133,7 @@ export class UsageAnalyticsService {
periodEnd: Date;
periodAnchor: UsagePeriodAnchor;
}): Promise<UsageConsumptionTotals> {
+ const resourceTypeFilter = buildUsageResourceTypeFilter(resourceType);
const scopeFilter = buildUsageScopeFilter({
operationType,
unit,
@@ -144,12 +147,12 @@ export class UsageAnalyticsService {
sum(quantity) AS quantity
FROM usageEvent
WHERE workspaceId = {workspaceId:String}
- AND resourceType = {resourceType:String}
+ ${resourceTypeFilter.clause}
${buildUsagePeriodClause(periodAnchor)}
${scopeFilter.clause}`,
{
workspaceId,
- resourceType,
+ ...resourceTypeFilter.params,
periodStart: formatDateTimeForClickHouse(periodStart),
periodEnd: formatDateTimeForClickHouse(periodEnd),
...scopeFilter.params,
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-resource-type-filter.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-resource-type-filter.util.spec.ts
new file mode 100644
index 00000000000..00ba0579477
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-resource-type-filter.util.spec.ts
@@ -0,0 +1,18 @@
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { buildUsageResourceTypeFilter } from 'src/engine/core-modules/usage/utils/build-usage-resource-type-filter.util';
+
+describe('buildUsageResourceTypeFilter', () => {
+ it('pins the resource when the scope names one', () => {
+ expect(buildUsageResourceTypeFilter(UsageResourceType.AI)).toEqual({
+ clause: 'AND resourceType = {resourceType:String}',
+ params: { resourceType: UsageResourceType.AI },
+ });
+ });
+
+ it('narrows nothing for a scope over every resource', () => {
+ expect(buildUsageResourceTypeFilter(UsageResourceType.ALL)).toEqual({
+ clause: '',
+ params: {},
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-resource-type-filter.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-resource-type-filter.util.ts
new file mode 100644
index 00000000000..b807aefef12
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-resource-type-filter.util.ts
@@ -0,0 +1,12 @@
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { type UsageScopeFilter } from 'src/engine/core-modules/usage/utils/build-usage-scope-filter.util';
+
+export const buildUsageResourceTypeFilter = (
+ resourceType: UsageResourceType,
+): UsageScopeFilter =>
+ resourceType === UsageResourceType.ALL
+ ? { clause: '', params: {} }
+ : {
+ clause: 'AND resourceType = {resourceType:String}',
+ params: { resourceType },
+ };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts
index 15e5992ec86..c56e4019287 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util.ts
@@ -6,7 +6,7 @@ import { isEmailToolName } from 'src/engine/metadata-modules/ai/ai-agent-executi
import { buildEmailProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/build-email-proposal.util';
import { type ProposedToolCallResolution } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/proposed-tool-call-resolution.type';
-// for proposers without registry tools (apps posting to the inbox, workflow steps without an agent):
+// for proposers without registry tools (apps posting to the inbox):
// an email runs only once approved, with the approver's own permissions, so nothing is looked up here
export const resolveEmailToolCallProposal = (
input: ProposeToolCallToolInput,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
index f64d848927a..e5588bf89fa 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/__tests__/agent-runner.service.spec.ts
@@ -18,6 +18,8 @@ const PRIOR_MESSAGES = [{ id: 'message-id', role: 'assistant', parts: [] }];
const MESSAGES = [{ role: 'user' as const, content: 'Draft a quote' }];
+const AGENT = { id: 'agent-id' } as AgentEntity;
+
const buildExecution = (
overrides: Partial<AgentExecutionResult> = {},
): AgentExecutionResult => ({
@@ -57,7 +59,7 @@ const RUN_INPUT: AgentRunnerRunInput = {
ref: { workflowRunId: 'run', stepId: 'step' },
},
spec: {
- agentId: null,
+ agentId: 'agent-id',
title: 'Draft the quote',
baseSystemPrompt: 'base prompt',
instructions: null,
@@ -65,7 +67,7 @@ const RUN_INPUT: AgentRunnerRunInput = {
canAskHumans: false,
},
},
- agent: null,
+ agent: AGENT,
prompt: {
messages: MESSAGES,
senderUserWorkspaceId: 'user-workspace-id',
@@ -141,7 +143,7 @@ const buildService = (execution = buildExecution()) => {
agentRunSuspensionService as never,
{ getHandlerOrThrow: () => callerHandler } as never,
pendingWakeUpService as never,
- {} as never,
+ { findOne: jest.fn().mockResolvedValue(AGENT) } as never,
);
return {
@@ -187,7 +189,7 @@ describe('AgentRunnerService', () => {
workspaceId: 'workspace-id',
threadId: 'thread-id',
title: 'Draft the quote',
- agentId: null,
+ agentId: 'agent-id',
senderUserWorkspaceId: 'user-workspace-id',
senderApplicationId: null,
createdBy: CREATED_BY,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index 7e0b9bc518e..edf8a1854f4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -14,7 +14,6 @@ import {
import { type RunAgentMessage } from 'twenty-shared/application';
import {
ASK_QUESTION_TOOL_NAME,
- AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
type AgentResponseFormat,
type ExtendedUIMessage,
PROPOSE_TOOL_CALL_TOOL_NAME,
@@ -49,13 +48,13 @@ import { getToolMetricName } from 'src/engine/core-modules/tool-provider/utils/g
import { isToolOutputSuccessful } from 'src/engine/core-modules/tool-provider/utils/is-tool-output-successful.util';
import { OUTPUT_NAVIGATION_TOOL_NAMES } from 'src/engine/core-modules/tool/tools/output-navigation-tool/constants/output-navigation-tool-names.constant';
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { OPEN_ENDED_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/open-ended-agent-registry-tool-categories.const';
import { AGENT_RUN_EXCLUDED_TOOL_NAMES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/agent-run-excluded-tool-names.const';
import { PRELOADED_AGENT_REGISTRY_TOOL_CATEGORIES } from 'src/engine/metadata-modules/ai/ai-agent-execution/constants/preloaded-agent-registry-tool-categories.const';
import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type';
import { endsOnPausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/ends-on-pausing-tool-call.util';
-import { resolveEmailToolCallProposal } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-email-tool-call-proposal.util';
import { resolveProposedToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/resolve-proposed-tool-call.util';
import { RunAgentAttachmentService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/run-agent-attachment.service';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
@@ -286,17 +285,11 @@ export class AgentAsyncExecutorService {
};
}
- private buildProposeToolCallTool(
- proposableTools: ProposableTools | undefined,
- ) {
- // an email runs only once approved, with the approver's own permissions
- if (!isDefined(proposableTools)) {
- return createProposeToolCallTool({
- resolveProposal: async (input) => resolveEmailToolCallProposal(input),
- });
- }
-
- const { isToolAllowed, findTool, toolContext } = proposableTools;
+ private buildProposeToolCallTool({
+ isToolAllowed,
+ findTool,
+ toolContext,
+ }: ProposableTools) {
const executeTool: PausingToolCompletionContext['executeTool'] = ({
toolName,
args,
@@ -330,7 +323,7 @@ export class AgentAsyncExecutorService {
canAskHumans = false,
responseFormat,
}: {
- agent: AgentEntity | null;
+ agent: AgentEntity;
responseFormat?: AgentResponseFormat;
messages: RunAgentMessage[];
// a continued conversation, with the tool calls and results plain run messages cannot carry
@@ -352,10 +345,16 @@ export class AgentAsyncExecutorService {
assertAgentResponseFormatHasOutputFieldsOrThrow(responseFormat);
+ const usageSpenders: UsageSpenders = {
+ userWorkspaceId,
+ agentId: agent.id,
+ applicationId: agent.applicationId,
+ };
+
await this.aiBillingService.assertAiExecutionAllowed({
workspaceId,
operationType: usageOperationType,
- spenders: { userWorkspaceId, agentId: agent?.id },
+ spenders: usageSpenders,
});
let accumulatedUsage: LanguageModelUsage = EMPTY_USAGE;
@@ -369,9 +368,7 @@ export class AgentAsyncExecutorService {
id: workspaceId,
});
- if (isDefined(agent)) {
- this.aiModelRegistryService.validateModelAvailability(agent.modelId);
- }
+ this.aiModelRegistryService.validateModelAvailability(agent.modelId);
const registeredModel =
await this.aiModelRegistryService.resolveModelForAgent(
@@ -381,7 +378,6 @@ export class AgentAsyncExecutorService {
resolvedModelId = registeredModel.modelId;
- let tools: ToolSet = {};
let toolCatalogSection = '';
let proposableTools: ProposableTools | undefined;
const providerOptions = getCallLevelProviderOptions({
@@ -390,65 +386,63 @@ export class AgentAsyncExecutorService {
this.aiModelConfigService.getReasoningProviderOptions(
registeredModel,
),
- promptCacheKey: agent?.id,
+ promptCacheKey: agent.id,
});
- if (agent) {
- const agentRoleId = await this.aiAgentRoleService.findAgentRoleId({
- workspaceId: agent.workspaceId,
- agentId: agent.id,
- });
+ const agentRoleId = await this.aiAgentRoleService.findAgentRoleId({
+ workspaceId: agent.workspaceId,
+ agentId: agent.id,
+ });
- const nativeModelToolOptions: NativeModelToolOptions = {
- webSearch: agent.modelConfiguration?.webSearch?.enabled === true,
- twitterSearch:
- agent.modelConfiguration?.twitterSearch?.enabled === true,
- };
+ const nativeModelToolOptions: NativeModelToolOptions = {
+ webSearch: agent.modelConfiguration?.webSearch?.enabled === true,
+ twitterSearch:
+ agent.modelConfiguration?.twitterSearch?.enabled === true,
+ };
- let registryTools: ToolSet = {};
+ let registryTools: ToolSet = {};
- if (isDefined(agentRoleId)) {
- const toolContext: RegistryToolContext = {
- workspaceId: agent.workspaceId,
- agentId: agent.id,
- authContext,
- actorContext,
- ...this.resolveUserIdentity(authContext),
- };
- const registryToolset =
- toolLoadingStrategy === 'lazy'
- ? await this.buildLazyRegistryTools({
+ if (isDefined(agentRoleId)) {
+ const toolContext: RegistryToolContext = {
+ workspaceId: agent.workspaceId,
+ agentId: agent.id,
+ authContext,
+ actorContext,
+ ...this.resolveUserIdentity(authContext),
+ };
+ const registryToolset =
+ toolLoadingStrategy === 'lazy'
+ ? await this.buildLazyRegistryTools({
+ toolContext,
+ agentRoleId,
+ agentRunRoleIds,
+ additionalExcludedToolNames,
+ })
+ : {
+ ...(await this.buildPreloadedRegistryTools({
toolContext,
agentRoleId,
agentRunRoleIds,
additionalExcludedToolNames,
- })
- : {
- ...(await this.buildPreloadedRegistryTools({
- toolContext,
- agentRoleId,
- agentRunRoleIds,
- additionalExcludedToolNames,
- })),
- catalogSection: '',
- };
-
- registryTools = registryToolset.tools;
- toolCatalogSection = registryToolset.catalogSection;
- proposableTools = registryToolset.proposableTools;
- }
-
- const nativeTools = this.aiModelConfigService.getNativeModelTools(
- registeredModel,
- nativeModelToolOptions,
- );
+ })),
+ catalogSection: '',
+ };
- tools = {
- ...registryTools,
- ...nativeTools,
- };
+ registryTools = registryToolset.tools;
+ toolCatalogSection = registryToolset.catalogSection;
+ proposableTools = registryToolset.proposableTools;
}
+ const nativeTools = this.aiModelConfigService.getNativeModelTools(
+ registeredModel,
+ nativeModelToolOptions,
+ );
+
+ const tools: ToolSet = {
+ ...registryTools,
+ ...nativeTools,
+ };
+
this.logger.log(`Generated ${Object.keys(tools).length} tools for agent`);
let hasNoMoreAvailableCredits = false;
@@ -467,7 +461,7 @@ export class AgentAsyncExecutorService {
},
workspaceId,
operationType: usageOperationType,
- spenders: { userWorkspaceId, agentId: agent?.id },
+ spenders: usageSpenders,
});
if (stepHasNoMoreAvailableCredits) {
@@ -500,8 +494,7 @@ export class AgentAsyncExecutorService {
[REQUEST_FORM_TOOL_NAME]: createRequestFormTool(),
}
: {}),
- // an agent proposes its own tools; a step without an agent has none, so it proposes only emails
- ...(canAskHumans && (!isDefined(agent) || isDefined(proposableTools))
+ ...(canAskHumans && isDefined(proposableTools)
? {
[PROPOSE_TOOL_CALL_TOOL_NAME]:
this.buildProposeToolCallTool(proposableTools),
@@ -511,7 +504,7 @@ export class AgentAsyncExecutorService {
const offeredToolNames = Object.keys(offeredPausingTools);
const textResponse = await generateText({
- instructions: `${baseSystemPrompt}\n\n${agent ? tipTapDocumentToMarkdown(agent.prompt) : ''}${toolCatalogSection}`,
+ instructions: `${baseSystemPrompt}\n\n${tipTapDocumentToMarkdown(agent.prompt)}${toolCatalogSection}`,
tools: { ...tools, ...offeredPausingTools },
model: registeredModel.model,
messages: [...priorModelMessages, ...modelMessages],
@@ -527,7 +520,7 @@ export class AgentAsyncExecutorService {
functionId: 'agent-execution',
workspaceId,
userWorkspaceId,
- agentId: agent?.id,
+ agentId: agent.id,
}),
onToolExecutionEnd: (event) => {
this.metricsService.recordHistogram({
@@ -593,8 +586,7 @@ export class AgentAsyncExecutorService {
aiBillingService: this.aiBillingService,
modelId: registeredModel.modelId,
workspaceId,
- userWorkspaceId: userWorkspaceId ?? null,
- agentId: agent?.id ?? null,
+ spenders: usageSpenders,
operationType: usageOperationType,
},
});
@@ -635,13 +627,13 @@ export class AgentAsyncExecutorService {
providerOptions: getCallLevelProviderOptions({
sdkPackage: registeredModel.sdkPackage,
providerOptions: undefined,
- promptCacheKey: agent?.id,
+ promptCacheKey: agent.id,
}),
...buildAiTelemetry({
functionId: 'agent-structured-output',
workspaceId,
userWorkspaceId,
- agentId: agent?.id,
+ agentId: agent.id,
}),
onStepEnd: decrementCreditsForStep,
});
@@ -697,10 +689,7 @@ export class AgentAsyncExecutorService {
AiExceptionCode.AGENT_EXECUTION_FAILED,
);
} finally {
- const modelId =
- resolvedModelId ??
- agent?.modelId ??
- AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID;
+ const modelId = resolvedModelId ?? agent.modelId;
// pricing an unresolved model id would throw over the original error
const costInDollars = isDefined(resolvedModelId)
? this.aiBillingService.calculateStepsCost(
@@ -713,21 +702,20 @@ export class AgentAsyncExecutorService {
(accumulatedUsage.inputTokens ?? 0) +
(accumulatedUsage.outputTokens ?? 0);
- void this.aiBillingService.emitAiTokenUsageEvent(
+ void this.aiBillingService.emitAiTokenUsageEvent({
workspaceId,
creditsUsedMicro,
totalTokens,
modelId,
- usageOperationType,
- agent?.id ?? null,
- userWorkspaceId,
- );
+ operationType: usageOperationType,
+ spenders: usageSpenders,
+ });
- void this.aiBillingService.billNativeWebSearchUsage(
+ void this.aiBillingService.billNativeWebSearchUsage({
nativeWebSearchCallCount,
workspaceId,
- userWorkspaceId,
- );
+ spenders: usageSpenders,
+ });
}
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
index 81e07985c4c..911714d3444 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-runner.service.ts
@@ -141,13 +141,11 @@ export class AgentRunnerService {
outcome: outcome.type === 'ANSWERED' ? { type: 'CANCELLED' } : outcome,
});
- const agent = isDefined(runSpec.agentId)
- ? await this.agentRepository.findOne(workspaceId, {
- where: { id: runSpec.agentId },
- })
- : null;
+ const agent = await this.agentRepository.findOne(workspaceId, {
+ where: { id: runSpec.agentId },
+ });
- if (isDefined(runSpec.agentId) && !isDefined(agent)) {
+ if (!isDefined(agent)) {
throw new AiException(
`Agent with id ${runSpec.agentId} not found`,
AiExceptionCode.AGENT_NOT_FOUND,
@@ -211,7 +209,6 @@ export class AgentRunnerService {
prompt,
executionContext,
} = input;
- const agentId = agent?.id ?? null;
if (!isCreated && !isDefined(suspension)) {
await this.agentRunSuspensionService.assertConversationNotSuspended({
@@ -235,7 +232,7 @@ export class AgentRunnerService {
workspaceId,
threadId,
title: spec.title,
- agentId,
+ agentId: agent.id,
senderUserWorkspaceId: prompt?.senderUserWorkspaceId ?? null,
senderApplicationId: prompt?.senderApplicationId ?? null,
createdBy: executionContext.turnCreatedBy,
@@ -263,7 +260,7 @@ export class AgentRunnerService {
].join('\n\n'),
pausingTools: createAgentWaitTools(),
canAskHumans: spec.capabilities.canAskHumans,
- responseFormat: spec.responseFormat ?? agent?.responseFormat,
+ responseFormat: spec.responseFormat ?? agent.responseFormat,
workspaceId,
executionContext,
additionalExcludedToolNames: spec.additionalExcludedToolNames,
@@ -297,7 +294,7 @@ export class AgentRunnerService {
threadId,
turnId,
title: spec.title,
- agentId,
+ agentId: agent.id,
execution,
}),
)
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts
index e53a2892da0..215b9388144 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-run-spec.type.ts
@@ -5,8 +5,7 @@ import { type AgentToolLoadingStrategy } from 'src/engine/metadata-modules/ai/ai
// What a suspended run needs to continue without its caller building it again.
// Permissions are left out: the caller derives them anew on each continuation
export type AgentRunSpec = {
- // without an agent, the run uses the workspace's default model
- agentId: string | null;
+ agentId: string;
title: string;
baseSystemPrompt: string;
// the caller's own instructions, after what the engine says about its pausing tools
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
index 8387acfc437..185d096e607 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/types/agent-runner-run-input.type.ts
@@ -13,7 +13,7 @@ export type AgentRunnerRunInput = {
conversation: AgentRunConversation;
caller: AgentRunCaller;
spec: AgentRunSpec;
- agent: AgentEntity | null;
+ agent: AgentEntity;
// what the run is asked and who asked it; absent when the run continues its conversation without a new message
prompt: {
messages: RunAgentMessage[];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/repair-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/repair-tool-call.util.ts
index 109501c368d..f828be99f1f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/repair-tool-call.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent/utils/repair-tool-call.util.ts
@@ -13,6 +13,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type z } from 'zod';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';
import { extractCacheCreationTokensFromSteps } from 'src/engine/metadata-modules/ai/ai-billing/utils/extract-cache-creation-tokens.util';
import { buildAiTelemetry } from 'src/engine/metadata-modules/ai/ai-models/utils/build-ai-telemetry.util';
@@ -30,8 +31,7 @@ type RepairToolCallBillingContext = {
aiBillingService: AiBillingService;
modelId: string;
workspaceId: string;
- userWorkspaceId: string | null;
- agentId: string | null;
+ spenders: UsageSpenders;
operationType: UsageOperationType;
};
@@ -91,7 +91,7 @@ export const repairToolCall = async ({
...buildAiTelemetry({
functionId: 'repair-tool-call',
workspaceId: billingContext.workspaceId,
- userWorkspaceId: billingContext.userWorkspaceId,
+ userWorkspaceId: billingContext.spenders.userWorkspaceId,
}),
});
@@ -119,14 +119,13 @@ export const repairToolCall = async ({
: 0;
void billingContext.aiBillingService
- .calculateAndBillUsage(
- billingContext.modelId,
- { usage, cacheCreationTokens },
- billingContext.workspaceId,
- billingContext.operationType,
- billingContext.agentId,
- billingContext.userWorkspaceId,
- )
+ .calculateAndBillUsage({
+ modelId: billingContext.modelId,
+ billingInput: { usage, cacheCreationTokens },
+ workspaceId: billingContext.workspaceId,
+ operationType: billingContext.operationType,
+ spenders: billingContext.spenders,
+ })
.catch((error: unknown) =>
logger.error(
`Could not bill the repair of tool call ${toolCall.toolCallId} in workspace ${billingContext.workspaceId}`,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
index 1843add7130..5069a6d63b7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
@@ -108,14 +108,19 @@ export class AiBillingService {
return breakdown.totalCostInDollars;
}
- async calculateAndBillUsage(
- modelId: ModelId,
- billingInput: BillingUsageInput,
- workspaceId: string,
- operationType: UsageOperationType,
- agentId?: string | null,
- userWorkspaceId?: string | null,
- ): Promise<void> {
+ async calculateAndBillUsage({
+ modelId,
+ billingInput,
+ workspaceId,
+ operationType,
+ spenders,
+ }: {
+ modelId: ModelId;
+ billingInput: BillingUsageInput;
+ workspaceId: string;
+ operationType: UsageOperationType;
+ spenders: UsageSpenders;
+ }): Promise<void> {
const costInDollars = this.calculateCost(modelId, billingInput);
const creditsUsedMicro = convertDollarsToCreditsMicro(costInDollars);
@@ -131,7 +136,7 @@ export class AiBillingService {
totalTokens,
modelId,
operationType,
- spenders: { userWorkspaceId, agentId },
+ spenders,
}),
],
});
@@ -172,11 +177,15 @@ export class AiBillingService {
return { hasNoMoreAvailableCredits: exhaustedKind === 'allowance' };
}
- async billNativeWebSearchUsage(
- nativeWebSearchCallCount: number,
- workspaceId: string,
- userWorkspaceId?: string | null,
- ): Promise<void> {
+ async billNativeWebSearchUsage({
+ nativeWebSearchCallCount,
+ workspaceId,
+ spenders,
+ }: {
+ nativeWebSearchCallCount: number;
+ workspaceId: string;
+ spenders: UsageSpenders;
+ }): Promise<void> {
if (nativeWebSearchCallCount <= 0) {
return;
}
@@ -198,28 +207,34 @@ export class AiBillingService {
creditsUsedMicro,
quantity: nativeWebSearchCallCount,
unit: UsageUnit.INVOCATION,
- spenders: { userWorkspaceId },
+ spenders,
},
],
});
}
- async emitAiTokenUsageEvent(
- workspaceId: string,
- creditsUsedMicro: number,
- totalTokens: number,
- modelId: ModelId,
- operationType: UsageOperationType,
- agentId?: string | null,
- userWorkspaceId?: string | null,
- ): Promise<void> {
+ async emitAiTokenUsageEvent({
+ workspaceId,
+ creditsUsedMicro,
+ totalTokens,
+ modelId,
+ operationType,
+ spenders,
+ }: {
+ workspaceId: string;
+ creditsUsedMicro: number;
+ totalTokens: number;
+ modelId: ModelId;
+ operationType: UsageOperationType;
+ spenders: UsageSpenders;
+ }): Promise<void> {
await this.usageRecorderService.record(workspaceId, [
this.buildAiTokenUsageEvent({
creditsUsedMicro,
totalTokens,
modelId,
operationType,
- spenders: { userWorkspaceId, agentId },
+ spenders,
}),
]);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.ts
index b53be0f2018..cd2dde2d213 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.ts
@@ -72,14 +72,13 @@ export class AgentTitleGenerationService {
? extractCacheCreationTokensFromSteps(steps)
: 0;
- void this.aiBillingService.calculateAndBillUsage(
- defaultModel.modelId,
- { usage, cacheCreationTokens },
+ void this.aiBillingService.calculateAndBillUsage({
+ modelId: defaultModel.modelId,
+ billingInput: { usage, cacheCreationTokens },
workspaceId,
- UsageOperationType.AI_CHAT_TOKEN,
- null,
- userWorkspaceId,
- );
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenders: { userWorkspaceId },
+ });
}
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
index 1e3cfb7e811..51e90c4735d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
@@ -484,21 +484,20 @@ export class ChatExecutionService {
);
const creditsUsedMicro = convertDollarsToCreditsMicro(costInDollars);
- await this.aiBillingService.emitAiTokenUsageEvent(
- workspace.id,
+ await this.aiBillingService.emitAiTokenUsageEvent({
+ workspaceId: workspace.id,
creditsUsedMicro,
totalTokens,
- registeredModel.modelId,
- UsageOperationType.AI_CHAT_TOKEN,
- null,
- userWorkspaceId,
- );
+ modelId: registeredModel.modelId,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenders: { userWorkspaceId },
+ });
- void this.aiBillingService.billNativeWebSearchUsage(
- countNativeWebSearchCallsFromSteps(steps),
- workspace.id,
- userWorkspaceId,
- );
+ void this.aiBillingService.billNativeWebSearchUsage({
+ nativeWebSearchCallCount: countNativeWebSearchCallsFromSteps(steps),
+ workspaceId: workspace.id,
+ spenders: { userWorkspaceId },
+ });
const modelAttr = { model: registeredModel.modelId };
@@ -698,8 +697,7 @@ export class ChatExecutionService {
aiBillingService: this.aiBillingService,
modelId: registeredModel.modelId,
workspaceId: workspace.id,
- userWorkspaceId,
- agentId: null,
+ spenders: { userWorkspaceId },
operationType: UsageOperationType.AI_CHAT_TOKEN,
},
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/ai-evaluation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/ai-evaluation.service.ts
index d0d537b244b..49e5004a27a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/ai-evaluation.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-evaluation/services/ai-evaluation.service.ts
@@ -58,14 +58,13 @@ export class AiEvaluationService {
abortSignal,
});
- await this.aiBillingService.calculateAndBillUsage(
+ await this.aiBillingService.calculateAndBillUsage({
modelId,
- { usage },
+ billingInput: { usage },
workspaceId,
- UsageOperationType.AI_WORKFLOW_TOKEN,
- null,
- userWorkspaceId,
- );
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ spenders: { userWorkspaceId },
+ });
return { modelId, answers, usage };
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.ts
index a05d21e629a..8d018972445 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.ts
@@ -6,7 +6,9 @@ import { ApiPath } from 'twenty-shared/types';
import { RestApiExceptionFilter } from 'src/engine/api/rest/rest-api-exception.filter';
import { UsageLimitRestApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-rest-api-exception.filter';
+import { getWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { buildUsageSpendersFromAuthContext } from 'src/engine/core-modules/usage/utils/build-usage-spenders-from-auth-context.util';
import type { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
@@ -65,6 +67,10 @@ export class AiGenerateTextController {
@AuthWorkspace() workspace: WorkspaceEntity,
@AuthUserWorkspaceId() userWorkspaceId: string,
) {
+ const usageSpenders = buildUsageSpendersFromAuthContext(
+ getWorkspaceAuthContext(),
+ );
+
if (this.aiModelRegistryService.getAvailableModels().length === 0) {
throw new AiException(
'No AI models are available. Please configure at least one AI provider API key.',
@@ -75,7 +81,7 @@ export class AiGenerateTextController {
await this.aiBillingService.assertAiExecutionAllowed({
workspaceId: workspace.id,
operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
- spenders: { userWorkspaceId },
+ spenders: usageSpenders,
});
const resolvedModelId = body.modelId ?? AUTO_SELECT_MODEL_ID_BY_TIER.fast;
@@ -114,18 +120,17 @@ export class AiGenerateTextController {
};
} finally {
if (result) {
- void this.aiBillingService.calculateAndBillUsage(
- registeredModel.modelId,
- {
+ void this.aiBillingService.calculateAndBillUsage({
+ modelId: registeredModel.modelId,
+ billingInput: {
usage: result.usage,
cacheCreationTokens:
result.usage.inputTokenDetails?.cacheWriteTokens ?? 0,
},
- workspace.id,
- UsageOperationType.AI_WORKFLOW_TOKEN,
- null,
- userWorkspaceId,
- );
+ workspaceId: workspace.id,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ spenders: usageSpenders,
+ });
}
}
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
index f7d7e46023d..eae9e5f5ca4 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-pending-input.workspace-service.ts
@@ -1,6 +1,9 @@
import { Injectable } from '@nestjs/common';
-import { type AskQuestionItem } from 'twenty-shared/ai';
+import {
+ AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
+ type AskQuestionItem,
+} from 'twenty-shared/ai';
import { FieldActorSource } from 'twenty-shared/types';
import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';
import { v5 } from 'uuid';
@@ -12,6 +15,7 @@ import {
import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
import { AgentRunConversationService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-conversation.service';
import { AgentRunSuspensionService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-run-suspension.service';
+import { AgentService } from 'src/engine/metadata-modules/ai/ai-agent/agent.service';
import {
AiException,
AiExceptionCode,
@@ -159,6 +163,7 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,
private readonly agentRunConversationService: AgentRunConversationService,
private readonly agentRunSuspensionService: AgentRunSuspensionService,
+ private readonly agentService: AgentService,
@InjectWorkspaceScopedRepository(WorkflowEntity)
private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,
@InjectWorkspaceScopedRepository(WorkflowVersionEntity)
@@ -173,13 +178,28 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
applicationId: string;
}): Promise<void> {
for (const agentWorkflow of AGENT_WORKFLOWS_TO_SEED) {
+ const stepId = seedId(agentWorkflow.stepKey, workspaceId);
+ const agent = await this.agentService.createOneAgent(
+ {
+ label: 'Workflow Agent ' + stepId.substring(0, 4),
+ icon: 'IconLego',
+ description: '',
+ prompt:
+ 'You are a helpful AI assistant. Complete the task based on the workflow context.',
+ modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,
+ responseFormat: { type: 'text' },
+ isSystem: true,
+ },
+ workspaceId,
+ );
const step: WorkflowAiAgentAction = {
- id: seedId(agentWorkflow.stepKey, workspaceId),
+ id: stepId,
name: agentWorkflow.stepName,
type: WorkflowActionType.AI_AGENT,
valid: true,
settings: {
input: {
+ agentId: agent.id,
prompt: agentWorkflow.stepPrompt,
humanInputInstructions: agentWorkflow.humanInputInstructions,
},
@@ -260,7 +280,7 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
workspaceId,
threadId,
title: workflow.step.name,
- agentId: null,
+ agentId: agent.id,
senderUserWorkspaceId: null,
senderApplicationId: null,
messages: [{ role: 'user', content: agentWorkflow.runPrompt }],
@@ -294,7 +314,7 @@ export class DevSeederWorkflowPendingInputWorkspaceService {
threadId,
turnId,
title: workflow.step.name,
- agentId: null,
+ agentId: agent.id,
execution: {
isPaused: true,
steps: [{ content }],
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
index e55ca9ed43c..f6a388730d4 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
@@ -1,4 +1,5 @@
import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
+import { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.module';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@@ -45,6 +46,7 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
imports: [
AgentHistoryModule,
AiAgentExecutionModule,
+ AiAgentModule,
TimelineActivityModule,
ObjectMetadataModule,
FieldMetadataModule,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index d7c2e004d49..f441a6e5319 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -87,15 +87,11 @@ export class AiAgentWorkflowAction implements WorkflowAction {
);
}
- let agent: AgentEntity | null = null;
-
- if (agentId) {
- agent = await this.agentRepository.findOne(workspaceId, {
- where: { id: agentId },
- });
- }
+ const agent = await this.agentRepository.findOne(workspaceId, {
+ where: { id: agentId },
+ });
- if (agentId && !agent) {
+ if (!isDefined(agent)) {
throw new WorkflowStepExecutorException(
`Agent with id ${agentId} not found`,
WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
@@ -107,15 +103,13 @@ export class AiAgentWorkflowAction implements WorkflowAction {
const { application } = executionContext;
- if (isDefined(agent)) {
- this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(
- {
- application,
- targetApplicationId: agent.applicationId,
- targetLabel: `Agent "${agent.name}"`,
- },
- );
- }
+ this.workflowExecutionContextService.assertStepTargetBelongsToRunApplicationOrThrow(
+ {
+ application,
+ targetApplicationId: agent.applicationId,
+ targetLabel: `Agent "${agent.name}"`,
+ },
+ );
const conversation =
await this.workflowAgentConversationService.openConversation({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
index 0d172dded53..d34516fd3a7 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/types/workflow-ai-agent-action-input.type.ts
@@ -2,7 +2,7 @@ import { type AgentResponseFormat } from 'twenty-shared/ai';
import { type WorkflowConversation } from 'twenty-shared/workflow';
export type WorkflowAiAgentActionInput = {
- agentId?: string;
+ agentId: string;
prompt?: string;
responseFormat?: AgentResponseFormat;
humanInputInstructions?: string;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts
index 4ad2597ae21..2936993936e 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/__tests__/build-workflow-agent-run-spec.util.spec.ts
@@ -26,6 +26,7 @@ describe('buildWorkflowAgentRunSpec', () => {
it('keeps the agent from asking without human input instructions', () => {
const spec = buildWorkflowAgentRunSpec({
step: buildStep({
+ agentId: 'agent-id',
prompt: 'Draft the quote',
humanInputInstructions: ' ',
}),
@@ -33,7 +34,7 @@ describe('buildWorkflowAgentRunSpec', () => {
});
expect(spec).toMatchObject({
- agentId: null,
+ agentId: 'agent-id',
title: 'Draft the quote',
instructions: null,
capabilities: {
@@ -62,7 +63,7 @@ describe('buildWorkflowAgentRunSpec', () => {
it('keeps tools out of reach of an application-bound run', () => {
expect(
buildWorkflowAgentRunSpec({
- step: buildStep({ prompt: 'Draft the quote' }),
+ step: buildStep({ agentId: 'agent-id', prompt: 'Draft the quote' }),
isApplicationBound: true,
}).additionalExcludedToolNames,
).toContain('send_email');
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
index badf3eda7c8..8a3d9aa05ee 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-workflow-agent-run-spec.util.ts
@@ -21,7 +21,7 @@ export const buildWorkflowAgentRunSpec = ({
const canAskHumans = isNonEmptyString(trimmedHumanInputInstructions);
return {
- agentId: isNonEmptyString(agentId) ? agentId : null,
+ agentId,
title: step.name,
baseSystemPrompt: WORKFLOW_BASE_SYSTEM_PROMPT,
instructions: canAskHumans
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
index d6dd9e99e9d..fce5ecb730f 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
@@ -27,6 +27,7 @@ import { type CacheStorageService } from 'src/engine/core-modules/cache-storage/
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { TEST_AI_MODEL_ID } from 'test/integration/constants/test-ai-model-ids.constants';
import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';
import {
activateCoreWorkflowVersion,
@@ -40,6 +41,8 @@ import {
} from 'test/integration/graphql/suites/workflow/utils/core-workflow.util';
import { submitFormStep } from 'test/integration/graphql/suites/workflow/utils/submit-form-step.util';
import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';
+import { createOneAgent } from 'test/integration/metadata/suites/agent/utils/create-one-agent.util';
+import { deleteOneAgent } from 'test/integration/metadata/suites/agent/utils/delete-one-agent.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
@@ -980,6 +983,25 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
});
describe('an agent step that asks a question', () => {
+ let agentId: string;
+
+ beforeAll(async () => {
+ const { data } = await createOneAgent({
+ expectToFail: false,
+ input: {
+ label: 'Quote Agent',
+ prompt: 'Draft the quote',
+ modelId: TEST_AI_MODEL_ID,
+ },
+ });
+
+ agentId = data.createOneAgent.id;
+ });
+
+ afterAll(async () => {
+ await deleteOneAgent({ expectToFail: false, input: { id: agentId } });
+ });
+
const QUESTION = {
header: 'Quote',
question: 'Send the quote to the customer?',
@@ -995,6 +1017,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
settings: {
...settings,
input: {
+ agentId,
prompt: 'Draft the quote',
humanInputInstructions: 'Ask before choosing a plan.',
workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
diff --git a/packages/twenty-server/test/integration/usage-limit/app-credit-availability.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/app-credit-availability.integration-spec.ts
new file mode 100644
index 00000000000..04beed28f79
--- /dev/null
+++ b/packages/twenty-server/test/integration/usage-limit/app-credit-availability.integration-spec.ts
@@ -0,0 +1,101 @@
+import { findManyApplications } from 'test/integration/graphql/utils/find-many-applications.util';
+import {
+ APPLICATION_ONLY_REST_REQUEST_FACTORIES,
+ makeApplicationOnlyRestRequest,
+} from 'test/integration/metadata/suites/application/utils/application-only-endpoint-request-factories.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
+import { type UsageLimitService } from 'src/engine/core-modules/usage-limit/services/usage-limit.service';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { TWENTY_STANDARD_APPLICATION } from 'src/engine/workspace-manager/twenty-standard-application/constants/twenty-standard-applications';
+
+const CREDIT_LIMIT_MICRO = 1_000;
+
+describe('App credit availability', () => {
+ let applicationId: string;
+ let applicationToken: string;
+
+ beforeAll(async () => {
+ const { data } = await findManyApplications({ expectToFail: false });
+
+ const standardApplication = data.findManyApplications.find(
+ (application) =>
+ application.universalIdentifier ===
+ TWENTY_STANDARD_APPLICATION.universalIdentifier,
+ );
+
+ if (!isDefined(standardApplication)) {
+ throw new Error('The standard application is not installed');
+ }
+
+ applicationId = standardApplication.id;
+
+ const tokenPair = await generateAppleAdminApplicationTokenPair({
+ applicationId,
+ });
+
+ applicationToken = tokenPair.applicationAccessToken.token;
+ });
+
+ it('refuses credits once an all-usage limit on the application is exhausted', async () => {
+ const usageLimitService =
+ getAppProviderByClassName<UsageLimitService>('UsageLimitService');
+
+ const usageLimit = await usageLimitService.create({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ input: {
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ spenderType: 'application',
+ spenderId: applicationId,
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ unit: UsageUnit.CREDIT,
+ limitValue: CREDIT_LIMIT_MICRO,
+ burstValue: null,
+ },
+ isOperator: true,
+ });
+
+ try {
+ await getAppProviderByClassName<UsageLimitQuotaService>(
+ 'UsageLimitQuotaService',
+ ).debitAheadOfRecord({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ event: {
+ resourceType: UsageResourceType.APP,
+ operationType: UsageOperationType.CALL_RECORDING,
+ creditsUsedMicro: CREDIT_LIMIT_MICRO,
+ quantity: 1,
+ unit: UsageUnit.MINUTE,
+ resourceId: applicationId,
+ spenders: { applicationId },
+ },
+ });
+
+ const response = await makeApplicationOnlyRestRequest(
+ APPLICATION_ONLY_REST_REQUEST_FACTORIES['GET /app/billing/credits'](),
+ applicationToken,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({
+ hasAvailableCredits: false,
+ reason: 'no-credits',
+ });
+ } finally {
+ await usageLimitService.delete({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ usageLimitId: usageLimit.id,
+ isOperator: true,
+ });
+ }
+ });
+});
diff --git a/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
index af4da5d5068..2f0d7e07041 100644
--- a/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
+++ b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
@@ -176,6 +176,17 @@ describe('Usage limit mutations', () => {
'EMAIL EMAIL_SEND quota limits cannot count MILLISECOND, only CREDIT, INVOCATION',
);
});
+
+ it('refuses a quota over all usage for the workspace', async () => {
+ const response = await createUsageLimitRequest({
+ resourceType: UsageResourceType.ALL,
+ operationType: UsageOperationType.ALL,
+ });
+
+ expect(response.body.errors?.[0]?.message).toBe(
+ 'ALL quota limits cannot be scoped to workspace',
+ );
+ });
});
describe('updateUsageLimit', () => {
diff --git a/packages/twenty-shared/src/application/workflowStepManifestType.ts b/packages/twenty-shared/src/application/workflowStepManifestType.ts
index 88dac2a3cdf..644b57f2397 100644
--- a/packages/twenty-shared/src/application/workflowStepManifestType.ts
+++ b/packages/twenty-shared/src/application/workflowStepManifestType.ts
@@ -189,7 +189,7 @@ export const workflowStepManifestSchema = z.discriminatedUnion('type', [
stepSchema(
'AI_AGENT',
z.strictObject({
- agentUniversalIdentifier: z.uuid().optional(),
+ agentUniversalIdentifier: z.uuid(),
prompt: z.string(),
responseFormat: agentResponseFormatSchema.optional(),
}),
diff --git a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
index c45072aaecb..ed4cdcb31ac 100644
--- a/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/ai-agent-action-settings-schema.ts
@@ -7,7 +7,7 @@ import { workflowConversationSchema } from './workflow-conversation-schema';
export const workflowAiAgentActionSettingsSchema =
baseWorkflowActionSettingsSchema.extend({
input: z.object({
- agentId: z.string().optional(),
+ agentId: z.string(),
prompt: z.string().optional(),
responseFormat: agentResponseFormatSchema.optional(),
// Empty by default: stopping for a person pauses the run, which existing workflows were not built to expect.