AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
chore(chat): remove the old chat beta rollout (#16574)
Hazem Adelbd65eeff443f
diff --git a/brain/knowledge/ai-intelligence/ai-mcp.md b/brain/knowledge/ai-intelligence/ai-mcp.mdindex 2295277a6b8..21e22c640a6 100644--- a/brain/knowledge/ai-intelligence/ai-mcp.md+++ b/brain/knowledge/ai-intelligence/ai-mcp.md@@ -27,8 +27,8 @@ Platform admins configure LLM backends for AI pieces; auto-provisions an "ActivePlatform-level AI assistant that manages projects via natural language, streaming over WebSocket and using the project's MCP server as its tool surface.- **Execution model (key gotcha)**: the LLM loop runs in the **worker**, not the API. Controller enqueues `WorkerJobType.EXECUTE_AGENT_RUN` → worker `execute-agent-run.ts` → `run-agent-turn.ts` runs `streamText()` → chunks stream back via RPC → `CHAT_MESSAGE_CHUNK` websocket (filtered by `runId`). `agent-conversation-service.ts` only does conversation CRUD.-- **Entities**: `AgentConversation` (table `agent_conversation`, per platform+user, optional project scope, messages as JSONB `ModelMessage[]`, compaction summary). `chat_rollout_user` tracks the cloud beta cohort (capped at 200 distinct users who sent a message).-- **Integration/gotchas**: EE/Cloud only (needs `chatEnabled`, or cloud rollout/grandfather); refuses PGLite dev DB — needs Postgres + Redis. Two-phase (discovery/build) tool gating; Redis pub/sub approval gates for display cards + write-action previews; MCP tools no longer gated (just timeout-wrapped). Server-managed connections — LLM never sees credential externalIds. Web search rides the configured LLM credential (no second BYOK).+- **Entities**: `AgentConversation` (table `agent_conversation`, per platform+user, optional project scope, messages as JSONB `ModelMessage[]`, compaction summary).+- **Integration/gotchas**: EE/Cloud only (needs `chatEnabled`); refuses PGLite dev DB — needs Postgres + Redis. Two-phase (discovery/build) tool gating; Redis pub/sub approval gates for display cards + write-action previews; MCP tools no longer gated (just timeout-wrapped). Server-managed connections — LLM never sees credential externalIds. Web search rides the configured LLM credential (no second BYOK).### Knowledge Basediff --git a/brain/knowledge/decisions/000030-chat-onboarding-asks-only-users-with-no-row-and-backfills-everyone-else.md b/brain/knowledge/decisions/000030-chat-onboarding-asks-only-users-with-no-row-and-backfills-everyone-else.mdindex 1701e29f658..836816cf968 100644--- a/brain/knowledge/decisions/000030-chat-onboarding-asks-only-users-with-no-row-and-backfills-everyone-else.md+++ b/brain/knowledge/decisions/000030-chat-onboarding-asks-only-users-with-no-row-and-backfills-everyone-else.md@@ -8,7 +8,7 @@ status: acceptedThe first-run onboarding card ("Who am I teaming up with?") renders when the caller has **no `chat_personalization` row at all**, a state the service synthesizes as `UNSET` and never persists. To keep that from firing for the entire existing user base on ship day, the shipping migration **backfills one terminal row per existing user** rather than gating the card on a hardcoded ship date.## Context-The card's gate is `isEmpty && !incognito && (isFirstRun || promptOpen)`, where `isFirstRun` is `status === UNSET`. `UNSET` means "no row exists", not "new account", so on first deploy every user who had never answered would have met it, including the grandfathered cloud users from the 200-user chat rollout cap. Those people have been chatting for months and would have opened a normal new chat to find a new-user welcome takeover where their greeting used to be.+The card's gate is `isEmpty && !incognito && (isFirstRun || promptOpen)`, where `isFirstRun` is `status === UNSET`. `UNSET` means "no row exists", not "new account", so on first deploy every user who had never answered would have met it, including users who have been chatting since the beta. Those people have been chatting for months and would have opened a normal new chat to find a new-user welcome takeover where their greeting used to be.The obvious fix is `user.created > SHIP_DATE`. It works, and it leaves a date constant in the code that nobody ever deletes and no one dares change.diff --git a/brain/knowledge/decisions/000045-chat-uses-an-orchestrator-with-stateless-single-writer-sub-agents.md b/brain/knowledge/decisions/000045-chat-uses-an-orchestrator-with-stateless-single-writer-sub-agents.mdindex 4ae4382620b..3dc226fd9fa 100644--- a/brain/knowledge/decisions/000045-chat-uses-an-orchestrator-with-stateless-single-writer-sub-agents.md+++ b/brain/knowledge/decisions/000045-chat-uses-an-orchestrator-with-stateless-single-writer-sub-agents.md@@ -19,4 +19,4 @@ Small contexts on cheaper tiers cost far less than trimming one big agent. We av## Consequences-The design binds to tiers, never to model names. The tier file gets a per-provider id map, because `nativeModelId` is Anthropic-only and OpenAI, Google, Azure and Bedrock otherwise resolve `fast` and `smart` to the same model. A provider missing from the map runs children on the orchestrator's model; the smaller context still carries most of the saving. On own-key providers, child tool calls must be persisted into the turn (tagged `delegationId`) and the child must get the outer turn's `creditsLeft`, or per-turn billing and the mid-turn credit check would miss them. Managed bills each child model call at cost through `billedLanguageModel` with no change. Only the orchestrator renders `ap_show_*` widgets. Rollout is per conversation through `getAgentConfig` (`single | subagents`), A/B tested on cloud free first. The gate is cost per message, cost per completed eval scenario, and the share of free users who reach a first flow within budget.+The design binds to tiers, never to model names. The tier file gets a per-provider id map, because `nativeModelId` is Anthropic-only and OpenAI, Google, Azure and Bedrock otherwise resolve `fast` and `smart` to the same model. A provider missing from the map runs children on the orchestrator's model; the smaller context still carries most of the saving. On own-key providers, child tool calls must be persisted into the turn (tagged `delegationId`) and the child must get the outer turn's `creditsLeft`, or per-turn billing and the mid-turn credit check would miss them. Managed bills each child model call at cost through `billedLanguageModel` with no change. Only the orchestrator renders `ap_show_*` widgets. The gate is cost per message, cost per completed eval scenario, and the share of free users who reach a first flow within budget.diff --git a/brain/knowledge/flows-execution/chat-activation-metric.md b/brain/knowledge/flows-execution/chat-activation-metric.mdindex d88b2e95a1a..ed57b0d3e57 100644--- a/brain/knowledge/flows-execution/chat-activation-metric.md+++ b/brain/knowledge/flows-execution/chat-activation-metric.md@@ -132,6 +132,6 @@ S3 counts a flow that was built in the window and later deleted. On 2026-09-29,- **Read `uiMessages`, not `messages`.** `messages` is the model context and compaction rewrites it; `uiMessages` is the durable transcript, and it is the only one holding `ap_build_flow` results with the flowId.- **Publish state is today's, not day 7's.** `flow.status` and `publishedVersionId` are current values, so a flow that was published and later turned off drops out of S4. Runs are windowed correctly.-- **The cohort anchor is the first CHAT message.** `chat_rollout_user` was never the anchor and stopped being written on 1 Oct 2026.+- **The cohort anchor is the first CHAT message.**- **Cohorts before and after 1 Oct 2026 are different populations.** Until then Cloud chat was capped at 200 users plus platforms whose plan had `chatEnabled`; from 1 Oct it is open to every Cloud user. Compare cohorts by first-chat date, and don't read the 2.9% baseline as what an open cohort should match.- **Small cohorts swing.** In the capped cohorts one user moved a stage by several points, so read the counts next to the percentages.diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.mdindex 9984e53c695..8a68aeca0f4 100644--- a/brain/knowledge/flows-execution/chat.md+++ b/brain/knowledge/flows-execution/chat.md@@ -12,7 +12,6 @@ The chat LLM loop runs in the **worker**, not the API. Send path: `agent-convers### Entities & services- **ChatPersonalization** (`chat_personalization`) — first-run onboarding: role + company, background research, researched empty-state cards. See [chat personalization](./chat-personalization.md).- **AgentConversation** (`agent_conversation`) — per-user, per-platform, optionally per-project; `status` STREAMING/IDLE/ERROR, `activeRunId`, `messages` (ModelMessage[] JSONB), `uiMessages`, `summary`/`summarizedUpToIndex` for compaction.-- **ChatRolloutUser** (`chat_rollout_user`) — the 200-user beta's per-user record of first landing and first chat. Nothing reads or writes it since chat went public on 1 Oct 2026; the entity stays registered only until a follow-up migration drops the table, so a rolling deploy never sees old pods writing to a table the new one dropped.- **UserMemory** (`user_memory`) — one row per (platformId, userId): `instructions` (nullable text) + `memories` (jsonb string[]); capped at 50 facts × 280 chars and 4000 chars of instructions (`agentHelpers.capMemories`).- Tool logic in `ee/agent/`; shared tool phase/classification in `core/shared/.../ee/agent/`.@@ -46,7 +45,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **Server-managed connections**: the LLM never sees connection externalIds; `ap_execute_action` auto-fills them from a Redis store.- **Prompt-injection taint**: a per-turn `taintState` flips to `tainted` once the turn reads outside or user data (MCP tools, web/search/scrape, `ap_explore_data`, `ap_execute_action`, `ap_run_code`, `ap_list_across_projects`, configured tools). It forces the action-preview gate on non-read-only actions, makes saved-agent edits (`ap_update_agent`, `ap_add_agent_tool`, `ap_remove_agent_tool`, `ap_create_agent`) ask for approval on the action card instead of refusing, and makes `ap_remember` ask before saving (memory reaches every future conversation). It carries one message: each saved reply stores `tainted` (this reply's own reads, via `createTaintState`), and the next message starts from it. Deletes are confirmed always, not by taint.- **Write-check gate**: before a live `ap_test_flow`, `__flow_write_check` RPC flags write/destructive PIECE steps; read-only flows run ungated; gate fails open on RPC error.-- **Chat follows the plan on Cloud and Enterprise.** `chatVisibility` returns `plan.chatEnabled` on both, and Community and embedded sessions never see chat. Opening chat to everyone on Cloud means granting `CHAT_ENABLED` on every Autumn plan, which `toPlatformPlanFlags` then writes to `chatEnabled`; the code has no Cloud override. The 200-user rollout cap (`CLOUD_CHAT_ROLLOUT_CAP`) and its grandfathering were removed when chat went public on 1 Oct 2026, so a beta user whose plan lacks the grant loses chat. It cached its closed state in Redis under `chat-rollout:closed` with no expiry, which is why raising the env var never reopened it; that key is now ignored and safe to delete.+- **Chat follows the plan on Cloud and Enterprise.** `chatVisibility` returns `plan.chatEnabled` on both, and Community and embedded sessions never see chat. Chat reaches a Cloud user only through `CHAT_ENABLED` on their Autumn plan, which `toPlatformPlanFlags` writes to `chatEnabled`; the code has no Cloud override.- **Flow correctness is 100% prompt/guide-driven — nothing in code enforces it.** The "#1 silent bug" ("Class A"): the agent frames a *recurring* automation as a *one-time task* and omits any anti-reprocessing step, so run N+1 redoes run N's work (re-pays, re-sends). It's a design-time reasoning gap, not a testing gap — `ap_test_flow` runs ONCE, so a single test looks perfect; the bug only shows on the 2nd run. Fix lives in the prompt (`chat-system-prompt.md` `<decision_framework>` + `build_flow.md` "Recurring flows must not reprocess") + capability eval fixtures with a `recurring_avoids_reprocessing` judge dimension. The platform already has every primitive (Tables New-Record webhook, polling `DedupeStrategy`, `_dedupe_key`, Store, update/delete-record); the agent just wasn't reaching for them. Watch the `build_flow.md` "don't over-build" bias — it once actively discouraged the fix.- **Compaction runs inside the 60s `getAgentConfig` RPC, so it must stay bounded.** The summarizer call is capped at `SUMMARY_OUTPUT_RESERVE_TOKENS` and aborted after `COMPACTION_TIMEOUT_MS` (35s). On failure the previous summary is kept and `buildCompactedPayload` still fits the history to the budget, flagging trimmed messages to the model. An unbounded summary once ran for 2.5 min and failed the turn as `RPC [getAgentConfig] failed (timeout: 60000ms)`.- **The eval replay harness drifts silently when a worker tool's signature changes.** `buildEvalToolSet` (`agent-eval/core/runner.ts`) hand-builds the tool set with stubs, and nothing type-checks `test/lib/agent-eval/` in CI, so a new required param never fails a build. Until Oct 2026 the eval passed no `taintState` to `createCrossProjectTools` (every data tool threw, transcripts showed `TOOL_RESULT: null`, and fixtures like the injection one never saw their data), `onSetProjectContext` returned void, and approvals lacked `outcome` so all counted as declined. When you change a tool factory's params, update the eval stubs too, and treat `TOOL_RESULT: null` in an eval transcript as a harness bug, not agent behaviour. Check with `npx tsc -p packages/server/worker/test/lib/agent-eval/cli/tsconfig.json --noEmit`.@@ -63,7 +62,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **Credits are checked after every step, not just before the turn.** `runAgentTurn` asks the API (`agentHasCredits`) after each tool step, sending what the turn has used so far (`chatBilling.creditsForTurn`, the same rule end-of-turn billing uses), and stops once the remaining balance no longer covers it. Flat credits are only charged when the turn ends, so without that pending count the balance never moves mid-turn. The check fails open if the RPC errors.- **Chat files belong to a conversation, not just a project.** Conversations are private to their user, so a project check is not enough. `saveAgentFile` and `persistAgentAttachments` stamp `conversationId` into the file metadata, and `readAgentFile` refuses a file whose stamp doesn't match. Files saved before the stamp existed can't be read back (image editing can't use them). Any tool that reads chat files by a model-supplied ID must go through `readConversationFile` (`agent-file-utils.ts`), and any new save that hands the model a file ID must stamp `conversationId`.- Local dev needs `AP_DB_TYPE=POSTGRES` + Redis; refuses PGLite. **Prefer `AP_EDITION=cloud` over `ee` for chat work.** Cloud boots locally against plain Postgres and Redis with no Autumn, Stripe or license-key config (verified Aug 2026: API healthy, migrations applied, zero billing or license errors), and on Cloud chat follows `plan.chatEnabled`, so set it on the local platform's plan. On `ee` it is gated behind `plan.chatEnabled` and you have to get a plan onto the platform first. Note SMTP is usually unset locally, which makes the auth card open on the password form rather than the email-code step. Debug a run with `npm run chat:logs -- <conversationId> [runId]` (needs `LOG_FILE=true`/`AP_LOG_FILE=true` set when the turn ran — otherwise `.evlog/logs` is empty).-- **Chat was renamed to agent in code and DB, but only the storage half.** As of release 0.87.1 (`1823000000000-AddRenamedChatTableCompatViews`) `chat_conversation` → `agent_conversation` and `user_chat_memory` → `user_memory`, the server module moved `ee/chat/` → `ee/agent/` (entry point `agentModule`), the worker dir moved `jobs/ee/chat/` → `jobs/ee/agent/`, shared types moved `core/shared/.../ee/chat/` → `.../ee/agent/`, and `server/utils/src/chat-ai-utils.ts` → `agent-ai-utils.ts`. **The rename is not uniform, and the split is the thing to learn**: files describing chat as a *user-facing surface* deliberately kept their `chat-` names inside `ee/agent/` — `chat-visibility.ts`, `chat-rollout-service.ts`, `chat-rollout-user-entity.ts`, `chat-analytics-sync.ts`, `chat-tool-billing.ts`, `chat-usage-tracker.ts`, `chat-plan-grant.ts`. So a new chat-surface concern keeps the `chat-` prefix; a new stored entity takes `agent_`. The migration also leaves `CREATE OR REPLACE VIEW` compat views at both old table names, so raw SQL against `chat_conversation` still reads fine and will NOT tell you the rename happened — grep the entity, not the database.+- **Chat was renamed to agent in code and DB, but only the storage half.** As of release 0.87.1 (`1823000000000-AddRenamedChatTableCompatViews`) `chat_conversation` → `agent_conversation` and `user_chat_memory` → `user_memory`, the server module moved `ee/chat/` → `ee/agent/` (entry point `agentModule`), the worker dir moved `jobs/ee/chat/` → `jobs/ee/agent/`, shared types moved `core/shared/.../ee/chat/` → `.../ee/agent/`, and `server/utils/src/chat-ai-utils.ts` → `agent-ai-utils.ts`. **The rename is not uniform, and the split is the thing to learn**: files describing chat as a *user-facing surface* deliberately kept their `chat-` names inside `ee/agent/` — `chat-visibility.ts`, `chat-analytics-sync.ts`, `chat-tool-billing.ts`, `chat-usage-tracker.ts`, `chat-plan-grant.ts`. So a new chat-surface concern keeps the `chat-` prefix; a new stored entity takes `agent_`. The migration also leaves `CREATE OR REPLACE VIEW` compat views at both old table names, so raw SQL against `chat_conversation` still reads fine and will NOT tell you the rename happened — grep the entity, not the database.- **An AI SDK major bump can typecheck clean while a callback payload silently changed shape.** v7 keeps most v6 option *names* as working deprecated aliases (`system`, `onStepFinish`, `experimental_repairToolCall`, `stepCountIs`, `result.toUIMessageStream`), so the option compiles but the data underneath can differ: `experimental_onToolCallFinish` survived as an alias for `onToolExecutionEnd` while its event lost `durationMs`/`success`/`error` (now `toolExecutionMs` plus a `toolOutput.type === 'tool-result'` discriminator). A type-probe that only names the option passes; you have to exercise each callback's property access. `onStepEnd`'s `content` is also cast to a structural `ContentPartLike` with an `args ?? input` fallback (`agent-ai-utils.ts`), which means a shape change there fails at **runtime**, not compile time — always smoke a real turn after a provider/SDK major.- **`ai` and `evlog` are version-coupled.** evlog ≤2.18.1 imports `TelemetryIntegration` from `ai`, which v7 renamed to `Telemetry`, so bumping `ai` to 7 without bumping `evlog` (≥2.22.4, which peers `ai >=6.0.168 <8.0.0` and supports both v6 and v7 hooks) will not compile. That evlog bump in turn changes `DefinedAuditAction` from `<TargetType>` to `<Action, Options>` and breaks `helper/audit-events.ts` — drop the explicit annotation and let `defineAuditAction`'s inference supply it.- **AI SDK v7 is ESM-only, and that is NOT a reason to convert the server to ESM.** `ai@7` ships `type: module` with no `require` condition, but the CJS server consumes it fine through Node's `require(esm)` (Node 22.12+/24, verified), and TS 5.5.4 resolves its types under `module: CommonJS` + `moduleResolution: node` because a root `main` and an adjacent `index.d.ts` still exist and `skipLibCheck` is on. No ESM migration, no TypeScript upgrade. Mixed `ai` majors across workspaces are also safe and intentional — `bunfig.toml` sets `linker = "isolated"`, so pieces/framework/engine can stay on v6 while the agent path runs v7.diff --git a/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.md b/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.mdindex cd283ce7787..b628badd8bc 100644--- a/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.md+++ b/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.md@@ -56,7 +56,7 @@ Billing and entitlements are powered by [Autumn](https://useautumn.com). Each pl- **A one-off plan can be on trial, but the purchase carries no `trialEndsAt` — you derive it.** Subscriptions carry `trialEndsAt` (nullable); purchases don't carry the key at all, so reading it for a trial signal on a purchase always says nothing. The trial is only visible via `purchases[].plan.freeTrial` and the `apCredits` entitlement's `resets_at`, which during a trial equals `startedAt + freeTrial` regardless of the item's own `reset.interval` (a yearly item resetting a week out is the tell). `granted` reads the full aggregate throughout, so a fully-granted balance is *not* evidence the trial was ignored. `freeTrial` on the purchase is also a per-attach snapshot — the catalog `getPlan` may omit it while a purchase of the same plan carries one, and two attaches of one plan can return different durations — so compute the end as `purchase.startedAt + purchase.plan.freeTrial` (`purchaseTrialEndsAt` in `autumn-billing.ts`) and never read it from the catalog. Two API caveats: `billing.preview_update` rejects a trial on a `one_off` plan with `400 invalid_request` while `attach` accepts and applies it, so the preview is stricter than reality here; and each attach appends a `customer.trials_used` row, which records past consumption, not a live trial.- **`trialEndsAt` silently switches three billing-page decisions, so a wrong derived value moves the UI in three places at once.** Non-nil makes `billingUtils.resolveCreditsAction` return `{ kind: 'upgrade' }`, so the credits card offers an upgrade instead of the auto-recharge control; `resolveFooter` (`credits-card.tsx`) swaps the credits-reset line for "Trial ends \<date>"; and `isComped` (`app/routes/platform/billing/index.tsx`, `isPaid && isNil(trialEndsAt) && !hasBillingPortal`) flips false, changing which sections render. A spurious value hides auto-recharge from a paying contract customer; a missing one — the pre-fix behaviour, when `trialEndsAt` came only from `subscriptions[]` — made `isComped` true for every trialing contract customer. That is why `trialEndsAt` is derived for purchases rather than left null.- **Cancelling has two UI entry points and a third path that never reaches the cancel call at all.** The billing page's "Cancel subscription" link (`app/routes/platform/billing/index.tsx`) and the plan selector's Free-plan "Downgrade" button (`plan-selector.tsx`) both render the same `CancelSubscriptionDialog` (the churn survey, which carries `planSelectorUtils.dropToFreeWarning` in its warning alert) and both call `cancelWithSeatCheck` from `useCancelSubscriptionGuard`. Anything added to the cancel moment (copy, survey options, telemetry) belongs in the dialog or the hook, never in one call site, or the other entry point silently skips it. The third path is the seat floor: when active users exceed the Free plan's seats, `cancelWithSeatCheck` opens the deactivate-users dialog *instead of* cancelling, and a `QUOTA_EXCEEDED` from the server does the same thing after the fact, so the user can leave the flow having intended to cancel without a single request reaching `/v1/platform-billing/cancel` — and with the survey answers they just typed thrown away (decision 000023).-- **Every console endpoint AP calls must live under `/v1`.** AP instances self-host and upgrade on their own schedule, so an AP-facing console route is a public contract and the version segment is the only place a breaking change can be absorbed without stranding older instances. All `/api/v1/billing/*` routes comply; three do not and should move when next touched: `/api/external/grant-chat-plan` (called from `autumn-utils.ts`), `/api/chat-analytics/external/sync` and `/api/chat-analytics/external/rollout-funnel` (called from `ee/chat/chat-analytics-sync.ts`). Console-web-only routes are not AP-facing and stay unversioned.+- **Every console endpoint AP calls must live under `/v1`.** AP instances self-host and upgrade on their own schedule, so an AP-facing console route is a public contract and the version segment is the only place a breaking change can be absorbed without stranding older instances. All `/api/v1/billing/*` routes comply; two do not and should move when next touched: `/api/external/grant-chat-plan` (called from `autumn-utils.ts`) and `/api/chat-analytics/external/sync` (called from `ee/agent/chat-analytics-sync.ts`). Console-web-only routes are not AP-facing and stay unversioned.- **Anything that must happen on every cancellation goes in the console's `/api/v1/billing/cancel` *controller*, not in `billingService.cancel`.** That service method early-returns when the customer's plan is nil or Free, before it touches Autumn, so a side effect placed inside it silently never runs for exactly the customers whose state is unusual. The cancellation-feedback insert sits in the controller for this reason, and is best-effort: it logs on failure and never fails the cancellation.- **`customer.flags` cannot tell you which plan granted a flag.** The map is keyed by feature id, so two plans granting the same boolean feature collapse into one entry reporting `planId: null` — the identical shape Autumn uses for a standalone customer-level grant. Anything branching on `flag.planId` therefore flips the moment a second plan grants that feature, which is how `showPoweredBy` inverted itself. Entitlement flags are resolved from the customer's plan set instead (decision 000030).- **The `auto_enable` `free` plan stays attached underneath a purchase-shaped plan.** Attaching a *subscription* plan replaces `free`; a one-off *purchase* plan (`appsumo`, `free_legacy`) does not — see the subscription-vs-purchase classification bullet above. So `free` stays active and both `customer.flags` and `customer.balances` become the union of the two plans: flags leak in, and numeric balances add up (free's 1 seat beside the purchase's 1 seat reads as `granted: 2`). Flags are resolved from the plan set to avoid this; **balances deliberately are not** (decision 000030), so seat and credit figures still union for exactly those platforms.diff --git a/packages/server/api/src/app/database/database-connection.ts b/packages/server/api/src/app/database/database-connection.tsindex 37027f53738..3b8beb5f410 100644--- a/packages/server/api/src/app/database/database-connection.ts+++ b/packages/server/api/src/app/database/database-connection.ts@@ -13,7 +13,6 @@ import { UserIdentityEntity } from '../authentication/user-identity/user-identitimport { AgentConversationEntity } from '../ee/agent/agent-conversation-entity'import { AgentEntity } from '../ee/agent/agent-entity'import { AgentTaskEntity } from '../ee/agent/agent-task-entity'-import { ChatRolloutUserEntity } from '../ee/agent/chat-rollout-user-entity'import { ChatPersonalizationEntity } from '../ee/agent/personalization/chat-personalization-entity'import { UserMemoryEntity } from '../ee/agent/user-memory-entity'import { AlertEntity } from '../ee/alerts/alerts-entity'@@ -118,7 +117,6 @@ function getEntities(): EntitySchema<unknown>[] {AgentConversationEntity,AgentTaskEntity,ChatPersonalizationEntity,- ChatRolloutUserEntity,UserMemoryEntity,TriggerSourceEntity,WaitpointEntity,diff --git a/packages/server/api/src/app/database/migration/postgres/1870000000000-DropChatRolloutUserTable.ts b/packages/server/api/src/app/database/migration/postgres/1870000000000-DropChatRolloutUserTable.tsnew file mode 100644index 00000000000..e6a7dd63954--- /dev/null+++ b/packages/server/api/src/app/database/migration/postgres/1870000000000-DropChatRolloutUserTable.ts@@ -0,0 +1,19 @@+import { QueryRunner } from 'typeorm'+import { Migration } from '../../migration'++export class DropChatRolloutUserTable1870000000000 implements Migration {+ name = 'DropChatRolloutUserTable1870000000000'+ breaking = true+ release = '0.93.0'+ transaction = true++ public async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`+ DROP TABLE IF EXISTS "chat_rollout_user" CASCADE+ `)+ }++ public async down(): Promise<void> {+ return+ }+}diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.tsindex e22a6c2dae3..77b768b7049 100644--- a/packages/server/api/src/app/database/postgres-connection.ts+++ b/packages/server/api/src/app/database/postgres-connection.ts@@ -457,6 +457,7 @@ import { AddAuditLogRetentionDaysToPlatform1865000000000 } from './migration/posimport { AddAiSpecificModelsVisibleToPlatformConfiguration1866000000000 } from './migration/postgres/1866000000000-AddAiSpecificModelsVisibleToPlatformConfiguration'import { AddAgentTask1867000000000 } from './migration/postgres/1867000000000-AddAgentTask'import { AddProviderConfigIdToAgentConversation1868000000000 } from './migration/postgres/1868000000000-AddProviderConfigIdToAgentConversation'+import { DropChatRolloutUserTable1870000000000 } from './migration/postgres/1870000000000-DropChatRolloutUserTable'import { AddAgentConversationProviderConfigIdIndex1869000000000 } from './migration/postgres/background/1869000000000-AddAgentConversationProviderConfigIdIndex'const getSslConfig = (): boolean | TlsOptions => {@@ -935,6 +936,7 @@ export const getMigrations = (): (new () => Migration)[] => {AddAiSpecificModelsVisibleToPlatformConfiguration1866000000000,AddAgentTask1867000000000,AddProviderConfigIdToAgentConversation1868000000000,+ DropChatRolloutUserTable1870000000000,]return migrations}diff --git a/packages/server/api/src/app/ee/agent/chat-rollout-user-entity.ts b/packages/server/api/src/app/ee/agent/chat-rollout-user-entity.tsdeleted file mode 100644index 71b0958477c..00000000000--- a/packages/server/api/src/app/ee/agent/chat-rollout-user-entity.ts+++ /dev/null@@ -1,85 +0,0 @@-import { Platform, User } from '@activepieces/shared'-import { EntitySchema } from 'typeorm'-import { ApIdSchema, BaseColumnSchemaPart } from '../../database/database-common'--type ChatRolloutUser = {- id: string- created: string- updated: string- userId: string- platformId: string- landedAt: string | null- chattedAt: string | null- grantedFreeCreditAt: string | null-}--type ChatRolloutUserWithRelations = ChatRolloutUser & {- user: User- platform: Platform-}--export const ChatRolloutUserEntity = new EntitySchema<ChatRolloutUserWithRelations>({- name: 'chat_rollout_user',- columns: {- ...BaseColumnSchemaPart,- userId: {- ...ApIdSchema,- nullable: false,- },- platformId: {- ...ApIdSchema,- nullable: false,- },- landedAt: {- type: 'timestamp with time zone',- nullable: true,- },- chattedAt: {- type: 'timestamp with time zone',- nullable: true,- },- grantedFreeCreditAt: {- type: 'timestamp with time zone',- nullable: true,- },- },- indices: [- {- name: 'idx_chat_rollout_user_user_id',- columns: ['userId'],- unique: true,- },- {- name: 'idx_chat_rollout_user_chatted',- columns: ['chattedAt'],- where: '"chattedAt" IS NOT NULL',- },- {- name: 'idx_chat_rollout_user_landed',- columns: ['landedAt'],- where: '"landedAt" IS NOT NULL',- },- ],- relations: {- user: {- type: 'many-to-one',- target: 'user',- cascade: true,- onDelete: 'CASCADE',- joinColumn: {- name: 'userId',- foreignKeyConstraintName: 'fk_chat_rollout_user_user_id',- },- },- platform: {- type: 'many-to-one',- target: 'platform',- cascade: true,- onDelete: 'CASCADE',- joinColumn: {- name: 'platformId',- foreignKeyConstraintName: 'fk_chat_rollout_user_platform_id',- },- },- },-})diff --git a/packages/server/api/test/integration/cloud/agent/chat-follows-plan.test.ts b/packages/server/api/test/integration/cloud/agent/chat-follows-plan.test.tsindex f4aca253922..ce9bda7e1ad 100644--- a/packages/server/api/test/integration/cloud/agent/chat-follows-plan.test.ts+++ b/packages/server/api/test/integration/cloud/agent/chat-follows-plan.test.ts@@ -26,7 +26,7 @@ describe('chat on Cloud follows the plan', () => {expect(platform.json().plan.chatEnabled).toBe(true)})- it('stays closed for a user whose plan does not include chat, even with no rollout cap in the way', async () => {+ it('stays closed for a user whose plan does not include chat', async () => {const ctx = await createTestContext(app, { plan: { chatEnabled: false } })const conversations = await ctx.get('/v1/agents/conversations')