Skip to content

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

feat(chat): chat on cloud follows the plan instead of a 200-user beta cap (#16016)

Hazem Adel305eab5f95e6
diff --git a/brain/knowledge/flows-execution/chat-activation-metric.md b/brain/knowledge/flows-execution/chat-activation-metric.md
index 76f97a25375..d88b2e95a1a 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, not `chat_rollout_user.chattedAt`.** The rollout table only exists on Cloud and counts one row per user across all platforms, while S1 is per user and platform. Expect the two to be close, not equal.
-- **The chatted count doesn't show the rollout cap.** Platforms whose plan has `chatEnabled` bypass the rollout, and their users still add `chattedAt` rows, so 1,505 chatted users on 2026-09-29 says nothing about `CLOUD_CHAT_ROLLOUT_CAP`.
-- **Small cohorts swing.** Under the rollout cap one user moves a stage by several points, so read the counts next to the percentages.
+- **The cohort anchor is the first CHAT message.** `chat_rollout_user` was never the anchor and stopped being written on 1 Oct 2026.
+- **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.md
index 734af3efb75..2f63eaa3734 100644
--- a/brain/knowledge/flows-execution/chat.md
+++ b/brain/knowledge/flows-execution/chat.md
@@ -12,7 +12,7 @@ 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`) — cloud rollout cohort; `chattedAt` drives the cap.
+- **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/`.
@@ -39,7 +39,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.
-- **Cloud rollout cap**: opens to non-embed users without `chatEnabled` until 200 distinct users have sent a message (`CLOUD_CHAT_ROLLOUT_CAP`); grandfathered after close. Embedded sessions never see chat.
+- **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.
- **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.
- **The context budget subtracts what the request reserves.** Anthropic/OpenRouter count tool schemas and the reserved `max_tokens` against the 200k window, so `getAgentConfig` passes `reservedTokens` (the clamped output window from `agentAiUtils.affordableOutputTokens`, the same helper the worker uses for `maxOutputTokens`, plus `TOOL_SCHEMA_TOKEN_ESTIMATE = 12_000`) into `agentCompaction`. The threshold, the fit check and the recent window are all measured against `maxContext - reservedTokens`, and the recent window is sized by estimated tokens, not message count. The tool-schema figure is a constant because the tools are built in the worker and the API never sees their definitions. The worker sets `maxOutputTokens` per step in `prepareStep`, so a thinking-disabled step (round one, discovery phase) does not reserve `thinkingBudget`. The system prompt's size is added to the reserve for the window and fit check, and each message is capped at 20k chars in the summary request so the summarizer itself cannot overflow.
- **A write tool in `BUILD_ONLY_TOOL_NAMES` is only reachable if something flips the phase for it.** The denylist is the consistent home for anything that writes (`ap_create_flow`, `ap_create_table`, `ap_lock_and_publish` are all in it), but the only route out of `discovery` is `ap_set_phase`, whose description tells the model to switch when it starts *building an automation*. A tool for a subject with no build guide and no sibling build-only call, the agent-building tools being the case that found this, becomes invisible in any conversation that never builds a flow: `activeToolsForPhase` filters it out and the prompt names no tool, so the model cannot discover that it exists. Classifying by "does it write" is not enough; check what would actually flip the phase in a conversation about *that* subject. The four agent *write* tools (`ap_create_agent`, `ap_update_agent`, `ap_add_agent_tool`, `ap_remove_agent_tool`) were added to the set and then reverted for exactly this, with a test pinning the choice; `ap_list_agents` is a read and was never in it, so the group is five tools and only four were ever candidates.
@@ -47,7 +47,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-
- **Tool output can't be trusted to waive a charge.** A user's own MCP server or `ap_run_code` controls its output's top-level keys, and they reach the persisted part unchanged. Chat billing only honours `billedAtCost` from `ap_web_search` and `ap_generate_image`; a new built-in tool that bills at cost must be added to `TOOLS_THAT_BILL_AT_COST` in `chatBilling`.
- **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 `chatVisibility` returns `planChatEnabled || cloudRolloutOpen || userHasChatted`, so chat is simply **on** while the rollout cap is unfilled. 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).
+- 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.
- **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.
@@ -60,7 +60,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-
### Key files
Entry point: `agentModule`, the Fastify plugin registered in `packages/server/api/src/app/app.ts`.
-- `packages/server/api/src/app/ee/agent/` — the API module: controllers, service, helpers, approval gate, compaction, rollout, console sync, billing (`chat-usage-tracker.ts`, `chat-tool-billing.ts`), memory (`agent-memory-ai.ts`, `user-memory-entity.ts`), entities, plus `tools/`, `mcp/`, `prompt/`, `history/` subdirs
+- `packages/server/api/src/app/ee/agent/` — the API module: controllers, service, helpers, approval gate, compaction, console sync, billing (`chat-usage-tracker.ts`, `chat-tool-billing.ts`), memory (`agent-memory-ai.ts`, `user-memory-entity.ts`), entities, plus `tools/`, `mcp/`, `prompt/`, `history/` subdirs
- `packages/server/worker/src/lib/execute/jobs/ee/agent/` — where the LLM loop actually runs: `execute-agent-run.ts` job handler (+ the three liveness timers + `streamChunksToClient` idle watchdog), `run-agent-turn.ts` DI streaming loop, `agent-worker-tools.ts` tool defs
- `packages/server/utils/src/ai-utils.ts` — the provider-agnostic half: `createModel` per provider, `createEmbeddingModel`/`toStorageEmbedding`, `supportsWebSearch`/`buildWebSearchTools`
- `packages/server/utils/src/agent-ai-utils.ts` — what is genuinely agent-shaped: `collapseStaleToolOutputs` history hygiene, the `onStepEnd` content handling
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index e02811a6df7..d6d48e205a8 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.187.1",
+ "version": "0.188.0",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/ee/agent/chat-visibility.ts b/packages/core/shared/src/lib/ee/agent/chat-visibility.ts
index a25f2d5e0da..5e61c8560ab 100644
--- a/packages/core/shared/src/lib/ee/agent/chat-visibility.ts
+++ b/packages/core/shared/src/lib/ee/agent/chat-visibility.ts
@@ -1,23 +1,8 @@
import { ApEdition } from '../../core/flag/flag'
-/**
- * Single source of truth for whether the AI chat is visible to a given user.
- * Used by the backend gate and by the platform endpoint (which feeds the
- * frontend `plan.chatEnabled`). Cloud opens chat to everyone during the capped
- * beta (`cloudRolloutOpen`) and keeps it for anyone who already chatted
- * (`userHasChatted`, grandfathered) once the cap closes.
- */
-function resolveChatEnabled({ edition, isEmbedded, planChatEnabled, cloudRolloutOpen, userHasChatted }: ResolveChatEnabledParams): boolean {
- if (isEmbedded) {
- return false
- }
- if (edition === ApEdition.CLOUD) {
- return planChatEnabled || cloudRolloutOpen || userHasChatted
- }
- if (edition === ApEdition.ENTERPRISE) {
- return planChatEnabled
- }
- return false
+function resolveChatEnabled({ edition, isEmbedded, planChatEnabled }: ResolveChatEnabledParams): boolean {
+ const chatUnavailable = isEmbedded || edition === ApEdition.COMMUNITY
+ return !chatUnavailable && planChatEnabled
}
export const chatVisibility = {
@@ -28,6 +13,4 @@ export type ResolveChatEnabledParams = {
edition: ApEdition
isEmbedded: boolean
planChatEnabled: boolean
- cloudRolloutOpen: boolean
- userHasChatted: boolean
}
diff --git a/packages/core/shared/test/ee/chat-visibility.test.ts b/packages/core/shared/test/ee/chat-visibility.test.ts
index 3873a694572..4dbec18d18a 100644
--- a/packages/core/shared/test/ee/chat-visibility.test.ts
+++ b/packages/core/shared/test/ee/chat-visibility.test.ts
@@ -2,42 +2,21 @@ import { describe, expect, it } from 'vitest'
import { ApEdition } from '../../src/lib/core/flag/flag'
import { chatVisibility } from '../../src/lib/ee/agent/chat-visibility'
-const base = {
- isEmbedded: false,
- planChatEnabled: false,
- cloudRolloutOpen: false,
- userHasChatted: false,
-}
-
describe('chatVisibility.resolveChatEnabled', () => {
- it('hides chat on Community regardless of flags', () => {
- expect(chatVisibility.resolveChatEnabled({ ...base, edition: ApEdition.COMMUNITY, planChatEnabled: true, cloudRolloutOpen: true, userHasChatted: true })).toBe(false)
+ it('hides chat on Community regardless of the plan', () => {
+ expect(chatVisibility.resolveChatEnabled({ edition: ApEdition.COMMUNITY, isEmbedded: false, planChatEnabled: true })).toBe(false)
})
it('hides chat for embedded users on every edition', () => {
for (const edition of [ApEdition.COMMUNITY, ApEdition.ENTERPRISE, ApEdition.CLOUD]) {
- expect(chatVisibility.resolveChatEnabled({ ...base, edition, isEmbedded: true, planChatEnabled: true, cloudRolloutOpen: true, userHasChatted: true })).toBe(false)
+ expect(chatVisibility.resolveChatEnabled({ edition, isEmbedded: true, planChatEnabled: true })).toBe(false)
}
})
- it('follows the plan flag on Enterprise', () => {
- expect(chatVisibility.resolveChatEnabled({ ...base, edition: ApEdition.ENTERPRISE, planChatEnabled: true })).toBe(true)
- expect(chatVisibility.resolveChatEnabled({ ...base, edition: ApEdition.ENTERPRISE, planChatEnabled: false, cloudRolloutOpen: true, userHasChatted: true })).toBe(false)
- })
-
- it('shows chat on Cloud while the rollout is open', () => {
- expect(chatVisibility.resolveChatEnabled({ ...base, edition: ApEdition.CLOUD, cloudRolloutOpen: true })).toBe(true)
- })
-
- it('grandfathers Cloud users who already chatted after the cap closes', () => {
- expect(chatVisibility.resolveChatEnabled({ ...base, edition: ApEdition.CLOUD, cloudRolloutOpen: false, userHasChatted: true })).toBe(true)
- })
-
- it('hides chat on Cloud for a fresh user once the cap closes', () => {
- expect(chatVisibility.resolveChatEnabled({ ...base, edition: ApEdition.CLOUD, cloudRolloutOpen: false, userHasChatted: false })).toBe(false)
- })
-
- it('keeps chat on Cloud for an entitled plan even after the cap closes', () => {
- expect(chatVisibility.resolveChatEnabled({ ...base, edition: ApEdition.CLOUD, planChatEnabled: true, cloudRolloutOpen: false })).toBe(true)
+ it('follows the plan flag on Enterprise and Cloud', () => {
+ for (const edition of [ApEdition.ENTERPRISE, ApEdition.CLOUD]) {
+ expect(chatVisibility.resolveChatEnabled({ edition, isEmbedded: false, planChatEnabled: true })).toBe(true)
+ expect(chatVisibility.resolveChatEnabled({ edition, isEmbedded: false, planChatEnabled: false })).toBe(false)
+ }
})
})
diff --git a/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts b/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts
index 385130f60b1..7f7a358bb2a 100644
--- a/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts
+++ b/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts
@@ -1,12 +1,10 @@
-import { ActivepiecesError, apId, assertNotNullOrUndefined, connectionTemplate, ErrorCode, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
-import { AgentConversation, AgentConversationStatus, AgentRunSource, AgentToolType, CreateAgentConversationRequest, ImportAgentMemoryRequest, InstructAgentMemoryRequest, LATEST_JOB_DATA_SCHEMA_VERSION, ListAgentRunsRequest, Permission, PrincipalType, SendAgentMessageRequest, SERVICE_KEY_SECURITY_OPENAPI, SetAgentMessageFeedbackRequest, UpdateAgentConversationRequest, UpdateAgentMemoryRequest, WorkerJobType } from '@activepieces/shared'
+import { ActivepiecesError, apId, connectionTemplate, ErrorCode, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
+import { AgentConversation, AgentConversationStatus, AgentRunSource, AgentToolType, CreateAgentConversationRequest, ImportAgentMemoryRequest, InstructAgentMemoryRequest, LATEST_JOB_DATA_SCHEMA_VERSION, PrincipalType, SendAgentMessageRequest, SERVICE_KEY_SECURITY_OPENAPI, SetAgentMessageFeedbackRequest, UpdateAgentConversationRequest, UpdateAgentMemoryRequest, WorkerJobType } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { StatusCodes } from 'http-status-codes'
import { z } from 'zod'
-import { ProjectResourceType } from '../../core/security/authorization/common'
import { securityAccess } from '../../core/security/authorization/fastify-security'
-import { securityHelper } from '../../helper/security-helper'
import { mcpUtils } from '../../mcp/tools/mcp-utils'
import { assertCreditsAndAppSumoNotExceeded } from '../../platform/billing-provider'
import { jobQueue, JobType } from '../../workers/job-queue/job-queue'
@@ -15,8 +13,6 @@ import { agentConversationService } from './agent-conversation-service'
import { agentHelpers } from './agent-helpers'
import { agentMemoryAi } from './agent-memory-ai'
import { agentService } from './agent-service'
-import { chatAnalyticsTelemetry } from './chat-analytics-sync'
-import { chatRolloutService } from './chat-rollout-service'
import { agentPrompt } from './prompt/agent-prompt'
import { updateConversationForRun } from './rpc/rpc-shared'
import { findConnectionsForPiece } from './tools/agent-tools'
@@ -46,37 +42,6 @@ export const agentConversationController: FastifyPluginAsyncZod = async (app) =>
})
})
- app.get('/conversations/runs', ListAgentRunsRoute, async (request) => {
- const readerId = await securityHelper.getUserIdFromRequest(request)
- assertNotNullOrUndefined(readerId, 'userId')
- await agentService(request.log).getOneOrThrow({
- id: request.query.agentId,
- projectId: request.projectId,
- userId: readerId,
- })
- return agentConversationService(request.log).listAgentRuns({
- projectId: request.projectId,
- agentId: request.query.agentId,
- cursor: request.query.cursor,
- limit: request.query.limit ?? 20,
- })
- })
-
- app.get('/conversations/runs/:id', GetAgentRunRoute, async (request) => {
- const readerId = await securityHelper.getUserIdFromRequest(request)
- assertNotNullOrUndefined(readerId, 'userId')
- const run = await agentConversationService(request.log).getAgentRunOrThrow({
- id: request.params.id,
- projectId: request.projectId,
- })
- await agentService(request.log).getOneOrThrow({
- id: run.agentId,
- projectId: request.projectId,
- userId: readerId,
- })
- return run
- })
-
app.get('/conversations/:id', GetConversationRoute, async (request) => {
return agentConversationService(request.log).getConversationOrThrow({
id: request.params.id,
@@ -122,17 +87,6 @@ export const agentConversationController: FastifyPluginAsyncZod = async (app) =>
return reply.status(StatusCodes.OK).send({ success: true })
})
- app.post('/funnel/landing', FunnelLandingRoute, async (request, reply) => {
- // Cloud rollout: record that this user opened the chat page, then refresh the console
- // funnel snapshot. Awaited recordLanding so the pushed landed count includes this landing.
- await chatRolloutService.recordLanding({
- userId: request.principal.id,
- platformId: request.principal.platform.id,
- })
- chatAnalyticsTelemetry(request.log).sendRolloutFunnelUpdate()
- return reply.status(StatusCodes.NO_CONTENT).send()
- })
-
app.post('/conversations/:id/messages', SendMessageRoute, async (request, reply) => {
const { content, runId: clientRunId, files } = request.body
const conversationId = request.params.id
@@ -150,11 +104,6 @@ export const agentConversationController: FastifyPluginAsyncZod = async (app) =>
await assertAgentMessageRateLimitNotExceeded({ platformId, userId, log })
- // Cloud rollout: count this user as a distinct chatter (no-op off cloud, deduped).
- await chatRolloutService.recordChatted({ userId, platformId })
- // Refresh the console rollout funnel snapshot (chatted count just changed).
- chatAnalyticsTelemetry(log).sendRolloutFunnelUpdate()
-
const runId = typeof clientRunId === 'string' ? clientRunId : apId()
const runLog = log.child({ run: { id: runId } })
@@ -454,41 +403,8 @@ const ListConversationsRoute = {
},
}
-const ListAgentRunsRoute = {
- config: {
- security: securityAccess.project(
- CHAT_PRINCIPALS,
- Permission.READ_AGENT,
- { type: ProjectResourceType.QUERY },
- ),
- },
- schema: {
- tags: ['agents'],
- security: [SERVICE_KEY_SECURITY_OPENAPI],
- description: 'List the unattended runs a flow step made with this agent',
- querystring: ListAgentRunsRequest,
- },
-}
-
const CONVERSATION_PARAMS = z.object({ id: z.string() })
-const GetAgentRunRoute = {
- config: {
- security: securityAccess.project(
- CHAT_PRINCIPALS,
- Permission.READ_AGENT,
- { type: ProjectResourceType.QUERY },
- ),
- },
- schema: {
- tags: ['agents'],
- security: [SERVICE_KEY_SECURITY_OPENAPI],
- description: 'Read one unattended run a flow step made, without being able to continue it',
- params: CONVERSATION_PARAMS,
- querystring: z.object({ projectId: z.string() }),
- },
-}
-
const GetConversationRoute = {
config: {
security: securityAccess.publicPlatform(CHAT_PRINCIPALS),
@@ -558,16 +474,6 @@ const SendMessageRoute = {
},
}
-const FunnelLandingRoute = {
- config: {
- security: securityAccess.publicPlatform(CHAT_PRINCIPALS),
- },
- schema: {
- tags: ['agent'],
- security: [SERVICE_KEY_SECURITY_OPENAPI],
- },
-}
-
const ToolApprovalRoute = {
config: {
security: securityAccess.publicPlatform(CHAT_PRINCIPALS),
diff --git a/packages/server/api/src/app/ee/agent/agent-run-history-controller.ts b/packages/server/api/src/app/ee/agent/agent-run-history-controller.ts
new file mode 100644
index 00000000000..e2be502f5ec
--- /dev/null
+++ b/packages/server/api/src/app/ee/agent/agent-run-history-controller.ts
@@ -0,0 +1,80 @@
+import { assertNotNullOrUndefined } from '@activepieces/core-utils'
+import { ListAgentRunsRequest, Permission, PrincipalType, SERVICE_KEY_SECURITY_OPENAPI } from '@activepieces/shared'
+import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
+import { z } from 'zod'
+import { ProjectResourceType } from '../../core/security/authorization/common'
+import { securityAccess } from '../../core/security/authorization/fastify-security'
+import { securityHelper } from '../../helper/security-helper'
+import { agentConversationService } from './agent-conversation-service'
+import { agentService } from './agent-service'
+
+export const agentRunHistoryController: FastifyPluginAsyncZod = async (app) => {
+
+ app.get('/conversations/runs', ListAgentRunsRoute, async (request) => {
+ const readerId = await securityHelper.getUserIdFromRequest(request)
+ assertNotNullOrUndefined(readerId, 'userId')
+ await agentService(request.log).getOneOrThrow({
+ id: request.query.agentId,
+ projectId: request.projectId,
+ userId: readerId,
+ })
+ return agentConversationService(request.log).listAgentRuns({
+ projectId: request.projectId,
+ agentId: request.query.agentId,
+ cursor: request.query.cursor,
+ limit: request.query.limit ?? 20,
+ })
+ })
+
+ app.get('/conversations/runs/:id', GetAgentRunRoute, async (request) => {
+ const readerId = await securityHelper.getUserIdFromRequest(request)
+ assertNotNullOrUndefined(readerId, 'userId')
+ const run = await agentConversationService(request.log).getAgentRunOrThrow({
+ id: request.params.id,
+ projectId: request.projectId,
+ })
+ await agentService(request.log).getOneOrThrow({
+ id: run.agentId,
+ projectId: request.projectId,
+ userId: readerId,
+ })
+ return run
+ })
+}
+
+const AGENT_RUN_PRINCIPALS = [PrincipalType.USER] as const
+
+const RUN_PARAMS = z.object({ id: z.string() })
+
+const ListAgentRunsRoute = {
+ config: {
+ security: securityAccess.project(
+ AGENT_RUN_PRINCIPALS,
+ Permission.READ_AGENT,
+ { type: ProjectResourceType.QUERY },
+ ),
+ },
+ schema: {
+ tags: ['agents'],
+ security: [SERVICE_KEY_SECURITY_OPENAPI],
+ description: 'List the unattended runs a flow step made with this agent',
+ querystring: ListAgentRunsRequest,
+ },
+}
+
+const GetAgentRunRoute = {
+ config: {
+ security: securityAccess.project(
+ AGENT_RUN_PRINCIPALS,
+ Permission.READ_AGENT,
+ { type: ProjectResourceType.QUERY },
+ ),
+ },
+ schema: {
+ tags: ['agents'],
+ security: [SERVICE_KEY_SECURITY_OPENAPI],
+ description: 'Read one unattended run a flow step made, without being able to continue it',
+ params: RUN_PARAMS,
+ querystring: z.object({ projectId: z.string() }),
+ },
+}
diff --git a/packages/server/api/src/app/ee/agent/agent.module.ts b/packages/server/api/src/app/ee/agent/agent.module.ts
index 4aa3d4ab648..accf4035f95 100644
--- a/packages/server/api/src/app/ee/agent/agent.module.ts
+++ b/packages/server/api/src/app/ee/agent/agent.module.ts
@@ -2,6 +2,7 @@ import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { platformMustHaveFeatureEnabled } from '../authentication/ee-authorization'
import { agentController } from './agent-controller'
import { agentConversationController } from './agent-conversation-controller'
+import { agentRunHistoryController } from './agent-run-history-controller'
import { chatVisibilityGuard } from './chat-visibility-helper'
import { chatPersonalizationController } from './personalization/chat-personalization-controller'
@@ -14,5 +15,6 @@ export const agentModule: FastifyPluginAsyncZod = async (app) => {
await app.register(async (agentSurface) => {
agentSurface.addHook('preHandler', platformMustHaveFeatureEnabled((platform) => platform.plan.agentsEnabled))
await agentSurface.register(agentController, { prefix: '/v1/agents' })
+ await agentSurface.register(agentRunHistoryController, { prefix: '/v1/agents' })
})
}
diff --git a/packages/server/api/src/app/ee/agent/chat-analytics-sync.ts b/packages/server/api/src/app/ee/agent/chat-analytics-sync.ts
index 029abd89e03..2d5b8646d36 100644
--- a/packages/server/api/src/app/ee/agent/chat-analytics-sync.ts
+++ b/packages/server/api/src/app/ee/agent/chat-analytics-sync.ts
@@ -9,11 +9,9 @@ import { platformService } from '../../platform/platform.service'
import { userService } from '../../user/user-service'
import { platformPlanRepo } from '../platform/platform-plan/platform-plan.service'
import { agentHelpers } from './agent-helpers'
-import { chatRolloutService } from './chat-rollout-service'
import { agentHistory } from './history/agent-history'
const CONSOLE_TELEMETRY_URL = 'https://console.activepieces.com/api/chat-analytics/external/sync'
-const CONSOLE_ROLLOUT_FUNNEL_URL = 'https://console.activepieces.com/api/chat-analytics/external/rollout-funnel'
const BATCH_SIZE = 50
const REQUEST_TIMEOUT_MS = 30000
@@ -23,11 +21,6 @@ export const chatAnalyticsTelemetry = (log: FastifyBaseLogger) => ({
}): void {
rejectedPromiseHandler(syncConversations({ conversations: [conversation], log }), log)
},
- // Pushes the authoritative rollout funnel snapshot (landed/chatted/cap/closed) to console over
- // the same shared-secret channel as conversation sync. Fire-and-forget; cloud-only.
- sendRolloutFunnelUpdate(): void {
- rejectedPromiseHandler(pushRolloutFunnel({ log }), log)
- },
})
export const chatAnalyticsBulkSync = (log: FastifyBaseLogger) => ({
@@ -73,38 +66,6 @@ async function syncConversations({ conversations, log }: {
return { pushed, skipped, failed }
}
-async function pushRolloutFunnel({ log }: {
- log: FastifyBaseLogger
-}): Promise<void> {
- if (isNotOneOfTheseEditions([ApEdition.CLOUD])) {
- return
- }
- const secret = system.get(AppSystemProp.CONSOLE_API_SECRET_KEY)
- if (isNil(secret)) {
- return
- }
-
- const snapshot = await chatRolloutService.getFunnelSnapshot()
-
- const result = await tryCatch(() => fetch(CONSOLE_ROLLOUT_FUNNEL_URL, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${secret}`,
- },
- body: JSON.stringify(snapshot),
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
- }))
-
- if (result.error) {
- log.error({ error: result.error }, 'Failed to push chat rollout funnel')
- return
- }
- if (!result.data.ok) {
- log.error({ status: result.data.status }, 'Failed to push chat rollout funnel: non-2xx response')
- }
-}
-
async function resolveLicenseKeysByPlatform({ platformIds }: {
platformIds: string[]
}): Promise<Map<string, string>> {
diff --git a/packages/server/api/src/app/ee/agent/chat-rollout-service.ts b/packages/server/api/src/app/ee/agent/chat-rollout-service.ts
deleted file mode 100644
index 0fbbe9c9214..00000000000
--- a/packages/server/api/src/app/ee/agent/chat-rollout-service.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { apId, isNil } from '@activepieces/core-utils'
-import { ApEdition } from '@activepieces/shared'
-import { IsNull, Not } from 'typeorm'
-import { repoFactory } from '../../core/db/repo-factory'
-import { isNotOneOfTheseEditions } from '../../database/database-common'
-import { distributedStore } from '../../database/redis-connections'
-import { system } from '../../helper/system/system'
-import { AppSystemProp } from '../../helper/system/system-props'
-import { ChatRolloutUserEntity } from './chat-rollout-user-entity'
-
-const DEFAULT_ROLLOUT_CAP = 200
-// Monotonic: once the cap is reached the rollout never reopens, so we cache the
-// closed state and stop counting on every gate check.
-const ROLLOUT_CLOSED_KEY = 'chat-rollout:closed'
-
-const rolloutRepo = repoFactory(ChatRolloutUserEntity)
-
-function getCap(): number {
- return system.getNumber(AppSystemProp.CLOUD_CHAT_ROLLOUT_CAP) ?? DEFAULT_ROLLOUT_CAP
-}
-
-function isCloud(): boolean {
- return !isNotOneOfTheseEditions([ApEdition.CLOUD])
-}
-
-async function countChatted(): Promise<number> {
- return rolloutRepo().count({ where: { chattedAt: Not(IsNull()) } })
-}
-
-async function countLanded(): Promise<number> {
- return rolloutRepo().count({ where: { landedAt: Not(IsNull()) } })
-}
-
-export const chatRolloutService = {
- async isRolloutOpen(): Promise<boolean> {
- if (!isCloud()) {
- return false
- }
- const closed = await distributedStore.getBoolean(ROLLOUT_CLOSED_KEY)
- if (closed === true) {
- return false
- }
- const open = (await countChatted()) < getCap()
- if (!open) {
- await distributedStore.putBoolean(ROLLOUT_CLOSED_KEY, true)
- }
- return open
- },
-
- async hasUserChatted({ userId }: { userId: string }): Promise<boolean> {
- if (!isCloud()) {
- return false
- }
- // Pure lookup on the unique userId index (at most one row), then read chattedAt.
- const row = await rolloutRepo().findOne({ where: { userId }, select: ['chattedAt'] })
- return !isNil(row) && !isNil(row.chattedAt)
- },
-
- // Records that a user opened the chat page. Sets landedAt without touching chattedAt, so a user
- // who lands but never sends a message still counts toward "landed" (landed >= chatted).
- async recordLanding({ userId, platformId }: { userId: string, platformId: string }): Promise<void> {
- if (!isCloud()) {
- return
- }
- await rolloutRepo().query(
- `INSERT INTO "chat_rollout_user" ("id", "userId", "platformId", "landedAt")
- VALUES ($1, $2, $3, now())
- ON CONFLICT ("userId") DO UPDATE
- SET "landedAt" = COALESCE("chat_rollout_user"."landedAt", now()),
- "updated" = now()`,
- [apId(), userId, platformId],
- )
- },
-
- // Authoritative funnel snapshot for the console rollout dashboard. landed/chatted come from the
- // same table that drives the cap, so the numbers always match the auto-close.
- async getFunnelSnapshot(): Promise<{ landed: number, chatted: number, cap: number, closed: boolean }> {
- if (!isCloud()) {
- return { landed: 0, chatted: 0, cap: getCap(), closed: false }
- }
- const cap = getCap()
- const [landed, chatted] = await Promise.all([countLanded(), countChatted()])
- // Derive closed from the count we already fetched rather than calling isRolloutOpen(), which
- // would COUNT chatted a second time. Read-only: the monotonic Redis closed flag is maintained
- // by recordChatted() when the cap is first reached.
- return { landed, chatted, cap, closed: chatted >= cap }
- },
-
- async recordChatted({ userId, platformId }: { userId: string, platformId: string }): Promise<void> {
- if (!isCloud()) {
- return
- }
- // Rows only ever exist once a user has chatted, so an INSERT (xmax = 0) is the first message.
- const rows = await rolloutRepo().query(
- `INSERT INTO "chat_rollout_user" ("id", "userId", "platformId", "landedAt", "chattedAt")
- VALUES ($1, $2, $3, now(), now())
- ON CONFLICT ("userId") DO UPDATE
- SET "chattedAt" = COALESCE("chat_rollout_user"."chattedAt", now()),
- "landedAt" = COALESCE("chat_rollout_user"."landedAt", now()),
- "updated" = now()
- RETURNING (xmax = 0) AS inserted`,
- [apId(), userId, platformId],
- )
- const firstChat = rows[0]?.inserted === true
- // Close the rollout the moment the cap is reached, not lazily on the next gate check.
- if (firstChat && (await countChatted()) >= getCap()) {
- await distributedStore.putBoolean(ROLLOUT_CLOSED_KEY, true)
- }
- },
-}
diff --git a/packages/server/api/src/app/ee/agent/chat-visibility-helper.ts b/packages/server/api/src/app/ee/agent/chat-visibility-helper.ts
index f1471742c64..2e181d644b9 100644
--- a/packages/server/api/src/app/ee/agent/chat-visibility-helper.ts
+++ b/packages/server/api/src/app/ee/agent/chat-visibility-helper.ts
@@ -1,27 +1,18 @@
import { ActivepiecesError, ErrorCode } from '@activepieces/core-utils'
-import { ApEdition, chatVisibility, PlatformWithoutSensitiveData, PrincipalType } from '@activepieces/shared'
+import { chatVisibility, PlatformWithoutSensitiveData, PrincipalType } from '@activepieces/shared'
import { onRequestAsyncHookHandler } from 'fastify'
import { system } from '../../helper/system/system'
import { userIdentityHelper } from '../../helper/user-identity-helper'
import { platformService } from '../../platform/platform.service'
-import { chatRolloutService } from './chat-rollout-service'
-async function resolveChatEnabledForUser({ userId, platform, isEmbedded }: {
- userId: string
+function resolveChatEnabledForUser({ platform, isEmbedded }: {
platform: PlatformWithoutSensitiveData
isEmbedded: boolean
-}): Promise<boolean> {
- const edition = system.getEdition()
- const isCloud = edition === ApEdition.CLOUD
- const [cloudRolloutOpen, userHasChatted] = isCloud
- ? await Promise.all([chatRolloutService.isRolloutOpen(), chatRolloutService.hasUserChatted({ userId })])
- : [false, false]
+}): boolean {
return chatVisibility.resolveChatEnabled({
- edition,
+ edition: system.getEdition(),
isEmbedded,
planChatEnabled: platform.plan.chatEnabled,
- cloudRolloutOpen,
- userHasChatted,
})
}
@@ -36,7 +27,7 @@ export const chatVisibilityGuard: onRequestAsyncHookHandler = async (request) =>
}
const platform = await platformService(request.log).getOneWithPlanOrThrow(principal.platform.id)
const isEmbedded = await userIdentityHelper(request.log).isUserEmbedded(principal.id)
- const enabled = await resolveChatEnabledForUser({ userId: principal.id, platform, isEmbedded })
+ const enabled = resolveChatEnabledForUser({ platform, isEmbedded })
if (!enabled) {
throw new ActivepiecesError({ code: ErrorCode.FEATURE_DISABLED, params: { message: 'Feature is disabled' } })
}
diff --git a/packages/server/api/src/app/helper/system-validator.ts b/packages/server/api/src/app/helper/system-validator.ts
index aa086c766f5..f25030034b4 100644
--- a/packages/server/api/src/app/helper/system-validator.ts
+++ b/packages/server/api/src/app/helper/system-validator.ts
@@ -99,7 +99,6 @@ const systemPropValidators: {
[AppSystemProp.LOG_PRETTY]: booleanValidator,
[AppSystemProp.LOG_FILE]: booleanValidator,
[AppSystemProp.ENVIRONMENT]: enumValidator(Object.values(ApEnvironment)),
- [AppSystemProp.CLOUD_CHAT_ROLLOUT_CAP]: numberValidator,
[AppSystemProp.TRIGGER_TIMEOUT_SECONDS]: numberValidator,
[AppSystemProp.TRIGGER_HOOKS_TIMEOUT_SECONDS]: numberValidator,
[AppSystemProp.FLOW_TIMEOUT_SECONDS]: numberValidator,
diff --git a/packages/server/api/src/app/helper/system/system-props.ts b/packages/server/api/src/app/helper/system/system-props.ts
index abbcb7fd631..24f2d5e32e0 100644
--- a/packages/server/api/src/app/helper/system/system-props.ts
+++ b/packages/server/api/src/app/helper/system/system-props.ts
@@ -23,7 +23,6 @@ export enum AppSystemProp {
BETTERSTACK_TOKEN = 'BETTERSTACK_TOKEN',
CLIENT_REAL_IP_HEADER = 'CLIENT_REAL_IP_HEADER',
CLOUD_AUTH_ENABLED = 'CLOUD_AUTH_ENABLED',
- CLOUD_CHAT_ROLLOUT_CAP = 'CLOUD_CHAT_ROLLOUT_CAP',
CLOUDFLARE_API_BASE = 'CLOUDFLARE_API_BASE',
CLOUDFLARE_API_TOKEN = 'CLOUDFLARE_API_TOKEN',
CLOUDFLARE_SAAS_FALLBACK_ORIGIN = 'CLOUDFLARE_SAAS_FALLBACK_ORIGIN',
diff --git a/packages/server/api/src/app/platform/platform.controller.ts b/packages/server/api/src/app/platform/platform.controller.ts
index 1a1d23fd475..c9c0c72bbd2 100644
--- a/packages/server/api/src/app/platform/platform.controller.ts
+++ b/packages/server/api/src/app/platform/platform.controller.ts
@@ -99,7 +99,7 @@ export const platformController: FastifyPluginAsyncZod = async (app) => {
const platform = await platformService(req.log).getOneWithPlanAndUsageOrThrow(req.principal.platform.id)
if (req.principal.type === PrincipalType.USER) {
const isEmbedded = await userIdentityHelper(req.log).isUserEmbedded(req.principal.id)
- const chatEnabled = await chatVisibilityHelper.resolveChatEnabledForUser({ userId: req.principal.id, platform, isEmbedded })
+ const chatEnabled = chatVisibilityHelper.resolveChatEnabledForUser({ platform, isEmbedded })
return {
...platform,
plan: {
diff --git a/packages/server/api/test/integration/cloud/agent/agent-run-endpoint.test.ts b/packages/server/api/test/integration/cloud/agent/agent-run-endpoint.test.ts
index 939f2d22319..33ef3293384 100644
--- a/packages/server/api/test/integration/cloud/agent/agent-run-endpoint.test.ts
+++ b/packages/server/api/test/integration/cloud/agent/agent-run-endpoint.test.ts
@@ -64,7 +64,7 @@ describe('POST /v1/agents/runs', () => {
})
it('keeps flow-step runs out of the owner\'s chat list', async () => {
- const ctx = await createTestContext(app)
+ const ctx = await createTestContext(app, { plan: { chatEnabled: true } })
const engineToken = await accessTokenManager(app.log).generateEngineToken({
jobId: 'job-3',
projectId: ctx.project.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.ts
new file mode 100644
index 00000000000..f4aca253922
--- /dev/null
+++ b/packages/server/api/test/integration/cloud/agent/chat-follows-plan.test.ts
@@ -0,0 +1,56 @@
+import { AgentIcon, ColorName } from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { createTestContext } from '../../../helpers/test-context'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('chat on Cloud follows the plan', () => {
+ it('opens for a user whose plan includes chat', async () => {
+ const ctx = await createTestContext(app, { plan: { chatEnabled: true } })
+
+ const conversations = await ctx.get('/v1/agents/conversations')
+ const platform = await ctx.get(`/v1/platforms/${ctx.platform.id}`)
+
+ expect(conversations.statusCode).toBe(StatusCodes.OK)
+ 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 () => {
+ const ctx = await createTestContext(app, { plan: { chatEnabled: false } })
+
+ const conversations = await ctx.get('/v1/agents/conversations')
+ const platform = await ctx.get(`/v1/platforms/${ctx.platform.id}`)
+
+ expect(conversations.statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
+ expect(platform.json().plan.chatEnabled).toBe(false)
+ })
+
+ it('keeps an agent\'s run history readable on a plan with agents but no chat', async () => {
+ const ctx = await createTestContext(app, { plan: { agentsEnabled: true, chatEnabled: false } })
+ const agent = await ctx.post('/v1/agents', {
+ projectId: ctx.project.id,
+ displayName: 'Nightly agent',
+ description: null,
+ icon: AgentIcon.BOT,
+ color: ColorName.PURPLE,
+ draft: { instructions: 'Do the nightly job.', maxSteps: 5, tools: [], structuredOutput: [], modelName: null },
+ })
+
+ const runs = await ctx.get(`/v1/agents/conversations/runs?projectId=${ctx.project.id}&agentId=${agent.json().id}`)
+ const chat = await ctx.get('/v1/agents/conversations')
+
+ expect(runs.statusCode).toBe(StatusCodes.OK)
+ expect(chat.statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
+ })
+})
diff --git a/packages/web/src/app/routes/chat-with-ai/index.tsx b/packages/web/src/app/routes/chat-with-ai/index.tsx
index 89fac8dd6f2..42d05c54d7a 100644
--- a/packages/web/src/app/routes/chat-with-ai/index.tsx
+++ b/packages/web/src/app/routes/chat-with-ai/index.tsx
@@ -62,12 +62,6 @@ export function ChatWithAIPage() {
);
const isMobile = useIsMobile();
- useEffect(() => {
- // Record the chat-page landing for the cloud rollout funnel (server is cloud-gated; no-op otherwise).
- chatApi.recordLanding().catch(() => undefined);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
useEffect(() => {
if (isNil(handedOverPrompt)) {
return;
diff --git a/packages/web/src/features/chat/lib/chat-api.ts b/packages/web/src/features/chat/lib/chat-api.ts
index 9034b3563c5..bd77a750cb1 100644
--- a/packages/web/src/features/chat/lib/chat-api.ts
+++ b/packages/web/src/features/chat/lib/chat-api.ts
@@ -136,10 +136,6 @@ async function getPendingGate(
return api.get(`/v1/agents/conversations/${conversationId}/pending-gate`);
}
-async function recordLanding(): Promise<void> {
- return api.post<void>('/v1/agents/funnel/landing');
-}
-
async function getMemory(): Promise<GetAgentMemoryResponse> {
return api.get<GetAgentMemoryResponse>('/v1/agents/memory');
}
@@ -178,7 +174,6 @@ export const chatApi = {
submitMessageFeedback,
getPickerConnections,
getPendingGate,
- recordLanding,
getMemory,
saveMemory,
importMemory,