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
fix(chat): show why a reply failed and let users retry (#15931)
Hazem Adel611db01a865b
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.mdindex bc2b2300bfd..ff6c555aee1 100644--- a/brain/knowledge/flows-execution/chat.md+++ b/brain/knowledge/flows-execution/chat.md@@ -31,6 +31,8 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **Stream idle watchdog** (`STREAM_IDLE_TIMEOUT_MS` 90s, in `streamChunksToClient`): aborts the turn if the drain-stream reader is silent 90s. It must be SUSPENDED while legitimate silent work is in flight — pending tool calls AND in-flight reasoning (`reasoning-start`→`reasoning-end`). **Reasoning-awareness was missing and caused the bug where long "thinking" on the Expert tier randomly aborted a healthy turn** (a >90s gap between reasoning deltas looked like a wedge). Backstop for a genuine mid-reasoning wedge is `MAX_TURN_WALL_CLOCK_MS` (20 min).### Gotchas+- **The streaming lock is per run, not per conversation.** A re-send can claim `activeRunId` before the first job reaches `getAgentConfig`. `agentHelpers.acquireStreamingLock` only lets the owning run set STREAMING; an older run gets `AGENT_RUN_SUPERSEDED` and the worker exits quietly, with no ERROR save and no events. A lock that ignored `runId` let the old run stream unowned while the new one was rejected as busy and marked ERROR, which is how users saw nothing after tapping a starter card twice.+- **A failed turn used to leave status ERROR with an empty reply.** The error text only travelled as a websocket `ERROR` event, so a reload, another tab, or a user who was away saw a dead conversation (and often no user message either when the job died inside `getAgentConfig`, before it persists the turn). The `execute-agent-run.ts` catch now sends `failure: { message, userMessage? }` on the empty `saveAgentMessages` call and `conversation-rpc.ts` appends it to `uiMessages` as an assistant text reply; `use-chat.ts` shows the Retry banner when a loaded conversation is ERROR. Stale STREAMING to IDLE recovery, a worker that never picks the job up, and `assertAgentMessageRateLimitNotExceeded` still leave no reply of their own.- **A built flow ends with a "Turn it on?" card, never an auto-publish**: an audit found 40% of built-but-unpublished flows ended on "open it to review", some claiming LIVE. Chat never publishes on its own; only a yes to the card calls `ap_lock_and_publish` (`build_flow.md` "Turn it on?"). Pinned by the `build-then-ask-turn-it-on` fixture (`askedToTurnItOn`, `noLiveClaimWithoutPublish`). The live-claim check is a regex plus "was `ap_lock_and_publish` called", so it cannot see whether publish succeeded.- **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, blocks saved-agent edits, 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.diff --git a/packages/core/execution/package.json b/packages/core/execution/package.jsonindex f642e826e8f..e8fa3d370d0 100644--- a/packages/core/execution/package.json+++ b/packages/core/execution/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/core-execution",- "version": "0.23.4",+ "version": "0.23.5","type": "commonjs","main": "./dist/src/index.js","scripts": {diff --git a/packages/core/execution/src/lib/workers/worker-contract.ts b/packages/core/execution/src/lib/workers/worker-contract.tsindex 78ce7655228..23a3fd0a0cf 100644--- a/packages/core/execution/src/lib/workers/worker-contract.ts+++ b/packages/core/execution/src/lib/workers/worker-contract.ts@@ -184,6 +184,7 @@ export type SaveAgentMessagesRequest = {uiMessages: unknown[]title?: stringmodelName?: string+ failure?: { message: string, userMessage?: string }}export type SaveAgentFileRequest = {diff --git a/packages/core/utils/package.json b/packages/core/utils/package.jsonindex 038de4dadb1..20638a9b878 100644--- a/packages/core/utils/package.json+++ b/packages/core/utils/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/core-utils",- "version": "0.8.2",+ "version": "0.8.3","type": "commonjs","main": "./dist/src/index.js","scripts": {diff --git a/packages/core/utils/src/lib/activepieces-error.ts b/packages/core/utils/src/lib/activepieces-error.tsindex 5696e6c790f..d6621c427a7 100644--- a/packages/core/utils/src/lib/activepieces-error.ts+++ b/packages/core/utils/src/lib/activepieces-error.ts@@ -50,6 +50,7 @@ export type ApErrorParams =| TriggerUpdateStatusErrorParams| TriggerFailedErrorParams| ValidationErrorParams+ | AgentRunSupersededErrorParams| FileTooLargeErrorParams| InvitationOnlySignUpParams| UserIsInActiveErrorParams@@ -325,6 +326,13 @@ ErrorCode.VALIDATION,}>+export type AgentRunSupersededErrorParams = BaseErrorParams<+ErrorCode.AGENT_RUN_SUPERSEDED,+{+ message: string+}+>+export type FileTooLargeErrorParams = BaseErrorParams<ErrorCode.FILE_TOO_LARGE,{@@ -592,6 +600,7 @@ export enum ErrorCode {USER_IS_INACTIVE = 'USER_IS_INACTIVE',USER_NOT_FOUND_ON_PLATFORM = 'USER_NOT_FOUND_ON_PLATFORM',VALIDATION = 'VALIDATION',+ AGENT_RUN_SUPERSEDED = 'AGENT_RUN_SUPERSEDED',FILE_TOO_LARGE = 'FILE_TOO_LARGE',INVALID_LICENSE_KEY = 'INVALID_LICENSE_KEY',EMAIL_ALREADY_HAS_ACTIVATION_KEY = 'EMAIL_ALREADY_HAS_ACTIVATION_KEY',diff --git a/packages/server/api/src/app/ee/agent/agent-helpers.ts b/packages/server/api/src/app/ee/agent/agent-helpers.tsindex 41272c51e47..3047b5fddfb 100644--- a/packages/server/api/src/app/ee/agent/agent-helpers.ts+++ b/packages/server/api/src/app/ee/agent/agent-helpers.ts@@ -350,6 +350,25 @@ async function claimConversationForRun({ conversationId, runId }: { conversation})}+async function acquireStreamingLock({ conversationId, runId }: { conversationId: string, runId?: string }): Promise<StreamingLockResult> {+ const builder = conversationRepo()+ .createQueryBuilder()+ .update()+ .set({ status: AgentConversationStatus.STREAMING })+ .where('id = :id AND status != :streaming', { id: conversationId, streaming: AgentConversationStatus.STREAMING })+ if (!isNil(runId)) {+ builder.andWhere('("activeRunId" IS NULL OR "activeRunId" = :runId)', { runId })+ }+ const result = await builder.returning('id').execute()+ const lockedRows: unknown[] = result.raw ?? []+ if (lockedRows.length > 0) {+ return 'acquired'+ }+ const current = await conversationRepo().findOneBy({ id: conversationId })+ const supersededByNewerRun = !isNil(runId) && !isNil(current?.activeRunId) && current.activeRunId !== runId+ return supersededByNewerRun ? 'superseded' : 'busy'+}+async function resolveFlowTools({ projectId, tools, log }: { projectId: string, tools: AgentTool[], log: FastifyBaseLogger }): Promise<ResolvedAgentFlowTool[]> {const flowToolRequests = tools.filter((tool): tool is AgentFlowTool => tool.type === AgentToolType.FLOW)if (flowToolRequests.length === 0) {@@ -411,6 +430,7 @@ async function assertAgentsSurfaceAvailable({ platformId, log }: { platformId: sexport const agentHelpers = {jobFieldsFromConfig,claimConversationForRun,+ acquireStreamingLock,resolveFlowTools,agentsSurfaceAvailable,assertAgentsSurfaceAvailable,@@ -439,3 +459,5 @@ export const agentHelpers = {}type AgentJobConfigFields = Pick<ExecuteAgentRunJobData, 'tools' | 'structuredOutput' | 'maxSteps' | 'modelName' | 'provider' | 'providerConfigId' | 'promptOverride'>++export type StreamingLockResult = 'acquired' | 'busy' | 'superseded'diff --git a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.tsindex 26c56491db0..cbc27a07ecf 100644--- a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts+++ b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts@@ -1,6 +1,6 @@import { ActivepiecesError, ErrorCode, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'import { agentAiUtils, aiUtils } from '@activepieces/server-utils'-import { AgentConfigResponse, AgentConversationStatus, AgentRunSource, GetAgentConfigRequest, GetEnabledAiToolsResponse, PersistedAgentMessage, PersistedAgentPartType, PersistedAgentRole } from '@activepieces/shared'+import { AgentConfigResponse, AgentRunSource, GetAgentConfigRequest, GetEnabledAiToolsResponse, PersistedAgentMessage, PersistedAgentPartType, PersistedAgentRole } from '@activepieces/shared'import { ModelMessage } from 'ai'import { FastifyBaseLogger } from 'fastify'import { agentApprovalGate } from '.././agent-approval-gate'@@ -110,15 +110,15 @@ export const agentConfigRpc = (log: FastifyBaseLogger) => ({? undefined: chosen.image?.modelId ?? await agentHelpers.resolveImageModelId({ platformId, providerConfig, scope: runScope, log })- const lockResult = await agentHelpers.conversationRepo()- .createQueryBuilder()- .update()- .set({ status: AgentConversationStatus.STREAMING })- .where('id = :id AND status != :streaming', { id: conversationId, streaming: AgentConversationStatus.STREAMING })- .returning('id')- .execute()- const lockedRows: unknown[] = lockResult.raw ?? []- if (lockedRows.length === 0) {+ const lock = await agentHelpers.acquireStreamingLock({ conversationId, ...spreadIfDefined('runId', input.runId) })+ if (lock === 'superseded') {+ log.info({ conversation: { id: conversationId } }, '[agentRpc#getAgentConfig] Run superseded by a newer message before it started')+ throw new ActivepiecesError({+ code: ErrorCode.AGENT_RUN_SUPERSEDED,+ params: { message: 'This message was replaced by a newer one' },+ })+ }+ if (lock === 'busy') {log.warn({ conversation: { id: conversationId } }, '[agentRpc#getAgentConfig] Concurrent run rejected (conversation already STREAMING)')throw new ActivepiecesError({code: ErrorCode.VALIDATION,diff --git a/packages/server/api/src/app/ee/agent/rpc/conversation-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/conversation-rpc.tsindex 42aa6b44896..4bbc696d458 100644--- a/packages/server/api/src/app/ee/agent/rpc/conversation-rpc.ts+++ b/packages/server/api/src/app/ee/agent/rpc/conversation-rpc.ts@@ -1,5 +1,5 @@import { ActivepiecesError, ErrorCode, isNil, sanitizeObjectForPostgresql, spreadIfDefined } from '@activepieces/core-utils'-import { AgentConversationStatus, AgentCreditsLeftRequest, AgentRunSource, FileCompression, FileType, HeartbeatAgentConversationRequest, ReadAgentFileRequest, ReadFlowStepFileResponse, SaveAgentFileRequest, SaveAgentFileResponse, SaveAgentMessagesRequest, UpdateAgentProgressRequest, UpdateProjectContextRequest } from '@activepieces/shared'+import { AgentConversationStatus, AgentCreditsLeftRequest, AgentRunSource, FileCompression, FileType, HeartbeatAgentConversationRequest, PersistedAgentPartType, PersistedAgentRole, ReadAgentFileRequest, ReadFlowStepFileResponse, SaveAgentFileRequest, SaveAgentFileResponse, SaveAgentMessagesRequest, UpdateAgentProgressRequest, UpdateProjectContextRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { readConversationFile } from '.././agent-file-utils'import { agentHelpers } from '.././agent-helpers'@@ -66,7 +66,8 @@ export const conversationRpc = (log: FastifyBaseLogger) => ({// that case — keep the richer history that updateAgentProgress persisted incrementally. The// status still reflects success/error so the UI is correct; only the destructive content// overwrite is suppressed. (uiMessages tracks messages, so we gate both on the same check.)- const storedMessageCount = ((await agentHelpers.conversationRepo().findOneBy({ id: input.conversationId }))?.messages as unknown[] | undefined)?.length ?? 0+ const stored = await agentHelpers.conversationRepo().findOneBy({ id: input.conversationId })+ const storedMessageCount = stored?.messages.length ?? 0const wouldShrinkHistory = input.messages.length < storedMessageCountconst persistContent = isSuccessfulCompletion && !wouldShrinkHistory@@ -76,7 +77,14 @@ export const conversationRpc = (log: FastifyBaseLogger) => ({if (input.title) updates.title = input.titleif (input.modelName) updates.modelName = input.modelName}- else if (wouldShrinkHistory) {+ const failureAppend = isNil(input.failure) ? null : failureAppendFor({ stored: stored?.uiMessages ?? [], failure: input.failure })+ if (!isNil(failureAppend)) {+ updates.uiMessages = () => 'coalesce("uiMessages", \'[]\'::jsonb) || :failureUiMessages::jsonb'+ if (failureAppend.modelMessages.length > 0) {+ updates.messages = () => 'coalesce("messages", \'[]\'::jsonb) || :failureModelMessages::jsonb'+ }+ }+ if (wouldShrinkHistory) {log.warn({conversation: { id: input.conversationId },run: { id: input.runId },@@ -85,7 +93,15 @@ export const conversationRpc = (log: FastifyBaseLogger) => ({}, '[agentRpc#saveAgentMessages] Refused shrinking save — kept incrementally-persisted history')}- const saveLanded = await updateConversationForRun({ conversationId: input.conversationId, runId: input.runId, updates })+ const saveLanded = await updateConversationForRun({+ conversationId: input.conversationId,+ runId: input.runId,+ updates,+ ...spreadIfDefined('parameters', isNil(failureAppend) ? undefined : {+ failureUiMessages: JSON.stringify(sanitizeObjectForPostgresql(failureAppend.uiMessages)),+ failureModelMessages: JSON.stringify(sanitizeObjectForPostgresql(failureAppend.modelMessages)),+ }),+ })if (!saveLanded) {log.warn({ conversation: { id: input.conversationId }, run: { id: input.runId } }, 'saveAgentMessages: no row updated — conversation deleted or superseded by a newer run; skipping analytics and usage tracking')}@@ -114,7 +130,7 @@ export const conversationRpc = (log: FastifyBaseLogger) => ({if (!isNil(input.messages)) {updates.messages = input.messages}- await updateConversationForRun({ conversationId: input.conversationId, runId: input.runId, updates })+ await updateConversationForRun({ conversationId: input.conversationId, runId: input.runId, updates, onlyWhileStreaming: true })log.debug({ conversation: { id: input.conversationId }, uiMessageCount: input.uiMessages.length, messageCount: input.messages?.length }, '[agentRpc#updateAgentProgress] Progress persisted')},@@ -161,3 +177,26 @@ export const conversationRpc = (log: FastifyBaseLogger) => ({},})++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && !isNil(value)+}++function failureAppendFor({ stored, failure }: { stored: unknown[], failure: { message: string, userMessage?: string } }): FailureAppend {+ const lastStored = stored.at(-1)+ const endsWithThisUserMessage = isObject(lastStored) && lastStored.role === PersistedAgentRole.USER+ const restoresUserTurn = !isNil(failure.userMessage) && !endsWithThisUserMessage+ const userTurn = restoresUserTurn+ ? [{ role: PersistedAgentRole.USER, parts: [{ type: PersistedAgentPartType.TEXT, text: failure.userMessage }] }]+ : []+ const failureReply = { role: PersistedAgentRole.ASSISTANT, parts: [{ type: PersistedAgentPartType.TEXT, text: failure.message }] }+ return {+ uiMessages: [...userTurn, failureReply],+ modelMessages: restoresUserTurn ? [{ role: 'user', content: failure.userMessage }] : [],+ }+}++type FailureAppend = {+ uiMessages: unknown[]+ modelMessages: unknown[]+}diff --git a/packages/server/api/src/app/ee/agent/rpc/rpc-shared.ts b/packages/server/api/src/app/ee/agent/rpc/rpc-shared.tsindex 83ef9284469..b4bbe731efc 100644--- a/packages/server/api/src/app/ee/agent/rpc/rpc-shared.ts+++ b/packages/server/api/src/app/ee/agent/rpc/rpc-shared.ts@@ -16,19 +16,27 @@ import { mcpUtils } from '../../../mcp/tools/mcp-utils'// Gate the UPDATE on the persisted owning run (activeRunId, claimed at turn start) so a run// preempted by a newer message matches zero rows — the ownership check is part of the write, with// no check-then-write window. A nil runId or unclaimed row (activeRunId IS NULL) writes freely.-export async function updateConversationForRun({ conversationId, runId, updates }: {+export async function updateConversationForRun({ conversationId, runId, updates, parameters, onlyWhileStreaming }: {conversationId: stringrunId?: stringupdates: Record<string, unknown>+ parameters?: Record<string, unknown>+ onlyWhileStreaming?: boolean}): Promise<boolean> {const builder = agentHelpers.conversationRepo().createQueryBuilder().update().set(updates).where('id = :id', { id: conversationId })+ if (!isNil(parameters)) {+ builder.setParameters(parameters)+ }if (!isNil(runId)) {builder.andWhere('("activeRunId" IS NULL OR "activeRunId" = :runId)', { runId })}+ if (onlyWhileStreaming === true) {+ builder.andWhere('status = :streamingStatus', { streamingStatus: AgentConversationStatus.STREAMING })+ }const result = await builder.returning('id').execute()const updatedRows: unknown[] = result.raw ?? []return updatedRows.length > 0diff --git a/packages/server/api/test/integration/cloud/agent/agent-resend-race.test.ts b/packages/server/api/test/integration/cloud/agent/agent-resend-race.test.tsnew file mode 100644index 00000000000..4154973d78b--- /dev/null+++ b/packages/server/api/test/integration/cloud/agent/agent-resend-race.test.ts@@ -0,0 +1,47 @@+import { AgentConversationStatus } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { agentHelpers } from '../../../../src/app/ee/agent/agent-helpers'+import { db } from '../../../helpers/db'+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('re-sending a message while the first run has not started yet', () => {+ it('lets the newer run start and turns the older run away without a busy rejection', async () => {+ const ctx = await createTestContext(app, { plan: { chatEnabled: true } })+ const created = await ctx.post('/v1/agents/conversations', { title: 'Resend' })+ const conversationId = created.json().id++ await agentHelpers.claimConversationForRun({ conversationId, runId: 'run-1' })+ await agentHelpers.claimConversationForRun({ conversationId, runId: 'run-2' })++ const older = await agentHelpers.acquireStreamingLock({ conversationId, runId: 'run-1' })+ const newer = await agentHelpers.acquireStreamingLock({ conversationId, runId: 'run-2' })++ expect(older).toBe('superseded')+ expect(newer).toBe('acquired')+ const stored = await db.findOneByOrFail<{ status: string, activeRunId: string }>('agent_conversation', { id: conversationId })+ expect(stored.status).toBe(AgentConversationStatus.STREAMING)+ expect(stored.activeRunId).toBe('run-2')+ })++ it('still reports busy when the same run finds the conversation already streaming', async () => {+ const ctx = await createTestContext(app, { plan: { chatEnabled: true } })+ const created = await ctx.post('/v1/agents/conversations', { title: 'Busy' })+ const conversationId = created.json().id+ await agentHelpers.claimConversationForRun({ conversationId, runId: 'run-1' })++ expect(await agentHelpers.acquireStreamingLock({ conversationId, runId: 'run-1' })).toBe('acquired')+ expect(await agentHelpers.acquireStreamingLock({ conversationId, runId: 'run-1' })).toBe('busy')+ })+})diff --git a/packages/server/api/test/unit/app/ee/agent/agent-rpc-handlers.test.ts b/packages/server/api/test/unit/app/ee/agent/agent-rpc-handlers.test.tsindex 5e3dd033fac..ca937f6c8cc 100644--- a/packages/server/api/test/unit/app/ee/agent/agent-rpc-handlers.test.ts+++ b/packages/server/api/test/unit/app/ee/agent/agent-rpc-handlers.test.ts@@ -14,9 +14,10 @@ vi.mock('../../../../../src/app/waitpoints/resume-service', () => ({resumeService: () => ({ resumeFromWaitpoint: mockResumeFromWaitpoint }),}))-const { mockSet, mockWhere, mockAndWhere, mockExecute, mockFindOneBy, mockFindOne, mockSave, mockTrack, mockSendConversationUpdate } = vi.hoisted(() => ({+const { mockSet, mockSetParameters, mockWhere, mockAndWhere, mockExecute, mockFindOneBy, mockFindOne, mockSave, mockTrack, mockSendConversationUpdate } = vi.hoisted(() => ({mockSave: vi.fn(),mockSet: vi.fn(),+ mockSetParameters: vi.fn(),mockWhere: vi.fn(),mockAndWhere: vi.fn(),mockExecute: vi.fn().mockResolvedValue({ raw: [{ id: 'conv-1' }] }),@@ -102,6 +103,7 @@ vi.mock('@activepieces/server-utils', async (importOriginal) => ({type QueryBuilderMock = {update: () => QueryBuilderMockset: (values: unknown) => QueryBuilderMock+ setParameters: (params: unknown) => QueryBuilderMockwhere: (sql: string, params: unknown) => QueryBuilderMockandWhere: (sql: string, params: unknown) => QueryBuilderMockreturning: (columns: string) => QueryBuilderMock@@ -122,6 +124,7 @@ vi.mock('../../../../../src/app/ee/agent/agent-helpers', () => ({const builder: QueryBuilderMock = {update: () => builder,set: (values) => { mockSet(values); return builder },+ setParameters: (params) => { mockSetParameters(params); return builder },where: (_sql, params) => { mockWhere(params); return builder },andWhere: (_sql, params) => { mockAndWhere(params); return builder },returning: () => builder,@@ -796,3 +799,55 @@ describe('agentRpcHandlers.executePieceTool — which account a configured actioexpect(call.connectionExternalId).toBeUndefined()})})++describe('agentRpcHandlers.saveAgentMessages: a failed turn leaves a visible reply', () => {+ beforeEach(() => {+ mockSet.mockClear()+ mockSetParameters.mockClear()+ mockAndWhere.mockClear()+ mockFindOneBy.mockReset()+ })++ it('appends the failure and restores a user message that never got stored, in the transcript and the model context', async () => {+ mockFindOneBy.mockResolvedValue({ messages: [], uiMessages: [] })++ await agentRpcHandlers(noopLogger as never).saveAgentMessages({+ conversationId: 'conv-1', runId: 'run-1', messages: [], uiMessages: [],+ failure: { message: 'provider is down', userMessage: 'Do my hiring' },+ } as never)++ const updates = mockSet.mock.calls[0][0]+ const params = mockSetParameters.mock.calls[0][0]+ expect(updates.status).toBe('ERROR')+ expect(typeof updates.uiMessages).toBe('function')+ expect(typeof updates.messages).toBe('function')+ expect(JSON.parse(params.failureUiMessages)).toEqual([+ { role: 'user', parts: [{ type: 'text', text: 'Do my hiring' }] },+ { role: 'assistant', parts: [{ type: 'text', text: 'provider is down' }] },+ ])+ expect(JSON.parse(params.failureModelMessages)).toEqual([{ role: 'user', content: 'Do my hiring' }])+ })++ it('appends only the failure reply when the user message is already the last stored one', async () => {+ const storedUser = { role: 'user', parts: [{ type: 'text', text: 'Do my hiring' }] }+ mockFindOneBy.mockResolvedValue({ messages: [{ role: 'user' }], uiMessages: [storedUser] })++ await agentRpcHandlers(noopLogger as never).saveAgentMessages({+ conversationId: 'conv-1', runId: 'run-1', messages: [], uiMessages: [],+ failure: { message: 'boom', userMessage: 'Do my hiring' },+ } as never)++ expect(mockSet.mock.calls[0][0].messages).toBeUndefined()+ expect(JSON.parse(mockSetParameters.mock.calls[0][0].failureUiMessages)).toEqual([+ { role: 'assistant', parts: [{ type: 'text', text: 'boom' }] },+ ])+ })++ it('only saves progress while the turn is still streaming, so a late progress save cannot wipe the failure reply', async () => {+ await agentRpcHandlers(noopLogger as never).updateAgentProgress({+ conversationId: 'conv-1', runId: 'run-1', uiMessages: [],+ } as never)++ expect(mockAndWhere).toHaveBeenCalledWith({ streamingStatus: 'STREAMING' })+ })+})diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.tsindex 37d65bbe53d..299372b052c 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts@@ -66,6 +66,7 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForgelet runProvider: string | undefinedlet runModelId: string | undefinedlet answer: AgentResult | undefined+ let configLoaded = falseconst structured: { output?: Record<string, unknown> } = {}let progressSequence = 0@@ -103,6 +104,7 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge...spreadIfDefined('discoveryOnly', discoveryOnly),})+ configLoaded = trueconst { credentials } = configconst { provider } = credentialsconst searchCredentials = config.searchCredentials ?? credentials@@ -398,6 +400,10 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge})}catch (err) {+ if (apErrorOf(err)?.code === ErrorCode.AGENT_RUN_SUPERSEDED) {+ log.info({ conversation: { id: conversationId }, run: { id: runId } }, '[executeAgentRun] Run superseded by a newer message, exiting quietly')+ return { kind: JobResultKind.FIRE_AND_FORGET, status: EngineResponseStatus.OK }+ }const errorClass = classifyAgentRunError({ error: err, provider: runProvider })log[errorClass === 'internal' ? 'error' : 'warn']({ error: err, conversation: { id: conversationId }, provider: runProvider, model: { id: runModelId }, agentRun: { errorClass, source } }, '[executeAgentRun] Agent job failed')const errorMessage = apErrorOf(err)?.message ?? formatPieceError(err).message@@ -417,6 +423,7 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge// its prior context instead of resetting the conversation.await ctx.apiClient.saveAgentMessages({conversationId, runId, messages: [], uiMessages: [],+ failure: { message: clientMessage, ...(configLoaded ? {} : { userMessage }) },}).catch(() => {})await sendEventWithRetry({event: { type: AgentEventType.ERROR, data: { message: clientMessage, ...spreadIfDefined('code', isCreditError ? ErrorCode.QUOTA_EXCEEDED : undefined) } },diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex c13004ef321..de6a9a9c4b4 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -2321,6 +2321,7 @@"{count, plural, =1 {1 hour} other {# hours}}": "{count, plural, =1 {1 hour} other {# hours}}","Image preview": "Image preview","The assistant did not respond. Please try again.": "The assistant did not respond. Please try again.",+ "The last reply did not finish. Please try again.": "The last reply did not finish. Please try again.","Edit Global Connection": "Edit Global Connection","Rename Connection": "Rename Connection","Enter a new display name for this connection.": "Enter a new display name for this connection.",diff --git a/packages/web/src/features/chat/lib/use-chat.ts b/packages/web/src/features/chat/lib/use-chat.tsindex c9da2c785c0..7b93c5dd1cf 100644--- a/packages/web/src/features/chat/lib/use-chat.ts+++ b/packages/web/src/features/chat/lib/use-chat.ts@@ -517,7 +517,18 @@ export function useAgentChat({history.findLastIndex((m) => m.role === 'assistant') >history.findLastIndex((m) => m.role === 'user');if (opts?.errorMessage) {- updateSendStatus({ type: 'error', message: opts.errorMessage });+ const lastReply = history?.at(-1);+ const failureIsInTranscript =+ lastReply?.role === 'assistant' &&+ lastReply.parts.some(+ (part) => part.type === 'text' && part.text === opts.errorMessage,+ );+ updateSendStatus({+ type: 'error',+ message: failureIsInTranscript+ ? t('The last reply did not finish. Please try again.')+ : opts.errorMessage,+ });} else if (!hasReply && !opts?.suppressNoReply) {updateSendStatus({type: 'error',@@ -863,10 +874,16 @@ export function useAgentChat({}} else {setPersistedMessages(mapped);+ if (convResult.data.status === AgentConversationStatus.ERROR) {+ updateSendStatus({+ type: 'error',+ message: t('The last reply did not finish. Please try again.'),+ });+ }}setIsLoadingHistory(false);},- [stopStream, startStream, updateSendStatus, store],+ [stopStream, startStream, updateSendStatus, store, t],);useQuery({