🤯 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
✨ feat(bot): let Feishu/Lark bots decide a reply acknowledgement (#22097)
Arvin Xua07301840e80
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.tsindex 9e95420c07e..1c89abf82d8 100644--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts@@ -279,7 +279,8 @@ export function registerHandlers(/*** How the bot opens a reply: an acknowledgement before the run, and the channel or a thread- * under the message, on any platform that offers the choice (`PlatformClient.getReplyTargets`).+ * under the message, on any platform that offers the choice (`PlatformClient.getReplyTargets`);+ * the acknowledgement alone on a threadless platform that opts in (`decidesReplyOpening`).* Decided by the bot only while the owner leaves the placement to it (see `./replyOpening`);* otherwise the previous behaviour.*/diff --git a/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.ts b/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.tsindex 0ec3970bc1b..07028f2bd9d 100644--- a/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.ts+++ b/apps/server/src/services/bot/BotMessageRouter/replyOpening.test.ts@@ -192,6 +192,37 @@ describe('createReplyOpening', () => {expect(result.verdict?.reason).toBe('channel:followup');});+ describe('on a platform without reply threads that lets the bot decide (Feishu)', () => {+ const FEISHU_CHAT = 'feishu:group:oc_1';+ const feishuClient = { decidesReplyOpening: true };++ it('decides the acknowledgement and answers where the message is', async () => {+ opener.mockResolvedValue({ ack: 'On it.', placement: 'channel' });+ const thread = makeThread(FEISHU_CHAT);+ const service = create({ client: feishuClient });++ await expect(service.decidesPlacement()).resolves.toBe(true);+ const result = await open(service, thread);++ expect(opener.mock.calls[0][0]).toMatchObject({ canOpenThread: false });+ expect(thread.id).toBe(FEISHU_CHAT);+ expect(thread.post).toHaveBeenCalledWith('On it.');+ expect(result.openingReply).toBe('On it.');+ expect(result.verdict?.reason).toBe('channel+ack');+ });++ it('stays where the message is when the model fails', async () => {+ opener.mockRejectedValue(new Error('provider down'));+ const thread = makeThread(FEISHU_CHAT);++ const result = await open(create({ client: feishuClient }), thread);++ expect(thread.id).toBe(FEISHU_CHAT);+ expect(thread.post).not.toHaveBeenCalled();+ expect(result.verdict?.reason).toBe('channel:fallback-error');+ });+ });+describe('on a platform whose message arrives keyed by the thread under it (Slack)', () => {const SLACK_THREAD = 'slack:C1:111.222';const openSlackThread = vi.fn(async () => SLACK_THREAD);diff --git a/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts b/apps/server/src/services/bot/BotMessageRouter/replyOpening.tsindex 0f2fd1c2340..833e9647f3a 100644--- a/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts+++ b/apps/server/src/services/bot/BotMessageRouter/replyOpening.ts@@ -86,7 +86,7 @@ export interface ReplyOpeningResult {export interface ReplyOpeningDeps {/** The bot's own platform id, so its earlier lines read as its own. */applicationId: string;- client: Pick<PlatformClient, 'getReplyTargets'>;+ client: Pick<PlatformClient, 'decidesReplyOpening' | 'getReplyTargets'>;/** The bot's wake switch (on unless `botWakeDisabled`): the bot decides only while it is on. */decides: boolean;/**@@ -146,6 +146,7 @@ const verdictOf = (* short model call: a quick answer stays in the channel, work that runs long moves into a thread* it names, and work that takes a while gets a one-sentence acknowledgement first. A wake nobody* asked for (`followup`) answers in the channel and never acknowledges: it may still end silent.+ * A platform without reply threads (`decidesReplyOpening`) only decides the acknowledgement.* - Otherwise, and whenever the model call fails, it behaves as before: a reply thread opens where* one used to, and nothing is posted before the run.*/@@ -154,7 +155,10 @@ export const createReplyOpening = (deps: ReplyOpeningDeps): ReplyOpeningServiceconst timeoutMs = deps.timeoutMs ?? REPLY_OPENER_TIMEOUT_MS;const decidesPlacement = async () =>- deps.decides && mode === 'agent' && !!opener && !!client.getReplyTargets;+ deps.decides &&+ mode === 'agent' &&+ !!opener &&+ (!!client.getReplyTargets || !!client.decidesReplyOpening);const moveTo = (thread: OpeningThread, platformThreadId: string) => {if (platformThreadId === thread.id) return;diff --git a/apps/server/src/services/bot/platforms/feishu/client.test.ts b/apps/server/src/services/bot/platforms/feishu/client.test.tsindex 848b289ce89..f8f59b728db 100644--- a/apps/server/src/services/bot/platforms/feishu/client.test.ts+++ b/apps/server/src/services/bot/platforms/feishu/client.test.ts@@ -57,6 +57,31 @@ vi.mock('./gateway', () => ({const { FeishuClientFactory, classifyLarkAuthError } = await import('./client');+describe('Feishu reply opening', () => {+ it.each([+ ['feishu', 'webhook'],+ ['feishu', 'websocket'],+ ['lark', 'webhook'],+ ['lark', 'websocket'],+ ] as const)(+ 'lets the bot decide its acknowledgement without reply threads (%s, %s)',+ (platform, connectionMode) => {+ const client = new FeishuClientFactory().createClient(+ {+ applicationId: 'cli_test_app',+ credentials: { appSecret: 'sec', encryptKey: 'enc' },+ platform,+ settings: { connectionMode },+ },+ { appUrl: 'https://example.com' },+ );++ expect(client.decidesReplyOpening).toBe(true);+ expect(client.getReplyTargets).toBeUndefined();+ },+ );+});+describe('FeishuWebhookClient.extractFiles', () => {// Verifies the post-Redis re-download path: when Feishu messages// round-trip through the chat-sdk debounce/queue, `Message.toJSON`diff --git a/apps/server/src/services/bot/platforms/feishu/client.ts b/apps/server/src/services/bot/platforms/feishu/client.tsindex 786fadfce51..b4729ce9a86 100644--- a/apps/server/src/services/bot/platforms/feishu/client.ts+++ b/apps/server/src/services/bot/platforms/feishu/client.ts@@ -362,6 +362,8 @@ async function resolveFeishuSenderName(class FeishuWebhookClient implements PlatformClient {readonly id: string;readonly applicationId: string;+ /** No reply threads here (a topic reply is not wired), but the bot still decides its acknowledgement. */+ readonly decidesReplyOpening = true;private config: BotProviderConfig;private domain: 'lark' | 'feishu';@@ -480,6 +482,8 @@ class FeishuWebhookClient implements PlatformClient {class FeishuWSClientImpl implements PlatformClient {readonly id: string;readonly applicationId: string;+ /** No reply threads here (a topic reply is not wired), but the bot still decides its acknowledgement. */+ readonly decidesReplyOpening = true;private config: BotProviderConfig;private context: BotPlatformRuntimeContext;diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.tsindex 6bb0da9dd9e..65ce38752b7 100644--- a/apps/server/src/services/bot/platforms/types.ts+++ b/apps/server/src/services/bot/platforms/types.ts@@ -302,6 +302,13 @@ export interface PlatformClient {/** Create a Chat SDK adapter config for inbound message handling. */createAdapter: () => Record<string, any>;+ /**+ * Whether the bot decides how it opens a reply (an acknowledgement before the run) on a platform+ * that offers no reply threads (no `getReplyTargets`): the reply always stays in+ * `platformThreadId`. A platform with `getReplyTargets` lets the bot decide without it.+ */+ readonly decidesReplyOpening?: boolean;+/*** Ensure the triggering user is a member of the platform thread the bot* replies in, so the platform pushes them a notification and surfaces the@@ -396,6 +403,8 @@ export interface PlatformClient {*/formatReply?: (body: string, stats?: UsageStats) => string;+ // --- Runtime Operations ---+/*** What people call the bot on this platform (display name, username), so a message that says the* name is read as addressed to it. Optional: without it the bot is recognised by @mention only.@@ -405,8 +414,6 @@ export interface PlatformClient {*/getBotNames?: (platformThreadId?: string) => Promise<string[]>;- // --- Runtime Operations ----/** Get a messenger for a specific thread (outbound messaging). */getMessenger: (platformThreadId: string) => PlatformMessenger;@@ -414,7 +421,8 @@ export interface PlatformClient {* Where the reply to `message` can go, when it sits at the top level of a channel that has* threads (see `ReplyTargets`). `undefined` when there is no choice: a DM, a message already* inside a thread, or a threadless platform (Telegram, WeChat, QQ). Omit when the platform never- * offers one; the reply then stays in `platformThreadId`.+ * offers one; the reply then stays in `platformThreadId`. Implementing it lets the bot decide how+ * it opens a reply (see `decidesReplyOpening`).*/getReplyTargets?: (platformThreadId: string,diff --git a/apps/server/src/services/bot/wake/__tests__/opener.test.ts b/apps/server/src/services/bot/wake/__tests__/opener.test.tsindex 8302b3d8cd8..2850d99d1bb 100644--- a/apps/server/src/services/bot/wake/__tests__/opener.test.ts+++ b/apps/server/src/services/bot/wake/__tests__/opener.test.ts@@ -33,7 +33,7 @@ describe('createReplyOpener', () => {const [payload, options] = mockGenerateObject.mock.calls[0];expect(options.tracing).toMatchObject({agentId: 'agt',- promptVersion: 'v1',+ promptVersion: 'v2',scenario: 'bot_reply_opener',schemaName: 'bot_reply_opener',});diff --git a/packages/prompts/src/chains/botReplyOpener.ts b/packages/prompts/src/chains/botReplyOpener.tsindex 17be35fd8ce..7c1537a21f8 100644--- a/packages/prompts/src/chains/botReplyOpener.ts+++ b/packages/prompts/src/chains/botReplyOpener.ts@@ -1,6 +1,6 @@import type { OpenAIChatMessage } from '@lobechat/types';-export const BOT_REPLY_OPENER_PROMPT_VERSION = 'v1';+export const BOT_REPLY_OPENER_PROMPT_VERSION = 'v2';export const BOT_REPLY_PLACEMENTS = ['channel', 'thread'] as const;export type BotReplyPlacement = (typeof BOT_REPLY_PLACEMENTS)[number];@@ -44,7 +44,7 @@ export interface BotReplyOpenerInput {agent?: { name?: string; title?: string };/** Names people call the assistant by in this chat. */botNames?: string[];- /** Whether the reply can move into a new thread; false in a DM or an existing thread. */+ /** Whether the reply can move into a new thread; false in a DM, an existing thread or a threadless platform. */canOpenThread: boolean;message: string;/** Short transcript of the messages just before this one, oldest first. */@@ -66,7 +66,7 @@ const buildState = (input: BotReplyOpenerInput): string => {sections.push(input.canOpenThread? 'You are in the main channel and may move the conversation into a new thread.'- : 'A thread is not available here: you are already in a thread or a direct message.',+ : 'A thread is not available here: you answer where the message was sent.',);if (input.recentMessages?.length) {sections.push(`Earlier messages (oldest first):\n${input.recentMessages.join('\n')}`);diff --git a/packages/prompts/src/chains/generationContracts.test.ts b/packages/prompts/src/chains/generationContracts.test.tsindex 7736c3992a8..57205ea11f7 100644--- a/packages/prompts/src/chains/generationContracts.test.ts+++ b/packages/prompts/src/chains/generationContracts.test.ts@@ -91,7 +91,7 @@ describe('application generation chains', () => {recentMessages: ['alice: deploy failed again'],});- expect(BOT_REPLY_OPENER_PROMPT_VERSION).toBe('v1');+ expect(BOT_REPLY_OPENER_PROMPT_VERSION).toBe('v2');expect(BOT_REPLY_OPENER_JSON_SCHEMA.name).toBe('bot_reply_opener');expect(BOT_REPLY_OPENER_JSON_SCHEMA.schema.required).toEqual(['acknowledge',@@ -116,6 +116,8 @@ describe('application generation chains', () => {const { messages } = chainBotReplyOpener({ canOpenThread: false, message: 'hi' });expect(messages[1].content).toContain('A thread is not available here');+ // A threadless platform's group chat is neither a thread nor a DM.+ expect(messages[1].content).not.toContain('direct message');expect(messages[1].content).not.toContain('may move the conversation');});