Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

๐Ÿ› fix(bot): read Feishu chat history and decode WeChat voice (#19323)

Rdmclin2d3c25f2a95d4
diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.ts
index 2db6b69e82f..72961993b58 100644
--- a/apps/server/src/services/bot/AgentBridgeService.ts
+++ b/apps/server/src/services/bot/AgentBridgeService.ts
@@ -147,6 +147,40 @@ interface DiscordChannelContext {
thread?: { id: string; name?: string };
}
+/**
+ * Resolve the `{ platform, channelId }` pair the `lobe-message` tool needs to
+ * act on the conversation this run is replying in.
+ *
+ * `PlatformClient.extractChatId` is the decoder each platform already uses for
+ * its own outbound calls, so what it returns is by construction what that
+ * platform's message service accepts as `channelId` โ€” Feishu/Lark `oc_โ€ฆ`,
+ * Discord channel-or-thread id, Telegram chat id. A platform whose history
+ * read cannot be scoped that precisely (a Slack reply thread decodes to its
+ * parent channel) overrides `extractConversationId` and returns undefined, and
+ * the block is omitted rather than pointing the model at the wrong history.
+ *
+ * Returns undefined when we have no bot context or no client (e.g. a run that
+ * didn't originate from an IM thread) โ€” the prompt block is then simply omitted.
+ */
+function resolveCurrentChannel(
+ botContext: ChatTopicBotContext | undefined,
+ client: PlatformClient | undefined,
+): { id: string; platformId: string } | undefined {
+ if (!botContext?.platformThreadId || !client) return undefined;
+ try {
+ const id = client.extractConversationId
+ ? client.extractConversationId(botContext.platformThreadId)
+ : client.extractChatId(botContext.platformThreadId);
+ if (!id) return undefined;
+ return { id, platformId: botContext.platform };
+ } catch (error) {
+ // A malformed/legacy threadId must never break the run โ€” the model just
+ // loses the shortcut and falls back to asking, which is today's behavior.
+ log('resolveCurrentChannel: failed to extract chat id (non-fatal): %O', error);
+ return undefined;
+ }
+}
+
interface ThreadState {
channelContext?: DiscordChannelContext;
/**
@@ -756,9 +790,18 @@ export class AgentBridgeService {
opts.botContext?.platform,
opts.botContext?.platformThreadId,
)?.includes(MessageApiName.readMessages);
+ // The `channelId` the model must pass to `lobe-message` to act on THIS
+ // conversation. `extractChatId` is the same decoder each platform client
+ // already uses for its own outbound calls, so the injected value is exactly
+ // what the message service expects (Feishu `oc_โ€ฆ`, Discord channel/thread
+ // id, Slack channel id). Without it `readMessages` โ€” whose `channelId` is
+ // required, and which most platforms have no `listChannels` to discover โ€”
+ // is unusable, and the model falls back to asking the user for a group ID.
+ const currentChannel = resolveCurrentChannel(opts.botContext, opts.client);
const botPlatformContext: BotPlatformContext | undefined = platformDef
? {
canReadHistory,
+ ...(currentChannel && { currentChannel }),
platformName: platformDef.name,
supportsMarkdown: platformDef.supportsMarkdown !== false,
}
diff --git a/apps/server/src/services/bot/BotMessageRouter.ts b/apps/server/src/services/bot/BotMessageRouter.ts
index 0761c70137b..a50aca88b47 100644
--- a/apps/server/src/services/bot/BotMessageRouter.ts
+++ b/apps/server/src/services/bot/BotMessageRouter.ts
@@ -1325,18 +1325,40 @@ export class BotMessageRouter {
// type `/new` directly without mentioning the bot), but they are NOT exempt
// from the access gates below.
//
- // a subscribed channel thread with only one human follower
- // is functionally a private 1:1 with the bot, so the @mention
- // requirement is dropped while `count <= 1`. Tracked + counted here
- // regardless of which exemption ultimately fires so the
- // 1-human-vs-many transition is visible to the announcement gate.
+ // A conversation holding only the operator and this bot is a private 1:1
+ // in all but name, so the @mention requirement is dropped there. Ask the
+ // platform when it can answer from real membership; only fall back to
+ // "how many distinct humans have SPOKEN here" when it can't.
+ //
+ // That fallback is a poor proxy and must not be trusted where the
+ // subscribed thread is an entire group chat: silent members are never
+ // counted, so a quiet 30-person group reads as private and the bot
+ // answers everything the one talkative person says โ€” including messages
+ // @-ing a different bot. It survives only for platforms whose subscribed
+ // threads really are narrow sub-conversations (Discord/Slack), where
+ // speakers and participants are close to the same set.
+ //
+ // 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 isSingleHumanThread = humanCount <= 1;
- const isAddressedToBot =
+ const isExplicitlyAddressed =
thread.isDM ||
message.isMention === true ||
- context?.skipped?.some((m) => m.isMention === true) === true ||
- isSingleHumanThread;
+ 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
+ // cache has lapsed โ€” not something a direct message should wait on.
+ const isSoloBotConversation =
+ !isExplicitlyAddressed &&
+ (client.isSoloBotConversation
+ ? await client.isSoloBotConversation(thread.id).catch((error) => {
+ // Fail closed: an unprovable chat stays mention-only.
+ log('onSubscribedMessage: isSoloBotConversation failed: %O', error);
+ return false;
+ })
+ : humanCount <= 1);
+ const isAddressedToBot = isExplicitlyAddressed || isSoloBotConversation;
const isCommand = looksLikeCommand(message.text);
// operator-configured keyword match also wakes the bot in a
// subscribed group thread. Skipped (debounced) siblings are inspected
diff --git a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts b/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
index ac0efdf43ae..b383df41b11 100644
--- a/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
+++ b/apps/server/src/services/bot/__tests__/AgentBridgeService.test.ts
@@ -204,6 +204,74 @@ describe('AgentBridgeService', () => {
expect(mockExecAgent.mock.calls[0][0].toolModeOverride).toBeUndefined();
});
+ describe('current-conversation injection (LOBE-13803)', () => {
+ it('injects the platform + channelId the message tool needs into botPlatformContext', async () => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread();
+ const message = createMessage();
+ const client = createClient();
+ // Feishu/Lark threadIds are `lark:group:oc_xxx`; the client's own decoder
+ // is what turns that into the `oc_xxx` the message service accepts.
+ client.extractChatId.mockReturnValue('oc_chat_1');
+ mockGetPlatform.mockReturnValue({ id: 'lark', name: 'Lark', supportsMessageEdit: true });
+
+ await service.handleMention(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platform: 'lark', platformThreadId: 'lark:group:oc_chat_1' } as any,
+ client,
+ });
+
+ expect(client.extractChatId).toHaveBeenCalledWith('lark:group:oc_chat_1');
+ expect(mockExecAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ botPlatformContext: expect.objectContaining({
+ currentChannel: { id: 'oc_chat_1', platformId: 'lark' },
+ }),
+ }),
+ );
+ });
+
+ it('prefers extractConversationId, so a platform can decline for an unscopable thread', async () => {
+ // Slack: `slack:C1:1700.1` is a reply thread, but readMessages can only
+ // read the channel โ€” advertising `C1` as "this conversation" would be a lie.
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const client = createClient() as any;
+ client.extractChatId.mockReturnValue('C1');
+ client.extractConversationId = vi.fn().mockReturnValue(undefined);
+ mockGetPlatform.mockReturnValue({ id: 'slack', name: 'Slack', supportsMessageEdit: true });
+
+ await service.handleMention(createThread(), createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platform: 'slack', platformThreadId: 'slack:C1:1700.1' } as any,
+ client,
+ });
+
+ expect(client.extractConversationId).toHaveBeenCalledWith('slack:C1:1700.1');
+ expect(mockExecAgent.mock.calls[0][0].botPlatformContext.currentChannel).toBeUndefined();
+ });
+
+ it('omits currentChannel when the platform client cannot decode the threadId', async () => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread();
+ const message = createMessage();
+ const client = createClient();
+ client.extractChatId.mockImplementation(() => {
+ throw new Error('malformed threadId');
+ });
+ mockGetPlatform.mockReturnValue({ id: 'lark', name: 'Lark', supportsMessageEdit: true });
+
+ await service.handleMention(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platform: 'lark', platformThreadId: 'garbage' } as any,
+ client,
+ });
+
+ // The run still completes โ€” losing the shortcut must never break the reply.
+ expect(mockExecAgent).toHaveBeenCalled();
+ expect(mockExecAgent.mock.calls[0][0].botPlatformContext.currentChannel).toBeUndefined();
+ });
+ });
+
it('constructs AiAgentService with workspaceId for workspace bot runs', async () => {
const service = new AgentBridgeService(FAKE_DB, USER_ID, 'workspace-1');
const thread = createThread();
diff --git a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts b/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts
index 6cd4a37d53f..c2702550807 100644
--- a/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts
+++ b/apps/server/src/services/bot/__tests__/BotMessageRouter.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BotMessageRouter } from '../BotMessageRouter';
@@ -954,6 +954,68 @@ describe('BotMessageRouter', () => {
expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
});
+ describe('platform-reported membership (isSoloBotConversation)', () => {
+ const defaultGetPlatform = mockGetPlatform.getMockImplementation()!;
+ afterEach(() => {
+ mockGetPlatform.mockImplementation(defaultGetPlatform);
+ });
+
+ /** Same client as the default factory, plus a membership lookup. */
+ function withMembershipLookup(isSoloBotConversation: ReturnType<typeof vi.fn>) {
+ // Persistent, not `Once`: the router resolves the platform more than
+ // once between registration and the first handled message.
+ mockGetPlatform.mockImplementation((platform: string) => {
+ const def = defaultGetPlatform(platform);
+ if (!def) return def;
+ const client = def.clientFactory.createClient();
+ return {
+ ...def,
+ clientFactory: {
+ createClient: vi.fn().mockReturnValue({ ...client, isSoloBotConversation }),
+ },
+ };
+ });
+ }
+
+ it('does not look up membership for a DM โ€” the answer cannot change', async () => {
+ // A lapsed cache would otherwise put a platform round-trip in front of
+ // every direct message.
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+
+ await handler(makeThread({ isDM: true }), makeMessage({ isMention: false, text: 'hi' }));
+
+ expect(isSoloBotConversation).not.toHaveBeenCalled();
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not look up membership for an @mention either', async () => {
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+
+ await handler(makeThread(), makeMessage({ isMention: true, text: '@bot hi' }));
+
+ expect(isSoloBotConversation).not.toHaveBeenCalled();
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('trusts membership over the speaker count for an unmentioned group message', async () => {
+ // Only one human has ever SPOKEN here (the old heuristic would let it
+ // through), but the platform says the chat is not 1:1 with the bot.
+ mockGetList.mockResolvedValue([]);
+ const isSoloBotConversation = vi.fn().mockResolvedValue(false);
+ withMembershipLookup(isSoloBotConversation);
+ const handler = await loadSubscribedHandler();
+
+ await handler(makeThread(), makeMessage({ isMention: false, text: 'just chatting' }));
+
+ expect(isSoloBotConversation).toHaveBeenCalledWith('telegram:chat-1');
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+ });
+
it('should respond when a debounced/skipped earlier message contained the mention', async () => {
const handler = await loadSubscribedHandler();
const thread = makeThread({ isDM: false });
diff --git a/apps/server/src/services/bot/platforms/feishu/boundedMemoryCache.ts b/apps/server/src/services/bot/platforms/feishu/boundedMemoryCache.ts
new file mode 100644
index 00000000000..e0c08b7277e
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/feishu/boundedMemoryCache.ts
@@ -0,0 +1,49 @@
+/**
+ * Process-local, TTL'd, size-bounded key/value cache.
+ *
+ * The Feishu bot helpers keep small pieces of per-chat / per-message state
+ * (`chatComposition`, `reactionTracker`) in agent-runtime Redis, because
+ * queue-mode callbacks land in a different process from the one that wrote
+ * the state. Deployments without that Redis (local / single-process) still
+ * need the state to survive between calls in the same process โ€” otherwise
+ * every inbound message costs a Feishu round-trip, or every reaction step
+ * stacks instead of swapping. This is that fallback: bounded so an app
+ * subscribed to many chats cannot grow it without limit, and expiring on the
+ * same TTLs the Redis keys use.
+ */
+export interface BoundedMemoryCache<T> {
+ clear: () => void;
+ delete: (key: string) => void;
+ get: (key: string) => T | undefined;
+ set: (key: string, value: T, ttlSeconds: number) => void;
+}
+
+export const createBoundedMemoryCache = <T>(maxEntries: number): BoundedMemoryCache<T> => {
+ const entries = new Map<string, { expiresAt: number; value: T }>();
+
+ return {
+ clear: () => entries.clear(),
+ delete: (key) => {
+ entries.delete(key);
+ },
+ get: (key) => {
+ const entry = entries.get(key);
+ if (!entry) return undefined;
+ if (entry.expiresAt <= Date.now()) {
+ entries.delete(key);
+ return undefined;
+ }
+ return entry.value;
+ },
+ set: (key, value, ttlSeconds) => {
+ // Re-inserting moves the key to the end, so insertion order doubles as
+ // "least recently written" and the first key is the eviction candidate.
+ entries.delete(key);
+ if (entries.size >= maxEntries) {
+ const oldest = entries.keys().next().value;
+ if (oldest !== undefined) entries.delete(oldest);
+ }
+ entries.set(key, { expiresAt: Date.now() + ttlSeconds * 1000, value });
+ },
+ };
+};
diff --git a/apps/server/src/services/bot/platforms/feishu/chatComposition.test.ts b/apps/server/src/services/bot/platforms/feishu/chatComposition.test.ts
new file mode 100644
index 00000000000..35d053ab265
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/feishu/chatComposition.test.ts
@@ -0,0 +1,141 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ redisAvailable: true,
+ set: vi.fn(),
+ store: new Map<string, string>(),
+}));
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () =>
+ mocks.redisAvailable
+ ? {
+ del: async (key: string) => mocks.store.delete(key),
+ 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 { clearChatCompositionMemoryCache, isSoloBotChat } = await import('./chatComposition');
+
+const makeApi = (getChatInfo: ReturnType<typeof vi.fn>) => ({ getChatInfo }) as any;
+
+describe('isSoloBotChat', () => {
+ beforeEach(() => {
+ mocks.redisAvailable = true;
+ mocks.store.clear();
+ mocks.set.mockClear();
+ clearChatCompositionMemoryCache();
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it('treats one user + one bot as the bot private conversation', async () => {
+ // Feishu reports both counts as strings.
+ const getChatInfo = vi.fn().mockResolvedValue({ bot_count: '1', user_count: '1' });
+
+ await expect(isSoloBotChat(makeApi(getChatInfo), 'cli_app', 'oc_1')).resolves.toBe(true);
+ });
+
+ it('requires an @mention once a second human is a MEMBER, even if they never spoke', async () => {
+ // The regression: the old speaker-count heuristic read this group as
+ // private because only one of the two members had ever talked.
+ const getChatInfo = vi.fn().mockResolvedValue({ bot_count: '1', user_count: '2' });
+
+ await expect(isSoloBotChat(makeApi(getChatInfo), 'cli_app', 'oc_1')).resolves.toBe(false);
+ });
+
+ it('requires an @mention when another bot is in the chat', async () => {
+ // One human, two bots โ€” a message @-ing the other bot must not wake this one.
+ const getChatInfo = vi.fn().mockResolvedValue({ bot_count: '2', user_count: '1' });
+
+ await expect(isSoloBotChat(makeApi(getChatInfo), 'cli_app', 'oc_1')).resolves.toBe(false);
+ });
+
+ it('fails closed when the chat cannot be inspected', async () => {
+ // e.g. the app lacks `im:chat:readonly`. Staying quiet beats talking over a group.
+ const getChatInfo = vi.fn().mockRejectedValue(new Error('230027 Permission denied'));
+
+ await expect(isSoloBotChat(makeApi(getChatInfo), 'cli_app', 'oc_1')).resolves.toBe(false);
+ });
+
+ it('caches the verdict instead of asking once per inbound message', async () => {
+ const getChatInfo = vi.fn().mockResolvedValue({ bot_count: '1', user_count: '1' });
+ const api = makeApi(getChatInfo);
+
+ await isSoloBotChat(api, 'cli_app', 'oc_1');
+ await isSoloBotChat(api, 'cli_app', 'oc_1');
+
+ expect(getChatInfo).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds a solo verdict far shorter than a shared one, so a newly joined member is noticed', async () => {
+ // A stale "solo" keeps the bot answering every message after someone joins;
+ // a stale "shared" only delays dropping the @mention requirement.
+ const api = makeApi(
+ vi
+ .fn()
+ .mockResolvedValueOnce({ bot_count: '1', user_count: '1' })
+ .mockResolvedValueOnce({ bot_count: '1', user_count: '3' }),
+ );
+
+ await isSoloBotChat(api, 'cli_app', 'oc_solo');
+ await isSoloBotChat(api, 'cli_app', 'oc_team');
+
+ const ttlOf = (chatId: string) =>
+ mocks.set.mock.calls.find(([key]) => String(key).endsWith(chatId))!.at(-1);
+ expect(ttlOf('oc_solo')).toBeLessThan(ttlOf('oc_team'));
+ expect(ttlOf('oc_solo')).toBeLessThanOrEqual(60);
+ });
+
+ it('keys the cache per chat, so one group does not answer for another', async () => {
+ const getChatInfo = vi
+ .fn()
+ .mockResolvedValueOnce({ bot_count: '1', user_count: '1' })
+ .mockResolvedValueOnce({ bot_count: '1', user_count: '5' });
+ const api = makeApi(getChatInfo);
+
+ await expect(isSoloBotChat(api, 'cli_app', 'oc_solo')).resolves.toBe(true);
+ await expect(isSoloBotChat(api, 'cli_app', 'oc_team')).resolves.toBe(false);
+ });
+
+ describe('without Redis', () => {
+ beforeEach(() => {
+ mocks.redisAvailable = false;
+ });
+
+ it('still answers from the real composition rather than refusing outright', async () => {
+ const getChatInfo = vi.fn().mockResolvedValue({ bot_count: '1', user_count: '1' });
+
+ await expect(isSoloBotChat(makeApi(getChatInfo), 'cli_app', 'oc_1')).resolves.toBe(true);
+ });
+
+ it('caches in process memory instead of one Feishu request per inbound message', async () => {
+ const getChatInfo = vi.fn().mockResolvedValue({ bot_count: '1', user_count: '4' });
+ const api = makeApi(getChatInfo);
+
+ await isSoloBotChat(api, 'cli_app', 'oc_1');
+ await isSoloBotChat(api, 'cli_app', 'oc_1');
+ await isSoloBotChat(api, 'cli_app', 'oc_1');
+
+ expect(getChatInfo).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-checks a solo verdict once its short TTL has elapsed', async () => {
+ vi.useFakeTimers();
+ const getChatInfo = vi
+ .fn()
+ .mockResolvedValueOnce({ bot_count: '1', user_count: '1' })
+ .mockResolvedValueOnce({ bot_count: '1', user_count: '2' });
+ const api = makeApi(getChatInfo);
+
+ await expect(isSoloBotChat(api, 'cli_app', 'oc_1')).resolves.toBe(true);
+ vi.advanceTimersByTime(61 * 1000);
+ await expect(isSoloBotChat(api, 'cli_app', 'oc_1')).resolves.toBe(false);
+ expect(getChatInfo).toHaveBeenCalledTimes(2);
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/feishu/chatComposition.ts b/apps/server/src/services/bot/platforms/feishu/chatComposition.ts
new file mode 100644
index 00000000000..ccf6b21dd90
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/feishu/chatComposition.ts
@@ -0,0 +1,117 @@
+import type { LarkApiClient } from '@lobechat/chat-adapter-feishu';
+import debug from 'debug';
+
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+import { createBoundedMemoryCache } from './boundedMemoryCache';
+
+const log = debug('bot-platform:feishu:chat-composition');
+
+/**
+ * Is this Feishu/Lark chat just the operator and this bot?
+ *
+ * The router drops the @-mention requirement for a conversation that is
+ * effectively 1:1 with the bot. It used to infer that from how many distinct
+ * humans had *spoken* in the thread, which is a bad proxy on Feishu: a
+ * subscribed "thread" there is the whole group chat, and a silent member is
+ * never counted โ€” so a 30-person group where only one person had talked read as
+ * private, and the bot answered everything that person said, including messages
+ * @-ing a different bot.
+ *
+ * `GET /im/v1/chats/{chat_id}` reports the real composition: `user_count`
+ * (็พคๅ†…็”จๆˆท็š„ๆ•ฐ้‡) and `bot_count` (็พคๅ†…ๆœบๅ™จไบบ็š„ๆ•ฐ้‡). Exactly one of each means
+ * the operator and this bot, and nobody else.
+ *
+ * Fails CLOSED: any error or missing field resolves to `false`, which means
+ * "require an @-mention". Staying quiet when we cannot prove the chat is
+ * private is the safe direction โ€” the opposite mistake is the bot talking over
+ * a group.
+ */
+
+/**
+ * A "solo" verdict is the dangerous one to hold stale: the moment a second
+ * human or bot joins, every unmentioned message would still wake the bot until
+ * the entry expires. No membership event invalidates the key, so keep positive
+ * verdicts short โ€” one minute bounds how long a freshly-shared group can be
+ * hijacked, while still collapsing a burst of DMs into one API call.
+ */
+const SOLO_TTL_SECONDS = 60;
+/** A shared group going back to 1:1 is rare and harmless to notice late. */
+const SHARED_TTL_SECONDS = 10 * 60;
+
+const buildKey = (applicationId: string, chatId: string): string =>
+ `bot:feishu-chat-solo:${applicationId}:${chatId}`;
+
+/**
+ * Process-local fallback for deployments without agent-runtime Redis, so the
+ * verdict is still cached instead of costing one blocking Feishu request per
+ * inbound message (including chatter the bot goes on to ignore). Entries
+ * expire on the same TTLs as Redis.
+ */
+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 clearChatCompositionMemoryCache = (): void => memoryCache.clear();
+
+/** Feishu returns the counts as strings (`"bot_count": "3"`). */
+const toCount = (value: unknown): number | undefined => {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : undefined;
+};
+
+export async function isSoloBotChat(
+ api: LarkApiClient,
+ applicationId: string,
+ chatId: string,
+): Promise<boolean> {
+ // Consulted on every inbound group message โ€” cache it rather than spending
+ // an API round-trip per message. Redis when available (queue-mode callbacks
+ // land in other processes), process memory otherwise.
+ const redis = getAgentRuntimeRedisClient();
+ const key = buildKey(applicationId, chatId);
+ if (redis) {
+ try {
+ const cached = await redis.get(key);
+ if (cached === '1') return true;
+ if (cached === '0') return false;
+ } catch (error) {
+ log('isSoloBotChat: cache read failed: %O', error);
+ }
+ } else {
+ const cached = memoryCache.get(key);
+ if (cached !== undefined) return cached;
+ }
+
+ let solo: boolean;
+ try {
+ const chat = await api.getChatInfo(chatId);
+ const userCount = toCount(chat?.user_count);
+ const botCount = toCount(chat?.bot_count);
+ solo = userCount === 1 && botCount === 1;
+ log(
+ 'isSoloBotChat: chat=%s users=%o bots=%o solo=%s',
+ chatId,
+ chat?.user_count,
+ chat?.bot_count,
+ solo,
+ );
+ } catch (error) {
+ // Reading chat info needs one of `im:chat` / `im:chat:read` /
+ // `im:chat:readonly`. Without it every group simply stays mention-only.
+ log('isSoloBotChat: getChatInfo failed, treating as a shared group: %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('isSoloBotChat: cache write failed: %O', error);
+ }
+ } else {
+ memoryCache.set(key, solo, ttlSeconds);
+ }
+ return solo;
+}
diff --git a/apps/server/src/services/bot/platforms/feishu/client.test.ts b/apps/server/src/services/bot/platforms/feishu/client.test.ts
index f4c0c4dc825..3b7f859d706 100644
--- a/apps/server/src/services/bot/platforms/feishu/client.test.ts
+++ b/apps/server/src/services/bot/platforms/feishu/client.test.ts
@@ -1,17 +1,36 @@
+import type * as FeishuAdapterModule from '@lobechat/chat-adapter-feishu';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mockCreateLarkAdapter = vi.hoisted(() => vi.fn());
const mockDownloadMediaFromRawMessage = vi.hoisted(() => vi.fn());
const mockGetTenantAccessToken = vi.hoisted(() => vi.fn().mockResolvedValue('tok'));
+const mockAddReaction = vi.hoisted(() => vi.fn());
+const mockRemoveReaction = vi.hoisted(() => vi.fn());
-vi.mock('@lobechat/chat-adapter-feishu', () => ({
+vi.mock('@lobechat/chat-adapter-feishu', async (importOriginal) => ({
+ // Keep the real `decodeLarkThreadId` โ€” the messenger decodes the threadId
+ // before it ever touches the API, so stubbing it would test nothing.
+ ...(await importOriginal<typeof FeishuAdapterModule>()),
createLarkAdapter: mockCreateLarkAdapter,
downloadMediaFromRawMessage: mockDownloadMediaFromRawMessage,
LarkApiClient: vi.fn().mockImplementation(() => ({
+ addReaction: mockAddReaction,
getTenantAccessToken: mockGetTenantAccessToken,
+ removeReaction: mockRemoveReaction,
})),
}));
+// Keep `./reactionTracker` real โ€” the key layout and the read-before-write
+// ordering are exactly what the stacking fix depends on.
+const reactionStore = vi.hoisted(() => new Map<string, string>());
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => ({
+ del: async (key: string) => reactionStore.delete(key),
+ get: async (key: string) => reactionStore.get(key) ?? null,
+ set: async (key: string, value: string) => reactionStore.set(key, value),
+ }),
+}));
+
vi.mock('@/server/services/gateway/runtimeStatus', () => ({
BOT_RUNTIME_STATUSES: {
connected: 'connected',
@@ -196,3 +215,148 @@ describe('FeishuWebhookClient.extractFiles', () => {
]);
});
});
+
+describe('Feishu messenger reactions', () => {
+ const messenger = (platform: 'feishu' | 'lark' = 'lark') =>
+ new FeishuClientFactory()
+ .createClient(
+ {
+ applicationId: 'cli_test_app',
+ credentials: { appSecret: 'sec', encryptKey: 'enc' },
+ platform,
+ settings: {},
+ },
+ {},
+ )
+ .getMessenger(`${platform}:group:oc_chat_1`);
+
+ beforeEach(async () => {
+ reactionStore.clear();
+ mockAddReaction.mockReset().mockResolvedValue({ reactionId: 'rct_1' });
+ mockRemoveReaction.mockReset().mockResolvedValue(undefined);
+ // The suite above ends on `vi.restoreAllMocks()`, which strips the module
+ // factory's constructor implementation โ€” re-establish it here rather than
+ // depending on describe ordering.
+ const { LarkApiClient } = await import('@lobechat/chat-adapter-feishu');
+ vi.mocked(LarkApiClient).mockImplementation(
+ () =>
+ ({
+ addReaction: mockAddReaction,
+ getTenantAccessToken: mockGetTenantAccessToken,
+ removeReaction: mockRemoveReaction,
+ }) as any,
+ );
+ });
+
+ it('sends the named emoji_type Feishu accepts, not the bridge unicode', async () => {
+ // '\u{1F440}' straight through is what returns `231001 reaction type is invalid`.
+ await messenger().replaceReaction!('om_1', null, '\u{1F440}');
+
+ expect(mockAddReaction).toHaveBeenCalledWith('om_1', 'OK');
+ });
+
+ it('removes the previous reaction on a step swap instead of stacking a second one', async () => {
+ const m = messenger();
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_received' });
+ await m.replaceReaction!('om_1', null, '\u{1F440}');
+
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_thinking' });
+ await m.replaceReaction!('om_1', '\u{1F440}', '\u{1F914}');
+
+ // Add first, then drop the old one โ€” the user always sees one reaction.
+ expect(mockAddReaction).toHaveBeenLastCalledWith('om_1', 'THINKING');
+ expect(mockRemoveReaction).toHaveBeenCalledWith('om_1', 'rct_received');
+ });
+
+ it('clears the last reaction when the run finishes', async () => {
+ const m = messenger();
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_working' });
+ await m.replaceReaction!('om_1', null, '\u{26A1}');
+
+ await m.replaceReaction!('om_1', '\u{26A1}', null);
+
+ expect(mockRemoveReaction).toHaveBeenCalledWith('om_1', 'rct_working');
+ // โ€ฆand the pointer is gone, so a later clear can't double-delete.
+ expect([...reactionStore.keys()]).toHaveLength(0);
+ });
+
+ it('skips the swap when both emoji map to the same emoji_type', async () => {
+ // '\u{1F44C}' and '\u{1F440}' both resolve to OK โ€” re-placing it would swap a
+ // live reaction for an identical one.
+ await messenger().replaceReaction!('om_1', '\u{1F44C}', '\u{1F440}');
+
+ expect(mockAddReaction).not.toHaveBeenCalled();
+ expect(mockRemoveReaction).not.toHaveBeenCalled();
+ });
+
+ it('retries a transient failure of the final clear in place', async () => {
+ // Nothing upstream retries the clear (the bridge and the queue callback
+ // both drop their reaction state afterwards), so the messenger must.
+ const m = messenger();
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_working' });
+ await m.replaceReaction!('om_1', null, '\u{26A1}');
+
+ mockRemoveReaction.mockRejectedValueOnce(new Error('network'));
+ await m.replaceReaction!('om_1', '\u{26A1}', null);
+
+ expect(mockRemoveReaction).toHaveBeenCalledTimes(2);
+ expect([...reactionStore.keys()]).toHaveLength(0);
+ });
+
+ it('keeps the id when the final clear keeps failing, so a later cleanup can still use it', async () => {
+ const m = messenger();
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_working' });
+ await m.replaceReaction!('om_1', null, '\u{26A1}');
+
+ // Forgetting the id BEFORE the delete succeeds would leave the reaction
+ // visible with nothing left to delete it by.
+ mockRemoveReaction
+ .mockRejectedValueOnce(new Error('network'))
+ .mockRejectedValueOnce(new Error('network'))
+ .mockRejectedValueOnce(new Error('network'));
+ await expect(m.replaceReaction!('om_1', '\u{26A1}', null)).rejects.toThrow('could not remove');
+ expect([...reactionStore.values()]).toEqual([JSON.stringify(['rct_working'])]);
+
+ await m.removeReaction!('om_1', '\u{26A1}');
+ expect(mockRemoveReaction).toHaveBeenLastCalledWith('om_1', 'rct_working');
+ expect([...reactionStore.keys()]).toHaveLength(0);
+ });
+
+ it('keeps the previous id when a swap adds fine but cannot remove it, and clears both later', async () => {
+ const m = messenger();
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_received' });
+ await m.replaceReaction!('om_1', null, '\u{1F440}');
+
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_thinking' });
+ mockRemoveReaction
+ .mockRejectedValueOnce(new Error('network'))
+ .mockRejectedValueOnce(new Error('network'))
+ .mockRejectedValueOnce(new Error('network'));
+ await expect(m.replaceReaction!('om_1', '\u{1F440}', '\u{1F914}')).rejects.toThrow(
+ 'could not remove',
+ );
+ // Both ids survive: the one that could not be removed and the one just placed.
+ expect([...reactionStore.values()]).toEqual([JSON.stringify(['rct_received', 'rct_thinking'])]);
+
+ mockRemoveReaction.mockClear();
+ await m.replaceReaction!('om_1', '\u{1F914}', null);
+ expect(mockRemoveReaction.mock.calls.map(([, id]) => id)).toEqual([
+ 'rct_received',
+ 'rct_thinking',
+ ]);
+ expect([...reactionStore.keys()]).toHaveLength(0);
+ });
+
+ it('keeps the stale pointer when the add fails, so the next swap retries cleanup', async () => {
+ const m = messenger();
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_received' });
+ await m.replaceReaction!('om_1', null, '\u{1F440}');
+
+ mockAddReaction.mockRejectedValueOnce(new Error('network'));
+ await expect(m.replaceReaction!('om_1', '\u{1F440}', '\u{1F914}')).rejects.toThrow('network');
+
+ mockAddReaction.mockResolvedValueOnce({ reactionId: 'rct_thinking' });
+ await m.replaceReaction!('om_1', '\u{1F440}', '\u{1F914}');
+ expect(mockRemoveReaction).toHaveBeenCalledWith('om_1', 'rct_received');
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/feishu/client.ts b/apps/server/src/services/bot/platforms/feishu/client.ts
index 69b4227ecb7..040dc1a1acc 100644
--- a/apps/server/src/services/bot/platforms/feishu/client.ts
+++ b/apps/server/src/services/bot/platforms/feishu/client.ts
@@ -4,6 +4,7 @@ import {
downloadMediaFromRawMessage,
LarkApiClient,
type LarkRawMessage,
+ toFeishuEmojiType,
} from '@lobechat/chat-adapter-feishu';
import type { Chat as ChatBot, Message } from 'chat';
import debug from 'debug';
@@ -27,7 +28,9 @@ import {
type ValidationResult,
} from '../types';
import { formatUsageStats } from '../utils';
+import { isSoloBotChat } from './chatComposition';
import { FeishuWSConnection } from './gateway';
+import { readReactionIds, writeReactionIds } from './reactionTracker';
import { sendFeishuAttachments } from './sendAttachments';
const log = debug('bot-platform:feishu:client');
@@ -55,6 +58,53 @@ function resolveDomain(platform: string): 'lark' | 'feishu' {
// ---------- Shared runtime operations ----------
+/**
+ * Reaction removal is the one step nothing retries for us: the bridge and the
+ * queue callback both drop their own reaction state after the final clear,
+ * whether or not it succeeded. So a transient Feishu/network failure here is
+ * retried in place before the leftover id is handed back to the tracker.
+ */
+const REMOVE_REACTION_ATTEMPTS = 3;
+const REMOVE_REACTION_RETRY_DELAY_MS = 250;
+
+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+/** Remove one reaction, retrying transient failures. Resolves whether it is gone. */
+async function removeReactionWithRetry(
+ api: LarkApiClient,
+ messageId: string,
+ reactionId: string,
+): Promise<boolean> {
+ for (let attempt = 1; attempt <= REMOVE_REACTION_ATTEMPTS; attempt++) {
+ try {
+ await api.removeReaction(messageId, reactionId);
+ return true;
+ } catch (error) {
+ log('removeReaction %s on %s failed (attempt %d): %O', reactionId, messageId, attempt, error);
+ if (attempt < REMOVE_REACTION_ATTEMPTS) await sleep(REMOVE_REACTION_RETRY_DELAY_MS * attempt);
+ }
+ }
+ return false;
+}
+
+/** Remove every tracked reaction; returns the ids that could not be removed. */
+async function removeTrackedReactions(
+ api: LarkApiClient,
+ messageId: string,
+ reactionIds: string[],
+): Promise<string[]> {
+ const leftovers: string[] = [];
+ for (const reactionId of reactionIds) {
+ if (!(await removeReactionWithRetry(api, messageId, reactionId))) leftovers.push(reactionId);
+ }
+ return leftovers;
+}
+
+const reactionCleanupError = (messageId: string, leftovers: string[]) =>
+ new Error(
+ `Feishu could not remove ${leftovers.length} bot reaction(s) on ${messageId}; ids kept for a later cleanup`,
+ );
+
function createMessenger(
config: BotProviderConfig,
domain: 'lark' | 'feishu',
@@ -62,8 +112,21 @@ function createMessenger(
): PlatformMessenger {
const api = new LarkApiClient(config.applicationId, config.credentials.appSecret, domain);
const chatId = extractChatId(platformThreadId);
+ const { applicationId, platform } = config;
return {
- addReaction: (messageId, emoji) => api.addReaction(messageId, emoji).then(() => {}),
+ // Feishu takes a named `emoji_type`, never unicode โ€” see `./reactionEmoji`.
+ // An unmapped emoji is skipped rather than passed through: the API would
+ // reject it with `231001` and the failure would only surface in logs.
+ addReaction: async (messageId, emoji) => {
+ const emojiType = toFeishuEmojiType(emoji);
+ if (!emojiType) {
+ log('addReaction: no Feishu emoji_type for %s, skipping', emoji);
+ return;
+ }
+ const tracked = await readReactionIds(platform, applicationId, messageId);
+ const { reactionId } = await api.addReaction(messageId, emojiType);
+ await writeReactionIds(platform, applicationId, messageId, [...tracked, reactionId]);
+ },
createMessage: async (content) => {
const text = messengerContentText(content);
const attachments = typeof content === 'string' ? undefined : content.attachments;
@@ -76,15 +139,52 @@ function createMessenger(
},
editMessage: (messageId, content) =>
api.editMessage(messageId, messengerContentText(content)).then(() => {}),
- // Feishu / Lark currently expose no authenticated removeReaction endpoint.
- // Callers should treat this as a best-effort no-op โ€” step swaps will stack
- // additions rather than clear the previous emoji.
- removeReaction: () => Promise.resolve(),
+ // Feishu's delete endpoint is keyed by `reaction_id` (protocol-spec ยง5.2),
+ // which only `./reactionTracker` remembers. Without a tracked id there is
+ // nothing to delete โ€” that reaction was placed by someone else, or by a run
+ // whose key has expired.
+ removeReaction: async (messageId) => {
+ const tracked = await readReactionIds(platform, applicationId, messageId);
+ if (tracked.length === 0) return;
+ const leftovers = await removeTrackedReactions(api, messageId, tracked);
+ await writeReactionIds(platform, applicationId, messageId, leftovers);
+ if (leftovers.length > 0) throw reactionCleanupError(messageId, leftovers);
+ },
replaceReaction: async (messageId, prevEmoji, nextEmoji) => {
- if (prevEmoji === nextEmoji) return;
- // No remove API upstream โ€” we can only add. Step swaps therefore stack
- // emoji on the user's message. Final cleanup is a no-op.
- if (nextEmoji) await api.addReaction(messageId, nextEmoji);
+ // Compare the MAPPED values, not the unicode: several bridge emoji can
+ // resolve to the same `emoji_type`, and re-placing one that is already
+ // there would swap a live reaction for an identical one.
+ const next = toFeishuEmojiType(nextEmoji);
+ if (next && next === toFeishuEmojiType(prevEmoji)) return;
+
+ // Everything the bot has placed on this message so far โ€” normally one
+ // id, more if an earlier cleanup failed. Read BEFORE adding: if the add
+ // throws, the tracker still names the old reaction and the next swap
+ // retries the cleanup instead of leaking it.
+ const tracked = await readReactionIds(platform, applicationId, messageId);
+
+ // Add before remove, per the PlatformMessenger contract: the user should
+ // see at least one bot reaction throughout the transition. Track the new
+ // id alongside the old ones straight away, so nothing is orphaned if the
+ // removal below fails. A null `nextEmoji` is the final clear โ€” remove only.
+ let placed: string | undefined;
+ if (next) {
+ const { reactionId } = await api.addReaction(messageId, next);
+ placed = reactionId;
+ await writeReactionIds(platform, applicationId, messageId, [...tracked, reactionId]);
+ }
+
+ // Whatever could not be removed stays tracked, so a later swap or clear
+ // can still take it back instead of it living on the message forever;
+ // the tracker entry disappears only once the remote state is really clean.
+ const leftovers = await removeTrackedReactions(api, messageId, tracked);
+ await writeReactionIds(
+ platform,
+ applicationId,
+ messageId,
+ placed ? [...leftovers, placed] : leftovers,
+ );
+ if (leftovers.length > 0) throw reactionCleanupError(messageId, leftovers);
},
};
}
@@ -232,6 +332,14 @@ class FeishuWebhookClient implements PlatformClient {
return extractChatId(platformThreadId);
}
+ /**
+ * A Feishu group holding exactly one user and one bot is this bot's private
+ * conversation โ€” see `./chatComposition`. Anything else stays mention-only.
+ */
+ async isSoloBotConversation(platformThreadId: string): Promise<boolean> {
+ return isSoloBotChat(this.api, this.config.applicationId, extractChatId(platformThreadId));
+ }
+
formatMarkdown(markdown: string): string {
return stripMarkdown(markdown);
}
@@ -428,6 +536,14 @@ class FeishuWSClientImpl implements PlatformClient {
return extractChatId(platformThreadId);
}
+ /**
+ * A Feishu group holding exactly one user and one bot is this bot's private
+ * conversation โ€” see `./chatComposition`. Anything else stays mention-only.
+ */
+ async isSoloBotConversation(platformThreadId: string): Promise<boolean> {
+ return isSoloBotChat(this.api, this.config.applicationId, extractChatId(platformThreadId));
+ }
+
formatMarkdown(markdown: string): string {
return stripMarkdown(markdown);
}
diff --git a/apps/server/src/services/bot/platforms/feishu/reactionEmoji.test.ts b/apps/server/src/services/bot/platforms/feishu/reactionEmoji.test.ts
new file mode 100644
index 00000000000..0076d8c5dc7
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/feishu/reactionEmoji.test.ts
@@ -0,0 +1,51 @@
+import { supportedFeishuEmojiTypes, toFeishuEmojiType } from '@lobechat/chat-adapter-feishu';
+import { describe, expect, it } from 'vitest';
+
+import { RECEIVED_REACTION_EMOJI, THINKING_REACTION_EMOJI, WORKING_REACTION_EMOJI } from '../const';
+
+describe('toFeishuEmojiType', () => {
+ // The bug this module exists for: the bridge fires these three on every run,
+ // and passing them through as unicode is a guaranteed `231001`.
+ it.each([
+ ['received', RECEIVED_REACTION_EMOJI],
+ ['thinking', THINKING_REACTION_EMOJI],
+ ['working', WORKING_REACTION_EMOJI],
+ ])('maps the bridge %s emoji to a documented emoji_type', (_label, emoji) => {
+ const emojiType = toFeishuEmojiType(emoji);
+ expect(emojiType).toBeDefined();
+ expect(supportedFeishuEmojiTypes()).toContain(emojiType);
+ });
+
+ it('maps each bridge state to a code that reads as that state', () => {
+ // A wrong-but-valid code is invisible to the API and very visible to the
+ // user: '\u{1F914}' once mapped to MUSCLE, which renders in Lark as ใ€ŒๅŠ ๆฒนใ€ โ€”
+ // the bot looked like it was cheering, not thinking.
+ expect(toFeishuEmojiType(RECEIVED_REACTION_EMOJI)).toBe('OK');
+ expect(toFeishuEmojiType(THINKING_REACTION_EMOJI)).toBe('THINKING');
+ expect(toFeishuEmojiType(WORKING_REACTION_EMOJI)).toBe('OnIt');
+ });
+
+ it('maps common unicode an agent would pass to reactToMessage', () => {
+ expect(toFeishuEmojiType('๐Ÿ‘')).toBe('THUMBSUP');
+ expect(toFeishuEmojiType('๐Ÿ‘Ž')).toBe('ThumbsDown');
+ expect(toFeishuEmojiType('โœ…')).toBe('CheckMark');
+ expect(toFeishuEmojiType('โค๏ธ')).toBe('HEART');
+ });
+
+ it('accepts an emoji_type name directly, in any casing, and canonicalizes it', () => {
+ expect(toFeishuEmojiType('THUMBSUP')).toBe('THUMBSUP');
+ // Feishu's own casing is inconsistent โ€” a caller that lowercases must
+ // still land on the exact string the API expects.
+ expect(toFeishuEmojiType('thumbsdown')).toBe('ThumbsDown');
+ expect(toFeishuEmojiType('checkmark')).toBe('CheckMark');
+ });
+
+ it('returns undefined for anything without a documented equivalent', () => {
+ expect(toFeishuEmojiType('๐Ÿฆ„')).toBeUndefined();
+ expect(toFeishuEmojiType('NOT_A_REAL_TYPE')).toBeUndefined();
+ expect(toFeishuEmojiType('')).toBeUndefined();
+ expect(toFeishuEmojiType(' ')).toBeUndefined();
+ expect(toFeishuEmojiType(null)).toBeUndefined();
+ expect(toFeishuEmojiType(undefined)).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/feishu/reactionTracker.test.ts b/apps/server/src/services/bot/platforms/feishu/reactionTracker.test.ts
new file mode 100644
index 00000000000..73be05f06bb
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/feishu/reactionTracker.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ redisAvailable: true,
+ store: new Map<string, string>(),
+}));
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () =>
+ mocks.redisAvailable
+ ? {
+ del: async (key: string) => mocks.store.delete(key),
+ get: async (key: string) => mocks.store.get(key) ?? null,
+ set: async (key: string, value: string) => mocks.store.set(key, value),
+ }
+ : null,
+}));
+
+const { clearReactionTrackerMemoryCache, readReactionIds, writeReactionIds, deleteReactionIds } =
+ await import('./reactionTracker');
+
+describe('reactionTracker', () => {
+ beforeEach(() => {
+ mocks.redisAvailable = true;
+ mocks.store.clear();
+ clearReactionTrackerMemoryCache();
+ });
+
+ it('round-trips a list of ids through Redis', async () => {
+ await writeReactionIds('lark', 'cli_app', 'om_1', ['rct_a', 'rct_b']);
+
+ await expect(readReactionIds('lark', 'cli_app', 'om_1')).resolves.toEqual(['rct_a', 'rct_b']);
+ });
+
+ it('still reads the bare id written by earlier builds during a rolling deploy', async () => {
+ mocks.store.set('bot:feishu-reaction-id:lark:cli_app:om_1', 'rct_legacy');
+
+ await expect(readReactionIds('lark', 'cli_app', 'om_1')).resolves.toEqual(['rct_legacy']);
+ });
+
+ it('treats an empty list as a delete', async () => {
+ await writeReactionIds('lark', 'cli_app', 'om_1', ['rct_a']);
+ await writeReactionIds('lark', 'cli_app', 'om_1', []);
+
+ expect(mocks.store.size).toBe(0);
+ await expect(readReactionIds('lark', 'cli_app', 'om_1')).resolves.toEqual([]);
+ });
+
+ describe('without Redis', () => {
+ beforeEach(() => {
+ mocks.redisAvailable = false;
+ });
+
+ it('keeps the ids in process memory so local runs swap instead of stacking', async () => {
+ // Local (non-queue) execution drives received โ†’ thinking โ†’ working โ†’
+ // clear in one process; dropping the ids would leave every step on the
+ // message.
+ await writeReactionIds('lark', 'cli_app', 'om_1', ['rct_a']);
+
+ await expect(readReactionIds('lark', 'cli_app', 'om_1')).resolves.toEqual(['rct_a']);
+ await deleteReactionIds('lark', 'cli_app', 'om_1');
+ await expect(readReactionIds('lark', 'cli_app', 'om_1')).resolves.toEqual([]);
+ });
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/feishu/reactionTracker.ts b/apps/server/src/services/bot/platforms/feishu/reactionTracker.ts
new file mode 100644
index 00000000000..214f42b04df
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/feishu/reactionTracker.ts
@@ -0,0 +1,116 @@
+import debug from 'debug';
+
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+import { createBoundedMemoryCache } from './boundedMemoryCache';
+
+const log = debug('bot-platform:feishu:reaction-tracker');
+
+/**
+ * Remembers which reactions the bot placed on a message, so it can take them
+ * back.
+ *
+ * Feishu/Lark's delete endpoint (`protocol-spec.md` ยง5.2) is keyed by
+ * `reaction_id`, and that id is handed out exactly once โ€” in the response to
+ * the add call. Without holding onto it the bot can only ever add, so a single
+ * run stacks its whole progress sequence (received โ†’ thinking โ†’ working) on the
+ * user's message and never clears it.
+ *
+ * Normally one id is tracked per message. A list is kept because a swap can
+ * add the next reaction and then fail to remove the previous one: both ids
+ * must survive so a later swap or the final clear can still delete the
+ * leftover instead of leaving it on the message forever.
+ *
+ * Redis rather than process memory because queue-mode step callbacks land in a
+ * different process from the one that placed the first reaction โ€” the same
+ * reason `../../reactionState.ts` exists. Keyed by `messageId` (not thread) so
+ * concurrent mentions in one chat don't clobber each other, and TTL'd to the
+ * agent execution ceiling so a crashed run can't leak the key forever.
+ *
+ * Without agent-runtime Redis (local, single-process execution) the ids live
+ * in a bounded process-local cache instead, so the step sequence still swaps
+ * rather than stacking; only a cross-process callback would miss them.
+ */
+const TTL_SECONDS = 30 * 60;
+const MEMORY_CACHE_MAX_ENTRIES = 2000;
+
+const memoryCache = createBoundedMemoryCache<string[]>(MEMORY_CACHE_MAX_ENTRIES);
+
+/** Test hook: the memory cache is module state and would leak across cases. */
+export const clearReactionTrackerMemoryCache = (): void => memoryCache.clear();
+
+const buildKey = (platform: string, applicationId: string, messageId: string): string =>
+ `bot:feishu-reaction-id:${platform}:${applicationId}:${messageId}`;
+
+/**
+ * Accept both the JSON list written today and the bare id written by earlier
+ * builds, so a rolling deploy can still clean up reactions placed before it.
+ */
+const parseIds = (raw: string | null): string[] => {
+ if (!raw) return [];
+ try {
+ const parsed = JSON.parse(raw);
+ if (Array.isArray(parsed)) return parsed.filter((id): id is string => typeof id === 'string');
+ } catch {
+ // not JSON โ€” legacy single id
+ }
+ return [raw];
+};
+
+/** The `reaction_id`s the bot has placed on `messageId` and not yet removed. */
+export async function readReactionIds(
+ platform: string,
+ applicationId: string,
+ messageId: string,
+): Promise<string[]> {
+ const key = buildKey(platform, applicationId, messageId);
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return memoryCache.get(key) ?? [];
+ try {
+ return parseIds(await redis.get(key));
+ } catch (error) {
+ log('readReactionIds failed: %O', error);
+ return [];
+ }
+}
+
+/** Replace the tracked set; an empty list clears the entry. */
+export async function writeReactionIds(
+ platform: string,
+ applicationId: string,
+ messageId: string,
+ reactionIds: string[],
+): Promise<void> {
+ const ids = reactionIds.filter(Boolean);
+ if (ids.length === 0) return deleteReactionIds(platform, applicationId, messageId);
+
+ const key = buildKey(platform, applicationId, messageId);
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) {
+ memoryCache.set(key, ids, TTL_SECONDS);
+ return;
+ }
+ try {
+ await redis.set(key, JSON.stringify(ids), 'EX', TTL_SECONDS);
+ } catch (error) {
+ log('writeReactionIds failed: %O', error);
+ }
+}
+
+export async function deleteReactionIds(
+ platform: string,
+ applicationId: string,
+ messageId: string,
+): Promise<void> {
+ const key = buildKey(platform, applicationId, messageId);
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) {
+ memoryCache.delete(key);
+ return;
+ }
+ try {
+ await redis.del(key);
+ } catch (error) {
+ log('deleteReactionIds failed: %O', error);
+ }
+}
diff --git a/apps/server/src/services/bot/platforms/feishu/service.test.ts b/apps/server/src/services/bot/platforms/feishu/service.test.ts
new file mode 100644
index 00000000000..d8398e03e84
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/feishu/service.test.ts
@@ -0,0 +1,102 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { FeishuMessageService } from './service';
+
+const makeService = (listMessages: ReturnType<typeof vi.fn>) =>
+ new FeishuMessageService({ listMessages } as any, 'feishu');
+
+describe('FeishuMessageService.reactToMessage', () => {
+ it('translates unicode into the named emoji_type Feishu actually accepts', async () => {
+ const addReaction = vi.fn().mockResolvedValue(undefined);
+ const service = new FeishuMessageService({ addReaction } as any, 'feishu');
+
+ await service.reactToMessage({
+ emoji: '\u{1F44D}',
+ messageId: 'om_1',
+ platform: 'feishu',
+ } as any);
+
+ // Passing the unicode straight through is what returns `231001`.
+ expect(addReaction).toHaveBeenCalledWith('om_1', 'THUMBSUP');
+ });
+
+ it('rejects an emoji Feishu has no equivalent for, naming what it does accept', async () => {
+ const addReaction = vi.fn().mockResolvedValue(undefined);
+ const service = new FeishuMessageService({ addReaction } as any, 'feishu');
+
+ await expect(
+ service.reactToMessage({ emoji: '\u{1F984}', messageId: 'om_1', platform: 'feishu' } as any),
+ ).rejects.toThrow('THUMBSUP');
+ expect(addReaction).not.toHaveBeenCalled();
+ });
+});
+
+describe('FeishuMessageService.readMessages', () => {
+ it('asks for the NEWEST page and returns it in chronological order', async () => {
+ // Feishu's default sort is ascending, so an unsorted first page would be
+ // the oldest messages in the chat โ€” useless for "what was just discussed".
+ const item = (id: string, createTime: string) => ({
+ body: { content: JSON.stringify({ text: id }) },
+ create_time: createTime,
+ message_id: id,
+ sender: { id: 'ou_1' },
+ });
+ const listMessages = vi.fn().mockResolvedValue({
+ hasMore: true,
+ items: [
+ item('om_newest', '1700000003000'),
+ item('om_middle', '1700000002000'),
+ item('om_oldest', '1700000001000'),
+ ],
+ pageToken: 'next',
+ });
+
+ const result = await makeService(listMessages).readMessages({
+ channelId: 'oc_chat_1',
+ cursor: 'prev',
+ platform: 'feishu',
+ } as any);
+
+ expect(listMessages).toHaveBeenCalledWith(
+ 'oc_chat_1',
+ expect.objectContaining({ pageToken: 'prev', sortType: 'ByCreateTimeDesc' }),
+ );
+ expect(result.channelId).toBe('oc_chat_1');
+ expect(result.messages?.map((m) => m.id)).toEqual(['om_oldest', 'om_middle', 'om_newest']);
+ });
+
+ it.each([
+ ['230027', 'im:message.group_msg'],
+ ['230002', 'not a member of this chat'],
+ ['230006', 'bot capability is not enabled'],
+ ['230073', 'not visible to the bot'],
+ ])(
+ 'turns Feishu error %s into an actionable hint instead of a bare code',
+ async (code, expected) => {
+ const listMessages = vi
+ .fn()
+ .mockRejectedValue(
+ new Error(`Lark API GET /im/v1/messages failed: ${code} Permission denied`),
+ );
+
+ await expect(
+ makeService(listMessages).readMessages({
+ channelId: 'oc_chat_1',
+ platform: 'feishu',
+ } as any),
+ ).rejects.toThrow(expected);
+ },
+ );
+
+ it('leaves unrecognized failures untouched so they stay debuggable', async () => {
+ const listMessages = vi.fn().mockRejectedValue(new Error('socket hang up'));
+
+ await expect(
+ makeService(listMessages).readMessages({
+ channelId: 'oc_chat_1',
+ platform: 'feishu',
+ } as any),
+ ).rejects.toThrow('socket hang up');
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/feishu/service.ts b/apps/server/src/services/bot/platforms/feishu/service.ts
index f038ab7ee5b..4da57c3144e 100644
--- a/apps/server/src/services/bot/platforms/feishu/service.ts
+++ b/apps/server/src/services/bot/platforms/feishu/service.ts
@@ -36,6 +36,7 @@ import type {
UnpinMessageState,
} from '@lobechat/builtin-tool-message/executionRuntime';
import type { LarkApiClient } from '@lobechat/chat-adapter-feishu';
+import { supportedFeishuEmojiTypes, toFeishuEmojiType } from '@lobechat/chat-adapter-feishu';
import { DEFAULT_BOT_HISTORY_LIMIT } from '@lobechat/const';
import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';
@@ -44,6 +45,43 @@ import { PlatformUnsupportedError } from '@/server/services/toolExecution/server
import { MAX_FEISHU_HISTORY_LIMIT } from './const';
import { sendFeishuAttachments } from './sendAttachments';
+/**
+ * Feishu/Lark error codes that make a history read fail for a *configuration*
+ * reason rather than a transient one, mapped to the action that fixes them.
+ *
+ * `LarkApiClient` surfaces failures as `Lark API GET /im/v1/messages failed:
+ * 230027 Permission denied` โ€” accurate but useless to the model, which then
+ * relays a bare code to the user. `im:message.group_msg` in particular is easy
+ * to miss: it's needed *on top of* `im:message:readonly` for group history, so
+ * a bot that sends and receives fine still can't read the backlog.
+ *
+ * See `protocol-spec.md` ยง4.5.
+ */
+const HISTORY_READ_ERROR_HINTS: Record<string, string> = {
+ '230002': 'the bot is not a member of this chat โ€” add it to the group first',
+ '230006':
+ 'the bot capability is not enabled for this app โ€” enable it in the Feishu/Lark developer console',
+ // Name the scope the way the console lists it. The console's permission
+ // search matches the Chinese display name, so a bare code sends the operator
+ // hunting; and the neighbouring `im:message.group_msg.include_bot:read`
+ // ("่Žทๅ–็พค็ป„ไธญ็”จๆˆทๅ’Œๆœบๅ™จไบบๅ‘้€็š„ๆถˆๆฏ") is a different scope that governs the
+ // receive-message event, not history reads โ€” easy to grab by mistake.
+ '230027':
+ 'the app lacks permission to read this chat history. Reading GROUP history requires the scope "่Žทๅ–็พค็ป„ไธญๆ‰€ๆœ‰ๆถˆๆฏ" (`im:message.group_msg`) IN ADDITION TO `im:message:readonly` โ€” add it under ๆƒ้™็ฎก็† in the developer console (it is ๅ…ๅฎก, but you must then ๅˆ›ๅปบ็‰ˆๆœฌ and ๅ‘ๅธƒ for it to take effect). Note this is not `im:message.group_msg.include_bot:read`, which only governs the receive-message event',
+ '230073': 'this topic is not visible to the bot',
+};
+
+/**
+ * Turn a raw Lark API failure into a message the model can act on, leaving
+ * anything unrecognized untouched so genuine/unknown errors stay debuggable.
+ */
+const explainHistoryReadError = (error: unknown): Error => {
+ const message = error instanceof Error ? error.message : String(error);
+ const code = Object.keys(HISTORY_READ_ERROR_HINTS).find((c) => message.includes(c));
+ if (!code) return error instanceof Error ? error : new Error(message);
+ return new Error(`${message} โ€” ${HISTORY_READ_ERROR_HINTS[code]}.`);
+};
+
/**
* Normalize a Feishu/Lark message object to MessageItem.
*/
@@ -102,13 +140,24 @@ export class FeishuMessageService implements MessageRuntimeService {
};
readMessages = async (params: ReadMessagesParams): Promise<ReadMessagesState> => {
- const result = await this.api.listMessages(params.channelId, {
- endTime: params.endTime,
- pageSize: Math.min(params.limit ?? DEFAULT_BOT_HISTORY_LIMIT, MAX_FEISHU_HISTORY_LIMIT),
- pageToken: params.cursor,
- startTime: params.startTime,
- });
- const messages = result.items.map(toMessageItem);
+ // Feishu defaults to `ByCreateTimeAsc`, so an unsorted first page is the
+ // OLDEST messages in the chat โ€” in any group past the 50-message cap the
+ // model would get the chat's beginnings instead of what was just said.
+ // Ask for newest-first, then flip the page so the tool's documented
+ // chronological order holds within the window. The same `sortType` goes on
+ // every cursor follow-up because Feishu requires it to stay constant.
+ const result = await this.api
+ .listMessages(params.channelId, {
+ endTime: params.endTime,
+ pageSize: Math.min(params.limit ?? DEFAULT_BOT_HISTORY_LIMIT, MAX_FEISHU_HISTORY_LIMIT),
+ pageToken: params.cursor,
+ sortType: 'ByCreateTimeDesc',
+ startTime: params.startTime,
+ })
+ .catch((error) => {
+ throw explainHistoryReadError(error);
+ });
+ const messages = result.items.map(toMessageItem).reverse();
return {
channelId: params.channelId,
hasMore: result.hasMore,
@@ -136,7 +185,18 @@ export class FeishuMessageService implements MessageRuntimeService {
// ==================== Reactions ====================
reactToMessage = async (params: ReactToMessageParams): Promise<ReactToMessageState> => {
- await this.api.addReaction(params.messageId, params.emoji);
+ // The tool schema asks for unicode because every other platform takes it;
+ // Feishu takes a named `emoji_type` (see `./reactionEmoji`). Unlike the
+ // bridge's fire-and-forget progress reactions, a tool call must not fail
+ // silently โ€” tell the model which names exist so it can pick another.
+ const emojiType = toFeishuEmojiType(params.emoji);
+ if (!emojiType) {
+ throw new Error(
+ `${this.platformName} has no reaction matching "${params.emoji}". ` +
+ `It accepts a fixed emoji set, named rather than unicode: ${supportedFeishuEmojiTypes().join(', ')}.`,
+ );
+ }
+ await this.api.addReaction(params.messageId, emojiType);
return { messageId: params.messageId, success: true };
};
diff --git a/apps/server/src/services/bot/platforms/slack/client.ts b/apps/server/src/services/bot/platforms/slack/client.ts
index d47490fd532..e414966e11e 100644
--- a/apps/server/src/services/bot/platforms/slack/client.ts
+++ b/apps/server/src/services/bot/platforms/slack/client.ts
@@ -234,6 +234,16 @@ class SlackWebhookClient implements PlatformClient {
return extractChannelId(platformThreadId);
}
+ /**
+ * A reply thread is `slack:<channel>:<thread_ts>`, and `readMessages` only
+ * knows channels (`conversations.history`) โ€” reading the parent channel
+ * would hand the model unrelated traffic while calling it "this
+ * conversation". Only a plain channel / DM identifies itself exactly.
+ */
+ extractConversationId(platformThreadId: string): string | undefined {
+ return extractThreadTs(platformThreadId) ? undefined : extractChannelId(platformThreadId);
+ }
+
formatMarkdown(markdown: string): string {
return markdownToSlackMrkdwn(markdown);
}
@@ -423,6 +433,16 @@ class SlackSocketModeClient implements PlatformClient {
return extractChannelId(platformThreadId);
}
+ /**
+ * A reply thread is `slack:<channel>:<thread_ts>`, and `readMessages` only
+ * knows channels (`conversations.history`) โ€” reading the parent channel
+ * would hand the model unrelated traffic while calling it "this
+ * conversation". Only a plain channel / DM identifies itself exactly.
+ */
+ extractConversationId(platformThreadId: string): string | undefined {
+ return extractThreadTs(platformThreadId) ? undefined : extractChannelId(platformThreadId);
+ }
+
formatMarkdown(markdown: string): string {
return markdownToSlackMrkdwn(markdown);
}
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index 0cf626b7e9b..81953708e85 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -266,6 +266,19 @@ export interface PlatformClient {
/** Extract the chat/channel ID from a composite platformThreadId. */
extractChatId: (platformThreadId: string) => string;
+ /**
+ * The `channelId` that `readMessages` needs to read THIS conversation's
+ * history, injected into the model's prompt as the current conversation.
+ *
+ * Omit it when `extractChatId` already identifies the conversation exactly
+ * (Feishu `oc_โ€ฆ`, Discord channel-or-thread id, Telegram chat id). Implement
+ * it โ€” returning `undefined` โ€” when the platform's history read cannot be
+ * scoped to what `platformThreadId` denotes: a Slack reply thread decodes to
+ * its parent channel, and `conversations.history` on that channel would read
+ * unrelated channel traffic while claiming to be the current conversation.
+ */
+ extractConversationId?: (platformThreadId: string) => string | undefined;
+
/**
* Resolve attachments on an inbound `Message` into `AttachmentSource[]` for
* ingestion by the bridge. Each platform owns its own attachment quirks
@@ -321,6 +334,21 @@ export interface PlatformClient {
readonly id: string;
+ /**
+ * Whether this conversation contains only the operator and this bot, so every
+ * message in it is implicitly addressed to the bot and no @-mention is needed.
+ *
+ * The router otherwise infers that from how many distinct humans have SPOKEN
+ * in the thread, which misreads a quiet group as private โ€” badly so on
+ * platforms where the subscribed "thread" is the entire group chat. A platform
+ * that can report real membership should implement this and settle it.
+ *
+ * Must fail CLOSED: resolve `false` whenever membership can't be established,
+ * so an unprovable chat stays mention-only rather than the bot talking over a
+ * group. Platforms that can't tell omit the method.
+ */
+ isSoloBotConversation?: (platformThreadId: string) => Promise<boolean>;
+
/**
* Optional hook called from the router when a non-DM message wakes the
* bot via a watch-keyword match (). Platforms that prefer to
diff --git a/apps/server/src/services/bot/platforms/wechat/client.test.ts b/apps/server/src/services/bot/platforms/wechat/client.test.ts
index f0148a6c020..716dc5330aa 100644
--- a/apps/server/src/services/bot/platforms/wechat/client.test.ts
+++ b/apps/server/src/services/bot/platforms/wechat/client.test.ts
@@ -408,7 +408,14 @@ describe('WechatGatewayClient', () => {
const voiceBuf = Buffer.from('voice');
mockDownloadMediaFromRawMessage.mockResolvedValue([
{ buffer: imageBuf, mimeType: 'image/jpeg', name: 'image.jpg', type: 'image', url: '' },
- { buffer: voiceBuf, mimeType: 'audio/silk', type: 'audio', url: '' },
+ {
+ buffer: voiceBuf,
+ mimeType: 'audio/wav',
+ name: 'voice.wav',
+ size: 5,
+ type: 'audio',
+ url: '',
+ },
]);
const client = createClient();
const result = await client.extractFiles!(
@@ -422,7 +429,7 @@ describe('WechatGatewayClient', () => {
expect(result).toEqual({
files: [
{ buffer: imageBuf, mimeType: 'image/jpeg', name: 'image.jpg', size: undefined },
- { buffer: voiceBuf, mimeType: 'audio/silk', name: undefined, size: undefined },
+ { buffer: voiceBuf, mimeType: 'audio/wav', name: 'voice.wav', size: 5 },
],
warnings: undefined,
});
diff --git a/docs/usage/channels/feishu.mdx b/docs/usage/channels/feishu.mdx
index 7b178533d27..918ee8b9fcb 100644
--- a/docs/usage/channels/feishu.mdx
+++ b/docs/usage/channels/feishu.mdx
@@ -80,8 +80,10 @@ LobeHub supports two connection modes for Feishu bots:
"event:ip_list",
"im:chat.access_event.bot_p2p_chat:read",
"im:chat.members:bot_access",
+ "im:chat:readonly",
"im:message",
"im:message.group_at_msg:readonly",
+ "im:message.group_msg",
"im:message.p2p_msg:readonly",
"im:message:readonly",
"im:message:send_as_bot",
diff --git a/docs/usage/channels/feishu.zh-CN.mdx b/docs/usage/channels/feishu.zh-CN.mdx
index 1d56e1cf396..53fd7697f13 100644
--- a/docs/usage/channels/feishu.zh-CN.mdx
+++ b/docs/usage/channels/feishu.zh-CN.mdx
@@ -76,8 +76,10 @@ LobeHub ๆ”ฏๆŒไธค็ง้ฃžไนฆๆœบๅ™จไบบ่ฟžๆŽฅๆจกๅผ๏ผš
"event:ip_list",
"im:chat.access_event.bot_p2p_chat:read",
"im:chat.members:bot_access",
+ "im:chat:readonly",
"im:message",
"im:message.group_at_msg:readonly",
+ "im:message.group_msg",
"im:message.p2p_msg:readonly",
"im:message:readonly",
"im:message:send_as_bot",
diff --git a/docs/usage/channels/lark.mdx b/docs/usage/channels/lark.mdx
index 3a1100990c1..b6c37be17e5 100644
--- a/docs/usage/channels/lark.mdx
+++ b/docs/usage/channels/lark.mdx
@@ -75,8 +75,10 @@ LobeHub supports two connection modes for Lark bots:
"contact:user.employee_id:readonly",
"event:ip_list",
"im:chat.members:bot_access",
+ "im:chat:readonly",
"im:message",
"im:message.group_at_msg:readonly",
+ "im:message.group_msg",
"im:message.p2p_msg:readonly",
"im:message:readonly",
"im:message:send_as_bot",
diff --git a/docs/usage/channels/lark.zh-CN.mdx b/docs/usage/channels/lark.zh-CN.mdx
index 76054b8ccd7..8b515d6f76e 100644
--- a/docs/usage/channels/lark.zh-CN.mdx
+++ b/docs/usage/channels/lark.zh-CN.mdx
@@ -72,8 +72,10 @@ LobeHub ๆ”ฏๆŒไธค็ง Lark ๆœบๅ™จไบบ่ฟžๆŽฅๆจกๅผ๏ผš
"contact:user.employee_id:readonly",
"event:ip_list",
"im:chat.members:bot_access",
+ "im:chat:readonly",
"im:message",
"im:message.group_at_msg:readonly",
+ "im:message.group_msg",
"im:message.p2p_msg:readonly",
"im:message:readonly",
"im:message:send_as_bot",
diff --git a/packages/builtin-skills/src/lobehub/references/bot-feishu.ts b/packages/builtin-skills/src/lobehub/references/bot-feishu.ts
index 09a6b1483e9..52605a41abf 100644
--- a/packages/builtin-skills/src/lobehub/references/bot-feishu.ts
+++ b/packages/builtin-skills/src/lobehub/references/bot-feishu.ts
@@ -72,6 +72,8 @@ Connect a Feishu custom app bot to your agent.
2. Search and add:
- \`im:message\` โ€” receive and send messages
- \`im:message.group_at_msg\` โ€” receive @bot messages in groups (if needed)
+ - \`im:message:readonly\` โ€” read chat history (needed for \`readMessages\`)
+ - \`im:message.group_msg\` โ€” ใ€Œ่Žทๅ–็พค็ป„ไธญๆ‰€ๆœ‰ๆถˆๆฏใ€, read **group** chat history; required *in addition to* \`im:message:readonly\`, otherwise history reads in groups fail with \`230027 ๆƒ้™ไธ่ถณ\`. Search ๆƒ้™็ฎก็† by the Chinese name โ€” the console does not match on the code. It is ๅ…ๅฎก, but the app must be re-published (ๅˆ›ๅปบ็‰ˆๆœฌ โ†’ ๅ‘ๅธƒ) before it takes effect. Do NOT confuse it with \`im:message.group_msg.include_bot:read\`๏ผˆ่Žทๅ–็พค็ป„ไธญ็”จๆˆทๅ’Œๆœบๅ™จไบบๅ‘้€็š„ๆถˆๆฏ๏ผ‰, which governs the receive-message event, not history reads
3. Publish the app (see Step 7) for permissions to take effect
### Step 7: Publish the App
diff --git a/packages/builtin-skills/src/lobehub/references/bot-lark.ts b/packages/builtin-skills/src/lobehub/references/bot-lark.ts
index 7fc3fa2a2a3..248c035c449 100644
--- a/packages/builtin-skills/src/lobehub/references/bot-lark.ts
+++ b/packages/builtin-skills/src/lobehub/references/bot-lark.ts
@@ -71,6 +71,8 @@ Connect a Lark custom app bot to your agent. Lark is the international version o
2. Add:
- \`im:message\` โ€” send and receive messages
- \`im:message.group_at_msg:readonly\` โ€” receive @bot mentions in groups (if needed)
+ - \`im:message:readonly\` โ€” read chat history (needed for \`readMessages\`)
+ - \`im:message.group_msg\` โ€” "่Žทๅ–็พค็ป„ไธญๆ‰€ๆœ‰ๆถˆๆฏ", read **group** chat history; required *in addition to* \`im:message:readonly\`, otherwise history reads in groups fail with \`230027 Permission denied\`. Search Permissions & Scopes by that display name โ€” the console does not match on the code. No review is required, but the app must be re-published for it to take effect. Do NOT confuse it with \`im:message.group_msg.include_bot:read\`, which governs the receive-message event, not history reads
### Step 7: Publish the App
diff --git a/packages/chat-adapter-feishu/src/adapter.test.ts b/packages/chat-adapter-feishu/src/adapter.test.ts
index 88e4174d13b..d1060b71ab8 100644
--- a/packages/chat-adapter-feishu/src/adapter.test.ts
+++ b/packages/chat-adapter-feishu/src/adapter.test.ts
@@ -924,3 +924,54 @@ describe('downloadMediaFromRawMessage', () => {
expect(warn).toHaveBeenCalled();
});
});
+
+describe('LarkAdapter.fetchMessages', () => {
+ const makeAdapter = () => {
+ const adapter = new LarkAdapter({ appId: 'a', appSecret: 's', platform: 'lark' });
+ adapter.initialize({
+ getLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+ getUserName: () => 'TestBot',
+ processMessage: vi.fn(),
+ } as any);
+ return adapter;
+ };
+ const page = (...ids: string[]) => ({
+ hasMore: false,
+ items: ids.map((id, index) =>
+ makeLarkMessage({ create_time: String(1_700_000_000_000 + index), message_id: id }),
+ ),
+ });
+ const threadId = 'lark:oc_test_chat';
+
+ it('fetches the NEWEST page for the default backward direction, oldest-first within it', async () => {
+ // Feishu's own default is ascending, i.e. the chat's oldest messages โ€”
+ // the opposite of what `direction: 'backward'` promises.
+ const adapter = makeAdapter();
+ const listMessages = vi
+ .spyOn((adapter as any).api, 'listMessages')
+ .mockResolvedValue(page('om_newest', 'om_middle', 'om_oldest'));
+
+ const result = await adapter.fetchMessages(threadId, { limit: 3 });
+
+ expect(listMessages).toHaveBeenCalledWith(
+ 'oc_test_chat',
+ expect.objectContaining({ sortType: 'ByCreateTimeDesc' }),
+ );
+ expect(result.messages.map((m) => m.id)).toEqual(['om_oldest', 'om_middle', 'om_newest']);
+ });
+
+ it('maps forward onto ascending order and keeps the page as returned', async () => {
+ const adapter = makeAdapter();
+ const listMessages = vi
+ .spyOn((adapter as any).api, 'listMessages')
+ .mockResolvedValue(page('om_1', 'om_2'));
+
+ const result = await adapter.fetchMessages(threadId, { direction: 'forward' });
+
+ expect(listMessages).toHaveBeenCalledWith(
+ 'oc_test_chat',
+ expect.objectContaining({ sortType: 'ByCreateTimeAsc' }),
+ );
+ expect(result.messages.map((m) => m.id)).toEqual(['om_1', 'om_2']);
+ });
+});
diff --git a/packages/chat-adapter-feishu/src/adapter.ts b/packages/chat-adapter-feishu/src/adapter.ts
index 600f0e0076f..cf659cf581b 100644
--- a/packages/chat-adapter-feishu/src/adapter.ts
+++ b/packages/chat-adapter-feishu/src/adapter.ts
@@ -18,6 +18,7 @@ import { Message, parseMarkdown } from 'chat';
import { LarkApiClient } from './api';
import { decryptLarkEvent } from './crypto';
import { LarkFormatConverter } from './format-converter';
+import { toFeishuEmojiType } from './reactionEmoji';
import type {
LarkAdapterConfig,
LarkMessageBody,
@@ -489,12 +490,20 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
): Promise<FetchResult<LarkRawMessage>> {
const { chatId } = this.decodeThreadId(threadId);
+ // `backward` (the default) means "the most recent messages", but Feishu's
+ // own default sort is ascending โ€” left alone, the first page would be the
+ // chat's oldest messages. Fetch newest-first for `backward` and flip the
+ // page so `FetchResult.messages` stays oldest-first as the contract says;
+ // `forward` maps straight onto Feishu's ascending order.
+ const forward = options?.direction === 'forward';
const result = await this.api.listMessages(chatId, {
pageSize: options?.limit || 50,
pageToken: options?.cursor,
+ sortType: forward ? 'ByCreateTimeAsc' : 'ByCreateTimeDesc',
});
const messages = result.items.map((item: any) => this.parseMessage(item));
+ if (!forward) messages.reverse();
return {
messages,
@@ -585,10 +594,17 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
emoji: EmojiValue | string,
): Promise<void> {
const emojiType = this.toEmojiType(emoji);
+ if (!emojiType) {
+ this.logger.warn('No Lark emoji_type for reaction %s, skipping', String(emoji));
+ return;
+ }
try {
await this.api.addReaction(messageId, emojiType);
- } catch {
- // Reactions may not be supported in all chat types
+ } catch (error) {
+ // Reactions are unavailable in some chat types, so this stays non-fatal โ€”
+ // but it is logged now: silently swallowing it is what hid the fact that
+ // every reaction was failing with `231001`.
+ this.logger.warn('Failed to add reaction %s: %s', emojiType, String(error));
}
}
@@ -597,8 +613,10 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
_messageId: string,
_emoji: EmojiValue | string,
): Promise<void> {
- // Lark's remove reaction requires a reaction ID, which we don't track.
- // No-op for now.
+ // Lark's delete endpoint is keyed by `reaction_id`, handed out only in the
+ // add response, and this adapter keeps no state to stash it in โ€” so removal
+ // is a no-op here. The server-side bot messenger, which is what the bot
+ // runtime actually drives, does track it (`feishu/reactionTracker.ts`).
}
// ------------------------------------------------------------------
@@ -741,10 +759,15 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
}
}
- private toEmojiType(emoji: EmojiValue | string): string {
- if (typeof emoji === 'string') return emoji;
- // EmojiValue is a symbol-like; use its string form
- return String(emoji);
+ /**
+ * Lark reactions are a named enum, not unicode โ€” `toFeishuEmojiType` owns the
+ * translation (and the reason it can't just be `String(emoji)`: passing a
+ * unicode emoji through is a guaranteed `231001 reaction type is invalid`).
+ * Returns undefined when there is no documented equivalent, so the caller can
+ * skip the request instead of making one that cannot succeed.
+ */
+ private toEmojiType(emoji: EmojiValue | string): string | undefined {
+ return toFeishuEmojiType(typeof emoji === 'string' ? emoji : String(emoji));
}
}
diff --git a/packages/chat-adapter-feishu/src/api.ts b/packages/chat-adapter-feishu/src/api.ts
index f163656092f..9058f27dc14 100644
--- a/packages/chat-adapter-feishu/src/api.ts
+++ b/packages/chat-adapter-feishu/src/api.ts
@@ -54,13 +54,28 @@ export class LarkApiClient {
return data.data;
}
+ /**
+ * List messages in a chat.
+ *
+ * `sortType` defaults to `ByCreateTimeAsc` on Feishu's side, i.e. the FIRST
+ * page is the OLDEST messages in the chat. A caller that wants "what was
+ * just discussed" must ask for `ByCreateTimeDesc` โ€” and keep passing the
+ * same value on every `pageToken` follow-up, which Feishu requires.
+ */
async listMessages(
chatId: string,
- options?: { pageSize?: number; pageToken?: string; startTime?: string; endTime?: string },
+ options?: {
+ pageSize?: number;
+ pageToken?: string;
+ sortType?: 'ByCreateTimeAsc' | 'ByCreateTimeDesc';
+ startTime?: string;
+ endTime?: string;
+ },
): Promise<{ items: any[]; hasMore: boolean; pageToken?: string }> {
const params = new URLSearchParams({ container_id_type: 'chat', container_id: chatId });
if (options?.pageSize) params.set('page_size', String(options.pageSize));
if (options?.pageToken) params.set('page_token', options.pageToken);
+ if (options?.sortType) params.set('sort_type', options.sortType);
if (options?.startTime) params.set('start_time', options.startTime);
if (options?.endTime) params.set('end_time', options.endTime);
@@ -80,10 +95,16 @@ export class LarkApiClient {
return { messageId: data.data.message_id, raw: data.data };
}
- async addReaction(messageId: string, emojiType: string): Promise<void> {
- await this.call('POST', `/im/v1/messages/${messageId}/reactions`, {
+ /**
+ * Add a reaction. Returns the `reaction_id` the delete endpoint needs โ€”
+ * it is only ever handed out here, so a caller that intends to remove its
+ * own reaction later has to keep it.
+ */
+ async addReaction(messageId: string, emojiType: string): Promise<{ reactionId: string }> {
+ const data = await this.call('POST', `/im/v1/messages/${messageId}/reactions`, {
reaction_type: { emoji_type: emojiType },
});
+ return { reactionId: data.data?.reaction_id };
}
async removeReaction(messageId: string, reactionId: string): Promise<void> {
@@ -266,6 +287,37 @@ export class LarkApiClient {
return text;
}
+ /**
+ * Flatten the `error` object Lark attaches to a failed response.
+ *
+ * `code` + `msg` alone are close to useless for the two failures operators
+ * actually hit: a permission error says `230027 Permission denied` and
+ * nothing about WHICH scope is missing โ€” even though Lark puts exactly that
+ * in `error.permission_violations`. Dropping it sent a real debugging session
+ * hunting for a scope name in our own docs instead of reading it off the
+ * response. `troubleshooter` is Lark's own log-id-scoped diagnosis link.
+ */
+ private static describeError(error: any): string {
+ if (!error || typeof error !== 'object') return '';
+ const parts: string[] = [];
+
+ const violations = Array.isArray(error.permission_violations)
+ ? error.permission_violations
+ : [];
+ for (const violation of violations) {
+ const subject = violation?.subject ?? violation?.type;
+ const description = violation?.description;
+ const detail = [subject, description].filter(Boolean).join(': ');
+ if (detail) parts.push(`missing permission โ€” ${detail}`);
+ }
+
+ if (typeof error.troubleshooter === 'string' && error.troubleshooter) {
+ parts.push(error.troubleshooter);
+ }
+
+ return parts.length > 0 ? ` (${parts.join('; ')})` : '';
+ }
+
private async call(method: string, path: string, body: Record<string, unknown>): Promise<any> {
const token = await this.getTenantAccessToken();
const url = `${this.baseUrl}${path}`;
@@ -292,7 +344,9 @@ export class LarkApiClient {
const data: any = await response.json();
if (data.code !== 0) {
- throw new Error(`Lark API ${method} ${path} failed: ${data.code} ${data.msg}`);
+ throw new Error(
+ `Lark API ${method} ${path} failed: ${data.code} ${data.msg}${LarkApiClient.describeError(data.error)}`,
+ );
}
return data;
diff --git a/packages/chat-adapter-feishu/src/index.ts b/packages/chat-adapter-feishu/src/index.ts
index 7d16cbb7e81..693c8b19686 100644
--- a/packages/chat-adapter-feishu/src/index.ts
+++ b/packages/chat-adapter-feishu/src/index.ts
@@ -9,6 +9,7 @@ export {
export { LarkApiClient } from './api';
export { decryptLarkEvent } from './crypto';
export { LarkFormatConverter } from './format-converter';
+export { supportedFeishuEmojiTypes, toFeishuEmojiType } from './reactionEmoji';
export type {
LarkAdapterConfig,
LarkEventHeader,
diff --git a/packages/chat-adapter-feishu/src/reactionEmoji.ts b/packages/chat-adapter-feishu/src/reactionEmoji.ts
new file mode 100644
index 00000000000..5d191e1a4de
--- /dev/null
+++ b/packages/chat-adapter-feishu/src/reactionEmoji.ts
@@ -0,0 +1,151 @@
+/**
+ * Feishu/Lark reactions are a **named enum**, not unicode.
+ *
+ * `POST /im/v1/messages/{id}/reactions` takes `reaction_type.emoji_type`
+ * values like `OK` / `MUSCLE` / `FIRE` and rejects anything else with
+ * `231001 reaction type is invalid`. Every other platform we support takes
+ * unicode, so callers speak unicode โ€” this module is the single translation
+ * point between them. Without it every reaction on Feishu/Lark fails, and
+ * because both call sites swallow reaction errors the only symptom is that the
+ * bot never appears to acknowledge anything.
+ *
+ * It lives in the adapter package, next to `LarkApiClient`, for the same reason
+ * `decodeLarkThreadId` does: `LarkAdapter` and the server-side bot platform
+ * client both need it, and two copies of an enum this fiddly would drift.
+ *
+ * Only enum names taken from Feishu's published emoji list appear here (the
+ * `ๅธธ็”จๅ€ผ` table in `protocol-spec.md` ยง5.1, plus the full list it links to at
+ * https://open.feishu.cn/document/server-docs/im-v1/message-reaction/emojis-introduce).
+ * Do NOT add a value guessed from Feishu's UI โ€” an undocumented `emoji_type` is
+ * just another `231001`. The casing is Feishu's own and is inconsistent on
+ * purpose (`THUMBSUP` but `ThumbsDown`, `OnIt`, `CheckMark`, `Trophy`).
+ */
+const FEISHU_EMOJI_TYPES = [
+ // ๆญฃ้ข / ่ฎคๅฏ
+ 'OK',
+ 'THUMBSUP',
+ 'THANKS',
+ 'MUSCLE',
+ 'APPLAUSE',
+ 'FISTBUMP',
+ 'JIAYI',
+ 'DONE',
+ 'LGTM',
+ // ็ฌ‘่„ธ
+ 'SMILE',
+ 'LAUGH',
+ 'LOL',
+ 'LOVE',
+ 'WINK',
+ 'JOYFUL',
+ 'WOW',
+ 'YEAH',
+ // ๆ‚ฒไผค
+ 'SOB',
+ 'CRY',
+ 'FROWN',
+ 'SPEECHLESS',
+ // ๆ‰‹ๅŠฟ
+ 'ThumbsDown',
+ 'HIGHFIVE',
+ 'WAVE',
+ 'SALUTE',
+ // ็‰ฉๅ“
+ 'HEART',
+ 'ROSE',
+ 'FIRE',
+ 'PARTY',
+ 'BEER',
+ 'CAKE',
+ 'GIFT',
+ 'Trophy',
+ // ่ฟ›่กŒไธญ โ€” the states the bot bridge cycles through
+ 'OnIt',
+ 'THINKING',
+ 'Typing',
+ 'OneSecond',
+ // ็ฌฆๅท
+ 'POOP',
+ 'HEARTBROKEN',
+ 'CheckMark',
+ 'CrossMark',
+ 'Hundred',
+] as const;
+
+/** Lower-cased enum name โ†’ the exact-cased value Feishu expects. */
+const CANONICAL_BY_LOWERCASE = new Map(
+ FEISHU_EMOJI_TYPES.map((name) => [name.toLowerCase(), name]),
+);
+
+/**
+ * Unicode โ†’ Feishu `emoji_type`.
+ *
+ * The first three entries are what the bot bridge actually sends on every run
+ * (`RECEIVED_REACTION_EMOJI` / `THINKING_REACTION_EMOJI` /
+ * `WORKING_REACTION_EMOJI` in `../const.ts`) โ€” keep them mapped or the
+ * progress reactions go dark again. The rest cover what an agent plausibly
+ * passes to the `reactToMessage` tool, whose schema asks for unicode.
+ */
+const EMOJI_TYPE_BY_UNICODE: Record<string, (typeof FEISHU_EMOJI_TYPES)[number]> = {
+ 'โค': 'HEART',
+ 'โค๏ธ': 'HEART',
+ 'โšก': 'OnIt', // bridge: a tool call is running โ€” ใ€Œๅค„็†ไธญใ€
+ 'โœ…': 'CheckMark',
+ 'โŒ': 'CrossMark',
+ '๐ŸŒน': 'ROSE',
+ '๐ŸŽ': 'GIFT',
+ '๐ŸŽ‚': 'CAKE',
+ '๐ŸŽ‰': 'PARTY',
+ '๐Ÿบ': 'BEER',
+ '๐Ÿ‘€': 'OK', // bridge: the bot has picked the message up โ€” ใ€Œๅฅฝ็š„ใ€
+ '๐Ÿ‘‹': 'WAVE',
+ '๐Ÿ‘Œ': 'OK',
+ '๐Ÿ‘': 'THUMBSUP',
+ '๐Ÿ‘Ž': 'ThumbsDown',
+ '๐Ÿ‘': 'APPLAUSE',
+ '๐Ÿ‘Š': 'FISTBUMP',
+ '๐Ÿ’”': 'HEARTBROKEN',
+ '๐Ÿ’ฉ': 'POOP',
+ '๐Ÿ’ช': 'MUSCLE',
+ '๐Ÿ’ฏ': 'Hundred',
+ '๐Ÿ”ฅ': 'FIRE',
+ '๐Ÿ™': 'FROWN',
+ '๐Ÿ™Œ': 'HIGHFIVE',
+ '๐Ÿ™': 'THANKS',
+ '๐Ÿค”': 'THINKING', // bridge: the agent is reasoning โ€” ใ€Œๆ€่€ƒใ€
+ '๐Ÿคฃ': 'LOL',
+ '๐Ÿฅณ': 'PARTY',
+ '๐Ÿซก': 'SALUTE',
+ '๐Ÿ˜€': 'SMILE',
+ '๐Ÿ˜‚': 'LOL',
+ '๐Ÿ˜„': 'SMILE',
+ '๐Ÿ˜†': 'LAUGH',
+ '๐Ÿ˜Š': 'SMILE',
+ '๐Ÿ˜‰': 'WINK',
+ '๐Ÿ˜': 'LOVE',
+ '๐Ÿ˜ฎ': 'WOW',
+ '๐Ÿ˜ฒ': 'WOW',
+ '๐Ÿ˜ถ': 'SPEECHLESS',
+ '๐Ÿ˜ข': 'CRY',
+ '๐Ÿ˜ญ': 'SOB',
+ '๐Ÿ†—': 'OK',
+};
+
+/**
+ * Resolve a Feishu/Lark `emoji_type` from what a caller supplied.
+ *
+ * Accepts either a unicode emoji (what the bridge and the tool schema use) or
+ * an `emoji_type` name the caller already knows, in any casing. Returns
+ * `undefined` when there is no documented equivalent โ€” callers decide what
+ * that means for them, but nobody may pass the raw input through: doing so is
+ * a guaranteed `231001`.
+ */
+export const toFeishuEmojiType = (emoji: string | null | undefined): string | undefined => {
+ if (!emoji) return undefined;
+ const trimmed = emoji.trim();
+ if (!trimmed) return undefined;
+ return EMOJI_TYPE_BY_UNICODE[trimmed] ?? CANONICAL_BY_LOWERCASE.get(trimmed.toLowerCase());
+};
+
+/** Every `emoji_type` this module can produce, for error messages. */
+export const supportedFeishuEmojiTypes = (): string[] => [...FEISHU_EMOJI_TYPES];
diff --git a/packages/chat-adapter-wechat/package.json b/packages/chat-adapter-wechat/package.json
index 1d07228feda..bab56409fb8 100644
--- a/packages/chat-adapter-wechat/package.json
+++ b/packages/chat-adapter-wechat/package.json
@@ -17,7 +17,8 @@
},
"dependencies": {
"chat": "~4.38.0",
- "mime": "^4.1.0"
+ "mime": "^4.1.0",
+ "silk-wasm": "^3.7.1"
},
"devDependencies": {
"@types/node": "^24.13.2",
diff --git a/packages/chat-adapter-wechat/src/adapter.test.ts b/packages/chat-adapter-wechat/src/adapter.test.ts
index 09ea7d1432c..2ae13fbbb67 100644
--- a/packages/chat-adapter-wechat/src/adapter.test.ts
+++ b/packages/chat-adapter-wechat/src/adapter.test.ts
@@ -6,6 +6,10 @@ import { WechatApiClient, WechatUploadMediaType } from './api';
import type { WechatRawMessage } from './types';
import { MessageItemType, MessageState, MessageType } from './types';
+const { mockDecodeWechatVoice } = vi.hoisted(() => ({ mockDecodeWechatVoice: vi.fn() }));
+
+vi.mock('./voice', () => ({ decodeWechatVoice: mockDecodeWechatVoice }));
+
// ---- helpers ----
function makeRawMessage(overrides: Partial<WechatRawMessage> = {}): WechatRawMessage {
@@ -460,7 +464,9 @@ describe('WechatAdapter', () => {
const message = await factory?.();
expect(downloadSpy).not.toHaveBeenCalled();
- expect(message?.attachments).toEqual([{ mimeType: 'audio/silk', type: 'audio', url: '' }]);
+ expect(message?.attachments).toEqual([
+ { mimeType: 'audio/wav', name: 'voice.wav', type: 'audio', url: '' },
+ ]);
// The transcription text should still flow into message.text via extractText
expect(message?.text).toBe('transcribed');
});
@@ -863,9 +869,48 @@ describe('downloadMediaFromRawMessage', () => {
]);
});
- it('downloads voice as audio/silk', async () => {
- const voiceBytes = Buffer.from([0x46]);
- downloadSpy.mockResolvedValueOnce(voiceBytes);
+ it('downloads voice and decodes SILK into a playable WAV', async () => {
+ const silkBytes = Buffer.from([0x02, ...Buffer.from('#!SILK_V3'), 0x01]);
+ const wavBytes = Buffer.from('RIFF....WAVE');
+ downloadSpy.mockResolvedValueOnce(silkBytes);
+ mockDecodeWechatVoice.mockResolvedValueOnce({
+ buffer: wavBytes,
+ durationMs: 1200,
+ mimeType: 'audio/wav',
+ name: 'voice.wav',
+ });
+
+ const voiceItem = {
+ encode_type: 6,
+ media: { aes_key: 'k', encrypt_query_param: 'q' },
+ sample_rate: 24_000,
+ };
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({ item_list: [{ type: MessageItemType.VOICE, voice_item: voiceItem }] }),
+ );
+
+ expect(mockDecodeWechatVoice).toHaveBeenCalledWith(silkBytes, voiceItem, expect.any(Function));
+ expect(result).toEqual([
+ {
+ buffer: wavBytes,
+ mimeType: 'audio/wav',
+ name: 'voice.wav',
+ size: wavBytes.length,
+ type: 'audio',
+ url: '',
+ },
+ ]);
+ });
+
+ it('keeps raw bytes when voice decoding falls back', async () => {
+ const rawBytes = Buffer.from([0x46]);
+ downloadSpy.mockResolvedValueOnce(rawBytes);
+ mockDecodeWechatVoice.mockResolvedValueOnce({
+ buffer: rawBytes,
+ mimeType: 'audio/silk',
+ name: 'voice.silk',
+ });
const result = await downloadMediaFromRawMessage(
api,
@@ -873,16 +918,21 @@ describe('downloadMediaFromRawMessage', () => {
item_list: [
{
type: MessageItemType.VOICE,
- voice_item: {
- media: { aes_key: 'k', encrypt_query_param: 'q' },
- },
+ voice_item: { media: { aes_key: 'k', encrypt_query_param: 'q' } },
},
],
}),
);
expect(result).toEqual([
- { buffer: voiceBytes, mimeType: 'audio/silk', type: 'audio', url: '' },
+ {
+ buffer: rawBytes,
+ mimeType: 'audio/silk',
+ name: 'voice.silk',
+ size: 1,
+ type: 'audio',
+ url: '',
+ },
]);
});
diff --git a/packages/chat-adapter-wechat/src/adapter.ts b/packages/chat-adapter-wechat/src/adapter.ts
index 3a4d0c394d0..cd5bbbbf5ef 100644
--- a/packages/chat-adapter-wechat/src/adapter.ts
+++ b/packages/chat-adapter-wechat/src/adapter.ts
@@ -21,6 +21,7 @@ import { getWechatTextSendCount, WechatApiClient, WechatUploadMediaType } from '
import { WechatFormatConverter } from './format-converter';
import type { MessageItem, WechatAdapterConfig, WechatRawMessage, WechatThreadId } from './types';
import { MessageItemType, MessageState, MessageType } from './types';
+import { decodeWechatVoice } from './voice';
/**
* Extract text content from a WechatRawMessage's item_list.
@@ -122,8 +123,11 @@ export function extractMediaMetadata(msg: WechatRawMessage): Attachment[] {
}
case MessageItemType.VOICE: {
if (!item.voice_item) break;
+ // Voice arrives as SILK but is decoded to WAV on download (see
+ // `decodeWechatVoice`), so advertise the shape consumers will get.
attachments.push({
- mimeType: 'audio/silk',
+ mimeType: 'audio/wav',
+ name: 'voice.wav',
type: 'audio',
url: '',
} as Attachment);
@@ -190,9 +194,17 @@ export async function downloadMediaFromRawMessage(
case MessageItemType.VOICE: {
if (!hasCdnMedia(item) || !item.voice_item?.media) break;
const voiceBuf = await api.downloadCdnMedia(item.voice_item.media);
+ // Raw SILK is unplayable in browsers and unsupported by audio-capable
+ // models; decode to WAV here so every downstream consumer gets a
+ // real audio file (a failed decode falls back to the raw bytes).
+ const voice = await decodeWechatVoice(voiceBuf, item.voice_item, (error) =>
+ warn(`[wechat] voice decode failed, keeping raw SILK bytes: ${String(error)}`),
+ );
attachments.push({
- buffer: voiceBuf,
- mimeType: 'audio/silk',
+ buffer: voice.buffer,
+ mimeType: voice.mimeType,
+ name: voice.name,
+ size: voice.buffer.length,
type: 'audio',
url: '',
} as Attachment);
diff --git a/packages/chat-adapter-wechat/src/index.ts b/packages/chat-adapter-wechat/src/index.ts
index 7f8d1579e3e..18672758382 100644
--- a/packages/chat-adapter-wechat/src/index.ts
+++ b/packages/chat-adapter-wechat/src/index.ts
@@ -20,3 +20,5 @@ export type {
WechatThreadId,
} from './types';
export { MessageItemType, MessageState, MessageType, WECHAT_RET_CODES } from './types';
+export type { DecodedWechatVoice } from './voice';
+export { decodeWechatVoice, WechatVoiceEncodeType } from './voice';
diff --git a/packages/chat-adapter-wechat/src/types.ts b/packages/chat-adapter-wechat/src/types.ts
index 19291af5b6f..54d70387973 100644
--- a/packages/chat-adapter-wechat/src/types.ts
+++ b/packages/chat-adapter-wechat/src/types.ts
@@ -68,9 +68,15 @@ export interface ImageItem {
}
export interface VoiceItem {
+ bits_per_sample?: number;
+ /** `1 = pcm`, `2 = adpcm`, `3 = feature`, `4 = speex`, `5 = amr`, `6 = silk`, `7 = mp3`, `8 = ogg-speex`. */
encode_type?: number;
media?: CDNMedia;
+ /** Playback length in milliseconds. */
playtime?: number;
+ /** Sample rate of the encoded audio; iLink voice defaults to 24000. */
+ sample_rate?: number;
+ /** Speech-to-text result provided by WeChat. */
text?: string;
}
diff --git a/packages/chat-adapter-wechat/src/voice.test.ts b/packages/chat-adapter-wechat/src/voice.test.ts
new file mode 100644
index 00000000000..2e25b895e39
--- /dev/null
+++ b/packages/chat-adapter-wechat/src/voice.test.ts
@@ -0,0 +1,141 @@
+import { encode } from 'silk-wasm';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ decodeWechatVoice,
+ DEFAULT_WECHAT_VOICE_SAMPLE_RATE,
+ isSilkStream,
+ normalizeSilkStream,
+ pcmS16ToWav,
+} from './voice';
+
+const SILK_MAGIC = Buffer.from('#!SILK_V3', 'ascii');
+
+/**
+ * 200ms 440Hz sine as mono pcm_s16le, then SILK-encoded by silk-wasm. The
+ * encoder emits the Tencent form (`0x02` + `#!SILK_V3`), same as WeChat.
+ */
+async function makeSilk(sampleRate = DEFAULT_WECHAT_VOICE_SAMPLE_RATE): Promise<Buffer> {
+ const samples = Math.round(sampleRate * 0.2);
+ const pcm = new Int16Array(samples);
+ for (let i = 0; i < samples; i++) {
+ pcm[i] = Math.round(Math.sin((2 * Math.PI * 440 * i) / sampleRate) * 8000);
+ }
+ const { data } = await encode(pcm.buffer, sampleRate);
+ return Buffer.from(data);
+}
+
+const readWavHeader = (wav: Buffer) => ({
+ audioFormat: wav.readUInt16LE(20),
+ bitsPerSample: wav.readUInt16LE(34),
+ channels: wav.readUInt16LE(22),
+ data: wav.subarray(36, 40).toString('ascii'),
+ dataSize: wav.readUInt32LE(40),
+ riff: wav.subarray(0, 4).toString('ascii'),
+ riffSize: wav.readUInt32LE(4),
+ sampleRate: wav.readUInt32LE(24),
+ wave: wav.subarray(8, 12).toString('ascii'),
+});
+
+describe('normalizeSilkStream / isSilkStream', () => {
+ it('keeps a Tencent-prefixed SILK stream as is', () => {
+ const prefixed = Buffer.concat([Buffer.from([0x02]), SILK_MAGIC, Buffer.from([1, 2, 3])]);
+ expect(isSilkStream(prefixed)).toBe(true);
+ expect(normalizeSilkStream(prefixed)).toBe(prefixed);
+ });
+
+ it('adds the 0x02 prefix to a bare SILK stream', () => {
+ const bare = Buffer.concat([SILK_MAGIC, Buffer.from([1, 2, 3])]);
+ expect(isSilkStream(bare)).toBe(true);
+ const normalized = normalizeSilkStream(bare);
+ expect(normalized[0]).toBe(0x02);
+ expect(normalized.subarray(1).equals(bare)).toBe(true);
+ });
+
+ it('rejects non-SILK bytes', () => {
+ expect(isSilkStream(Buffer.from('hello world'))).toBe(false);
+ expect(isSilkStream(Buffer.from([0x02, 0x00, 0x01]))).toBe(false);
+ expect(isSilkStream(Buffer.alloc(0))).toBe(false);
+ const raw = Buffer.from('hello world');
+ expect(normalizeSilkStream(raw)).toBe(raw);
+ });
+});
+
+describe('pcmS16ToWav', () => {
+ it('writes a valid mono 16-bit RIFF header', () => {
+ const pcm = new Uint8Array([0, 0, 1, 0, 2, 0, 3, 0]);
+ const wav = pcmS16ToWav(pcm, 16_000);
+ expect(wav.length).toBe(44 + pcm.length);
+ expect(readWavHeader(wav)).toEqual({
+ audioFormat: 1,
+ bitsPerSample: 16,
+ channels: 1,
+ data: 'data',
+ dataSize: 8,
+ riff: 'RIFF',
+ riffSize: 36 + 8,
+ sampleRate: 16_000,
+ wave: 'WAVE',
+ });
+ expect(wav.subarray(44).equals(Buffer.from(pcm))).toBe(true);
+ });
+});
+
+describe('decodeWechatVoice', () => {
+ it('decodes SILK to a playable WAV using the protocol default sample rate', async () => {
+ const silk = await makeSilk();
+ const result = await decodeWechatVoice(silk, { encode_type: 6 });
+
+ expect(result.mimeType).toBe('audio/wav');
+ expect(result.name).toBe('voice.wav');
+ const header = readWavHeader(result.buffer);
+ expect(header.riff).toBe('RIFF');
+ expect(header.sampleRate).toBe(DEFAULT_WECHAT_VOICE_SAMPLE_RATE);
+ // 200ms mono 16-bit @ 24kHz โ‰ˆ 9600 bytes; decoder pads to frame boundary.
+ expect(header.dataSize).toBeGreaterThanOrEqual(9600);
+ expect(result.durationMs).toBeGreaterThanOrEqual(200);
+ });
+
+ it('honours voice_item.sample_rate', async () => {
+ const silk = await makeSilk(16_000);
+ const result = await decodeWechatVoice(silk, { encode_type: 6, sample_rate: 16_000 });
+ expect(readWavHeader(result.buffer).sampleRate).toBe(16_000);
+ });
+
+ it('decodes a bare #!SILK_V3 stream even without encode_type', async () => {
+ const silk = await makeSilk();
+ expect(silk[0]).toBe(0x02);
+ const bare = silk.subarray(1);
+ const result = await decodeWechatVoice(bare);
+ expect(result.mimeType).toBe('audio/wav');
+ expect(readWavHeader(result.buffer).dataSize).toBeGreaterThanOrEqual(9600);
+ });
+
+ it('passes MP3 through untouched', async () => {
+ const mp3 = Buffer.from([0xff, 0xfb, 0x90, 0x00]);
+ const result = await decodeWechatVoice(mp3, { encode_type: 7 });
+ expect(result).toEqual({ buffer: mp3, mimeType: 'audio/mpeg', name: 'voice.mp3' });
+ });
+
+ it('falls back to raw audio/silk when the stream is not SILK', async () => {
+ const onError = vi.fn();
+ const raw = Buffer.from('not audio');
+ const result = await decodeWechatVoice(raw, undefined, onError);
+ expect(result).toEqual({ buffer: raw, mimeType: 'audio/silk', name: 'voice.silk' });
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('falls back and reports the error when SILK decoding fails', async () => {
+ const onError = vi.fn();
+ const corrupt = Buffer.concat([
+ Buffer.from([0x02]),
+ SILK_MAGIC,
+ Buffer.from([0xff, 0xff, 0xff]),
+ ]);
+ const result = await decodeWechatVoice(corrupt, { encode_type: 6 }, onError);
+ expect(result.mimeType).toBe('audio/silk');
+ expect(result.name).toBe('voice.silk');
+ expect(result.buffer).toBe(corrupt);
+ expect(onError).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/chat-adapter-wechat/src/voice.ts b/packages/chat-adapter-wechat/src/voice.ts
new file mode 100644
index 00000000000..c085413eaf3
--- /dev/null
+++ b/packages/chat-adapter-wechat/src/voice.ts
@@ -0,0 +1,127 @@
+/**
+ * Inbound WeChat voice decoding.
+ *
+ * iLink delivers voice items as raw SILK v3 (`voice_item.encode_type = 6`),
+ * which no browser `<audio>` element and almost no LLM audio input accepts.
+ * We decode it to 16-bit PCM WAV right after download so every downstream
+ * consumer (file storage, chat UI player, audio-capable models) gets a
+ * format it can actually play. See protocol-spec.md ยง5.6 / ยง8.5.
+ */
+import type { VoiceItem } from './types';
+
+/** Protocol default when `voice_item.sample_rate` is absent. */
+export const DEFAULT_WECHAT_VOICE_SAMPLE_RATE = 24_000;
+
+const SILK_MAGIC = Buffer.from('#!SILK_V3', 'ascii');
+
+/** `voice_item.encode_type` values from the iLink protocol (ยง5.6). */
+export const WechatVoiceEncodeType = {
+ AMR: 5,
+ MP3: 7,
+ SILK: 6,
+} as const;
+
+export interface DecodedWechatVoice {
+ buffer: Buffer;
+ /** Playback length in milliseconds when the decoder reports one. */
+ durationMs?: number;
+ mimeType: string;
+ name: string;
+}
+
+const TENCENT_SILK_PREFIX = 0x02;
+
+const hasSilkMagicAt = (input: Buffer, offset: number): boolean =>
+ input.length >= offset + SILK_MAGIC.length &&
+ input.subarray(offset, offset + SILK_MAGIC.length).equals(SILK_MAGIC);
+
+/**
+ * SILK v3 streams come in two shapes: the bare `#!SILK_V3` header, and the
+ * Tencent variant with a single `0x02` byte in front of it (what WeChat/QQ
+ * produce). silk-wasm's decoder only accepts the Tencent form, so make sure
+ * the prefix byte is present before handing the stream over.
+ */
+export function normalizeSilkStream(input: Buffer): Buffer {
+ if (input[0] === TENCENT_SILK_PREFIX && hasSilkMagicAt(input, 1)) return input;
+ if (hasSilkMagicAt(input, 0)) return Buffer.concat([Buffer.from([TENCENT_SILK_PREFIX]), input]);
+ return input;
+}
+
+export function isSilkStream(input: Buffer): boolean {
+ return hasSilkMagicAt(input, 0) || (input[0] === TENCENT_SILK_PREFIX && hasSilkMagicAt(input, 1));
+}
+
+/**
+ * Wrap mono 16-bit little-endian PCM in a 44-byte RIFF/WAVE header.
+ */
+export function pcmS16ToWav(pcm: Uint8Array, sampleRate: number): Buffer {
+ const channels = 1;
+ const bitsPerSample = 16;
+ const blockAlign = (channels * bitsPerSample) / 8;
+ const byteRate = sampleRate * blockAlign;
+
+ const header = Buffer.alloc(44);
+ header.write('RIFF', 0, 'ascii');
+ header.writeUInt32LE(36 + pcm.byteLength, 4);
+ header.write('WAVE', 8, 'ascii');
+ header.write('fmt ', 12, 'ascii');
+ header.writeUInt32LE(16, 16); // PCM fmt chunk size
+ header.writeUInt16LE(1, 20); // audio format: PCM
+ header.writeUInt16LE(channels, 22);
+ header.writeUInt32LE(sampleRate, 24);
+ header.writeUInt32LE(byteRate, 28);
+ header.writeUInt16LE(blockAlign, 32);
+ header.writeUInt16LE(bitsPerSample, 34);
+ header.write('data', 36, 'ascii');
+ header.writeUInt32LE(pcm.byteLength, 40);
+
+ return Buffer.concat([header, Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength)]);
+}
+
+const resolveSampleRate = (voiceItem?: VoiceItem): number => {
+ const rate = voiceItem?.sample_rate;
+ return typeof rate === 'number' && Number.isFinite(rate) && rate > 0
+ ? rate
+ : DEFAULT_WECHAT_VOICE_SAMPLE_RATE;
+};
+
+/**
+ * Turn downloaded voice bytes into a playable attachment.
+ *
+ * - SILK (by `encode_type` or magic header) โ†’ decoded to `audio/wav`.
+ * - MP3 passes through as `audio/mpeg`.
+ * - Anything else, or a SILK stream the decoder rejects, falls back to the
+ * raw bytes labelled `audio/silk` so the message still goes through; the
+ * caller may log the `error` for diagnostics.
+ */
+export async function decodeWechatVoice(
+ input: Buffer,
+ voiceItem?: VoiceItem,
+ onError?: (error: unknown) => void,
+): Promise<DecodedWechatVoice> {
+ if (voiceItem?.encode_type === WechatVoiceEncodeType.MP3) {
+ return { buffer: input, mimeType: 'audio/mpeg', name: 'voice.mp3' };
+ }
+
+ const looksLikeSilk =
+ isSilkStream(input) || voiceItem?.encode_type === WechatVoiceEncodeType.SILK;
+
+ if (looksLikeSilk) {
+ try {
+ const { decode } = await import('silk-wasm');
+ const sampleRate = resolveSampleRate(voiceItem);
+ const silk = normalizeSilkStream(input);
+ const { data, duration } = await decode(silk, sampleRate);
+ return {
+ buffer: pcmS16ToWav(data, sampleRate),
+ durationMs: duration,
+ mimeType: 'audio/wav',
+ name: 'voice.wav',
+ };
+ } catch (error) {
+ onError?.(error);
+ }
+ }
+
+ return { buffer: input, mimeType: 'audio/silk', name: 'voice.silk' };
+}
diff --git a/packages/context-engine/src/providers/BotPlatformContextInjector.ts b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
index c13f5d54bb4..faad1a18193 100644
--- a/packages/context-engine/src/providers/BotPlatformContextInjector.ts
+++ b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
@@ -10,6 +10,8 @@ const log = debug('context-engine:provider:BotPlatformContextInjector');
export interface BotPlatformContext {
/** Whether the platform can read chat history at runtime (`readMessages`). */
canReadHistory?: boolean;
+ /** Identifiers of the conversation this run replies in (`lobe-message` args). */
+ currentChannel?: BotPlatformInfo['currentChannel'];
platformName: string;
/** Pre-injected recent same-channel history for platforms without history-read. */
recentChannelHistory?: BotPlatformInfo['recentChannelHistory'];
diff --git a/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snap
index a719629183f..4d49538b327 100644
--- a/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snap
+++ b/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snap
@@ -193,6 +193,35 @@ Briefly inform the user about these issues in your response:
</bot_platform_context>"
`;
+exports[`formatBotPlatformContext > renders the current conversation identifiers for the message tool 1`] = `
+"<bot_platform_context platform="Lark">
+You are a participant in a **Lark** conversation โ€” not an external assistant being consulted.
+
+<behavior>
+- Act like a knowledgeable group member: respond naturally, stay on topic, and match the conversational tone.
+- When the user's message references prior context you don't have (e.g. "what do you think?", "summarize this", "look at that"), use \`readMessages\` IMMEDIATELY to fetch recent chat history before responding. Never ask the user to repeat what was already said in the channel.
+- When you lack enough context to give a useful answer, silently read more history rather than asking clarifying questions โ€” the answer is usually already in the chat.
+- Keep responses concise and conversational โ€” IM platforms have character limits and small viewports. Avoid long preambles or formal structure unless the question demands it.
+- Do NOT reference UI elements from other environments (e.g. "check the sidebar", "click the button above").
+</behavior>
+
+<message_delivery>
+Your text response is AUTOMATICALLY delivered to the current conversation โ€” the runtime pipeline handles it.
+Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.
+\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.
+</message_delivery>
+
+<current_conversation platform="lark" channelId="oc_84983ff6516d731e">
+These are the EXACT argument values for any \`lobe-message\` call that targets the conversation you are currently in:
+- \`platform\`: "lark"
+- \`channelId\`: "oc_84983ff6516d731e"
+
+You already have everything \`readMessages\` needs. Call it with these two values the moment you need prior context.
+NEVER ask the user for a chat / channel / group ID, and never call \`listChannels\` to look up the current one โ€” it is right here.
+</current_conversation>
+</bot_platform_context>"
+`;
+
exports[`formatBotPlatformContext > sanitizes user-controlled topic/message text to prevent prompt injection 1`] = `
"<bot_platform_context platform="WeChat">
You are a participant in a **WeChat** conversation โ€” not an external assistant being consulted.
diff --git a/packages/prompts/src/prompts/botPlatformContext/index.test.ts b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
index 93f81f61271..9c76bd87d5b 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.test.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.test.ts
@@ -22,6 +22,54 @@ describe('formatBotPlatformContext', () => {
expect(result).toMatchSnapshot();
});
+ it('renders the current conversation identifiers for the message tool', () => {
+ const result = formatBotPlatformContext({
+ currentChannel: { id: 'oc_84983ff6516d731e', platformId: 'lark' },
+ platformName: 'Lark',
+ supportsMarkdown: true,
+ });
+
+ // The whole point of the block: readMessages' required `channelId` is
+ // handed over, so the model never has to ask the user for a group ID.
+ expect(result).toContain(
+ '<current_conversation platform="lark" channelId="oc_84983ff6516d731e">',
+ );
+ expect(result).toContain('`channelId`: "oc_84983ff6516d731e"');
+ expect(result).toMatchSnapshot();
+ });
+
+ it('keeps the channel block on platforms without history-read, minus the readMessages line', () => {
+ const result = formatBotPlatformContext({
+ canReadHistory: false,
+ currentChannel: { id: 'oc_nohistory', platformId: 'wechat' },
+ platformName: 'WeChat',
+ supportsMarkdown: false,
+ });
+
+ expect(result).toContain('channelId="oc_nohistory"');
+ expect(result).not.toContain('You already have everything `readMessages` needs');
+ });
+
+ it('escapes channel identifiers so they cannot break out of the XML block', () => {
+ const result = formatBotPlatformContext({
+ currentChannel: { id: 'oc_"><injected>', platformId: 'lark' },
+ platformName: 'Lark',
+ supportsMarkdown: true,
+ });
+
+ expect(result).not.toContain('<injected>');
+ expect(result).toContain('&quot;&gt;&lt;injected&gt;');
+ });
+
+ it('omits the current-conversation block when the channel is unknown', () => {
+ const result = formatBotPlatformContext({
+ platformName: 'Lark',
+ supportsMarkdown: true,
+ });
+
+ expect(result).not.toContain('<current_conversation');
+ });
+
it('renders pre-injected recent topics with per-topic detail', () => {
const result = formatBotPlatformContext({
canReadHistory: false,
diff --git a/packages/prompts/src/prompts/botPlatformContext/index.ts b/packages/prompts/src/prompts/botPlatformContext/index.ts
index a8ee6a91c05..c7d23cab910 100644
--- a/packages/prompts/src/prompts/botPlatformContext/index.ts
+++ b/packages/prompts/src/prompts/botPlatformContext/index.ts
@@ -21,6 +21,22 @@ export interface RecentChannelHistory {
topics: RecentChannelTopic[];
}
+/**
+ * Identity of the conversation the bot is currently replying in, expressed in
+ * the exact terms the `lobe-message` tool takes.
+ *
+ * Without this the model holds a `readMessages` tool whose `channelId` is a
+ * required parameter it has no way to fill: most platforms have no
+ * `listChannels` to discover it with, so it ends up asking the user to paste a
+ * chat ID (the Feishu "ไฝ ๆ–นไพฟๆ‹ฟไธ€ไธ‹็พค ID ๅ—" case).
+ */
+export interface CurrentBotChannel {
+ /** Channel / chat / conversation id, as `readMessages.channelId` expects it. */
+ id: string;
+ /** Platform id for the tool's `platform` enum (e.g. `lark`, not `Lark`). */
+ platformId: string;
+}
+
export interface BotPlatformInfo {
/**
* Whether the platform can read chat history at runtime via `readMessages`.
@@ -29,6 +45,8 @@ export interface BotPlatformInfo {
* to true.
*/
canReadHistory?: boolean;
+ /** Identifiers of the conversation this run is replying in. */
+ currentChannel?: CurrentBotChannel;
platformName: string;
/** Pre-injected recent same-channel history (cross-session). */
recentChannelHistory?: RecentChannelHistory;
@@ -37,6 +55,17 @@ export interface BotPlatformInfo {
warnings?: string[];
}
+/**
+ * Sanitize user-controlled text before embedding it in the XML-ish prompt, so
+ * titles / message bodies / channel ids containing tags or quotes can't break
+ * out or inject.
+ */
+const sanitize = (text: string) =>
+ text.replaceAll(
+ /[<>&"']/g,
+ (ch) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' })[ch]!,
+ );
+
/**
* Format bot platform context into a system-level instruction.
*
@@ -45,6 +74,7 @@ export interface BotPlatformInfo {
*/
export const formatBotPlatformContext = ({
canReadHistory = true,
+ currentChannel,
platformName,
recentChannelHistory,
supportsMarkdown,
@@ -79,6 +109,30 @@ export const formatBotPlatformContext = ({
'</message_delivery>',
];
+ // The identifiers of the conversation we're standing in. `readMessages` takes
+ // `channelId` as a REQUIRED parameter, and most platforms have no
+ // `listChannels` for the model to discover it with โ€” without this block it
+ // can only ask the user to paste a chat ID, which is exactly the failure this
+ // exists to prevent. Rendered whenever we know the channel, including on
+ // platforms without history-read (the id still serves reactions / channel info).
+ if (currentChannel?.id) {
+ lines.push(
+ '',
+ `<current_conversation platform="${sanitize(currentChannel.platformId)}" channelId="${sanitize(currentChannel.id)}">`,
+ 'These are the EXACT argument values for any `lobe-message` call that targets the conversation you are currently in:',
+ `- \`platform\`: "${sanitize(currentChannel.platformId)}"`,
+ `- \`channelId\`: "${sanitize(currentChannel.id)}"`,
+ '',
+ ...(canReadHistory
+ ? [
+ 'You already have everything `readMessages` needs. Call it with these two values the moment you need prior context.',
+ ]
+ : []),
+ 'NEVER ask the user for a chat / channel / group ID, and never call `listChannels` to look up the current one โ€” it is right here.',
+ '</current_conversation>',
+ );
+ }
+
if (!supportsMarkdown) {
lines.push(
'',
@@ -96,14 +150,6 @@ export const formatBotPlatformContext = ({
);
}
- // Sanitize user-controlled text before embedding it in the XML-ish prompt, so
- // titles / message bodies containing tags or quotes can't break out or inject.
- const sanitize = (text: string) =>
- text.replaceAll(
- /[<>&"']/g,
- (ch) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' })[ch]!,
- );
-
const recentTopics = recentChannelHistory?.topics?.filter((t) => t?.id) ?? [];
if (recentTopics.length > 0) {
lines.push(
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
index f431567268b..6db6f36e3a7 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
@@ -8,6 +8,7 @@ interface SendToMessengerParams {
}
const mocks = vi.hoisted(() => ({
+ activeWorkspaceId: null as string | null,
confirmModal: vi.fn(),
deleteResource: vi.fn<() => Promise<void>>(async () => {}),
dropTreeNodes: vi.fn(async () => undefined),
@@ -49,6 +50,10 @@ vi.mock('@/store/file', () => ({
),
}));
vi.mock('@/store/library', () => ({ useKnowledgeBaseStore: () => [vi.fn(), vi.fn()] }));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,
+}));
+
vi.mock('@/store/tree', () => ({
useTreeStore: Object.assign(() => vi.fn(), {
getState: () => ({ dropNodes: mocks.dropTreeNodes, revalidate: mocks.revalidateTree }),
@@ -69,6 +74,35 @@ const pushedFile = () => mocks.useSendToMessengerMenuItem.mock.calls.at(-1)![0].
beforeEach(() => {
vi.clearAllMocks();
+ mocks.activeWorkspaceId = null;
+});
+
+describe('useFileItemDropdown โ€” visibility toggles', () => {
+ const ownFile = (visibility: 'private' | 'public') =>
+ renderHook(() => useFileItemDropdown({ ...baseParams, userId: 'user-1', visibility } as any));
+ const keys = (result: { current: { menuItems: () => any[] } }) =>
+ result.current.menuItems().map((item) => item?.key);
+
+ it('hides "Make private" and "Publish to workspace" in personal mode', () => {
+ // Regression: `files.visibility` defaults to 'public' even when
+ // `workspace_id IS NULL`, so every personal file offered "Make private".
+ expect(keys(ownFile('public').result)).not.toContain('makePrivate');
+ expect(keys(ownFile('private').result)).not.toContain('publishToWorkspace');
+ });
+
+ it('offers the matching toggle for the creator inside a workspace', () => {
+ mocks.activeWorkspaceId = 'ws-1';
+ expect(keys(ownFile('public').result)).toContain('makePrivate');
+ expect(keys(ownFile('private').result)).toContain('publishToWorkspace');
+ });
+
+ it("never offers the toggles on another member's workspace file", () => {
+ mocks.activeWorkspaceId = 'ws-1';
+ const { result } = renderHook(() =>
+ useFileItemDropdown({ ...baseParams, userId: 'another-member', visibility: 'public' } as any),
+ );
+ expect(keys(result)).not.toContain('makePrivate');
+ });
});
describe('useFileItemDropdown โ€” messenger push id', () => {
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index fd78b67f238..e7906e6909a 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -18,6 +18,7 @@ import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { shallow } from 'zustand/shallow';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import RepoIcon from '@/components/LibIcon';
import { useSendToMessengerMenuItem } from '@/features/Messenger/PushResourceModal/useSendToMessengerMenuItem';
import { useKnowledgeBaseListContext } from '@/features/ResourceManager/components/KnowledgeBaseListProvider';
@@ -99,6 +100,7 @@ export const useFileItemDropdown = ({
const appOrigin = useAppOrigin();
const { allowed: canEditResources } = usePermission('edit_own_content');
const currentUserId = useUserStore(userProfileSelectors.userId);
+ const activeWorkspaceId = useActiveWorkspaceId();
const {
deleteResource,
@@ -272,23 +274,23 @@ export const useFileItemDropdown = ({
const hasKnowledgeBaseActions = libraryRelatedActions.some(Boolean);
- // Only the creator of a still-private file (not a folder, since folders
- // live in the `documents` table and have their own publish flow) sees the
- // "Publish to workspace" entry. Mirrors the agent / task one-way publish.
- const isOwnPrivateFile =
+ // Visibility is a workspace concept: `files.visibility` defaults to
+ // `'public'` even for personal-mode rows (`workspace_id IS NULL`), where it
+ // is meaningless. Without this gate every personal file would offer
+ // "Make private" (and, once flipped, "Publish to workspace").
+ const isOwnWorkspaceFile =
+ !!activeWorkspaceId &&
sourceType !== DERIVED_DOCUMENT_SOURCE_TYPE &&
!isFolder &&
- visibility === 'private' &&
!!currentUserId &&
userId === currentUserId;
+ // Only the creator of a still-private file (not a folder, since folders
+ // live in the `documents` table and have their own publish flow) sees the
+ // "Publish to workspace" entry. Mirrors the agent / task one-way publish.
+ const isOwnPrivateFile = isOwnWorkspaceFile && visibility === 'private';
// Bidirectional counterpart: workspace-public files owned by the caller
// can be pulled back to private via the same guarded server path.
- const isOwnPublicFile =
- sourceType !== DERIVED_DOCUMENT_SOURCE_TYPE &&
- !isFolder &&
- visibility === 'public' &&
- !!currentUserId &&
- userId === currentUserId;
+ const isOwnPublicFile = isOwnWorkspaceFile && visibility === 'public';
return (
[
@@ -490,6 +492,7 @@ export const useFileItemDropdown = ({
}, [
addFilesToKnowledgeBase,
appOrigin,
+ activeWorkspaceId,
canEditResources,
currentUserId,
deleteResource,