Skip to content

🀯 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.

πŸ› fix(bot): recover empty completion replies from DB and notify thread members (#17068)

Rdmclin243469cf3d0c9
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 0b0c21e3e1b..5dac2e0b8eb 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -1,4 +1,6 @@
import { isParkedStatus } from '@lobechat/agent-runtime';
+import type { MessageContentPart } from '@lobechat/types';
+import { deserializeParts } from '@lobechat/utils';
import debug from 'debug';
import {
@@ -476,7 +478,11 @@ export class CompletionLifecycle {
const isAsyncToolPark = reason === 'waiting_for_async_tool';
try {
- const { event, metadata } = this.buildLifecycleEvent(operationId, state, reason);
+ const { assistantMessageId, event, metadata } = this.buildLifecycleEvent(
+ operationId,
+ state,
+ reason,
+ );
// Finalize the agent_operations row before user hooks fire so
// downstream consumers see the row in its terminal shape.
@@ -484,6 +490,26 @@ export class CompletionLifecycle {
if (isAsyncToolPark) return;
+ // `lastAssistantContent` comes off the Redis-backed `state.messages`,
+ // while the assistant message row is persisted through a separate
+ // `messageModel.update` path. When the two diverge (state entry empty
+ // but the DB row holds the full reply β€” LOBE-11632: bot completions
+ // arrived with no content while the app showed the reply), consumers
+ // like the IM bot callback silently drop the reply. Recover from the DB
+ // row β€” the same source of truth the app UI renders β€” before dispatch.
+ if (
+ (reason === 'done' || reason === 'max_steps' || reason === 'cost_limit') &&
+ !event.lastAssistantContent?.trim() &&
+ !event.attachments?.length
+ ) {
+ const recovered = await this.recoverLastAssistantContent(
+ operationId,
+ assistantMessageId,
+ metadata?.userId || this.userId,
+ );
+ if (recovered) event.lastAssistantContent = recovered;
+ }
+
await hookDispatcher.dispatch(operationId, 'onComplete', event, metadata._hooks);
// Delivery checker: on a successful completion, run the confirmed verify
@@ -568,6 +594,59 @@ export class CompletionLifecycle {
}
}
+ /**
+ * Load the final assistant message row from the DB and return its text
+ * content, for completions whose Redis-side state carried no assistant
+ * text (see the LOBE-11632 note in {@link dispatchHooks}). Non-fatal: any
+ * failure just leaves the event as-built.
+ */
+ private async recoverLastAssistantContent(
+ operationId: string,
+ assistantMessageId: string | undefined,
+ userId: string,
+ ): Promise<string | undefined> {
+ if (!assistantMessageId) return undefined;
+
+ try {
+ const messageModel =
+ userId === this.userId
+ ? this.messageModel
+ : new MessageModel(this.serverDB, userId, this.workspaceId);
+ const row = await messageModel.findById(assistantMessageId);
+ const raw = typeof row?.content === 'string' ? row.content : undefined;
+ if (!raw?.trim()) return undefined;
+
+ // Multimodal rows store `content` as serialized MessageContentPart[]
+ // (see serverCallLlmFinalizer / serializePartsForStorage) β€” sending
+ // that verbatim would deliver raw JSON to the bot channel. Gate on the
+ // row's `metadata.isMultimodal` flag (the same signal the app UI uses
+ // in DisplayContent) rather than sniffing the string, so a legitimate
+ // plain-text reply that happens to be a JSON array is preserved as-is.
+ // Extract only the text parts; an image-only row recovers nothing.
+ const isMultimodal =
+ (row?.metadata as { isMultimodal?: boolean } | null | undefined)?.isMultimodal === true;
+ const parts = isMultimodal ? deserializeParts(raw) : null;
+ const content = parts
+ ? parts
+ .filter((p): p is Extract<MessageContentPart, { type: 'text' }> => p.type === 'text')
+ .map((p) => p.text)
+ .join('')
+ : raw;
+ if (!content.trim()) return undefined;
+
+ // console (not debug) so state/DB divergence stays visible in
+ // production logs β€” the silent variant of this is what made
+ // LOBE-11632 hard to diagnose.
+ console.warn(
+ `[CompletionLifecycle][${operationId}] completion event had no assistant text; recovered ${content.length} chars from message ${assistantMessageId}`,
+ );
+ return content;
+ } catch (error) {
+ log('[%s] recoverLastAssistantContent failed (non-fatal): %O', operationId, error);
+ return undefined;
+ }
+ }
+
private buildLifecycleEvent(operationId: string, state: any, reason: string) {
const metadata = state?.metadata || {};
const messages: any[] = Array.isArray(state?.messages) ? state.messages : [];
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 4a9cc2d23e5..24d6327ccf3 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -412,6 +412,175 @@ describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
});
});
+describe('CompletionLifecycle.dispatchHooks β€” lastAssistantContent DB recovery (LOBE-11632)', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ const buildDoneState = (assistantContent: string | undefined) => ({
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ { content: assistantContent, id: 'msg-assistant', role: 'assistant' },
+ ],
+ metadata: { _hooks: [], agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
+ status: 'done',
+ });
+
+ const setupSpies = (lifecycle: CompletionLifecycle) => {
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
+ vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ return vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ };
+
+ it('recovers the reply text from the DB row when the state carries no assistant text', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockResolvedValue({ content: 'the real reply', id: 'msg-assistant' });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(findById).toHaveBeenCalledWith('msg-assistant');
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'the real reply' }),
+ [],
+ );
+ });
+
+ it('does not hit the DB when the state already carries assistant text', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn();
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState('state reply'), 'done');
+
+ expect(findById).not.toHaveBeenCalled();
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'state reply' }),
+ [],
+ );
+ });
+
+ it('extracts only text parts when the DB row stores serialized multimodal content', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const serialized = JSON.stringify([
+ { text: 'ε›Ύι‡Œζ˜―δΈ€εͺ猫', type: 'text' },
+ { image: 'data:image/png;base64,xxx', type: 'image' },
+ ]);
+ const findById = vi.fn().mockResolvedValue({
+ content: serialized,
+ id: 'msg-assistant',
+ metadata: { isMultimodal: true },
+ });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: 'ε›Ύι‡Œζ˜―δΈ€εͺ猫' }),
+ [],
+ );
+ });
+
+ it('returns a plain-text reply verbatim even when it looks like a parts array', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ // A legitimate text answer that happens to be a JSON array with `type`
+ // fields β€” without metadata.isMultimodal it must NOT be parsed as parts.
+ const jsonLookalike = '[{"type":"custom","value":1}]';
+ const findById = vi.fn().mockResolvedValue({ content: jsonLookalike, id: 'msg-assistant' });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: jsonLookalike }),
+ [],
+ );
+ });
+
+ it('does not recover raw JSON from an image-only multimodal DB row', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const serialized = JSON.stringify([{ image: 'data:image/png;base64,xxx', type: 'image' }]);
+ const findById = vi.fn().mockResolvedValue({
+ content: serialized,
+ id: 'msg-assistant',
+ metadata: { isMultimodal: true },
+ });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: undefined }),
+ [],
+ );
+ });
+
+ it('leaves the event untouched when the DB row is empty too', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockResolvedValue({ content: '', id: 'msg-assistant' });
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: undefined }),
+ [],
+ );
+ });
+
+ it('still dispatches the original event when the DB lookup throws', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const findById = vi.fn().mockRejectedValue(new Error('db down'));
+ (lifecycle as any).messageModel = { findById };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({ lastAssistantContent: undefined }),
+ [],
+ );
+ });
+
+ it('skips recovery on the error path', async () => {
+ const lifecycle = buildLifecycle();
+ setupSpies(lifecycle);
+ const findById = vi.fn();
+ (lifecycle as any).messageModel = { findById, update: vi.fn().mockResolvedValue(undefined) };
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ { ...buildDoneState(''), error: { message: 'boom' }, status: 'error' },
+ 'error',
+ );
+
+ expect(findById).not.toHaveBeenCalled();
+ });
+});
+
describe('CompletionLifecycle.emitSignalEvents β€” assistant anchor', () => {
afterEach(() => {
vi.restoreAllMocks();
diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.ts
index 76a56f497f7..c1a04294f5c 100644
--- a/apps/server/src/services/bot/AgentBridgeService.ts
+++ b/apps/server/src/services/bot/AgentBridgeService.ts
@@ -703,13 +703,13 @@ export class AgentBridgeService {
? platformRegistry.getPlatform(opts.botContext.platform)
: undefined;
const botPlatformContext:
- | { platformName: string; supportsMarkdown: boolean; warnings?: string[] }
- | undefined = platformDef
- ? {
- platformName: platformDef.name,
- supportsMarkdown: platformDef.supportsMarkdown !== false,
- }
- : undefined;
+ { platformName: string; supportsMarkdown: boolean; warnings?: string[] } | undefined =
+ platformDef
+ ? {
+ platformName: platformDef.name,
+ supportsMarkdown: platformDef.supportsMarkdown !== false,
+ }
+ : undefined;
// Whether we can edit a previously-posted message in place. When false
// (QQ/WeChat today), the chat-adapter falls editMessage back to postMessage,
// so each step/completion edit surfaces as a NEW message β€” leaving the
@@ -737,6 +737,19 @@ export class AgentBridgeService {
});
const timezone = await this.loadTimezone();
+ // Make sure the person who triggered the run is a member of the reply
+ // thread, so the platform notifies them when the reply lands (LOBE-11632:
+ // Discord's auto-created mention threads never add the mentioning user,
+ // and pill rendering on the origin message proved unreliable β€” replies
+ // were delivered but nobody was told). Fire-and-forget; never blocks.
+ const senderPlatformId = userMessage.author?.userId;
+ if (client?.ensureThreadMember && botContext?.platformThreadId && senderPlatformId) {
+ void safeSideEffect(
+ () => client.ensureThreadMember!(botContext.platformThreadId!, senderPlatformId),
+ 'ensureThreadMember (executeWithCallback)',
+ );
+ }
+
// When the message-gateway is configured AND the platform supports typing
// indicators, skip the ack/progress message and rely on the gateway's
// alarm-based typing indicator throughout AI generation.
@@ -1613,8 +1626,7 @@ export class AgentBridgeService {
const userModel = new UserModel(this.db, this.userId);
const settings = await userModel.getUserSettings();
this.timezone = (settings?.general as Record<string, unknown>)?.timezone as
- | string
- | undefined;
+ string | undefined;
} catch {
// Fall back to server time if settings can't be loaded
}
diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.ts
index 64f2c1267a4..21560abf5e8 100644
--- a/apps/server/src/services/bot/BotCallbackService.ts
+++ b/apps/server/src/services/bot/BotCallbackService.ts
@@ -39,6 +39,28 @@ import {
const log = debug('lobe-server:bot:callback');
+/**
+ * Render a platform delivery error for production logging WITHOUT dumping
+ * the raw error object β€” platform SDK errors (e.g. `@discordjs/rest`
+ * DiscordAPIError) carry the full `requestBody`, i.e. the user/assistant
+ * message content, which must not be persisted in logs. Status/code live on
+ * well-known fields; the message string from these SDKs is the API error
+ * summary (e.g. "Unknown Channel"), not the payload.
+ */
+const describePlatformError = (error: unknown): string => {
+ if (error instanceof Error) {
+ const status = (error as { status?: unknown }).status;
+ const code = (error as { code?: unknown }).code;
+ const parts = [
+ `${error.name}: ${error.message}`,
+ status === undefined ? undefined : `status=${status}`,
+ code === undefined ? undefined : `code=${code}`,
+ ].filter(Boolean);
+ return parts.join(' ');
+ }
+ return String(error);
+};
+
// --------------- Callback body types ---------------
export interface BotCallbackBody {
@@ -437,7 +459,12 @@ export class BotCallbackService {
const hasText = !!lastAssistantContent?.trim();
const hasAttachments = !!attachments?.length;
if (!hasText && !hasAttachments) {
- log('handleCompletion: no lastAssistantContent and no attachments, skipping');
+ // console (not debug) β€” every one of these is a user-facing "bot went
+ // silent" (LOBE-11632): the run completed but the completion event
+ // carried nothing to deliver. Must stay visible in production logs.
+ console.error(
+ `[BotCallbackService] completion had no lastAssistantContent and no attachments, skipping reply (operationId=${operationId}, topicId=${body.topicId}, thread=${body.platformThreadId})`,
+ );
return;
}
@@ -488,7 +515,9 @@ export class BotCallbackService {
isLast && attachments?.length ? { attachments, content: chunks[i] } : chunks[i],
);
} catch (error) {
- log('handleCompletion: failed to send chunk %d: %O', i, error);
+ console.error(
+ `[BotCallbackService] failed to send reply chunk ${i}/${lastIndex} (thread=${body.platformThreadId}): ${describePlatformError(error)}`,
+ );
}
}
}
@@ -511,6 +540,14 @@ export class BotCallbackService {
if (canEdit && progressMessageId) {
try {
await messenger.editMessage(progressMessageId, payload);
+ // Positive delivery record (console, not debug): "we sent it and the
+ // platform accepted it" must be provable from production logs alone β€”
+ // LOBE-11632 burned days on inferring delivery from the absence of
+ // error logs while the target thread had been deleted out from under
+ // the bot.
+ console.info(
+ `[BotCallbackService] completion reply delivered via editMessage (message=${progressMessageId})`,
+ );
return;
} catch (error) {
log('handleCompletion: editMessage failed, falling back to createMessage: %O', error);
@@ -518,8 +555,14 @@ export class BotCallbackService {
}
try {
await messenger.createMessage(payload);
+ console.info('[BotCallbackService] completion reply delivered via createMessage');
} catch (error) {
- log('handleCompletion: createMessage fallback failed: %O', error);
+ // Last resort failed β€” the reply is lost. console (not debug) so the
+ // "agent ran but no reply appeared" class of failures (LOBE-11632)
+ // is visible in production logs instead of an HTTP 200 with nothing.
+ console.error(
+ `[BotCallbackService] createMessage fallback failed, reply lost: ${describePlatformError(error)}`,
+ );
}
}
diff --git a/apps/server/src/services/bot/platforms/discord/api.ts b/apps/server/src/services/bot/platforms/discord/api.ts
index 79556ac34eb..4f486218d54 100644
--- a/apps/server/src/services/bot/platforms/discord/api.ts
+++ b/apps/server/src/services/bot/platforms/discord/api.ts
@@ -224,6 +224,16 @@ export class DiscordApi {
});
}
+ /**
+ * Add a user to a thread. Members receive a notification and see the
+ * thread in their client regardless of whether the origin message's
+ * thread pill rendered (see LOBE-11632).
+ */
+ async addThreadMember(threadId: string, userId: string): Promise<void> {
+ log('addThreadMember: thread=%s, user=%s', threadId, userId);
+ await this.rest.put(Routes.threadMembers(threadId, userId));
+ }
+
// ==================== Message Operations ====================
async getMessages(
diff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.ts
index be49cd1b1e1..30b79ab426b 100644
--- a/apps/server/src/services/bot/platforms/discord/client.ts
+++ b/apps/server/src/services/bot/platforms/discord/client.ts
@@ -224,6 +224,26 @@ class DiscordGatewayClient implements PlatformClient {
};
}
+ /**
+ * Add the triggering user to the auto-created reply thread so Discord
+ * notifies them and the thread shows up in their client. Only applies to
+ * guild threads (4-segment composite); DMs and top-level channels deliver
+ * in place. Best-effort: a failure (missing permission, user left the
+ * guild) must never affect the reply flow.
+ */
+ async ensureThreadMember(platformThreadId: string, platformUserId: string): Promise<void> {
+ const parts = platformThreadId.split(':');
+ // Format: discord:guildId:channelId:discordThreadId
+ if (parts.length !== 4 || parts[1] === '@me' || !parts[3] || !platformUserId) return;
+
+ try {
+ await this.discord.addThreadMember(parts[3], platformUserId);
+ log('ensureThreadMember: added user %s to thread %s', platformUserId, parts[3]);
+ } catch (error) {
+ log('ensureThreadMember: failed (non-fatal): %O', error);
+ }
+ }
+
getMessenger(platformThreadId: string): PlatformMessenger {
const channelId = extractChannelId(platformThreadId);
const threadId = platformThreadId.split(':')[3];
@@ -302,8 +322,7 @@ class DiscordGatewayClient implements PlatformClient {
const directAttachments = (message as any).attachments as DirectAttachment[] | undefined;
const raw = (message as any).raw as Record<string, any> | undefined;
const refAttachments = raw?.referenced_message?.attachments as
- | DiscordRefAttachment[]
- | undefined;
+ DiscordRefAttachment[] | undefined;
log(
'extractFiles: msgId=%s, direct=%d, referenced=%d',
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index 7fec9e975db..63d96367392 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -193,6 +193,23 @@ export interface PlatformClient {
/** Create a Chat SDK adapter config for inbound message handling. */
createAdapter: () => Record<string, any>;
+ /**
+ * Ensure the triggering user is a member of the platform thread the bot
+ * replies in, so the platform pushes them a notification and surfaces the
+ * thread in their client.
+ *
+ * Discord: the auto-created per-mention reply thread never adds the
+ * mentioning user as a member β€” the reply lands in a thread the user is
+ * not notified about, and thread-pill rendering on the origin message has
+ * proven unreliable (LOBE-11632: two separate clients showed no pill for
+ * hours while the API said `HAS_THREAD`). Explicit membership bypasses
+ * both gaps. Best-effort β€” implementations must swallow failures.
+ *
+ * Platforms whose replies land directly in the conversation (Telegram,
+ * Slack channel replies, DMs) can omit this method.
+ */
+ ensureThreadMember?: (platformThreadId: string, platformUserId: string) => Promise<void>;
+
/**
* Read the inbound message author's preferred language from the platform
* payload (e.g. Telegram's `from.language_code`, Discord's `user.locale`).
diff --git a/src/server/agent-hono/handlers/botCallback.ts b/src/server/agent-hono/handlers/botCallback.ts
index e39d46d8748..bf2922ad16d 100644
--- a/src/server/agent-hono/handlers/botCallback.ts
+++ b/src/server/agent-hono/handlers/botCallback.ts
@@ -39,6 +39,15 @@ export async function botCallback(c: Context): Promise<Response> {
return c.json({ error: `Unknown callback type: ${type}` }, 400);
}
+ // console (not debug) for completions only: arrival of the final-reply
+ // callback must be provable from production logs (LOBE-11632) β€” the debug
+ // namespace above is not enabled in production, and steps are too chatty.
+ if (type === 'completion') {
+ console.info(
+ `[botCallback] completion received (operationId=${body.operationId}, thread=${platformThreadId}, reason=${body.reason}, contentLen=${typeof body.lastAssistantContent === 'string' ? body.lastAssistantContent.length : 0})`,
+ );
+ }
+
try {
const serverDB = await getServerDB();
const service = new BotCallbackService(serverDB);