🤯 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: harden bot messaging and channel setup (#19405)
Rdmclin2f2a0901ef1e0
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/botReplay.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/botReplay.test.tsnew file mode 100644index 00000000000..83e90d5af66--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/__tests__/botReplay.test.ts@@ -0,0 +1,29 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { botReplay } from '../botReplay';++const mockReplay = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/bot/deferredReplay', () => ({ runDeferredReplay: mockReplay }));++const target = { applicationId: 'app', platform: 'wechat', platformThreadId: 'wechat:single:user' };+const context = (body: unknown) =>+ ({+ json: (value: unknown, status = 200) => Response.json(value, { status }),+ req: { json: async () => body },+ }) as any;++beforeEach(() => {+ vi.resetAllMocks();+});+describe('bot replay endpoint', () => {+ it('returns a retryable status after a delivery error, then succeeds on retry', async () => {+ mockReplay.mockRejectedValueOnce(new Error('temporary')).mockResolvedValueOnce(undefined);+ expect((await botReplay(context({ payload: target }))).status).toBe(500);+ expect((await botReplay(context({ payload: target }))).status).toBe(200);+ expect(mockReplay).toHaveBeenCalledWith(target);+ });+ it('rejects malformed payloads before dispatch', async () => {+ expect((await botReplay(context({ payload: {} }))).status).toBe(400);+ expect(mockReplay).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/router-hono/agent/handlers/botReplay.ts b/apps/server/src/router-hono/agent/handlers/botReplay.tsnew file mode 100644index 00000000000..13ba2159edb--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/botReplay.ts@@ -0,0 +1,25 @@+import type { Context } from 'hono';+import { z } from 'zod';++import { runDeferredReplay } from '@/server/services/bot/deferredReplay';++const payloadSchema = z.object({+ payload: z.object({+ applicationId: z.string().min(1),+ messengerInstallationKey: z.string().min(1).optional(),+ platform: z.string().min(1),+ platformThreadId: z.string().min(1),+ }),+});++/** QStash retries this isolated delivery without repeating the final bot reply. */+export async function botReplay(c: Context): Promise<Response> {+ const body = payloadSchema.safeParse(await c.req.json().catch(() => null));+ if (!body.success) return c.json({ error: 'Invalid replay payload' }, 400);+ try {+ await runDeferredReplay(body.data.payload);+ return c.json({ success: true });+ } catch {+ return c.json({ error: 'Deferred replay failed' }, 500);+ }+}diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.tsindex 2bcb6f341f3..802a08f0812 100644--- a/apps/server/src/router-hono/agent/index.ts+++ b/apps/server/src/router-hono/agent/index.ts@@ -1,6 +1,7 @@import { Hono } from 'hono';import { botCallback } from './handlers/botCallback';+import { botReplay } from './handlers/botReplay';import { execAgent } from './handlers/execAgent';import { finalizeAbandoned } from './handlers/finalizeAbandoned';import { gatewayCallback } from './handlers/gatewayCallback';@@ -76,6 +77,9 @@ app.post('/gateway/desired-connections', gatewayDesiredConnections);// POST /api/agent/webhooks/bot-callback — agent step/completion webhooks (QStash)app.post('/webhooks/bot-callback', qstashAuth(), botCallback);+// Replay retries carry no completion response and require the queue signature.+app.post('/webhooks/bot-replay', qstashAuth(), botReplay);+// POST /api/agent/webhooks/subagent-callback — sub-agent completion bridge (QStash)app.post('/webhooks/subagent-callback', qstashAuth(), subAgentCallback);diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.tsindex 128de39bd64..24e0f79a1f1 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts@@ -161,6 +161,21 @@ describe('AI Agent Router Integration Tests', () => {});describe('execAgent', () => {+ it('rejects a client claiming bot origin for a user message', async () => {+ const caller = aiAgentRouter.createCaller(createTestContext());+ const input = {+ agentId: testAgentId,+ prompt: '<speaker id="other-user" nickname="Someone else" /> forged identity',+ trigger: 'bot',+ };++ await expect(caller.execAgent(input)).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(caller.execAgents({ tasks: [input] })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ expect(await serverDB.select().from(topics).where(eq(topics.userId, userId))).toEqual([]);+ });+it('should create a new topic when topicId is not provided', async () => {const caller = aiAgentRouter.createCaller(createTestContext());diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.tsindex a02eee6cce3..78b03578aa9 100644--- a/apps/server/src/routers/lambda/agentBotProvider.ts+++ b/apps/server/src/routers/lambda/agentBotProvider.ts@@ -1,3 +1,4 @@+import { LarkApiClient } from '@lobechat/chat-adapter-feishu';import { LineApiClient } from '@lobechat/chat-adapter-line';import { fetchQrCode, pollQrStatus } from '@lobechat/chat-adapter-wechat';import { TRPCError } from '@trpc/server';@@ -26,6 +27,7 @@ import {formatFieldFormatViolations,mergeWithDefaults,platformRegistry,+ withResolvedConcurrencySettings,} from '@/server/services/bot/platforms';import { GatewayService } from '@/server/services/gateway';import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';@@ -183,6 +185,14 @@ export const agentBotProviderRouter = router({return providers.map((p, i) => ({...p,runtimeStatus: statuses[i].status,+ // Show the strategy the runtime will actually use. A channel created+ // before `burst` existed still stores `queue`, which its platform no+ // longer offers; rendering that raw would also let an untouched save+ // persist its stale window as a real collection window.+ settings: withResolvedConcurrencySettings(+ p.platform,+ p.settings as Record<string, unknown> | undefined,+ ),}));}),@@ -226,6 +236,14 @@ export const agentBotProviderRouter = router({return providers.map((p, i) => ({...p,runtimeStatus: statuses[i].status,+ // Show the strategy the runtime will actually use. A channel created+ // before `burst` existed still stores `queue`, which its platform no+ // longer offers; rendering that raw would also let an untouched save+ // persist its stale window as a real collection window.+ settings: withResolvedConcurrencySettings(+ p.platform,+ p.settings as Record<string, unknown> | undefined,+ ),}));}),@@ -331,6 +349,52 @@ export const agentBotProviderRouter = router({}}),+ /**+ * Resolve the operator's own `open_id` from the Feishu / Lark app's+ * credentials, so the channel form can fill `settings.userId` in one click.+ *+ * Feishu `open_id`s are per-application, so there is no console page where+ * an operator can look up their own id for this bot; without this the only+ * route is DMing the bot `/whoami`. The app owner is the one personal+ * identity the platform will hand back to the app itself.+ *+ * The display name is best-effort on purpose: it needs a contact scope the+ * bot may not hold, and a missing name must not fail a lookup that already+ * succeeded. When it is there, the form can name who it filled in — an app+ * an admin created on someone else's behalf resolves to that admin, and the+ * operator has to notice that before saving.+ */+ feishuFetchOwnerId: authedProcedure+ .input(+ z.object({+ appId: z.string().min(1),+ appSecret: z.string().min(1),+ platform: z.enum(['feishu', 'lark']),+ }),+ )+ .mutation(async ({ input }) => {+ const api = new LarkApiClient(input.appId, input.appSecret, input.platform);+ try {+ const owner = await api.getAppOwnerId();+ if (!owner) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message:+ 'The app info carries no personal open_id for its owner or creator. Send /whoami to the bot instead.',+ });+ }+ const info = await api.getUserInfo(owner.openId).catch(() => null);+ return { name: info?.name, openId: owner.openId, source: owner.source };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message:+ error instanceof Error ? error.message : 'Failed to fetch app info from Feishu / Lark',+ });+ }+ }),+wechatGetQrCode: authedProcedure.mutation(async ({ ctx }) => {await assertBotFeatureAccess({action: 'manage',diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 93ed7c83d68..04586d2884a 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -1098,7 +1098,12 @@ const ExecAgentSchema = z* messages are the dominant caller. Pass a more specific value (`'cli'`,* `'openapi'`, `'eval'`, …) to override.*/- trigger: z.string().optional(),+ trigger: z+ .string()+ .refine((value) => value !== RequestTrigger.Bot, {+ message: 'The bot trigger is reserved for authenticated server-side bot ingress',+ })+ .optional(),/*** User intervention configuration for tool approvals.* Pass `{ approvalMode: 'headless' }` from headless clients (CLI, cron, bots)diff --git a/apps/server/src/routers/lambda/botMessage.ts b/apps/server/src/routers/lambda/botMessage.tsindex 17e3fad87a6..dcb8343ef4a 100644--- a/apps/server/src/routers/lambda/botMessage.ts+++ b/apps/server/src/routers/lambda/botMessage.ts@@ -71,6 +71,27 @@ const attachmentsInputSchema = z// one serverless request..max(10);+const embedsInputSchema = z.array(+ z+ .object({+ author: z+ .object({ icon_url: z.string().optional(), name: z.string(), url: z.string().optional() })+ .optional(),+ color: z.union([z.number(), z.string()]).optional(),+ description: z.string().optional(),+ fields: z+ .array(z.object({ inline: z.boolean().optional(), name: z.string(), value: z.string() }))+ .optional(),+ footer: z.object({ icon_url: z.string().optional(), text: z.string() }).optional(),+ image: z.object({ url: z.string() }).optional(),+ thumbnail: z.object({ url: z.string() }).optional(),+ timestamp: z.string().optional(),+ title: z.string().optional(),+ url: z.string().optional(),+ })+ .passthrough(),+);+// ── Service Factory ──────────────────────────────────────/**@@ -297,6 +318,7 @@ export const botMessageRouter = router({attachments: attachmentsInputSchema.optional(),botId: z.string().optional(),content: z.string(),+ embeds: embedsInputSchema.optional(),messengerInstallationId: z.string().optional(),userId: z.string(),})@@ -315,6 +337,7 @@ export const botMessageRouter = router({return service.sendDirectMessage({attachments: input.attachments,content: input.content,+ embeds: input.embeds,platform,userId: input.userId,});@@ -330,7 +353,7 @@ export const botMessageRouter = router({botId: z.string().optional(),channelId: z.string(),content: z.string(),- embeds: z.array(z.record(z.string(), z.unknown())).optional(),+ embeds: embedsInputSchema.optional(),messengerInstallationId: z.string().optional(),replyTo: z.string().optional(),})@@ -658,6 +681,7 @@ export const botMessageRouter = router({attachments: attachmentsInputSchema.optional(),botId: z.string().optional(),content: z.string(),+ embeds: embedsInputSchema.optional(),messengerInstallationId: z.string().optional(),threadId: z.string(),})@@ -670,6 +694,7 @@ export const botMessageRouter = router({return service.replyToThread({attachments: input.attachments,content: input.content,+ embeds: input.embeds,platform,threadId: input.threadId,});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 14328eb4718..3c01069b6e8 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -654,6 +654,7 @@ export class AiAgentService {appContext,autoStart = true,botContext,+ botSender,createdThreadId,clientIp,userAgent,@@ -969,6 +970,7 @@ export class AiAgentService {attachedFileIds,batchApprovalAnchorId,botContext,+ botSender,clientIds,continuationAssistantId,conversationAgentId,diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 8bbafc5cbab..c9dd7db8c6e 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -318,6 +318,7 @@ export interface TurnSetupInput {/** Spine anchor for a batch approval — overrides the assistant's parent. */batchApprovalAnchorId?: string;botContext?: InternalExecAgentParams['botContext'];+ botSender?: InternalExecAgentParams['botSender'];clientIds?: InternalExecAgentParams['clientIds'];/** Stable assistant id for a generic intervention continuation. */continuationAssistantId?: string;@@ -391,6 +392,7 @@ export const setupTurn = async (attachedFileIds,batchApprovalAnchorId,botContext,+ botSender,clientIds,continuationAssistantId,conversationAgentId,@@ -644,6 +646,9 @@ export const setupTurn = async (...(appContext?.conversationAgentId && appContext.scope === 'sub_agent'? { agentDispatch: { kind: 'callAgent' as const, visibility: 'internal' as const } }: undefined),+ // Bot-channel turns are inserted under the OWNER's userId; keep the real+ // platform author alongside so the UI can attribute the bubble correctly.+ ...(botSender ? { botSender } : undefined),};// Attachment ingestion: raw bot/IM `files` → S3, pre-uploadeddiff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.tsindex bffb225b3a6..dbd2415ace2 100644--- a/apps/server/src/services/aiAgent/types.ts+++ b/apps/server/src/services/aiAgent/types.ts@@ -1,5 +1,6 @@import type { BotPlatformContext } from '@lobechat/context-engine';import type {+ BotSenderMetadata,ChatTopicBotContext,ExecAgentParams,LobeAgentChatConfig,@@ -81,6 +82,11 @@ export interface InternalExecAgentParams extends ExecAgentParams {botContext?: ChatTopicBotContext;/** Bot platform context for injecting platform capabilities (e.g. markdown support) */botPlatformContext?: BotPlatformContext;+ /**+ * Real platform author of a bot-channel turn, persisted on the inbound user+ * message as `metadata.botSender` so the UI shows them instead of the owner.+ */+ botSender?: BotSenderMetadata;/*** chatConfig overrides (thinking / reasoning-effort extend params) merged over* the executing agent's own chatConfig, skipping nulled keys. Internal-only:diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.tsindex a0c13d1157f..cfd8c61ef76 100644--- a/apps/server/src/services/bot/AgentBridgeService.ts+++ b/apps/server/src/services/bot/AgentBridgeService.ts@@ -1,6 +1,6 @@import { MessageApiName } from '@lobechat/builtin-tool-message';import type { BotPlatformContext } from '@lobechat/context-engine';-import type { ChatTopicBotContext, ExecAgentResult } from '@lobechat/types';+import type { BotSenderMetadata, ChatTopicBotContext, ExecAgentResult } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import type { Message, SentMessage, Thread } from 'chat';import debug from 'debug';@@ -12,13 +12,17 @@ import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';import { createAbortError, isAbortError } from '@/server/services/agentRuntime/abort';import { AiAgentService } from '@/server/services/aiAgent';+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';import { GatewayService } from '@/server/services/gateway';import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewayClient';import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';import { SystemAgentService } from '@/server/services/systemAgent';import { createBotCompletionWebhook } from './createBotCompletionHook';-import { formatPrompt as formatPromptUtil } from './formatPrompt';+import { deferBotMessages, isDeferredMessagesAvailable } from './deferredMessages';+import { runDeferredReplay, scheduleDeferredReplay } from './deferredReplay';+import { buildBotSender, formatPrompt as formatPromptUtil } from './formatPrompt';+import { getSourceMessages } from './mergeMessages';import type { BotReplyLocale, PlatformClient } from './platforms';import {getBotReplyLocale,@@ -44,6 +48,12 @@ import {const log = debug('lobe-server:bot:agent-bridge');+/**+ * `acquireTopicStartReservation` gives up with this message when the topic's+ * `runningOperation` stayed alive through its bounded backoff.+ */+const isTopicBusyError = (errMsg: string): boolean => errMsg.includes('remained busy');+/*** Convert hook-event JSON-safe attachments (`{ data?: base64, fetchUrl? }`)* into chat-sdk `Attachment` shape (`{ data?: Buffer, url? }`) so they can@@ -668,6 +678,22 @@ export class AgentBridgeService {await thread.setState({ ...threadState, topicId: undefined });return this.handleMention(thread, message, opts);}++ // In queue mode the previous run may still be executing on the job+ // queue even though the thread lock and `activeThreads` were released+ // at handoff. Starting a second run now would lose the topic-start+ // reservation race and surface as "Agent Execution Failed" — the+ // WeChat "one image + one sentence" case. Park the message instead;+ // the completion callback replays it once the topic is idle.+ const runningOperation = existingTopic.metadata?.runningOperation;+ if (+ runningOperation &&+ isQueueAgentRuntimeEnabled() &&+ (await topicModel.isRunningOperationAlive(this.db, runningOperation))+ ) {+ const deferred = await this.deferWhileTopicBusy(thread, message, botContext, topicId);+ if (deferred) return;+ }} catch (error) {log('handleSubscribedMessage: stale-topic lookup failed, continuing with existing topicId=%s: %O',@@ -737,6 +763,15 @@ export class AgentBridgeService {return this.handleMention(thread, message, opts);}+ // The pre-flight liveness check above and the reservation are not+ // atomic: a run that started between them still makes the+ // reservation give up with "remained busy". Same remedy — park the+ // message for replay instead of telling the user the agent failed.+ if (queueMode && isTopicBusyError(errMsg)) {+ const deferred = await this.deferWhileTopicBusy(thread, message, botContext, topicId);+ if (deferred) return;+ }+const operationId = AgentBridgeService.activeOperations.get(thread.id);log('handleSubscribedMessage error: operationId=%s, %O', operationId, error);try {@@ -970,6 +1005,9 @@ export class AgentBridgeService {const { files, warnings: fileWarnings } = await this.resolveFiles(userMessage, client);const prompt = this.formatPrompt(userMessage, client);+ const botSender = botContext?.platform+ ? buildBotSender(userMessage as any, botContext.platform)+ : undefined;// Attach file warnings to botPlatformContext for injection via context engineif (fileWarnings?.length && botPlatformContext) {@@ -1019,6 +1057,7 @@ export class AgentBridgeService {agentId,botContext,botPlatformContext,+ botSender,callbackUrl,channelContext,client,@@ -1038,6 +1077,7 @@ export class AgentBridgeService {agentId,botContext,botPlatformContext,+ botSender,callbackUrl,charLimit,channelContext,@@ -1067,6 +1107,7 @@ export class AgentBridgeService {agentId: string;botContext?: ChatTopicBotContext;botPlatformContext?: BotPlatformContext;+ botSender?: BotSenderMetadata;callbackUrl: string;channelContext?: DiscordChannelContext;client?: PlatformClient;@@ -1084,6 +1125,7 @@ export class AgentBridgeService {agentId,botContext,botPlatformContext,+ botSender,callbackUrl,channelContext,client,@@ -1106,6 +1148,7 @@ export class AgentBridgeService {autoStart: true,botContext,botPlatformContext,+ botSender,discordContext: channelContext? {channel: channelContext.channel,@@ -1171,6 +1214,12 @@ export class AgentBridgeService {if (errMsg.includes('Topic not found')) {throw error;}+ // The topic-start reservation lost against a still-running operation.+ // Rethrow so handleSubscribedMessage can defer the message for replay+ // after that run completes instead of posting a failure.+ if (isTopicBusyError(errMsg)) {+ throw error;+ }await this.finishStartupFailure({client,@@ -1232,6 +1281,7 @@ export class AgentBridgeService {agentId: string;botContext?: ChatTopicBotContext;botPlatformContext?: BotPlatformContext;+ botSender?: BotSenderMetadata;callbackUrl: string;charLimit?: number;channelContext?: DiscordChannelContext;@@ -1253,6 +1303,7 @@ export class AgentBridgeService {agentId,botContext,botPlatformContext,+ botSender,callbackUrl,charLimit,channelContext,@@ -1303,6 +1354,7 @@ export class AgentBridgeService {autoStart: true,botContext,botPlatformContext,+ botSender,discordContext: channelContext? {channel: channelContext.channel,@@ -1770,10 +1822,91 @@ export class AgentBridgeService {}>;warnings?: string[];}> {- const result = await client?.extractFiles?.(message);- if (!result) return {};- if (Array.isArray(result)) return { files: result };- return { files: result.files, warnings: result.warnings };+ if (!client?.extractFiles) return {};++ // A merged message (Chat SDK queue/debounce `skipped` context, or a+ // deferred-message replay) carries only the LAST message's `raw`, but+ // every platform's `extractFiles` reads media descriptors from `raw`. Walk+ // each source message so an image that arrived one message before the+ // text is still downloaded.+ const sources = getSourceMessages(message);+ const files: AttachmentSource[] = [];+ const warnings: string[] = [];+ let sawResult = false;++ for (const source of sources) {+ const result = await client.extractFiles(source);+ if (!result) continue;+ sawResult = true;+ if (Array.isArray(result)) {+ files.push(...result);+ continue;+ }+ if (result.files) files.push(...result.files);+ if (result.warnings) warnings.push(...result.warnings);+ }++ if (!sawResult) return {};+ return {+ files,+ ...(warnings.length > 0 ? { warnings } : {}),+ };+ }++ /**+ * Park an inbound follow-up whose topic is still running so the completion+ * callback can replay it. Returns `false` when deferral is impossible (no+ * bot context, no Redis) — the caller then keeps the previous behavior.+ */+ private async deferWhileTopicBusy(+ thread: Thread<ThreadState>,+ message: Message,+ botContext: ChatTopicBotContext | undefined,+ topicId: string,+ ): Promise<boolean> {+ if (!botContext?.applicationId) return false;+ if (!isDeferredMessagesAvailable()) return false;++ // Store the individual sources of a merged message so each keeps its own+ // `raw` (media descriptors) across the Redis round-trip.+ const deferred = await deferBotMessages(+ botContext.applicationId,+ thread.id,+ getSourceMessages(message),+ );+ if (!deferred) return false;++ // Completion may have drained the queue between the initial liveness+ // check and this write. Recheck after enqueueing and initiate replay when+ // no live operation remains; the callback covers completion after this check.+ const target = {+ applicationId: botContext.applicationId,+ messengerInstallationKey: botContext.messengerInstallationKey,+ platform: botContext.platform,+ platformThreadId: thread.id,+ };+ try {+ const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);+ const topic = await topicModel.findById(topicId);+ const running = topic?.metadata?.runningOperation;+ if (!running || !(await topicModel.isRunningOperationAlive(this.db, running))) {+ await runDeferredReplay(target);+ }+ } catch (error) {+ log('Post-enqueue replay failed for thread=%s: %O', thread.id, error);+ try {+ await scheduleDeferredReplay(target, `defer:${message.id}`);+ } catch (scheduleError) {+ log('Could not schedule deferred replay for thread=%s: %O', thread.id, scheduleError);+ }+ }++ log(+ 'handleSubscribedMessage: topic busy, deferred message=%s on thread=%s until the running operation completes',+ message.id,+ thread.id,+ );+ return true;}/**diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.tsindex 9cdc70c714e..d4d3100eda9 100644--- a/apps/server/src/services/bot/BotCallbackService.ts+++ b/apps/server/src/services/bot/BotCallbackService.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import type { ChatErrorBudgetContext } from '@lobechat/types';import debug from 'debug';@@ -16,6 +18,7 @@ import { messengerPlatformRegistry } from '@/server/services/messenger/platformsimport { SystemAgentService } from '@/server/services/systemAgent';import { AgentBridgeService } from './AgentBridgeService';+import { runDeferredReplay, scheduleDeferredReplay } from './deferredReplay';import type {BotMessageAttachment,BotReplyLocale,@@ -218,6 +221,42 @@ export class BotCallbackService {{ ...body, workspaceId: body.workspaceId ?? workspaceId ?? undefined },messenger,);+ // The topic is idle now — replay any follow-up the bridge parked while+ // this run was executing (WeChat "one image + one sentence" arrives as+ // two messages; the second used to fail the topic-start reservation).+ await this.replayDeferredMessages(+ platform,+ applicationId,+ platformThreadId,+ messengerInstallationKey,+ body.operationId ?? randomUUID(),+ );+ }+ }++ private async replayDeferredMessages(+ platform: string,+ applicationId: string,+ platformThreadId: string,+ messengerInstallationKey: string | undefined,+ replayId: string,+ ): Promise<void> {+ const target = { applicationId, messengerInstallationKey, platform, platformThreadId };+ try {+ await runDeferredReplay(target);+ } catch (error) {+ log('replayDeferredMessages failed for thread=%s: %O', platformThreadId, error);+ // Only the replay job retries. Redelivering this completion would post+ // the already-delivered final response again.+ try {+ await scheduleDeferredReplay(target, replayId);+ } catch (scheduleError) {+ log(+ 'Could not schedule deferred replay for thread=%s: %O',+ platformThreadId,+ scheduleError,+ );+ }}}diff --git a/apps/server/src/services/bot/BotMessageRouter.ts b/apps/server/src/services/bot/BotMessageRouter.tsindex a50aca88b47..dd8c784ba68 100644--- a/apps/server/src/services/bot/BotMessageRouter.ts+++ b/apps/server/src/services/bot/BotMessageRouter.ts@@ -1,5 +1,4 @@import { createIoRedisState } from '@chat-adapter/state-ioredis';-import { DEFAULT_BOT_DEBOUNCE_MS } from '@lobechat/const';import type { Message, MessageContext, WebhookOptions } from 'chat';import { Chat, ConsoleLogger } from 'chat';import debug from 'debug';@@ -19,6 +18,7 @@ import { AiAgentService } from '@/server/services/aiAgent';import { AgentBridgeService } from './AgentBridgeService';import { buildBotContext } from './buildBotContext';+import { replayDeferredBotMessages } from './deferredMessages';import {createOrGetPairingRequest,deletePairingRequest,@@ -26,6 +26,8 @@ import {releasePairingClaim,} from './dmPairingStore';import { submitBotFeedback } from './feedbackSubmit';+import { buildReplayMessages, getSameSenderMessages, mergeBotMessages } from './mergeMessages';+import { patchSenderBatches } from './patchSenderBatches';import {type BotPlatformRuntimeContext,type BotReplyLocale,@@ -48,6 +50,7 @@ import {type PlatformClient,type PlatformDefinition,platformRegistry,+ resolveBotConcurrency,resolveBotProviderConfig,shouldAllowSender,shouldHandleDm,@@ -70,6 +73,7 @@ import {renderInlineError,renderModeStatus,renderSenderRejected,+ renderWhoami,} from './replyTemplate';/** Minimum gap between two webhook re-registrations for the same bot. */@@ -119,6 +123,8 @@ interface ResolvedAgentInfo {}interface RegisteredBot {+ /** Chat SDK adapters keyed by platform id, as passed to the `Chat` config. */+ adapters: Record<string, any>;agentInfo: ResolvedAgentInfo;chatBot: Chat<any>;client: PlatformClient;@@ -170,6 +176,14 @@ interface CommandContext {/** A single bot command definition.* Add new entries to `buildCommands()` to register additional commands. */interface BotCommand {+ /**+ * Skip the allowFrom / DM-policy / group-policy gate for this command.+ * Reserved for commands with no side effects that only reveal the+ * caller's own data (e.g. `/whoami`), so an operator who hasn't filled in+ * `settings.userId` yet can still discover it under a `pairing` /+ * `allowlist` / `disabled` DM policy that would otherwise lock them out.+ */+ bypassGate?: boolean;description: string;handler: (ctx: CommandContext) => Promise<void>;name: string;@@ -458,19 +472,22 @@ export class BotMessageRouter {workspaceId: workspaceId ?? undefined,});- // Default to 'queue' for legacy providers that don't have `concurrency`- // in their saved settings. Historically this defaulted to 'debounce', but- // chat-sdk's debounce semantics are "drop all but the latest" (Lodash-style),- // which silently evicts media messages when followed by a quick text query.- // 'queue' preserves all pending messages and merges them via- // `mergeSkippedMessages`, which is the right default for chat UX.- const concurrencyStrategy = (settings.concurrency as string) || 'queue';- const debounceMs = (settings.debounceMs as number) || DEFAULT_BOT_DEBOUNCE_MS;+ // 'queue' stays the fallback for channels that never picked a strategy:+ // it preserves every pending message and merges them via+ // `mergeSkippedMessages`. Platforms that split one logical turn across+ // several messages need the window BEFORE the first dispatch instead —+ // see `resolveBotConcurrency`, which also rescues channels created before+ // 'burst' existed in chat-sdk 4.29.+ const { debounceMs, strategy } = resolveBotConcurrency(platform, settings);const chatBot = this.createChatBot(adapters,`agent-${agentId}`,- concurrencyStrategy,+ strategy,debounceMs,+ (message) => {+ const text = client.sanitizeUserInput?.(message.text ?? '') ?? message.text;+ return BotMessageRouter.dispatchTextCommand(text, commands) !== null;+ },);this.registerHandlers(chatBot, serverDB, client, commands, {agentId,@@ -496,6 +513,7 @@ export class BotMessageRouter {}const registered: RegisteredBot = {+ adapters,agentInfo: { agentId, userId, workspaceId: workspaceId ?? undefined },chatBot,client,@@ -552,11 +570,19 @@ export class BotMessageRouter {label: string,concurrencyStrategy: string,debounceMs: number,+ isCommand: (message: Message) => boolean,): Chat<any> {const config: any = {adapters,+ // `burst` and `debounce` both wait `debounceMs` before dispatching; they+ // differ in what happens to the earlier messages in that window. `burst`+ // hands them to the handler as `context.skipped`, which+ // `mergeSkippedMessages` folds into one turn; `debounce` drops them.+ // Anything else keeps the plain queue, which dispatches immediately.concurrency:- concurrencyStrategy === 'debounce' ? { debounceMs, strategy: 'debounce' } : 'queue',+ concurrencyStrategy === 'burst' || concurrencyStrategy === 'debounce'+ ? { debounceMs, strategy: concurrencyStrategy }+ : 'queue',userName: `lobehub-bot-${label}`,};@@ -569,7 +595,9 @@ export class BotMessageRouter {});}- return new Chat(config);+ const bot = new Chat(config);+ patchSenderBatches(bot, isCommand);+ return bot;}/**@@ -581,19 +609,35 @@ export class BotMessageRouter {message: Message,context?: { skipped?: Message[] },): Message {- if (!context?.skipped?.length) return message;-// context.skipped is chronological; current message is the latest- const allMessages = [...context.skipped, message];- const mergedText = allMessages- .map((m) => m.text)- .filter(Boolean)- .join('\n');- const mergedAttachments = allMessages.flatMap((m) => (m as any).attachments || []);-- return Object.assign(Object.create(Object.getPrototypeOf(message)), message, {- attachments: mergedAttachments,- text: mergedText,+ return mergeBotMessages(message, context?.skipped);+ }++ /**+ * Re-dispatch the messages that `AgentBridgeService` parked while this+ * thread's topic was still running. Called by `BotCallbackService` once the+ * completion callback lands, so the follow-up ("one sentence" after "one+ * image" on WeChat) becomes the next turn instead of a failed start.+ *+ * Each original message goes through `Chat.processMessage`, i.e. the same+ * subscription / mention / command routing as a live webhook delivery.+ */+ async replayDeferredMessages(+ platform: string,+ applicationId: string,+ platformThreadId: string,+ ): Promise<void> {+ await replayDeferredBotMessages(applicationId, platformThreadId, async (entries) => {+ const bot = await this.getOrCreateBot(platform, applicationId);+ const adapter = bot?.adapters[platform];+ if (!bot || !adapter) throw new Error(`Bot adapter unavailable for ${platform}`);+ const results = await Promise.allSettled(+ buildReplayMessages(entries).map((message) =>+ bot.chatBot.processMessage(adapter, platformThreadId, message),+ ),+ );+ const failure = results.find((result) => result.status === 'rejected');+ if (failure?.status === 'rejected') throw failure.reason;});}@@ -957,10 +1001,17 @@ export class BotMessageRouter {text: string | undefined,author: { userId?: string; userName?: string } | undefined,replyLocale: BotReplyLocale,+ /**+ * `ungatedOnly` restricts dispatch to `bypassGate` commands. Callers+ * run it once BEFORE `passGatesOrNotify` (so `/whoami` answers even+ * when the sender would be rejected) and once after for the rest.+ */+ options?: { ungatedOnly?: boolean },): Promise<boolean> => {const sanitized = client.sanitizeUserInput?.(text ?? '') ?? text;const result = BotMessageRouter.dispatchTextCommand(sanitized, commands);if (!result) return false;+ if (options?.ungatedOnly && !result.command.bypassGate) return false;await result.command.handler({args: result.args,authorUserId: author?.userId,@@ -1213,13 +1264,37 @@ export class BotMessageRouter {return { count: participants.length + 1, isNewParticipant: true };};+ const trackThreadParticipants = async (+ thread: { id: string; isDM?: boolean },+ messages: readonly Message[],+ ): Promise<{ count: number; isNewParticipant: boolean }> => {+ let count = 0;+ let isNewParticipant = false;+ for (const candidate of messages) {+ const tracked = await trackThreadParticipant(thread, candidate);+ count = Math.max(count, tracked.count);+ isNewParticipant ||= tracked.isNewParticipant;+ }+ return { count, isNewParticipant };+ };+bot.onNewMention(async (thread, message, context?: MessageContext) => {const replyLocale = detectReplyLocale(message);// Record the original @mentioner so the first follow-up in// `onSubscribedMessage` recognises them as participant #1 instead of// a "newcomer" — otherwise count would be 0 at that moment and the// single-user-relaxation logic wouldn't kick in.- await trackThreadParticipant(thread, message);+ await trackThreadParticipants(thread, [...(context?.skipped ?? []), message]);++ // Side-effect-free `bypassGate` commands (`/whoami`) answer before the+ // gate so a not-yet-configured operator can discover their own ID.+ if (+ await tryDispatch(thread, message.text, message.author, replyLocale, {+ ungatedOnly: true,+ })+ ) {+ return;+ }// Gate first — must run before tryDispatch so a /command from a// non-allowlisted sender can't slip through and side-effect.@@ -1311,6 +1386,14 @@ export class BotMessageRouter {});bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {+ // Queue/debounce only dispatches the latest message as `message`; every+ // earlier arrival is preserved in `context.skipped`. Track all of them+ // before any early return so bot primaries and ignored chatter cannot+ // hide human participants from the mention-only transition.+ const { count: humanCount } = await trackThreadParticipants(thread, [+ ...(context?.skipped ?? []),+ message,+ ]);if (message.author.isBot === true) return;const replyLocale = detectReplyLocale(message);@@ -1340,11 +1423,10 @@ export class BotMessageRouter {//// Participants are tracked either way so the announcement gate below can// still see the 1-human-vs-many transition.- const { count: humanCount } = await trackThreadParticipant(thread, message);const isExplicitlyAddressed =thread.isDM ||message.isMention === true ||- context?.skipped?.some((m) => m.isMention === true) === true;+ getSameSenderMessages(message, context?.skipped).some((m) => m.isMention === true) === true;// Only consult membership when it can change the outcome: a DM or an// @-mention is addressed to the bot regardless, and the platform lookup// behind `isSoloBotConversation` is a network round-trip whenever its@@ -1359,6 +1441,8 @@ export class BotMessageRouter {}): humanCount <= 1);const isAddressedToBot = isExplicitlyAddressed || isSoloBotConversation;+ const platformReportsShared =+ !isExplicitlyAddressed && !!client.isSoloBotConversation && !isSoloBotConversation;const isCommand = looksLikeCommand(message.text);// operator-configured keyword match also wakes the bot in a// subscribed group thread. Skipped (debounced) siblings are inspected@@ -1367,8 +1451,9 @@ export class BotMessageRouter {const matchesWatchKeyword =watchKeywords.length > 0 &&(messageMatchesWatchKeyword(message.text, watchKeywords) ||- context?.skipped?.some((m) => messageMatchesWatchKeyword(m.text, watchKeywords)) ===- true);+ getSameSenderMessages(message, context?.skipped).some((m) =>+ messageMatchesWatchKeyword(m.text, watchKeywords),+ ) === true);if (!isAddressedToBot && !isCommand && !matchesWatchKeyword) {log(@@ -1381,7 +1466,7 @@ export class BotMessageRouter {// first skip in this thread → tell participants the bot// is now mention-only so newcomers don't think it broke. Dedupe by// thread id so we never announce more than once.- if (!thread.isDM && humanCount >= 2) {+ if (!thread.isDM && (humanCount >= 2 || platformReportsShared)) {try {const fresh = await bot.getState()@@ -1410,6 +1495,16 @@ export class BotMessageRouter {);}+ // Side-effect-free `bypassGate` commands (`/whoami`) answer before the+ // gate so a not-yet-configured operator can discover their own ID.+ if (+ await tryDispatch(thread, message.text, message.author, replyLocale, {+ ungatedOnly: true,+ })+ ) {+ return;+ }+// Gate before tryDispatch so a /command from a non-allowlisted sender// (or in a disabled DM/group scope) cannot side-effect.if (!(await passGatesOrNotify(thread, message.author, replyLocale, 'onSubscribedMessage'))) {@@ -1572,8 +1667,9 @@ export class BotMessageRouter {!isDM &&keywordCatchAllEnabled &&(messageMatchesWatchKeyword(message.text, watchKeywords) ||- context?.skipped?.some((m) => messageMatchesWatchKeyword(m.text, watchKeywords)) ===- true);+ getSameSenderMessages(message, context?.skipped).some((m) =>+ messageMatchesWatchKeyword(m.text, watchKeywords),+ ) === true);// If neither path applies, return so the regex doesn't act as a// channel-wide hijack. DMs still need the dmCatchAllEnabled gate@@ -2072,6 +2168,38 @@ export class BotMessageRouter {},name: 'feedback',},+ {+ // Ungated on purpose: the whole point is to let the operator learn+ // the value for `settings.userId` before it is configured, and the+ // reply contains nothing but the caller's own identity.+ bypassGate: true,+ description: 'Show your platform user ID for the bot settings',+ handler: async (ctx) => {+ log(+ 'command /whoami: agent=%s, platform=%s, author=%s',+ agentId,+ platform,+ ctx.authorUserName ?? ctx.authorUserId,+ );+ const reply = ctx.postEphemeral ?? ctx.post;+ const callerId = ctx.authorUserId?.trim();+ if (!callerId) {+ await reply(renderCommandReply('cmdWhoamiUnavailable', ctx.replyLocale));+ return;+ }+ await reply(+ renderWhoami(+ {+ isOperator: !!operatorUserId && callerId === operatorUserId,+ userId: callerId,+ userName: ctx.authorUserName,+ },+ ctx.replyLocale,+ ),+ );+ },+ name: 'whoami',+ },];}@@ -2137,7 +2265,10 @@ export class BotMessageRouter {userName: event.user?.userName,};const replyLocale = locale.fallback;- if (!(await gate(threadLike, authorLike, replyLocale, `onSlashCommand /${cmd.name}`))) {+ if (+ !cmd.bypassGate &&+ !(await gate(threadLike, authorLike, replyLocale, `onSlashCommand /${cmd.name}`))+ ) {return;}await cmd.handler({@@ -2182,6 +2313,7 @@ export class BotMessageRouter {if (!result) return;const replyLocale = locale.detectFromMessage(message);if (+ !result.command.bypassGate &&!(await gate(thread, message.author, replyLocale, `onNewMessage /${result.command.name}`))) {return;diff --git a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts b/apps/server/src/services/bot/__tests__/AgentBridgeService.test.tsindex 1455b167144..95d320a2129 100644--- a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts+++ b/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts@@ -6,15 +6,33 @@ const mockFormatPrompt = vi.hoisted(() => vi.fn());const mockGetPlatform = vi.hoisted(() => vi.fn());const mockIsQueueAgentRuntimeEnabled = vi.hoisted(() => vi.fn());const mockTopicFindById = vi.hoisted(() => vi.fn());+const mockIsRunningOperationAlive = vi.hoisted(() => vi.fn());+const mockDeferBotMessages = vi.hoisted(() => vi.fn());+const mockIsDeferredMessagesAvailable = vi.hoisted(() => vi.fn());++const mockReplayBot = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const mockReplayMessenger = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock('../BotMessageRouter', () => ({+ getBotMessageRouter: () => ({ replayDeferredMessages: mockReplayBot }),+}));+vi.mock('@/server/services/messenger/MessengerRouter', () => ({+ getMessengerRouter: () => ({ replayDeferredMessages: mockReplayMessenger }),+}));vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(function () {return {findById: mockTopicFindById,+ isRunningOperationAlive: mockIsRunningOperationAlive,};}),}));+vi.mock('@/server/services/bot/deferredMessages', () => ({+ deferBotMessages: mockDeferBotMessages,+ isDeferredMessagesAvailable: mockIsDeferredMessagesAvailable,+}));+vi.mock('@/database/models/user', () => ({UserModel: vi.fn().mockImplementation(function () {return {@@ -51,6 +69,11 @@ vi.mock('@/server/services/systemAgent', () => ({}));vi.mock('@/server/services/bot/formatPrompt', () => ({+ buildBotSender: vi.fn((message: any, platform: string) => ({+ fullName: message?.author?.fullName,+ id: message?.author?.userId,+ platform,+ })),formatPrompt: mockFormatPrompt,}));@@ -135,6 +158,9 @@ describe('AgentBridgeService', () => {id: 'topic-1',updatedAt: new Date(),});+ mockIsRunningOperationAlive.mockResolvedValue(false);+ mockIsDeferredMessagesAvailable.mockReturnValue(true);+ mockDeferBotMessages.mockResolvedValue(true);});it('calls execAgent with hooks in queue mode for mention', async () => {@@ -641,6 +667,165 @@ describe('AgentBridgeService', () => {});});+ describe('follow-up while the topic is still running', () => {+ // Regression for WeChat "one image + one sentence": the two arrive as+ // separate messages, and in queue mode the second one landed while the+ // first run was still executing on the job queue. It lost the topic-start+ // reservation race and the user saw "Agent Execution Failed".+ const busyTopic = {+ agentId: 'agent-1',+ id: 'topic-1',+ metadata: { runningOperation: { assistantMessageId: 'a-1', operationId: 'op-running' } },+ updatedAt: new Date(),+ };+ const opts = () => ({+ agentId: 'agent-1',+ botContext: {+ applicationId: 'app-1',+ platform: 'wechat',+ platformThreadId: THREAD_ID,+ } as any,+ client: createClient(),+ });++ it('defers the message instead of starting a second run when the topic is busy', async () => {+ mockTopicFindById.mockResolvedValue(busyTopic);+ mockIsRunningOperationAlive.mockResolvedValue(true);+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ const thread = createThread({ topicId: 'topic-1' });+ const message = createMessage();++ await service.handleSubscribedMessage(thread, message, opts());++ expect(mockIsRunningOperationAlive).toHaveBeenCalledWith(+ FAKE_DB,+ busyTopic.metadata.runningOperation,+ );+ expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [message]);+ expect(mockExecAgent).not.toHaveBeenCalled();+ expect(thread.post).not.toHaveBeenCalled();+ });++ it('defers each source of a merged message so every raw survives the round-trip', async () => {+ mockTopicFindById.mockResolvedValue(busyTopic);+ mockIsRunningOperationAlive.mockResolvedValue(true);+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ const image = { id: 'img', raw: { item: 'image' }, text: '' } as any;+ const text = { id: 'txt', raw: { item: 'text' }, text: 'hi' } as any;+ const merged = { ...text, sourceMessages: [image, text] } as any;++ await service.handleSubscribedMessage(createThread({ topicId: 'topic-1' }), merged, opts());++ expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [image, text]);+ });++ it.each([false, true])(+ 'replays when completion wins the enqueue race (messenger=%s)',+ async (messenger) => {+ mockTopicFindById+ .mockResolvedValueOnce(busyTopic)+ .mockResolvedValueOnce({ ...busyTopic, metadata: {} });+ mockIsRunningOperationAlive.mockResolvedValue(true);+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ const options = opts();+ if (messenger) options.botContext.messengerInstallationKey = 'wechat:example';+ await service.handleSubscribedMessage(+ createThread({ topicId: 'topic-1' }),+ createMessage(),+ options,+ );+ expect(mockDeferBotMessages).toHaveBeenCalledTimes(1);+ expect(messenger ? mockReplayMessenger : mockReplayBot).toHaveBeenCalledWith(+ messenger ? 'wechat:example' : 'wechat',+ 'app-1',+ THREAD_ID,+ );+ expect(mockExecAgent).not.toHaveBeenCalled();+ },+ );++ it('runs normally when the marker is stale (operation no longer alive)', async () => {+ mockTopicFindById.mockResolvedValue(busyTopic);+ mockIsRunningOperationAlive.mockResolvedValue(false);+ const service = new AgentBridgeService(FAKE_DB, USER_ID);++ await service.handleSubscribedMessage(+ createThread({ topicId: 'topic-1' }),+ createMessage(),+ opts(),+ );++ expect(mockDeferBotMessages).not.toHaveBeenCalled();+ expect(mockExecAgent).toHaveBeenCalledTimes(1);+ });++ it('keeps the previous behavior outside queue mode (SDK lock serializes runs)', async () => {+ mockIsQueueAgentRuntimeEnabled.mockReturnValue(false);+ mockTopicFindById.mockResolvedValue(busyTopic);+ mockIsRunningOperationAlive.mockResolvedValue(true);+ const service = new AgentBridgeService(FAKE_DB, USER_ID);++ await service.handleSubscribedMessage(+ createThread({ topicId: 'topic-1' }),+ createMessage(),+ opts(),+ );++ expect(mockDeferBotMessages).not.toHaveBeenCalled();+ expect(mockExecAgent).toHaveBeenCalledTimes(1);+ });++ it('falls back to running when deferral is unavailable (no Redis)', async () => {+ mockTopicFindById.mockResolvedValue(busyTopic);+ mockIsRunningOperationAlive.mockResolvedValue(true);+ mockIsDeferredMessagesAvailable.mockReturnValue(false);+ const service = new AgentBridgeService(FAKE_DB, USER_ID);++ await service.handleSubscribedMessage(+ createThread({ topicId: 'topic-1' }),+ createMessage(),+ opts(),+ );++ expect(mockDeferBotMessages).not.toHaveBeenCalled();+ expect(mockExecAgent).toHaveBeenCalledTimes(1);+ });++ it('defers when the reservation still reports the topic busy (check/reserve race)', async () => {+ mockExecAgent.mockRejectedValueOnce(+ new Error('Topic topic-1 remained busy while starting operation agent-start-x'),+ );+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ const thread = createThread({ topicId: 'topic-1' });+ const message = createMessage();++ await service.handleSubscribedMessage(thread, message, opts());++ expect(mockDeferBotMessages).toHaveBeenCalledWith('app-1', THREAD_ID, [message]);+ // No "Agent Execution Failed" for the user (only the start ack was posted).+ expect(thread.post).not.toHaveBeenCalledWith(+ expect.objectContaining({ markdown: expect.stringContaining('执行失败') }),+ );+ expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);+ });++ it('still surfaces the busy error when it cannot defer', async () => {+ mockIsDeferredMessagesAvailable.mockReturnValue(false);+ mockExecAgent.mockRejectedValueOnce(+ new Error('Topic topic-1 remained busy while starting operation agent-start-x'),+ );+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ const thread = createThread({ topicId: 'topic-1' });++ await service.handleSubscribedMessage(thread, createMessage(), opts());++ expect(mockDeferBotMessages).not.toHaveBeenCalled();+ expect(thread.post).toHaveBeenCalledWith(+ expect.objectContaining({ markdown: expect.stringContaining('执行失败') }),+ );+ });+ });+describe('resolveFiles dispatcher', () => {// The bridge no longer has its own attachment extraction logic — every// platform owns its own `client.extractFiles`. resolveFiles is just a@@ -695,5 +880,33 @@ describe('AgentBridgeService', () => {expect(clientExtractFiles).toHaveBeenCalledTimes(1);expect(result).toEqual({ files: [] });});++ it('extracts files from every source of a merged message', async () => {+ // A merged message keeps only the LAST raw; the image that arrived one+ // message earlier must still be downloaded from its own raw.+ const image = { id: 'img', raw: { item: 'image' }, text: '' } as any;+ const text = { id: 'txt', raw: { item: 'text' }, text: 'hi' } as any;+ const merged = { ...text, sourceMessages: [image, text] } as any;+ const clientExtractFiles = vi+ .fn()+ .mockImplementation(async (m: any) =>+ m.id === 'img'+ ? { files: [{ buffer: Buffer.from('jpg'), name: 'image.jpg' }], warnings: ['w1'] }+ : undefined,+ );+ const service = new AgentBridgeService(FAKE_DB, USER_ID);++ const result = await (service as any).resolveFiles(merged, {+ extractFiles: clientExtractFiles,+ });++ expect(clientExtractFiles).toHaveBeenCalledTimes(2);+ expect(clientExtractFiles).toHaveBeenNthCalledWith(1, image);+ expect(clientExtractFiles).toHaveBeenNthCalledWith(2, text);+ expect(result).toEqual({+ files: [{ buffer: Buffer.from('jpg'), name: 'image.jpg' }],+ warnings: ['w1'],+ });+ });});});diff --git a/apps/server/src/services/bot/__tests__/BotCallbackService.test.ts b/apps/server/src/services/bot/__tests__/BotCallbackService.test.tsindex 1988bbc4de5..e90a99cf9bb 100644--- a/apps/server/src/services/bot/__tests__/BotCallbackService.test.ts+++ b/apps/server/src/services/bot/__tests__/BotCallbackService.test.ts@@ -112,6 +112,17 @@ vi.mock('../AgentBridgeService', () => ({},}));+const mockBotRouterReplay = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const mockMessengerRouterReplay = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));++vi.mock('../BotMessageRouter', () => ({+ getBotMessageRouter: () => ({ replayDeferredMessages: mockBotRouterReplay }),+}));++vi.mock('@/server/services/messenger/MessengerRouter', () => ({+ getMessengerRouter: () => ({ replayDeferredMessages: mockMessengerRouterReplay }),+}));+vi.mock('@/server/services/gateway/MessageGatewayClient', () => ({getMessageGatewayClient: vi.fn().mockReturnValue({isConfigured: false,@@ -216,6 +227,12 @@ function makeTelegramBody(overrides: Partial<BotCallbackBody> = {}): BotCallback// ==================== Tests ====================+const mockScheduleDeferredReplay = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock('../deferredReplay', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ scheduleDeferredReplay: mockScheduleDeferredReplay,+}));+describe('BotCallbackService', () => {let service: BotCallbackService;@@ -532,6 +549,64 @@ describe('BotCallbackService', () => {// ==================== Completion handling ====================+ describe('deferred follow-up replay', () => {+ it('replays deferred messages through the bot router after completion', async () => {+ await service.handleCallback(+ makeBody({ lastAssistantContent: 'done', reason: 'completed', type: 'completion' }),+ );++ expect(mockBotRouterReplay).toHaveBeenCalledWith(+ 'discord',+ 'app-123',+ 'discord:guild:channel-id',+ );+ expect(mockMessengerRouterReplay).not.toHaveBeenCalled();+ });++ it('routes messenger-originated runs to the messenger router', async () => {+ await service.handleCallback(+ makeTelegramBody({+ applicationId: 'messenger-telegram',+ lastAssistantContent: 'done',+ messengerInstallationKey: 'telegram:singleton',+ reason: 'completed',+ type: 'completion',+ }),+ );++ expect(mockMessengerRouterReplay).toHaveBeenCalledWith(+ 'telegram:singleton',+ 'messenger-telegram',+ 'telegram:chat-456',+ );+ expect(mockBotRouterReplay).not.toHaveBeenCalled();+ });++ it('does not replay on step callbacks', async () => {+ await service.handleCallback(makeBody({ shouldContinue: true, type: 'step' }));++ expect(mockBotRouterReplay).not.toHaveBeenCalled();+ });++ it('schedules an isolated retry after replay fails without failing the completion', async () => {+ mockBotRouterReplay.mockRejectedValueOnce(new Error('redis down'));++ await expect(+ service.handleCallback(+ makeBody({ lastAssistantContent: 'done', reason: 'completed', type: 'completion' }),+ ),+ ).resolves.toBeUndefined();+ expect(mockScheduleDeferredReplay).toHaveBeenCalledWith(+ expect.objectContaining({+ applicationId: 'app-123',+ platform: 'discord',+ platformThreadId: 'discord:guild:channel-id',+ }),+ expect.any(String),+ );+ });+ });+describe('completion handling', () => {it('should render operation id when reason is error', async () => {const body = makeBody({diff --git a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts b/apps/server/src/services/bot/__tests__/BotMessageRouter.test.tsindex 08b9dbdf557..dbc17d6e902 100644--- a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts+++ b/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts@@ -1,6 +1,9 @@+import { DEFAULT_BOT_DEBOUNCE_MS } from '@lobechat/const';+import { Chat } from 'chat';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { BotMessageRouter } from '../BotMessageRouter';+import type * as PlatformUtils from '../platforms/utils';// ==================== Hoisted mocks ====================@@ -85,11 +88,16 @@ const mockWebhookHandler = vi.hoisted(() =>const mockGetList = vi.hoisted(() => vi.fn().mockResolvedValue([]));const mockAppendToList = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));const mockStateSetIfNotExists = vi.hoisted(() => vi.fn().mockResolvedValue(true));+const mockDispatchToHandlers = vi.hoisted(() => vi.fn());+const mockProcessMessage = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const mockDrainDeferredBotMessages = vi.hoisted(() => vi.fn().mockResolvedValue([]));+const mockBuildReplayMessages = vi.hoisted(() => vi.fn());vi.mock('chat', () => ({BaseFormatConverter: class {},Chat: vi.fn().mockImplementation(function () {return {+ dispatchToHandlers: mockDispatchToHandlers,getState: vi.fn(() => ({appendToList: mockAppendToList,getList: mockGetList,@@ -100,12 +108,29 @@ vi.mock('chat', () => ({onNewMessage: mockOnNewMessage,onSlashCommand: mockOnSlashCommand,onSubscribedMessage: mockOnSubscribedMessage,+ processMessage: mockProcessMessage,webhooks: mockChatWebhooks,};}),ConsoleLogger: vi.fn(),}));+vi.mock('../deferredMessages', () => ({+ replayDeferredBotMessages: async (+ app: string,+ thread: string,+ replay: (entries: unknown[]) => Promise<void>,+ ) => {+ const entries = await mockDrainDeferredBotMessages(app, thread);+ if (entries.length) await replay(entries);+ },+}));++vi.mock('../mergeMessages', async (importOriginal) => {+ const actual = (await importOriginal()) as Record<string, unknown>;+ return { ...actual, buildReplayMessages: mockBuildReplayMessages };+});+vi.mock('@/server/services/aiAgent', () => ({AiAgentService: vi.fn().mockImplementation(function () {return {@@ -240,8 +265,14 @@ const parseAllowlistMock = vi.hoisted(() => (raw: unknown): string[] => {return [];});-vi.mock('../platforms', () => ({+vi.mock('../platforms', async () => ({buildRuntimeKey: (platform: string, appId: string) => `${platform}:${appId}`,+ // Pull the real resolver rather than restating it: these tests assert the+ // exact Chat SDK concurrency config a channel ends up with, and a stub would+ // only ever test itself. `utils` is safe to import for real — the barrel is+ // mocked because it instantiates every platform definition, `utils` does not.+ resolveBotConcurrency: (await vi.importActual<typeof PlatformUtils>('../platforms/utils'))+ .resolveBotConcurrency,getBotReplyLocale: (platform: string | undefined): string => {if (platform === 'feishu' || platform === 'qq' || platform === 'wechat') return 'zh-CN';return 'en-US';@@ -887,6 +918,40 @@ describe('BotMessageRouter', () => {};}+ it.each([+ ['/new', 'question'],+ ['question', '/new'],+ ])('preserves command and content order for %s then %s', async (first, second) => {+ const events: string[] = [];+ const thread = {+ ...makeThread({ isDM: true }),+ state: Promise.resolve({ topicId: 'old-topic' }),+ };+ thread.setState.mockImplementation(async () => {+ events.push('reset');+ });+ mockHandleSubscribedMessage.mockImplementation(async (_thread, message) => {+ events.push(message.text);+ });+ mockDispatchToHandlers.mockImplementation(async (_adapter, _threadId, message, context) => {+ const handler = mockOnSubscribedMessage.mock.calls.at(-1)![0];+ await handler(thread, message, context);+ });+ try {+ await loadSubscribedHandler();+ const bot = vi.mocked(Chat).mock.results.at(-1)!.value;+ await bot.dispatchToHandlers({}, thread.id, makeMessage({ text: second }), {+ skipped: [makeMessage({ text: first })],+ totalSinceLastHandler: 2,+ });+ expect(events).toEqual([first, second].map((text) => (text === '/new' ? 'reset' : text)));+ expect(thread.setState).toHaveBeenCalledTimes(1);+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);+ } finally {+ mockDispatchToHandlers.mockReset();+ }+ });+it('should skip non-mention messages in a multi-human group thread', async () => {// post-fix the gate keys off thread.isDM || mention ||// singleHumanThread. Default beforeEach seeds two known participants,@@ -1021,6 +1086,189 @@ describe('BotMessageRouter', () => {expect(isSoloBotConversation).toHaveBeenCalledWith('telegram:chat-1');expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();});++ it('announces mention-only mode immediately when real membership reports a shared thread', async () => {+ // Regression: one human + this bot + another bot has only one human+ // speaker, but is still shared and must not silently enter mention-only+ // mode without the one-time explanation.+ mockGetList.mockResolvedValue([]);+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);+ withMembershipLookup(isSoloBotConversation);+ const handler = await loadSubscribedHandler();+ const thread = makeThread({ id: 'discord:guild-1:channel-1:thread-1' });+ mockStateSetIfNotExists.mockResolvedValueOnce(true).mockResolvedValueOnce(false);++ await handler(thread, makeMessage({ isMention: false, text: 'talking to another bot' }));+ await handler(thread, makeMessage({ isMention: false, text: 'still talking' }));++ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();+ expect(mockStateSetIfNotExists).toHaveBeenCalledWith(+ 'messenger:thread-mention-required-announced:discord:guild-1:channel-1:thread-1',+ '1',+ expect.any(Number),+ );+ expect(thread.post).toHaveBeenCalledWith(expect.stringContaining('@mention me'));+ expect(thread.post).toHaveBeenCalledTimes(1);+ });++ it('routes real Discord membership verdicts and preserves batched participants', async () => {+ const { DiscordClientFactory } = await import('../platforms/discord/client');+ const { clearDiscordChatCompositionMemoryCache } =+ await import('../platforms/discord/chatComposition');+ clearDiscordChatCompositionMemoryCache();+ const client = new DiscordClientFactory().createClient(+ {+ applicationId: 'app-123',+ credentials: { botToken: 'fixture-token', publicKey: 'fixture-key' },+ platform: 'discord',+ settings: {},+ },+ {},+ );+ const human = (id: string) => ({ member: { user: { bot: false, id } } });+ const botMember = (id: string) => ({ member: { user: { bot: true, id } } });+ const requests: unknown[] = [];+ const get = vi.fn(async (path: string, options: { query: URLSearchParams }) => {+ requests.push({ path, query: Object.fromEntries(options.query) });+ if (path.includes('unavailable')) throw new Error('Missing Access');+ return path.includes('shared')+ ? [human('alice-id'), botMember('app-123'), botMember('other-bot')]+ : [human('alice-id'), botMember('app-123')];+ });+ (client as any).discord.rest = { get };+ const membership = vi.fn((id: string) => client.isSoloBotConversation!(id));+ withMembershipLookup(membership);++ const lists = new Map<string, string[]>();+ const announcements = new Set<string>();+ mockGetList.mockImplementation(async (key: string) => lists.get(key) ?? []);+ mockAppendToList.mockImplementation(async (key: string, id: string) => {+ lists.set(key, [...(lists.get(key) ?? []), id]);+ });+ mockStateSetIfNotExists.mockImplementation(async (key: string) => {+ if (announcements.has(key)) return false;+ announcements.add(key);+ return true;+ });+ const handler = await loadSubscribedHandler();+ const observations: Record<string, unknown> = {};+ for (const scenario of ['solo', 'shared', 'unavailable', 'channel']) {+ const id = `discord:guild-1:channel-1${scenario === 'channel' ? '' : `:${scenario}`}`;+ const thread = makeThread({ id });+ mockHandleSubscribedMessage.mockClear();+ await handler(thread, makeMessage({ text: 'ordinary follow-up' }));+ const firstDispatches = mockHandleSubscribedMessage.mock.calls.length;+ const firstPosts = thread.post.mock.calls.length;+ await handler(thread, makeMessage({ text: 'second follow-up' }));+ const repeatedPosts = thread.post.mock.calls.length;+ mockHandleSubscribedMessage.mockClear();+ await handler(thread, makeMessage({ isMention: true, text: '@bot please answer' }));+ observations[scenario] = {+ firstDispatches,+ firstPosts,+ mentionDispatches: mockHandleSubscribedMessage.mock.calls.length,+ repeatedPosts,+ };+ expect(firstDispatches).toBe(scenario === 'solo' ? 1 : 0);+ expect(firstPosts).toBe(scenario === 'solo' ? 0 : 1);+ expect(repeatedPosts).toBe(firstPosts);+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);+ }++ const queuedThread = makeThread({ id: 'discord:guild-1:channel-1:queued' });+ const botMessage = {+ author: { isBot: true, userId: 'other-bot', userName: 'other bot' },+ isMention: false,+ text: 'bot reply',+ };+ mockHandleSubscribedMessage.mockClear();+ await handler(queuedThread, botMessage, {+ skipped: [+ makeMessage({ userId: 'bob-id' }),+ botMessage,+ makeMessage({ userId: 'carol-id' }),+ ],+ totalSinceLastHandler: 4,+ });+ const queuedHumans = lists.get(`messenger:thread-humans:${queuedThread.id}`);+ expect(queuedHumans).toEqual(['bob-id', 'carol-id']);+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();+ observations.queued = {+ agentDispatches: mockHandleSubscribedMessage.mock.calls.length,+ inputSenders: ['bob-id', 'other-bot', 'carol-id', 'other-bot'],+ persistedHumans: queuedHumans,+ };+ if (process.env.T500_ACCEPTANCE_CAPTURE === '1') {+ console.log(+ 'T500_ACCEPTANCE:integrated-routing',+ JSON.stringify({ observations, requests }),+ );+ }+ clearDiscordChatCompositionMemoryCache();+ });+ });++ it('tracks every human sender preserved in context.skipped', async () => {+ mockGetList.mockResolvedValue(['alice-id']);+ const handler = await loadSubscribedHandler();+ const thread = makeThread();+ const skipped = [+ makeMessage({ text: 'from bob', userId: 'bob-id' }),+ {+ author: { isBot: true, userId: 'skipped-bot-id', userName: 'skipped bot' },+ isMention: false,+ text: 'from a bot',+ },+ makeMessage({ text: 'from carol', userId: 'carol-id' }),+ ];++ await handler(+ thread,+ makeMessage({ isMention: true, text: '@bot latest', userId: 'alice-id' }),+ { skipped, totalSinceLastHandler: 4 },+ );++ expect(mockAppendToList).toHaveBeenCalledWith(+ 'messenger:thread-humans:telegram:chat-1',+ 'bob-id',+ expect.any(Object),+ );+ expect(mockAppendToList).toHaveBeenCalledWith(+ 'messenger:thread-humans:telegram:chat-1',+ 'carol-id',+ expect.any(Object),+ );+ expect(mockAppendToList).not.toHaveBeenCalledWith(+ 'messenger:thread-humans:telegram:chat-1',+ 'skipped-bot-id',+ expect.any(Object),+ );+ });++ it('tracks skipped humans before returning for a bot primary message', async () => {+ mockGetList.mockResolvedValue([]);+ const handler = await loadSubscribedHandler();+ const thread = makeThread();+ const skipped = [makeMessage({ text: 'human arrived first', userId: 'alice-id' })];+ const botMessage = {+ author: { isBot: true, userId: 'another-bot', userName: 'other bot' },+ isMention: false,+ text: 'bot primary',+ };++ await handler(thread, botMessage, { skipped, totalSinceLastHandler: 2 });++ expect(mockAppendToList).toHaveBeenCalledWith(+ 'messenger:thread-humans:telegram:chat-1',+ 'alice-id',+ expect.any(Object),+ );+ expect(mockAppendToList).not.toHaveBeenCalledWith(+ 'messenger:thread-humans:telegram:chat-1',+ 'another-bot',+ expect.any(Object),+ );+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();});it('should respond when a debounced/skipped earlier message contained the mention', async () => {@@ -2841,6 +3089,70 @@ describe('BotMessageRouter', () => {expect(thread.setState).not.toHaveBeenCalled();});+ it('answers /whoami for a non-allowlisted sender without touching state (bypassGate)', async () => {+ const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });+ const thread = {+ channelId: 'channel-1',+ id: 'telegram:channel-1',+ isDM: true,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };+ const message = {+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },+ isMention: false,+ text: '/whoami',+ };++ await cmdRegexHandler(thread, message);++ expect(thread.post).toHaveBeenCalledTimes(1);+ expect(thread.post.mock.calls[0][0]).toContain('`lin-id`');+ expect(thread.post.mock.calls[0][0]).not.toContain("aren't authorized");+ expect(thread.setState).not.toHaveBeenCalled();+ });++ it('answers /whoami under the pairing DM policy before settings.userId exists (no pairing code)', async () => {+ const { subscribed } = await loadAllHandlers({ dmPolicy: 'pairing' });+ const thread = {+ channelId: 'channel-1',+ id: 'telegram:channel-1',+ isDM: true,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ state: Promise.resolve(null),+ };+ const message = {+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },+ isMention: false,+ text: '/whoami',+ };++ await subscribed(thread, message);++ expect(thread.post).toHaveBeenCalledTimes(1);+ expect(thread.post.mock.calls[0][0]).toContain('`lin-id`');+ expect(thread.post.mock.calls[0][0]).not.toMatch(/approve/i);+ expect(mockHandleMention).not.toHaveBeenCalled();+ });++ it('marks the caller as operator in /whoami when their ID matches settings.userId', async () => {+ const { cmdRegexHandler } = await loadAllHandlers({ userId: 'lin-id' });+ const thread = {+ channelId: 'channel-1',+ id: 'telegram:channel-1',+ isDM: true,+ post: vi.fn().mockResolvedValue(undefined),+ setState: vi.fn().mockResolvedValue(undefined),+ };+ await cmdRegexHandler(thread, {+ author: { isBot: false, userId: 'lin-id', userName: 'lin' },+ isMention: false,+ text: '/whoami',+ });+ expect(thread.post.mock.calls[0][0]).toContain('already set as the bot operator');+ });+it('still allows /commands from an allowlisted sender (gate does not break the happy path)', async () => {const { cmdRegexHandler } = await loadAllHandlers({ allowFrom: 'alice-id' });const thread = {@@ -3198,6 +3510,107 @@ describe('BotMessageRouter', () => {});});+ describe('concurrency strategy wiring', () => {+ const loadWith = async (settings: Record<string, unknown>, platform = 'telegram') => {+ mockFindEnabledByPlatform.mockResolvedValue([+ makeProvider({ applicationId: 'app-1', settings }),+ ]);+ const router = new BotMessageRouter();+ await router.getWebhookHandler(+ platform,+ 'app-1',+ )(new Request('https://example.com/webhook', { body: '{}', method: 'POST' }));+ return (Chat as unknown as { mock: { calls: any[][] } }).mock.calls.at(-1)![0];+ };++ it('collects a burst window when the channel asks for it', async () => {+ // The strategy a WeChat channel needs so an image and the sentence about+ // it reach the agent as one turn instead of two separate runs.+ const config = await loadWith({ concurrency: 'burst', debounceMs: 1200 });++ expect(config.concurrency).toEqual({ debounceMs: 1200, strategy: 'burst' });+ });++ it('still supports debounce for channels that opted into it', async () => {+ const config = await loadWith({ concurrency: 'debounce', debounceMs: 900 });++ expect(config.concurrency).toEqual({ debounceMs: 900, strategy: 'debounce' });+ });++ it('falls back to the plain queue when the setting is absent or unknown', async () => {+ expect((await loadWith({})).concurrency).toBe('queue');+ expect((await loadWith({ concurrency: 'nonsense' })).concurrency).toBe('queue');+ });++ it('rescues a WeChat channel still carrying the pre-burst queue setting', async () => {+ // Live WeChat channels persisted `queue` plus the old 5s window when they+ // were created, so a schema default alone would never reach them. They+ // collect a burst regardless, on the platform's own window — 5s in front+ // of every reply would read as a dead bot.+ const config = await loadWith({ concurrency: 'queue', debounceMs: 5000 }, 'wechat');++ expect(config.concurrency).toEqual({+ debounceMs: DEFAULT_BOT_DEBOUNCE_MS,+ strategy: 'burst',+ });+ });+ });++ describe('replayDeferredMessages', () => {+ const THREAD = 'telegram:chat-1';++ beforeEach(() => {+ mockDrainDeferredBotMessages.mockResolvedValue([]);+ mockBuildReplayMessages.mockReset();+ mockProcessMessage.mockResolvedValue(undefined);+ mockCreateAdapter.mockReturnValue({ telegram: { type: 'mock-adapter' } });+ });++ it('re-dispatches each original through Chat.processMessage with the platform adapter', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'tg-bot-123' })]);+ const entries = [{ id: 'm1' }, { id: 'm2' }];+ const replays = [+ { id: 'm1:replay:1:0', text: 'first' },+ { id: 'm2:replay:1:1', text: 'second' },+ ];+ mockDrainDeferredBotMessages.mockResolvedValue(entries);+ mockBuildReplayMessages.mockReturnValue(replays);++ const router = new BotMessageRouter();+ await router.replayDeferredMessages('telegram', 'tg-bot-123', THREAD);++ expect(mockDrainDeferredBotMessages).toHaveBeenCalledWith('tg-bot-123', THREAD);+ expect(mockBuildReplayMessages).toHaveBeenCalledWith(entries);+ expect(mockProcessMessage).toHaveBeenCalledTimes(2);+ for (const replay of replays) {+ expect(mockProcessMessage).toHaveBeenCalledWith({ type: 'mock-adapter' }, THREAD, replay);+ }+ });++ it('does nothing (and does not load the bot) when nothing was deferred', async () => {+ mockBuildReplayMessages.mockReturnValue([]);++ const router = new BotMessageRouter();+ await router.replayDeferredMessages('telegram', 'tg-bot-123', THREAD);++ expect(mockFindEnabledByPlatform).not.toHaveBeenCalled();+ expect(mockProcessMessage).not.toHaveBeenCalled();+ });++ it('rejects replay when no bot is registered so entries remain pending', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockDrainDeferredBotMessages.mockResolvedValue([{ id: 'm1' }]);+ mockBuildReplayMessages.mockReturnValue([{ id: 'm1:replay:1:0' }]);++ const router = new BotMessageRouter();+ await expect(+ router.replayDeferredMessages('telegram', 'tg-bot-missing', THREAD),+ ).rejects.toThrow('Bot adapter unavailable');++ expect(mockProcessMessage).not.toHaveBeenCalled();+ });+ });+describe('/mode command (per-conversation agent/chat switch)', () => {async function loadModeHandlers() {mockFindEnabledByPlatform.mockResolvedValue([diff --git a/apps/server/src/services/bot/__tests__/deferredMessages.test.ts b/apps/server/src/services/bot/__tests__/deferredMessages.test.tsnew file mode 100644index 00000000000..09029c49682--- /dev/null+++ b/apps/server/src/services/bot/__tests__/deferredMessages.test.ts@@ -0,0 +1,109 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mockGetAgentRuntimeRedisClient = vi.hoisted(() => vi.fn());++vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: mockGetAgentRuntimeRedisClient,+}));++const {+ buildDeferredMessagesKey,+ deferBotMessages,+ readDeferredBotMessages,+ replayDeferredBotMessages,+ isDeferredMessagesAvailable,+} = await import('../deferredMessages');++/** Minimal ioredis `multi()` chain recorder. */+function createRedis(execResult: unknown = []) {+ const calls: Array<[string, ...unknown[]]> = [];+ const chain: any = {};+ for (const cmd of ['rpush', 'ltrim', 'expire', 'lrem']) {+ chain[cmd] = vi.fn((...args: unknown[]) => {+ calls.push([cmd, ...args]);+ return chain;+ });+ }+ chain.exec = vi.fn().mockResolvedValue(execResult);+ return { calls, chain, lrange: vi.fn().mockResolvedValue([]), multi: vi.fn(() => chain) };+}++const makeMessage = (id: string) => ({ id, toJSON: () => ({ _type: 'chat:Message', id }) }) as any;++describe('deferredMessages', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('builds a key scoped by application and thread', () => {+ expect(buildDeferredMessagesKey('app-1', 'wechat:single:u')).toBe(+ 'bot:deferred-messages:app-1:wechat:single:u',+ );+ });++ it('reports unavailable and stores nothing without Redis', async () => {+ mockGetAgentRuntimeRedisClient.mockReturnValue(null);++ expect(isDeferredMessagesAvailable()).toBe(false);+ await expect(deferBotMessages('app-1', 't', [makeMessage('1')])).resolves.toBe(false);+ await expect(readDeferredBotMessages('app-1', 't')).resolves.toEqual([]);+ });++ it('appends serialized messages in order with a cap and TTL', async () => {+ const redis = createRedis();+ mockGetAgentRuntimeRedisClient.mockReturnValue(redis);++ const ok = await deferBotMessages('app-1', 't', [makeMessage('1'), makeMessage('2')]);++ expect(ok).toBe(true);+ expect(redis.calls[0]).toEqual([+ 'rpush',+ 'bot:deferred-messages:app-1:t',+ JSON.stringify({ _type: 'chat:Message', id: '1' }),+ JSON.stringify({ _type: 'chat:Message', id: '2' }),+ ]);+ expect(redis.calls[1]).toEqual(['ltrim', 'bot:deferred-messages:app-1:t', -20, -1]);+ expect(redis.calls[2]).toEqual(['expire', 'bot:deferred-messages:app-1:t', 30 * 60]);+ });++ it('returns false when the write fails so callers keep the fallback path', async () => {+ const redis = createRedis();+ redis.chain.exec.mockRejectedValue(new Error('boom'));+ mockGetAgentRuntimeRedisClient.mockReturnValue(redis);++ await expect(deferBotMessages('app-1', 't', [makeMessage('1')])).resolves.toBe(false);+ });++ it('reads oldest-first without removing entries and skips corrupt payloads', async () => {+ const redis = createRedis();+ redis.lrange.mockResolvedValue(['{"id":"1"}', 'not json', '{"id":"2"}']);+ mockGetAgentRuntimeRedisClient.mockReturnValue(redis);+ expect(await readDeferredBotMessages('app-1', 't')).toEqual([{ id: '1' }, { id: '2' }]);+ expect(redis.calls).toEqual([]);+ });++ it('retains the full batch when replay fails, then acknowledges only those entries on retry', async () => {+ const redis = createRedis();+ const payloads = ['{"id":"1"}', '{"id":"2"}'];+ redis.lrange.mockResolvedValue(payloads);+ mockGetAgentRuntimeRedisClient.mockReturnValue(redis);+ const replay = vi+ .fn()+ .mockRejectedValueOnce(new Error('adapter unavailable'))+ .mockResolvedValueOnce(undefined);+ await expect(replayDeferredBotMessages('app-1', 't', replay)).rejects.toThrow(+ 'adapter unavailable',+ );+ expect(redis.calls).toEqual([]);+ await replayDeferredBotMessages('app-1', 't', replay);+ expect(replay).toHaveBeenNthCalledWith(2, [{ id: '1' }, { id: '2' }]);+ expect(redis.calls).toEqual(+ payloads.map((payload) => ['lrem', 'bot:deferred-messages:app-1:t', 1, payload]),+ );+ });++ it('reports Redis transaction errors as a failed write', async () => {+ mockGetAgentRuntimeRedisClient.mockReturnValue(createRedis([[new Error('read only'), null]]));+ await expect(deferBotMessages('app-1', 't', [makeMessage('1')])).resolves.toBe(false);+ });+});diff --git a/apps/server/src/services/bot/__tests__/deferredReplay.test.ts b/apps/server/src/services/bot/__tests__/deferredReplay.test.tsnew file mode 100644index 00000000000..814279cfe42--- /dev/null+++ b/apps/server/src/services/bot/__tests__/deferredReplay.test.ts@@ -0,0 +1,73 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mockRunBot = vi.hoisted(() => vi.fn());+const mockRunMessenger = vi.hoisted(() => vi.fn());+const mockPublish = vi.hoisted(() => vi.fn().mockResolvedValue({ messageId: 'queued' }));+const config = vi.hoisted(() => ({+ APP_URL: 'https://example.com',+ enableQueueAgentRuntime: false,+}));+vi.mock('@/envs/app', () => ({ appEnv: config }));+vi.mock('../BotMessageRouter', () => ({+ getBotMessageRouter: () => ({ replayDeferredMessages: mockRunBot }),+}));+vi.mock('@/server/services/messenger/MessengerRouter', () => ({+ getMessengerRouter: () => ({ replayDeferredMessages: mockRunMessenger }),+}));+vi.mock('@/libs/qstash', () => ({+ OtelQstashClient: class {+ publishJSON = mockPublish;+ },+}));++const { scheduleDeferredReplay } = await import('../deferredReplay');+const target = { applicationId: 'app', platform: 'wechat', platformThreadId: 'wechat:single:user' };++beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ config.enableQueueAgentRuntime = false;+ vi.stubEnv('AGENT_RUNTIME_BASE_URL', '');+});+afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllEnvs();+});++describe('independent deferred replay retries', () => {+ it.each([false, true])(+ 'retries a failed local delivery without another completion (messenger=%s)',+ async (messenger) => {+ const replay = messenger ? mockRunMessenger : mockRunBot;+ replay+ .mockRejectedValueOnce(new Error('temporary adapter error'))+ .mockResolvedValue(undefined);+ await scheduleDeferredReplay(+ { ...target, ...(messenger ? { messengerInstallationKey: 'wechat:singleton' } : {}) },+ 'op-1',+ );+ await vi.advanceTimersByTimeAsync(1000);+ expect(replay).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(replay).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(replay).toHaveBeenCalledTimes(2);+ },+ );++ it('publishes a deduplicated replay-only job with bounded provider retries', async () => {+ config.enableQueueAgentRuntime = true;+ vi.stubEnv('QSTASH_TOKEN', 'example-token');+ await scheduleDeferredReplay(target, 'op-1');+ expect(mockPublish).toHaveBeenCalledWith(+ expect.objectContaining({+ body: expect.objectContaining({ operationId: 'op-1', payload: target }),+ deduplicationId: expect.stringMatching(/^[a-f\d]{64}$/),+ retries: 8,+ retryDelay: '60000',+ url: 'https://example.com/api/agent/webhooks/bot-replay',+ }),+ );+ expect(mockPublish.mock.calls[0][0].body.payload).not.toHaveProperty('lastAssistantContent');+ });+});diff --git a/apps/server/src/services/bot/__tests__/formatPrompt.test.ts b/apps/server/src/services/bot/__tests__/formatPrompt.test.tsindex 85fc2ff2b2f..ef0ce58f04a 100644--- a/apps/server/src/services/bot/__tests__/formatPrompt.test.ts+++ b/apps/server/src/services/bot/__tests__/formatPrompt.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { formatPrompt, formatReferencedMessage } from '../formatPrompt';+import { buildBotSender, formatPrompt, formatReferencedMessage } from '../formatPrompt';describe('formatReferencedMessage', () => {it('should return undefined when raw is undefined', () => {@@ -229,3 +229,51 @@ describe('formatPrompt', () => {);});});++describe('buildBotSender', () => {+ it('keeps a Feishu sender as name only, dropping the duplicated username', () => {+ expect(+ buildBotSender(+ { author: { fullName: '文彬', userId: 'ou_1', userName: '文彬' }, raw: {} },+ 'feishu',+ ),+ ).toEqual({+ avatar: undefined,+ fullName: '文彬',+ id: 'ou_1',+ platform: 'feishu',+ username: undefined,+ });+ });++ it('resolves a Discord avatar hash and prefers global_name', () => {+ expect(+ buildBotSender(+ {+ author: { fullName: 'john', userId: '123', userName: 'john' },+ raw: { author: { avatar: 'a_hash', global_name: 'John Doe' } },+ },+ 'discord',+ ),+ ).toEqual({+ avatar: 'https://cdn.discordapp.com/avatars/123/a_hash.gif',+ fullName: 'John Doe',+ id: '123',+ platform: 'discord',+ username: 'john',+ });+ });++ it('passes an absolute avatar url through and drops an opaque one', () => {+ expect(+ buildBotSender(+ { author: { userId: 'u1' }, raw: { author: { avatar: 'https://x/a.png' } } },+ 'slack',+ ).avatar,+ ).toBe('https://x/a.png');+ expect(+ buildBotSender({ author: { userId: 'u1' }, raw: { author: { avatar: 'hash' } } }, 'slack')+ .avatar,+ ).toBeUndefined();+ });+});diff --git a/apps/server/src/services/bot/__tests__/mergeMessages.test.ts b/apps/server/src/services/bot/__tests__/mergeMessages.test.tsnew file mode 100644index 00000000000..24d8dbc2d87--- /dev/null+++ b/apps/server/src/services/bot/__tests__/mergeMessages.test.ts@@ -0,0 +1,93 @@+import { Message } from 'chat';+import { describe, expect, it } from 'vitest';++import { buildReplayMessages, getSourceMessages, mergeBotMessages } from '../mergeMessages';++const makeMessage = (id: string, text: string, raw: unknown, attachments: unknown[] = []) =>+ new Message({+ attachments: attachments as any,+ author: { fullName: 'u', isBot: false, isMe: false, userId: 'u', userName: 'u' },+ formatted: [] as any,+ id,+ metadata: { dateSent: new Date('2026-09-09T00:00:00Z'), edited: false },+ raw,+ text,+ threadId: 'wechat:single:u',+ });++describe('mergeBotMessages', () => {+ it('returns the message untouched when there is nothing to merge', () => {+ const message = makeMessage('1', 'hi', { a: 1 });++ expect(mergeBotMessages(message, undefined)).toBe(message);+ expect(mergeBotMessages(message, [])).toBe(message);+ expect(getSourceMessages(message)).toEqual([message]);+ });++ it('joins text, concatenates attachments and records every source', () => {+ const image = makeMessage('1', '', { item: 'image' }, [{ type: 'image' }]);+ const text = makeMessage('2', 'describe this', { item: 'text' });++ const merged = mergeBotMessages(text, [image]);++ expect(merged.text).toBe('describe this');+ expect(merged.attachments).toEqual([{ type: 'image' }]);+ // The last message's raw wins on the merged message itself…+ expect(merged.raw).toEqual({ item: 'text' });+ // …but every original raw stays reachable for extractFiles.+ expect(getSourceMessages(merged).map((m) => m.raw)).toEqual([+ { item: 'image' },+ { item: 'text' },+ ]);+ expect(merged).toBeInstanceOf(Message);+ });+});++describe('buildReplayMessages', () => {+ it('returns an empty list for no entries', () => {+ expect(buildReplayMessages([])).toEqual([]);+ });++ it('keeps each original raw through the SDK JSON round-trip before merging', () => {+ const image = makeMessage('10', '', { item: 'image' }, [{ type: 'image', url: '' }]);+ const text = makeMessage('11', '参考这个风格', { item: 'text' });+ const entries = [image.toJSON(), text.toJSON()];++ const replays = buildReplayMessages(entries);+ expect(replays).toHaveLength(2);+ const restored = replays.map((message) =>+ // JSON wire serialization intentionally calls Message.toJSON.+ // eslint-disable-next-line unicorn/prefer-structured-clone+ Message.fromJSON(JSON.parse(JSON.stringify(message))),+ );+ const replay = mergeBotMessages(restored[1], [restored[0]]);++ expect(replay).toBeInstanceOf(Message);+ expect(replay.id).toMatch(/^11:replay:\d+:1$/);+ expect(replay.text).toBe('参考这个风格');+ expect(replay.threadId).toBe('wechat:single:u');+ expect(replay.attachments).toHaveLength(1);+ expect(getSourceMessages(replay).map((m) => m.raw)).toEqual([+ { item: 'image' },+ { item: 'text' },+ ]);+ });+});++describe('sender isolation', () => {+ it('does not merge another author or bot into the authenticated sender turn', () => {+ const owner = makeMessage('owner', 'owner followup', { item: 'text' });+ const attacker = makeMessage('attacker', 'untrusted instruction', { item: 'image' }, [+ { type: 'image' },+ ]);+ attacker.author = { ...attacker.author, userId: 'someone-else' };+ const bot = makeMessage('bot', 'bot instruction', {});+ bot.author = { ...bot.author, isBot: true };++ const merged = mergeBotMessages(owner, [attacker, bot]);++ expect(merged).toBe(owner);+ expect(getSourceMessages(merged)).toEqual([owner]);+ expect(merged.attachments).toEqual([]);+ });+});diff --git a/apps/server/src/services/bot/__tests__/patchSenderBatches.test.ts b/apps/server/src/services/bot/__tests__/patchSenderBatches.test.tsnew file mode 100644index 00000000000..c95b8bccba4--- /dev/null+++ b/apps/server/src/services/bot/__tests__/patchSenderBatches.test.ts@@ -0,0 +1,38 @@+import { Message } from 'chat';+import { describe, expect, it, vi } from 'vitest';++import { patchSenderBatches } from '../patchSenderBatches';++const message = (id: string) =>+ new Message({+ attachments: [],+ author: { fullName: id, isBot: false, isMe: false, userId: id, userName: id },+ formatted: { type: 'root', children: [] },+ id,+ metadata: { dateSent: new Date(), edited: false },+ raw: {},+ text: id,+ threadId: 'thread',+ });++describe('sender batch failure isolation', () => {+ it('still delivers later senders when an earlier sender handler rejects', async () => {+ const dispatch = vi+ .fn()+ .mockRejectedValueOnce(new Error('first sender failed'))+ .mockResolvedValue(undefined);+ const bot = { dispatchToHandlers: dispatch };+ patchSenderBatches(bot as any);+ const alice = message('alice');+ const bob = message('bob');++ await expect(+ bot.dispatchToHandlers({} as any, 'thread', bob, {+ skipped: [alice],+ totalSinceLastHandler: 2,+ }),+ ).rejects.toThrow('Sender batch dispatch failed');+ expect(dispatch).toHaveBeenCalledTimes(2);+ expect(dispatch.mock.calls.map((call) => call[2].author.userId)).toEqual(['alice', 'bob']);+ });+});diff --git a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts b/apps/server/src/services/bot/__tests__/replyTemplate.test.tsindex f309ae90654..24ddebb5bec 100644--- a/apps/server/src/services/bot/__tests__/replyTemplate.test.ts+++ b/apps/server/src/services/bot/__tests__/replyTemplate.test.ts@@ -21,6 +21,7 @@ import {renderStepProgress,renderStopped,renderToolExecuting,+ renderWhoami,splitMessage,summarizeOutput,} from '../replyTemplate';@@ -898,6 +899,35 @@ describe('replyTemplate', () => {});});+ // ==================== renderWhoami ====================++ describe('renderWhoami', () => {+ it('echoes the caller ID, display name and the settings pointer in English', () => {+ const text = renderWhoami({ isOperator: false, userId: 'ou_abc123', userName: 'Lin' });+ expect(text).toContain('`ou_abc123`');+ expect(text).toContain('Lin');+ expect(text).toContain('Your Platform User ID');+ });++ it('omits the display name line when unknown and flags an already-configured operator', () => {+ const text = renderWhoami({ isOperator: true, userId: 'ou_abc123' });+ expect(text).toContain('`ou_abc123`');+ expect(text).not.toContain('Display name');+ expect(text).toContain('already set as the bot operator');+ });++ it('renders Chinese copy for zh-CN', () => {+ const text = renderWhoami(+ { isOperator: false, userId: 'ou_abc123', userName: '林' },+ 'zh-CN',+ );+ expect(text).toContain('你的平台用户 ID:`ou_abc123`');+ expect(text).toContain('显示名称:林');+ expect(text).toContain('高级设置');+ expect(renderCommandReply('cmdWhoamiUnavailable', 'zh-CN')).toContain('无法');+ });+ });+// ==================== renderGuestCopy ====================describe('renderGuestCopy', () => {diff --git a/apps/server/src/services/bot/deferredMessages.ts b/apps/server/src/services/bot/deferredMessages.tsnew file mode 100644index 00000000000..f0d97d3ec39--- /dev/null+++ b/apps/server/src/services/bot/deferredMessages.ts@@ -0,0 +1,134 @@+import type { Message } from 'chat';+import debug from 'debug';++import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';++const log = debug('lobe-server:bot:deferred-messages');++/**+ * Cross-process queue for inbound bot messages that arrive while the thread's+ * topic still has a live agent run.+ *+ * Why this exists: in queue mode the bridge hands the run to the job queue and+ * returns immediately, so both the Chat SDK thread lock and the in-process+ * `activeThreads` guard are released long before the agent finishes. A+ * follow-up that lands in that window (WeChat delivers "one image + one+ * sentence" as two messages a few hundred ms apart) used to race the+ * topic-start reservation, lose, and surface as "Agent Execution Failed".+ *+ * Instead the bridge parks the serialized message here, and the completion+ * callback replays every parked message through the Chat SDK once the run is+ * done — the same path a brand-new inbound message takes, so subscription /+ * mention / command routing stay untouched.+ *+ * Key layout: `bot:deferred-messages:<applicationId>:<platformThreadId>`.+ * Scoped by application because one WeChat user can talk to several bots and+ * their thread ids collide (`wechat:single:<userId>`).+ *+ * Entries are `Message.toJSON()` payloads. `raw` survives serialization, which+ * is what the per-platform `extractFiles` needs to re-download media after the+ * round-trip (the same contract the SDK's own queue relies on).+ */+export type DeferredBotMessage = ReturnType<Message['toJSON']>;++/** Matches the agent execution ceiling so a crashed run can't strand entries. */+const TTL_SECONDS = 30 * 60;++/** Hard cap so a runaway sender cannot grow the list unboundedly. */+const MAX_DEFERRED_PER_THREAD = 20;++export const buildDeferredMessagesKey = (applicationId: string, platformThreadId: string): string =>+ `bot:deferred-messages:${applicationId}:${platformThreadId}`;++/**+ * Whether deferral is available at all — it needs Redis because the replay+ * happens in the callback process, not the one that received the message.+ */+export const isDeferredMessagesAvailable = (): boolean => !!getAgentRuntimeRedisClient();++/**+ * Park messages (chronological) for replay after the running agent completes.+ * A merged message should be passed as its individual sources so each one+ * keeps its own `raw` for media re-download.+ *+ * @returns `true` when the messages were stored; `false` when Redis is+ * unavailable or the write failed — callers should then fall back to the+ * previous (fail-fast) behavior rather than drop the message silently.+ */+export async function deferBotMessages(+ applicationId: string,+ platformThreadId: string,+ messages: Message[],+): Promise<boolean> {+ const redis = getAgentRuntimeRedisClient();+ if (!redis || messages.length === 0) return false;++ const key = buildDeferredMessagesKey(applicationId, platformThreadId);+ try {+ const payloads = messages.map((message) => JSON.stringify(message.toJSON()));+ const results = await redis+ .multi()+ .rpush(key, ...payloads)+ .ltrim(key, -MAX_DEFERRED_PER_THREAD, -1)+ .expire(key, TTL_SECONDS)+ .exec();+ const failure = results?.find(([error]) => error)?.[0];+ if (!results || failure) throw failure ?? new Error('Deferred write aborted');+ log(+ 'deferred %d message(s) [%s] for thread=%s app=%s',+ messages.length,+ messages.map((message) => message.id).join(','),+ platformThreadId,+ applicationId,+ );+ return true;+ } catch (error) {+ log('deferBotMessage failed for thread=%s: %O', platformThreadId, error);+ return false;+ }+}++/** Read a snapshot without removing messages before the SDK accepts them. */+export async function readDeferredBotMessages(+ applicationId: string,+ platformThreadId: string,+): Promise<DeferredBotMessage[]> {+ const redis = getAgentRuntimeRedisClient();+ if (!redis) return [];+ const key = buildDeferredMessagesKey(applicationId, platformThreadId);+ const entries = await redis.lrange(key, 0, -1);+ const messages: DeferredBotMessage[] = [];+ for (const entry of entries) {+ try {+ messages.push(JSON.parse(entry) as DeferredBotMessage);+ } catch (error) {+ log('Invalid deferred payload for thread=%s: %O', platformThreadId, error);+ }+ }+ return messages;+}++/**+ * Acknowledge only the snapshot successfully handed to the SDK. New arrivals+ * remain queued. A failure (including process/Redis failure) leaves the original+ * entries available for retry. Delivery is at-least-once if a batch partially+ * succeeds or completion callbacks overlap.+ */+export async function replayDeferredBotMessages(+ applicationId: string,+ platformThreadId: string,+ replay: (entries: DeferredBotMessage[]) => Promise<void>,+): Promise<void> {+ const entries = await readDeferredBotMessages(applicationId, platformThreadId);+ if (entries.length === 0) return;+ await replay(entries);++ const redis = getAgentRuntimeRedisClient();+ if (!redis) throw new Error('Redis unavailable while acknowledging deferred messages');+ const key = buildDeferredMessagesKey(applicationId, platformThreadId);+ const transaction = redis.multi();+ for (const entry of entries) transaction.lrem(key, 1, JSON.stringify(entry));+ const results = await transaction.exec();+ const failure = results?.find(([error]) => error)?.[0];+ if (!results || failure) throw failure ?? new Error('Deferred replay acknowledgement aborted');+}diff --git a/apps/server/src/services/bot/deferredReplay.ts b/apps/server/src/services/bot/deferredReplay.tsnew file mode 100644index 00000000000..7097fd03bf0--- /dev/null+++ b/apps/server/src/services/bot/deferredReplay.ts@@ -0,0 +1,62 @@+import { appEnv } from '@/envs/app';+import { QueueService } from '@/server/services/queue';+import { LocalQueueServiceImpl } from '@/server/services/queue/impls';+import type { QueueMessage } from '@/server/services/queue/types';++export interface DeferredReplayTarget {+ applicationId: string;+ messengerInstallationKey?: string;+ platform: string;+ platformThreadId: string;+}++export async function runDeferredReplay(target: DeferredReplayTarget): Promise<void> {+ const { applicationId, messengerInstallationKey, platform, platformThreadId } = target;+ if (messengerInstallationKey) {+ const { getMessengerRouter } = await import('@/server/services/messenger/MessengerRouter');+ await getMessengerRouter().replayDeferredMessages(+ messengerInstallationKey,+ applicationId,+ platformThreadId,+ );+ return;+ }+ const { getBotMessageRouter } = await import('./BotMessageRouter');+ await getBotMessageRouter().replayDeferredMessages(platform, applicationId, platformThreadId);+}++/** Retry only inbound replay; the completed run's reply is never part of this job. */+export async function scheduleDeferredReplay(+ target: DeferredReplayTarget,+ replayId: string,+): Promise<void> {+ const queue = new QueueService();+ const baseURL = process.env.AGENT_RUNTIME_BASE_URL || appEnv.APP_URL || 'http://localhost:3010';+ const message: QueueMessage = {+ deduplicationId: `bot-replay:${target.applicationId}:${target.platformThreadId}:${replayId}`,+ delay: 1000,+ endpoint: new URL('/api/agent/webhooks/bot-replay', baseURL).toString(),+ operationId: replayId,+ payload: target,+ retries: 8,+ retryDelay: '60000',+ stepIndex: 0,+ };+ const impl = queue.getImpl();+ if (impl instanceof LocalQueueServiceImpl) {+ impl.setExecutionCallback(async (_operationId, attempt) => {+ try {+ await runDeferredReplay(target);+ } catch (error) {+ if (attempt >= 8) throw error;+ await queue.scheduleMessage({+ ...message,+ deduplicationId: `${message.deduplicationId}:${attempt + 1}`,+ delay: 60_000,+ stepIndex: attempt + 1,+ });+ }+ });+ }+ await queue.scheduleMessage(message);+}diff --git a/apps/server/src/services/bot/formatPrompt.ts b/apps/server/src/services/bot/formatPrompt.tsindex b8a12b06be8..f1aead5dd6b 100644--- a/apps/server/src/services/bot/formatPrompt.ts+++ b/apps/server/src/services/bot/formatPrompt.ts@@ -1,4 +1,5 @@import { formatSpeakerMessage } from '@lobechat/prompts';+import type { BotSenderMetadata } from '@lobechat/types';interface RawReferencedMessage {author?: { global_name?: string; username?: string };@@ -83,13 +84,63 @@ export const formatPrompt = (message: MessageLike, options?: FormatPromptOptionstext = `${referencedText}\n${text}`;}+ const { avatar, id, nickname, username } = resolveSpeaker(message);++ return formatSpeakerMessage({ avatar, id, nickname, username }, text);+};++/**+ * Single source of the author identity used by both the `<speaker>` prompt tag+ * and the persisted `metadata.botSender`, so the model and the UI never see+ * two different names for the same person.+ */+const resolveSpeaker = (message: Pick<MessageLike, 'author' | 'raw'>) => {const { userId, userName, fullName } = message.author;const raw = message.raw?.author;- const avatar = raw?.avatar ?? '';- const globalName = raw?.global_name ?? fullName;+ return {+ avatar: raw?.avatar ?? '',+ id: userId,+ nickname: raw?.global_name ?? fullName,+ username: userName,+ };+};++const DISCORD_CDN = 'https://cdn.discordapp.com';- return formatSpeakerMessage(- { avatar, id: userId, nickname: globalName, username: userName },- text,- );+/**+ * Turn whatever the platform handed us into an absolute avatar URL. Discord+ * only exposes an avatar *hash* on `raw.author`, which is meaningless to an+ * `<img>` until combined with the user id.+ */+export const resolveBotSenderAvatar = (+ avatar: string | undefined,+ platform: string,+ userId: string,+): string | undefined => {+ if (!avatar) return undefined;+ if (/^https?:\/\//.test(avatar)) return avatar;+ if (platform === 'discord') {+ const ext = avatar.startsWith('a_') ? 'gif' : 'png';+ return `${DISCORD_CDN}/avatars/${userId}/${avatar}.${ext}`;+ }+ return undefined;+};++/**+ * Build the structured sender block stored on the inbound user message so the+ * workspace UI can show the real platform author instead of the bot owner.+ */+export const buildBotSender = (+ message: Pick<MessageLike, 'author' | 'raw'>,+ platform: string,+): BotSenderMetadata => {+ const { avatar, id, nickname, username } = resolveSpeaker(message);+ return {+ avatar: resolveBotSenderAvatar(avatar, platform, id),+ fullName: nickname || undefined,+ id,+ platform,+ // Feishu/Lark fills both fields with the display name — drop the duplicate.+ username: username && username !== nickname ? username : undefined,+ };};diff --git a/apps/server/src/services/bot/mergeMessages.ts b/apps/server/src/services/bot/mergeMessages.tsnew file mode 100644index 00000000000..cc65d0c65a3--- /dev/null+++ b/apps/server/src/services/bot/mergeMessages.ts@@ -0,0 +1,77 @@+import { Message } from 'chat';++import type { DeferredBotMessage } from './deferredMessages';++/**+ * Field stamped on a merged message so downstream consumers (notably+ * `AgentBridgeService.resolveFiles`) can reach every original message's+ * `raw`, not just the last one's. Per-platform `extractFiles` re-downloads+ * media from `raw`, so without this an image that arrived one message before+ * the text is lost when the two are merged into a single turn.+ *+ * The field is in-process only: the Chat SDK's `Message.toJSON` drops it.+ * Replay must enqueue original messages separately and merge only after the+ * SDK has restored them from its queue.+ */+export const SOURCE_MESSAGES_FIELD = 'sourceMessages';++type MessageWithSources = Message & { [SOURCE_MESSAGES_FIELD]?: Message[] };++/** Earlier messages may contribute content and triggers only for the same sender. */+export function getSameSenderMessages(message: Message, earlier?: Message[]): Message[] {+ const senderId = message.author?.userId;+ if (!senderId) return [];++ return (earlier ?? []).filter(+ (source) =>+ source.author?.userId === senderId &&+ source.author?.isBot === message.author.isBot &&+ source.author?.isMe === message.author.isMe,+ );+}++/**+ * Merge earlier messages (chronological) into `message`, producing a single+ * message with combined text + attachments and the full source list. Returns+ * `message` untouched when there is nothing to merge.+ */+export function mergeBotMessages(message: Message, earlier: Message[] | undefined): Message {+ const sameSender = getSameSenderMessages(message, earlier);+ if (sameSender.length === 0) return message;++ const allMessages = [...sameSender, message].flatMap(getSourceMessages);+ const mergedText = allMessages+ .map((m) => m.text)+ .filter(Boolean)+ .join('\n');+ const mergedAttachments = allMessages.flatMap((m) => (m as any).attachments || []);++ return Object.assign(Object.create(Object.getPrototypeOf(message)), message, {+ attachments: mergedAttachments,+ [SOURCE_MESSAGES_FIELD]: allMessages,+ text: mergedText,+ });+}++/**+ * Every original message behind `message`: the merged sources when it was+ * produced by {@link mergeBotMessages}, otherwise the message itself.+ */+export function getSourceMessages(message: Message): Message[] {+ const sources = (message as MessageWithSources)[SOURCE_MESSAGES_FIELD];+ return sources?.length ? sources : [message];+}++/**+ * Rebuild original messages from deferred payloads (oldest first).+ *+ * The replayed message gets a fresh id: the Chat SDK dedupes inbound messages+ * by `<adapter>:<id>` for 10 minutes, and the originals already went through+ * `processMessage` once when they were deferred.+ */+export function buildReplayMessages(entries: DeferredBotMessage[]): Message[] {+ const now = Date.now();+ return entries.map((entry, index) => {+ return Message.fromJSON({ ...entry, id: `${entry.id}:replay:${now}:${index}` });+ });+}diff --git a/apps/server/src/services/bot/patchSenderBatches.ts b/apps/server/src/services/bot/patchSenderBatches.tsnew file mode 100644index 00000000000..72f2873e311--- /dev/null+++ b/apps/server/src/services/bot/patchSenderBatches.ts@@ -0,0 +1,60 @@+import type { Adapter, Chat, Message, MessageContext } from 'chat';++import { getSameSenderMessages } from './mergeMessages';++type Dispatch = (+ adapter: Adapter,+ threadId: string,+ message: Message,+ context?: MessageContext,+) => Promise<void>;++/**+ * Split collected messages before the SDK chooses mention/subscription handlers.+ * Keep the SDK's thread lock and arrival order, while resolving each author's+ * identity and access gates independently. Handler-level filtering is too late:+ * it can discard another author's message or inherit their mention flag.+ *+ * This internal SDK boundary is covered by real-package contract tests.+ */+export function patchSenderBatches(+ bot: Chat,+ isCommand: (message: Message) => boolean = () => false,+): void {+ const target = bot as unknown as { dispatchToHandlers: Dispatch };+ if (typeof target.dispatchToHandlers !== 'function') {+ throw new Error('Chat SDK does not expose the sender-batch dispatch boundary');+ }+ const dispatch = target.dispatchToHandlers.bind(bot);+ target.dispatchToHandlers = async (adapter, threadId, message, context) => {+ const batches: Message[][] = [];+ for (const source of [...(context?.skipped ?? []), message]) {+ const batch = batches.at(-1);+ // Commands change conversation state and must retain their own turn on+ // either side of ordinary content, even when every source has one author.+ if (+ batch &&+ !isCommand(source) &&+ !isCommand(batch[0]) &&+ getSameSenderMessages(source, [batch[0]]).length > 0+ ) {+ batch.push(source);+ } else {+ batches.push([source]);+ }+ }+ const failures: unknown[] = [];+ for (const batch of batches) {+ const latest = batch.at(-1)!;+ try {+ await dispatch(adapter, threadId, latest, {+ skipped: batch.slice(0, -1),+ totalSinceLastHandler: batch.length,+ });+ } catch (error) {+ failures.push(error);+ }+ }+ if (failures.length) throw new AggregateError(failures, 'Sender batch dispatch failed');+ };+}diff --git a/apps/server/src/services/bot/platforms/chatSdkContract.test.ts b/apps/server/src/services/bot/platforms/chatSdkContract.test.tsindex a9c64c10955..65c44dd6fdb 100644--- a/apps/server/src/services/bot/platforms/chatSdkContract.test.ts+++ b/apps/server/src/services/bot/platforms/chatSdkContract.test.ts@@ -1,7 +1,9 @@import { createDiscordAdapter } from '@chat-adapter/discord';-import { Chat } from 'chat';+import { Chat, Message } from 'chat';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { buildReplayMessages, getSourceMessages, mergeBotMessages } from '../mergeMessages';+import { patchSenderBatches } from '../patchSenderBatches';import { patchDiscordForwardedInteractions } from './discord/patch';/**@@ -33,18 +35,28 @@ const APPLICATION_ID = '111111111111111111';const DM_CHANNEL_ID = '333333333333333333';const USER_ID = '222222222222222222';-/** Minimal in-memory `StateAdapter`; production wires ioredis instead. */-const createMemoryState = () => {+/**+ * Minimal in-memory `StateAdapter`; production wires ioredis instead.+ *+ * `exclusiveLocks` is off by default so the older tests keep dispatching every+ * event straight through. The concurrency tests turn it on, because a lock that+ * never reports contention would let each message open its own burst window+ * instead of joining the one already collecting.+ */+const createMemoryState = ({ exclusiveLocks = false }: { exclusiveLocks?: boolean } = {}) => {+ const heldLocks = new Set<string>();const values = new Map<string, unknown>();const lists = new Map<string, unknown[]>();const subscribed = new Set<string>();const queues = new Map<string, unknown[]>();return {- acquireLock: async (threadId: string) => ({- expiresAt: Number.MAX_SAFE_INTEGER,- threadId,- token: 'token',- }),+ acquireLock: async (threadId: string) => {+ if (exclusiveLocks) {+ if (heldLocks.has(threadId)) return null;+ heldLocks.add(threadId);+ }+ return { expiresAt: Number.MAX_SAFE_INTEGER, threadId, token: 'token' };+ },appendToList: async (key: string, value: unknown) => {lists.set(key, [...(lists.get(key) ?? []), value]);},@@ -56,7 +68,9 @@ const createMemoryState = () => {disconnect: async () => {},enqueue: async (threadId: string, entry: unknown) => {const queue = queues.get(threadId) ?? [];- queue.push(entry);+ // Redis stores JSON; structuredClone would preserve fields that Message.toJSON drops.+ // eslint-disable-next-line unicorn/prefer-structured-clone+ queue.push(JSON.parse(JSON.stringify(entry)));queues.set(threadId, queue);return queue.length;},@@ -66,7 +80,9 @@ const createMemoryState = () => {getList: async (key: string) => lists.get(key) ?? [],isSubscribed: async (threadId: string) => subscribed.has(threadId),queueDepth: async (threadId: string) => queues.get(threadId)?.length ?? 0,- releaseLock: async () => {},+ releaseLock: async (lock?: { threadId: string }) => {+ if (lock) heldLocks.delete(lock.threadId);+ },set: async (key: string, value: unknown) => {values.set(key, value);},@@ -84,7 +100,11 @@ const createMemoryState = () => {};};-const createRealBot = ({ patch = true }: { patch?: boolean } = {}) => {+const createRealBot = ({+ concurrency,+ isCommand,+ patch = true,+}: { concurrency?: unknown; isCommand?: (message: Message) => boolean; patch?: boolean } = {}) => {const chatBot = new Chat({adapters: {discord: createDiscordAdapter({@@ -93,10 +113,12 @@ const createRealBot = ({ patch = true }: { patch?: boolean } = {}) => {publicKey: 'a'.repeat(64),}),},- state: createMemoryState(),+ ...(concurrency ? { concurrency } : {}),+ state: createMemoryState({ exclusiveLocks: !!concurrency }),userName: 'lobehub',} as any);+ patchSenderBatches(chatBot, isCommand);if (patch) patchDiscordForwardedInteractions(chatBot);return chatBot;};@@ -308,3 +330,185 @@ describe('chat-sdk contract · Discord thread recovery', () => {await expect(adapter.createDiscordThread(DM_CHANNEL_ID, 'message-1')).rejects.toThrow();});});++describe('chat-sdk contract · overlapping-message strategies', () => {+ // WeChat delivers one logical turn as several messages: an image, then the+ // sentence about it, a few hundred ms apart. `burst` is what folds them into+ // a single agent turn, and it is the WeChat channel default in+ // `wechat/schema.ts`. `debounce` looks similar but is documented to keep only+ // the final message of the window. The difference is invisible to tsgo and+ // decides whether a user's picture reaches the model, so pin it here.+ beforeEach(() => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', { status: 200 })));+ });++ const collectTurn = async (strategy: 'burst' | 'debounce') => {+ const chatBot = createRealBot({ concurrency: { debounceMs: 80, strategy } });+ const calls: { skipped: string[]; text: string }[] = [];+ chatBot.onNewMention(async (_thread, message, context) => {+ calls.push({+ skipped: (context?.skipped ?? []).map((m) => m.text),+ text: message.text,+ });+ });+ await chatBot.initialize();++ const adapter = (chatBot as any).adapters.get('discord');+ // Not awaited in order: the window has to still be open when the second+ // message lands, which is exactly how the two WeChat webhooks arrive.+ const first = adapter.handleForwardedGatewayEvent(dmMessageEvent('这是一张图'));+ await new Promise((resolve) => setTimeout(resolve, 10));+ const second = adapter.handleForwardedGatewayEvent(dmMessageEvent('参考这个风格说话'));+ await Promise.all([first, second]);++ return calls;+ };++ it('preserves all deferred raw media through a serialized burst queue', async () => {+ const bot = createRealBot({ concurrency: { debounceMs: 80, strategy: 'burst' } });+ const received: unknown[][] = [];+ bot.onNewMention(async (_thread, message, context) => {+ received.push(+ getSourceMessages(mergeBotMessages(message, context?.skipped)).map((source) => source.raw),+ );+ });+ await bot.initialize();+ const adapter = (bot as any).adapters.get('discord');+ const threadId = `discord:@me:${DM_CHANNEL_ID}`;+ const entries = ['image', 'text'].map((kind, index) =>+ new Message({+ attachments: [],+ author: {+ fullName: 'Example user',+ isBot: false,+ isMe: false,+ userId: USER_ID,+ userName: 'example',+ },+ formatted: { type: 'root', children: [] },+ id: `deferred-${index}`,+ metadata: { dateSent: new Date(), edited: false },+ raw: { kind },+ text: kind === 'text' ? 'describe the image' : '',+ threadId,+ }).toJSON(),+ );++ await Promise.all(+ buildReplayMessages(entries).map((message) => bot.processMessage(adapter, threadId, message)),+ );++ expect(received).toEqual([[{ kind: 'image' }, { kind: 'text' }]]);+ });++ it.each(['burst', 'debounce', 'queue'])(+ 'keeps commands separate from neighboring content through real %s dispatch',+ async (strategy) => {+ const bot = createRealBot({+ concurrency: { debounceMs: 80, strategy },+ isCommand: (message) => /^\/new(?:\s|$)/.test(message.text),+ });+ const received: string[] = [];+ bot.onNewMention(async (_thread, message, context) => {+ received.push(mergeBotMessages(message, context?.skipped).text);+ });+ await bot.initialize();+ const adapter = (bot as any).adapters.get('discord');+ const threadId = `discord:@me:${DM_CHANNEL_ID}`;+ const texts = ['before', '/new', 'after', '/new', 'last'];+ const messages = texts.map(+ (text, index) =>+ new Message({+ attachments: [],+ author: {+ fullName: 'user',+ isBot: false,+ isMe: false,+ userId: USER_ID,+ userName: 'user',+ },+ formatted: { type: 'root', children: [] },+ id: `command-${index}`,+ metadata: { dateSent: new Date(), edited: false },+ raw: {},+ text,+ threadId,+ }),+ );+ await Promise.all(messages.map((message) => bot.processMessage(adapter, threadId, message)));+ expect(received).toEqual(texts);+ },+ );++ it.each(['burst', 'debounce', 'queue'])(+ 'preserves each sender through %s dispatch',+ async (strategy) => {+ const bot = createRealBot({ concurrency: { debounceMs: 80, strategy } });+ const received: { sender: string; sourceIds: string[]; authors: string[] }[] = [];+ bot.onNewMention(async (_thread, message, context) => {+ const sources = getSourceMessages(mergeBotMessages(message, context?.skipped));+ received.push({+ sender: message.author.userId,+ sourceIds: sources.map((m) => m.id),+ authors: sources.map((m) => m.author.userId),+ });+ });+ await bot.initialize();+ const adapter = (bot as any).adapters.get('discord');+ const threadId = `discord:@me:${DM_CHANNEL_ID}`;+ const messages = ['alice', 'alice', 'bob', 'alice'].map(+ (sender, index) =>+ new Message({+ attachments: [],+ author: {+ fullName: sender,+ isBot: false,+ isMe: false,+ userId: sender,+ userName: sender,+ },+ formatted: { type: 'root', children: [] },+ id: `sender-${index}`,+ metadata: { dateSent: new Date(), edited: false },+ raw: { kind: index === 0 ? 'image' : 'text' },+ text: index === 0 ? '' : `message ${index}`,+ threadId,+ }),+ );+ await Promise.all(messages.map((message) => bot.processMessage(adapter, threadId, message)));+ expect(received.flatMap((call) => call.sourceIds)).toEqual(+ messages.map((message) => message.id),+ );+ for (const call of received)+ expect(call.authors.every((author) => author === call.sender)).toBe(true);+ expect(received.map((call) => call.sender)).toContain('bob');+ },+ );++ it('collects a burst into ONE handler call carrying the earlier message', async () => {+ const calls = await collectTurn('burst');++ // One turn, not two: without this the bot answers the bare image first and+ // the question separately.+ expect(calls).toHaveLength(1);+ expect(calls[0].text).toBe('参考这个风格说话');+ // The image message survives as context, which is what+ // `mergeSkippedMessages` folds back in so its media still reaches the agent.+ expect(calls[0].skipped).toEqual(['这是一张图']);+ });++ it('hands over the earlier message under debounce too, which its own docs deny', async () => {+ const calls = await collectTurn('debounce');++ expect(calls).toHaveLength(1);+ expect(calls[0].text).toBe('参考这个风格说话');+ // chat 4.38.1 passes the earlier message exactly like `burst`, while+ // `docs/concurrency.mdx` documents debounce as keeping "only the final+ // message in the burst window". WeChat stays on `burst` regardless: that is+ // the documented contract for collecting a turn, and it also drains+ // messages that arrive while the handler is running. If this assertion ever+ // flips to `[]` the implementation has caught up with its docs — which is+ // the exact moment a debounce-configured channel starts losing images.+ expect(calls[0].skipped).toEqual(['这是一张图']);+ });+});diff --git a/apps/server/src/services/bot/platforms/discord/api.test.ts b/apps/server/src/services/bot/platforms/discord/api.test.tsnew file mode 100644index 00000000000..de80cc99e31--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/api.test.ts@@ -0,0 +1,68 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { DiscordApi } from './api';++const makeApi = () => {+ const api = new DiscordApi('token');+ const get = vi.fn();+ const post = vi.fn().mockResolvedValue({ id: 'msg-1' });+ (api as any).rest = { get, post };+ return { api, get, post };+};++describe('DiscordApi.createMessage', () => {+ it('posts a plain JSON body when neither files nor embeds are given', async () => {+ const { api, post } = makeApi();++ const result = await api.createMessage('ch-1', 'hello');++ expect(post).toHaveBeenCalledWith('/channels/ch-1/messages', { body: { content: 'hello' } });+ expect(result).toEqual({ id: 'msg-1' });+ });++ it('includes embeds in the body', async () => {+ const { api, post } = makeApi();+ const embeds = [{ color: 0x58_65_f2, title: 'Card' }];++ await api.createMessage('ch-1', 'hello', undefined, embeds);++ expect(post).toHaveBeenCalledWith('/channels/ch-1/messages', {+ body: { content: 'hello', embeds },+ });+ });++ it('sends embeds alongside files in the same message', async () => {+ const { api, post } = makeApi();+ const files = [{ data: Buffer.from('x'), name: 'x.png' }];+ const embeds = [{ title: 'Card' }];++ await api.createMessage('ch-1', 'hello', files, embeds);++ expect(post).toHaveBeenCalledWith('/channels/ch-1/messages', {+ body: { content: 'hello', embeds },+ files,+ });+ });++ it('omits the embeds key for an empty array', async () => {+ const { api, post } = makeApi();++ await api.createMessage('ch-1', 'hello', undefined, []);++ expect(post).toHaveBeenCalledWith('/channels/ch-1/messages', { body: { content: 'hello' } });+ });+});++describe('DiscordApi.listThreadMembers', () => {+ it('requests expanded member data for up to 100 thread members', async () => {+ const { api, get } = makeApi();+ get.mockResolvedValue([{ user_id: 'alice' }]);++ await expect(api.listThreadMembers('thread-1')).resolves.toEqual([{ user_id: 'alice' }]);++ expect(get).toHaveBeenCalledWith('/channels/thread-1/thread-members', {+ query: new URLSearchParams({ limit: '100', with_member: 'true' }),+ });+ });+});diff --git a/apps/server/src/services/bot/platforms/discord/api.ts b/apps/server/src/services/bot/platforms/discord/api.tsindex b0bb46c3329..1a1ff9d6eb0 100644--- a/apps/server/src/services/bot/platforms/discord/api.ts+++ b/apps/server/src/services/bot/platforms/discord/api.ts@@ -1,6 +1,7 @@import { type RawFile, REST } from '@discordjs/rest';import debug from 'debug';import {+ type APIEmbed,ApplicationCommandOptionType,ApplicationCommandType,ButtonStyle,@@ -11,6 +12,7 @@ import {type RESTGetAPIChannelMessagesResult,type RESTGetAPIChannelPinsResult,type RESTGetAPIChannelResult,+ type RESTGetAPIChannelThreadMembersResult,type RESTGetAPIGuildChannelsResult,type RESTGetAPIGuildMemberResult,type RESTGetAPIGuildThreadsResult,@@ -122,14 +124,23 @@ export class DiscordApi {channelId: string,content: string,files?: RawFile[],+ embeds?: APIEmbed[],): Promise<{ id: string }> {- log('createMessage: channel=%s, files=%d', channelId, files?.length ?? 0);+ log(+ 'createMessage: channel=%s, files=%d, embeds=%d',+ channelId,+ files?.length ?? 0,+ embeds?.length ?? 0,+ );// When `files` is set, @discordjs/rest packs `body` into `payload_json`// and emits multipart/form-data automatically. Without files we keep the// application/json path because that's what the API rate-limit bucket// expects for plain messages.const data = (await this.rest.post(Routes.channelMessages(channelId), {- body: { content },+ body: {+ content,+ ...(embeds && embeds.length > 0 ? { embeds } : {}),+ },...(files && files.length > 0 ? { files } : {}),})) as RESTPostAPIChannelMessageResult;@@ -234,6 +245,13 @@ export class DiscordApi {await this.rest.put(Routes.threadMembers(threadId, userId));}+ async listThreadMembers(threadId: string): Promise<RESTGetAPIChannelThreadMembersResult> {+ log('listThreadMembers: thread=%s', threadId);+ return (await this.rest.get(Routes.threadMembers(threadId), {+ query: new URLSearchParams({ limit: '100', with_member: 'true' }),+ })) as RESTGetAPIChannelThreadMembersResult;+ }+// ==================== Message Operations ====================async getMessages(diff --git a/apps/server/src/services/bot/platforms/discord/chatComposition.test.ts b/apps/server/src/services/bot/platforms/discord/chatComposition.test.tsnew file mode 100644index 00000000000..565d3439200--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/chatComposition.test.ts@@ -0,0 +1,184 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { DiscordApi } from './api';++const mocks = vi.hoisted(() => ({+ redisAvailable: true,+ set: vi.fn(),+ store: new Map<string, string>(),+}));++vi.mock('@/server/modules/AgentRuntime/redis', () => ({+ getAgentRuntimeRedisClient: () =>+ mocks.redisAvailable+ ? {+ get: async (key: string) => mocks.store.get(key) ?? null,+ set: async (key: string, value: string, ...ttl: unknown[]) => {+ mocks.set(key, value, ...ttl);+ mocks.store.set(key, value);+ },+ }+ : null,+}));++const { clearDiscordChatCompositionMemoryCache, isSoloDiscordBotThread } =+ await import('./chatComposition');++const human = (id: string) => ({ member: { user: { bot: false, id } } });+const bot = (id: string) => ({ member: { user: { bot: true, id } } });+const makeApi = (listThreadMembers: DiscordApi['listThreadMembers']) => ({ listThreadMembers });++describe('isSoloDiscordBotThread', () => {+ beforeEach(() => {+ mocks.redisAvailable = true;+ mocks.store.clear();+ mocks.set.mockClear();+ clearDiscordChatCompositionMemoryCache();+ });++ afterEach(() => vi.useRealTimers());++ it('treats one human plus the current bot as solo', async () => {+ const listThreadMembers = vi.fn().mockResolvedValue([human('alice'), bot('app-123')]);++ await expect(+ isSoloDiscordBotThread(makeApi(listThreadMembers), 'app-123', 'thread-1'),+ ).resolves.toBe(true);+ });++ it('requires a mention when a second human is a member, even if they never spoke', async () => {+ const listThreadMembers = vi+ .fn()+ .mockResolvedValue([human('alice'), human('bob'), bot('app-123')]);++ await expect(+ isSoloDiscordBotThread(makeApi(listThreadMembers), 'app-123', 'thread-1'),+ ).resolves.toBe(false);+ });++ it('requires a mention when another bot is in the thread', async () => {+ const listThreadMembers = vi+ .fn()+ .mockResolvedValue([human('alice'), bot('app-123'), bot('another-bot')]);++ await expect(+ isSoloDiscordBotThread(makeApi(listThreadMembers), 'app-123', 'thread-1'),+ ).resolves.toBe(false);+ });++ it('fails closed when the current bot or expanded member data is missing', async () => {+ const missingOwnBot = vi.fn().mockResolvedValue([human('alice'), bot('another-bot')]);+ const missingMember = vi.fn().mockResolvedValue([human('alice'), { user_id: 'app-123' }]);++ await expect(+ isSoloDiscordBotThread(makeApi(missingOwnBot), 'app-123', 'thread-no-own-bot'),+ ).resolves.toBe(false);+ await expect(+ isSoloDiscordBotThread(makeApi(missingMember), 'app-123', 'thread-no-member'),+ ).resolves.toBe(false);+ });++ it('fails closed when Discord rejects the member lookup', async () => {+ const listThreadMembers = vi.fn().mockRejectedValue(new Error('Missing Access'));++ await expect(+ isSoloDiscordBotThread(makeApi(listThreadMembers), 'app-123', 'thread-1'),+ ).resolves.toBe(false);+ });++ it('caches each thread verdict and gives solo a shorter TTL than shared', async () => {+ const listThreadMembers = vi+ .fn()+ .mockResolvedValueOnce([human('alice'), bot('app-123')])+ .mockResolvedValueOnce([human('alice'), bot('app-123'), bot('another-bot')]);+ const api = makeApi(listThreadMembers);++ await isSoloDiscordBotThread(api, 'app-123', 'thread-solo');+ await isSoloDiscordBotThread(api, 'app-123', 'thread-shared');+ await isSoloDiscordBotThread(api, 'app-123', 'thread-solo');++ expect(listThreadMembers).toHaveBeenCalledTimes(2);+ expect(mocks.set).toHaveBeenCalledWith(+ 'bot:discord-thread-solo:app-123:thread-solo',+ '1',+ 'EX',+ 60,+ );+ expect(mocks.set).toHaveBeenCalledWith(+ 'bot:discord-thread-solo:app-123:thread-shared',+ '0',+ 'EX',+ 600,+ );+ if (process.env.T500_ACCEPTANCE_CAPTURE === '1') {+ console.log(+ 'T500_ACCEPTANCE:cache',+ JSON.stringify({+ listCalls: listThreadMembers.mock.calls.length,+ writes: mocks.set.mock.calls,+ }),+ );+ }+ });++ it('isolates membership verdicts between threads', async () => {+ const evaluate = async (threadId: string, members: unknown[] | Error) => {+ const listThreadMembers =+ members instanceof Error+ ? vi.fn().mockRejectedValue(members)+ : vi.fn().mockResolvedValue(members);+ const result = await isSoloDiscordBotThread(makeApi(listThreadMembers), 'app-123', threadId);+ return { listCalls: listThreadMembers.mock.calls.length, result };+ };++ const observations = {+ apiError: await evaluate('matrix-api-error', new Error('Missing Access')),+ missingOwnBot: await evaluate('matrix-missing-own', [human('alice'), bot('another-bot')]),+ otherBot: await evaluate('matrix-other-bot', [+ human('alice'),+ bot('app-123'),+ bot('another-bot'),+ ]),+ secondHuman: await evaluate('matrix-second-human', [+ human('alice'),+ human('bob'),+ bot('app-123'),+ ]),+ solo: await evaluate('matrix-solo', [human('alice'), bot('app-123')]),+ };++ expect(observations).toEqual({+ apiError: { listCalls: 1, result: false },+ missingOwnBot: { listCalls: 1, result: false },+ otherBot: { listCalls: 1, result: false },+ secondHuman: { listCalls: 1, result: false },+ solo: { listCalls: 1, result: true },+ });+ if (process.env.T500_ACCEPTANCE_CAPTURE === '1') {+ console.log('T500_ACCEPTANCE:membership-matrix', JSON.stringify(observations));+ }+ });++ describe('without Redis', () => {+ beforeEach(() => {+ mocks.redisAvailable = false;+ });++ it('uses the bounded memory cache and re-checks after the solo TTL', async () => {+ vi.useFakeTimers();+ const listThreadMembers = vi+ .fn()+ .mockResolvedValueOnce([human('alice'), bot('app-123')])+ .mockResolvedValueOnce([human('alice'), human('bob'), bot('app-123')]);+ const api = makeApi(listThreadMembers);++ await expect(isSoloDiscordBotThread(api, 'app-123', 'thread-1')).resolves.toBe(true);+ await expect(isSoloDiscordBotThread(api, 'app-123', 'thread-1')).resolves.toBe(true);+ vi.advanceTimersByTime(61 * 1000);+ await expect(isSoloDiscordBotThread(api, 'app-123', 'thread-1')).resolves.toBe(false);++ expect(listThreadMembers).toHaveBeenCalledTimes(2);+ });+ });+});diff --git a/apps/server/src/services/bot/platforms/discord/chatComposition.ts b/apps/server/src/services/bot/platforms/discord/chatComposition.tsnew file mode 100644index 00000000000..b2f9b04e8e2--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/chatComposition.ts@@ -0,0 +1,94 @@+import debug from 'debug';++import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';++import { createBoundedMemoryCache } from '../feishu/boundedMemoryCache';+import type { DiscordApi } from './api';++const log = debug('bot-platform:discord:chat-composition');++/**+ * A stale solo verdict is dangerous: after another human or bot joins, the bot+ * would keep treating unmentioned chatter as addressed to it. Keep it short.+ */+const SOLO_TTL_SECONDS = 60;+/** A shared thread returning to 1:1 is rare and harmless to notice late. */+const SHARED_TTL_SECONDS = 10 * 60;++const buildKey = (applicationId: string, threadId: string): string =>+ `bot:discord-thread-solo:${applicationId}:${threadId}`;++const MEMORY_CACHE_MAX_ENTRIES = 1000;+const memoryCache = createBoundedMemoryCache<boolean>(MEMORY_CACHE_MAX_ENTRIES);++/** Test hook: the memory cache is module state and would leak across cases. */+export const clearDiscordChatCompositionMemoryCache = (): void => memoryCache.clear();++/**+ * Whether a Discord thread contains exactly one human and this bot.+ *+ * `with_member=true` is essential: the bare thread-member shape only exposes+ * user ids and cannot tell humans from bots. Missing member data, an absent+ * current bot, or any REST error fails closed to mention-only behavior.+ */+export async function isSoloDiscordBotThread(+ api: Pick<DiscordApi, 'listThreadMembers'>,+ applicationId: string,+ threadId: string,+): Promise<boolean> {+ const redis = getAgentRuntimeRedisClient();+ const key = buildKey(applicationId, threadId);+ if (redis) {+ try {+ const cached = await redis.get(key);+ if (cached === '1') return true;+ if (cached === '0') return false;+ } catch (error) {+ log('isSoloDiscordBotThread: cache read failed: %O', error);+ }+ } else {+ const cached = memoryCache.get(key);+ if (cached !== undefined) return cached;+ }++ let solo: boolean;+ try {+ const members = await api.listThreadMembers(threadId);+ const users = members.map((entry) => entry.member?.user);+ if (users.some((user) => !user)) {+ log('isSoloDiscordBotThread: thread=%s returned incomplete member data', threadId);+ return false;+ }++ const humans = users.filter((user) => user?.bot !== true);+ const bots = users.filter((user) => user?.bot === true);+ solo =+ humans.length === 1 &&+ bots.length === 1 &&+ bots[0]?.id === applicationId &&+ members.length === 2;+ log(+ 'isSoloDiscordBotThread: thread=%s humans=%d bots=%d ownBot=%s solo=%s',+ threadId,+ humans.length,+ bots.length,+ bots.some((bot) => bot?.id === applicationId),+ solo,+ );+ } catch (error) {+ log('isSoloDiscordBotThread: listThreadMembers failed, treating as shared: %O', error);+ return false;+ }++ const ttlSeconds = solo ? SOLO_TTL_SECONDS : SHARED_TTL_SECONDS;+ if (redis) {+ try {+ await redis.set(key, solo ? '1' : '0', 'EX', ttlSeconds);+ } catch (error) {+ log('isSoloDiscordBotThread: cache write failed: %O', error);+ }+ } else {+ memoryCache.set(key, solo, ttlSeconds);+ }+ return solo;+}diff --git a/apps/server/src/services/bot/platforms/discord/client.test.ts b/apps/server/src/services/bot/platforms/discord/client.test.tsindex 70cbd6625d2..e567fbca459 100644--- a/apps/server/src/services/bot/platforms/discord/client.test.ts+++ b/apps/server/src/services/bot/platforms/discord/client.test.ts@@ -34,6 +34,39 @@ describe('DiscordGatewayClient', () => {});});+ describe('isSoloBotConversation', () => {+ const installFakeApi = (client: any) => {+ const listThreadMembers = vi.fn().mockResolvedValue([]);+ client.discord = { listThreadMembers };+ return listThreadMembers;+ };++ it('checks the real Discord thread id for a guild thread', async () => {+ const client = createClient() as any;+ const listThreadMembers = installFakeApi(client);+ listThreadMembers.mockResolvedValue([+ { member: { user: { bot: false, id: 'alice' } } },+ { member: { user: { bot: true, id: 'app-123' } } },+ ]);++ await expect(+ client.isSoloBotConversation('discord:guild-1:channel-1:thread-1'),+ ).resolves.toBe(true);+ expect(listThreadMembers).toHaveBeenCalledWith('thread-1');+ });++ it('fails closed without a guild thread segment', async () => {+ const client = createClient() as any;+ const listThreadMembers = installFakeApi(client);++ const guildChannel = await client.isSoloBotConversation('discord:guild-1:channel-1');+ const dm = await client.isSoloBotConversation('discord:@me:dm-1');+ expect(guildChannel).toBe(false);+ expect(dm).toBe(false);+ expect(listThreadMembers).not.toHaveBeenCalled();+ });+ });+describe('extraGroupAllowlistChannels', () => {// Operators paste the parent channel ID (Discord "Copy Channel ID")// into groupAllowFrom; @-mentions arrive routed through an auto-createddiff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.tsindex f027b7989b3..50c01448253 100644--- a/apps/server/src/services/bot/platforms/discord/client.ts+++ b/apps/server/src/services/bot/platforms/discord/client.ts@@ -22,6 +22,7 @@ import {} from '../types';import { formatUsageStats } from '../utils';import { DiscordApi } from './api';+import { isSoloDiscordBotThread } from './chatComposition';import { DISCORD_BOT_TOKEN_PATTERN, DISCORD_PUBLIC_KEY_PATTERN } from './const';import { patchDiscordForwardedInteractions } from './patch';import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';@@ -244,6 +245,17 @@ class DiscordGatewayClient implements PlatformClient {}}+ async isSoloBotConversation(platformThreadId: string): Promise<boolean> {+ const parts = platformThreadId.split(':');+ // Only real guild threads have a member list scoped narrowly enough to+ // establish 1:1 composition. DMs are already handled by thread.isDM;+ // top-level guild channels stay mention-only because Discord has no+ // per-channel member list and GUILD_MEMBERS is a privileged intent.+ if (parts.length !== 4 || parts[1] === '@me' || !parts[3]) return false;++ return isSoloDiscordBotThread(this.discord, this.applicationId, parts[3]);+ }+getMessenger(platformThreadId: string): PlatformMessenger {const channelId = extractChannelId(platformThreadId);const threadId = platformThreadId.split(':')[3];diff --git a/apps/server/src/services/bot/platforms/discord/embeds.test.ts b/apps/server/src/services/bot/platforms/discord/embeds.test.tsnew file mode 100644index 00000000000..d23527b84ec--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/embeds.test.ts@@ -0,0 +1,227 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import {+ DISCORD_EMBED_DEFAULT_COLOR,+ DISCORD_EMBED_LIMITS,+ normalizeDiscordEmbed,+ normalizeDiscordEmbeds,+ parseDiscordEmbedColor,+} from './embeds';++describe('parseDiscordEmbedColor', () => {+ it('accepts integers within the 24-bit range', () => {+ expect(parseDiscordEmbedColor(0x58_65_f2)).toBe(0x58_65_f2);+ expect(parseDiscordEmbedColor(0)).toBe(0);+ expect(parseDiscordEmbedColor(0x1_00_00_00)).toBeUndefined();+ expect(parseDiscordEmbedColor(-1)).toBeUndefined();+ expect(parseDiscordEmbedColor(Number.NaN)).toBeUndefined();+ });++ it('accepts hex strings with or without prefix', () => {+ expect(parseDiscordEmbedColor('#22c55e')).toBe(0x22_c5_5e);+ expect(parseDiscordEmbedColor('22C55E')).toBe(0x22_c5_5e);+ expect(parseDiscordEmbedColor('0xef4444')).toBe(0xef_44_44);+ expect(parseDiscordEmbedColor(' #f59e0b ')).toBe(0xf5_9e_0b);+ });++ it('accepts decimal numeric strings', () => {+ expect(parseDiscordEmbedColor('5793266')).toBe(5_793_266);+ });++ it('rejects unknown formats', () => {+ expect(parseDiscordEmbedColor('red')).toBeUndefined();+ expect(parseDiscordEmbedColor('#fff')).toBeUndefined();+ expect(parseDiscordEmbedColor(null)).toBeUndefined();+ expect(parseDiscordEmbedColor({})).toBeUndefined();+ });+});++describe('normalizeDiscordEmbed', () => {+ it('converts a full report card into a Discord embed', () => {+ const embed = normalizeDiscordEmbed({+ author: { icon_url: 'https://x/icon.png', name: 'Landing GA', url: 'https://x' },+ color: '#5865F2',+ description: 'Example property: `example-property` | 2026-08-10',+ fields: [+ { inline: true, name: '📅 Yesterday', value: 'Users: **100**' },+ { inline: true, name: '📅 Last 7d', value: 'Users: **700**' },+ { name: '🔥 Trending Up', value: '1. +10 PV' },+ ],+ footer: { text: 'GA4 → Discord via Apps Script' },+ thumbnail: { url: 'https://x/thumb.png' },+ timestamp: '2026-08-10T08:00:00Z',+ title: '📊 Google Analytics Daily Report',+ url: 'https://analytics.google.com',+ });++ expect(embed).toEqual({+ author: { icon_url: 'https://x/icon.png', name: 'Landing GA', url: 'https://x' },+ color: 0x58_65_f2,+ description: 'Example property: `example-property` | 2026-08-10',+ fields: [+ { inline: true, name: '📅 Yesterday', value: 'Users: **100**' },+ { inline: true, name: '📅 Last 7d', value: 'Users: **700**' },+ { name: '🔥 Trending Up', value: '1. +10 PV' },+ ],+ footer: { text: 'GA4 → Discord via Apps Script' },+ thumbnail: { url: 'https://x/thumb.png' },+ timestamp: '2026-08-10T08:00:00.000Z',+ title: '📊 Google Analytics Daily Report',+ url: 'https://analytics.google.com',+ });+ });++ it('applies the default colour when none is given or it is invalid', () => {+ expect(normalizeDiscordEmbed({ title: 'a' })?.color).toBe(DISCORD_EMBED_DEFAULT_COLOR);+ expect(normalizeDiscordEmbed({ color: 'purple', title: 'a' })?.color).toBe(+ DISCORD_EMBED_DEFAULT_COLOR,+ );+ });++ it('accepts loose aliases the model is likely to produce', () => {+ const embed = normalizeDiscordEmbed({+ author: 'Reporter',+ colour: '#22c55e',+ fields: [{ label: 'Users', value: 42 }],+ footer: 'generated',+ imageUrl: 'https://x/img.png',+ text: 'body',+ thumbnailUrl: 'https://x/t.png',+ timestamp: true,+ });++ expect(embed).toMatchObject({+ author: { name: 'Reporter' },+ color: 0x22_c5_5e,+ description: 'body',+ fields: [{ name: 'Users', value: '42' }],+ footer: { text: 'generated' },+ image: { url: 'https://x/img.png' },+ thumbnail: { url: 'https://x/t.png' },+ });+ expect(typeof embed?.timestamp).toBe('string');+ });++ it('truncates strings to Discord limits and caps fields at 25', () => {+ const embed = normalizeDiscordEmbed({+ description: 'd'.repeat(5000),+ fields: Array.from({ length: 30 }, (_, i) => ({+ name: `n${i}`.repeat(200),+ value: 'v'.repeat(2000),+ })),+ footer: { text: 'f'.repeat(3000) },+ title: 't'.repeat(300),+ });++ expect(embed?.title).toHaveLength(DISCORD_EMBED_LIMITS.title);+ expect(embed?.title?.endsWith('…')).toBe(true);+ expect(embed?.description).toHaveLength(DISCORD_EMBED_LIMITS.description);+ expect(embed?.footer?.text).toHaveLength(DISCORD_EMBED_LIMITS.footerText);+ expect(embed?.fields).toHaveLength(DISCORD_EMBED_LIMITS.fields);+ expect(embed?.fields?.[0].name).toHaveLength(DISCORD_EMBED_LIMITS.fieldName);+ expect(embed?.fields?.[0].value).toHaveLength(DISCORD_EMBED_LIMITS.fieldValue);+ });++ it('drops non-http urls and unknown keys', () => {+ const embed = normalizeDiscordEmbed({+ footer: { icon_url: 'javascript:alert(1)', text: 'ok' },+ image: { url: 'data:image/png;base64,xxx' },+ title: 'a',+ unknown: 'x',+ url: 'ftp://nope',+ });++ expect(embed).toEqual({+ color: DISCORD_EMBED_DEFAULT_COLOR,+ footer: { text: 'ok' },+ title: 'a',+ });+ });++ it('fills a missing field name or value with a zero-width placeholder', () => {+ const embed = normalizeDiscordEmbed({+ fields: [{ name: 'only name' }, { value: 'only value' }, { inline: true }],+ title: 'a',+ });++ expect(embed?.fields).toEqual([+ { name: 'only name', value: '' },+ { name: '', value: 'only value' },+ ]);+ });++ it('returns undefined when nothing visible remains', () => {+ expect(normalizeDiscordEmbed({ color: '#fff000', url: 'https://x' })).toBeUndefined();+ expect(normalizeDiscordEmbed({ title: ' ' })).toBeUndefined();+ expect(normalizeDiscordEmbed('not an object')).toBeUndefined();+ expect(normalizeDiscordEmbed(null)).toBeUndefined();+ });+});++describe('normalizeDiscordEmbeds', () => {+ it('returns undefined for empty or non-array input', () => {+ expect(normalizeDiscordEmbeds(undefined)).toBeUndefined();+ expect(normalizeDiscordEmbeds([])).toBeUndefined();+ expect(normalizeDiscordEmbeds('nope')).toBeUndefined();+ expect(normalizeDiscordEmbeds([{ color: 1 }, null])).toBeUndefined();+ });++ it('skips invalid entries and caps the list at 10 embeds', () => {+ const embeds = normalizeDiscordEmbeds([+ null,+ ...Array.from({ length: 12 }, (_, i) => ({ title: `e${i}` })),+ ]);++ expect(embeds).toHaveLength(DISCORD_EMBED_LIMITS.perMessage);+ expect(embeds?.[0].title).toBe('e0');+ });++ it('shrinks a later embed into the remaining 6000 character message budget', () => {+ const embeds = normalizeDiscordEmbeds([+ { description: 'a'.repeat(4000) },+ { description: 'b'.repeat(2500) },+ { description: 'c'.repeat(1500) },+ ]);++ expect(embeds).toHaveLength(2);+ expect(embeds?.[0].description).toHaveLength(4000);+ // second embed is cut down to the 2000 characters left in the budget+ expect(embeds?.[1].description).toHaveLength(2000);+ expect(embeds?.[1].description?.startsWith('b')).toBe(true);+ });++ it('shrinks an oversized single embed by dropping trailing fields, then the description', () => {+ const embeds = normalizeDiscordEmbeds([+ {+ description: 'd'.repeat(5000),+ fields: Array.from({ length: 30 }, (_, i) => ({ name: `f${i}`, value: 'v'.repeat(2000) })),+ footer: { text: 'footer' },+ title: 'Report',+ },+ ]);++ const embed = embeds?.[0];+ expect(embed?.title).toBe('Report');+ expect(embed?.footer?.text).toBe('footer');+ // description is capped to 4096 first; with title + footer that leaves+ // room for one 1024-char field (2 + 1024) but not two.+ expect(embed?.fields).toHaveLength(1);+ expect(embed?.description).toHaveLength(DISCORD_EMBED_LIMITS.description);+ const total =+ (embed?.title?.length ?? 0) ++ (embed?.description?.length ?? 0) ++ (embed?.footer?.text.length ?? 0) ++ (embed?.fields ?? []).reduce((n, f) => n + f.name.length + f.value.length, 0);+ expect(total).toBeLessThanOrEqual(DISCORD_EMBED_LIMITS.totalCharacters);+ });++ it('drops an embed whose fixed parts alone exceed the remaining budget', () => {+ const embeds = normalizeDiscordEmbeds([+ { description: 'a'.repeat(4096), footer: { text: 'f'.repeat(1900) } },+ { footer: { text: 'g'.repeat(100) }, title: 't'.repeat(200) },+ ]);++ expect(embeds).toHaveLength(1);+ });+});diff --git a/apps/server/src/services/bot/platforms/discord/embeds.ts b/apps/server/src/services/bot/platforms/discord/embeds.tsnew file mode 100644index 00000000000..357d65597d3--- /dev/null+++ b/apps/server/src/services/bot/platforms/discord/embeds.ts@@ -0,0 +1,263 @@+import type { APIEmbed, APIEmbedField } from 'discord-api-types/v10';++/**+ * Discord embed limits.+ * @see https://discord.com/developers/docs/resources/message#embed-object-embed-limits+ */+export const DISCORD_EMBED_LIMITS = {+ /** Author name */+ authorName: 256,+ /** Embed description */+ description: 4096,+ /** Field name */+ fieldName: 256,+ /** Field value */+ fieldValue: 1024,+ /** Fields per embed */+ fields: 25,+ /** Footer text */+ footerText: 2048,+ /** Embeds per message */+ perMessage: 10,+ /** Embed title */+ title: 256,+ /** Sum of title + description + field names/values + footer + author across all embeds */+ totalCharacters: 6000,+} as const;++/** Default accent colour (Discord "blurple") when the caller passes none. */+export const DISCORD_EMBED_DEFAULT_COLOR = 0x58_65_f2;++const ZERO_WIDTH_SPACE = '\u200B';++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const truncate = (value: string, max: number): string => {+ if (value.length <= max) return value;+ if (max <= 1) return value.slice(0, max);+ return `${value.slice(0, max - 1)}…`;+};++const readString = (value: unknown, max: number): string | undefined => {+ if (typeof value === 'number' || typeof value === 'boolean') value = String(value);+ if (typeof value !== 'string') return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ return truncate(trimmed, max);+};++const readUrl = (value: unknown): string | undefined => {+ if (typeof value !== 'string') return undefined;+ const trimmed = value.trim();+ if (!/^(?:https?|attachment):\/\//i.test(trimmed)) return undefined;+ return trimmed;+};++/**+ * Accepts a Discord colour integer, a `#RRGGBB` / `RRGGBB` / `0xRRGGBB`+ * string, or a decimal numeric string. Returns undefined for anything else so+ * the caller can fall back to the default accent.+ */+export const parseDiscordEmbedColor = (value: unknown): number | undefined => {+ if (typeof value === 'number') {+ if (!Number.isFinite(value)) return undefined;+ const int = Math.trunc(value);+ return int >= 0 && int <= 0xff_ff_ff ? int : undefined;+ }+ if (typeof value !== 'string') return undefined;+ const raw = value.trim();+ if (!raw) return undefined;+ const hex = raw.match(/^(?:#|0x)?([\dA-Fa-f]{6})$/);+ if (hex) return Number.parseInt(hex[1], 16);+ if (/^\d+$/.test(raw)) {+ const int = Number.parseInt(raw, 10);+ return int <= 0xff_ff_ff ? int : undefined;+ }+ return undefined;+};++const readTimestamp = (value: unknown): string | undefined => {+ if (value === true) return new Date().toISOString();+ if (typeof value === 'number') {+ const date = new Date(value);+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();+ }+ if (typeof value !== 'string' || !value.trim()) return undefined;+ const date = new Date(value);+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();+};++const readMedia = (value: unknown): { url: string } | undefined => {+ const url =+ typeof value === 'string' ? readUrl(value) : isRecord(value) ? readUrl(value.url) : undefined;+ return url ? { url } : undefined;+};++const readFields = (value: unknown): APIEmbedField[] => {+ if (!Array.isArray(value)) return [];+ const fields: APIEmbedField[] = [];+ for (const item of value) {+ if (fields.length >= DISCORD_EMBED_LIMITS.fields) break;+ if (!isRecord(item)) continue;+ const name = readString(item.name ?? item.label ?? item.title, DISCORD_EMBED_LIMITS.fieldName);+ const fieldValue = readString(item.value, DISCORD_EMBED_LIMITS.fieldValue);+ // Discord rejects empty field names/values — fall back to a zero-width+ // placeholder so a partially-filled field still renders.+ if (!name && !fieldValue) continue;+ const field: APIEmbedField = {+ name: name ?? ZERO_WIDTH_SPACE,+ value: fieldValue ?? ZERO_WIDTH_SPACE,+ };+ if (typeof item.inline === 'boolean') field.inline = item.inline;+ fields.push(field);+ }+ return fields;+};++const embedCharacterCount = (embed: APIEmbed): number =>+ (embed.title?.length ?? 0) ++ (embed.description?.length ?? 0) ++ (embed.footer?.text.length ?? 0) ++ (embed.author?.name.length ?? 0) ++ (embed.fields ?? []).reduce((sum, f) => sum + f.name.length + f.value.length, 0);++/**+ * Coerce a single loosely-typed embed (as produced by an LLM tool call) into a+ * Discord `APIEmbed`. Unknown keys are dropped, strings are trimmed to+ * Discord's per-field caps, and `color` accepts hex strings. Returns undefined+ * when nothing renderable is left so the caller can skip it instead of+ * letting Discord reject the whole message with a 400.+ */+export const normalizeDiscordEmbed = (input: unknown): APIEmbed | undefined => {+ if (!isRecord(input)) return undefined;++ const embed: APIEmbed = {};++ const title = readString(input.title, DISCORD_EMBED_LIMITS.title);+ if (title) embed.title = title;++ const description = readString(+ input.description ?? input.text ?? input.content,+ DISCORD_EMBED_LIMITS.description,+ );+ if (description) embed.description = description;++ const url = readUrl(input.url);+ if (url) embed.url = url;++ const timestamp = readTimestamp(input.timestamp);+ if (timestamp) embed.timestamp = timestamp;++ const footerInput = isRecord(input.footer) ? input.footer : { text: input.footer };+ const footerText = readString(footerInput.text, DISCORD_EMBED_LIMITS.footerText);+ if (footerText) {+ embed.footer = { text: footerText };+ const iconUrl = readUrl(footerInput.icon_url ?? footerInput.iconUrl);+ if (iconUrl) embed.footer.icon_url = iconUrl;+ }++ const authorInput = isRecord(input.author) ? input.author : { name: input.author };+ const authorName = readString(authorInput.name, DISCORD_EMBED_LIMITS.authorName);+ if (authorName) {+ embed.author = { name: authorName };+ const authorUrl = readUrl(authorInput.url);+ if (authorUrl) embed.author.url = authorUrl;+ const iconUrl = readUrl(authorInput.icon_url ?? authorInput.iconUrl);+ if (iconUrl) embed.author.icon_url = iconUrl;+ }++ const image = readMedia(input.image ?? input.imageUrl);+ if (image) embed.image = image;++ const thumbnail = readMedia(input.thumbnail ?? input.thumbnailUrl);+ if (thumbnail) embed.thumbnail = thumbnail;++ const fields = readFields(input.fields);+ if (fields.length > 0) embed.fields = fields;++ // An embed with only a colour / url / timestamp renders as an empty box on+ // Discord, so require at least one visible text or media block.+ const hasContent =+ !!embed.title ||+ !!embed.description ||+ !!embed.footer ||+ !!embed.author ||+ !!embed.image ||+ !!embed.thumbnail ||+ !!embed.fields;+ if (!hasContent) return undefined;++ embed.color = parseDiscordEmbedColor(input.color ?? input.colour) ?? DISCORD_EMBED_DEFAULT_COLOR;++ return embed;+};++/**+ * Shrink one embed until it fits the remaining character budget: drop trailing+ * fields first (the least important part of a report card), then cut the+ * description. Returns undefined when even the title/footer/author alone+ * exceed the budget.+ */+const fitEmbedToBudget = (embed: APIEmbed, budget: number): APIEmbed | undefined => {+ if (embedCharacterCount(embed) <= budget) return embed;++ const fitted: APIEmbed = { ...embed, fields: embed.fields ? [...embed.fields] : undefined };+ while (fitted.fields && fitted.fields.length > 0 && embedCharacterCount(fitted) > budget) {+ fitted.fields.pop();+ }+ if (fitted.fields && fitted.fields.length === 0) delete fitted.fields;++ if (embedCharacterCount(fitted) > budget && fitted.description) {+ const overflow = embedCharacterCount(fitted) - budget;+ const room = fitted.description.length - overflow;+ if (room > 0) {+ fitted.description = truncate(fitted.description, room);+ } else {+ delete fitted.description;+ }+ }++ if (embedCharacterCount(fitted) > budget) return undefined;++ const hasContent =+ !!fitted.title ||+ !!fitted.description ||+ !!fitted.footer ||+ !!fitted.author ||+ !!fitted.image ||+ !!fitted.thumbnail ||+ !!fitted.fields;+ return hasContent ? fitted : undefined;+};++/**+ * Normalize a list of tool-supplied embeds for one Discord message: drops+ * invalid entries, caps the list at 10 embeds, and enforces the 6000-character+ * budget shared by all embeds in a single message. An embed that would+ * overflow the budget is shrunk (trailing fields, then description) rather+ * than sent as-is, since Discord rejects the whole request otherwise; embeds+ * that cannot be shrunk to fit are dropped.+ *+ * Returns undefined when nothing survives so callers can spread the result+ * into the request body without emitting `embeds: []`.+ */+export const normalizeDiscordEmbeds = (input: unknown): APIEmbed[] | undefined => {+ if (!Array.isArray(input) || input.length === 0) return undefined;++ const embeds: APIEmbed[] = [];+ let budget = DISCORD_EMBED_LIMITS.totalCharacters;++ for (const item of input) {+ if (embeds.length >= DISCORD_EMBED_LIMITS.perMessage) break;+ if (budget <= 0) break;+ const normalized = normalizeDiscordEmbed(item);+ if (!normalized) continue;+ const embed = fitEmbedToBudget(normalized, budget);+ if (!embed) continue;+ budget -= embedCharacterCount(embed);+ embeds.push(embed);+ }++ return embeds.length > 0 ? embeds : undefined;+};diff --git a/apps/server/src/services/bot/platforms/discord/schema.ts b/apps/server/src/services/bot/platforms/discord/schema.tsindex 1a27c84e3f8..5eea018d931 100644--- a/apps/server/src/services/bot/platforms/discord/schema.ts+++ b/apps/server/src/services/bot/platforms/discord/schema.ts@@ -79,9 +79,17 @@ export const schema: FieldSchema[] = [key: 'concurrency',default: 'queue',description: 'channel.concurrencyHint',- enum: ['queue', 'debounce'],- enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],- enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],label: 'channel.concurrency',type: 'string',},@@ -93,7 +101,7 @@ export const schema: FieldSchema[] = [maximum: MAX_BOT_DEBOUNCE_MS,minimum: 100,type: 'number',- visibleWhen: { field: 'concurrency', value: 'debounce' },+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },},{key: 'showUsageStats',diff --git a/apps/server/src/services/bot/platforms/discord/service.test.ts b/apps/server/src/services/bot/platforms/discord/service.test.tsindex 5555470a21d..1a14304933b 100644--- a/apps/server/src/services/bot/platforms/discord/service.test.ts+++ b/apps/server/src/services/bot/platforms/discord/service.test.ts@@ -23,7 +23,7 @@ describe('DiscordMessageService.sendMessage', () => {platform: 'discord',});- expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'hello');+ expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'hello', undefined, undefined);expect(result).toMatchObject({ channelId: 'ch-1', messageId: 'msg-1', platform: 'discord' });});@@ -55,6 +55,7 @@ describe('DiscordMessageService.sendMessage', () => {name: 'foo.png',}),]),+ undefined,);});@@ -101,7 +102,105 @@ describe('DiscordMessageService.sendMessage', () => {// Only a single text-only call should be made — no files arg.expect(api.createMessage).toHaveBeenCalledTimes(1);- expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'still send the text');+ expect(api.createMessage).toHaveBeenCalledWith(+ 'ch-1',+ 'still send the text',+ undefined,+ undefined,+ );+ });+});++describe('DiscordMessageService.sendMessage embeds', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', vi.fn());+ });++ it('normalizes embeds and sends them with the text content', async () => {+ const api = makeApi();+ const service = new DiscordMessageService(api as any);++ await service.sendMessage({+ channelId: 'ch-1',+ content: 'Daily report',+ embeds: [+ {+ color: '#22c55e',+ fields: [{ inline: true, name: 'Users', value: '100' }],+ footer: { text: 'GA4' },+ title: '📊 Daily Report',+ },+ ],+ platform: 'discord',+ });++ expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'Daily report', undefined, [+ {+ color: 0x22_c5_5e,+ fields: [{ inline: true, name: 'Users', value: '100' }],+ footer: { text: 'GA4' },+ title: '📊 Daily Report',+ },+ ]);+ });++ it('omits embeds entirely when none survive normalization', async () => {+ const api = makeApi();+ const service = new DiscordMessageService(api as any);++ await service.sendMessage({+ channelId: 'ch-1',+ content: 'plain',+ embeds: [{ color: '#fff000' } as any],+ platform: 'discord',+ });++ expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'plain', undefined, undefined);+ });++ it('attaches embeds only to the first batch when attachments are split', async () => {+ const api = makeApi();+ const service = new DiscordMessageService(api as any);++ const attachments = Array.from({ length: 12 }, (_, i) => ({+ data: Buffer.from(`bytes-${i}`).toString('base64'),+ mimeType: 'image/png',+ name: `a${i}.png`,+ type: 'image' as const,+ }));++ await service.sendMessage({+ attachments,+ channelId: 'ch-1',+ content: 'batch',+ embeds: [{ title: 'Card' }],+ platform: 'discord',+ });++ expect(api.createMessage).toHaveBeenCalledTimes(2);+ expect(api.createMessage.mock.calls[0][3]).toEqual([+ expect.objectContaining({ title: 'Card' }),+ ]);+ expect(api.createMessage.mock.calls[1][3]).toBeUndefined();+ });++ it('keeps embeds when all attachments fail to materialize', async () => {+ const api = makeApi();+ const service = new DiscordMessageService(api as any);+ vi.mocked(fetch).mockResolvedValueOnce(new Response(null, { status: 500 }) as any);++ await service.sendMessage({+ attachments: [{ fetchUrl: 'https://cdn.example.com/broken.png', type: 'image' }],+ channelId: 'ch-1',+ content: 'text',+ embeds: [{ title: 'Card' }],+ platform: 'discord',+ });++ expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'text', undefined, [+ expect.objectContaining({ title: 'Card' }),+ ]);});});@@ -138,8 +237,28 @@ describe('DiscordMessageService.sendDirectMessage', () => {expect.arrayContaining([expect.objectContaining({ contentType: 'image/png', name: 'foo.png' }),]),+ undefined,);});++ it('forwards embeds to the DM channel', async () => {+ const api = {+ createDMChannel: vi.fn().mockResolvedValue({ id: 'dm-ch' }),+ createMessage: vi.fn().mockResolvedValue({ id: 'msg-dm' }),+ };+ const service = new DiscordMessageService(api as any);++ await service.sendDirectMessage({+ content: 'card',+ embeds: [{ title: 'Hi' }],+ platform: 'discord',+ userId: 'user-1',+ });++ expect(api.createMessage).toHaveBeenCalledWith('dm-ch', 'card', undefined, [+ expect.objectContaining({ title: 'Hi' }),+ ]);+ });});describe('DiscordMessageService.replyToThread', () => {@@ -162,6 +281,23 @@ describe('DiscordMessageService.replyToThread', () => {'thread-id-1','thread reply',expect.arrayContaining([expect.objectContaining({ name: 'x.png' })]),+ undefined,);});++ it('forwards embeds to the thread', async () => {+ const api = { createMessage: vi.fn().mockResolvedValue({ id: 'tr-2' }) };+ const service = new DiscordMessageService(api as any);++ await service.replyToThread({+ content: 'card reply',+ embeds: [{ description: 'body' }],+ platform: 'discord',+ threadId: 'thread-id-1',+ });++ expect(api.createMessage).toHaveBeenCalledWith('thread-id-1', 'card reply', undefined, [+ expect.objectContaining({ description: 'body' }),+ ]);+ });});diff --git a/apps/server/src/services/bot/platforms/discord/service.ts b/apps/server/src/services/bot/platforms/discord/service.tsindex 5d5bf50dca7..709d9fcdfc5 100644--- a/apps/server/src/services/bot/platforms/discord/service.ts+++ b/apps/server/src/services/bot/platforms/discord/service.ts@@ -43,6 +43,7 @@ import type { MessageRuntimeService } from '@/server/services/toolExecution/servimport type { DiscordApi } from './api';import { MAX_DISCORD_HISTORY_LIMIT } from './const';+import { normalizeDiscordEmbeds } from './embeds';import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';/**@@ -66,30 +67,42 @@ export class DiscordMessageService implements MessageRuntimeService {* 10-files-per-message cap, and falls back to a text-only `createMessage`* if all attachments fail to resolve. Returns the message id of the FIRST* post (the one that carried the text content).+ *+ * `embeds` are normalized to Discord's embed limits (see `embeds.ts`) and+ * ride along the first post together with the text content, so a rich+ * "card" reply renders as a single Discord message.*/private async postToChannel(channelId: string,content: string,attachments: SendMessageParams['attachments'],+ rawEmbeds?: SendMessageParams['embeds'],): Promise<{ id: string } | undefined> {+ const embeds = normalizeDiscordEmbeds(rawEmbeds);+if (!attachments?.length) {- return this.api.createMessage(channelId, content);+ return this.api.createMessage(channelId, content, undefined, embeds);}const files = await materializeAttachmentsForDiscord(attachments);if (files.length === 0) {// All attachments failed to materialize — fall back to text-only so the// reply still reaches the user.- return this.api.createMessage(channelId, content);+ return this.api.createMessage(channelId, content, undefined, embeds);}// Discord caps attachments per message at 10. The first batch carries the- // text content; subsequent batches send empty-content follow-ups so the- // reply body isn't repeated.+ // text content and embeds; subsequent batches send empty-content+ // follow-ups so the reply body isn't repeated.const batches = batchDiscordFiles(files);let firstResult: { id: string } | undefined;for (const [i, batch] of batches.entries()) {- const result = await this.api.createMessage(channelId, i === 0 ? content : '', batch);+ const result = await this.api.createMessage(+ channelId,+ i === 0 ? content : '',+ batch,+ i === 0 ? embeds : undefined,+ );if (i === 0) firstResult = result;}return firstResult;@@ -99,14 +112,24 @@ export class DiscordMessageService implements MessageRuntimeService {sendDirectMessage = async (params: SendDirectMessageParams): Promise<SendDirectMessageState> => {const dmChannel = await this.api.createDMChannel(params.userId);- const result = await this.postToChannel(dmChannel.id, params.content, params.attachments);+ const result = await this.postToChannel(+ dmChannel.id,+ params.content,+ params.attachments,+ params.embeds,+ );return { channelId: dmChannel.id, messageId: result?.id, platform: 'discord' };};// ==================== Core Message Operations ====================sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {- const result = await this.postToChannel(params.channelId, params.content, params.attachments);+ const result = await this.postToChannel(+ params.channelId,+ params.content,+ params.attachments,+ params.embeds,+ );return { channelId: params.channelId, messageId: result?.id, platform: 'discord' };};@@ -294,7 +317,12 @@ export class DiscordMessageService implements MessageRuntimeService {replyToThread = async (params: ReplyToThreadParams): Promise<ReplyToThreadState> => {// Discord threads ARE channels — posting to a thread id goes through the// same `channelMessages` route, so we reuse the shared attachments path.- const result = await this.postToChannel(params.threadId, params.content, params.attachments);+ const result = await this.postToChannel(+ params.threadId,+ params.content,+ params.attachments,+ params.embeds,+ );return { messageId: result?.id, threadId: params.threadId };};diff --git a/apps/server/src/services/bot/platforms/imessage/schema.ts b/apps/server/src/services/bot/platforms/imessage/schema.tsindex 1dfb8ba0398..621b4d948f1 100644--- a/apps/server/src/services/bot/platforms/imessage/schema.ts+++ b/apps/server/src/services/bot/platforms/imessage/schema.ts@@ -33,9 +33,17 @@ export const schema: FieldSchema[] = [key: 'concurrency',default: 'queue',description: 'channel.concurrencyHint',- enum: ['queue', 'debounce'],- enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],- enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],label: 'channel.concurrency',type: 'string',},@@ -47,7 +55,7 @@ export const schema: FieldSchema[] = [maximum: MAX_BOT_DEBOUNCE_MS,minimum: 100,type: 'number',- visibleWhen: { field: 'concurrency', value: 'debounce' },+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },},{key: 'showUsageStats',diff --git a/apps/server/src/services/bot/platforms/index.ts b/apps/server/src/services/bot/platforms/index.tsindex 6a6b3da5aec..8ec30d38c9f 100644--- a/apps/server/src/services/bot/platforms/index.ts+++ b/apps/server/src/services/bot/platforms/index.ts@@ -71,7 +71,12 @@ export type {ValidationResult,} from './types';export { ClientFactory, messengerContentText } from './types';-export type { ProviderConfigInput, ResolvedBotProviderConfig } from './utils';+export type {+ BotConcurrencyStrategy,+ ProviderConfigInput,+ ResolvedBotConcurrency,+ ResolvedBotProviderConfig,+} from './utils';export {buildRuntimeKey,extractDefaults,@@ -82,8 +87,10 @@ export {mergeWithDefaults,parseRuntimeKey,platformFromThreadId,+ resolveBotConcurrency,resolveBotProviderConfig,resolveConnectionMode,+ withResolvedConcurrencySettings,} from './utils';export type { BotProviderFieldValues, FieldFormatViolation } from './validateFieldFormats';export { collectFieldFormatViolations, formatFieldFormatViolations } from './validateFieldFormats';diff --git a/apps/server/src/services/bot/platforms/line/schema.ts b/apps/server/src/services/bot/platforms/line/schema.tsindex f29ee59bf70..3396f729a14 100644--- a/apps/server/src/services/bot/platforms/line/schema.ts+++ b/apps/server/src/services/bot/platforms/line/schema.ts@@ -52,9 +52,17 @@ export const schema: FieldSchema[] = [key: 'concurrency',default: 'queue',description: 'channel.concurrencyHint',- enum: ['queue', 'debounce'],- enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],- enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],label: 'channel.concurrency',type: 'string',},@@ -66,7 +74,7 @@ export const schema: FieldSchema[] = [maximum: MAX_BOT_DEBOUNCE_MS,minimum: 100,type: 'number',- visibleWhen: { field: 'concurrency', value: 'debounce' },+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },},{key: 'showUsageStats',diff --git a/apps/server/src/services/bot/platforms/qq/schema.ts b/apps/server/src/services/bot/platforms/qq/schema.tsindex 9d7690ff865..0d3592d3477 100644--- a/apps/server/src/services/bot/platforms/qq/schema.ts+++ b/apps/server/src/services/bot/platforms/qq/schema.ts@@ -64,9 +64,17 @@ export const schema: FieldSchema[] = [key: 'concurrency',default: 'queue',description: 'channel.concurrencyHint',- enum: ['queue', 'debounce'],- enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],- enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],label: 'channel.concurrency',type: 'string',},@@ -78,7 +86,7 @@ export const schema: FieldSchema[] = [maximum: MAX_BOT_DEBOUNCE_MS,minimum: 100,type: 'number',- visibleWhen: { field: 'concurrency', value: 'debounce' },+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },},{key: 'showUsageStats',diff --git a/apps/server/src/services/bot/platforms/slack/schema.ts b/apps/server/src/services/bot/platforms/slack/schema.tsindex eff4ec06ad6..e6dc3747fc2 100644--- a/apps/server/src/services/bot/platforms/slack/schema.ts+++ b/apps/server/src/services/bot/platforms/slack/schema.ts@@ -85,9 +85,17 @@ export const schema: FieldSchema[] = [key: 'concurrency',default: 'queue',description: 'channel.concurrencyHint',- enum: ['queue', 'debounce'],- enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],- enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],label: 'channel.concurrency',type: 'string',},@@ -99,7 +107,7 @@ export const schema: FieldSchema[] = [maximum: MAX_BOT_DEBOUNCE_MS,minimum: 100,type: 'number',- visibleWhen: { field: 'concurrency', value: 'debounce' },+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },},{key: 'showUsageStats',diff --git a/apps/server/src/services/bot/platforms/telegram/schema.ts b/apps/server/src/services/bot/platforms/telegram/schema.tsindex 082be7c1ccc..500a5f22e60 100644--- a/apps/server/src/services/bot/platforms/telegram/schema.ts+++ b/apps/server/src/services/bot/platforms/telegram/schema.ts@@ -59,9 +59,17 @@ export const schema: FieldSchema[] = [key: 'concurrency',default: 'queue',description: 'channel.concurrencyHint',- enum: ['queue', 'debounce'],- enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],- enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],label: 'channel.concurrency',type: 'string',},@@ -73,7 +81,7 @@ export const schema: FieldSchema[] = [maximum: MAX_BOT_DEBOUNCE_MS,minimum: 100,type: 'number',- visibleWhen: { field: 'concurrency', value: 'debounce' },+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },},{key: 'showUsageStats',diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.tsindex 81953708e85..26bc8345b37 100644--- a/apps/server/src/services/bot/platforms/types.ts+++ b/apps/server/src/services/bot/platforms/types.ts@@ -105,7 +105,11 @@ export interface FieldSchema {* - 'array' → list*/type: 'array' | 'boolean' | 'integer' | 'number' | 'object' | 'password' | 'string';- /** Conditional visibility: show only when another field matches a value */+ /**+ * Conditional visibility: show only when another field matches a value. Pass+ * an array to match any of several values, e.g. a window size that applies to+ * both the `burst` and `debounce` concurrency strategies.+ */visibleWhen?: { field: string; value: unknown };}diff --git a/apps/server/src/services/bot/platforms/utils.test.ts b/apps/server/src/services/bot/platforms/utils.test.tsindex dff6090ea76..2796f466f5f 100644--- a/apps/server/src/services/bot/platforms/utils.test.ts+++ b/apps/server/src/services/bot/platforms/utils.test.ts@@ -1,3 +1,4 @@+import { DEFAULT_BOT_DEBOUNCE_MS } from '@lobechat/const';import { describe, expect, it } from 'vitest';import type { PlatformDefinition } from './types';@@ -5,8 +6,10 @@ import {formatDuration,formatTokens,formatUsageStats,+ resolveBotConcurrency,resolveBotProviderConfig,resolveConnectionMode,+ withResolvedConcurrencySettings,} from './utils';function makePlatform(overrides: Partial<PlatformDefinition> = {}): PlatformDefinition {@@ -140,3 +143,96 @@ describe('resolveConnectionMode', () => {expect(resolveConnectionMode(undefined, { connectionMode: 'websocket' })).toBe('websocket');});});++describe('resolveBotConcurrency', () => {+ // WeChat splits one logical turn across several messages, so it collects a+ // window before the first dispatch. Everything else dispatches at once and+ // merges whatever arrives while the handler runs.+ it('collects a burst on WeChat when the channel has no stored strategy', () => {+ expect(resolveBotConcurrency('wechat', {})).toEqual({+ debounceMs: DEFAULT_BOT_DEBOUNCE_MS,+ strategy: 'burst',+ });+ });++ it('rescues a WeChat channel created before burst existed', () => {+ // Older channels persisted `concurrency: queue` + the old 5s window+ // when they were created, so a schema default alone would never reach+ // them. The stored window goes with it: it is hidden and unused under+ // `queue`, and 5s in front of every reply reads as a dead bot.+ expect(resolveBotConcurrency('wechat', { concurrency: 'queue', debounceMs: 5000 })).toEqual({+ debounceMs: DEFAULT_BOT_DEBOUNCE_MS,+ strategy: 'burst',+ });+ });++ it('leaves an explicit WeChat debounce exactly as the operator set it', () => {+ expect(+ resolveBotConcurrency('wechat', { concurrency: 'debounce', debounceMs: 15_000 }),+ ).toEqual({ debounceMs: 15_000, strategy: 'debounce' });+ });++ it('keeps the plain queue on platforms that send media with its caption', () => {+ expect(resolveBotConcurrency('telegram', { concurrency: 'queue', debounceMs: 5000 })).toEqual({+ debounceMs: 5000,+ strategy: 'queue',+ });+ expect(resolveBotConcurrency('telegram', {})).toEqual({+ debounceMs: DEFAULT_BOT_DEBOUNCE_MS,+ strategy: 'queue',+ });+ });++ it('honours burst and debounce wherever they were chosen', () => {+ expect(resolveBotConcurrency('telegram', { concurrency: 'burst', debounceMs: 1200 })).toEqual({+ debounceMs: 1200,+ strategy: 'burst',+ });+ expect(resolveBotConcurrency('slack', { concurrency: 'debounce' })).toEqual({+ debounceMs: DEFAULT_BOT_DEBOUNCE_MS,+ strategy: 'debounce',+ });+ });++ it('falls back to the queue for missing or nonsensical stored values', () => {+ expect(resolveBotConcurrency('discord', undefined).strategy).toBe('queue');+ expect(resolveBotConcurrency('discord', { concurrency: 'nonsense' }).strategy).toBe('queue');+ // A zero or negative window would make the SDK dispatch with no wait.+ expect(resolveBotConcurrency('discord', { concurrency: 'burst', debounceMs: 0 })).toEqual({+ debounceMs: DEFAULT_BOT_DEBOUNCE_MS,+ strategy: 'burst',+ });+ });+});++describe('withResolvedConcurrencySettings', () => {+ it('shows a legacy WeChat channel the strategy the runtime will actually use', () => {+ // Rendering the stored `queue` raw would put a value in the picker that the+ // platform no longer offers, and saving the untouched form would persist+ // the stale 5s window next to a strategy that DOES read it.+ expect(+ withResolvedConcurrencySettings('wechat', {+ charLimit: 2000,+ concurrency: 'queue',+ debounceMs: 5000,+ }),+ ).toEqual({ charLimit: 2000, concurrency: 'burst', debounceMs: DEFAULT_BOT_DEBOUNCE_MS });+ });++ it('passes through every channel the runtime does not override', () => {+ const telegram = { concurrency: 'queue', debounceMs: 5000 };+ expect(withResolvedConcurrencySettings('telegram', telegram)).toBe(telegram);++ const wechatBurst = { concurrency: 'burst', debounceMs: 1200 };+ expect(withResolvedConcurrencySettings('wechat', wechatBurst)).toBe(wechatBurst);++ const wechatDebounce = { concurrency: 'debounce', debounceMs: 15_000 };+ expect(withResolvedConcurrencySettings('wechat', wechatDebounce)).toBe(wechatDebounce);+ });++ it('leaves settings without a stored strategy alone', () => {+ const bare = { charLimit: 2000 };+ expect(withResolvedConcurrencySettings('wechat', bare)).toBe(bare);+ expect(withResolvedConcurrencySettings('wechat', undefined)).toBeUndefined();+ });+});diff --git a/apps/server/src/services/bot/platforms/utils.ts b/apps/server/src/services/bot/platforms/utils.tsindex 3bae5935244..6a0cf799456 100644--- a/apps/server/src/services/bot/platforms/utils.ts+++ b/apps/server/src/services/bot/platforms/utils.ts@@ -1,3 +1,4 @@+import { DEFAULT_BOT_DEBOUNCE_MS } from '@lobechat/const';import { merge } from '@lobechat/utils';import type {@@ -56,6 +57,85 @@ export function mergeWithDefaults(return merge(defaults, userSettings) as Record<string, unknown>;}+// --------------- Concurrency resolution ---------------++export type BotConcurrencyStrategy = 'burst' | 'debounce' | 'queue';++export interface ResolvedBotConcurrency {+ /** Collection window, in ms. Ignored by `queue`, which dispatches at once. */+ debounceMs: number;+ strategy: BotConcurrencyStrategy;+}++/**+ * Platforms that deliver one logical turn as several messages. WeChat sends an+ * image and the sentence about it as two webhooks a few hundred ms apart, so+ * there is no useful immediate-dispatch mode: `queue` answers the picture+ * before the question has arrived, which starts an incomplete turn. Their+ * schema offers `burst` and `debounce` only.+ */+const TURN_COLLECTING_PLATFORMS = new Set(['wechat']);++/**+ * Decide how the Chat SDK should handle overlapping messages for one channel.+ *+ * A channel created before `burst` existed has `concurrency: 'queue'` baked+ * into its stored settings by `mergeBotSettingsForPersist`, so a schema default+ * alone would never reach it. Resolving it here fixes every existing channel+ * without rewriting anyone's saved settings, and reverts with the code.+ *+ * The stored window is deliberately dropped along with it: `debounceMs` is+ * hidden in the form while a channel sits on `queue` and is never read at+ * runtime, so whatever it holds is a stale default rather than a choice. Under+ * `burst` that window delays every single reply, and the value these rows carry+ * is the old 5s one.+ *+ * An explicit `debounce` is left exactly as the operator set it.+ */+export function resolveBotConcurrency(+ platform: string,+ settings: Record<string, unknown> | null | undefined,+): ResolvedBotConcurrency {+ const stored = typeof settings?.concurrency === 'string' ? settings.concurrency : undefined;+ const storedWindow =+ typeof settings?.debounceMs === 'number' && settings.debounceMs > 0+ ? settings.debounceMs+ : undefined;++ if (TURN_COLLECTING_PLATFORMS.has(platform) && (stored === undefined || stored === 'queue')) {+ return { debounceMs: DEFAULT_BOT_DEBOUNCE_MS, strategy: 'burst' };+ }++ const strategy: BotConcurrencyStrategy =+ stored === 'burst' || stored === 'debounce' ? stored : 'queue';++ return { debounceMs: storedWindow ?? DEFAULT_BOT_DEBOUNCE_MS, strategy };+}++/**+ * Project a provider's stored settings onto what the runtime will actually do,+ * for the settings form to render.+ *+ * A channel created before `burst` existed stores `concurrency: 'queue'`, which+ * its platform no longer offers. Handing that to the form renders a bare+ * `queue` in the picker, and — worse — saving the untouched form would persist+ * the stale window next to a strategy that DOES read it, putting the old 5s+ * wait in front of every reply. Only rows the runtime actually overrides are+ * rewritten; every other channel is passed through untouched.+ */+export function withResolvedConcurrencySettings(+ platform: string,+ settings: Record<string, unknown> | null | undefined,+): Record<string, unknown> | null | undefined {+ const stored = settings?.concurrency;+ if (typeof stored !== 'string') return settings;++ const resolved = resolveBotConcurrency(platform, settings);+ if (resolved.strategy === stored) return settings;++ return { ...settings, concurrency: resolved.strategy, debounceMs: resolved.debounceMs };+}+// --------------- Connection mode resolution ---------------/**diff --git a/apps/server/src/services/bot/platforms/wechat/schema.test.ts b/apps/server/src/services/bot/platforms/wechat/schema.test.tsnew file mode 100644index 00000000000..8a9f4cd97f4--- /dev/null+++ b/apps/server/src/services/bot/platforms/wechat/schema.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest';++import type { FieldSchema } from '../types';+import { schema } from './schema';++const settingsProperties = (): FieldSchema[] =>+ schema.find((field) => field.key === 'settings')?.properties ?? [];++const field = (key: string): FieldSchema | undefined =>+ settingsProperties().find((property) => property.key === key);++describe('WeChat channel schema', () => {+ it('collects a burst by default so an image and its sentence form one turn', () => {+ // WeChat delivers "one picture + one sentence" as two webhooks a few+ // hundred ms apart. Under the plain queue the image starts its own run and+ // the sentence lands while that run still owns the topic, which is the+ // premature execution failure. `burst` waits out the window before the first+ // dispatch instead. Never `debounce`: its documented contract keeps only+ // the last message, dropping the picture.+ expect(field('concurrency')?.default).toBe('burst');+ });++ it('drops the immediate-dispatch mode and keeps labels in step with the options', () => {+ const concurrency = field('concurrency');++ // `queue` answers the picture before its sentence arrives, so WeChat does+ // not offer it. Channels created before `burst` existed still carry it in+ // their stored settings; `resolveBotConcurrency` maps that at runtime.+ expect(concurrency?.enum).toEqual(['burst', 'debounce']);+ // A label/hint list out of step with `enum` silently mislabels the picker.+ expect(concurrency?.enumLabels).toHaveLength(concurrency?.enum?.length ?? 0);+ expect(concurrency?.enumDescriptions).toHaveLength(concurrency?.enum?.length ?? 0);+ expect(concurrency?.enumLabels).toContain('channel.concurrencyBurst');+ expect(concurrency?.enumDescriptions).toContain('channel.concurrencyBurstHint');+ });++ it('shows the window size for burst as well as debounce', () => {+ // Under `burst` the window applies to every message, so it has to stay+ // editable; it used to be revealed by `debounce` alone.+ expect(field('debounceMs')?.visibleWhen).toEqual({+ field: 'concurrency',+ value: ['burst', 'debounce'],+ });+ });++ it('keeps the default window short enough to sit in front of every reply', () => {+ // The window now delays the acknowledgement of a lone message too, so the+ // old 5s value would read as an unresponsive bot.+ const debounceMs = field('debounceMs')?.default as number;++ expect(debounceMs).toBeLessThanOrEqual(2000);+ expect(debounceMs).toBeGreaterThanOrEqual(500);+ });+});diff --git a/apps/server/src/services/bot/platforms/wechat/schema.ts b/apps/server/src/services/bot/platforms/wechat/schema.tsindex 3b51821a472..4705d9667a7 100644--- a/apps/server/src/services/bot/platforms/wechat/schema.ts+++ b/apps/server/src/services/bot/platforms/wechat/schema.ts@@ -1,4 +1,4 @@-import { MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';+import { DEFAULT_BOT_DEBOUNCE_MS, MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';import { displayToolCallsField, watchKeywordsField } from '../const';import type { FieldSchema } from '../types';@@ -20,23 +20,31 @@ export const schema: FieldSchema[] = [},{key: 'concurrency',- default: 'queue',+ // WeChat splits one logical turn across several messages: an image and+ // the sentence about it arrive as two webhooks a few hundred ms apart.+ // `burst` collects that window and hands the agent a single turn, so the+ // picture and its instruction are never answered separately.+ default: 'burst',description: 'channel.concurrencyHint',- enum: ['queue', 'debounce'],- enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],- enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],+ // No `queue` here: WeChat splits a turn across messages, so dispatching+ // the first one immediately answers the picture before its sentence+ // arrives. Channels stored before `burst` existed still carry `queue`;+ // `resolveBotConcurrency` maps that to `burst` at runtime.+ enum: ['burst', 'debounce'],+ enumDescriptions: ['channel.concurrencyBurstHint', 'channel.concurrencyDebounceHint'],+ enumLabels: ['channel.concurrencyBurst', 'channel.concurrencyDebounce'],label: 'channel.concurrency',type: 'string',},{key: 'debounceMs',- default: 5000,+ default: DEFAULT_BOT_DEBOUNCE_MS,description: 'channel.debounceMsHint',label: 'channel.debounceMs',maximum: MAX_BOT_DEBOUNCE_MS,minimum: 100,type: 'number',- visibleWhen: { field: 'concurrency', value: 'debounce' },+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },},{key: 'showUsageStats',diff --git a/apps/server/src/services/bot/replyTemplate.ts b/apps/server/src/services/bot/replyTemplate.tsindex a4d752aeb90..b7a892dfe45 100644--- a/apps/server/src/services/bot/replyTemplate.ts+++ b/apps/server/src/services/bot/replyTemplate.ts@@ -238,6 +238,8 @@ type SystemStrings = {cmdStopNotActive: string;cmdStopRequested: string;cmdStopUnable: string;+ cmdWhoami: (params: WhoamiReplyParams) => string;+ cmdWhoamiUnavailable: string;dmPairingApplicantApproved: string;dmPairingCapacityExceeded: string;dmPairingCode: (code: string) => string;@@ -330,6 +332,18 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {cmdStopNotActive: 'No active execution to stop.',cmdStopRequested: 'Stop requested.',cmdStopUnable: 'Unable to stop the current execution.',+ cmdWhoami: ({ isOperator, userId, userName }) => {+ const lines = [`Your platform user ID: \`${userId}\``];+ if (userName) lines.push(`Display name: ${userName}`);+ lines.push(+ isOperator+ ? 'This ID is already set as the bot operator in Advanced Settings.'+ : 'Paste it into Advanced Settings → "Your Platform User ID" on the bot channel page so AI tools can reach you and pairing approvals work.',+ );+ return lines.join('\n');+ },+ cmdWhoamiUnavailable:+ "Couldn't read your user ID from this message — the platform didn't include a sender ID.",dmPairingApplicantApproved: "You've been approved. Send your message again.",dmPairingCapacityExceeded:'This bot is handling too many pairing requests right now. Please try again in a few minutes.',@@ -446,6 +460,17 @@ const SYSTEM_STRINGS: Partial<Record<BotReplyLocale, SystemStrings>> = {cmdStopNotActive: '当前没有正在执行的任务可以停止。',cmdStopRequested: '已发出停止请求。',cmdStopUnable: '无法停止当前执行。',+ cmdWhoami: ({ isOperator, userId, userName }) => {+ const lines = [`你的平台用户 ID:\`${userId}\``];+ if (userName) lines.push(`显示名称:${userName}`);+ lines.push(+ isOperator+ ? '该 ID 已经是这个机器人「高级设置」中配置的管理员 ID。'+ : '把它填到机器人渠道页「高级设置 → 你的平台用户 ID」,AI 工具就能主动联系你,配对审批也会生效。',+ );+ return lines.join('\n');+ },+ cmdWhoamiUnavailable: '无法从这条消息中读取你的用户 ID —— 平台没有提供发送者 ID。',dmPairingApplicantApproved: '已通过审批,请重新发送你的消息。',dmPairingCapacityExceeded: '该机器人当前待审批请求过多,请稍后再试。',dmPairingCode: (code) =>@@ -762,6 +787,7 @@ export type CommandReplyKey =| 'cmdStopNotActive'| 'cmdStopRequested'| 'cmdStopUnable'+ | 'cmdWhoamiUnavailable'| 'dmPairingApplicantApproved';/**@@ -797,6 +823,23 @@ export function renderGuestTruncated(limit: number, lng?: BotReplyLocale): strinreturn getSystemStrings(lng).guestTextTruncated(limit);}+export interface WhoamiReplyParams {+ /** True when the caller's ID already matches the bot's configured `settings.userId`. */+ isOperator: boolean;+ userId: string;+ userName?: string;+}++/**+ * Render the `/whoami` reply: echoes the caller's platform user ID (Feishu /+ * Lark `open_id`, Telegram numeric ID, …) with a pointer to the settings+ * field it belongs in. This is how operators discover the value for+ * "Your Platform User ID" on platforms that expose no self-service lookup.+ */+export function renderWhoami(params: WhoamiReplyParams, lng?: BotReplyLocale): string {+ return getSystemStrings(lng).cmdWhoami(params);+}+/*** Render the `/mode` status reply (no-arg invocation). `mode` is the explicit* per-conversation override when one was set via `/mode agent|chat`; undefineddiff --git a/apps/server/src/services/messenger/MessengerRouter.test.ts b/apps/server/src/services/messenger/MessengerRouter.test.tsindex 29caa403899..3cf054a39b5 100644--- a/apps/server/src/services/messenger/MessengerRouter.test.ts+++ b/apps/server/src/services/messenger/MessengerRouter.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { Chat } from 'chat';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MessengerRouter } from './MessengerRouter';@@ -69,6 +70,7 @@ const mockSetIfNotExists = vi.fn();const mockGetList = vi.fn();const mockAppendToList = vi.fn();const mockChatBot = {+ dispatchToHandlers: vi.fn(),getState: vi.fn(() => ({appendToList: (...args: any[]) => mockAppendToList(...args),getList: (...args: any[]) => mockGetList(...args),@@ -301,6 +303,7 @@ const wechatCreds = {};beforeEach(() => {+ mockChatBot.dispatchToHandlers = vi.fn();mockVerifySignature.mockReturnValue(true);mockChatBot.webhooks = {slack: mockWebhookHandler,@@ -583,6 +586,43 @@ const fakeWechatDmThread = (): any => ({subscribe: vi.fn(),});+describe('MessengerRouter collected commands', () => {+ it.each([+ ['/new', 'question'],+ ['question', '/new'],+ ])('preserves command and content order for %s then %s', async (first, second) => {+ const events: string[] = [];+ const thread = {+ ...fakeWechatDmThread(),+ state: Promise.resolve({ topicId: 'old-topic' }),+ setState: vi.fn(async () => {+ events.push('reset');+ }),+ };+ mockFindLink.mockResolvedValue({+ activeAgentId: 'agt_main',+ id: 'link',+ platformUserId: 'U_ALICE',+ userId: 'user_alice',+ });+ mockHandleSubscribed.mockImplementation(async (_thread, message) => {+ events.push(message.text);+ });+ mockChatBot.dispatchToHandlers = vi.fn(async (_adapter, _threadId, message, context) => {+ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0];+ await handler(thread, message, context);+ });+ await loadWechatBot();+ await mockChatBot.dispatchToHandlers({}, thread.id, fakeMessage({ text: second }), {+ skipped: [fakeMessage({ text: first })],+ totalSinceLastHandler: 2,+ });+ expect(events).toEqual([first, second].map((text) => (text === '/new' ? 'reset' : text)));+ expect(thread.setState).toHaveBeenCalledTimes(1);+ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);+ });+});+describe('MessengerRouter channel @mention', () => {it('dispatches a linked user mention to the active agent (in-thread reply)', async () => {await loadSlackBot();@@ -2153,3 +2193,144 @@ describe('MessengerRouter Telegram Guest command privacy', () => {expect(mockTelegramBinder.replyToMessage).not.toHaveBeenCalled();});});++describe('MessengerRouter overlapping messages', () => {+ const wechatLink = {+ activeAgentId: 'agt_main',+ id: 'link_wechat',+ platformUserId: 'wechat-user',+ tenantId: 'wechat-user',+ userId: 'user_alice',+ workspaceId: null,+ };++ const chatConfig = () => (Chat as unknown as { mock: { calls: any[][] } }).mock.calls.at(-1)![0];++ it('collects a burst window on WeChat instead of dispatching each message alone', async () => {+ // WeChat sends an image and the sentence about it as two webhooks a few+ // hundred ms apart. Without the window the picture starts its own run and+ // the sentence arrives while that run still owns the topic.+ await loadWechatBot();++ expect(chatConfig().concurrency).toEqual({+ debounceMs: expect.any(Number),+ strategy: 'burst',+ });+ });++ it('keeps the plain queue on platforms that send media together with its caption', async () => {+ await loadSlackBot();++ expect(chatConfig().concurrency).toBe('queue');+ });++ it('folds the collected messages into the single turn handed to the agent', async () => {+ await loadWechatBot();+ mockFindLink.mockResolvedValue(wechatLink);++ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0] as (+ thread: any,+ msg: any,+ context?: any,+ ) => Promise<void>;+ await handler(fakeWechatDmThread(), fakeMessage({ id: 'm2', text: '参考这个风格说话' }), {+ skipped: [fakeMessage({ attachments: [{ type: 'image' }], id: 'm1', text: '' })],+ totalSinceLastHandler: 2,+ });++ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);+ const dispatched = mockHandleSubscribed.mock.calls[0][1];+ expect(dispatched.text).toBe('参考这个风格说话');+ // The image rides along instead of being answered as its own turn, and each+ // source stays reachable so its media can still be downloaded.+ expect(dispatched.attachments).toEqual([{ type: 'image' }]);+ expect(dispatched.sourceMessages.map((m: any) => m.id)).toEqual(['m1', 'm2']);+ });++ it.each(['onSubscribedMessage', 'onNewMention'] as const)(+ '%s never dispatches another sender content under the linked owner',+ async (entry) => {+ await loadSlackBot();+ mockFindLink.mockResolvedValue({+ activeAgentId: 'agt_main',+ id: 'link_1',+ platformUserId: 'U_ALICE',+ tenantId: 'T_ACME',+ userId: 'user_alice',+ });+ const handler = mockChatBot[entry].mock.calls.at(-1)![0];+ await handler(+ fakeChannelThread(),+ fakeMessage({ id: 'owner', isMention: true, text: 'owner request' }),+ {+ skipped: [+ fakeMessage({+ author: { isBot: false, userId: 'U_OTHER', userName: 'other' },+ id: 'other',+ isMention: true,+ text: 'untrusted instruction',+ attachments: [{ type: 'image' }],+ }),+ ],+ totalSinceLastHandler: 2,+ },+ );+ const dispatch = entry === 'onSubscribedMessage' ? mockHandleSubscribed : mockHandleMention;+ expect(dispatch).toHaveBeenCalledTimes(1);+ expect(dispatch.mock.calls[0][1].text).toBe('owner request');+ expect(dispatch.mock.calls[0][1].attachments ?? []).toEqual([]);+ expect(mockAppendToList).toHaveBeenCalledWith(+ expect.any(String),+ 'U_OTHER',+ expect.any(Object),+ );+ },+ );++ it('does not use another sender mention to wake an unmentioned owner turn', async () => {+ await loadSlackBot();+ mockGetList.mockResolvedValue(['U_ALICE', 'U_OTHER']);+ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0];+ await handler(+ fakeChannelThread(),+ fakeMessage({ id: 'owner', isMention: false, text: 'owner chatter' }),+ {+ skipped: [+ fakeMessage({+ author: { isBot: false, userId: 'U_OTHER', userName: 'other' },+ id: 'other',+ isMention: true,+ }),+ ],+ totalSinceLastHandler: 2,+ },+ );+ expect(mockHandleSubscribed).not.toHaveBeenCalled();+ expect(mockFindLink).not.toHaveBeenCalled();+ });++ it('treats a mention anywhere in the collected turn as addressed to the bot', async () => {+ // The last message of a burst usually carries the question without the `@`.+ await loadSlackBot();+ mockFindLink.mockResolvedValue({+ activeAgentId: 'agt_main',+ id: 'link_1',+ platformUserId: 'U_ALICE',+ tenantId: 'T_ACME',+ userId: 'user_alice',+ });+ mockGetList.mockResolvedValue(['U_ALICE', 'U_BOB']);++ const handler = mockChatBot.onSubscribedMessage.mock.calls.at(-1)![0] as (+ thread: any,+ msg: any,+ context?: any,+ ) => Promise<void>;+ await handler(fakeChannelThread(), fakeMessage({ id: 'm2', isMention: false }), {+ skipped: [fakeMessage({ id: 'm1', isMention: true, text: '<@U_BOT> 看看这个' })],+ totalSinceLastHandler: 2,+ });++ expect(mockHandleSubscribed).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/messenger/MessengerRouter.ts b/apps/server/src/services/messenger/MessengerRouter.tsindex a813bf1bb60..ffa5ef28c71 100644--- a/apps/server/src/services/messenger/MessengerRouter.ts+++ b/apps/server/src/services/messenger/MessengerRouter.ts@@ -19,9 +19,19 @@ import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis'import { AiAgentService } from '@/server/services/aiAgent';import { AgentBridgeService } from '@/server/services/bot/AgentBridgeService';import { buildBotContext } from '@/server/services/bot/buildBotContext';+import { replayDeferredBotMessages } from '@/server/services/bot/deferredMessages';import { submitBotFeedback } from '@/server/services/bot/feedbackSubmit';+import {+ buildReplayMessages,+ getSameSenderMessages,+ mergeBotMessages,+} from '@/server/services/bot/mergeMessages';+import { patchSenderBatches } from '@/server/services/bot/patchSenderBatches';import type { PlatformClient } from '@/server/services/bot/platforms';import { getBotReplyLocale } from '@/server/services/bot/platforms/const';+// Leaf module, not the `./platforms` barrel: the barrel instantiates every+// platform definition (and its ClientFactory) at import time.+import { resolveBotConcurrency } from '@/server/services/bot/platforms/utils';import {renderCommandReply,renderFeedbackSubmitted,@@ -53,6 +63,8 @@ const PERSONAL_SCOPE_ID = 'personal';const WECHAT_UNSUPPORTED_COMMANDS = new Set(['start']);interface RegisteredMessengerBot {+ /** Chat SDK adapters keyed by platform id, as passed to the `Chat` config. */+ adapters: Record<string, any>;binder: MessengerPlatformBinder;chatBot: Chat<any>;client: PlatformClient;@@ -418,17 +430,53 @@ export class MessengerRouter {);}- const registered: RegisteredMessengerBot = { binder, chatBot, client, creds };+ const registered: RegisteredMessengerBot = { adapters, binder, chatBot, client, creds };this.bots.set(creds.installationKey, registered);log('loadBot: registered messenger %s bot', creds.installationKey);return registered;}+ /**+ * Re-dispatch the messages `AgentBridgeService` parked while the thread's+ * topic was still running (see `BotMessageRouter.replayDeferredMessages`).+ * `applicationId` is the synthetic per-install id the bridge used when+ * deferring (`messenger-<platform>[-<tenant>]`).+ */+ async replayDeferredMessages(+ installationKey: string,+ applicationId: string,+ platformThreadId: string,+ ): Promise<void> {+ await replayDeferredBotMessages(applicationId, platformThreadId, async (entries) => {+ const platform = installationKey.split(':')[0] as MessengerPlatform;+ const store = getInstallationStore(platform);+ const creds = await store?.resolveByKey(installationKey);+ const bot = creds ? await this.getOrCreateBot(creds) : null;+ const adapter = bot?.adapters[platform];+ if (!bot || !adapter) throw new Error(`Messenger adapter unavailable for ${platform}`);+ const results = await Promise.allSettled(+ buildReplayMessages(entries).map((message) =>+ bot.chatBot.processMessage(adapter, platformThreadId, message),+ ),+ );+ const failure = results.find((result) => result.status === 'rejected');+ if (failure?.status === 'rejected') throw failure.reason;+ });+ }+private createChatBot(adapters: Record<string, any>, creds: InstallationCredentials): Chat<any> {const config: any = {adapters,- concurrency: 'queue',+ // Messenger installs carry no per-channel settings, so this is purely the+ // platform's own answer: WeChat collects a burst window because it splits+ // one turn across several messages, everything else keeps the plain queue.+ // Shared with `BotMessageRouter` so both paths agree on which platforms+ // need collecting.+ concurrency: (() => {+ const { debounceMs, strategy } = resolveBotConcurrency(creds.platform, undefined);+ return strategy === 'queue' ? 'queue' : { debounceMs, strategy };+ })(),// Per-install Chat SDK identity so the queue / state / debounce keys// never overlap across workspaces.userName: `messenger-bot-${creds.installationKey}`,@@ -444,7 +492,13 @@ export class MessengerRouter {});}- return new Chat(config);+ const bot = new Chat(config);+ const commands = this.getCommandsForPlatform(creds.platform);+ patchSenderBatches(bot, (message) => {+ const parsed = parseCommand(message.text);+ return !!parsed && commands.some((command) => command.name === parsed.name);+ });+ return bot;}private registerHandlers(@@ -697,17 +751,30 @@ export class MessengerRouter {return { count: participants.length + 1, isNewParticipant: true };};- bot.onSubscribedMessage(async (thread, message, _context?: MessageContext) => {+ bot.onSubscribedMessage(async (thread, message, context?: MessageContext) => {log('onSubscribedMessage: install=%s, msgId=%s', creds.installationKey, (message as any).id);+ // Fold in whatever the SDK collected while the previous handler ran (or+ // during a `burst` window) so the agent sees the whole user turn — text+ // and media alike — instead of only its last message.+ const merged = mergeBotMessages(message, context?.skipped);+// DM short-circuit — always 1:1 with the bot, no participant gating.if (thread.isDM) {- await handle(thread, message, 'handleSubscribedMessage');+ await handle(thread, merged, 'handleSubscribedMessage');return;}- const isMention = message.isMention === true;- const { count } = await trackThreadParticipant(thread, message);+ // A mention anywhere in the collected turn addresses the bot; the last+ // message of a burst often carries the question without the `@`.+ const isMention =+ message.isMention === true ||+ getSameSenderMessages(message, context?.skipped).some((m) => m.isMention === true) === true;+ let count = 0;+ for (const source of [...(context?.skipped ?? []), message]) {+ const participant = await trackThreadParticipant(thread, source);+ count = Math.max(count, participant.count);+ }// Single-human thread → respond without `@`. Multi-human thread →// only @mention triggers a reply, so the bot doesn't insert itself@@ -739,7 +806,7 @@ export class MessengerRouter {// subscribed channel thread). `handleSubscribedMessage` reads the// cached topicId from chat-sdk thread state and continues that topic;// it falls back to `handleMention` internally if no topicId is cached.- await handle(thread, message, 'handleSubscribedMessage');+ await handle(thread, merged, 'handleSubscribedMessage');});// First-touch entry point for any non-subscribed conversation:@@ -750,19 +817,22 @@ export class MessengerRouter {// thread state, and (for subscribable platforms / threads — see// `client.shouldSubscribe`) subscribes the thread so subsequent// messages route through `onSubscribedMessage` and continue the topic.- bot.onNewMention(async (thread, message, _context?: MessageContext) => {+ bot.onNewMention(async (thread, message, context?: MessageContext) => {log('onNewMention: install=%s, msgId=%s, threadId=%s',creds.installationKey,(message as any).id,thread.id,);+ const merged = mergeBotMessages(message, context?.skipped);// Record the original @mentioner so the participant count starts at 1// (not 0) when their first follow-up lands in `onSubscribedMessage`.// Without this the follow-up looks like a "new participant" instead// of the same person continuing.- await trackThreadParticipant(thread, message);- await handle(thread, message, 'handleMention');+ for (const source of [...(context?.skipped ?? []), message]) {+ await trackThreadParticipant(thread, source);+ }+ await handle(thread, merged, 'handleMention');});// Native slash commands. chat-adapter routes a leading `/command` to thediff --git a/locales/ar/agent.json b/locales/ar/agent.jsonindex cefb1c4c635..c3243b962a4 100644--- a/locales/ar/agent.json+++ b/locales/ar/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "نعمل على جلب هذا التكامل إلى LobeHub. تابعنا للحصول على التحديثات.","channel.comingSoonTitle": "تكامل {{name}} قادم قريبًا","channel.concurrency": "وضع التزامن",+ "channel.concurrencyBurst": "اندفاع",+ "channel.concurrencyBurstHint": "انتظر لفترة وجيزة، ثم تعامل مع مجموعة من الرسائل كدورة واحدة (لا يتم إسقاط أي شيء)","channel.concurrencyDebounce": "إزالة الارتداد","channel.concurrencyDebounceHint": "معالجة آخر رسالة فقط في الدفعة (يتم تجاهل الرسائل السابقة)","channel.concurrencyHint": "يقوم الوضع التتابعي بمعالجة الرسائل واحدة تلو الأخرى؛ بينما ينتظر وضع إزالة الارتداد انتهاء دفعة الرسائل قبل المعالجة",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "يرجى نسخ هذا العنوان ولصقه في الحقل <bold>{{fieldName}}</bold> في بوابة مطوري {{name}}.","channel.exportConfig": "تصدير التكوين","channel.feishu.description": "قم بتوصيل هذا المساعد بـ Feishu للدردشة الخاصة والجماعية.",+ "channel.feishu.fetchOwnerId": "جلب من معلومات التطبيق",+ "channel.feishu.fetchOwnerIdAutoSuccess": "تم ملء معرف Open الخاص بمالك التطبيق — تحقق من أنه أنت، ثم احفظ",+ "channel.feishu.fetchOwnerIdFailed": "فشل في قراءة مالك التطبيق",+ "channel.feishu.fetchOwnerIdMissingCredentials": "أدخل معرف التطبيق والسر الخاص بالتطبيق أولاً — يتم البحث كجزء من تطبيقك.",+ "channel.feishu.fetchOwnerIdSuccess": "تم ملء معرف Open — تحقق من أنه أنت، ثم احفظ","channel.feishu.webhookMigrationDesc": "يوفّر وضع WebSocket تسليمًا فوريًا للأحداث دون الحاجة إلى عنوان URL عام لرد النداء. للانتقال، قم بتغيير وضع الاتصال إلى WebSocket في الإعدادات المتقدمة. لا يلزم أي إعداد إضافي على منصة Feishu/Lark المفتوحة.","channel.feishu.webhookMigrationTitle": "النظر في الترقية إلى وضع WebSocket","channel.groupAllowFrom": "القنوات المسموح بها",diff --git a/locales/bg-BG/agent.json b/locales/bg-BG/agent.jsonindex 54014bced3a..3684595f137 100644--- a/locales/bg-BG/agent.json+++ b/locales/bg-BG/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Работим върху интеграцията на това в LobeHub. Следете за актуализации.","channel.comingSoonTitle": "Интеграцията на {{name}} идва скоро","channel.concurrency": "Режим на едновременност",+ "channel.concurrencyBurst": "Изблик",+ "channel.concurrencyBurstHint": "Изчакайте за кратко, след това обработете серия от съобщения като един ход (нищо не се губи)","channel.concurrencyDebounce": "Забавяне","channel.concurrencyDebounceHint": "Обработва само последното съобщение от серия (по-ранните се игнорират)","channel.concurrencyHint": "Опашка обработва съобщенията едно по едно; Забавяне изчаква завършването на серия от съобщения преди обработка",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Моля, копирайте този URL и го поставете в полето <bold>{{fieldName}}</bold> в {{name}} Developer Portal.","channel.exportConfig": "Експортиране на конфигурация","channel.feishu.description": "Свържете този асистент с Feishu за лични и групови чатове.",+ "channel.feishu.fetchOwnerId": "Извличане от информацията за приложението",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Попълнен е Open ID на собственика на приложението — проверете дали сте вие, след това запазете",+ "channel.feishu.fetchOwnerIdFailed": "Неуспешно извличане на собственика на приложението",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Въведете Application ID и App Secret първо — търсенето се изпълнява като вашето приложение.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID е попълнен — проверете дали сте вие, след това запазете","channel.feishu.webhookMigrationDesc": "Режимът WebSocket осигурява доставяне на събития в реално време без необходимост от публичен callback URL. За миграция превключете режима на свързване към WebSocket в Разширени настройки. Не е необходима допълнителна конфигурация в Feishu/Lark Open Platform.","channel.feishu.webhookMigrationTitle": "Обмислете миграция към режим WebSocket","channel.groupAllowFrom": "Разрешени канали",diff --git a/locales/de-DE/agent.json b/locales/de-DE/agent.jsonindex ad583d975ca..5bad6e2f429 100644--- a/locales/de-DE/agent.json+++ b/locales/de-DE/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Wir arbeiten daran, diese Integration in LobeHub zu bringen. Bleiben Sie dran für Updates.","channel.comingSoonTitle": "{{name}}-Integration kommt bald","channel.concurrency": "Konkurrenzmodus",+ "channel.concurrencyBurst": "Burst",+ "channel.concurrencyBurstHint": "Kurz warten, dann eine Reihe von Nachrichten als eine Aktion bearbeiten (nichts geht verloren)","channel.concurrencyDebounce": "Entprellen","channel.concurrencyDebounceHint": "Nur die letzte Nachricht in einer Serie verarbeiten (frühere werden verworfen)","channel.concurrencyHint": "Warteschlange verarbeitet Nachrichten nacheinander; Entprellen wartet, bis ein Nachrichtenburst abgeschlossen ist, bevor die Verarbeitung beginnt.",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Bitte kopieren Sie diese URL und fügen Sie sie in das Feld <bold>{{fieldName}}</bold> im {{name}} Entwicklerportal ein.","channel.exportConfig": "Konfiguration exportieren","channel.feishu.description": "Verbinden Sie diesen Assistenten mit Feishu für private und Gruppenchats.",+ "channel.feishu.fetchOwnerId": "Aus App-Informationen abrufen",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Die Open ID des App-Besitzers wurde ausgefüllt — überprüfen Sie, ob es sich um Sie handelt, und speichern Sie dann",+ "channel.feishu.fetchOwnerIdFailed": "Das Lesen des App-Besitzers ist fehlgeschlagen",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Geben Sie zuerst die Anwendungs-ID und das App-Geheimnis ein — die Abfrage wird als Ihre App ausgeführt.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID ausgefüllt — überprüfen Sie, ob es sich um Sie handelt, und speichern Sie dann","channel.feishu.webhookMigrationDesc": "Der WebSocket-Modus bietet die Zustellung von Ereignissen in Echtzeit, ohne dass eine öffentliche Callback-URL erforderlich ist. Um zu migrieren, wechseln Sie den Verbindungsmodus in den erweiterten Einstellungen zu WebSocket. Es ist keine zusätzliche Konfiguration auf der Feishu/Lark Open Platform erforderlich.","channel.feishu.webhookMigrationTitle": "Erwägen Sie die Migration zum WebSocket-Modus","channel.groupAllowFrom": "Zugelassene Kanäle",diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 9879b26ba68..f373d06c95e 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "We are working on bringing this integration to LobeHub. Stay tuned for updates.","channel.comingSoonTitle": "{{name}} integration is coming soon","channel.concurrency": "Concurrency Mode",+ "channel.concurrencyBurst": "Burst",+ "channel.concurrencyBurstHint": "Wait briefly, then handle a run of messages as one turn (nothing is dropped)","channel.concurrencyDebounce": "Debounce","channel.concurrencyDebounceHint": "Only process the last message in a burst (earlier ones are dropped)","channel.concurrencyHint": "How concurrent messages are batched",@@ -55,7 +57,7 @@"channel.copied": "Copied to clipboard","channel.copy": "Copy","channel.credentials": "Credentials",- "channel.debounceMs": "Debounce Window (ms)",+ "channel.debounceMs": "Wait Window (ms)","channel.debounceMsHint": "How long to wait for additional messages before dispatching to the agent (ms)","channel.deleteAllChannels": "Remove All Channels","channel.deleteAllConfirm": "Are you sure you want to remove all channels?",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Please copy this URL and paste it into the <bold>{{fieldName}}</bold> field in the {{name}} Developer Portal.","channel.exportConfig": "Export Configuration","channel.feishu.description": "Connect this agent to Feishu for private and group chats.",+ "channel.feishu.fetchOwnerId": "Fetch from app info",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Filled in the app owner’s Open ID — check it is you, then save",+ "channel.feishu.fetchOwnerIdFailed": "Failed to read the app owner",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Enter the Application ID and App Secret first — the lookup runs as your app.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID filled in — check it is you, then save","channel.feishu.webhookMigrationDesc": "WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket in Advanced Settings. No additional configuration is needed on the Feishu/Lark Open Platform.","channel.feishu.webhookMigrationTitle": "Consider migrating to WebSocket mode","channel.groupAllowFrom": "Allowed Channels",@@ -263,13 +270,13 @@"channel.userId": "Your Platform User ID","channel.userIdHint": "Lets AI tools reach you proactively (e.g. reminders); auto-trusted by the global allowlist","channel.userIdHint.discord": "Enable Developer Mode (Settings → Advanced), then right-click your avatar → Copy User ID.",- "channel.userIdHint.feishu": "Open your app on the Feishu / Lark Open Platform → Permissions, then look up your Open ID.",+ "channel.userIdHint.feishu": "Feishu Open IDs are per-app, so no console page shows you your own. Once the credentials are in, the app owner's is filled in for you; if nothing appears, use the button below or send /whoami to the bot in a direct message.","channel.userIdHint.imessage": "Use your iMessage handle as seen in BlueBubbles, usually an email address or E.164 phone number.","channel.userIdHint.line": "Open the LINE Developers Console → your channel → Basic settings tab, and copy \"Your user ID\" (starts with U, 33 chars).","channel.userIdHint.qq": "Your QQ number, shown on your QQ profile page.","channel.userIdHint.slack": "Open your Slack profile → ⋮ More → Copy member ID (starts with U).","channel.userIdHint.telegram": "Send any message to @userinfobot on Telegram — it replies with your numeric User ID.",- "channel.userIdMissingDesc": "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Fill it in under Advanced Settings.",+ "channel.userIdMissingDesc": "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Send /whoami to the bot to get your ID, then fill it in under Advanced Settings.","channel.userIdMissingTitle": "Add your platform User ID","channel.validationError": "Please fill in Application ID and Token","channel.verificationToken": "Verification Token",diff --git a/locales/es-ES/agent.json b/locales/es-ES/agent.jsonindex ef9c18b4662..f698bb1f299 100644--- a/locales/es-ES/agent.json+++ b/locales/es-ES/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Estamos trabajando para traer esta integración a LobeHub. Mantente atento para más actualizaciones.","channel.comingSoonTitle": "La integración de {{name}} estará disponible próximamente","channel.concurrency": "Modo de Concurrencia",+ "channel.concurrencyBurst": "Explosión",+ "channel.concurrencyBurstHint": "Espera brevemente, luego maneja una serie de mensajes como un solo turno (nada se pierde)","channel.concurrencyDebounce": "Antirrebote","channel.concurrencyDebounceHint": "Procesar solo el último mensaje de una ráfaga (los anteriores se descartan)","channel.concurrencyHint": "La cola procesa los mensajes uno a la vez; el antirrebote espera a que termine un grupo de mensajes antes de procesarlos.",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Por favor, copia esta URL y pégala en el campo <bold>{{fieldName}}</bold> en el Portal de Desarrolladores de {{name}}.","channel.exportConfig": "Exportar configuración","channel.feishu.description": "Conecta este asistente a Feishu para chats privados y grupales.",+ "channel.feishu.fetchOwnerId": "Obtener de la información de la aplicación",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Se completó con el Open ID del propietario de la aplicación — verifica que seas tú, luego guarda",+ "channel.feishu.fetchOwnerIdFailed": "No se pudo leer el propietario de la aplicación",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Primero ingresa el ID de la aplicación y el App Secret — la búsqueda se ejecuta como tu aplicación.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID completado — verifica que seas tú, luego guarda","channel.feishu.webhookMigrationDesc": "El modo WebSocket ofrece entrega de eventos en tiempo real sin necesidad de una URL de callback pública. Para migrar, cambie el Modo de Conexión a WebSocket en Configuración Avanzada. No se necesita ninguna configuración adicional en la Plataforma Abierta de Feishu/Lark.","channel.feishu.webhookMigrationTitle": "Considere migrar al modo WebSocket","channel.groupAllowFrom": "Canales permitidos",diff --git a/locales/fa-IR/agent.json b/locales/fa-IR/agent.jsonindex 56f99e881b0..2e3261e6c5c 100644--- a/locales/fa-IR/agent.json+++ b/locales/fa-IR/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "ما در حال کار بر روی اضافه کردن این یکپارچهسازی به LobeHub هستیم. منتظر بهروزرسانیها باشید.","channel.comingSoonTitle": "یکپارچهسازی {{name}} به زودی در دسترس خواهد بود","channel.concurrency": "حالت همزمانی",+ "channel.concurrencyBurst": "انفجار",+ "channel.concurrencyBurstHint": "کمی صبر کنید، سپس یک سری پیامها را به عنوان یک نوبت پردازش کنید (هیچ چیزی حذف نمیشود)","channel.concurrencyDebounce": "دیبانس","channel.concurrencyDebounceHint": "فقط آخرین پیام در یک سری پردازش میشود (پیامهای قبلی نادیده گرفته میشوند)","channel.concurrencyHint": "صف پیامها را یکی یکی پردازش میکند؛ دیبانس منتظر میماند تا یک سری پیامها تمام شوند و سپس پردازش را آغاز میکند.",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "لطفاً این آدرس را کپی کرده و در قسمت <bold>{{fieldName}}</bold> در پورتال توسعهدهنده {{name}} وارد کنید.","channel.exportConfig": "صادرات تنظیمات","channel.feishu.description": "این دستیار را به Feishu برای چتهای خصوصی و گروهی متصل کنید.",+ "channel.feishu.fetchOwnerId": "از اطلاعات برنامه دریافت کنید",+ "channel.feishu.fetchOwnerIdAutoSuccess": "شناسه باز صاحب برنامه پر شد — بررسی کنید که شما هستید، سپس ذخیره کنید",+ "channel.feishu.fetchOwnerIdFailed": "خواندن صاحب برنامه ناموفق بود",+ "channel.feishu.fetchOwnerIdMissingCredentials": "ابتدا شناسه برنامه و رمز برنامه را وارد کنید — جستجو به عنوان برنامه شما اجرا میشود.",+ "channel.feishu.fetchOwnerIdSuccess": "شناسه باز پر شد — بررسی کنید که شما هستید، سپس ذخیره کنید","channel.feishu.webhookMigrationDesc": "حالت وبسوکت بدون نیاز به یک نشانی callback عمومی، تحویل آنی رویدادها را فراهم میکند. برای مهاجرت، در تنظیمات پیشرفته حالت اتصال را به وبسوکت تغییر دهید. هیچ تنظیم اضافهای در پلتفرم Feishu/Lark لازم نیست.","channel.feishu.webhookMigrationTitle": "مهاجرت به حالت وبسوکت را در نظر بگیرید","channel.groupAllowFrom": "کانالهای مجاز",diff --git a/locales/fr-FR/agent.json b/locales/fr-FR/agent.jsonindex c2f7a07e77e..d3e7ad3bd98 100644--- a/locales/fr-FR/agent.json+++ b/locales/fr-FR/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Nous travaillons à intégrer cette fonctionnalité à LobeHub. Restez à l'écoute pour les mises à jour.","channel.comingSoonTitle": "L'intégration de {{name}} arrive bientôt","channel.concurrency": "Mode de Concurrence",+ "channel.concurrencyBurst": "Rafale",+ "channel.concurrencyBurstHint": "Attendez brièvement, puis traitez une série de messages comme un seul tour (rien n'est perdu)","channel.concurrencyDebounce": "Anti-rebond","channel.concurrencyDebounceHint": "Ne traiter que le dernier message d’une rafale (les précédents sont ignorés)","channel.concurrencyHint": "La file d'attente traite les messages un par un ; l'anti-rebond attend qu'une rafale de messages soit terminée avant de les traiter.",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Veuillez copier cette URL et la coller dans le champ <bold>{{fieldName}}</bold> du portail développeur {{name}}.","channel.exportConfig": "Exporter la configuration","channel.feishu.description": "Connectez cet assistant à Feishu pour les discussions privées et de groupe.",+ "channel.feishu.fetchOwnerId": "Récupérer depuis les informations de l'application",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Identifiant Open ID du propriétaire de l'application rempli — vérifiez que c'est vous, puis sauvegardez",+ "channel.feishu.fetchOwnerIdFailed": "Échec de la lecture du propriétaire de l'application",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Entrez d'abord l'ID de l'application et le secret de l'application — la recherche s'exécute en tant que votre application.",+ "channel.feishu.fetchOwnerIdSuccess": "Identifiant Open ID rempli — vérifiez que c'est vous, puis sauvegardez","channel.feishu.webhookMigrationDesc": "Le mode WebSocket offre une livraison d’événements en temps réel sans nécessiter d’URL de rappel publique. Pour migrer, changez le mode de connexion vers WebSocket dans les paramètres avancés. Aucune configuration supplémentaire n’est requise sur la plateforme Feishu/Lark Open Platform.","channel.feishu.webhookMigrationTitle": "Envisagez de migrer vers le mode WebSocket","channel.groupAllowFrom": "Canaux autorisés",diff --git a/locales/it-IT/agent.json b/locales/it-IT/agent.jsonindex b3582bb1460..b31ffe91ca8 100644--- a/locales/it-IT/agent.json+++ b/locales/it-IT/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Stiamo lavorando per portare questa integrazione su LobeHub. Resta sintonizzato per gli aggiornamenti.","channel.comingSoonTitle": "L'integrazione di {{name}} arriverà presto","channel.concurrency": "Modalità Concorrenza",+ "channel.concurrencyBurst": "Esplosione",+ "channel.concurrencyBurstHint": "Attendi brevemente, quindi gestisci una serie di messaggi come un unico turno (nulla viene perso)","channel.concurrencyDebounce": "Debounce","channel.concurrencyDebounceHint": "Elabora solo l’ultimo messaggio in una raffica (i precedenti vengono ignorati)","channel.concurrencyHint": "La modalità Coda elabora i messaggi uno alla volta; Debounce attende che un gruppo di messaggi sia completato prima di procedere con l'elaborazione.",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Copia questo URL e incollalo nel campo <bold>{{fieldName}}</bold> nel Portale Sviluppatori di {{name}}.","channel.exportConfig": "Esporta configurazione","channel.feishu.description": "Connetti questo assistente a Feishu per chat private e di gruppo.",+ "channel.feishu.fetchOwnerId": "Recupera dalle informazioni dell'app",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Compilato con l'Open ID del proprietario dell'app — verifica che sia tuo, poi salva",+ "channel.feishu.fetchOwnerIdFailed": "Impossibile leggere il proprietario dell'app",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Inserisci prima l'ID dell'applicazione e il segreto dell'app — la ricerca viene eseguita come la tua app.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID compilato — verifica che sia tuo, poi salva","channel.feishu.webhookMigrationDesc": "La modalità WebSocket offre la consegna in tempo reale degli eventi senza la necessità di un URL pubblico di callback. Per eseguire la migrazione, passa la Modalità di connessione a WebSocket nelle Impostazioni avanzate. Non è necessaria alcuna configurazione aggiuntiva sulla Piattaforma Open di Feishu/Lark.","channel.feishu.webhookMigrationTitle": "Valuta la migrazione alla modalità WebSocket","channel.groupAllowFrom": "Canali autorizzati",diff --git a/locales/ja-JP/agent.json b/locales/ja-JP/agent.jsonindex a706b5fe6fc..6db7f691923 100644--- a/locales/ja-JP/agent.json+++ b/locales/ja-JP/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "この統合をLobeHubに導入するために作業を進めています。更新情報をお待ちください。","channel.comingSoonTitle": "{{name}}の統合が近日公開予定です","channel.concurrency": "同時実行モード",+ "channel.concurrencyBurst": "バースト",+ "channel.concurrencyBurstHint": "少し待ってから、メッセージの一連の処理を1回のターンとして処理します(何も失われません)","channel.concurrencyDebounce": "デバウンス","channel.concurrencyDebounceHint": "連続したメッセージの最後のものだけを処理します(それ以前は破棄)","channel.concurrencyHint": "キューはメッセージを1つずつ処理します。デバウンスはメッセージのバーストが終了するのを待ってから処理を開始します。",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "このURLをコピーして、{{name}}開発者ポータルの<bold>{{fieldName}}</bold>フィールドに貼り付けてください。","channel.exportConfig": "設定をエクスポート","channel.feishu.description": "このアシスタントをFeishuに接続して、プライベートチャットやグループチャットを利用します。",+ "channel.feishu.fetchOwnerId": "アプリ情報から取得",+ "channel.feishu.fetchOwnerIdAutoSuccess": "アプリ所有者のOpen IDを入力しました — 自分であることを確認して保存してください",+ "channel.feishu.fetchOwnerIdFailed": "アプリ所有者の読み取りに失敗しました",+ "channel.feishu.fetchOwnerIdMissingCredentials": "最初にアプリケーションIDとApp Secretを入力してください — ルックアップはアプリとして実行されます。",+ "channel.feishu.fetchOwnerIdSuccess": "Open IDを入力しました — 自分であることを確認して保存してください","channel.feishu.webhookMigrationDesc": "WebSocket モードでは、公開コールバック URL を必要とせず、リアルタイムでイベントを受信できます。移行するには、詳細設定で接続モードを WebSocket に切り替えてください。Feishu/Lark オープンプラットフォーム側での追加設定は不要です。","channel.feishu.webhookMigrationTitle": "WebSocket モードへの移行をご検討ください","channel.groupAllowFrom": "許可されたチャンネル",diff --git a/locales/ko-KR/agent.json b/locales/ko-KR/agent.jsonindex 60f527be57e..acded15be83 100644--- a/locales/ko-KR/agent.json+++ b/locales/ko-KR/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "이 통합을 LobeHub에 제공하기 위해 작업 중입니다. 업데이트를 기대해주세요.","channel.comingSoonTitle": "{{name}} 통합이 곧 출시됩니다","channel.concurrency": "동시성 모드",+ "channel.concurrencyBurst": "폭발",+ "channel.concurrencyBurstHint": "잠시 기다린 후 메시지를 한 번에 처리합니다 (아무것도 누락되지 않음)","channel.concurrencyDebounce": "디바운스","channel.concurrencyDebounceHint": "빠르게 연속된 메시지 중 마지막 메시지만 처리합니다(이전 메시지는 무시됨).","channel.concurrencyHint": "큐는 메시지를 한 번에 하나씩 처리하며, 디바운스는 메시지 폭주가 끝난 후 처리합니다.",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "이 URL을 복사하여 {{name}} 개발자 포털의 <bold>{{fieldName}}</bold> 필드에 붙여넣으세요.","channel.exportConfig": "구성 내보내기","channel.feishu.description": "이 어시스턴트를 Feishu에 연결하여 개인 및 그룹 채팅을 사용할 수 있습니다.",+ "channel.feishu.fetchOwnerId": "앱 정보에서 가져오기",+ "channel.feishu.fetchOwnerIdAutoSuccess": "앱 소유자의 Open ID가 입력되었습니다 — 본인인지 확인한 후 저장하세요",+ "channel.feishu.fetchOwnerIdFailed": "앱 소유자를 읽는 데 실패했습니다",+ "channel.feishu.fetchOwnerIdMissingCredentials": "먼저 애플리케이션 ID와 앱 비밀을 입력하세요 — 조회는 귀하의 앱으로 실행됩니다.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID가 입력되었습니다 — 본인인지 확인한 후 저장하세요","channel.feishu.webhookMigrationDesc": "WebSocket 모드는 퍼블릭 콜백 URL 없이도 실시간 이벤트를 제공할 수 있습니다. 마이그레이션하려면 고급 설정에서 연결 모드를 WebSocket으로 변경하세요. Feishu/Lark 오픈 플랫폼에서 추가 설정은 필요하지 않습니다.","channel.feishu.webhookMigrationTitle": "WebSocket 모드로의 전환을 고려하세요","channel.groupAllowFrom": "허용된 채널",diff --git a/locales/nl-NL/agent.json b/locales/nl-NL/agent.jsonindex efc52519deb..bf92fd10025 100644--- a/locales/nl-NL/agent.json+++ b/locales/nl-NL/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "We werken eraan om deze integratie naar LobeHub te brengen. Blijf op de hoogte voor updates.","channel.comingSoonTitle": "{{name}} integratie komt binnenkort beschikbaar","channel.concurrency": "Concurrentie Modus",+ "channel.concurrencyBurst": "Uitbarsting",+ "channel.concurrencyBurstHint": "Wacht kort, en verwerk vervolgens een reeks berichten als één beurt (niets wordt overgeslagen)","channel.concurrencyDebounce": "Debounce","channel.concurrencyDebounceHint": "Alleen het laatste bericht in een reeks verwerken (eerdere worden genegeerd)","channel.concurrencyHint": "Wachtrij verwerkt berichten één voor één; Debounce wacht tot een reeks berichten is voltooid voordat ze worden verwerkt",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Kopieer deze URL en plak deze in het <bold>{{fieldName}}</bold>-veld in de {{name}} Developer Portal.","channel.exportConfig": "Configuratie Exporteren","channel.feishu.description": "Verbind deze assistent met Feishu voor privé- en groepschats.",+ "channel.feishu.fetchOwnerId": "Ophalen uit app-informatie",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Open ID van de app-eigenaar ingevuld — controleer of jij het bent, en sla op",+ "channel.feishu.fetchOwnerIdFailed": "Het ophalen van de app-eigenaar is mislukt",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Voer eerst de Applicatie-ID en App Secret in — de zoekopdracht wordt uitgevoerd als jouw app.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID ingevuld — controleer of jij het bent, en sla op","channel.feishu.webhookMigrationDesc": "De WebSocket-modus biedt realtime aflevering van events zonder dat een openbare callback-URL nodig is. Om te migreren, schakel je in Geavanceerde instellingen de Verbindingsmodus over naar WebSocket. Er is geen extra configuratie nodig op het Feishu/Lark Open Platform.","channel.feishu.webhookMigrationTitle": "Overweeg om over te stappen op de WebSocket-modus","channel.groupAllowFrom": "Toegestane kanalen",diff --git a/locales/pl-PL/agent.json b/locales/pl-PL/agent.jsonindex 26f1149a8e2..c4a3b9177cf 100644--- a/locales/pl-PL/agent.json+++ b/locales/pl-PL/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Pracujemy nad wprowadzeniem tej integracji do LobeHub. Śledź nasze aktualizacje.","channel.comingSoonTitle": "Integracja {{name}} już wkrótce","channel.concurrency": "Tryb współbieżności",+ "channel.concurrencyBurst": "Wybuch",+ "channel.concurrencyBurstHint": "Poczekaj chwilę, a następnie obsłuż serię wiadomości jako jeden obrót (nic nie zostanie pominięte)","channel.concurrencyDebounce": "Debounce","channel.concurrencyDebounceHint": "Przetwarzaj tylko ostatnią wiadomość z serii (wcześniejsze są pomijane)","channel.concurrencyHint": "Kolejka przetwarza wiadomości jedna po drugiej; Debounce czeka, aż seria wiadomości się zakończy, zanim rozpocznie przetwarzanie",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Proszę skopiować ten URL i wkleić go w polu <bold>{{fieldName}}</bold> w Portalu Deweloperskim {{name}}.","channel.exportConfig": "Eksportuj konfigurację","channel.feishu.description": "Połącz tego asystenta z Feishu, aby umożliwić czaty prywatne i grupowe.",+ "channel.feishu.fetchOwnerId": "Pobierz z informacji o aplikacji",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Wypełniono Open ID właściciela aplikacji — sprawdź, czy to Ty, a następnie zapisz",+ "channel.feishu.fetchOwnerIdFailed": "Nie udało się odczytać właściciela aplikacji",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Najpierw wprowadź ID aplikacji i App Secret — wyszukiwanie działa jako Twoja aplikacja.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID wypełnione — sprawdź, czy to Ty, a następnie zapisz","channel.feishu.webhookMigrationDesc": "Tryb WebSocket zapewnia dostarczanie zdarzeń w czasie rzeczywistym bez konieczności używania publicznego adresu URL wywołania zwrotnego. Aby przeprowadzić migrację, przełącz Tryb połączenia na WebSocket w Zaawansowanych ustawieniach. Nie jest wymagana żadna dodatkowa konfiguracja na platformie Feishu/Lark Open Platform.","channel.feishu.webhookMigrationTitle": "Rozważ migrację do trybu WebSocket","channel.groupAllowFrom": "Dozwolone kanały",diff --git a/locales/pt-BR/agent.json b/locales/pt-BR/agent.jsonindex 7abf8933810..f96ef3de78f 100644--- a/locales/pt-BR/agent.json+++ b/locales/pt-BR/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Estamos trabalhando para trazer esta integração para o LobeHub. Fique atento para atualizações.","channel.comingSoonTitle": "A integração {{name}} está chegando em breve","channel.concurrency": "Modo de Concorrência",+ "channel.concurrencyBurst": "Explosão",+ "channel.concurrencyBurstHint": "Aguarde brevemente, depois lide com uma sequência de mensagens como um único turno (nada é descartado)","channel.concurrencyDebounce": "Debounce","channel.concurrencyDebounceHint": "Processar apenas a última mensagem em uma sequência rápida (as anteriores serão descartadas)","channel.concurrencyHint": "Fila processa mensagens uma de cada vez; Debounce espera um surto de mensagens terminar antes de processar",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Por favor, copie este URL e cole no campo <bold>{{fieldName}}</bold> no Portal de Desenvolvedores do {{name}}.","channel.exportConfig": "Exportar Configuração","channel.feishu.description": "Conecte este assistente ao Feishu para bate-papo privado e em grupo.",+ "channel.feishu.fetchOwnerId": "Buscar das informações do aplicativo",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Preenchido com o Open ID do proprietário do aplicativo — verifique se é você, então salve",+ "channel.feishu.fetchOwnerIdFailed": "Falha ao ler o proprietário do aplicativo",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Insira o ID do Aplicativo e o App Secret primeiro — a busca é executada como seu aplicativo.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID preenchido — verifique se é você, então salve","channel.feishu.webhookMigrationDesc": "O modo WebSocket oferece entrega de eventos em tempo real sem a necessidade de um URL público de callback. Para migrar, altere o Modo de Conexão para WebSocket em Configurações Avançadas. Não é necessária configuração adicional na Plataforma Aberta do Feishu/Lark.","channel.feishu.webhookMigrationTitle": "Considere migrar para o modo WebSocket","channel.groupAllowFrom": "Canais Permitidos",diff --git a/locales/ru-RU/agent.json b/locales/ru-RU/agent.jsonindex a9e28f5e95e..d6969766d99 100644--- a/locales/ru-RU/agent.json+++ b/locales/ru-RU/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Мы работаем над добавлением этой интеграции в LobeHub. Следите за обновлениями.","channel.comingSoonTitle": "Интеграция {{name}} скоро будет доступна","channel.concurrency": "Режим параллельности",+ "channel.concurrencyBurst": "Всплеск",+ "channel.concurrencyBurstHint": "Коротко подождите, затем обработайте серию сообщений как один ход (ничего не теряется)","channel.concurrencyDebounce": "Дебаунс","channel.concurrencyDebounceHint": "Обрабатывать только последнее сообщение в серии (предыдущие будут отброшены)","channel.concurrencyHint": "Очередь обрабатывает сообщения по одному; Дебаунс ожидает завершения серии сообщений перед обработкой",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Пожалуйста, скопируйте этот URL и вставьте его в поле <bold>{{fieldName}}</bold> на портале разработчика {{name}}.","channel.exportConfig": "Экспортировать конфигурацию","channel.feishu.description": "Подключите этого помощника к Feishu для общения в личных и групповых чатах.",+ "channel.feishu.fetchOwnerId": "Получить из информации о приложении",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Заполнен Open ID владельца приложения — проверьте, что это вы, затем сохраните",+ "channel.feishu.fetchOwnerIdFailed": "Не удалось прочитать владельца приложения",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Сначала введите Application ID и App Secret — поиск выполняется от имени вашего приложения.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID заполнен — проверьте, что это вы, затем сохраните","channel.feishu.webhookMigrationDesc": "Режим WebSocket обеспечивает доставку событий в реальном времени без необходимости публичного URL для обратного вызова. Чтобы перейти на него, переключите режим подключения на WebSocket в дополнительных настройках. Дополнительная конфигурация на платформе Feishu/Lark Open Platform не требуется.","channel.feishu.webhookMigrationTitle": "Рекомендуем перейти на режим WebSocket","channel.groupAllowFrom": "Разрешённые каналы",diff --git a/locales/tr-TR/agent.json b/locales/tr-TR/agent.jsonindex 808a6bde1d5..2e239990168 100644--- a/locales/tr-TR/agent.json+++ b/locales/tr-TR/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Bu entegrasyonu LobeHub'a getirmek için çalışıyoruz. Güncellemeler için bizi takip edin.","channel.comingSoonTitle": "{{name}} entegrasyonu çok yakında geliyor","channel.concurrency": "Eşzamanlılık Modu",+ "channel.concurrencyBurst": "Patlama",+ "channel.concurrencyBurstHint": "Kısa bir süre bekleyin, ardından mesajları bir tur olarak işleyin (hiçbir şey düşmez)","channel.concurrencyDebounce": "Debounce","channel.concurrencyDebounceHint": "Bir patlamadaki yalnızca son mesajı işle (öncekiler yok sayılır)","channel.concurrencyHint": "Kuyruk, mesajları birer birer işler; Debounce, bir mesaj patlamasının bitmesini bekler ve ardından işlem yapar.",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Lütfen bu URL'yi kopyalayın ve {{name}} Geliştirici Portalındaki <bold>{{fieldName}}</bold> alanına yapıştırın.","channel.exportConfig": "Yapılandırmayı Dışa Aktar","channel.feishu.description": "Bu ajanı Feishu'ya özel ve grup sohbetleri için bağlayın.",+ "channel.feishu.fetchOwnerId": "Uygulama bilgisinden al",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Uygulama sahibinin Open ID'si dolduruldu — sizin olduğunuzu kontrol edin, ardından kaydedin",+ "channel.feishu.fetchOwnerIdFailed": "Uygulama sahibini okumak başarısız oldu",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Önce Uygulama Kimliği ve Uygulama Gizli Anahtarını girin — arama uygulamanız olarak çalışır.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID dolduruldu — sizin olduğunuzu kontrol edin, ardından kaydedin","channel.feishu.webhookMigrationDesc": "WebSocket modu, genel bir geri çağırma URL’sine ihtiyaç duymadan gerçek zamanlı etkinlik iletimi sağlar. Geçiş yapmak için Gelişmiş Ayarlar’dan Bağlantı Modunu WebSocket olarak değiştirin. Feishu/Lark Açık Platformunda ek bir yapılandırma gerekmez.","channel.feishu.webhookMigrationTitle": "WebSocket moduna geçmeyi düşünün","channel.groupAllowFrom": "İzin Verilen Kanallar",diff --git a/locales/vi-VN/agent.json b/locales/vi-VN/agent.jsonindex 5fd626bdc6f..c8970cdf6ff 100644--- a/locales/vi-VN/agent.json+++ b/locales/vi-VN/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "Chúng tôi đang làm việc để mang tích hợp này đến LobeHub. Hãy chờ đợi các cập nhật.","channel.comingSoonTitle": "Tích hợp {{name}} sắp ra mắt","channel.concurrency": "Chế độ Đồng thời",+ "channel.concurrencyBurst": "Bùng nổ",+ "channel.concurrencyBurstHint": "Chờ một chút, sau đó xử lý một loạt tin nhắn như một lượt (không có gì bị bỏ qua)","channel.concurrencyDebounce": "Giảm chấn","channel.concurrencyDebounceHint": "Chỉ xử lý tin nhắn cuối cùng trong một chuỗi (các tin nhắn trước bị bỏ qua)","channel.concurrencyHint": "Hàng đợi xử lý từng tin nhắn một; Giảm chấn chờ một loạt tin nhắn kết thúc trước khi xử lý",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "Vui lòng sao chép URL này và dán vào trường <bold>{{fieldName}}</bold> trong Cổng thông tin Nhà phát triển {{name}}.","channel.exportConfig": "Xuất cấu hình","channel.feishu.description": "Kết nối trợ lý này với Feishu để trò chuyện riêng tư và nhóm.",+ "channel.feishu.fetchOwnerId": "Lấy từ thông tin ứng dụng",+ "channel.feishu.fetchOwnerIdAutoSuccess": "Đã điền Open ID của chủ sở hữu ứng dụng — kiểm tra xem đó có phải bạn không, sau đó lưu",+ "channel.feishu.fetchOwnerIdFailed": "Không thể đọc chủ sở hữu ứng dụng",+ "channel.feishu.fetchOwnerIdMissingCredentials": "Nhập ID Ứng dụng và Mã Bí mật Ứng dụng trước — tra cứu sẽ chạy dưới dạng ứng dụng của bạn.",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID đã được điền — kiểm tra xem đó có phải bạn không, sau đó lưu","channel.feishu.webhookMigrationDesc": "Chế độ WebSocket cung cấp việc truyền sự kiện theo thời gian thực mà không cần URL callback công khai. Để chuyển đổi, hãy đặt Chế độ kết nối thành WebSocket trong Cài đặt nâng cao. Không cần cấu hình thêm trên Nền tảng Mở Feishu/Lark.","channel.feishu.webhookMigrationTitle": "Cân nhắc chuyển sang chế độ WebSocket","channel.groupAllowFrom": "Kênh được phép",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex dac9c21b98c..69ceba3ccaa 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "我们正在为 LobeHub 接入该平台,敬请期待。","channel.comingSoonTitle": "{{name}} 集成即将上线","channel.concurrency": "并发模式",+ "channel.concurrencyBurst": "聚合",+ "channel.concurrencyBurstHint": "先等待片刻,把连发的多条消息合并成一次处理,不丢消息","channel.concurrencyDebounce": "防抖","channel.concurrencyDebounceHint": "仅处理连续消息中的最后一条,前序消息会被丢弃","channel.concurrencyHint": "并发消息的处理方式",@@ -55,7 +57,7 @@"channel.copied": "已复制到剪贴板","channel.copy": "复制","channel.credentials": "凭证配置",- "channel.debounceMs": "防抖窗口(毫秒)",+ "channel.debounceMs": "等待窗口(毫秒)","channel.debounceMsHint": "在派发给 Agent 之前等待更多消息的时间(毫秒)","channel.deleteAllChannels": "移除所有频道","channel.deleteAllConfirm": "确定要移除所有频道吗?",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "请复制此 URL 并粘贴到 {{name}} 开发者门户的 <bold>{{fieldName}}</bold> 字段中。","channel.exportConfig": "导出平台配置","channel.feishu.description": "将助手连接到飞书,支持私聊和群聊。",+ "channel.feishu.fetchOwnerId": "从应用信息获取",+ "channel.feishu.fetchOwnerIdAutoSuccess": "已自动填入应用所有者的 Open ID,确认是你本人后保存",+ "channel.feishu.fetchOwnerIdFailed": "读取应用所有者失败",+ "channel.feishu.fetchOwnerIdMissingCredentials": "请先填写应用 ID 和 App Secret,查询以你的应用身份发起。",+ "channel.feishu.fetchOwnerIdSuccess": "已填入 Open ID,确认是你本人后保存","channel.feishu.webhookMigrationDesc": "WebSocket 模式提供实时事件推送,无需配置公网回调地址。如需迁移,在高级设置中将连接模式切换为 WebSocket 即可,无需在飞书/Lark 开放平台进行额外配置。","channel.feishu.webhookMigrationTitle": "建议迁移到 WebSocket 模式","channel.groupAllowFrom": "允许的频道",@@ -263,13 +270,13 @@"channel.userId": "你的平台用户 ID","channel.userIdHint": "供 AI 工具主动联系你(如提醒、通知),并自动加入全局白名单","channel.userIdHint.discord": "在 Discord 设置 → 高级中开启开发者模式,然后右键你的头像 → 复制用户 ID。",- "channel.userIdHint.feishu": "在飞书 / Lark 开放平台打开你的应用 → 权限管理,查看你的 Open ID。",+ "channel.userIdHint.feishu": "飞书 Open ID 按应用区分,后台没有任何页面能查到你自己的。填好凭据后会自动读取应用所有者的 ID;若没有填上,可点下方按钮重试,或在私聊里给机器人发送 /whoami。","channel.userIdHint.imessage": "使用 BlueBubbles 中显示的 iMessage handle,通常是邮箱或 E.164 手机号。","channel.userIdHint.line": "打开 LINE Developers Console → 你的 channel → Basic settings 选项卡,复制 \"Your user ID\"(以 U 开头共 33 位)。","channel.userIdHint.qq": "你的 QQ 号,在 QQ 资料页可见。","channel.userIdHint.slack": "打开 Slack 个人资料 → ⋮ 更多 → 复制 Member ID(以 U 开头)。","channel.userIdHint.telegram": "在 Telegram 中给 @userinfobot 发送任意消息,它会回复你的数字 User ID。",- "channel.userIdMissingDesc": "未填写时,AI 工具无法主动联系你,配对申请也将无法被批准。请在「高级设置」中补充。",+ "channel.userIdMissingDesc": "未填写时,AI 工具无法主动联系你,配对申请也将无法被批准。给机器人发送 /whoami 即可获取你的 ID,然后在「高级设置」中补充。","channel.userIdMissingTitle": "建议补充你的平台用户 ID","channel.validationError": "请填写应用 ID 和 Token","channel.verificationToken": "Verification Token",diff --git a/locales/zh-TW/agent.json b/locales/zh-TW/agent.jsonindex c32457cdb9d..bce9871d0f0 100644--- a/locales/zh-TW/agent.json+++ b/locales/zh-TW/agent.json@@ -27,6 +27,8 @@"channel.comingSoonDesc": "我們正在努力將此整合帶到 LobeHub。敬請期待更新。","channel.comingSoonTitle": "{{name}} 整合即將推出","channel.concurrency": "併發模式",+ "channel.concurrencyBurst": "突發",+ "channel.concurrencyBurstHint": "稍等片刻,然後將多條消息作為一個回合處理(不會丟失任何消息)","channel.concurrencyDebounce": "防抖","channel.concurrencyDebounceHint": "僅處理突發訊息中的最後一則(較早的會被忽略)","channel.concurrencyHint": "佇列以一次處理一條消息;防抖等待消息突發完成後再進行處理",@@ -89,6 +91,11 @@"channel.endpointUrlHint": "請複製此 URL 並將其貼到 {{name}} 開發者平台中的 <bold>{{fieldName}}</bold> 欄位。","channel.exportConfig": "匯出設定","channel.feishu.description": "將此助手連接到飛書以進行私人和群組聊天。",+ "channel.feishu.fetchOwnerId": "從應用信息中獲取",+ "channel.feishu.fetchOwnerIdAutoSuccess": "已填寫應用所有者的 Open ID — 請檢查是否為您,然後保存",+ "channel.feishu.fetchOwnerIdFailed": "無法讀取應用所有者",+ "channel.feishu.fetchOwnerIdMissingCredentials": "請先輸入應用 ID 和應用密鑰 — 查詢將以您的應用身份運行。",+ "channel.feishu.fetchOwnerIdSuccess": "Open ID 已填寫 — 請檢查是否為您,然後保存","channel.feishu.webhookMigrationDesc": "WebSocket 模式可即時傳遞事件,且無需公開的回呼網址。若要遷移,請在進階設定中將連線模式切換為 WebSocket,無須在飛書/Lark 開放平台進行額外設定。","channel.feishu.webhookMigrationTitle": "建議遷移至 WebSocket 模式","channel.groupAllowFrom": "允許的頻道",diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex bda6e7a4d57..b23da0aabf3 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -1141,6 +1141,157 @@ describe('tool executors', () => {});});+ describe('ordered batch calls', () => {+ // A model that posts a long report as several `sendMessage` calls emits+ // them in reading order, but `Promise.all` handed every call to the+ // platform at once and the channel kept whichever arrived first. An API+ // marked `ordered` runs its calls one after another in emission order;+ // everything else in the batch stays concurrent.+ const manifestMap = {+ 'lobe-message': {+ api: [+ { name: 'sendMessage', ordered: true },+ { name: 'replyToThread', ordered: true },+ { name: 'readMessages' },+ ],+ identifier: 'lobe-message',+ },+ };++ const messageCall = (id: string, apiName: string) => ({+ apiName,+ arguments: '{}',+ id,+ identifier: 'lobe-message',+ type: 'builtin' as const,+ });++ const batchOf = (+ toolsCalling: ReturnType<typeof messageCall>[],+ ): Extract<AgentInstruction, { type: 'call_tools_batch' }> => ({+ payload: { parentMessageId: 'assistant-msg-1', toolsCalling },+ type: 'call_tools_batch',+ });++ /** Records `start:<id>` / `end:<id>` so the interleaving is observable. */+ const trackingRunner = (delays: Record<string, number>, timeline: string[]) =>+ vi.fn().mockImplementation(async (tool: { id: string }) => {+ timeline.push(`start:${tool.id}`);+ await new Promise((resolve) => setTimeout(resolve, delays[tool.id] ?? 0));+ timeline.push(`end:${tool.id}`);+ return {+ attempts: 1,+ result: { content: `sent ${tool.id}`, executionTime: 1, state: {}, success: true },+ };+ });++ it('runs ordered calls one after another in emission order, even when the first is slowest', async () => {+ const timeline: string[] = [];+ // Slowest first: concurrent dispatch would finish send-3 before send-1.+ host.transports.tools!.run = trackingRunner(+ { 'send-1': 30, 'send-2': 10, 'send-3': 0 },+ timeline,+ );+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));++ const result = await callToolsBatch(host)(+ batchOf([+ messageCall('send-1', 'sendMessage'),+ messageCall('send-2', 'sendMessage'),+ messageCall('send-3', 'replyToThread'),+ ]),+ createState({ toolManifestMap: manifestMap }),+ );++ expect(timeline).toEqual([+ 'start:send-1',+ 'end:send-1',+ 'start:send-2',+ 'end:send-2',+ 'start:send-3',+ 'end:send-3',+ ]);+ // Every call still lands in the batch result.+ expect((result.nextContext?.payload as any).toolResults).toHaveLength(3);+ expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'assistant-msg-1' });+ });++ it('does not hold up unordered siblings behind the ordered chain', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner(+ { 'read-1': 0, 'send-1': 30, 'send-2': 10 },+ timeline,+ );+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));++ await callToolsBatch(host)(+ batchOf([+ messageCall('send-1', 'sendMessage'),+ messageCall('read-1', 'readMessages'),+ messageCall('send-2', 'sendMessage'),+ ]),+ createState({ toolManifestMap: manifestMap }),+ );++ // The read finished while send-1 was still in flight …+ expect(timeline.indexOf('end:read-1')).toBeLessThan(timeline.indexOf('end:send-1'));+ // … and send-2 still waited for send-1.+ expect(timeline.indexOf('start:send-2')).toBeGreaterThan(timeline.indexOf('end:send-1'));+ });++ it('reads the flag from a step-activated manifest as well', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner({ 'send-1': 20, 'send-2': 0 }, timeline);+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));++ await callToolsBatch(host)(+ batchOf([messageCall('send-1', 'sendMessage'), messageCall('send-2', 'sendMessage')]),+ createState({+ activatedStepTools: [+ {+ activatedAtStep: 0,+ id: 'lobe-message',+ manifest: manifestMap['lobe-message'] as any,+ source: 'activator' as any,+ },+ ],+ toolManifestMap: {},+ }),+ );++ expect(timeline).toEqual(['start:send-1', 'end:send-1', 'start:send-2', 'end:send-2']);+ });++ it('keeps unmarked calls concurrent', async () => {+ const timeline: string[] = [];+ host.transports.tools!.run = trackingRunner({ 'read-1': 20, 'read-2': 0 }, timeline);+ host.transports.messages.createToolMessage = vi+ .fn()+ .mockImplementation(async ({ tool_call_id }: { tool_call_id: string }) => ({+ id: `tool-msg-${tool_call_id}`,+ }));++ await callToolsBatch(host)(+ batchOf([messageCall('read-1', 'readMessages'), messageCall('read-2', 'readMessages')]),+ createState({ toolManifestMap: manifestMap }),+ );++ expect(timeline.indexOf('start:read-2')).toBeLessThan(timeline.indexOf('end:read-1'));+ });+ });+describe('work registration redaction', () => {// A skill intent carries the UNTRUNCATED tool payload (`data`/`args`) solely// for server-side Work registration. It must NOT ride the published streamdiff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 102169feb18..93c23d71ef8 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -129,6 +129,29 @@ const buildEffectiveManifestMap = (state: AgentState): Record<string, any> => ({),});+/**+ * Split a batch into the calls whose API is marked `ordered` (kept in emission+ * order) and the rest. The flag lives on the manifest API entry, so it is read+ * from the same effective map the run context exposes to executors.+ */+const partitionOrderedCalls = (+ state: AgentState,+ toolsCalling: ChatToolPayload[],+): { ordered: ChatToolPayload[]; unordered: ChatToolPayload[] } => {+ const manifestMap = buildEffectiveManifestMap(state);+ const ordered: ChatToolPayload[] = [];+ const unordered: ChatToolPayload[] = [];++ for (const tool of toolsCalling) {+ const apis = manifestMap[tool.identifier]?.api as+ Array<{ name?: string; ordered?: boolean }> | undefined;+ const api = apis?.find((item) => item.name === tool.apiName);+ (api?.ordered === true ? ordered : unordered).push(tool);+ }++ return { ordered, unordered };+};+const resolveCallIndex = (state: AgentState, toolName: string) => {const existingToolStats = state.usage?.tools?.byTool?.find((tool) => tool.name === toolName);return (existingToolStats?.calls ?? 0) + 1;@@ -852,130 +875,141 @@ export const callToolsBatch =const deferredToolMessageIds: Record<string, string> = {};const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;- await Promise.all(- toolsToExecute.map(async (tool) => {- const existingMessageId = existingToolMessageIds[tool.id];- const runContext = createRunContext({- host,- mode: 'batch',- parentMessageId,- reuseExistingMessage: !!existingMessageId,- state,- stepContext: runtimeContext?.stepContext,- tool,- toolMessageId: existingMessageId,- });+ const runOne = async (tool: ChatToolPayload) => {+ const existingMessageId = existingToolMessageIds[tool.id];+ const runContext = createRunContext({+ host,+ mode: 'batch',+ parentMessageId,+ reuseExistingMessage: !!existingMessageId,+ state,+ stepContext: runtimeContext?.stepContext,+ tool,+ toolMessageId: existingMessageId,+ });- await host.transports.stream.publishEvent({- data: { parentMessageId, toolCalling: tool },- stepIndex: host.operation.stepIndex,- type: 'tool_start',- });+ await host.transports.stream.publishEvent({+ data: { parentMessageId, toolCalling: tool },+ stepIndex: host.operation.stepIndex,+ type: 'tool_start',+ });- try {- const execution = await raceToolAbort(- () => tools.run(tool, runContext),- host.operation.abortSignal,- );+ try {+ const execution = await raceToolAbort(+ () => tools.run(tool, runContext),+ host.operation.abortSignal,+ );- if (execution.interrupted) {- abortedTools.push(tool);- return;- }+ if (execution.interrupted) {+ abortedTools.push(tool);+ return;+ }- if (execution.result.deferred) {- deferredTools.push(tool);- const deferredId = deferredToolMessageId(execution.result);- if (deferredId) deferredToolMessageIds[tool.id] = deferredId;- return;- }+ if (execution.result.deferred) {+ deferredTools.push(tool);+ const deferredId = deferredToolMessageId(execution.result);+ if (deferredId) deferredToolMessageIds[tool.id] = deferredId;+ return;+ }- const executionResult = execution.result;- const executionTime = executionResult.executionTime ?? 0;- const isSuccess = executionResult.success;-- await host.transports.stream.publishEvent({- data: {- executionTime,- isSuccess,- attempts: execution.attempts,- maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,- payload: { parentMessageId, toolCalling: tool },- phase: TOOL_EXECUTION_PHASE,- result: redactResultForEvents(executionResult),- },- stepIndex: host.operation.stepIndex,- type: 'tool_end',- });+ const executionResult = execution.result;+ const executionTime = executionResult.executionTime ?? 0;+ const isSuccess = executionResult.success;- let toolMessageId: string;- if (execution.toolMessageId) {- toolMessageId = execution.toolMessageId;- if (!execution.resultPersisted) {- await updateExistingToolMessage({ host, result: executionResult, toolMessageId });- }- } else if (existingMessageId) {- // Batch approval resume: fill the pending placeholder in place.- // Creating a fresh row here would leave the approved-but-empty- // original stranded under the same assistant.- toolMessageId = existingMessageId;- await updateExistingToolMessage({ host, result: executionResult, toolMessageId });- } else {- const toolMessage = await createToolMessage({- host,- parentMessageId,- result: executionResult,- state,- tool,- });- toolMessageId = toolMessage.id;- }-- // `sourceMessageId` + `workRegistration` are carried so the- // post-batch accumulate loop can persist the Work version ONCE with- // this call's cumulative cost (known only then).- const resultEntry: ToolResultEntry = {- data: executionResult,+ await host.transports.stream.publishEvent({+ data: {executionTime,isSuccess,- sourceMessageId: toolMessageId,- toolCall: tool,- toolCallId: tool.id,- workRegistration: executionResult.workRegistration,- };-- events.push({- id: tool.id,+ attempts: execution.attempts,+ maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,+ payload: { parentMessageId, toolCalling: tool },+ phase: TOOL_EXECUTION_PHASE,result: redactResultForEvents(executionResult),- type: 'tool_result',- });+ },+ stepIndex: host.operation.stepIndex,+ type: 'tool_end',+ });- const toolCost = tools.getCost?.(runContext.toolName) ?? 0;- resultEntry.usageParams = {- executionTime,- success: isSuccess,- toolCost,- toolName: runContext.toolName,- };- toolResults.push(resultEntry);- } catch (error) {- if (isPersistFatal(error)) throw error;-- // Abort is not a tool failure — see `callTool`. Siblings that already- // finished keep their real results; this one is collected for the- // aborted-row settle after the batch.- if (isOperationAbort(error, host.operation.abortSignal)) {- abortedTools.push(tool);- return;+ let toolMessageId: string;+ if (execution.toolMessageId) {+ toolMessageId = execution.toolMessageId;+ if (!execution.resultPersisted) {+ await updateExistingToolMessage({ host, result: executionResult, toolMessageId });}+ } else if (existingMessageId) {+ // Batch approval resume: fill the pending placeholder in place.+ // Creating a fresh row here would leave the approved-but-empty+ // original stranded under the same assistant.+ toolMessageId = existingMessageId;+ await updateExistingToolMessage({ host, result: executionResult, toolMessageId });+ } else {+ const toolMessage = await createToolMessage({+ host,+ parentMessageId,+ result: executionResult,+ state,+ tool,+ });+ toolMessageId = toolMessage.id;+ }- await tools.handleError?.(tool, error, runContext);- await publishError(host, error, TOOL_EXECUTION_PHASE);+ // `sourceMessageId` + `workRegistration` are carried so the+ // post-batch accumulate loop can persist the Work version ONCE with+ // this call's cumulative cost (known only then).+ const resultEntry: ToolResultEntry = {+ data: executionResult,+ executionTime,+ isSuccess,+ sourceMessageId: toolMessageId,+ toolCall: tool,+ toolCallId: tool.id,+ workRegistration: executionResult.workRegistration,+ };++ events.push({+ id: tool.id,+ result: redactResultForEvents(executionResult),+ type: 'tool_result',+ });- events.push({ error, type: 'error' });+ const toolCost = tools.getCost?.(runContext.toolName) ?? 0;+ resultEntry.usageParams = {+ executionTime,+ success: isSuccess,+ toolCost,+ toolName: runContext.toolName,+ };+ toolResults.push(resultEntry);+ } catch (error) {+ if (isPersistFatal(error)) throw error;++ // Abort is not a tool failure — see `callTool`. Siblings that already+ // finished keep their real results; this one is collected for the+ // aborted-row settle after the batch.+ if (isOperationAbort(error, host.operation.abortSignal)) {+ abortedTools.push(tool);+ return;}- }),- );++ await tools.handleError?.(tool, error, runContext);+ await publishError(host, error, TOOL_EXECUTION_PHASE);++ events.push({ error, type: 'error' });+ }+ };++ // Calls to an API marked `ordered` (posting successive chat messages) run+ // one after another in the order the model emitted them: handing them to+ // the platform concurrently let the channel keep whichever request landed+ // first, so a report emitted as nine sends arrived shuffled. The chain runs+ // alongside the unordered calls so a read-only sibling never waits on it.+ const { ordered, unordered } = partitionOrderedCalls(state, toolsToExecute);+ await Promise.all([+ ...unordered.map((tool) => runOne(tool)),+ (async () => {+ for (const tool of ordered) await runOne(tool);+ })(),+ ]);// Client tools in a mixed batch never entered `toolsToExecute` — they were// waiting for the pause below to hand them to the client. Once the operationdiff --git a/packages/builtin-tool-message/src/manifest.test.ts b/packages/builtin-tool-message/src/manifest.test.tsnew file mode 100644index 00000000000..a92526dca78--- /dev/null+++ b/packages/builtin-tool-message/src/manifest.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';++import { MessageManifest } from './manifest';+import { MessageApiName } from './types';++const findApi = (name: string) => MessageManifest.api.find((api) => api.name === name);++describe('MessageManifest', () => {+ // A report the model emits as several send calls in one step must land in+ // the channel in the order it was written. The runtime only serializes+ // calls whose API carries `ordered`, so every outbound send has to say so.+ it('marks every outbound send API as ordered', () => {+ for (const name of [+ MessageApiName.sendMessage,+ MessageApiName.sendDirectMessage,+ MessageApiName.replyToThread,+ MessageApiName.sendMessengerPush,+ ]) {+ expect(findApi(name)?.ordered, name).toBe(true);+ }+ });++ it('leaves read-only APIs concurrent', () => {+ for (const name of [+ MessageApiName.readMessages,+ MessageApiName.searchMessages,+ MessageApiName.listChannels,+ ]) {+ expect(findApi(name)?.ordered, name).toBeUndefined();+ }+ });+});diff --git a/packages/builtin-tool-message/src/manifest.ts b/packages/builtin-tool-message/src/manifest.tsindex c1e88f41a7d..187d372ce90 100644--- a/packages/builtin-tool-message/src/manifest.ts+++ b/packages/builtin-tool-message/src/manifest.ts@@ -59,6 +59,102 @@ const attachmentsSchema = {type: 'array',};+/**+ * JSON Schema for the optional `embeds` array shared by the message-sending+ * tools. Mirrors the `SendMessageEmbed` TypeScript type — the Discord embed+ * object. Other platforms ignore embeds so the `content` text still ships.+ */+const embedsSchema = {+ description:+ 'Optional rich "cards" rendered natively on Discord as embeds (title, coloured accent bar, key/value fields, footer, images). Use for reports, dashboards, structured summaries, or status notices where a card reads better than plain text. Put the human-readable summary in `content` as well so platforms without embeds (Slack / Telegram / Feishu / …) still receive the message — they silently ignore `embeds`. Max 10 embeds per message, 6000 characters total across all embeds.',+ items: {+ additionalProperties: false,+ properties: {+ author: {+ additionalProperties: false,+ description: 'Small header line above the title (e.g. the report source).',+ properties: {+ icon_url: {+ description: 'HTTPS URL of a small icon shown before the name.',+ type: 'string',+ },+ name: { description: 'Author / source name (max 256 chars).', type: 'string' },+ url: { description: 'HTTPS URL the author name links to.', type: 'string' },+ },+ required: ['name'],+ type: 'object',+ },+ color: {+ description:+ 'Accent colour of the left bar. Accepts a hex string like "#22c55e" or a decimal integer (0xRRGGBB). Use green for success, red for failure/alerts, blue/blurple for neutral info. Defaults to Discord blurple.',+ type: ['string', 'integer'],+ },+ description: {+ description:+ 'Body text below the title (max 4096 chars). Supports Discord markdown: **bold**, `code`, lists, links.',+ type: 'string',+ },+ fields: {+ description:+ 'Key/value blocks below the description (max 25). Set `inline: true` on consecutive fields to lay them out side-by-side (up to 3 per row) — ideal for "Yesterday / Last 7d / Last 30d" style columns.',+ items: {+ additionalProperties: false,+ properties: {+ inline: {+ description: 'Render side-by-side with neighbouring inline fields (max 3 per row).',+ type: 'boolean',+ },+ name: { description: 'Field label (max 256 chars).', type: 'string' },+ value: {+ description:+ 'Field body (max 1024 chars). Markdown allowed; use newlines for multi-line stats.',+ type: 'string',+ },+ },+ required: ['name', 'value'],+ type: 'object',+ },+ type: 'array',+ },+ footer: {+ additionalProperties: false,+ description: 'Small muted line at the bottom of the card (e.g. data source, generated-at).',+ properties: {+ icon_url: {+ description: 'HTTPS URL of a small icon shown before the text.',+ type: 'string',+ },+ text: { description: 'Footer text (max 2048 chars).', type: 'string' },+ },+ required: ['text'],+ type: 'object',+ },+ image: {+ additionalProperties: false,+ description: 'Large image rendered below the fields.',+ properties: { url: { description: 'HTTPS image URL.', type: 'string' } },+ required: ['url'],+ type: 'object',+ },+ thumbnail: {+ additionalProperties: false,+ description: 'Small image rendered in the top-right corner of the card.',+ properties: { url: { description: 'HTTPS image URL.', type: 'string' } },+ required: ['url'],+ type: 'object',+ },+ timestamp: {+ description: 'ISO-8601 timestamp shown next to the footer (e.g. "2026-08-10T08:00:00Z").',+ type: 'string',+ },+ title: { description: 'Card heading (max 256 chars). Emoji allowed.', type: 'string' },+ url: { description: 'HTTPS URL — makes the title a hyperlink.', type: 'string' },+ },+ type: 'object',+ },+ type: 'array',+};+/*** Schema for the bot's `settings` JSON column. Both `createBot` and* `updateBot` accept a partial object — only the keys you pass are written@@ -160,12 +256,14 @@ export const MessageManifest: BuiltinToolManifest = {// ==================== Direct Messaging ===================={description:- 'Send a direct/private message to ANOTHER user by their platform user ID. Creates a DM channel automatically. To reach the CURRENT user themselves ("DM me", "send me a message"), use `sendMessengerPush` instead — it needs no user id. Supports optional outbound media `attachments` (images / files / video / audio). To pick the target: call `listBots` for the platform first — if there\'s an entry, use its `botId`; otherwise call `listMessengers` and use that entry\'s `id` as `messengerInstallationId`.',+ 'Send a direct/private message to ANOTHER user by their platform user ID. Creates a DM channel automatically. To reach the CURRENT user themselves ("DM me", "send me a message"), use `sendMessengerPush` instead — it needs no user id. Supports optional outbound media `attachments` (images / files / video / audio) and rich `embeds` cards (Discord). To pick the target: call `listBots` for the platform first — if there\'s an entry, use its `botId`; otherwise call `listMessengers` and use that entry\'s `id` as `messengerInstallationId`.',name: MessageApiName.sendDirectMessage,+ ordered: true,parameters: {additionalProperties: false,properties: {attachments: attachmentsSchema,+ embeds: embedsSchema,botId: {description:'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',@@ -198,8 +296,9 @@ export const MessageManifest: BuiltinToolManifest = {// ==================== Core Message Operations ===================={description:- "Send a message to a specific channel or conversation on the target platform. Supports optional outbound media `attachments` (images / files / video / audio) — use this when you need to deliver a generated image, document, or other binary alongside your reply. To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",+ "Send a message to a specific channel or conversation on the target platform. Supports optional outbound media `attachments` (images / files / video / audio) — use this when you need to deliver a generated image, document, or other binary alongside your reply — and rich `embeds` cards (rendered natively on Discord; ignored elsewhere) for reports, dashboards, and structured summaries. To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",name: MessageApiName.sendMessage,+ ordered: true,parameters: {additionalProperties: false,properties: {@@ -218,12 +317,7 @@ export const MessageManifest: BuiltinToolManifest = {'Message content. Supports text and markdown depending on platform capabilities.',type: 'string',},- embeds: {- description:- 'Optional array of platform-specific embed objects (Discord embeds, Slack blocks, etc.). For generic file/image delivery use `attachments` instead.',- items: { type: 'object' },- type: 'array',- },+ embeds: embedsSchema,messengerInstallationId: {description:'System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.',@@ -656,12 +750,14 @@ export const MessageManifest: BuiltinToolManifest = {},{description:- "Send a reply to a thread. Supports optional outbound media `attachments` (images / files / video / audio). To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",+ "Send a reply to a thread. Supports optional outbound media `attachments` (images / files / video / audio) and rich `embeds` cards (Discord). To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",name: MessageApiName.replyToThread,+ ordered: true,parameters: {additionalProperties: false,properties: {attachments: attachmentsSchema,+ embeds: embedsSchema,botId: {description:'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',@@ -993,6 +1089,7 @@ export const MessageManifest: BuiltinToolManifest = {description:'Proactively push a message to the CURRENT USER\'s own DM with the LobeHub System Bot — THE api for "send me a message on <platform>", "DM me", "notify me when done". Unlike `sendDirectMessage` it needs no bot discovery, channel id, or platform user id: the server resolves the user\'s own account link. Availability comes from that account link, NOT from `listBots` / `listMessengers` — a platform missing there can still be pushable, so never refuse based on those lists. Call `listMessengerLinks` when unsure which platforms are linked; when the user named one, just push and let an `unlinked` status tell you. Telegram / Discord deliver immediately. Slack with several linked workspaces returns `needs_workspace_selection` — ask the user to pick, then retry with that `tenantId`. WeChat can only deliver inside the send window opened by the user\'s last inbound message; outside it the push is `queued` and you must tell the user to message the LobeHub WeChat bot first so the queued push gets delivered.',name: MessageApiName.sendMessengerPush,+ ordered: true,parameters: {additionalProperties: false,properties: {diff --git a/packages/builtin-tool-message/src/systemRole.ts b/packages/builtin-tool-message/src/systemRole.tsindex 8d40830b5f5..ad787afe071 100644--- a/packages/builtin-tool-message/src/systemRole.ts+++ b/packages/builtin-tool-message/src/systemRole.ts@@ -169,6 +169,36 @@ Each item is \`{ type: 'image' | 'file' | 'video' | 'audio', name?, mimeType?, fFor platforms with degradation rules, prefer URL-sourced \`image\` attachments when you want maximum compatibility. The runtime never throws on a degraded attachment — it logs and falls back so the reply still reaches the user.</attachments>+<embeds>+\`sendMessage\`, \`sendDirectMessage\`, and \`replyToThread\` also accept an optional **\`embeds\`** array — rich "cards" with a title, coloured accent bar, key/value fields, footer, and optional images. **On Discord they render natively as embeds**; every other platform ignores \`embeds\` and only delivers \`content\`, so ALWAYS put a readable plain-text/markdown version of the same information in \`content\` (it doubles as the notification preview on Discord).++**Use a card when the reply is a report, dashboard, status notice, or any structured data with several labelled numbers** (daily analytics, deploy results, task summaries, leaderboards). Keep conversational answers as plain \`content\`.++Card shape (all keys optional, at least one of title / description / fields / footer / author / image must be present):+\`\`\`json+{+ "title": "📊 Daily Report",+ "description": "Example property: \`example-property\` | 2026-08-10",+ "color": "#5865F2",+ "fields": [+ { "name": "📅 Yesterday", "value": "Users: **100**\\nSess: **120**\\nPV: **200**", "inline": true },+ { "name": "📅 Last 7d", "value": "Users: **700**\\nSess: **840**\\nPV: **1400**", "inline": true },+ { "name": "📅 Last 30d", "value": "Users: **3000**\\nSess: **3600**\\nPV: **6000**", "inline": true },+ { "name": "🔥 Trending Up", "value": "1. ↑ **+10** PV \`/example-a\`\\n2. ↑ **+5** PV \`/example-b\`" }+ ],+ "footer": { "text": "GA4 → Discord" },+ "timestamp": "2026-08-10T08:00:00Z"+}+\`\`\`++Layout rules:+- Consecutive fields with \`inline: true\` sit side-by-side, up to **3 per row** — use this for "Yesterday / 7d / 30d" style columns. A field without \`inline\` starts a new full-width row.+- Field \`value\` supports Discord markdown (**bold**, \`code\`, newlines); put one metric per line.+- \`color\` is a hex string or integer: green (\`#22c55e\`) for success, red (\`#ef4444\`) for failures/alerts, amber (\`#f59e0b\`) for warnings, default blurple for neutral info.+- Limits (the runtime truncates automatically, but plan for them): title 256, description 4096, 25 fields, field name 256 / value 1024, footer 2048, 10 embeds per message, 6000 characters total per message. Split very long reports across multiple embeds or messages.+- Do NOT pass Slack Block Kit or Feishu card JSON in \`embeds\` — only the shape above is understood.+</embeds>+<usage_guidelines>- **When the recipient is the user themselves, use \`sendMessengerPush\`** — that includes "DM me", "send me a message on <platform>", "ping me when done". Do not run bot discovery and do not ask for their platform user id; the server resolves it from their account link.- **Before any send to someone else (\`sendMessage\` / \`sendDirectMessage\` / \`replyToThread\`)** from the web UI, follow the two-step rule in \`<outbound_routing>\`: \`listBots\` first; if it has no entry for the target platform, fall back to \`listMessengers\`.@@ -185,7 +215,7 @@ For platforms with degradation rules, prefer URL-sourced \`image\` attachments w<platform_notes>**Discord:**-- Supports rich embeds, threads, polls, reactions, pins+- Supports rich embeds (see \`<embeds>\` — pass them via the \`embeds\` param of \`sendMessage\` / \`replyToThread\` / \`sendDirectMessage\`), threads, polls, reactions, pins- serverId (guild ID) needed for listChannels and getMemberInfo- **Channel types:** Discord has text channels (type 0), voice channels (type 2), categories (type 4), forum channels (type 15), and threads (types 10/11/12). Threads are child channels — they have their own unique ID.- **channelId works for both channels and threads.** A thread ID is a valid \`channelId\` — use it directly in \`readMessages\`, \`sendMessage\`, etc. No special handling needed.diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.tsindex d380ed052e7..5e17b47db7f 100644--- a/packages/builtin-tool-message/src/types.ts+++ b/packages/builtin-tool-message/src/types.ts@@ -97,6 +97,50 @@ export interface MessageTarget {// ==================== Parameter Types ====================+// --- Rich embeds (Discord cards) ---++/** A single key/value block inside a Discord embed. */+export interface SendMessageEmbedField {+ /** Render side-by-side with neighbouring inline fields (up to 3 per row). */+ inline?: boolean;+ /** Field label (max 256 chars). */+ name: string;+ /** Field body, markdown allowed (max 1024 chars). */+ value: string;+}++/**+ * JSON-safe outbound "card" for platforms with native rich embeds. Modelled+ * on the Discord embed object — every property is optional but at least one+ * visible block (title / description / fields / footer / author / image) is+ * required for the card to render. Platforms without an embed concept drop+ * these silently so the text `content` still ships.+ *+ * @see https://discord.com/developers/docs/resources/message#embed-object+ */+export interface SendMessageEmbed {+ /** Small header line above the title. */+ author?: { icon_url?: string; name: string; url?: string };+ /** Left accent colour — integer (0xRRGGBB) or `#RRGGBB` string. */+ color?: number | string;+ /** Body text, markdown allowed (max 4096 chars). */+ description?: string;+ /** Key/value blocks below the description (max 25). */+ fields?: SendMessageEmbedField[];+ /** Small footer line at the bottom of the card. */+ footer?: { icon_url?: string; text: string };+ /** Large image rendered below the fields. */+ image?: { url: string };+ /** Small image rendered top-right of the card. */+ thumbnail?: { url: string };+ /** ISO-8601 timestamp shown next to the footer. */+ timestamp?: string;+ /** Card heading (max 256 chars). */+ title?: string;+ /** Makes the title a hyperlink. */+ url?: string;+}+// --- Direct Messaging ---export interface SendDirectMessageParams {@@ -107,6 +151,11 @@ export interface SendDirectMessageParams {attachments?: SendMessageAttachment[];/** Message content */content: string;+ /**+ * Optional: rich embeds / cards. Same shape as `SendMessageParams.embeds`.+ * Only Discord renders these today; other platforms ignore them.+ */+ embeds?: SendMessageEmbed[];/** Platform */platform: MessagePlatformType;/** Target user ID on the platform */@@ -150,8 +199,12 @@ export interface SendMessageParams {channelId: string;/** Message content (text, markdown depending on platform support) */content: string;- /** Optional: embed / attachment metadata (platform-specific) */- embeds?: Record<string, unknown>[];+ /**+ * Optional: rich embeds / cards rendered natively by the platform. Only+ * Discord renders these today (as Discord embeds); other platforms ignore+ * them so the text `content` still ships. See `SendMessageEmbed`.+ */+ embeds?: SendMessageEmbed[];/** Platform to send on */platform: MessagePlatformType;/** Optional: reply to a specific message */@@ -438,6 +491,11 @@ export interface ReplyToThreadParams {attachments?: SendMessageAttachment[];/** Reply content */content: string;+ /**+ * Optional: rich embeds / cards. Same shape as `SendMessageParams.embeds`.+ * Only Discord renders these today; other platforms ignore them.+ */+ embeds?: SendMessageEmbed[];/** Platform */platform: MessagePlatformType;/** Thread ID */diff --git a/packages/chat-adapter-feishu/src/api.test.ts b/packages/chat-adapter-feishu/src/api.test.tsindex 4a989191f4b..c93dfd102ba 100644--- a/packages/chat-adapter-feishu/src/api.test.ts+++ b/packages/chat-adapter-feishu/src/api.test.ts@@ -117,3 +117,100 @@ describe('LarkApiClient cloud documents', () => {);});});++const TOKEN_RESPONSE = { code: 0, expire: 7200, msg: 'ok', tenant_access_token: 't-acc' };++/**+ * Answer the token handshake `call()` always performs first, then hand the+ * next response to the endpoint under test.+ */+function mockFetch(appResponse: unknown, status = 200) {+ return vi.fn(async (input: any) => {+ const url = typeof input === 'string' ? input : input.url;+ if (url.includes('/auth/v3/tenant_access_token/internal')) {+ return new Response(JSON.stringify(TOKEN_RESPONSE), { status: 200 });+ }+ return new Response(JSON.stringify(appResponse), { status });+ });+}++function appInfo(app: Record<string, unknown>) {+ return { code: 0, data: { app }, msg: 'success' };+}++describe('LarkApiClient.getAppOwnerId', () => {+ let fetchSpy: ReturnType<typeof mockFetch>;++ beforeEach(() => {+ vi.restoreAllMocks();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const client = () => new LarkApiClient('cli_app_1', 'secret', 'feishu');++ it('returns the app owner open_id', async () => {+ fetchSpy = mockFetch(+ appInfo({+ app_id: 'cli_app_1',+ creator_id: 'ou_creator_1111',+ owner: { name: 'Lin', owner_id: 'ou_owner_2222', type: 2 },+ }),+ );+ vi.stubGlobal('fetch', fetchSpy);++ await expect(client().getAppOwnerId()).resolves.toEqual({+ openId: 'ou_owner_2222',+ source: 'owner',+ });+ });++ it('asks the app-info endpoint for open_id ids and the required lang', async () => {+ fetchSpy = mockFetch(appInfo({ owner: { owner_id: 'ou_owner_2222' } }));+ vi.stubGlobal('fetch', fetchSpy);++ await client().getAppOwnerId();++ const url = fetchSpy.mock.calls.at(-1)![0] as string;+ expect(url).toContain('/application/v6/applications/cli_app_1');+ expect(url).toContain('user_id_type=open_id');+ // `lang` is a required query parameter; omitting it fails the request.+ expect(url).toContain('lang=');+ });++ it('falls back to the creator when the owner slot is not a person', async () => {+ // A partner- or tenant-owned app puts a non-`ou_` id in `owner`, which can+ // never match an inbound `sender_id.open_id`.+ fetchSpy = mockFetch(+ appInfo({+ creator_id: 'ou_creator_1111',+ owner: { owner_id: 'tenant_abc', type: 0 },+ }),+ );+ vi.stubGlobal('fetch', fetchSpy);++ await expect(client().getAppOwnerId()).resolves.toEqual({+ openId: 'ou_creator_1111',+ source: 'creator',+ });+ });++ it('returns null when neither field carries a user open_id', async () => {+ fetchSpy = mockFetch(appInfo({ app_id: 'cli_app_1', owner: { type: 0 } }));+ vi.stubGlobal('fetch', fetchSpy);++ await expect(client().getAppOwnerId()).resolves.toBeNull();+ });++ it('surfaces a permission failure instead of returning null', async () => {+ // Missing `application:application:self_manage` comes back as a non-zero+ // business code, which `call()` turns into an error — the caller has to be+ // able to tell "no permission" from "no owner on the app".+ fetchSpy = mockFetch({ code: 99_991_672, msg: 'no permission' });+ vi.stubGlobal('fetch', fetchSpy);++ await expect(client().getAppOwnerId()).rejects.toThrow(/99991672|no permission/);+ });+});diff --git a/packages/chat-adapter-feishu/src/api.ts b/packages/chat-adapter-feishu/src/api.tsindex 1862b51a42c..dc8bec0d06a 100644--- a/packages/chat-adapter-feishu/src/api.ts+++ b/packages/chat-adapter-feishu/src/api.ts@@ -137,6 +137,51 @@ export class LarkApiClient {return data.bot;}+ /**+ * Resolve the `open_id` of the human who owns this Feishu / Lark app.+ *+ * Why this exists: an `open_id` is scoped to a single application, so no+ * console page can ever show a person their own id for THIS bot — the only+ * other way to learn it is to message the bot and read the sender id back.+ * For a self-built app the platform does know one relevant human, the app's+ * owner (and, separately, its creator), which is normally the same person+ * configuring the channel.+ *+ * The call authenticates with the app's own tenant token, so the id that+ * comes back is already scoped to this app — the exact value inbound+ * webhooks carry as `sender_id.open_id`.+ *+ * Needs `application:application:self_manage` (already part of the+ * documented Batch Import scope list) or `admin:app.info:readonly`. `lang`+ * is a required query parameter; the value only selects the language of the+ * human-readable fields, which we ignore.+ *+ * @see https://open.feishu.cn/document/server-docs/application-v6/application/get+ */+ async getAppOwnerId(): Promise<{ openId: string; source: 'creator' | 'owner' } | null> {+ const data = await this.call(+ 'GET',+ `/application/v6/applications/${this.appId}?lang=zh_cn&user_id_type=open_id`,+ {},+ );+ const app = data.data?.app;+ if (!app) return null;++ // `owner.owner_id` is the current owner, which the console lets an admin+ // transfer; `creator_id` is whoever first created the app. Prefer the+ // owner and fall back to the creator, but only accept `ou_`-prefixed+ // values: the owner slot can also hold a tenant-level or partner entry,+ // which is not a person and would never match an inbound sender id.+ const candidates: Array<{ source: 'creator' | 'owner'; value: unknown }> = [+ { source: 'owner', value: app.owner?.owner_id },+ { source: 'creator', value: app.creator_id },+ ];+ for (const { source, value } of candidates) {+ if (typeof value === 'string' && value.startsWith('ou_')) return { openId: value, source };+ }+ return null;+ }+async getUserInfo(openId: string): Promise<{ name?: string } | null> {const userIdType = openId.startsWith('ou_')? 'open_id'diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 146412b3053..26756dde88b 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -268,6 +268,9 @@ export default {'channel.charLimit': 'Character Limit','channel.charLimitHint': 'Maximum number of characters per message','channel.concurrency': 'Concurrency Mode',+ 'channel.concurrencyBurst': 'Burst',+ 'channel.concurrencyBurstHint':+ 'Wait briefly, then handle a run of messages as one turn (nothing is dropped)','channel.concurrencyDebounce': 'Debounce','channel.concurrencyDebounceHint':'Only process the last message in a burst (earlier ones are dropped)',@@ -275,7 +278,7 @@ export default {'channel.concurrencyQueue': 'Queue','channel.concurrencyQueueHint': 'Process messages one at a time','channel.credentials': 'Credentials',- 'channel.debounceMs': 'Debounce Window (ms)',+ 'channel.debounceMs': 'Wait Window (ms)','channel.debounceMsHint':'How long to wait for additional messages before dispatching to the agent (ms)','channel.dm': 'Direct Messages',@@ -358,12 +361,19 @@ export default {'channel.userIdHint':'Lets AI tools reach you proactively (e.g. reminders); auto-trusted by the global allowlist','channel.userIdMissingDesc':- "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Fill it in under Advanced Settings.",+ "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Send /whoami to the bot to get your ID, then fill it in under Advanced Settings.",'channel.userIdMissingTitle': 'Add your platform User ID','channel.userIdHint.discord':'Enable Developer Mode (Settings → Advanced), then right-click your avatar → Copy User ID.','channel.userIdHint.feishu':- 'Open your app on the Feishu / Lark Open Platform → Permissions, then look up your Open ID.',+ "Feishu Open IDs are per-app, so no console page shows you your own. Once the credentials are in, the app owner's is filled in for you; if nothing appears, use the button below or send /whoami to the bot in a direct message.",+ 'channel.feishu.fetchOwnerId': 'Fetch from app info',+ 'channel.feishu.fetchOwnerIdAutoSuccess':+ 'Filled in the app owner’s Open ID — check it is you, then save',+ 'channel.feishu.fetchOwnerIdSuccess': 'Open ID filled in — check it is you, then save',+ 'channel.feishu.fetchOwnerIdFailed': 'Failed to read the app owner',+ 'channel.feishu.fetchOwnerIdMissingCredentials':+ 'Enter the Application ID and App Secret first — the lookup runs as your app.','channel.userIdHint.imessage':'Use your iMessage handle as seen in BlueBubbles, usually an email address or E.164 phone number.','channel.userIdHint.line':diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex 7c475a909e6..6551a364f1b 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -195,7 +195,35 @@ export interface AgentDispatchMetadata {visibility: 'internal';}+export const BotSenderMetadataSchema = z.object({+ avatar: z.string().optional(),+ fullName: z.string().optional(),+ id: z.string(),+ platform: z.string(),+ username: z.string().optional(),+});++/**+ * The real platform author of a user message that arrived through a bot+ * channel (Feishu, Discord, Slack, …). Such rows are inserted under the bot+ * OWNER's `userId`, so the joined `sender` is the owner — this block carries+ * the identity the UI should show instead.+ */+export interface BotSenderMetadata {+ /** Absolute avatar URL when the platform exposes one. */+ avatar?: string;+ /** Platform display name / nickname. */+ fullName?: string;+ /** Platform user id (Feishu open_id, Discord snowflake, …). */+ id: string;+ /** Bot platform identifier, e.g. `feishu`, `discord`. */+ platform: string;+ /** Platform handle when distinct from the display name. */+ username?: string;+}+export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema).extend({+ botSender: BotSenderMetadataSchema.optional(),agentDispatch: AgentDispatchMetadataSchema.optional(),collapsed: z.boolean().optional(),contextSelections: z.array(ContextSelectionSchema).optional(),@@ -289,6 +317,10 @@ export interface MessageMetadata {* Renderers consume this marker instead of inferring intent from the message tree.*/agentDispatch?: AgentDispatchMetadata;+ /**+ * Real platform author of a bot-channel user message; see `BotSenderMetadata`.+ */+ botSender?: BotSenderMetadata;/*** Message collapse state* true: collapsed, false/undefined: expandeddiff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 67a74ef228e..44a9299745c 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -199,6 +199,17 @@ export interface LobeChatPluginApi {*/humanIntervention?: ExtendedHumanInterventionConfig;name: string;+ /**+ * Run this API's calls one after another, in the order the model emitted+ * them, when several land in the same tool batch. Set it on APIs whose side+ * effects are order-sensitive — posting successive chat messages — where+ * concurrent dispatch would let the platform keep whichever arrived first.+ * Unmarked APIs in the same batch still run concurrently.+ *+ * Framework-only config like `humanIntervention`: it never reaches the+ * LLM-facing tool spec.+ */+ ordered?: boolean;parameters: Record<string, any>;/*** Control the render display behavior for tool results@@ -223,6 +234,7 @@ export const LobeChatPluginApiSchema = z.object({description: z.string(),humanIntervention: ExtendedHumanInterventionConfigSchema.optional(),name: z.string(),+ ordered: z.boolean().optional(),parameters: z.record(z.string(), z.any()),renderDisplayControl: RenderDisplayControlSchema.optional(),url: z.string().optional(),diff --git a/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsxnew file mode 100644index 00000000000..5fe55067961--- /dev/null+++ b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx@@ -0,0 +1,162 @@+'use client';++import { Button, toast } from '@lobehub/ui/base-ui';+import { Form as AntdForm } from 'antd';+import { Download } from 'lucide-react';+import { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentStore } from '@/store/agent';++import type { PlatformSettingsFieldExtrasProps } from '../types';+import { fillOwnerId } from './fillOwnerId';+import { useAutoOwnerLookup } from './useAutoOwnerLookup';++/**+ * Fills "Your Platform User ID" on Feishu / Lark from the app's own info.+ *+ * A Feishu `open_id` is scoped to one application, so no console page can show+ * an operator their own id for this bot — the only other route is DMing the bot+ * `/whoami`. The app's own credentials, however, can read the app's owner,+ * which for a self-built app is normally the person configuring this channel.+ *+ * The lookup runs on its own once credential input has settled and the+ * field is still empty: asking for a click bought nothing, since the value is+ * an opaque `ou_…` string nobody can verify by looking at it.+ *+ * What it deliberately does NOT do is save. This id decides `isOwner`, which+ * is what grants device tools (`local-system` / `remote-device`) access to the+ * operator's own machines — so on an app an admin created for someone else, a+ * silent write would hand that admin those tools. Writing into the visible+ * field instead keeps the value on screen, editable, and behind the operator's+ * own Save. The button stays as the retry path, and is the only one that+ * surfaces an error: an automatic attempt that fails stays quiet, because the+ * operator never asked for it.+ */+export const FeishuUserIdExtras = ({+ disabled,+ onFilled,+ platformId,+ savedValue,+}: PlatformSettingsFieldExtrasProps) => {+ const { t: _t } = useTranslation('agent');+ const t = _t as (key: string) => string;++ const form = AntdForm.useFormInstance();+ const applicationId = AntdForm.useWatch('applicationId', form) as string | undefined;+ const appSecret = AntdForm.useWatch(['credentials', 'appSecret'], form) as string | undefined;+ const [loading, setLoading] = useState(false);+ const requestRef = useRef(0);++ const feishuFetchOwnerId = useAgentStore((s) => s.feishuFetchOwnerId);++ const appId = applicationId?.trim();+ const secret = appSecret?.trim();+ useEffect(() => {+ setLoading(false);+ return () => {+ requestRef.current += 1;+ };+ }, [appId, disabled, platformId, secret]);++ const fetchOwnerId = useCallback(+ async (mode: 'auto' | 'manual') => {+ if (disabled || !appId || !secret) return;++ const request = ++requestRef.current;+ setLoading(true);+ try {+ const owner = await fillOwnerId({+ credentials: {+ appId,+ appSecret: secret,+ platform: platformId === 'lark' ? 'lark' : 'feishu',+ },+ fetchOwner: feishuFetchOwnerId,+ form,+ isCurrent: () => request === requestRef.current,+ });+ if (!owner) return;+ // Mirror the field's own validation/dirty handling: `setFieldValue`+ // neither validates nor notifies, so do both explicitly.+ form.validateFields([['settings', 'userId']]).catch(() => undefined);+ onFilled?.();+ const base = t(+ mode === 'auto'+ ? 'channel.feishu.fetchOwnerIdAutoSuccess'+ : 'channel.feishu.fetchOwnerIdSuccess',+ );+ // The toast is the only thing that tells an operator a value appeared+ // without them asking, so it always fires — including on the+ // automatic path.+ toast.success(owner.name ? `${base} (${owner.name})` : base);+ } catch (error) {+ if (mode === 'auto' || request !== requestRef.current) return;+ const text = error instanceof Error ? error.message : String(error);+ toast.error(`${t('channel.feishu.fetchOwnerIdFailed')}: ${text}`);+ } finally {+ if (request === requestRef.current) setLoading(false);+ }+ },+ [appId, disabled, feishuFetchOwnerId, form, onFilled, platformId, secret, t],+ );++ // Whether the field currently holds a value, which decides whether the+ // retry button is worth showing at all. antd hydrates the form after mount,+ // so an `undefined` watch means "not loaded yet" rather than "empty" — fall+ // back to the saved value during that window so an already-configured bot+ // never flashes a button it doesn't need.+ const watchedUserId = AntdForm.useWatch(['settings', 'userId'], form) as string | undefined;+ const [formHydrated, setFormHydrated] = useState(false);+ useEffect(() => {+ if (watchedUserId !== undefined) setFormHydrated(true);+ }, [watchedUserId]);+ const effectiveUserId = formHydrated+ ? watchedUserId+ : typeof savedValue === 'string'+ ? savedValue+ : undefined;+ const hasUserId = !!effectiveUserId?.trim();++ const cancelAutomaticLookup = useAutoOwnerLookup({+ appId,+ secret,+ disabled,+ platformId,+ savedValue,+ onLookup: () => {+ void fetchOwnerId('auto');+ },+ });++ const handleClick = () => {+ if (!appId || !secret) {+ toast.warning(t('channel.feishu.fetchOwnerIdMissingCredentials'));+ return;+ }+ cancelAutomaticLookup();+ void fetchOwnerId('manual');+ };++ // Hidden once the field holds a value: in the happy path the lookup already+ // ran on its own and a permanent button is just noise. It comes back+ // whenever the field is empty — the automatic attempt failed and the+ // operator wants the reason, or they cleared the value and changed their+ // mind — and it is the only path that surfaces the error, because an+ // attempt nobody asked for stays quiet.+ if (hasUserId) return null;++ return (+ <Button+ disabled={disabled || !appId || !secret}+ icon={<Download size={14} />}+ loading={loading}+ size="small"+ style={{ alignSelf: 'flex-start', marginBlockEnd: 12, marginInlineStart: 32 }}+ type="default"+ onClick={handleClick}+ >+ {t('channel.feishu.fetchOwnerId')}+ </Button>+ );+};diff --git a/src/features/AgentSetting/AgentChannel/feishu/fillOwnerId.test.ts b/src/features/AgentSetting/AgentChannel/feishu/fillOwnerId.test.tsnew file mode 100644index 00000000000..e24af658911--- /dev/null+++ b/src/features/AgentSetting/AgentChannel/feishu/fillOwnerId.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it, vi } from 'vitest';++import { fillOwnerId } from './fillOwnerId';++describe('fillOwnerId', () => {+ it.each(['unchanged', 'user-id', 'cleared', 'app-id', 'secret', 'superseded'])(+ 'handles %s form state while an owner lookup is pending',+ async (change) => {+ const fields: Record<string, unknown> = {+ 'applicationId': 'app-a',+ 'credentials.appSecret': 'secret-a',+ 'settings.userId': '',+ };+ let touched = false;+ let current = true;+ let resolve!: (owner: { openId: string }) => void;+ const response = new Promise<{ openId: string }>((done) => {+ resolve = done;+ });+ const form = {+ getFieldValue: (name: string | string[]) =>+ fields[Array.isArray(name) ? name.join('.') : name],+ isFieldTouched: () => touched,+ setFieldValue: vi.fn((name: string[], value: string) => {+ fields[name.join('.')] = value;+ }),+ };+ const pending = fillOwnerId({+ credentials: { appId: 'app-a', appSecret: 'secret-a', platform: 'feishu' },+ fetchOwner: () => response,+ form,+ isCurrent: () => current,+ });+ if (change === 'user-id') fields['settings.userId'] = 'deliberate-user';+ if (change === 'cleared') touched = true;+ if (change === 'app-id') fields.applicationId = 'app-b';+ if (change === 'secret') fields['credentials.appSecret'] = 'secret-b';+ if (change === 'superseded') current = false;+ resolve({ openId: 'app-owner' });++ const result = await pending;++ if (change === 'unchanged') {+ expect(result).toEqual({ openId: 'app-owner' });+ expect(fields['settings.userId']).toBe('app-owner');+ } else {+ expect(result).toBeUndefined();+ expect(form.setFieldValue).not.toHaveBeenCalled();+ }+ },+ );+});diff --git a/src/features/AgentSetting/AgentChannel/feishu/fillOwnerId.ts b/src/features/AgentSetting/AgentChannel/feishu/fillOwnerId.tsnew file mode 100644index 00000000000..55853bfa011--- /dev/null+++ b/src/features/AgentSetting/AgentChannel/feishu/fillOwnerId.ts@@ -0,0 +1,49 @@+interface OwnerLookupForm {+ getFieldValue: (name: string | string[]) => unknown;+ isFieldTouched: (name: string[]) => boolean;+ setFieldValue: (name: string[], value: string) => void;+}++interface AppCredentials {+ appId: string;+ appSecret: string;+ platform: 'feishu' | 'lark';+}++interface AppOwner {+ name?: string;+ openId: string;+}++/** Apply a lookup only while its credentials and the operator's field are unchanged. */+export async function fillOwnerId({+ credentials,+ fetchOwner,+ form,+ isCurrent,+}: {+ credentials: AppCredentials;+ fetchOwner: (credentials: AppCredentials) => Promise<AppOwner>;+ form: OwnerLookupForm;+ isCurrent: () => boolean;+}): Promise<AppOwner | undefined> {+ const field = ['settings', 'userId'];+ const initialValue = form.getFieldValue(field);+ if (typeof initialValue === 'string' && initialValue.trim()) return undefined;+ const initiallyTouched = form.isFieldTouched(field);+ const owner = await fetchOwner(credentials);++ if (+ !isCurrent() ||+ String(form.getFieldValue('applicationId') ?? '').trim() !== credentials.appId ||+ String(form.getFieldValue(['credentials', 'appSecret']) ?? '').trim() !==+ credentials.appSecret ||+ form.getFieldValue(field) !== initialValue ||+ form.isFieldTouched(field) !== initiallyTouched+ ) {+ return undefined;+ }++ form.setFieldValue(field, owner.openId);+ return owner;+}diff --git a/src/features/AgentSetting/AgentChannel/feishu/useAutoOwnerLookup.test.ts b/src/features/AgentSetting/AgentChannel/feishu/useAutoOwnerLookup.test.tsnew file mode 100644index 00000000000..cd7f99f3da4--- /dev/null+++ b/src/features/AgentSetting/AgentChannel/feishu/useAutoOwnerLookup.test.ts@@ -0,0 +1,84 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useAutoOwnerLookup } from './useAutoOwnerLookup';++describe('automatic owner lookup timing', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it('only requests the settled credential pair after a sequence of edits', () => {+ const lookup = vi.fn();+ const { rerender } = renderHook(+ ({ secret }) =>+ useAutoOwnerLookup({+ appId: 'app',+ secret,+ platformId: 'feishu',+ onLookup: () => lookup(secret),+ }),+ { initialProps: { secret: 's' } },+ );+ for (const secret of ['se', 'sec', 'secret']) {+ act(() => vi.advanceTimersByTime(100));+ rerender({ secret });+ }+ act(() => vi.advanceTimersByTime(599));+ expect(lookup).not.toHaveBeenCalled();+ act(() => vi.advanceTimersByTime(1));+ expect(lookup.mock.calls).toEqual([['secret']]);+ rerender({ secret: 'secret' });+ act(() => vi.advanceTimersByTime(1000));+ expect(lookup).toHaveBeenCalledTimes(1);+ });++ it.each(['disabled', 'saved', 'unmounted', 'manual'])(+ 'cancels a pending automatic lookup when %s',+ (reason) => {+ const lookup = vi.fn();+ const { rerender, unmount, result } = renderHook(+ ({ disabled, savedValue }) =>+ useAutoOwnerLookup({+ appId: 'app',+ secret: 'secret',+ platformId: 'lark',+ onLookup: lookup,+ disabled,+ savedValue,+ }),+ { initialProps: { disabled: false, savedValue: '' } },+ );+ act(() => vi.advanceTimersByTime(200));+ if (reason === 'disabled') rerender({ disabled: true, savedValue: '' });+ if (reason === 'saved') rerender({ disabled: false, savedValue: 'owner' });+ if (reason === 'unmounted') unmount();+ if (reason === 'manual') act(() => result.current());+ act(() => vi.advanceTimersByTime(1000));+ expect(lookup).not.toHaveBeenCalled();+ },+ );++ it('re-arms for corrected credentials and a different platform', () => {+ const lookup = vi.fn();+ const { rerender } = renderHook(+ ({ secret, platformId }) =>+ useAutoOwnerLookup({+ appId: 'app',+ secret,+ platformId,+ onLookup: () => lookup(platformId, secret),+ }),+ { initialProps: { secret: 'first', platformId: 'feishu' } },+ );+ act(() => vi.advanceTimersByTime(600));+ rerender({ secret: 'corrected', platformId: 'feishu' });+ act(() => vi.advanceTimersByTime(600));+ rerender({ secret: 'corrected', platformId: 'lark' });+ act(() => vi.advanceTimersByTime(600));+ expect(lookup.mock.calls).toEqual([+ ['feishu', 'first'],+ ['feishu', 'corrected'],+ ['lark', 'corrected'],+ ]);+ });+});diff --git a/src/features/AgentSetting/AgentChannel/feishu/useAutoOwnerLookup.ts b/src/features/AgentSetting/AgentChannel/feishu/useAutoOwnerLookup.tsnew file mode 100644index 00000000000..d106792d1ea--- /dev/null+++ b/src/features/AgentSetting/AgentChannel/feishu/useAutoOwnerLookup.ts@@ -0,0 +1,43 @@+import { useDebounceFn } from 'ahooks';+import { useEffect, useRef } from 'react';++interface AutoOwnerLookupOptions {+ appId?: string;+ disabled?: boolean;+ onLookup: () => void;+ platformId: string;+ savedValue?: unknown;+ secret?: string;+}++/** Wait for credential edits to settle, without refilling a deliberately cleared owner. */+export const useAutoOwnerLookup = ({+ appId,+ disabled,+ onLookup,+ platformId,+ savedValue,+ secret,+}: AutoOwnerLookupOptions) => {+ const attemptedKey = useRef<string | null>(null);+ const key = appId && secret ? `${platformId}\u0000${appId}\u0000${secret}` : null;+ const hasSavedValue = typeof savedValue === 'string' && !!savedValue.trim();+ const { cancel, run } = useDebounceFn(+ (credentialKey: string) => {+ attemptedKey.current = credentialKey;+ onLookup();+ },+ { wait: 600 },+ );++ useEffect(() => {+ if (disabled || hasSavedValue || !key || attemptedKey.current === key) return;+ run(key);+ return cancel;+ }, [cancel, disabled, hasSavedValue, key, run]);++ return () => {+ cancel();+ attemptedKey.current = key;+ };+};diff --git a/src/features/AgentSetting/AgentChannel/types.ts b/src/features/AgentSetting/AgentChannel/types.tsnew file mode 100644index 00000000000..6363b3f36e4--- /dev/null+++ b/src/features/AgentSetting/AgentChannel/types.ts@@ -0,0 +1,17 @@+export interface PlatformSettingsFieldExtrasProps {+ disabled?: boolean;+ /**+ * Report that the helper wrote into the form. `form.setFieldValue` does not+ * fire the Form's `onValuesChange`, so without this the page never learns it+ * has unsaved changes and the Discard button stays hidden.+ */+ onFilled?: () => void;+ /** Platform the field belongs to — the shared Feishu/Lark schema needs it to pick a domain. */+ platformId: string;+ /**+ * The field's value as currently persisted, which is what a helper should+ * test before acting on its own: antd hydrates the form after mount, so a+ * watched empty value cannot distinguish "unset" from "not loaded yet".+ */+ savedValue?: unknown;+}diff --git a/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsx b/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsxindex b94dd5fa0c6..caa41e750bb 100644--- a/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsx+++ b/src/features/Conversation/Messages/CompressedGroup/CompressedMessageItem.tsx@@ -13,7 +13,7 @@ import { userProfileSelectors } from '@/store/user/selectors';import { useAgentMeta } from '../../hooks';import ContentBlock from '../AssistantGroup/components/ContentBlock';import UserMessageContent from '../User/components/MessageContent';-import { resolveSenderIdentity } from '../User/resolveSenderIdentity';+import { getBotSender, resolveSenderIdentity } from '../User/resolveSenderIdentity';interface CompressedMessageItemProps {message: UIChatMessage;@@ -35,6 +35,7 @@ const CompressedMessageItem = memo<CompressedMessageItemProps>(({ message }) =>// A shared (workspace) topic's compressed history may hold messages from// other members — render the sender's identity, not the viewer's.const { avatar, title } = resolveSenderIdentity({+ botSender: getBotSender(message),currentUserId,selfAvatar: userAvatar,sender,diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsxindex 2f5dbc170c7..674f5d098d8 100644--- a/src/features/Conversation/Messages/User/index.tsx+++ b/src/features/Conversation/Messages/User/index.tsx@@ -24,7 +24,7 @@ import {import Actions from './Actions';import UserMessageContent from './components/MessageContent';import { UserMessageExtra } from './Extra';-import { resolveSenderIdentity } from './resolveSenderIdentity';+import { getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';import ScheduledRunFooter from './ScheduledRunFooter';interface UserMessageProps {@@ -36,6 +36,7 @@ interface UserMessageProps {const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual)!;const { content, createdAt, error, role, extra, targetId, sender } = item;+ const botSender = getBotSender(item);const { t } = useTranslation('chat');const selfAvatar = useUserAvatar();@@ -47,9 +48,12 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {// visible even during single-user testing; personal mode keeps the legacy// hidden-avatar behavior. Self identity applies only to the viewer's own// rows — see resolveSenderIdentity.- const showSender = Boolean(activeWorkspaceId);+ // A bot-channel row is authored by someone else even in personal mode, so+ // its sender is always shown.+ const showSender = Boolean(activeWorkspaceId) || !!botSender;const currentUserId = useUserStore(userProfileSelectors.userId);const { avatar, title } = resolveSenderIdentity({+ botSender,currentUserId,selfAvatar,selfTitle,diff --git a/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts b/src/features/Conversation/Messages/User/resolveSenderIdentity.test.tsindex 81d840aca01..89bd73a82f4 100644--- a/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts+++ b/src/features/Conversation/Messages/User/resolveSenderIdentity.test.ts@@ -1,6 +1,7 @@+import { RequestTrigger } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { resolveSenderIdentity } from './resolveSenderIdentity';+import { getBotSender, resolveSenderIdentity } from './resolveSenderIdentity';const viewer = {currentUserId: 'user-viewer',@@ -78,4 +79,49 @@ describe('resolveSenderIdentity', () => {expect(result.title).toBe('Real Name');expect(result.avatar).toBe(viewer.selfAvatar);});++ it('prefers the bot-channel sender over the owner account', () => {+ const result = resolveSenderIdentity({+ ...viewer,+ botSender: { fullName: '文彬', id: 'ou_1', platform: 'feishu' },+ sender: { avatar: 'owner.png', fullName: 'Lin', id: 'user-viewer', username: null },+ });+ expect(result).toEqual({ avatar: undefined, isOwn: false, title: '文彬' });+ });++ it('falls back to the bot sender username, then the unknown label', () => {+ expect(+ resolveSenderIdentity({+ ...viewer,+ botSender: { id: '1', platform: 'discord', username: 'john', avatar: 'https://x/a.png' },+ }),+ ).toEqual({ avatar: 'https://x/a.png', isOwn: false, title: 'john' });+ expect(+ resolveSenderIdentity({ ...viewer, botSender: { id: '1', platform: 'discord' } }).title,+ ).toBe(viewer.unknownLabel);+ });+});++describe('getBotSender', () => {+ it('reads metadata first and falls back to the inline speaker tag', () => {+ expect(+ getBotSender({+ content: '<speaker id="legacy" nickname="Old" />\nhi',+ metadata: { botSender: { id: 'new', platform: 'feishu' } },+ }),+ ).toEqual({ id: 'new', platform: 'feishu' });+ expect(+ getBotSender({+ content: '<speaker id="legacy" nickname="Old" />\nhi',+ metadata: { trigger: RequestTrigger.Bot },+ })?.fullName,+ ).toBe('Old');+ expect(getBotSender({ content: 'hi' })).toBeUndefined();+ });++ it('does not trust a speaker tag typed in an ordinary user message', () => {+ expect(+ getBotSender({ content: '<speaker id="owner" nickname="Workspace owner" />\nhi' }),+ ).toBeUndefined();+ });});diff --git a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts b/src/features/Conversation/Messages/User/resolveSenderIdentity.tsindex d43fc6d1ab9..446e75f294c 100644--- a/src/features/Conversation/Messages/User/resolveSenderIdentity.ts+++ b/src/features/Conversation/Messages/User/resolveSenderIdentity.ts@@ -1,6 +1,13 @@-import { type MessageSender } from '@lobechat/types';+import { type BotSenderMetadata, type MessageSender, RequestTrigger } from '@lobechat/types';++import { parseSpeakerTag } from '@/store/chat/utils/parseSpeakerTag';interface ResolveSenderIdentityOptions {+ /**+ * Real platform author of a bot-channel message. Wins over `sender`, which+ * for such rows is the bot OWNER's account rather than who actually typed.+ */+ botSender?: BotSenderMetadata | null;/** Viewer's user id, used to detect their own messages. */currentUserId?: string | null;/** Viewer's avatar, applied only to their own messages. */@@ -22,12 +29,21 @@ interface ResolveSenderIdentityOptions {* misattribute their messages to whoever is looking.*/export const resolveSenderIdentity = ({+ botSender,currentUserId,selfAvatar,selfTitle,sender,unknownLabel,}: ResolveSenderIdentityOptions) => {+ if (botSender) {+ return {+ avatar: botSender.avatar || undefined,+ isOwn: false,+ title: botSender.fullName || botSender.username || unknownLabel,+ };+ }+const isOwn = !sender || sender.id === currentUserId;const senderName = sender?.fullName || sender?.username || '';const title = isOwn ? senderName || selfTitle || '' : senderName || unknownLabel;@@ -38,3 +54,14 @@ export const resolveSenderIdentity = ({return { avatar, isOwn, title };};++/**+ * Bot-channel sender for a user message: the structured block written by the+ * server, falling back to the `<speaker>` tag older rows still carry inline.+ */+export const getBotSender = (message: {+ content?: string | null;+ metadata?: { botSender?: BotSenderMetadata | null; trigger?: RequestTrigger } | null;+}): BotSenderMetadata | undefined =>+ message.metadata?.botSender ??+ (message.metadata?.trigger === RequestTrigger.Bot ? parseSpeakerTag(message.content) : undefined);diff --git a/src/features/Messenger/LinkModal/Discord.tsx b/src/features/Messenger/LinkModal/Discord.tsxindex 94ec4def805..0a8406860dd 100644--- a/src/features/Messenger/LinkModal/Discord.tsx+++ b/src/features/Messenger/LinkModal/Discord.tsx@@ -7,6 +7,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { PlatformAvatar } from '../constants';+import { useMessengerInstallHref } from '../installHref';interface DiscordLinkBodyProps {appId?: string;@@ -17,6 +18,7 @@ interface DiscordLinkBodyProps {const DiscordLinkBody = memo<DiscordLinkBodyProps>(({ appId, disabled, name }) => {const { t } = useTranslation('messenger');+ const installHref = useMessengerInstallHref('discord');// Route Discord installs through the LobeHub install endpoint so the OAuth// redirect lands at our callback — we read `guild_id` straight off the@@ -47,8 +49,8 @@ const DiscordLinkBody = memo<DiscordLinkBodyProps>(({ appId, disabled, name }) =</Flexbox><Buttonblock- disabled={disabled}- href={disabled ? undefined : '/api/agent/messenger/discord/install'}+ disabled={disabled || !installHref}+ href={disabled ? undefined : installHref}size="large"target="_blank"type="primary"diff --git a/src/features/Messenger/LinkModal/Slack.tsx b/src/features/Messenger/LinkModal/Slack.tsxindex a494bea2be9..a1a3e8ca668 100644--- a/src/features/Messenger/LinkModal/Slack.tsx+++ b/src/features/Messenger/LinkModal/Slack.tsx@@ -6,6 +6,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { PlatformAvatar } from '../constants';+import { useMessengerInstallHref } from '../installHref';interface SlackLinkBodyProps {disabled?: boolean;@@ -13,6 +14,7 @@ interface SlackLinkBodyProps {const SlackLinkBody = memo<SlackLinkBodyProps>(({ disabled }) => {const { t } = useTranslation('messenger');+ const installHref = useMessengerInstallHref('slack');return (<>@@ -27,8 +29,8 @@ const SlackLinkBody = memo<SlackLinkBodyProps>(({ disabled }) => {</Flexbox><Buttonblock- disabled={disabled}- href={disabled ? undefined : '/api/agent/messenger/slack/install'}+ disabled={disabled || !installHref}+ href={disabled ? undefined : installHref}size="large"target="_blank"type="primary"diff --git a/src/features/Messenger/installHref.test.ts b/src/features/Messenger/installHref.test.tsnew file mode 100644index 00000000000..a2919d44adc--- /dev/null+++ b/src/features/Messenger/installHref.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { resolveMessengerInstallHref } from './installHref';++describe('resolveMessengerInstallHref', () => {+ it('builds an absolute install URL against the app origin on web', () => {+ expect(resolveMessengerInstallHref('discord', 'https://lobehub.com')).toBe(+ 'https://lobehub.com/api/agent/messenger/discord/install',+ );+ });++ it('builds against the desktop remote server URL and tolerates trailing slashes', () => {+ expect(resolveMessengerInstallHref('slack', 'https://app.lobehub.com/')).toBe(+ 'https://app.lobehub.com/api/agent/messenger/slack/install',+ );+ });++ it('returns undefined while the origin is not resolved yet', () => {+ expect(resolveMessengerInstallHref('discord', undefined)).toBeUndefined();+ expect(resolveMessengerInstallHref('discord', '')).toBeUndefined();+ });+});diff --git a/src/features/Messenger/installHref.ts b/src/features/Messenger/installHref.tsnew file mode 100644index 00000000000..2c47a1d2d21--- /dev/null+++ b/src/features/Messenger/installHref.ts@@ -0,0 +1,36 @@+import urlJoin from 'url-join';++import { useAppOrigin } from '@/hooks/useAppOrigin';++/** Platforms whose "Connect" flow starts at the LobeHub OAuth install endpoint. */+export type MessengerOAuthInstallPlatform = 'discord' | 'slack';++const MESSENGER_INSTALL_PATHS: Record<MessengerOAuthInstallPlatform, string> = {+ discord: '/api/agent/messenger/discord/install',+ slack: '/api/agent/messenger/slack/install',+};++/**+ * The install endpoint must be opened as an absolute web URL. On web a relative+ * path would resolve against the site origin anyway, but on desktop the renderer+ * runs on `app://renderer`, so a relative `target="_blank"` link becomes+ * `app://renderer/api/...` and the main process denies it instead of handing it+ * to the system browser. Returns `undefined` until the origin is known so the+ * caller can keep the button disabled.+ */+export const resolveMessengerInstallHref = (+ platform: MessengerOAuthInstallPlatform,+ appOrigin: string | undefined,+): string | undefined => {+ if (!appOrigin) return undefined;++ return urlJoin(appOrigin, MESSENGER_INSTALL_PATHS[platform]);+};++export const useMessengerInstallHref = (+ platform: MessengerOAuthInstallPlatform,+): string | undefined => {+ const appOrigin = useAppOrigin();++ return resolveMessengerInstallHref(platform, appOrigin);+};diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsxindex 09d9d5d6326..8b447e627eb 100644--- a/src/routes/(main)/agent/channel/detail/Body.tsx+++ b/src/routes/(main)/agent/channel/detail/Body.tsx@@ -29,7 +29,11 @@ import type {SerializedPlatformDefinition,} from '@/server/services/bot/platforms/types';-import { platformCredentialBodyMap, platformCredentialExtrasMap } from '../platform/registry';+import {+ platformCredentialBodyMap,+ platformCredentialExtrasMap,+ platformSettingsFieldExtrasMap,+} from '../platform/registry';import { extractSettingsDefaults } from './formState';import type { ChannelFormValues } from './index';@@ -214,7 +218,15 @@ const SchemaField = memo<SchemaFieldProps>(const watchedValue = AntdForm.useWatch(field.visibleWhen ? [parentKey, field.visibleWhen.field] : [],);- if (field.visibleWhen && watchedValue !== field.visibleWhen.value) return null;+ if (field.visibleWhen) {+ // An array matches any of its entries, so one field can be shared by+ // several sibling values (e.g. the window size for `burst` + `debounce`).+ const expected = field.visibleWhen.value;+ const matches = Array.isArray(expected)+ ? expected.includes(watchedValue)+ : watchedValue === expected;+ if (!matches) return null;+ }// Only explicitly authored, actionable guidance earns a help affordance.// Generic schema descriptions stay out of the compact row layout.@@ -565,6 +577,14 @@ const Body = memo<BodyProps>(onValuesChange?.(form.getFieldsValue(true) as ChannelFormValues);}, [form, onValuesChange, platformDef.schema]);+ // A settings-field helper writes straight into the form, which does not+ // fire the Form's `onValuesChange` — same reason `handleResetSettings`+ // reports its own write. Without this the page never sees the change and+ // the unsaved-changes affordances stay hidden.+ const handleFieldExtrasFilled = useCallback(() => {+ onValuesChange?.(form.getFieldsValue(true) as ChannelFormValues);+ }, [form, onValuesChange]);+const handleSettingsHeaderClick = useCallback((event: MouseEvent<HTMLDivElement>) => {const target = event.target;if (!(target instanceof Element)) return;@@ -674,15 +694,26 @@ const Body = memo<BodyProps>(const featureLocked =!!field.paidFeature &&platformDef.access?.features?.[field.paidFeature]?.allowed === false;+ const FieldExtras =+ platformSettingsFieldExtrasMap[`${platformDef.id}:${field.key}`];return (- <SchemaField- divider- disabled={disabled}- featureLocked={featureLocked}- field={field}- key={field.key}- parentKey="settings"- />+ <Fragment key={field.key}>+ <SchemaField+ divider+ disabled={disabled}+ featureLocked={featureLocked}+ field={field}+ parentKey="settings"+ />+ {FieldExtras && (+ <FieldExtras+ disabled={disabled || featureLocked}+ platformId={platformDef.id}+ savedValue={currentConfig?.settings?.[field.key]}+ onFilled={handleFieldExtrasFilled}+ />+ )}+ </Fragment>);})}</FormGroup>diff --git a/src/routes/(main)/agent/channel/platform/registry.ts b/src/routes/(main)/agent/channel/platform/registry.tsindex ad58b6a6310..496eeba63a9 100644--- a/src/routes/(main)/agent/channel/platform/registry.ts+++ b/src/routes/(main)/agent/channel/platform/registry.ts@@ -1,8 +1,14 @@import type { ComponentType } from 'react';+import { FeishuUserIdExtras } from '@/features/AgentSetting/AgentChannel/feishu/UserIdExtras';+import ImessageCredentialExtras from './imessage/CredentialExtras';import LineCredentialExtras from './line/CredentialExtras';-import type { PlatformCredentialBodyProps, PlatformCredentialExtrasProps } from './types';+import type {+ PlatformCredentialBodyProps,+ PlatformCredentialExtrasProps,+ PlatformSettingsFieldExtrasProps,+} from './types';import WechatCredentialBody from './wechat/CredentialBody';export const platformCredentialBodyMap: Record<@@ -26,3 +32,21 @@ export const platformCredentialExtrasMap: Record<imessage: ImessageCredentialExtras,line: LineCredentialExtras,};++/**+ * Components rendered directly under a single Advanced-Settings field, keyed+ * by `<platformId>:<fieldKey>`. Use this when a helper acts on one specific+ * setting rather than on the credential block — Feishu's "fetch my Open ID+ * from the app info" button has to sit next to `settings.userId`, which+ * `platformCredentialExtrasMap` renders too far from.+ *+ * Feishu and Lark share one schema but address different API domains, so both+ * ids are registered against the same component.+ */+export const platformSettingsFieldExtrasMap: Record<+ string,+ ComponentType<PlatformSettingsFieldExtrasProps>+> = {+ 'feishu:userId': FeishuUserIdExtras,+ 'lark:userId': FeishuUserIdExtras,+};diff --git a/src/routes/(main)/agent/channel/platform/types.ts b/src/routes/(main)/agent/channel/platform/types.tsindex fb7a70f026e..9191e710873 100644--- a/src/routes/(main)/agent/channel/platform/types.ts+++ b/src/routes/(main)/agent/channel/platform/types.ts@@ -1,3 +1,5 @@+export type { PlatformSettingsFieldExtrasProps } from '@/features/AgentSetting/AgentChannel/types';+export interface PlatformCredentialBodyProps {currentConfig?: {applicationId: string;diff --git a/src/services/agentBotProvider.ts b/src/services/agentBotProvider.tsindex c054d7c7fe9..5753cd433c1 100644--- a/src/services/agentBotProvider.ts+++ b/src/services/agentBotProvider.ts@@ -72,6 +72,14 @@ class AgentBotProviderService {return lambdaClient.agentBotProvider.lineFetchBotInfo.mutate({ channelAccessToken });};+ feishuFetchOwnerId = async (params: {+ appId: string;+ appSecret: string;+ platform: 'feishu' | 'lark';+ }) => {+ return lambdaClient.agentBotProvider.feishuFetchOwnerId.mutate(params);+ };+wechatGetQrCode = async () => {return lambdaClient.agentBotProvider.wechatGetQrCode.mutate();};diff --git a/src/store/agent/slices/bot/action.ts b/src/store/agent/slices/bot/action.tsindex 26ed4a62681..c7c025e107d 100644--- a/src/store/agent/slices/bot/action.ts+++ b/src/store/agent/slices/bot/action.ts@@ -59,6 +59,14 @@ export class BotSliceActionImpl {return agentBotProviderService.lineFetchBotInfo(channelAccessToken);};+ feishuFetchOwnerId = async (params: {+ appId: string;+ appSecret: string;+ platform: 'feishu' | 'lark';+ }) => {+ return agentBotProviderService.feishuFetchOwnerId(params);+ };+deleteAllBotProviders = async (agentId: string) => {const providers = await agentBotProviderService.getByAgentId(agentId);await Promise.all(providers.map((p) => agentBotProviderService.delete(p.id)));diff --git a/src/store/chat/utils/parseSpeakerTag.test.ts b/src/store/chat/utils/parseSpeakerTag.test.tsnew file mode 100644index 00000000000..a78370f3a43--- /dev/null+++ b/src/store/chat/utils/parseSpeakerTag.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { parseSpeakerTag } from './parseSpeakerTag';++describe('parseSpeakerTag', () => {+ it('returns undefined for plain content', () => {+ expect(parseSpeakerTag('hello')).toBeUndefined();+ expect(parseSpeakerTag('')).toBeUndefined();+ expect(parseSpeakerTag(null)).toBeUndefined();+ });++ it('ignores group-chat speaker tags without an id', () => {+ expect(parseSpeakerTag('<speaker name="Weather Expert" />\nhi')).toBeUndefined();+ });++ it('parses a Feishu style tag (name only)', () => {+ expect(parseSpeakerTag('<speaker id="ou_1" username="文彬" nickname="文彬" />\nhi')).toEqual({+ avatar: undefined,+ fullName: '文彬',+ id: 'ou_1',+ platform: 'unknown',+ username: undefined,+ });+ });++ it('resolves a Discord avatar hash against the CDN', () => {+ expect(+ parseSpeakerTag('<speaker id="123" username="john" nickname="John Doe" avatar="abc" />\nhi'),+ ).toEqual({+ avatar: 'https://cdn.discordapp.com/avatars/123/abc.png',+ fullName: 'John Doe',+ id: '123',+ platform: 'discord',+ username: 'john',+ });+ });++ it('keeps an absolute avatar url', () => {+ expect(parseSpeakerTag('<speaker id="u1" avatar="https://x/a.png" />\nhi')?.avatar).toBe(+ 'https://x/a.png',+ );+ });+});diff --git a/src/store/chat/utils/parseSpeakerTag.ts b/src/store/chat/utils/parseSpeakerTag.tsnew file mode 100644index 00000000000..09774b7c592--- /dev/null+++ b/src/store/chat/utils/parseSpeakerTag.ts@@ -0,0 +1,44 @@+import type { BotSenderMetadata } from '@lobechat/types';++/**+ * Matches the IM-bot speaker tag at the start of a user message:+ * `<speaker id="…" username="…" nickname="…" avatar="…" />`.+ * Group-chat tags (`<speaker name="…" />`) carry no `id` and are ignored.+ */+const SPEAKER_TAG_REGEX = /^<speaker\s([^>]*)\/>/;+const ATTR_REGEX = /(\w+)="([^"]*)"/g;++const DISCORD_CDN = 'https://cdn.discordapp.com';++/**+ * Recover the bot-channel sender from the `<speaker>` tag that older inbound+ * bot messages carry in their content (rows written before+ * `metadata.botSender` existed). Returns `undefined` for any other content.+ *+ * The tag has no platform attribute; a bare avatar hash is only ever produced+ * by Discord (`raw.author.avatar`), so it is resolved against the Discord CDN.+ */+export const parseSpeakerTag = (content?: string | null): BotSenderMetadata | undefined => {+ if (!content) return undefined;+ const match = SPEAKER_TAG_REGEX.exec(content);+ if (!match) return undefined;++ const attrs: Record<string, string> = {};+ for (const [, key, value] of match[1].matchAll(ATTR_REGEX)) attrs[key] = value;+ if (!attrs.id) return undefined;++ const isUrl = /^https?:\/\//.test(attrs.avatar ?? '');+ const avatar = !attrs.avatar+ ? undefined+ : isUrl+ ? attrs.avatar+ : `${DISCORD_CDN}/avatars/${attrs.id}/${attrs.avatar}.${attrs.avatar.startsWith('a_') ? 'gif' : 'png'}`;++ return {+ avatar,+ fullName: attrs.nickname || undefined,+ id: attrs.id,+ platform: isUrl || !attrs.avatar ? 'unknown' : 'discord',+ username: attrs.username && attrs.username !== attrs.nickname ? attrs.username : undefined,+ };+};