🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(bot): bind the completion reply to its own operation, and surface failure reasons (#19114)
Rdmclin2db920ea16256
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 51184cf44b8..7040cc35459 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -887,6 +887,7 @@ export class CompletionLifecycle {operationId,assistantMessageId,metadata?.userId || this.userId,+ typeof metadata?.topicId === 'string' ? metadata.topicId : undefined,);if (recovered) event.lastAssistantContent = recovered;}@@ -1051,8 +1052,9 @@ export class CompletionLifecycle {operationId: string,assistantMessageId: string | undefined,userId: string,+ topicId?: string,): Promise<string | undefined> {- if (!assistantMessageId) return undefined;+ if (!assistantMessageId && !topicId) return undefined;try {const messageModel =@@ -1061,7 +1063,28 @@ export class CompletionLifecycle {: new MessageModel(this.serverDB, userId, this.workspaceId, undefined, {includeShareVisitor: this.includeShareVisitor,});- const row = await messageModel.findById(assistantMessageId);++ // 1. The row the event already names (client-runtime `metadata.assistantMessageId`,+ // or the final assistant leaf in state).+ let row = assistantMessageId ? await messageModel.findById(assistantMessageId) : undefined;+ let recoveredFrom = assistantMessageId;++ // 2. Otherwise the run's own final assistant row, by the creation-time+ // provenance `call_llm` stamps on every assistant row it creates or+ // reuses (`metadata.operationId`). Unlike "the latest assistant row in+ // the topic", this is bound to THIS operation, so a topic that also+ // holds a concurrent run's rows cannot supply the answer (LOBE-13787).+ if (!extractTextFromMessage(row)?.trim() && topicId) {+ const byOperation = await messageModel.findLatestAssistantByOperationId({+ operationId,+ topicId,+ });+ if (byOperation) {+ row = byOperation;+ recoveredFrom = byOperation.id;+ }+ }+const raw = typeof row?.content === 'string' ? row.content : undefined;if (!raw?.trim()) return undefined;@@ -1079,7 +1102,7 @@ export class CompletionLifecycle {// production logs — the silent variant of this is what made// the Discord bot empty-reply issue hard to diagnose.console.warn(- `[CompletionLifecycle][${operationId}] completion event had no assistant text; recovered ${content.length} chars from message ${assistantMessageId}`,+ `[CompletionLifecycle][${operationId}] completion event had no assistant text; recovered ${content.length} chars from message ${recoveredFrom}`,);return content;} catch (error) {diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 6ef7f010ec8..67990daf314 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -1219,6 +1219,34 @@ describe('CompletionLifecycle.dispatchHooks — lastAssistantContent DB recovery);});+ // LOBE-13787: the named row can be an empty placeholder while the run's real+ // reply sits on another row. Resolve it by the run's own provenance+ // (`metadata.operationId`), never by "the latest assistant row in the topic" —+ // a topic can hold a concurrent run's rows.+ it('falls back to operation provenance when the named row is empty', async () => {+ const lifecycle = buildLifecycle();+ const dispatchSpy = setupSpies(lifecycle);+ const findById = vi.fn().mockResolvedValue({ content: '', id: 'msg-assistant' });+ const findLatestAssistantByOperationId = vi+ .fn()+ .mockResolvedValue({ content: 'final step reply', id: 'msg-final-step' });+ (lifecycle as any).messageModel = { findById, findLatestAssistantByOperationId };++ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');++ expect(findById).toHaveBeenCalledWith('msg-assistant');+ expect(findLatestAssistantByOperationId).toHaveBeenCalledWith({+ operationId: 'op-1',+ topicId: 'tpc-1',+ });+ expect(dispatchSpy).toHaveBeenCalledWith(+ 'op-1',+ 'onComplete',+ expect.objectContaining({ lastAssistantContent: 'final step reply' }),+ [],+ );+ });+it('extracts only text parts when the DB row stores serialized multimodal content', async () => {const lifecycle = buildLifecycle();const dispatchSpy = setupSpies(lifecycle);diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.tsindex 072317f6bd0..c3b91bef747 100644--- a/apps/server/src/services/bot/AgentBridgeService.ts+++ b/apps/server/src/services/bot/AgentBridgeService.ts@@ -30,9 +30,9 @@ import {} from './platforms';import { clearReactionState, saveReactionState } from './reactionState';import { buildRecentChannelHistory } from './recentChannelHistory';+import { renderThrownAgentError } from './renderThrownError';import {renderAgentError,- renderError,renderErrorWithDetails,renderFinalReply,renderStart,@@ -414,10 +414,14 @@ export class AgentBridgeService {AgentBridgeService.clearActiveThread(thread.id);+ // Classify before rendering so a startup failure lands on curated copy+ // (harness / provider / user tier) instead of a bare "Agent Execution+ // Failed" that tells the user nothing — especially when the run died+ // before it had an operation id to show.const errorContent = {markdown: stopped? renderStopped(errorMessage, replyLocale)- : renderError(operationId, replyLocale),+ : renderThrownAgentError(error, operationId, replyLocale),};if (progressMessage) {@@ -531,7 +535,7 @@ export class AgentBridgeService {const operationId = AgentBridgeService.activeOperations.get(thread.id);log('handleMention error: operationId=%s, %O', operationId, error);try {- await thread.post({ markdown: renderError(operationId, replyLocale) });+ await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });} catch (postError) {log('handleMention: failed to post error message: %O', postError);}@@ -1531,7 +1535,7 @@ export class AgentBridgeService {if (progressMessage) {try {await progressMessage.edit({- markdown: renderError(result.operationId, replyLocale),+ markdown: renderThrownAgentError(result.error, result.operationId, replyLocale),});} catch (error) {log('executeWithCallback[local]: failed to edit startup error: %O', error);@@ -1608,7 +1612,7 @@ export class AgentBridgeService {if (progressMessage) {try {await progressMessage.edit({- markdown: renderError(fallbackOperationId, replyLocale),+ markdown: renderThrownAgentError(error, fallbackOperationId, replyLocale),});} catch (editError) {log('executeWithCallback[local]: failed to edit startup error: %O', editError);diff --git a/apps/server/src/services/bot/BotMessageRouter.ts b/apps/server/src/services/bot/BotMessageRouter.tsindex 11a478055d7..25ff2d35698 100644--- a/apps/server/src/services/bot/BotMessageRouter.ts+++ b/apps/server/src/services/bot/BotMessageRouter.ts@@ -51,12 +51,12 @@ import {type UserAllowlist,type WatchKeywordEntry,} from './platforms';+import { renderThrownAgentError } from './renderThrownError';import {renderApproveSuccess,renderCommandReply,renderDmPairing,renderDmRejected,- renderError,renderFeedbackSubmitted,renderGroupRejected,renderInlineError,@@ -1231,7 +1231,7 @@ export class BotMessageRouter {error,);try {- await thread.post({ markdown: renderError(operationId, replyLocale) });+ await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });} catch {// best-effort notification}@@ -1419,7 +1419,7 @@ export class BotMessageRouter {error,);try {- await thread.post({ markdown: renderError(operationId, replyLocale) });+ await thread.post({ markdown: renderThrownAgentError(error, operationId, replyLocale) });} catch {// best-effort notification}diff --git a/apps/server/src/services/bot/__tests__/renderThrownError.test.ts b/apps/server/src/services/bot/__tests__/renderThrownError.test.tsnew file mode 100644index 00000000000..f2582eb1f6f--- /dev/null+++ b/apps/server/src/services/bot/__tests__/renderThrownError.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { renderThrownAgentError } from '../renderThrownError';++// LOBE-13787: the bot's startup / catch-all failure paths posted a bare+// "**Agent Execution Failed**" — with no operation id, that carried no+// information at all. Classifying the thrown value first lets the tiered+// renderer pick curated copy, WITHOUT ever emitting the raw message.+describe('renderThrownAgentError', () => {+ it('gives a plain thrown Error the harness-tier copy instead of a bare header', () => {+ const out = renderThrownAgentError(new Error('Topic not found'), 'op-1');++ expect(out).toContain('Something went wrong on our side');+ expect(out).toContain('Operation ID: `op-1`');+ expect(out).not.toBe('**Agent Execution Failed**\nOperation ID: `op-1`');+ });++ // The case from the issue screenshot: the run died before it had an id, so+ // the old rendering was a bare header with literally nothing else.+ it('still says something useful when the run never got an operation id', () => {+ const out = renderThrownAgentError(new Error('gateway unreachable'), undefined);++ expect(out).not.toBe('**Agent Execution Failed**');+ expect(out).toContain('Something went wrong on our side');+ expect(out).not.toContain('Operation ID: `');+ });++ it('keeps the precise copy for a classified runtime payload', () => {+ const out = renderThrownAgentError(+ { errorType: 'NoAvailableProvider', message: 'no channel' },+ 'op-2',+ );++ expect(out).toContain('No model provider configured');+ expect(out).toContain('op-2');+ });++ it('never leaks the raw error message into the reply', () => {+ const secret = 'connect ECONNREFUSED 10.0.0.7:5432';++ expect(renderThrownAgentError(new Error(secret), 'op-3')).not.toContain(secret);+ expect(renderThrownAgentError(secret, 'op-3')).not.toContain(secret);+ });++ it('renders localized copy', () => {+ const en = renderThrownAgentError(new Error('boom'), 'op-4');+ const zh = renderThrownAgentError(new Error('boom'), 'op-4', 'zh-CN');++ expect(zh).toContain('op-4');+ expect(zh).not.toContain('boom');+ expect(zh).not.toBe(en);+ });+});diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.tsindex eef390ebda3..d0f493bfc1e 100644--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts@@ -505,6 +505,19 @@ describe('replyTemplate', () => {expect(renderAgentError(undefined, undefined, undefined)).toBe('**Agent Execution Failed**');});+ // The raw runtime message must never reach an IM channel — it is+ // server-side triage material only (b4aa51baa, #13998). Classification is+ // what earns the user a reason; the message itself stays out of every tier.+ it('never leaks the raw error message, on any tier', () => {+ const secret = 'connect ECONNREFUSED 10.0.0.7:5432';++ expect(renderAgentError('NoAvailableProvider', secret, 'op-1')).not.toContain(secret);+ expect(+ renderAgentError('SomeNewErrorCode', secret, 'op-1', undefined, 'harness'),+ ).not.toContain(secret);+ expect(renderAgentError('SomeNewErrorCode', secret, 'op-1')).not.toContain(secret);+ });+it('surfaces a network message for ProviderNetworkError instead of a bare op id', () => {const en = renderAgentError('ProviderNetworkError', 'fetch failed', 'op-net');expect(en).toContain('Network error talking to the model provider');diff --git a/apps/server/src/services/bot/renderThrownError.ts b/apps/server/src/services/bot/renderThrownError.tsnew file mode 100644index 00000000000..a856bf9972d--- /dev/null+++ b/apps/server/src/services/bot/renderThrownError.ts@@ -0,0 +1,44 @@+import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';++import type { BotReplyLocale } from './platforms';+import { renderAgentError } from './replyTemplate';++/**+ * Render a thrown value as a user-facing IM failure reply.+ *+ * The bot's failure paths that catch a raw `Error` (bridge startup, the+ * handleMention / router catch-alls) used to render `renderError(operationId)`,+ * which produces a bare "**Agent Execution Failed**" — and, when the operation+ * never got far enough to have an id, not even that (LOBE-13787: the user saw+ * two consecutive failures carrying no information at all).+ *+ * Running the value through the runtime's own error normalizer first gives+ * those paths the same `errorType` + `attribution` the completion path already+ * receives from the lifecycle event, so `renderAgentError` can pick curated+ * copy ("Something went wrong on our side…", "Model provider temporarily+ * unavailable…") instead of the opaque legacy template.+ *+ * The raw message is passed only as a matching signal — `renderAgentError`+ * never emits it (see the legacy-tier comment there).+ */+export const renderThrownAgentError = (+ error: unknown,+ operationId: string | undefined,+ replyLocale?: BotReplyLocale,+): string => {+ const formatted = formatErrorForState(error);++ // An unclassified throw normalizes to a numeric `InternalServerError`, which+ // carries no spec and therefore no attribution — that is exactly the case+ // that used to render the bare header. These call sites only ever catch a+ // throw out of our OWN harness (bridge startup, router catch-all), never a+ // provider response, so `harness` is the honest default: "something went+ // wrong on our side, it is logged, retry or quote the operation id".+ return renderAgentError(+ formatted.type === undefined ? undefined : String(formatted.type),+ formatted.message,+ operationId,+ replyLocale,+ formatted.attribution ?? 'harness',+ );+};diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex c8e2a660b81..51af4084935 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -587,6 +587,11 @@ export function renderAgentError(}}+ // Legacy tier: nothing friendly matched. The raw `errorMessage` deliberately+ // stays out of the reply — IM channels can hold arbitrary members, so runtime+ // error text is server-side triage material only (b4aa51baa, #13998). Callers+ // that hold a thrown error should classify it first (see+ // `renderThrownAgentError`) so it lands on one of the tiers above instead.return operationId ? strings.errorWithId(operationId) : strings.error;}diff --git a/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts b/packages/database/src/models/__tests__/messages/message.operationLookup.test.tsnew file mode 100644index 00000000000..942a18114ae--- /dev/null+++ b/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts@@ -0,0 +1,110 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { MessageModel } from '../../message';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'op-msg-lookup-user';+const otherUserId = 'op-msg-lookup-other';+const topicId = 'op-msg-lookup-topic';+const otherTopicId = 'op-msg-lookup-topic-other';+const messageModel = new MessageModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.delete(users).where(eq(users.id, otherUserId));+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(topics).values([+ { id: topicId, userId },+ { id: otherTopicId, userId },+ ]);+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.delete(users).where(eq(users.id, otherUserId));+});++describe('MessageModel.findLatestAssistantByOperationId', () => {+ it('resolves the newest assistant row stamped with the operation provenance', async () => {+ await messageModel.create({+ content: 'step 1 (tool call)',+ metadata: { operationId: 'op-1' },+ role: 'assistant',+ topicId,+ });+ const final = await messageModel.create({+ content: 'final reply',+ metadata: { operationId: 'op-1' },+ role: 'assistant',+ topicId,+ });++ const found = await messageModel.findLatestAssistantByOperationId({+ operationId: 'op-1',+ topicId,+ });++ expect(found?.id).toBe(final.id);+ expect(found?.content).toBe('final reply');+ });++ it('does not return rows of another operation in the same topic', async () => {+ await messageModel.create({+ content: 'previous turn reply',+ metadata: { operationId: 'op-old' },+ role: 'assistant',+ topicId,+ });++ const found = await messageModel.findLatestAssistantByOperationId({+ operationId: 'op-new',+ topicId,+ });++ expect(found).toBeUndefined();+ });++ it('ignores non-assistant rows and rows in other topics', async () => {+ await messageModel.create({+ content: 'user text',+ metadata: { operationId: 'op-2' },+ role: 'user',+ topicId,+ });+ await messageModel.create({+ content: 'assistant in another topic',+ metadata: { operationId: 'op-2' },+ role: 'assistant',+ topicId: otherTopicId,+ });++ const found = await messageModel.findLatestAssistantByOperationId({+ operationId: 'op-2',+ topicId,+ });++ expect(found).toBeUndefined();+ });++ it('is scoped to the owning user', async () => {+ await messageModel.create({+ content: 'mine',+ metadata: { operationId: 'op-3' },+ role: 'assistant',+ topicId,+ });++ const asOther = await new MessageModel(serverDB, otherUserId).findLatestAssistantByOperationId({+ operationId: 'op-3',+ topicId,+ });++ expect(asOther).toBeUndefined();+ });+});diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex fcd230d4bb1..6e4740d8c73 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -2654,6 +2654,34 @@ export class MessageModel {});};+ /**+ * Resolve the newest assistant row an Agent Run produced, by the creation+ * provenance `call_llm` stamps on every assistant row it creates or reuses+ * (`metadata.operationId`). Scoped by `topicId` so the JSONB predicate runs+ * inside the topic's own (indexed) rows rather than across the whole table.+ *+ * Used by the completion lifecycle to recover the run's real final reply+ * when the runtime state no longer carries this run's messages — the+ * topic-wide "latest assistant" would be an earlier turn's reply.+ */+ findLatestAssistantByOperationId = async ({+ operationId,+ topicId,+ }: {+ operationId: string;+ topicId: string;+ }) => {+ return this.db.query.messages.findFirst({+ where: and(+ eq(messages.userId, this.userId),+ eq(messages.topicId, topicId),+ eq(messages.role, 'assistant'),+ sql`${messages.metadata}->>'operationId' = ${operationId}`,+ ),+ orderBy: [desc(messages.createdAt)],+ });+ };+/*** Get parent messages for a thread*