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.

✨ feat: support multi media and multiple connection mode (#13624)

Rdmclin2475622a4b969
diff --git a/.agents/skills/bot/SKILL.md b/.agents/skills/bot/SKILL.md
new file mode 100644
index 00000000000..e81e687d9ea
--- /dev/null
+++ b/.agents/skills/bot/SKILL.md
@@ -0,0 +1,298 @@
+---
+name: bot
+description: 'Bot platform architecture (Discord, Slack, Telegram, Feishu/Lark, QQ, WeChat). Use when working on inbound webhooks, Chat SDK message routing, agent execution from chat platforms, queue-mode callbacks, gateway lifecycle (websocket/polling), bot provider CRUD/credentials, or platform-specific clients/adapters/schemas. Triggers on bot, channel, webhook, mention, Chat SDK, agent bot provider, gateway, bot-callback, qstash bot.'
+---
+
+# Bot System
+
+> **Last updated: 2026-04-08.** Implementation evolves quickly — this doc is a map, not the source of truth. Always read the key files below to verify behavior, especially per-platform quirks. Update this doc when the architecture changes.
+
+LobeChat agents can answer inside external chat platforms. Inbound messages flow through the Chat SDK (`chat` npm package), get routed to the right agent by `(platform, applicationId)`, executed via `AiAgentService`, and replied back through a per-platform `PlatformClient`. There are **two execution modes** (in-memory vs queue/QStash) and **three connection modes** (`webhook`, `websocket`, `polling`).
+
+## Supported Platforms
+
+| Platform | id | Default mode | Markdown | Edit | Notes |
+| -------- | ---------- | ------------------------------- | ----------------- | ------ | -------------------------------------------------------------------------------------- |
+| Discord | `discord` | `websocket` | yes | yes | Persistent gateway via Chat SDK adapter; reaction-thread quirks; native slash commands |
+| Slack | `slack` | `websocket` (Socket Mode) | yes (mrkdwn) | yes | Multi-mode — user can pick `webhook` per provider |
+| Telegram | `telegram` | `webhook` | yes (HTML) | yes | `setMyCommands` menu via `registerBotCommands` |
+| Feishu | `feishu` | `websocket` (Lark SDK WSClient) | **no** (stripped) | yes | Multi-mode; shared client with Lark |
+| Lark | `lark` | `websocket` | **no** | yes | Same client/schema as Feishu, different domain |
+| QQ | `qq` | `websocket` | **no** | **no** | All replies are final-only |
+| WeChat | `wechat` | `polling` (iLink long-poll) | **no** | **no** | 10-minute gateway window |
+
+`supportsMarkdown=false` ⇒ outbound markdown is stripped to plain text via `stripMarkdown` and the AI is told not to use markdown. `supportsMessageEdit=false` ⇒ no progress edits — only the final reply is sent.
+
+**Multi-mode connection** — Slack/Feishu/Lark/QQ shipped as websocket but support `webhook` per-provider via `settings.connectionMode`. Legacy rows without that field stay on `webhook` (see `LEGACY_WEBHOOK_PLATFORMS` in `platforms/utils.ts`) — **never add new platforms to that list**.
+
+## Inbound Flow (one webhook → reply)
+
+```
+Platform server
+ │ POST /api/agent/webhooks/[platform]/[appId]
+ ▼
+route.ts ── catch-all `[[...appId]]` route
+ │
+ ▼
+BotMessageRouter (singleton)
+ │ • lazy-loads bot per `platform:applicationId`
+ │ • merges schema defaults + provider.settings (mergeWithDefaults)
+ │ • builds Chat SDK Chat<any> with createIoRedisState (if Redis available)
+ │ • registerHandlers: onNewMention / onSubscribedMessage / onNewMessage(/.dm)
+ │ • registerCommands: /new (reset topic), /stop (interrupt)
+ │
+ ▼
+chatBot.webhooks[platform](req) ← Chat SDK parses → fires events
+ │
+ ▼
+AgentBridgeService.handleMention / handleSubscribedMessage
+ │ • activeThreads guard (no duplicate runs per thread)
+ │ • adds 👀 reaction (eyes), startTyping
+ │ • merges debounced/queued skipped messages (mergeSkippedMessages)
+ │ • extractFiles (buffer → fetchData → url)
+ │ • formatPrompt (sanitize mention + speaker tag + referenced_message)
+ │
+ ├── In-memory mode ──► AiAgentService.execAgent({ stepCallbacks })
+ │ → onAfterStep edits progress message live
+ │ → onComplete edits final reply, splits via splitMessage(charLimit)
+ │
+ └── Queue mode (isQueueAgentRuntimeEnabled) ──► execAgent({ stepWebhook, completionWebhook, webhookDelivery: 'qstash' })
+ → returns immediately, callbacks land at /api/agent/webhooks/bot-callback
+```
+
+The router caches loaded bots in memory. Cache is **invalidated** by `BotMessageRouter.invalidateBot(platform, appId)` whenever the TRPC `update`/`delete` mutations run, so new credentials/settings take effect on the next webhook.
+
+## Execution Modes
+
+### In-memory (default)
+
+`AgentBridgeService.executeWithInMemoryCallbacks` wraps `execAgent` with `stepCallbacks`. Lives in one process — Promise-based wait, 30-min timeout, edits the same `progressMessage` after every step. Topic title is summarized inline via `SystemAgentService`.
+
+### Queue (`isQueueAgentRuntimeEnabled`)
+
+`AgentBridgeService.executeWithWebhooks`:
+
+1. Posts the `renderStart` placeholder, captures `progressMessageId`.
+2. Calls `execAgent` with `stepWebhook` and `completionWebhook` pointing at `${INTERNAL_APP_URL ?? APP_URL}/api/agent/webhooks/bot-callback`, plus `webhookDelivery: 'qstash'`.
+3. Returns immediately; the bridge `finally` block keeps the active-thread marker held until the `completion` callback fires.
+
+`/api/agent/webhooks/bot-callback/route.ts` verifies the QStash signature and hands off to `BotCallbackService.handleCallback`:
+
+- `type: 'step'` → `handleStep` re-renders `renderStepProgress`, edits `progressMessageId` (skipped if `displayToolCalls=false` or platform `supportsMessageEdit=false`).
+- `type: 'completion'` → `handleCompletion` writes the final reply (or error/interrupted message), removes the 👀 reaction, clears active-thread tracker, fires async `summarizeTopicTitle`.
+
+`BotCallbackService.createMessenger` reloads provider + credentials from DB and rebuilds a `PlatformClient` per call (no in-memory state).
+
+## Commands
+
+Defined in `BotMessageRouter.buildCommands` and registered via two paths:
+
+- **Native slash commands** (Slack/Discord): `bot.onSlashCommand('/<name>', ...)`
+- **Text-based fallback** (Telegram/Feishu/QQ/Lark/WeChat): `bot.onNewMessage(/^\/(new|stop)(\s|$|@)/, ...)` plus a per-mention `tryDispatch` so commands work even before subscribe.
+
+Built-in commands:
+
+- `/new` — clears `topicId` in thread state, next message starts a fresh topic.
+- `/stop` — interrupts the active execution (calls `AiAgentService.interruptTask` if `operationId` is known; otherwise queues a deferred stop via `requestStop`/`pendingStopThreads`, also aborts the startup phase via `startupControllers`).
+
+To add a command, append to `buildCommands` — it auto-registers everywhere; on Telegram it also surfaces in the `/` menu via `client.registerBotCommands` → `setMyCommands`.
+
+## Active-thread State (statics on `AgentBridgeService`)
+
+- `activeThreads: Set<threadId>` — prevents duplicate runs per thread (must guard before stale-topic check, otherwise concurrent messages can drop).
+- `activeOperations: Map<threadId, operationId>` — needed by `/stop` once `execAgent` returns.
+- `startupControllers: Map<threadId, AbortController>` — cancels pre-`operationId` work (topic/tool prep).
+- `pendingStopThreads: Set<threadId>` — `/stop` arrived before `operationId` existed; consumed once available.
+
+In **queue mode**, the bridge `finally` skips cleanup so the marker persists until `BotCallbackService.handleCompletion` calls `clearActiveThread`.
+
+## Topic Lifecycle in Threads
+
+- `handleMention` always treats the message as the start of a new conversation.
+- `handleSubscribedMessage` reads `topicId` from `thread.state`. If the topic is stale (`> 4 hours` since `updatedAt`), state is cleared and it retries as a fresh mention.
+- If `execAgent` fails with a Postgres FK violation on `topic_id` (cached topic was deleted), the bridge clears state and retries as a mention.
+- `subscribe()` is gated by `client.shouldSubscribe(threadId)` — Discord top-level channels return `false` so we don't follow up there.
+
+## Attachments
+
+`AgentBridgeService.extractFiles` resolves attachments in priority order:
+
+1. `att.buffer` — already downloaded by the adapter (WeChat/Feishu inbound).
+2. `att.fetchData()` — adapter-provided lazy download with auth (Telegram, Slack, Feishu history). **Required** when URLs are token-protected — naive `fetch(url)` later in `ingestAttachment.ts` has no credentials.
+3. `att.url` — public CDN fallback (Discord, public QQ).
+
+`inferMimeType` / `inferName` patch Telegram-style `photo` payloads (no `mimeType`/`name` from Bot API → defaults to `image/jpeg`) so vision models actually see them. Quoted-message attachments are also pulled from `raw.referenced_message.attachments` (Discord).
+
+## Concurrency
+
+`settings.concurrency` is `'queue'` or `'debounce'`:
+
+- `debounce` → Chat SDK debounces inbound messages by `debounceMs`; `mergeSkippedMessages` joins skipped texts/attachments into the current message before handing to the agent.
+- `queue` → Chat SDK serializes per-thread; the bridge's own `activeThreads` set is still required because in queue mode the SDK lock releases before the agent finishes.
+
+## Gateway (persistent platforms)
+
+Webhook platforms run fine in serverless functions. Persistent platforms (`websocket`, `polling`) need a long-running listener — that's the **gateway**.
+
+**`GatewayService.startClient(platform, appId, userId)`** (`src/server/services/gateway/index.ts`):
+
+- On Vercel + persistent mode → `BotConnectQueue.push` (Redis hash) and mark runtime status `queued`. The cron picks it up.
+- On Vercel + webhook mode → start the client inline (one HTTP call).
+- Off-Vercel → `GatewayManager` singleton holds long-lived clients in process.
+
+**`GET /api/agent/gateway/route.ts`** (cron, `Bearer ${CRON_SECRET}`):
+
+- Iterates registered platforms and starts every enabled persistent provider with `durationMs = 10min`, then in `after(...)` polls `BotConnectQueue` every 30s for new connect requests, until the window expires.
+- `getEffectiveConnectionMode(platform, settings)` is the only place that resolves per-provider mode — respect it everywhere.
+
+**`POST /api/agent/gateway/start/route.ts`** is the non-Vercel `ensureRunning` entry point (`Bearer ${KEY_VAULTS_SECRET}`).
+
+**Runtime status** is stored in Redis at `bot:runtime-status:platform:appId` with TTL ≈ `durationMs + 60s`. States: `starting | connected | disconnected | failed | queued`. Updated by each `PlatformClient.start/stop` and by the gateway service.
+
+## Platform Definitions
+
+Each platform exposes a `PlatformDefinition` registered in `platforms/index.ts`:
+
+```ts
+{
+ id: 'discord',
+ name: 'Discord',
+ connectionMode: 'websocket', // recommended default
+ schema: FieldSchema[], // applicationId + credentials + settings
+ clientFactory: new DiscordClientFactory(),
+ supportsMarkdown?: boolean, // default true
+ supportsMessageEdit?: boolean, // default true
+ documentation?: { portalUrl, setupGuideUrl },
+}
+```
+
+`schema` drives both server validation (`mergeWithDefaults`, `extractDefaults`) **and** the auto-generated UI form. Top-level keys `applicationId` / `credentials` / `settings` map to DB columns. Common settings fields live in `platforms/const.ts` (`displayToolCallsField`, `serverIdField`, `userIdField`).
+
+Each platform implements `PlatformClient` (see `platforms/types.ts`):
+
+- Lifecycle: `start(opts?)`, `stop()`
+- Inbound: `createAdapter()` → Chat SDK adapter map
+- Outbound: `getMessenger(platformThreadId)` → `{ createMessage, editMessage, removeReaction, triggerTyping, updateThreadName? }`
+- Formatting: `formatMarkdown?`, `formatReply?` (usage-stats footer when `showUsageStats`)
+- Helpers: `extractChatId`, `parseMessageId`, `sanitizeUserInput`, `shouldSubscribe`, `resolveReactionThreadId`
+- Optional patches: `applyChatPatches(chatBot)` (Discord uses this for `forwardedInteractions` + `threadRecovery`)
+- Optional menu: `registerBotCommands(commands)` (Telegram `setMyCommands`)
+
+`ClientFactory.validateCredentials` is called from the TRPC `testConnection` mutation — implement it to hit the platform API and return useful per-field errors.
+
+## Database
+
+**Schema** (`packages/database/src/schemas/agentBotProvider.ts`):
+
+```ts
+agent_bot_providers (
+ id uuid pk,
+ agent_id text fk → agents.id (cascade),
+ user_id text fk → users.id (cascade),
+ platform varchar(50), // 'discord' | 'slack' | …
+ application_id varchar(255),
+ credentials text, // KeyVaults-encrypted JSON
+ settings jsonb default '{}',
+ enabled boolean default true,
+ …timestamps
+)
+unique (platform, application_id)
+```
+
+**Model** (`packages/database/src/models/agentBotProvider.ts`):
+
+- User-scoped: `create / update / delete / query / findById / findByAgentId / findEnabledByApplicationId`. Credentials are encrypted/decrypted via the injected `KeyVaultsGateKeeper`.
+- Static (system-wide): `findByPlatformAndAppId`, `findEnabledByPlatform` — used by webhook routing & gateway sync, since they don't have a user context yet.
+
+**TRPC router** (`src/server/routers/lambda/agentBotProvider.ts`):
+
+| Procedure | Notes | |
+| -------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------ |
+| `listPlatforms` | Returns `SerializedPlatformDefinition[]` (no `clientFactory`) | |
+| `create` / `update` / `delete` | Calls `BotMessageRouter.invalidateBot` + `GatewayService.stopClient` so changes take effect | |
+| `list` / `getByAgentId` / `getRuntimeStatus` | Decorate rows with Redis runtime status | |
+| `connectBot` | Returns \`{ status: 'started' | 'queued' }\` |
+| `testConnection` | Calls `clientFactory.validateCredentials` | |
+| `wechatGetQrCode` / `wechatPollQrStatus` | iLink onboarding flow | |
+
+Client service: `src/services/agentBotProvider.ts`. Store actions: `src/store/agent/slices/bot/action.ts`. UI: `src/routes/(main)/agent/channel/{list,detail}` — settings form is auto-generated from each platform's `schema`.
+
+## Reply Templates
+
+`src/server/services/bot/replyTemplate.ts` exports `renderStart`, `renderStepProgress`, `renderFinalReply`, `renderError`, `renderStopped`, `splitMessage`. Step progress carries elapsed time, last LLM content, last tools, totals; final reply uses `client.formatMarkdown` then `client.formatReply` (which optionally appends `formatUsageStats`). `splitMessage(text, charLimit)` chunks at paragraph → line → hard cut.
+
+`src/server/services/bot/ackPhrases/` provides randomized ack phrases.
+
+## Key Files
+
+```plaintext
+Webhook routes:
+ src/app/(backend)/api/agent/webhooks/[platform]/[[...appId]]/route.ts — inbound catch-all
+ src/app/(backend)/api/agent/webhooks/bot-callback/route.ts — qstash bot callback
+ src/app/(backend)/api/agent/gateway/route.ts — cron gateway (10min window)
+ src/app/(backend)/api/agent/gateway/start/route.ts — non-Vercel ensureRunning
+
+Bot service:
+ src/server/services/bot/index.ts — barrel
+ src/server/services/bot/BotMessageRouter.ts — lazy bot loading + handler registration + commands
+ src/server/services/bot/AgentBridgeService.ts — Chat SDK ↔ AiAgentService bridge, both exec modes
+ src/server/services/bot/BotCallbackService.ts — qstash callback handler
+ src/server/services/bot/formatPrompt.ts — speaker tag + referenced_message + sanitize
+ src/server/services/bot/replyTemplate.ts — render*/splitMessage
+ src/server/services/bot/ackPhrases/ — randomized acks
+ src/server/services/bot/__tests__/ — unit tests for the above
+
+Platform abstraction:
+ src/server/services/bot/platforms/index.ts — registry singleton + exports
+ src/server/services/bot/platforms/types.ts — PlatformClient/Definition/FieldSchema/ClientFactory
+ src/server/services/bot/platforms/registry.ts — PlatformRegistry class
+ src/server/services/bot/platforms/utils.ts — mergeWithDefaults, getEffectiveConnectionMode, formatUsageStats, runtimeKey
+ src/server/services/bot/platforms/const.ts — shared FieldSchema fragments (displayToolCalls, serverId, userId)
+ src/server/services/bot/platforms/stripMarkdown.ts — used by no-markdown platforms
+
+Per-platform (each ships definition.ts, schema.ts, client.ts, const.ts, protocol-spec.md):
+ src/server/services/bot/platforms/discord/ — websocket gateway + chat patches
+ src/server/services/bot/platforms/slack/ — multi-mode (Socket Mode / webhook), markdownToMrkdwn
+ src/server/services/bot/platforms/telegram/ — webhook, markdownToHTML, registerBotCommands
+ src/server/services/bot/platforms/feishu/ — feishu + lark share client/schema (definitions/{feishu,lark,shared}.ts)
+ src/server/services/bot/platforms/qq/ — websocket, no markdown, no edit
+ src/server/services/bot/platforms/wechat/ — long-poll, no markdown, no edit
+
+Gateway:
+ src/server/services/gateway/index.ts — GatewayService (Vercel-aware startClient/stopClient)
+ src/server/services/gateway/GatewayManager.ts — long-running client registry (non-Vercel)
+ src/server/services/gateway/botConnectQueue.ts — Redis hash queue with TTL
+ src/server/services/gateway/runtimeStatus.ts — Redis bot:runtime-status keys
+
+Database:
+ packages/database/src/schemas/agentBotProvider.ts — agent_bot_providers table
+ packages/database/src/models/agentBotProvider.ts — encrypted CRUD + system-wide finders
+
+TRPC + client:
+ src/server/routers/lambda/agentBotProvider.ts — TRPC router
+ src/services/agentBotProvider.ts — client wrapper
+ src/store/agent/slices/bot/action.ts — Zustand actions
+
+UI:
+ src/routes/(main)/agent/channel/list.tsx — channel list
+ src/routes/(main)/agent/channel/detail/ — auto-generated form (Header/Body/Footer)
+ src/routes/(main)/agent/channel/const.ts — platform icons
+
+Types & runtime status:
+ src/types/botRuntimeStatus.ts — BOT_RUNTIME_STATUSES enum + snapshot type
+```
+
+## Adding a New Platform
+
+1. Create `src/server/services/bot/platforms/<id>/`:
+ - `definition.ts` — `PlatformDefinition` registered in `platforms/index.ts`
+ - `schema.ts` — `FieldSchema[]` (`applicationId` + `credentials` + `settings`); reuse fragments from `../const.ts`
+ - `client.ts` — `class XClientFactory extends ClientFactory` returning a `PlatformClient` (lifecycle + adapter + messenger + helpers)
+ - `const.ts` — `DEFAULT_X_CONNECTION_MODE`, history limits, etc.
+ - `protocol-spec.md` — protocol notes (every existing platform has one)
+2. Pick the right `connectionMode` — webhook is much simpler if the platform supports it.
+3. If the platform can't render markdown, set `supportsMarkdown: false` and implement `formatMarkdown` via `stripMarkdown`.
+4. If it can't edit messages, set `supportsMessageEdit: false` — `BotCallbackService` will skip step edits and only send the final reply.
+5. Implement `validateCredentials` so the UI's "Test connection" button gives useful errors.
+6. Add the platform icon in `src/routes/(main)/agent/channel/const.ts` and register the platform in `src/server/services/bot/platforms/index.ts`.
+7. Add i18n keys under `channel.*` in `src/locales/default/setting.ts` (or wherever the channel namespace lives) — the schema's `label`/`description`/`placeholder`/`enumLabels` are i18n keys.
diff --git a/.agents/skills/local-testing/SKILL.md b/.agents/skills/local-testing/SKILL.md
index e27c54874b2..e5a7c1092ce 100644
--- a/.agents/skills/local-testing/SKILL.md
+++ b/.agents/skills/local-testing/SKILL.md
@@ -379,621 +379,30 @@ agent-browser --auto-connect snapshot -i
# Part 2: osascript (Native macOS App Bot Testing)
-Use AppleScript via `osascript` to control native macOS desktop apps for bot testing. This works with any app that supports macOS Accessibility, without needing CDP or Chromium.
+Use AppleScript via `osascript` to control native macOS desktop apps for bot testing. Works with any app that supports macOS Accessibility, no CDP or Chromium needed.
-## Core osascript Patterns
+The pattern is the same for every platform:
-### Activate an App
+1. **Activate** the app (`tell application "X" to activate`)
+2. **Navigate** to a channel/chat (Quick Switcher `Cmd+K` or Search `Cmd+F`)
+3. **Send** a message (clipboard paste `Cmd+V` + Enter)
+4. **Wait** for the bot response
+5. **Screenshot** for verification (`screencapture` + `Read` tool)
-```bash
-osascript -e 'tell application "Discord" to activate'
-```
-
-### Type Text
-
-```bash
-# Type character by character (reliable, but slow for long text)
-osascript -e 'tell application "System Events" to keystroke "Hello world"'
-
-# Press Enter
-osascript -e 'tell application "System Events" to key code 36'
-
-# Press Tab
-osascript -e 'tell application "System Events" to key code 48'
-
-# Press Escape
-osascript -e 'tell application "System Events" to key code 53'
-```
-
-### Paste from Clipboard (fast, for long text)
-
-```bash
-# Set clipboard and paste — much faster than keystroke for long messages
-osascript -e 'set the clipboard to "Your long message here"'
-osascript -e 'tell application "System Events" to keystroke "v" using command down'
-```
-
-Or in one shot:
-
-```bash
-osascript -e '
-set the clipboard to "Your long message here"
-tell application "System Events" to keystroke "v" using command down
-'
-```
-
-### Keyboard Shortcuts
-
-```bash
-# Cmd+K (quick switcher in Discord/Slack)
-osascript -e 'tell application "System Events" to keystroke "k" using command down'
-
-# Cmd+F (search)
-osascript -e 'tell application "System Events" to keystroke "f" using command down'
-
-# Cmd+N (new message/chat)
-osascript -e 'tell application "System Events" to keystroke "n" using command down'
-
-# Cmd+Shift+K (example: multi-modifier)
-osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}'
-```
-
-### Click at Position
-
-```bash
-# Click at absolute screen coordinates
-osascript -e '
-tell application "System Events"
- click at {500, 300}
-end tell
-'
-```
-
-### Get Window Info
-
-```bash
-# Get window position and size
-osascript -e '
-tell application "System Events"
- tell process "Discord"
- get {position, size} of window 1
- end tell
-end tell
-'
-```
-
-### Screenshot
-
-```bash
-# Full screen
-screencapture /tmp/screenshot.png
-
-# Interactive region select
-screencapture -i /tmp/screenshot.png
-
-# Specific window (by window ID from CGWindowList)
-screencapture -l < WINDOW_ID > /tmp/screenshot.png
-```
-
-To get window ID for a specific app:
-
-```bash
-osascript -e '
-tell application "System Events"
- tell process "Discord"
- get id of window 1
- end tell
-end tell
-'
-```
-
-### Read Accessibility Elements
-
-```bash
-# Get all UI elements of the frontmost window (can be slow/large)
-osascript -e '
-tell application "System Events"
- tell process "Discord"
- entire contents of window 1
- end tell
-end tell
-'
-
-# Get a specific element's value
-osascript -e '
-tell application "System Events"
- tell process "Discord"
- get value of text field 1 of window 1
- end tell
-end tell
-'
-```
-
-> **Warning:** `entire contents` can be extremely slow on complex UIs. Prefer screenshots + `Read` tool for visual verification.
-
-### Read Screen Text via Clipboard
+## Per-Platform References
-For reading the latest message or response from an app:
-
-```bash
-# Select all text in the focused area and copy
-osascript -e '
-tell application "System Events"
- keystroke "a" using command down
- keystroke "c" using command down
-end tell
-'
-sleep 0.5
-# Read clipboard
-pbpaste
-```
-
----
-
-## Client: Discord
-
-**App name:** `Discord` | **Process name:** `Discord`
-
-### Activate & Navigate
-
-```bash
-# Activate Discord
-osascript -e 'tell application "Discord" to activate'
-sleep 1
-
-# Open Quick Switcher (Cmd+K) to navigate to a channel
-osascript -e 'tell application "System Events" to keystroke "k" using command down'
-sleep 0.5
-osascript -e 'tell application "System Events" to keystroke "bot-testing"'
-sleep 1
-osascript -e 'tell application "System Events" to key code 36' # Enter
-sleep 2
-```
-
-### Send Message to Bot
-
-```bash
-# The message input is focused after navigating to a channel
-# Type a message
-osascript -e 'tell application "System Events" to keystroke "/hello"'
-sleep 0.5
-osascript -e 'tell application "System Events" to key code 36' # Enter
-```
-
-### Send Long Message (via clipboard)
-
-```bash
-osascript -e '
-tell application "Discord" to activate
-delay 0.5
-set the clipboard to "Write a 3000 word essay about space exploration"
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36 -- Enter
-end tell
-'
-```
-
-### Verify Bot Response
-
-```bash
-# Wait for bot to respond, then screenshot
-sleep 10
-screencapture /tmp/discord-bot-response.png
-# Read with the Read tool for visual verification
-```
-
-### Full Bot Test Example
-
-```bash
-#!/usr/bin/env bash
-# test-discord-bot.sh — Send message and verify bot response
-
-# 1. Activate Discord and navigate to channel
-osascript -e '
-tell application "Discord" to activate
-delay 1
--- Quick Switcher
-tell application "System Events" to keystroke "k" using command down
-delay 0.5
-tell application "System Events" to keystroke "bot-testing"
-delay 1
-tell application "System Events" to key code 36
-delay 2
-'
-
-# 2. Send test message
-osascript -e '
-set the clipboard to "!ping"
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36
-end tell
-'
-
-# 3. Wait for response and capture
-sleep 5
-screencapture /tmp/discord-test-result.png
-echo "Screenshot saved to /tmp/discord-test-result.png"
-```
-
----
-
-## Client: Slack
-
-**App name:** `Slack` | **Process name:** `Slack`
-
-### Activate & Navigate
-
-```bash
-# Activate Slack
-osascript -e 'tell application "Slack" to activate'
-sleep 1
-
-# Quick Switcher (Cmd+K)
-osascript -e 'tell application "System Events" to keystroke "k" using command down'
-sleep 0.5
-osascript -e 'tell application "System Events" to keystroke "bot-testing"'
-sleep 1
-osascript -e 'tell application "System Events" to key code 36' # Enter
-sleep 2
-```
-
-### Send Message to Bot
-
-```bash
-# Direct message input (focused after channel nav)
-osascript -e 'tell application "System Events" to keystroke "@mybot hello"'
-sleep 0.3
-osascript -e 'tell application "System Events" to key code 36'
-```
-
-### Send Long Message
-
-```bash
-osascript -e '
-tell application "Slack" to activate
-delay 0.5
-set the clipboard to "A long test message for the bot..."
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36
-end tell
-'
-```
-
-### Slash Command Test
-
-```bash
-osascript -e '
-tell application "Slack" to activate
-delay 0.5
-tell application "System Events"
- keystroke "/ask What is the meaning of life?"
- delay 0.5
- key code 36
-end tell
-'
-```
-
-### Verify Response
-
-```bash
-sleep 10
-screencapture /tmp/slack-bot-response.png
-```
-
----
-
-## Client: Telegram
-
-**App name:** `Telegram` | **Process name:** `Telegram`
-
-### Activate & Navigate
-
-```bash
-# Activate Telegram
-osascript -e 'tell application "Telegram" to activate'
-sleep 1
-
-# Search for a bot (Cmd+F or click search)
-osascript -e '
-tell application "System Events"
- keystroke "f" using command down
- delay 0.5
- keystroke "MyTestBot"
- delay 1
- key code 36 -- Enter to select
-end tell
-'
-sleep 2
-```
-
-### Send Message to Bot
-
-```bash
-# After navigating to bot chat, input is focused
-osascript -e '
-tell application "System Events"
- keystroke "/start"
- delay 0.3
- key code 36
-end tell
-'
-```
-
-### Send Long Message
-
-```bash
-osascript -e '
-tell application "Telegram" to activate
-delay 0.5
-set the clipboard to "Tell me about quantum computing in detail"
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36
-end tell
-'
-```
-
-### Verify Response
-
-```bash
-sleep 10
-screencapture /tmp/telegram-bot-response.png
-```
-
-### Telegram Bot API (programmatic alternative)
-
-For sending messages directly to the bot's chat without UI:
-
-```bash
-# Send message as the bot (for testing webhooks/responses)
-curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
- -d "chat_id=$CHAT_ID&text=test message"
-
-# Get recent updates
-curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates?limit=5" | jq .
-```
-
----
-
-## Client: WeChat / 微信
-
-**App name:** `微信` or `WeChat` | **Process name:** `WeChat`
-
-### Activate & Navigate
-
-```bash
-# Activate WeChat
-osascript -e 'tell application "微信" to activate'
-sleep 1
-
-# Search for a contact/bot (Cmd+F)
-osascript -e '
-tell application "System Events"
- keystroke "f" using command down
- delay 0.5
- keystroke "TestBot"
- delay 1
- key code 36 -- Enter to select
-end tell
-'
-sleep 2
-```
-
-### Send Message
-
-```bash
-# After navigating to a chat, the input is focused
-osascript -e '
-tell application "System Events"
- keystroke "Hello bot!"
- delay 0.3
- key code 36
-end tell
-'
-```
-
-### Send Long Message (clipboard)
-
-```bash
-osascript -e '
-tell application "微信" to activate
-delay 0.5
-set the clipboard to "Please help me with this task..."
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36
-end tell
-'
-```
-
-### Verify Response
-
-```bash
-sleep 10
-screencapture /tmp/wechat-bot-response.png
-```
-
-### WeChat-Specific Notes
-
-- WeChat macOS app name can be `微信` or `WeChat` depending on system language. Try both:
- ```bash
- osascript -e 'tell application "微信" to activate' 2> /dev/null \
- || osascript -e 'tell application "WeChat" to activate'
- ```
-- WeChat uses **Enter** to send (not Cmd+Enter by default, but configurable)
-- For multi-line messages without sending, use **Shift+Enter**:
- ```bash
- osascript -e 'tell application "System Events" to key code 36 using shift down'
- ```
-
----
-
-## Client: Lark / 飞书
-
-**App name:** `Lark` or `飞书` | **Process name:** `Lark` or `飞书`
-
-### Activate & Navigate
-
-```bash
-# Activate Lark (auto-detects Lark or 飞书)
-osascript -e 'tell application "Lark" to activate' 2> /dev/null \
- || osascript -e 'tell application "飞书" to activate'
-sleep 1
-
-# Quick Switcher / Search (Cmd+K)
-osascript -e 'tell application "System Events" to keystroke "k" using command down'
-sleep 0.5
-osascript -e '
-set the clipboard to "bot-testing"
-tell application "System Events"
- keystroke "v" using command down
- delay 1.5
- key code 36 -- Enter
-end tell
-'
-sleep 2
-```
-
-### Send Message to Bot
-
-```bash
-osascript -e '
-set the clipboard to "@MyBot help me with this task"
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36 -- Enter
-end tell
-'
-```
-
-### Verify Response
-
-```bash
-sleep 10
-screencapture /tmp/lark-bot-response.png
-```
-
-### Lark-Specific Notes
-
-- App name varies: `Lark` (international) vs `飞书` (China mainland) — the script auto-detects
-- Uses `Cmd+K` for quick search (same as Discord/Slack)
-- Enter sends message by default
-
----
-
-## Client: QQ
-
-**App name:** `QQ` | **Process name:** `QQ`
-
-### Activate & Navigate
-
-```bash
-osascript -e 'tell application "QQ" to activate'
-sleep 1
-
-# Search for contact/group (Cmd+F)
-osascript -e '
-tell application "System Events"
- keystroke "f" using command down
- delay 0.8
-end tell
-'
-osascript -e '
-set the clipboard to "bot-testing"
-tell application "System Events"
- keystroke "v" using command down
- delay 1.5
- key code 36 -- Enter
-end tell
-'
-sleep 2
-```
-
-### Send Message to Bot
-
-```bash
-osascript -e '
-set the clipboard to "Hello bot!"
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36 -- Enter
-end tell
-'
-```
-
-### Verify Response
-
-```bash
-sleep 10
-screencapture /tmp/qq-bot-response.png
-```
-
-### QQ-Specific Notes
-
-- Enter sends message by default; Shift+Enter for newlines
-- Uses `Cmd+F` for search
-- Always use clipboard paste for CJK characters
-
----
-
-## Common Bot Testing Workflow (osascript)
-
-Regardless of platform, the pattern is:
-
-```bash
-APP_NAME="Discord" # or "Slack", "Telegram", "微信"
-CHANNEL="bot-testing"
-MESSAGE="Hello bot!"
-WAIT_SECONDS=10
-
-# 1. Activate
-osascript -e "tell application \"$APP_NAME\" to activate"
-sleep 1
-
-# 2. Navigate to channel/chat (via Quick Switcher or Search)
-osascript -e 'tell application "System Events" to keystroke "k" using command down'
-sleep 0.5
-osascript -e "tell application \"System Events\" to keystroke \"$CHANNEL\""
-sleep 1
-osascript -e 'tell application "System Events" to key code 36'
-sleep 2
-
-# 3. Send message
-osascript -e "set the clipboard to \"$MESSAGE\""
-osascript -e '
-tell application "System Events"
- keystroke "v" using command down
- delay 0.3
- key code 36
-end tell
-'
-
-# 4. Wait for bot response
-sleep "$WAIT_SECONDS"
-
-# 5. Screenshot for verification
-screencapture /tmp/"${APP_NAME,,}"-bot-test.png
-echo "Result saved to /tmp/${APP_NAME,,}-bot-test.png"
-```
+Pick the file for your target platform — each contains activation, navigation, send-message, and verification snippets specific to that app:
-### Tips
+| Platform | Reference | Quick switcher |
+| ------------- | ------------------------------------------------ | -------------- |
+| Discord | [reference/discord.md](./reference/discord.md) | `Cmd+K` |
+| Slack | [reference/slack.md](./reference/slack.md) | `Cmd+K` |
+| Telegram | [reference/telegram.md](./reference/telegram.md) | `Cmd+F` |
+| WeChat / 微信 | [reference/wechat.md](./reference/wechat.md) | `Cmd+F` |
+| Lark / 飞书 | [reference/lark.md](./reference/lark.md) | `Cmd+K` |
+| QQ | [reference/qq.md](./reference/qq.md) | `Cmd+F` |
-- **Use clipboard paste** (`Cmd+V`) for messages containing special characters or long text — `keystroke` can mangle non-ASCII
-- **Add `delay`** between actions — apps need time to process UI events
-- **Screenshot for verification** — use `screencapture` + `Read` tool for visual checks
-- **Use a dedicated test channel/chat** — avoid polluting real conversations
-- **Check app name** — some apps have different names in different locales (e.g., `微信` vs `WeChat`)
-- **Accessibility permissions required** — System Events automation requires granting Accessibility access in System Preferences > Privacy & Security > Accessibility
+For **shared osascript patterns** (activate, type, paste, screenshot, read accessibility, common workflow template, gotchas), see [reference/osascript-common.md](./reference/osascript-common.md). Read this first if you're new to osascript automation.
---
@@ -1104,14 +513,4 @@ Outputs to `.records/` directory (gitignored): `<name>.mp4` (video) + `<name>/`
### osascript
-- **Accessibility permission required** — first run will prompt for access; grant it in System Preferences > Privacy & Security > Accessibility for Terminal / iTerm / Claude Code
-- **`keystroke` is slow for long text** — always use clipboard paste (`Cmd+V`) for messages over \~20 characters
-- **`keystroke` can mangle non-ASCII** — use clipboard paste for Chinese, emoji, or special characters
-- **`key code 36` is Enter** — this is the hardware key code, works regardless of keyboard layout
-- **`entire contents` is extremely slow** — avoid for complex UIs; use screenshots instead
-- **App name varies by locale** — `微信` vs `WeChat`, `企业微信` vs `WeCom`; handle both
-- **WeChat Enter sends immediately** — use `Shift+Enter` for newlines within a message
-- **Rate limiting** — don't send messages too fast; platforms may throttle or flag automated input
-- **Lark / 飞书 app name varies** — `Lark` (international) vs `飞书` (China mainland); scripts auto-detect
-- **QQ uses `Cmd+F` for search** — not `Cmd+K` like Discord/Slack/Lark
-- **Bot response times vary** — AI-powered bots may take 10-60s; use generous sleep values
+See [reference/osascript-common.md](./reference/osascript-common.md#gotchas) for the full osascript gotchas list (accessibility permissions, `keystroke` non-ASCII issues, locale-specific app names, rate limiting, etc.).
diff --git a/.agents/skills/local-testing/reference/discord.md b/.agents/skills/local-testing/reference/discord.md
new file mode 100644
index 00000000000..d10d7df93f0
--- /dev/null
+++ b/.agents/skills/local-testing/reference/discord.md
@@ -0,0 +1,97 @@
+# Discord Bot Testing
+
+**App name:** `Discord` | **Process name:** `Discord`
+
+See [osascript-common.md](./osascript-common.md) for shared patterns.
+
+## Activate & Navigate
+
+```bash
+# Activate Discord
+osascript -e 'tell application "Discord" to activate'
+sleep 1
+
+# Open Quick Switcher (Cmd+K) to navigate to a channel
+osascript -e 'tell application "System Events" to keystroke "k" using command down'
+sleep 0.5
+osascript -e 'tell application "System Events" to keystroke "bot-testing"'
+sleep 1
+osascript -e 'tell application "System Events" to key code 36' # Enter
+sleep 2
+```
+
+## Send Message to Bot
+
+```bash
+# The message input is focused after navigating to a channel
+# Type a message
+osascript -e 'tell application "System Events" to keystroke "/hello"'
+sleep 0.5
+osascript -e 'tell application "System Events" to key code 36' # Enter
+```
+
+## Send Long Message (via clipboard)
+
+```bash
+osascript -e '
+tell application "Discord" to activate
+delay 0.5
+set the clipboard to "Write a 3000 word essay about space exploration"
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36 -- Enter
+end tell
+'
+```
+
+## Verify Bot Response
+
+```bash
+# Wait for bot to respond, then screenshot
+sleep 10
+screencapture /tmp/discord-bot-response.png
+# Read with the Read tool for visual verification
+```
+
+## Full Bot Test Example
+
+```bash
+#!/usr/bin/env bash
+# test-discord-bot.sh — Send message and verify bot response
+
+# 1. Activate Discord and navigate to channel
+osascript -e '
+tell application "Discord" to activate
+delay 1
+-- Quick Switcher
+tell application "System Events" to keystroke "k" using command down
+delay 0.5
+tell application "System Events" to keystroke "bot-testing"
+delay 1
+tell application "System Events" to key code 36
+delay 2
+'
+
+# 2. Send test message
+osascript -e '
+set the clipboard to "!ping"
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36
+end tell
+'
+
+# 3. Wait for response and capture
+sleep 5
+screencapture /tmp/discord-test-result.png
+echo "Screenshot saved to /tmp/discord-test-result.png"
+```
+
+## Script
+
+```bash
+./.agents/skills/local-testing/scripts/test-discord-bot.sh "bot-testing" "!ping"
+./.agents/skills/local-testing/scripts/test-discord-bot.sh "bot-testing" "/ask Tell me a joke" 30
+```
diff --git a/.agents/skills/local-testing/reference/lark.md b/.agents/skills/local-testing/reference/lark.md
new file mode 100644
index 00000000000..69183a7db87
--- /dev/null
+++ b/.agents/skills/local-testing/reference/lark.md
@@ -0,0 +1,61 @@
+# Lark / 飞书 Bot Testing
+
+**App name:** `Lark` or `飞书` | **Process name:** `Lark` or `飞书`
+
+See [osascript-common.md](./osascript-common.md) for shared patterns.
+
+## Activate & Navigate
+
+```bash
+# Activate Lark (auto-detects Lark or 飞书)
+osascript -e 'tell application "Lark" to activate' 2> /dev/null \
+ || osascript -e 'tell application "飞书" to activate'
+sleep 1
+
+# Quick Switcher / Search (Cmd+K)
+osascript -e 'tell application "System Events" to keystroke "k" using command down'
+sleep 0.5
+osascript -e '
+set the clipboard to "bot-testing"
+tell application "System Events"
+ keystroke "v" using command down
+ delay 1.5
+ key code 36 -- Enter
+end tell
+'
+sleep 2
+```
+
+## Send Message to Bot
+
+```bash
+osascript -e '
+set the clipboard to "@MyBot help me with this task"
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36 -- Enter
+end tell
+'
+```
+
+## Verify Response
+
+```bash
+sleep 10
+screencapture /tmp/lark-bot-response.png
+```
+
+## Lark-Specific Notes
+
+- App name varies: `Lark` (international) vs `飞书` (China mainland) — the script auto-detects
+- Uses `Cmd+K` for quick search (same as Discord/Slack)
+- Enter sends message by default
+- Always use clipboard paste for CJK characters
+
+## Script
+
+```bash
+./.agents/skills/local-testing/scripts/test-lark-bot.sh "bot-testing" "@MyBot hello"
+./.agents/skills/local-testing/scripts/test-lark-bot.sh "bot-testing" "Help me with this" 30
+```
diff --git a/.agents/skills/local-testing/reference/osascript-common.md b/.agents/skills/local-testing/reference/osascript-common.md
new file mode 100644
index 00000000000..3aaecf39d2b
--- /dev/null
+++ b/.agents/skills/local-testing/reference/osascript-common.md
@@ -0,0 +1,217 @@
+# osascript Common Patterns
+
+Shared AppleScript / `osascript` patterns used by all platform bot tests. Read this first, then refer to the per-platform file for app-specific quirks.
+
+## Core Patterns
+
+### Activate an App
+
+```bash
+osascript -e 'tell application "Discord" to activate'
+```
+
+### Type Text
+
+```bash
+# Type character by character (reliable, but slow for long text)
+osascript -e 'tell application "System Events" to keystroke "Hello world"'
+
+# Press Enter
+osascript -e 'tell application "System Events" to key code 36'
+
+# Press Tab
+osascript -e 'tell application "System Events" to key code 48'
+
+# Press Escape
+osascript -e 'tell application "System Events" to key code 53'
+```
+
+### Paste from Clipboard (fast, for long text)
+
+```bash
+# Set clipboard and paste — much faster than keystroke for long messages
+osascript -e 'set the clipboard to "Your long message here"'
+osascript -e 'tell application "System Events" to keystroke "v" using command down'
+```
+
+Or in one shot:
+
+```bash
+osascript -e '
+set the clipboard to "Your long message here"
+tell application "System Events" to keystroke "v" using command down
+'
+```
+
+### Keyboard Shortcuts
+
+```bash
+# Cmd+K (quick switcher in Discord/Slack)
+osascript -e 'tell application "System Events" to keystroke "k" using command down'
+
+# Cmd+F (search)
+osascript -e 'tell application "System Events" to keystroke "f" using command down'
+
+# Cmd+N (new message/chat)
+osascript -e 'tell application "System Events" to keystroke "n" using command down'
+
+# Cmd+Shift+K (example: multi-modifier)
+osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}'
+```
+
+### Click at Position
+
+```bash
+# Click at absolute screen coordinates
+osascript -e '
+tell application "System Events"
+ click at {500, 300}
+end tell
+'
+```
+
+### Get Window Info
+
+```bash
+# Get window position and size
+osascript -e '
+tell application "System Events"
+ tell process "Discord"
+ get {position, size} of window 1
+ end tell
+end tell
+'
+```
+
+### Screenshot
+
+```bash
+# Full screen
+screencapture /tmp/screenshot.png
+
+# Interactive region select
+screencapture -i /tmp/screenshot.png
+
+# Specific window (by window ID from CGWindowList)
+screencapture -l < WINDOW_ID > /tmp/screenshot.png
+```
+
+To get window ID for a specific app:
+
+```bash
+osascript -e '
+tell application "System Events"
+ tell process "Discord"
+ get id of window 1
+ end tell
+end tell
+'
+```
+
+### Read Accessibility Elements
+
+```bash
+# Get all UI elements of the frontmost window (can be slow/large)
+osascript -e '
+tell application "System Events"
+ tell process "Discord"
+ entire contents of window 1
+ end tell
+end tell
+'
+
+# Get a specific element's value
+osascript -e '
+tell application "System Events"
+ tell process "Discord"
+ get value of text field 1 of window 1
+ end tell
+end tell
+'
+```
+
+> **Warning:** `entire contents` can be extremely slow on complex UIs. Prefer screenshots + `Read` tool for visual verification.
+
+### Read Screen Text via Clipboard
+
+For reading the latest message or response from an app:
+
+```bash
+# Select all text in the focused area and copy
+osascript -e '
+tell application "System Events"
+ keystroke "a" using command down
+ keystroke "c" using command down
+end tell
+'
+sleep 0.5
+# Read clipboard
+pbpaste
+```
+
+---
+
+## Common Bot Testing Workflow
+
+Regardless of platform, the pattern is:
+
+```bash
+APP_NAME="Discord" # or "Slack", "Telegram", "微信"
+CHANNEL="bot-testing"
+MESSAGE="Hello bot!"
+WAIT_SECONDS=10
+
+# 1. Activate
+osascript -e "tell application \"$APP_NAME\" to activate"
+sleep 1
+
+# 2. Navigate to channel/chat (via Quick Switcher or Search)
+osascript -e 'tell application "System Events" to keystroke "k" using command down'
+sleep 0.5
+osascript -e "tell application \"System Events\" to keystroke \"$CHANNEL\""
+sleep 1
+osascript -e 'tell application "System Events" to key code 36'
+sleep 2
+
+# 3. Send message
+osascript -e "set the clipboard to \"$MESSAGE\""
+osascript -e '
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36
+end tell
+'
+
+# 4. Wait for bot response
+sleep "$WAIT_SECONDS"
+
+# 5. Screenshot for verification
+screencapture /tmp/"${APP_NAME,,}"-bot-test.png
+echo "Result saved to /tmp/${APP_NAME,,}-bot-test.png"
+```
+
+### Tips
+
+- **Use clipboard paste** (`Cmd+V`) for messages containing special characters or long text — `keystroke` can mangle non-ASCII
+- **Add `delay`** between actions — apps need time to process UI events
+- **Screenshot for verification** — use `screencapture` + `Read` tool for visual checks
+- **Use a dedicated test channel/chat** — avoid polluting real conversations
+- **Check app name** — some apps have different names in different locales (e.g., `微信` vs `WeChat`)
+- **Accessibility permissions required** — System Events automation requires granting Accessibility access in System Preferences > Privacy & Security > Accessibility
+
+---
+
+## Gotchas
+
+- **Accessibility permission required** — first run will prompt for access; grant it in System Preferences > Privacy & Security > Accessibility for Terminal / iTerm / Claude Code
+- **`keystroke` is slow for long text** — always use clipboard paste (`Cmd+V`) for messages over \~20 characters
+- **`keystroke` can mangle non-ASCII** — use clipboard paste for Chinese, emoji, or special characters
+- **`key code 36` is Enter** — this is the hardware key code, works regardless of keyboard layout
+- **`entire contents` is extremely slow** — avoid for complex UIs; use screenshots instead
+- **App name varies by locale** — `微信` vs `WeChat`, `企业微信` vs `WeCom`; handle both
+- **WeChat Enter sends immediately** — use `Shift+Enter` for newlines within a message
+- **Rate limiting** — don't send messages too fast; platforms may throttle or flag automated input
+- **Lark / 飞书 app name varies** — `Lark` (international) vs `飞书` (China mainland); scripts auto-detect
+- **QQ uses `Cmd+F` for search** — not `Cmd+K` like Discord/Slack/Lark
+- **Bot response times vary** — AI-powered bots may take 10-60s; use generous sleep values
diff --git a/.agents/skills/local-testing/reference/qq.md b/.agents/skills/local-testing/reference/qq.md
new file mode 100644
index 00000000000..826760e9289
--- /dev/null
+++ b/.agents/skills/local-testing/reference/qq.md
@@ -0,0 +1,62 @@
+# QQ Bot Testing
+
+**App name:** `QQ` | **Process name:** `QQ`
+
+See [osascript-common.md](./osascript-common.md) for shared patterns.
+
+## Activate & Navigate
+
+```bash
+osascript -e 'tell application "QQ" to activate'
+sleep 1
+
+# Search for contact/group (Cmd+F)
+osascript -e '
+tell application "System Events"
+ keystroke "f" using command down
+ delay 0.8
+end tell
+'
+osascript -e '
+set the clipboard to "bot-testing"
+tell application "System Events"
+ keystroke "v" using command down
+ delay 1.5
+ key code 36 -- Enter
+end tell
+'
+sleep 2
+```
+
+## Send Message to Bot
+
+```bash
+osascript -e '
+set the clipboard to "Hello bot!"
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36 -- Enter
+end tell
+'
+```
+
+## Verify Response
+
+```bash
+sleep 10
+screencapture /tmp/qq-bot-response.png
+```
+
+## QQ-Specific Notes
+
+- Enter sends message by default; Shift+Enter for newlines
+- Uses `Cmd+F` for search (not `Cmd+K` like Discord/Slack/Lark)
+- Always use clipboard paste for CJK characters
+
+## Script
+
+```bash
+./.agents/skills/local-testing/scripts/test-qq-bot.sh "bot-testing" "Hello bot" 15
+./.agents/skills/local-testing/scripts/test-qq-bot.sh "MyBot" "/help" 10
+```
diff --git a/.agents/skills/local-testing/reference/slack.md b/.agents/skills/local-testing/reference/slack.md
new file mode 100644
index 00000000000..0a238b5064a
--- /dev/null
+++ b/.agents/skills/local-testing/reference/slack.md
@@ -0,0 +1,73 @@
+# Slack Bot Testing
+
+**App name:** `Slack` | **Process name:** `Slack`
+
+See [osascript-common.md](./osascript-common.md) for shared patterns.
+
+## Activate & Navigate
+
+```bash
+# Activate Slack
+osascript -e 'tell application "Slack" to activate'
+sleep 1
+
+# Quick Switcher (Cmd+K)
+osascript -e 'tell application "System Events" to keystroke "k" using command down'
+sleep 0.5
+osascript -e 'tell application "System Events" to keystroke "bot-testing"'
+sleep 1
+osascript -e 'tell application "System Events" to key code 36' # Enter
+sleep 2
+```
+
+## Send Message to Bot
+
+```bash
+# Direct message input (focused after channel nav)
+osascript -e 'tell application "System Events" to keystroke "@mybot hello"'
+sleep 0.3
+osascript -e 'tell application "System Events" to key code 36'
+```
+
+## Send Long Message
+
+```bash
+osascript -e '
+tell application "Slack" to activate
+delay 0.5
+set the clipboard to "A long test message for the bot..."
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36
+end tell
+'
+```
+
+## Slash Command Test
+
+```bash
+osascript -e '
+tell application "Slack" to activate
+delay 0.5
+tell application "System Events"
+ keystroke "/ask What is the meaning of life?"
+ delay 0.5
+ key code 36
+end tell
+'
+```
+
+## Verify Response
+
+```bash
+sleep 10
+screencapture /tmp/slack-bot-response.png
+```
+
+## Script
+
+```bash
+./.agents/skills/local-testing/scripts/test-slack-bot.sh "bot-testing" "@mybot hello"
+./.agents/skills/local-testing/scripts/test-slack-bot.sh "bot-testing" "/ask What is 2+2?" 20
+```
diff --git a/.agents/skills/local-testing/reference/telegram.md b/.agents/skills/local-testing/reference/telegram.md
new file mode 100644
index 00000000000..f93f596a1ad
--- /dev/null
+++ b/.agents/skills/local-testing/reference/telegram.md
@@ -0,0 +1,80 @@
+# Telegram Bot Testing
+
+**App name:** `Telegram` | **Process name:** `Telegram`
+
+See [osascript-common.md](./osascript-common.md) for shared patterns.
+
+## Activate & Navigate
+
+```bash
+# Activate Telegram
+osascript -e 'tell application "Telegram" to activate'
+sleep 1
+
+# Search for a bot (Cmd+F or click search)
+osascript -e '
+tell application "System Events"
+ keystroke "f" using command down
+ delay 0.5
+ keystroke "MyTestBot"
+ delay 1
+ key code 36 -- Enter to select
+end tell
+'
+sleep 2
+```
+
+## Send Message to Bot
+
+```bash
+# After navigating to bot chat, input is focused
+osascript -e '
+tell application "System Events"
+ keystroke "/start"
+ delay 0.3
+ key code 36
+end tell
+'
+```
+
+## Send Long Message
+
+```bash
+osascript -e '
+tell application "Telegram" to activate
+delay 0.5
+set the clipboard to "Tell me about quantum computing in detail"
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36
+end tell
+'
+```
+
+## Verify Response
+
+```bash
+sleep 10
+screencapture /tmp/telegram-bot-response.png
+```
+
+## Telegram Bot API (programmatic alternative)
+
+For sending messages directly to the bot's chat without UI:
+
+```bash
+# Send message as the bot (for testing webhooks/responses)
+curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
+ -d "chat_id=$CHAT_ID&text=test message"
+
+# Get recent updates
+curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates?limit=5" | jq .
+```
+
+## Script
+
+```bash
+./.agents/skills/local-testing/scripts/test-telegram-bot.sh "MyTestBot" "/start"
+./.agents/skills/local-testing/scripts/test-telegram-bot.sh "GPTBot" "Hello" 60
+```
diff --git a/.agents/skills/local-testing/reference/wechat.md b/.agents/skills/local-testing/reference/wechat.md
new file mode 100644
index 00000000000..2cc8d23f77a
--- /dev/null
+++ b/.agents/skills/local-testing/reference/wechat.md
@@ -0,0 +1,81 @@
+# WeChat / 微信 Bot Testing
+
+**App name:** `微信` or `WeChat` | **Process name:** `WeChat`
+
+See [osascript-common.md](./osascript-common.md) for shared patterns.
+
+## Activate & Navigate
+
+```bash
+# Activate WeChat
+osascript -e 'tell application "微信" to activate'
+sleep 1
+
+# Search for a contact/bot (Cmd+F)
+osascript -e '
+tell application "System Events"
+ keystroke "f" using command down
+ delay 0.5
+ keystroke "TestBot"
+ delay 1
+ key code 36 -- Enter to select
+end tell
+'
+sleep 2
+```
+
+## Send Message
+
+```bash
+# After navigating to a chat, the input is focused
+osascript -e '
+tell application "System Events"
+ keystroke "Hello bot!"
+ delay 0.3
+ key code 36
+end tell
+'
+```
+
+## Send Long Message (clipboard)
+
+```bash
+osascript -e '
+tell application "微信" to activate
+delay 0.5
+set the clipboard to "Please help me with this task..."
+tell application "System Events"
+ keystroke "v" using command down
+ delay 0.3
+ key code 36
+end tell
+'
+```
+
+## Verify Response
+
+```bash
+sleep 10
+screencapture /tmp/wechat-bot-response.png
+```
+
+## WeChat-Specific Notes
+
+- WeChat macOS app name can be `微信` or `WeChat` depending on system language. Try both:
+ ```bash
+ osascript -e 'tell application "微信" to activate' 2> /dev/null \
+ || osascript -e 'tell application "WeChat" to activate'
+ ```
+- WeChat uses **Enter** to send (not Cmd+Enter by default, but configurable)
+- For multi-line messages without sending, use **Shift+Enter**:
+ ```bash
+ osascript -e 'tell application "System Events" to key code 36 using shift down'
+ ```
+- Always use clipboard paste for CJK characters — `keystroke` mangles non-ASCII
+
+## Script
+
+```bash
+./.agents/skills/local-testing/scripts/test-wechat-bot.sh "文件传输助手" "test message" 5
+./.agents/skills/local-testing/scripts/test-wechat-bot.sh "MyBot" "Tell me a joke" 30
+```
diff --git a/docs/development/basic/add-new-bot-platform.mdx b/docs/development/basic/add-new-bot-platform.mdx
index c3436eed355..31fed3c3d7d 100644
--- a/docs/development/basic/add-new-bot-platform.mdx
+++ b/docs/development/basic/add-new-bot-platform.mdx
@@ -337,6 +337,7 @@ import { schema } from './schema';
export const myPlatform: PlatformDefinition = {
id: '<platform>',
name: 'Platform Name',
+ connectionMode: 'webhook', // 'webhook' | 'websocket' | 'polling'
description: 'Connect a Platform bot',
documentation: {
portalUrl: 'https://developers.example.com',
diff --git a/docs/development/basic/add-new-bot-platform.zh-CN.mdx b/docs/development/basic/add-new-bot-platform.zh-CN.mdx
index 38087d0b3c5..fa3f478282b 100644
--- a/docs/development/basic/add-new-bot-platform.zh-CN.mdx
+++ b/docs/development/basic/add-new-bot-platform.zh-CN.mdx
@@ -334,6 +334,7 @@ import { schema } from './schema';
export const myPlatform: PlatformDefinition = {
id: '<platform>',
name: 'Platform Name',
+ connectionMode: 'webhook', // 'webhook' | 'websocket' | 'polling'
description: 'Connect a Platform bot',
documentation: {
portalUrl: 'https://developers.example.com',
diff --git a/docs/usage/channels/qq.mdx b/docs/usage/channels/qq.mdx
index fe6765122ce..5e26cedba52 100644
--- a/docs/usage/channels/qq.mdx
+++ b/docs/usage/channels/qq.mdx
@@ -20,6 +20,15 @@ By connecting a QQ channel to your LobeHub agent, users can interact with the AI
- A LobeHub account with an active subscription
- A QQ account
+## Connection Modes
+
+LobeHub supports two connection modes for QQ bots:
+
+- **WebSocket (Recommended)** — Persistent connection. Events are delivered in real time via WebSocket. No callback URL configuration required. This is the default mode for new bots.
+- **Webhook** — Stateless HTTP callbacks. Use this mode if your bot already has a callback URL configured on the QQ Open Platform and cannot switch.
+
+> **Note:** On the QQ Open Platform, once a bot is configured with a Webhook callback URL, it cannot be switched to WebSocket mode. New bots that have not configured a callback URL should use WebSocket mode.
+
## Step 1: Create a QQ Bot
<Steps>
@@ -42,9 +51,11 @@ By connecting a QQ channel to your LobeHub agent, users can interact with the AI
![](/blog/assets276a4e8748e9bd300b30dcd9d0e24980.webp)
- ### Configure Webhook URL
+ ### Configure Event Delivery (Webhook Only)
+
+ If you are using **Webhook mode**, navigate to **Development Settings** → **Callback Configuration** in the QQ Open Platform. You will need to paste the LobeHub Callback URL here after completing Step 2.
- In the QQ Open Platform, navigate to **Development Settings** → **Callback Configuration**. You will need to paste the LobeHub Callback URL here after completing Step 2.
+ If you are using **WebSocket mode** (default), skip this step — no callback URL is needed.
</Steps>
## Step 2: Configure QQ in LobeHub
@@ -61,16 +72,26 @@ By connecting a QQ channel to your LobeHub agent, users can interact with the AI
- **Application ID** — The App ID from the QQ Open Platform
- **App Secret** — The App Secret from the QQ Open Platform
- ### Save and Copy the Callback URL
+ ### Select Connection Mode
- Click **Save Configuration**. After saving, a **Callback URL** will be displayed. Copy this URL.
+ In **Advanced Settings**, choose the **Connection Mode**:
- Your credentials will be encrypted and stored securely.
+ - **WebSocket** (default) — Recommended for new bots
+ - **Webhook** — For bots with an existing callback URL on QQ Open Platform
+
+ ### Save Configuration
+
+ Click **Save Configuration**. Your credentials will be encrypted and stored securely.
+
+ - In **WebSocket mode**, the bot will automatically connect to the QQ gateway. No further configuration is needed.
+ - In **Webhook mode**, a **Callback URL** will be displayed after saving. Copy this URL for Step 3.
![](/blog/assetsf9317924035e48fcb1d1ae586568ea5f.webp)
</Steps>
-## Step 3: Configure Callback in QQ Open Platform
+## Step 3: Configure Callback in QQ Open Platform (Webhook Only)
+
+> Skip this step if you are using WebSocket mode.
<Steps>
### Paste the Callback URL
@@ -121,11 +142,11 @@ To use the bot in QQ groups:
## Configuration Reference
-| Field | Required | Description |
-| ------------------ | -------- | -------------------------------------------------------- |
-| **Application ID** | Yes | Your bot's App ID from QQ Open Platform |
-| **App Secret** | Yes | Your bot's App Secret from QQ Open Platform |
-| **Callback URL** | — | Auto-generated after saving; paste into QQ Open Platform |
+| Field | Required | Description |
+| ------------------- | -------- | --------------------------------------------------------------------------------------- |
+| **Application ID** | Yes | Your bot's App ID from QQ Open Platform |
+| **App Secret** | Yes | Your bot's App Secret from QQ Open Platform |
+| **Connection Mode** | No | `websocket` (default) or `webhook`. Choose based on your QQ Open Platform configuration |
## Limitations
@@ -136,7 +157,8 @@ To use the bot in QQ groups:
## Troubleshooting
-- **Callback URL verification failed:** Ensure you saved the configuration in LobeHub first and the URL was copied correctly. LobeHub handles Ed25519 verification automatically.
+- **Bot not connecting (WebSocket mode):** Verify the App ID and App Secret are correct. Ensure the bot has not been configured with a callback URL on QQ Open Platform — once a callback URL is set, WebSocket mode is unavailable.
+- **Callback URL verification failed (Webhook mode):** Ensure you saved the configuration in LobeHub first and the URL was copied correctly. LobeHub handles Ed25519 verification automatically.
- **Bot not responding:** Verify the App ID and App Secret are correct, the bot is published (or you are a sandbox test user), and the required message events are subscribed.
- **Group chat issues:** Make sure the bot has been added to the group. @mention the bot to trigger a response.
- **Test Connection failed:** Double-check the App ID and App Secret in LobeHub's channel settings.
diff --git a/docs/usage/channels/qq.zh-CN.mdx b/docs/usage/channels/qq.zh-CN.mdx
index 67bc472511b..69aceee63ee 100644
--- a/docs/usage/channels/qq.zh-CN.mdx
+++ b/docs/usage/channels/qq.zh-CN.mdx
@@ -17,6 +17,15 @@ tags:
- 一个拥有有效订阅的 LobeHub 账户
- 一个 QQ 账户
+## 连接模式
+
+LobeHub ��持两种 QQ 机器人连接模式:
+
+- **WebSocket(推荐)** — 持久连接。事件通过 WebSocket 实时推送,无需配置回调地址。这是新机器人的默认模式。
+- **Webhook** — 无状态 HTTP ��调。如果您的机器人已在 QQ 开放平台配置了回调地址且无法切换,请使用此模式。
+
+> **注意:** 在 QQ 开放平台上,一旦机器人配置了 Webhook 回调地址,就无法切换到 WebSocket 模式。尚未配置回调地址的新机器人应使用 WebSocket 模式。
+
## 第一步:创建 QQ 机器人
<Steps>
@@ -39,9 +48,11 @@ tags:
![](/blog/assets276a4e8748e9bd300b30dcd9d0e24980.webp)
- ### 配置回调地址
+ ### 配置事件接收方式(仅 Webhook 模式)
+
+ 如果您使用的是 **Webhook 模式**,请在 QQ 开放平台中导航到 **开发设置** → **回调配置**。您需要在完成第二步后将 LobeHub 的回调地址粘贴到此处。
- 在 QQ 开放平台中,导航到 **开发设置** → **回调配置**。您需要在完成第二步后将 LobeHub 的回调地址粘贴到此处。
+ 如果您使用的是 **WebSocket 模式**(默认),请跳过此步骤 — 无需配置回调地址。
</Steps>
## 第二步:在 LobeHub 中配置 QQ
@@ -49,7 +60,7 @@ tags:
<Steps>
### 打开渠道设置
- 在 LobeHub 中,导航到您的代理设置,然后选择 **渠道** 标签页。从平台列表中点击 **QQ**。
+ 在 LobeHub 中,导航到您的代理设置,然后选择 **渠道** 标签页。��平台列表中点击 **QQ**。
### 输入应用凭证
@@ -58,16 +69,26 @@ tags:
- **应用 ID** — 来自 QQ 开放平台的 App ID
- **App Secret** — 来自 QQ 开放平台的 App Secret
- ### 保存并复制回调地址
+ ### 选择连接模式
- 点击 **保存配置**。保存后,将显示一个 **回调地址(Callback URL)**。复制此地址。
+ 在 **高级设置** 中,选择 **连接模式**:
- 您的凭证将被加密并安全存储。
+ - **WebSocket**(默认)— 推荐新机器人使用
+ - **Webhook** — 适用于已在 QQ 开放平台配置了回调地址的机器人
+
+ ### 保存配置
+
+ 点击 **保存配置**。您的凭证将被加密并安全存储。
+
+ - 在 **WebSocket 模式** 下,机器人会自动连接到 QQ 网关,无需额外配置。
+ - 在 **Webhook 模式** 下,保存后将显示 **回调地址(Callback URL)**。复制此地址用于第三步。
![](/blog/assetsf9317924035e48fcb1d1ae586568ea5f.webp)
</Steps>
-## 第三步:在 QQ 开放平台配置回调
+## 第三步:在 QQ 开放平台配置回调(仅 Webhook 模式)
+
+> 如果您使用的是 WebSocket 模式,请跳过此步骤。
<Steps>
### 粘贴回调地址
@@ -118,11 +139,11 @@ tags:
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| -------------- | ---- | ---------------------- |
-| **应用 ID** | 是 | 来自 QQ 开放平台的 App ID |
-| **App Secret** | 是 | 来自 QQ 开放平台的 App Secret |
-| **回调地址** | — | 保存后自动生成;粘贴到 QQ 开放平台 |
+| 字段 | 是否必需 | 描述 |
+| -------------- | ---- | ----------------------------------------- |
+| **应用 ID** | 是 | 来自 QQ 开放平台的 App ID |
+| **App Secret** | 是 | 来自 QQ 开放平台的 App Secret |
+| **连接模式** | 否 | `websocket`(默认)或 `webhook`,根据 QQ 开放平台配置选择 |
## 功能限制
@@ -133,7 +154,8 @@ tags:
## 故障排除
-- **回调地址验证失败:** 确保您已在 LobeHub 中保存配置,并正确复制了 URL。LobeHub 会自动处理 Ed25519 验证。
+- **机器人无法连接(WebSocket 模式):** 验证 App ID 和 App Secret 是否正确。确保机��人在 QQ 开放平台上未配置回调地址 — 一旦设置了回调地址,WebSocket 模式将不可用。
+- **回调地址验证失败(Webhook 模式):** 确保您已在 LobeHub 中保存配置,并正确复制了 URL。LobeHub 会自动处理 Ed25519 验证。
- **机器人未响应:** 验证 App ID 和 App Secret 是否正确,机器人是否已发布(或您是沙盒测试用户),以及是否订阅了所需的消息事件。
- **群聊问题:** 确保机器人已被添加到群聊中。@提及机器人以触发响应。
- **测试连接失败:** 仔细检查 LobeHub 渠道设置中的 App ID 和 App Secret。
diff --git a/docs/usage/channels/slack.mdx b/docs/usage/channels/slack.mdx
index 927810bcd6c..7505b6faa48 100644
--- a/docs/usage/channels/slack.mdx
+++ b/docs/usage/channels/slack.mdx
@@ -20,129 +20,183 @@ By connecting a Slack channel to your LobeHub agent, users can interact with the
- A LobeHub account with an active subscription
- A Slack workspace where you have permission to install apps
-## Step 1: Create a Slack App
+## Connection Modes
-<Steps>
- ### Go to the Slack API Dashboard
+LobeHub supports two connection modes for Slack:
- Visit [Slack API Apps](https://api.slack.com/apps) and click **Create New App**. Choose **From scratch**, give your app a name (e.g., "LobeHub Assistant"), select the workspace to install it in, and click **Create App**.
+- **Socket Mode / WebSocket (Recommended)** — Real-time event delivery via WebSocket. No public URL required. Ideal for development and private deployments.
+- **Webhook** — Stateless HTTP callbacks via the Events API. Requires a publicly accessible URL. Use this if your Slack app already has Event Subscriptions configured.
- ### Copy the App ID and Signing Secret
+## Socket Mode Setup (Recommended)
- On the **Basic Information** page, copy and save:
+### Step 1: Create a Slack App from Manifest
- - **App ID** — displayed at the top of the page
- - **Signing Secret** — under the **App Credentials** section
+<Steps>
+ ### Open the Slack API Dashboard
+
+ Visit [api.slack.com/apps](https://api.slack.com/apps) and click **Create New App** → **From an app manifest**.
+
+ ### Select Your Workspace
+
+ Choose the Slack workspace where you want to install the app.
+
+ ### Paste the Manifest
+
+ Select **YAML** format and paste the following manifest template:
+
+ ```yaml
+ display_information:
+ name: LobeHub Assistant
+ description: AI assistant powered by LobeHub
+ features:
+ app_home:
+ home_tab_enabled: false
+ messages_tab_enabled: true
+ messages_tab_read_only_enabled: false
+ bot_user:
+ display_name: LobeHub Assistant
+ always_online: true
+ oauth_config:
+ scopes:
+ bot:
+ - app_mentions:read
+ - channels:history
+ - channels:read
+ - chat:write
+ - groups:history
+ - groups:read
+ - im:history
+ - im:read
+ - mpim:history
+ - mpim:read
+ - reactions:read
+ - reactions:write
+ - users:read
+ - assistant:write
+ settings:
+ event_subscriptions:
+ bot_events:
+ - app_mention
+ - message.channels
+ - message.groups
+ - message.im
+ - message.mpim
+ - member_joined_channel
+ - assistant_thread_started
+ - assistant_thread_context_changed
+ org_deploy_enabled: false
+ socket_mode_enabled: true
+ token_rotation_enabled: false
+ ```
+
+ > **Note:** `socket_mode_enabled: true` means no Request URL is needed. Events are delivered via WebSocket.
+
+ ### Create the App
+
+ Review the summary and click **Create**.
![](/blog/assets3865756ef6158a855aee64dd01bd3d6b.webp)
+</Steps>
- ### Add Bot Token Scopes
+### Step 2: Collect Credentials
+
+<Steps>
+ ### Copy the App ID and Signing Secret
- In the left sidebar, go to **OAuth & Permissions**. Scroll down to **Scopes** → **Bot Token Scopes** and add the following:
+ On the **Basic Information** page, copy:
- - `app_mentions:read` — Detect when the bot is mentioned
- - `channels:history` — Read messages in public channels
- - `channels:read` — Read channel info
- - `chat:write` — Send messages
- - `groups:history` — Read messages in private channels
- - `groups:read` — Read private channel info
- - `im:history` — Read direct messages
- - `im:read` — Read DM channel info
- - `mpim:history` — Read group DM messages
- - `mpim:read` — Read group DM channel info
- - `reactions:read` — Read reactions
- - `reactions:write` — Add reactions
- - `users:read` — Look up user info
+ - **App ID** — displayed at the top
+ - **Signing Secret** — under **App Credentials**
- **Optional scopes** (for Slack Assistants API support):
+ ### Generate an App-Level Token
- - `assistant:write` — Enable the Slack Assistants API features
+ Scroll down to **App-Level Tokens** and click **Generate Token and Scopes**. Name it (e.g., "socket-mode"), add the `connections:write` scope, and click **Generate**.
- ### Install the App to Your Workspace
+ Copy the token (starts with `xapp-`).
- Still on the **OAuth & Permissions** page, click **Install to Workspace** and authorize the app. After installation, copy the **Bot User OAuth Token** (starts with `xoxb-`).
+ > **Important:** This token is only shown once. Store it securely.
- > **Important:** Treat your bot token like a password. Never share it publicly or commit it to version control.
+ ### Install the App to Your Workspace
+
+ Go to **OAuth & Permissions** in the sidebar, click **Install to Workspace**, and authorize. Copy the **Bot User OAuth Token** (starts with `xoxb-`).
![](/blog/assetsfd4606a4b5d801a8764bf333cde77d57.webp)
</Steps>
-## Step 2: Configure Slack in LobeHub
+### Step 3: Configure Slack in LobeHub
<Steps>
### Open Channel Settings
- In LobeHub, navigate to your agent's settings, then select the **Channels** tab. Click **Slack** from the platform list.
+ In LobeHub, navigate to your agent's settings → **Channels** tab → click **Slack**.
- ### Fill in the Credentials
+ ### Enter Credentials
- Enter the following fields:
+ Fill in:
- - **Application ID** — The App ID from your Slack app's Basic Information page
- - **Bot Token** — The Bot User OAuth Token (xoxb-...) from OAuth & Permissions
- - **Signing Secret** — The Signing Secret from your Slack app's Basic Information page
+ - **Application ID** — The App ID
+ - **Bot Token** — The Bot User OAuth Token (`xoxb-...`)
+ - **Signing Secret** — The Signing Secret
+ - **App-Level Token** — The app-level token (`xapp-...`)
- Your token will be encrypted and stored securely.
+ ### Select Connection Mode
- ### Save Configuration
+ In **Advanced Settings**, set **Connection Mode** to **WebSocket**.
- Click **Save Configuration**. LobeHub will save your credentials and display a **Webhook URL**.
-
- ### Copy the Webhook URL
+ ### Save Configuration
- Copy the displayed Webhook URL — you will need it in the next step to configure Slack's Event Subscriptions.
+ Click **Save Configuration**. The bot will automatically connect via Socket Mode. No webhook URL configuration is needed.
![](/blog/assetsc3042da681a9df811e70473636a8f461.webp)
</Steps>
-## Step 3: Configure Event Subscriptions
+### Step 4: Test the Connection
-<Steps>
- ### Enable Events
+Click **Test Connection** in LobeHub, then go to Slack, invite the bot to a channel, and mention it with `@LobeHub Assistant` to confirm it responds.
- Back in the [Slack API Dashboard](https://api.slack.com/apps), go to **Event Subscriptions** and toggle **Enable Events** to **On**.
+---
- ### Set the Request URL
+## Webhook Setup (Alternative)
- Paste the **Webhook URL** you copied from LobeHub into the **Request URL** field. Slack will send a verification challenge — LobeHub will respond automatically.
+Use this method if your Slack app already has Event Subscriptions configured with a public HTTP endpoint, or if you cannot use Socket Mode.
- ### Subscribe to Bot Events
+<Steps>
+ ### Create a Slack App
- Under **Subscribe to bot events**, add:
+ Visit [api.slack.com/apps](https://api.slack.com/apps), click **Create New App** → **From scratch**. Name your app and select the workspace.
- - `app_mention` — Triggered when someone mentions the bot
- - `message.channels` — Messages in public channels
- - `message.groups` — Messages in private channels
- - `message.im` — Direct messages to the bot
- - `message.mpim` — Messages in group DMs
- - `member_joined_channel` — When a user joins a channel
+ ### Add Bot Token Scopes
- **Optional events** (for Slack Assistants API support):
+ Go to **OAuth & Permissions** → **Bot Token Scopes** and add: `app_mentions:read`, `channels:history`, `channels:read`, `chat:write`, `groups:history`, `groups:read`, `im:history`, `im:read`, `mpim:history`, `mpim:read`, `reactions:read`, `reactions:write`, `users:read`.
- - `assistant_thread_started` — When a user opens a new assistant thread
- - `assistant_thread_context_changed` — When a user navigates to a different channel with the assistant panel open
+ ### Install to Workspace
- ### Save Changes
+ Click **Install to Workspace** and copy the **Bot User OAuth Token** (`xoxb-...`).
- Click **Save Changes** at the bottom of the page.
+ ### Configure in LobeHub
- ![](/blog/assets8f3657f3785fc04c42b0f53c17daa72e.webp)
-</Steps>
+ Enter **Application ID**, **Bot Token**, and **Signing Secret** in LobeHub's Slack channel settings. Set **Connection Mode** to **Webhook** in Advanced Settings. Save and copy the displayed **Webhook URL**.
+
+ ### Configure Event Subscriptions
-## Step 4: Test the Connection
+ In the Slack API Dashboard → **Event Subscriptions**, enable events, paste the Webhook URL as the **Request URL**, and subscribe to bot events: `app_mention`, `message.channels`, `message.groups`, `message.im`, `message.mpim`, `member_joined_channel`.
-Back in LobeHub's channel settings for Slack, click **Test Connection** to verify the integration. Then go to your Slack workspace, invite the bot to a channel, and mention it with `@YourBotName` to confirm it responds.
+ ![](/blog/assets8f3657f3785fc04c42b0f53c17daa72e.webp)
+</Steps>
## Configuration Reference
-| Field | Required | Description |
-| ------------------ | -------- | ------------------------------------------ |
-| **Application ID** | Yes | Your Slack app's ID |
-| **Bot Token** | Yes | Bot User OAuth Token (xoxb-...) |
-| **Signing Secret** | Yes | Used to verify webhook requests from Slack |
+| Field | Required | Description |
+| ------------------- | ---------------- | ----------------------------------------------------- |
+| **Application ID** | Yes | Your Slack app's ID |
+| **Bot Token** | Yes | Bot User OAuth Token (`xoxb-...`) |
+| **Signing Secret** | Yes | Used to verify requests from Slack |
+| **App-Level Token** | Socket Mode only | App-level token (`xapp-...`) for WebSocket connection |
+| **Connection Mode** | No | `websocket` or `webhook` (default: `webhook`) |
## Troubleshooting
-- **Bot not responding:** Confirm the bot has been invited to the channel and the Event Subscriptions are correctly configured with the right webhook URL.
-- **Test Connection failed:** Double-check the Application ID and Bot Token are correct. Ensure the app is installed to the workspace.
-- **Webhook verification failed:** Make sure the Signing Secret matches the one in your Slack app's Basic Information page.
+- **Bot not responding:** Confirm the bot has been invited to the channel. For Socket Mode, ensure the App-Level Token is correct and Socket Mode is enabled in Slack app settings.
+- **Test Connection failed:** Double-check the Application ID and Bot Token. Ensure the app is installed to the workspace.
+- **Webhook verification failed (Webhook mode):** Make sure the Signing Secret matches and the Webhook URL is correct.
+- **Socket Mode not connecting:** Verify the App-Level Token has the `connections:write` scope. Check that Socket Mode is enabled in your Slack app settings under **Socket Mode**.
diff --git a/docs/usage/channels/slack.zh-CN.mdx b/docs/usage/channels/slack.zh-CN.mdx
index 7042ef1ff74..c81adef46b9 100644
--- a/docs/usage/channels/slack.zh-CN.mdx
+++ b/docs/usage/channels/slack.zh-CN.mdx
@@ -17,129 +17,183 @@ tags:
- 一个拥有有效订阅的 LobeHub 账户
- 一个拥有安装应用权限的 Slack 工作区
-## 第一步:创建 Slack 应用
+## 连接模式
-<Steps>
- ### 访问 Slack API 控制台
+LobeHub 支持两种 Slack 连接模式:
- 访问 [Slack API Apps](https://api.slack.com/apps),点击 **Create New App**。选择 **From scratch**,为您的应用命名(例如 "LobeHub 助手"),选择要安装到的工作区,然后点击 **Create App**。
+- **Socket Mode / WebSocket(推荐)** — 通过 WebSocket 实时接收事件。无需公网 URL。适合开发环境和私有部署。
+- **Webhook** — 通过 Events API 的无状态 HTTP 回调。需要公网可访问的 URL。如果您的 Slack 应用已配置了事件订阅,请使用此模式。
- ### 复制 App ID 和 Signing Secret
+## Socket Mode 设置(推荐)
- 在 **Basic Information** 页面,复制并保存:
+### 第一步:通过 Manifest 创建 Slack 应用
- - **App ID** — 显示在页面顶部
- - **Signing Secret** — 在 **App Credentials** 部分下
+<Steps>
+ ### 打开 Slack API 控制台
+
+ 访问 [api.slack.com/apps](https://api.slack.com/apps),点击 **Create New App** → **From an app manifest**。
+
+ ### 选择工作区
+
+ 选择您要安装应用的 Slack 工作区。
+
+ ### 粘贴 Manifest 模板
+
+ 选择 **YAML** 格式,粘贴以下模板:
+
+ ```yaml
+ display_information:
+ name: LobeHub Assistant
+ description: AI assistant powered by LobeHub
+ features:
+ app_home:
+ home_tab_enabled: false
+ messages_tab_enabled: true
+ messages_tab_read_only_enabled: false
+ bot_user:
+ display_name: LobeHub Assistant
+ always_online: true
+ oauth_config:
+ scopes:
+ bot:
+ - app_mentions:read
+ - channels:history
+ - channels:read
+ - chat:write
+ - groups:history
+ - groups:read
+ - im:history
+ - im:read
+ - mpim:history
+ - mpim:read
+ - reactions:read
+ - reactions:write
+ - users:read
+ - assistant:write
+ settings:
+ event_subscriptions:
+ bot_events:
+ - app_mention
+ - message.channels
+ - message.groups
+ - message.im
+ - message.mpim
+ - member_joined_channel
+ - assistant_thread_started
+ - assistant_thread_context_changed
+ org_deploy_enabled: false
+ socket_mode_enabled: true
+ token_rotation_enabled: false
+ ```
+
+ > **注意:** `socket_mode_enabled: true` 表示无需配置 Request URL。事件通过 WebSocket 推送。
+
+ ### 创建应用
+
+ 确认配置摘要后,点击 **Create**。
![](/blog/assets3865756ef6158a855aee64dd01bd3d6b.webp)
+</Steps>
+
+### 第二步:获取凭证
- ### 添加 Bot Token 权限范围
+<Steps>
+ ### 复制 App ID 和 Signing Secret
+
+ 在 **Basic Information** 页面,复制:
- 在左侧菜单中,进入 **OAuth & Permissions**。向下滚动到 **Scopes** → **Bot Token Scopes**,添加以下权限:
+ - **App ID** — 显示在页面顶部
+ - **Signing Secret** — 在 **App Credentials** 部分
- - `app_mentions:read` — 检测机器人被提及
- - `channels:history` — 读取公共频道中的消息
- - `channels:read` — 读取频道信息
- - `chat:write` — 发送消息
- - `groups:history` — 读取私有频道中的消息
- - `groups:read` — 读取私有频道信息
- - `im:history` — 读取私信
- - `im:read` — 读取私信频道信息
- - `mpim:history` — 读取群组私信消息
- - `mpim:read` — 读取群组私信信息
- - `reactions:read` — 读取表情回应
- - `reactions:write` — 添加表情回应
- - `users:read` — 查询用户信息
+ ### 生成应用级别 Token
- **可选权限**(用于 Slack Assistants API):
+ 向下滚动到 **App-Level Tokens**,点击 **Generate Token and Scopes**。命名(如 "socket-mode"),添加 `connections:write` 权限,点击 **Generate**。
- - `assistant:write` — 启用 Slack Assistants API 功能
+ 复制生成的 Token(以 `xapp-` 开头)。
- ### 安装应用到工作区
+ > **重要:** 此 Token 仅显示一次,请妥善保管。
- 仍然在 **OAuth & Permissions** 页面,点击 **Install to Workspace** 并授权应用。安装完成后,复制 **Bot User OAuth Token**(以 `xoxb-` 开头)。
+ ### 安装应用到工作区
- > **重要提示:** 请将您的 Bot Token 视为密码。切勿公开分享或提交到版本控制系统。
+ 进入侧边栏的 **OAuth & Permissions**,点击 **Install to Workspace** 并授权。复制 **Bot User OAuth Token**(以 `xoxb-` 开头)。
![](/blog/assetsfd4606a4b5d801a8764bf333cde77d57.webp)
</Steps>
-## 第二步:在 LobeHub 中配置 Slack
+### 第三步:在 LobeHub 中配置 Slack
<Steps>
### 打开渠道设置
- 在 LobeHub 中,导航到您的代理设置,然后选择 **渠道** 标签。点击平台列表中的 **Slack**。
+ 在 LobeHub 中,导航到代理设置 → **渠道** 标签 → 点击 **Slack**。
- ### 填写凭据
+ ### 输入凭证
- 输入以下字段:
+ 填写:
- - **应用 ID** — 来自 Slack 应用 Basic Information 页面的 App ID
- - **Bot Token** — 来自 OAuth & Permissions 页面的 Bot User OAuth Token(xoxb-...)
- - **签名密钥** — 来自 Slack 应用 Basic Information 页面的 Signing Secret
+ - **应用 ID** — App ID
+ - **Bot Token** — Bot User OAuth Token(`xoxb-...`)
+ - **签名密钥** — Signing Secret
+ - **应用级别 Token** — App-Level Token(`xapp-...`)
- 您的令牌将被加密并安全存储。
+ ### 选择连接模式
- ### 保存配置
-
- 点击 **保存配置**。LobeHub 将保存您的凭据并显示一个 **Webhook URL**。
+ 在 **高级设置** 中,将 **连接模式** 设置为 **WebSocket**。
- ### 复制 Webhook URL
+ ### 保存配置
- 复制显示的 Webhook URL —— 您将在下一步中使用它来配置 Slack 的事件订阅。
+ 点击 **保存配置**。机器人将自动通过 Socket Mode 连接。无需配置 Webhook URL。
![](/blog/assetsc3042da681a9df811e70473636a8f461.webp)
</Steps>
-## 第三步:配置事件订阅
+### 第四步:测试连接
-<Steps>
- ### 启用事件
+在 LobeHub 点击 **测试连接**,然后进入 Slack,将机器人邀请到频道,通过 `@LobeHub Assistant` 提及它,确认是否正常响应。
- 返回 [Slack API 控制台](https://api.slack.com/apps),进入 **Event Subscriptions**,将 **Enable Events** 切换为 **On**。
+---
- ### 设置请求 URL
+## Webhook 设置(备选方案)
- 将您从 LobeHub 复制的 **Webhook URL** 粘贴到 **Request URL** 字段中。Slack 将发送一个验证请求 —— LobeHub 会自动响应。
+如果您的 Slack 应用已配置了 Event Subscriptions 的公网 HTTP 端点,或无法使用 Socket Mode,请使用此方式。
- ### 订阅机器人事件
+<Steps>
+ ### 创建 Slack 应用
- 在 **Subscribe to bot events** 下,添加:
+ 访问 [api.slack.com/apps](https://api.slack.com/apps),点击 **Create New App** → **From scratch**。命名应用并选择工作区。
- - `app_mention` — 当有人提及机器人时触发
- - `message.channels` — 公共频道中的消息
- - `message.groups` — 私有频道中的消息
- - `message.im` — 发送给机器人的私信
- - `message.mpim` — 群组私信中的消息
- - `member_joined_channel` — 当用户加入频道时触发
+ ### 添加 Bot Token 权限
- **可选事件**(用于 Slack Assistants API):
+ 进入 **OAuth & Permissions** → **Bot Token Scopes**,添加:`app_mentions:read`、`channels:history`、`channels:read`、`chat:write`、`groups:history`、`groups:read`、`im:history`、`im:read`、`mpim:history`、`mpim:read`、`reactions:read`、`reactions:write`、`users:read`。
- - `assistant_thread_started` — 当用户打开新的助手会话时触发
- - `assistant_thread_context_changed` — 当用户在助手面板打开时切换到不同频道时触发
+ ### 安装到工作区
- ### 保存更改
+ 点击 **Install to Workspace**,复制 **Bot User OAuth Token**(`xoxb-...`)。
- 点击页面底部的 **Save Changes**。
+ ### 在 LobeHub 中配置
- ![](/blog/assets8f3657f3785fc04c42b0f53c17daa72e.webp)
-</Steps>
+ 在 LobeHub 的 Slack 渠道设置中输入 **应用 ID**、**Bot Token** 和 **签名密钥**。在高级设置中将 **连接模式** 设为 **Webhook**。保存后复制显示的 **Webhook URL**。
+
+ ### 配置事件订阅
-## 第四步:测试连接
+ 在 Slack API 控制台 → **Event Subscriptions** 中,启用事件,将 Webhook URL 粘贴为 **Request URL**,订阅事件:`app_mention`、`message.channels`、`message.groups`、`message.im`、`message.mpim`、`member_joined_channel`。
-返回 LobeHub 的 Slack 渠道设置,点击 **测试连接** 以验证集成是否正确。然后进入您的 Slack 工作区,将机器人邀请到一个频道,通过 `@你的机器人名称` 提及它,确认其是否响应。
+ ![](/blog/assets8f3657f3785fc04c42b0f53c17daa72e.webp)
+</Steps>
## 配置参考
-| 字段 | 是否必需 | 描述 |
-| ------------- | ---- | ------------------------------ |
-| **应用 ID** | 是 | 您的 Slack 应用的 ID |
-| **Bot Token** | 是 | Bot User OAuth Token(xoxb-...) |
-| **签名密钥** | 是 | 用于验证来自 Slack 的 Webhook 请求 |
+| 字段 | 是否必需 | 描述 |
+| -------------- | ------------- | -------------------------------------- |
+| **应用 ID** | 是 | 您的 Slack 应用 ID |
+| **Bot Token** | 是 | Bot User OAuth Token(`xoxb-...`) |
+| **签名密钥** | 是 | 用于验证来自 Slack 的请求 |
+| **应用级别 Token** | 仅 Socket Mode | 应用级别 Token(`xapp-...`),用于 WebSocket 连接 |
+| **连接模式** | 否 | `websocket` 或 `webhook`(默认:`webhook`) |
## 故障排除
-- **机器人未响应:** 确认机器人已被邀请到频道,且事件订阅已正确配置了正确的 Webhook URL。
+- **机器人未响应:** 确认机器人已被邀请到频道。Socket Mode 下请确保应用级别 Token 正确且 Socket Mode 已在 Slack 应用设置中启用。
- **测试连接失败:** 仔细检查应用 ID 和 Bot Token 是否正确。确保应用已安装到工作区。
-- **Webhook 验证失败:** 确保签名密钥与 Slack 应用 Basic Information 页面中的一致。
+- **Webhook 验证失败(Webhook 模式):** 确保签名密钥匹配且 Webhook URL 正确。
+- **Socket Mode 无法连接:** 验证应用级别 Token 具有 `connections:write` 权限。检查 Slack 应用设置中的 **Socket Mode** 是否已启用。
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 6e0d1061177..a0157348a4a 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -22,6 +22,10 @@
"channel.connectSuccess": "Bot connected successfully",
"channel.connecting": "Connecting...",
"channel.connectionConfig": "Connection Configuration",
+ "channel.connectionMode": "Connection Mode",
+ "channel.connectionModeHint": "WebSocket is recommended for new bots. Use Webhook if your bot already has a callback URL configured on QQ Open Platform.",
+ "channel.connectionModeWebSocket": "WebSocket",
+ "channel.connectionModeWebhook": "Webhook",
"channel.copied": "Copied to clipboard",
"channel.copy": "Copy",
"channel.credentials": "Credentials",
@@ -57,6 +61,8 @@
"channel.endpointUrlHint": "Please copy this URL and paste it into the <bold>{{fieldName}}</bold> field in the {{name}} Developer Portal.",
"channel.exportConfig": "Export Configuration",
"channel.feishu.description": "Connect this assistant to Feishu for private and group chats.",
+ "channel.feishu.webhookMigrationDesc": "WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket in Advanced Settings. No additional configuration is needed on the Feishu/Lark Open Platform.",
+ "channel.feishu.webhookMigrationTitle": "Consider migrating to WebSocket mode",
"channel.historyLimit": "History Message Limit",
"channel.historyLimitHint": "Default number of messages to fetch when reading channel history",
"channel.importConfig": "Import Configuration",
@@ -93,7 +99,11 @@
"channel.signingSecret": "Signing Secret",
"channel.signingSecretHint": "Used to verify webhook requests.",
"channel.slack.appIdHint": "Your Slack App ID from the Slack API dashboard (starts with A).",
+ "channel.slack.appToken": "App-Level Token",
+ "channel.slack.appTokenHint": "Required for Socket Mode (WebSocket). Generate an app-level token (xapp-...) under Basic Information in your Slack app settings.",
"channel.slack.description": "Connect this assistant to Slack for channel conversations and direct messages.",
+ "channel.slack.webhookMigrationDesc": "Socket Mode provides real-time event delivery via WebSocket without exposing a public HTTP endpoint. To migrate, enable Socket Mode in your Slack app settings, generate an App-Level Token, then switch the Connection Mode to WebSocket in Advanced Settings.",
+ "channel.slack.webhookMigrationTitle": "Consider migrating to Socket Mode (WebSocket)",
"channel.telegram.description": "Connect this assistant to Telegram for private and group chats.",
"channel.testConnection": "Test Connection",
"channel.testFailed": "Connection test failed",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index dfe5bc2a6d8..e29960077f2 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -22,6 +22,10 @@
"channel.connectSuccess": "Bot 连接成功",
"channel.connecting": "连接中...",
"channel.connectionConfig": "连接配置",
+ "channel.connectionMode": "连接模式",
+ "channel.connectionModeHint": "新机器人推荐使用 WebSocket。如果你的机器人已在 QQ 开放平台配置了回调地址,请选择 Webhook。",
+ "channel.connectionModeWebSocket": "WebSocket",
+ "channel.connectionModeWebhook": "Webhook",
"channel.copied": "已复制到剪贴板",
"channel.copy": "复制",
"channel.credentials": "凭证配置",
@@ -57,6 +61,8 @@
"channel.endpointUrlHint": "请复制此 URL 并粘贴到 {{name}} 开发者门户的 <bold>{{fieldName}}</bold> 字段中。",
"channel.exportConfig": "导出平台配置",
"channel.feishu.description": "将助手连接到飞书,支持私聊和群聊。",
+ "channel.feishu.webhookMigrationDesc": "WebSocket 模式提供实时事件推送,无需配置公网回调地址。如需迁移,在高级设置中将连接模式切换为 WebSocket 即可,无需在飞书/Lark 开放平台进行额外配置。",
+ "channel.feishu.webhookMigrationTitle": "建议迁移到 WebSocket 模式",
"channel.historyLimit": "历史消息条数",
"channel.historyLimitHint": "读取频道历史消息时默认获取的消息数量",
"channel.importConfig": "导入平台配置",
@@ -93,7 +99,11 @@
"channel.signingSecret": "签名密钥",
"channel.signingSecretHint": "用于验证 Webhook 请求。",
"channel.slack.appIdHint": "你的 Slack 应用 ID,可在 Slack API 控制台中找到(以 A 开头)。",
+ "channel.slack.appToken": "应用级别 Token",
+ "channel.slack.appTokenHint": "Socket Mode(WebSocket)所需。在 Slack 应用设置的 Basic Information 中生成应用级别 Token(xapp-...)。",
"channel.slack.description": "将助手连接到 Slack,支持频道对话和私信。",
+ "channel.slack.webhookMigrationDesc": "Socket Mode 通过 WebSocket 提供实时事件推送,无需暴露公网 HTTP 端点。如需迁移,请在 Slack 应用设置中启用 Socket Mode,生成应用级别 Token,然后在高级设置中将连接模式切换为 WebSocket。",
+ "channel.slack.webhookMigrationTitle": "建议迁移到 Socket Mode(WebSocket)",
"channel.telegram.description": "将助手连接到 Telegram,支持私聊和群聊。",
"channel.testConnection": "测试连接",
"channel.testFailed": "连接测试失败",
diff --git a/package.json b/package.json
index 53829cd9796..803d565e38b 100644
--- a/package.json
+++ b/package.json
@@ -197,6 +197,7 @@
"@huggingface/inference": "^4.13.10",
"@icons-pack/react-simple-icons": "^13.8.0",
"@khmyznikov/pwa-install": "0.3.9",
+ "@larksuiteoapi/node-sdk": "^1.60.0",
"@lexical/utils": "^0.42.0",
"@lobechat/agent-runtime": "workspace:*",
"@lobechat/agent-templates": "workspace:*",
diff --git a/packages/chat-adapter-feishu/src/adapter.test.ts b/packages/chat-adapter-feishu/src/adapter.test.ts
new file mode 100644
index 00000000000..88e4174d13b
--- /dev/null
+++ b/packages/chat-adapter-feishu/src/adapter.test.ts
@@ -0,0 +1,926 @@
+import type { MockInstance } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createLarkAdapter,
+ downloadMediaFromRawMessage,
+ extractMediaMetadata,
+ LarkAdapter,
+} from './adapter';
+import { LarkApiClient } from './api';
+import type { LarkMessageBody } from './types';
+
+// ---- helpers ----
+
+function makeLarkMessage(overrides: Partial<LarkMessageBody> = {}): LarkMessageBody {
+ return {
+ chat_id: 'oc_test_chat',
+ content: JSON.stringify({ text: 'hello' }),
+ create_time: '1700000000000',
+ message_id: 'om_test_msg_001',
+ message_type: 'text',
+ ...overrides,
+ };
+}
+
+function makeSender(overrides: Record<string, any> = {}) {
+ return {
+ sender_id: { open_id: 'ou_user_abc' },
+ sender_type: 'user',
+ ...overrides,
+ };
+}
+
+function makeWebhookPayload(message: LarkMessageBody, sender = makeSender()) {
+ return {
+ event: { message, sender },
+ header: {
+ event_type: 'im.message.receive_v1',
+ token: 'verify_tok',
+ },
+ };
+}
+
+function makeRequest(body: unknown): Request {
+ return new Request('http://localhost/webhook', {
+ body: JSON.stringify(body),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+}
+
+// ---- tests ----
+
+describe('LarkAdapter', () => {
+ let adapter: LarkAdapter;
+
+ const mockChat = {
+ getLogger: vi.fn(() => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ })),
+ getUserName: vi.fn(() => 'TestBot'),
+ processMessage: vi.fn(),
+ };
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ adapter = new LarkAdapter({
+ appId: 'cli_test',
+ appSecret: 'secret_test',
+ platform: 'lark',
+ verificationToken: 'verify_tok',
+ });
+ // Mock API methods to avoid real network calls
+ vi.spyOn((adapter as any).api, 'getTenantAccessToken').mockResolvedValue('mock_token');
+ adapter.initialize(mockChat as any);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // ---------- constructor & initialize ----------
+
+ describe('constructor', () => {
+ it('should default userName to "lark-bot"', () => {
+ const a = new LarkAdapter({ appId: 'a', appSecret: 's' });
+ expect(a.userName).toBe('lark-bot');
+ });
+
+ it('should use custom userName if provided', () => {
+ const a = new LarkAdapter({ appId: 'a', appSecret: 's', userName: 'MyBot' });
+ expect(a.userName).toBe('MyBot');
+ });
+ });
+
+ // ---------- thread ID encoding/decoding ----------
+
+ describe('encodeThreadId / decodeThreadId', () => {
+ it('should encode legacy 2-segment format when chatType is unknown', () => {
+ const encoded = adapter.encodeThreadId({ chatId: 'oc_chat1', platform: 'lark' });
+ expect(encoded).toBe('lark:oc_chat1');
+ });
+
+ it('should encode 3-segment format with chatType=p2p', () => {
+ const encoded = adapter.encodeThreadId({
+ chatId: 'oc_chat1',
+ chatType: 'p2p',
+ platform: 'lark',
+ });
+ expect(encoded).toBe('lark:p2p:oc_chat1');
+ });
+
+ it('should encode 3-segment format with chatType=group', () => {
+ const encoded = adapter.encodeThreadId({
+ chatId: 'oc_chat1',
+ chatType: 'group',
+ platform: 'feishu',
+ });
+ expect(encoded).toBe('feishu:group:oc_chat1');
+ });
+
+ it('should decode legacy 2-segment format (chatType undefined)', () => {
+ const decoded = adapter.decodeThreadId('lark:oc_chat1');
+ expect(decoded).toEqual({ chatId: 'oc_chat1', platform: 'lark' });
+ });
+
+ it('should decode feishu prefix in legacy format', () => {
+ const decoded = adapter.decodeThreadId('feishu:oc_chat2');
+ expect(decoded).toEqual({ chatId: 'oc_chat2', platform: 'feishu' });
+ });
+
+ it('should decode 3-segment p2p format', () => {
+ const decoded = adapter.decodeThreadId('lark:p2p:oc_dm');
+ expect(decoded).toEqual({ chatId: 'oc_dm', chatType: 'p2p', platform: 'lark' });
+ });
+
+ it('should decode 3-segment group format', () => {
+ const decoded = adapter.decodeThreadId('feishu:group:oc_team');
+ expect(decoded).toEqual({ chatId: 'oc_team', chatType: 'group', platform: 'feishu' });
+ });
+
+ it('should treat unrecognized middle segment as part of legacy chatId', () => {
+ // `lark:weird:oc_x` — `weird` is not a known chat type, fall back to
+ // legacy 2-segment decoding so anything in the tail (incl. extra colons)
+ // becomes the chat ID.
+ const decoded = adapter.decodeThreadId('lark:weird:oc_x');
+ expect(decoded).toEqual({ chatId: 'weird:oc_x', platform: 'lark' });
+ });
+
+ it('should fallback for bare chat ID', () => {
+ const decoded = adapter.decodeThreadId('oc_chat3');
+ expect(decoded).toEqual({ chatId: 'oc_chat3', platform: 'lark' });
+ });
+
+ it('should round-trip encode/decode for legacy format', () => {
+ const original = { chatId: 'oc_abc', platform: 'lark' as const };
+ expect(adapter.decodeThreadId(adapter.encodeThreadId(original))).toEqual(original);
+ });
+
+ it('should round-trip encode/decode for p2p format', () => {
+ const original = { chatId: 'oc_abc', chatType: 'p2p' as const, platform: 'lark' as const };
+ expect(adapter.decodeThreadId(adapter.encodeThreadId(original))).toEqual(original);
+ });
+
+ it('should round-trip encode/decode for group format', () => {
+ const original = {
+ chatId: 'oc_abc',
+ chatType: 'group' as const,
+ platform: 'feishu' as const,
+ };
+ expect(adapter.decodeThreadId(adapter.encodeThreadId(original))).toEqual(original);
+ });
+ });
+
+ // ---------- handleWebhook ----------
+
+ describe('handleWebhook', () => {
+ it('should return 400 for invalid JSON', async () => {
+ const req = new Request('http://localhost/webhook', {
+ body: 'not json',
+ method: 'POST',
+ });
+ const res = await adapter.handleWebhook(req);
+ expect(res.status).toBe(400);
+ });
+
+ it('should respond to url_verification challenge', async () => {
+ const body = { challenge: 'challenge_123', token: 'verify_tok', type: 'url_verification' };
+ const res = await adapter.handleWebhook(makeRequest(body));
+ const data = await res.json();
+ expect(data.challenge).toBe('challenge_123');
+ });
+
+ it('should reject invalid verification token', async () => {
+ const body = {
+ event: {},
+ header: { event_type: 'im.message.receive_v1', token: 'wrong_tok' },
+ };
+ const res = await adapter.handleWebhook(makeRequest(body));
+ expect(res.status).toBe(401);
+ });
+
+ it('should process text message', async () => {
+ const msg = makeLarkMessage();
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should skip empty text messages with no media', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ text: ' ' }),
+ message_type: 'text',
+ });
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).not.toHaveBeenCalled();
+ });
+
+ it('should process image message', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ image_key: 'img_test_key' }),
+ message_type: 'image',
+ });
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should process file message', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'file_test_key', file_name: 'doc.pdf' }),
+ message_type: 'file',
+ });
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should process audio message', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'audio_key' }),
+ message_type: 'audio',
+ });
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should process video (media) message', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'video_key', image_key: 'thumb_key' }),
+ message_type: 'media',
+ });
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should process sticker message', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'sticker_key' }),
+ message_type: 'sticker',
+ });
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should skip unsupported message types', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ chat_id: 'oc_xxx' }),
+ message_type: 'share_chat',
+ });
+ const res = await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).not.toHaveBeenCalled();
+ });
+ });
+
+ // ---------- parseRawEvent metadata-only attachments (webhook path) ----------
+ //
+ // The inbound parse path is metadata-only — it does NOT call the Lark
+ // resource API. Eager downloading was removed because the chat-sdk's
+ // `Message.toJSON` strips both `att.buffer` AND `att.fetchData` whenever
+ // the message is enqueued, making any pre-downloaded buffer or lazy
+ // closure pure waste. Server-side `Feishu*Client.extractFiles` is now the
+ // sole download path; it walks `message.raw` on demand via the standalone
+ // `downloadMediaFromRawMessage` helper (separately tested below).
+
+ describe('parseRawEvent metadata-only attachments', () => {
+ it('should produce metadata-only image attachment without calling the API', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadResource');
+
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ image_key: 'img_test' }),
+ message_type: 'image',
+ });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(message?.attachments).toEqual([
+ { mimeType: 'image/jpeg', name: 'image.jpg', type: 'image' },
+ ]);
+ // raw is preserved so server-side extractFiles can re-fetch from image_key.
+ expect(message?.raw).toBeDefined();
+ });
+
+ it('should produce metadata-only file attachment with name from content', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadResource');
+
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'file_test', file_name: 'report.pdf' }),
+ message_type: 'file',
+ });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(message?.attachments).toEqual([
+ {
+ mimeType: 'application/octet-stream',
+ name: 'report.pdf',
+ type: 'file',
+ },
+ ]);
+ });
+
+ it('should produce metadata-only audio attachment', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadResource');
+
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'audio_key' }),
+ message_type: 'audio',
+ });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(message?.attachments).toEqual([
+ { mimeType: 'audio/ogg', name: 'audio.ogg', type: 'audio' },
+ ]);
+ });
+
+ it('should produce metadata-only video attachment', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadResource');
+
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'video_key', image_key: 'thumb_key' }),
+ message_type: 'media',
+ });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(message?.attachments).toEqual([
+ { mimeType: 'video/mp4', name: 'video.mp4', type: 'video' },
+ ]);
+ });
+
+ it('should produce metadata-only sticker attachment as image type', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadResource');
+
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'sticker_key' }),
+ message_type: 'sticker',
+ });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(message?.attachments).toEqual([
+ { mimeType: 'image/png', name: 'sticker.png', type: 'image' },
+ ]);
+ });
+
+ it('should return no attachments for text messages', async () => {
+ const msg = makeLarkMessage();
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(msg)));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments).toEqual([]);
+ });
+ });
+
+ // ---------- mention detection ----------
+ //
+ // Lark renders @-mentions in raw text as `@_user_N` placeholders that the
+ // adapter strips before display, so the Chat SDK's text-based mention
+ // detection cannot match. The authoritative signal is `message.mentions[]`,
+ // and we look up the bot's own `open_id` (loaded during `initialize()` via
+ // `getBotInfo`) to set `Message.isMention`.
+
+ describe('mention detection', () => {
+ beforeEach(() => {
+ // Pretend bot info loaded successfully during initialize()
+ (adapter as any)._botUserId = 'ou_bot_test';
+ });
+
+ async function parseFromWebhook(message: LarkMessageBody) {
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(message)));
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ return factory?.();
+ }
+
+ it('should set isMention=true when bot is in mentions[]', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ text: '@_user_1 hello' }),
+ mentions: [{ id: { open_id: 'ou_bot_test' }, key: '@_user_1', name: 'TestBot' }],
+ });
+
+ const message = await parseFromWebhook(msg);
+
+ expect(message?.isMention).toBe(true);
+ });
+
+ it('should set isMention=false when only other users are mentioned', async () => {
+ const msg = makeLarkMessage({
+ content: JSON.stringify({ text: '@_user_1 hi' }),
+ mentions: [{ id: { open_id: 'ou_other_user' }, key: '@_user_1', name: 'Alice' }],
+ });
+
+ const message = await parseFromWebhook(msg);
+
+ expect(message?.isMention).toBe(false);
+ });
+
+ it('should set isMention=false when mentions[] is absent', async () => {
+ const message = await parseFromWebhook(makeLarkMessage());
+
+ expect(message?.isMention).toBe(false);
+ });
+
+ it('should set isMention=false when _botUserId is unknown', async () => {
+ (adapter as any)._botUserId = undefined;
+ const msg = makeLarkMessage({
+ mentions: [{ id: { open_id: 'ou_anyone' }, key: '@_user_1', name: 'X' }],
+ });
+
+ const message = await parseFromWebhook(msg);
+
+ expect(message?.isMention).toBe(false);
+ });
+
+ it('parseMessage (history fetch path) should also set isMention from mentions[]', () => {
+ const raw = makeLarkMessage({
+ mentions: [{ id: { open_id: 'ou_bot_test' }, key: '@_user_1', name: 'TestBot' }],
+ });
+
+ const message = adapter.parseMessage(raw);
+
+ expect(message.isMention).toBe(true);
+ });
+ });
+
+ // ---------- parseMessage (sync, lazy attachments) ----------
+
+ describe('parseMessage', () => {
+ it('should parse text message with no attachments', () => {
+ const raw = makeLarkMessage();
+ const message = adapter.parseMessage(raw);
+
+ expect(message.text).toBe('hello');
+ expect(message.id).toBe('om_test_msg_001');
+ expect(message.attachments).toEqual([]);
+ });
+
+ it('should strip @mentions from text', () => {
+ const raw = makeLarkMessage({
+ content: JSON.stringify({ text: '@_user_1 hello @_all' }),
+ });
+ const message = adapter.parseMessage(raw);
+ expect(message.text).toBe('hello');
+ });
+
+ it('should create metadata-only attachment for image message', () => {
+ const raw = makeLarkMessage({
+ content: JSON.stringify({ image_key: 'img_lazy' }),
+ message_type: 'image',
+ });
+ const message = adapter.parseMessage(raw);
+
+ expect(message.attachments).toHaveLength(1);
+ expect(message.attachments[0].type).toBe('image');
+ expect(message.attachments[0].mimeType).toBe('image/jpeg');
+ // No fetchData closure or buffer — actual download is server-side via
+ // FeishuWebhookClient.extractFiles → downloadMediaFromRawMessage(api, raw).
+ expect((message.attachments[0] as any).fetchData).toBeUndefined();
+ expect((message.attachments[0] as any).buffer).toBeUndefined();
+ });
+
+ it('should create metadata-only attachment for file message', () => {
+ const raw = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'file_lazy', file_name: 'doc.xlsx' }),
+ message_type: 'file',
+ });
+ const message = adapter.parseMessage(raw);
+
+ expect(message.attachments).toHaveLength(1);
+ expect(message.attachments[0].type).toBe('file');
+ expect(message.attachments[0].name).toBe('doc.xlsx');
+ expect((message.attachments[0] as any).fetchData).toBeUndefined();
+ });
+
+ it('should create metadata-only attachment for audio message', () => {
+ const raw = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'audio_lazy' }),
+ message_type: 'audio',
+ });
+ const message = adapter.parseMessage(raw);
+
+ expect(message.attachments).toHaveLength(1);
+ expect(message.attachments[0].type).toBe('audio');
+ expect((message.attachments[0] as any).fetchData).toBeUndefined();
+ });
+
+ it('should create metadata-only attachment for video message', () => {
+ const raw = makeLarkMessage({
+ content: JSON.stringify({ file_key: 'video_lazy', image_key: 'thumb' }),
+ message_type: 'media',
+ });
+ const message = adapter.parseMessage(raw);
+
+ expect(message.attachments).toHaveLength(1);
+ expect(message.attachments[0].type).toBe('video');
+ expect((message.attachments[0] as any).fetchData).toBeUndefined();
+ });
+
+ it('should return empty attachments for malformed content', () => {
+ const raw = makeLarkMessage({
+ content: 'not json',
+ message_type: 'image',
+ });
+ const message = adapter.parseMessage(raw);
+ expect(message.attachments).toEqual([]);
+ });
+
+ it('should return empty attachments when key is missing', () => {
+ const raw = makeLarkMessage({
+ content: JSON.stringify({}),
+ message_type: 'image',
+ });
+ const message = adapter.parseMessage(raw);
+ expect(message.attachments).toEqual([]);
+ });
+ });
+
+ // ---------- no-op methods ----------
+
+ describe('no-op methods', () => {
+ it('addReaction should resolve', async () => {
+ vi.spyOn((adapter as any).api, 'addReaction').mockResolvedValue(undefined);
+ await expect(adapter.addReaction('t', 'msg', 'thumbsup')).resolves.toBeUndefined();
+ });
+
+ it('removeReaction should resolve (no-op)', async () => {
+ await expect(adapter.removeReaction('t', 'msg', 'emoji')).resolves.toBeUndefined();
+ });
+
+ it('startTyping should resolve (no-op)', async () => {
+ await expect(adapter.startTyping('t')).resolves.toBeUndefined();
+ });
+ });
+
+ // ---------- isDM ----------
+
+ describe('isDM', () => {
+ it('should return true for a p2p threadId', () => {
+ expect(adapter.isDM('lark:p2p:oc_dm')).toBe(true);
+ });
+
+ it('should return false for a group threadId', () => {
+ expect(adapter.isDM('lark:group:oc_team')).toBe(false);
+ });
+
+ it('should return false for an unknown legacy threadId with no cache hit', () => {
+ expect(adapter.isDM('lark:oc_chat1')).toBe(false);
+ });
+
+ it('should make handleWebhook produce a p2p threadId for single-chat events', async () => {
+ const message = makeLarkMessage({ chat_id: 'oc_p2p', chat_type: 'p2p' });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(message)));
+
+ const threadId = vi.mocked(mockChat.processMessage).mock.calls[0]?.[1];
+ expect(threadId).toBe('lark:p2p:oc_p2p');
+ expect(adapter.isDM(threadId as string)).toBe(true);
+ });
+
+ it('should make handleWebhook produce a group threadId for group events', async () => {
+ const message = makeLarkMessage({ chat_id: 'oc_team', chat_type: 'group' });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(message)));
+
+ const threadId = vi.mocked(mockChat.processMessage).mock.calls[0]?.[1];
+ expect(threadId).toBe('lark:group:oc_team');
+ expect(adapter.isDM(threadId as string)).toBe(false);
+ });
+
+ // ----- legacy 2-segment threadId fallback -----
+ //
+ // Persisted threadIds from before the encoded-type rollout look like
+ // `lark:oc_xxx` and have no chat type to decode. We still want isDM to
+ // answer correctly for them while migration runs, so the adapter records
+ // P2P chat IDs from incoming webhook events into a per-process set and
+ // consults it whenever decode returns no chatType.
+
+ it('should fall back to the p2p set for a legacy threadId after a p2p webhook', async () => {
+ const message = makeLarkMessage({ chat_id: 'oc_legacy_dm', chat_type: 'p2p' });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(message)));
+
+ // Legacy 2-segment format — must hit the fallback path
+ expect(adapter.isDM('lark:oc_legacy_dm')).toBe(true);
+ });
+
+ it('should not flip a legacy threadId to DM after only a group webhook', async () => {
+ const message = makeLarkMessage({ chat_id: 'oc_legacy_group', chat_type: 'group' });
+ await adapter.handleWebhook(makeRequest(makeWebhookPayload(message)));
+
+ expect(adapter.isDM('lark:oc_legacy_group')).toBe(false);
+ });
+
+ it('should let the encoded type win over the fallback set', () => {
+ // Manually seed the fallback set as if a prior webhook had recorded
+ // this chat as P2P, then ask isDM for an explicitly group-typed
+ // threadId for the same chat ID. The encoded type must take precedence
+ // — the set is a fallback, not an override.
+ (adapter as any).p2pChatIds.add('oc_disputed');
+
+ expect(adapter.isDM('lark:group:oc_disputed')).toBe(false);
+ expect(adapter.isDM('lark:p2p:oc_disputed')).toBe(true);
+ // Legacy form for the same chat still hits the fallback
+ expect(adapter.isDM('lark:oc_disputed')).toBe(true);
+ });
+ });
+});
+
+// ---------- createLarkAdapter factory ----------
+
+describe('createLarkAdapter', () => {
+ it('should return a LarkAdapter instance', () => {
+ const adapter = createLarkAdapter({ appId: 'a', appSecret: 's' });
+ expect(adapter).toBeInstanceOf(LarkAdapter);
+ expect(adapter.name).toBe('lark');
+ });
+
+ it('should use feishu platform when specified', () => {
+ const adapter = createLarkAdapter({ appId: 'a', appSecret: 's', platform: 'feishu' });
+ expect(adapter.name).toBe('feishu');
+ });
+});
+
+// ---------- extractMediaMetadata (the metadata-only parse-time helper) ----------
+
+describe('extractMediaMetadata', () => {
+ it('returns empty array for text messages', () => {
+ expect(extractMediaMetadata(makeLarkMessage())).toEqual([]);
+ });
+
+ it('returns empty array for post messages', () => {
+ expect(
+ extractMediaMetadata(makeLarkMessage({ message_type: 'post', content: JSON.stringify({}) })),
+ ).toEqual([]);
+ });
+
+ it('returns empty array for malformed content JSON', () => {
+ expect(
+ extractMediaMetadata(makeLarkMessage({ content: 'not json', message_type: 'image' })),
+ ).toEqual([]);
+ });
+
+ it('returns metadata-only image attachment', () => {
+ const attachments = extractMediaMetadata(
+ makeLarkMessage({
+ content: JSON.stringify({ image_key: 'img_1' }),
+ message_type: 'image',
+ }),
+ );
+ expect(attachments).toEqual([{ mimeType: 'image/jpeg', name: 'image.jpg', type: 'image' }]);
+ });
+
+ it('returns metadata-only file attachment with name from content', () => {
+ const attachments = extractMediaMetadata(
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 'f_1', file_name: 'plan.pdf' }),
+ message_type: 'file',
+ }),
+ );
+ expect(attachments).toEqual([
+ { mimeType: 'application/octet-stream', name: 'plan.pdf', type: 'file' },
+ ]);
+ });
+
+ it('falls back to "file" name when file_name missing', () => {
+ const attachments = extractMediaMetadata(
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 'f_1' }),
+ message_type: 'file',
+ }),
+ );
+ expect(attachments[0].name).toBe('file');
+ });
+
+ it('returns metadata-only audio attachment', () => {
+ const attachments = extractMediaMetadata(
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 'a_1' }),
+ message_type: 'audio',
+ }),
+ );
+ expect(attachments).toEqual([{ mimeType: 'audio/ogg', name: 'audio.ogg', type: 'audio' }]);
+ });
+
+ it('returns metadata-only video attachment for media type', () => {
+ const attachments = extractMediaMetadata(
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 'v_1', image_key: 't_1' }),
+ message_type: 'media',
+ }),
+ );
+ expect(attachments).toEqual([{ mimeType: 'video/mp4', name: 'video.mp4', type: 'video' }]);
+ });
+
+ it('returns metadata-only sticker attachment as image type', () => {
+ const attachments = extractMediaMetadata(
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 's_1' }),
+ message_type: 'sticker',
+ }),
+ );
+ expect(attachments).toEqual([{ mimeType: 'image/png', name: 'sticker.png', type: 'image' }]);
+ });
+
+ it('returns empty array when image_key is missing', () => {
+ expect(
+ extractMediaMetadata(makeLarkMessage({ content: JSON.stringify({}), message_type: 'image' })),
+ ).toEqual([]);
+ });
+});
+
+// ---------- downloadMediaFromRawMessage (the on-demand download path) ----------
+//
+// This is the helper called by server-side `Feishu*Client.extractFiles` to
+// materialize media after a chat-sdk Redis round-trip has stripped any
+// in-memory buffer/fetchData. It walks `raw.content` (JSON) and downloads
+// each media item via `LarkApiClient.downloadResource(messageId, key, type)`.
+
+describe('downloadMediaFromRawMessage', () => {
+ let api: LarkApiClient;
+ let downloadSpy: MockInstance<LarkApiClient['downloadResource']>;
+
+ beforeEach(() => {
+ api = new LarkApiClient('app', 'secret', 'feishu');
+ downloadSpy = vi.spyOn(api, 'downloadResource') as MockInstance<
+ LarkApiClient['downloadResource']
+ >;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('downloads an image via image_key + downloadResource(messageId, key, "image")', async () => {
+ const imageBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
+ downloadSpy.mockResolvedValueOnce(imageBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({
+ content: JSON.stringify({ image_key: 'img_1' }),
+ message_type: 'image',
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledTimes(1);
+ expect(downloadSpy).toHaveBeenCalledWith('om_test_msg_001', 'img_1', 'image');
+ expect(result).toEqual([
+ {
+ buffer: imageBytes,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ },
+ ]);
+ });
+
+ it('downloads a file via file_key with name from content', async () => {
+ const pdfBytes = Buffer.from([0x25, 0x50, 0x44, 0x46]);
+ downloadSpy.mockResolvedValueOnce(pdfBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 'f_1', file_name: 'doc.pdf' }),
+ message_type: 'file',
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledWith('om_test_msg_001', 'f_1', 'file');
+ expect(result).toEqual([
+ {
+ buffer: pdfBytes,
+ mimeType: 'application/octet-stream',
+ name: 'doc.pdf',
+ type: 'file',
+ },
+ ]);
+ });
+
+ it('downloads audio via file_key as audio/ogg', async () => {
+ const audioBytes = Buffer.from([0x4f, 0x67, 0x67, 0x53]);
+ downloadSpy.mockResolvedValueOnce(audioBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 'a_1' }),
+ message_type: 'audio',
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledWith('om_test_msg_001', 'a_1', 'file');
+ expect(result).toEqual([
+ { buffer: audioBytes, mimeType: 'audio/ogg', name: 'audio.ogg', type: 'audio' },
+ ]);
+ });
+
+ it('downloads video via file_key as video/mp4', async () => {
+ const videoBytes = Buffer.from([0x00, 0x00, 0x00, 0x18]);
+ downloadSpy.mockResolvedValueOnce(videoBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 'v_1', image_key: 't_1' }),
+ message_type: 'media',
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledWith('om_test_msg_001', 'v_1', 'file');
+ expect(result?.[0]?.type).toBe('video');
+ });
+
+ it('downloads sticker via file_key with type "image" (not "file")', async () => {
+ const stickerBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
+ downloadSpy.mockResolvedValueOnce(stickerBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({
+ content: JSON.stringify({ file_key: 's_1' }),
+ message_type: 'sticker',
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledWith('om_test_msg_001', 's_1', 'image');
+ expect(result?.[0]?.mimeType).toBe('image/png');
+ });
+
+ it('returns empty array when downloadResource throws (per-item swallow)', async () => {
+ downloadSpy.mockRejectedValueOnce(new Error('Download failed: 500'));
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({
+ content: JSON.stringify({ image_key: 'img_broken' }),
+ message_type: 'image',
+ }),
+ );
+
+ expect(result).toEqual([]);
+ });
+
+ it('returns empty array for text messages', async () => {
+ const result = await downloadMediaFromRawMessage(api, makeLarkMessage());
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(result).toEqual([]);
+ });
+
+ it('returns empty array when content is malformed JSON', async () => {
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({ content: 'not json', message_type: 'image' }),
+ );
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(result).toEqual([]);
+ });
+
+ it('forwards warnings to the optional logger on download failure', async () => {
+ downloadSpy.mockRejectedValueOnce(new Error('boom'));
+ const warn = vi.fn();
+
+ await downloadMediaFromRawMessage(
+ api,
+ makeLarkMessage({
+ content: JSON.stringify({ image_key: 'img_1' }),
+ message_type: 'image',
+ }),
+ { warn },
+ );
+
+ expect(warn).toHaveBeenCalled();
+ });
+});
diff --git a/packages/chat-adapter-feishu/src/adapter.ts b/packages/chat-adapter-feishu/src/adapter.ts
index 417b29f6580..600f0e0076f 100644
--- a/packages/chat-adapter-feishu/src/adapter.ts
+++ b/packages/chat-adapter-feishu/src/adapter.ts
@@ -1,6 +1,7 @@
import type {
Adapter,
AdapterPostableMessage,
+ Attachment,
Author,
ChatInstance,
EmojiValue,
@@ -25,6 +26,236 @@ import type {
LarkWebhookPayload,
} from './types';
+type WarnFn = (message: string, ...args: unknown[]) => void;
+
+/**
+ * Encode a Lark/Feishu thread ID with optional inline chat type.
+ *
+ * - `lark:p2p:oc_xxx` single chat (DM with bot)
+ * - `lark:group:oc_xxx` group chat
+ * - `lark:oc_xxx` legacy / unknown type — emitted only when callers
+ * don't have `chatType` at hand (e.g. `parseMessage`
+ * on history fetches). `decodeLarkThreadId` accepts
+ * both formats so older persisted threadIds keep working.
+ *
+ * Encoding the chat type into the threadId itself lets the sync `isDM` the
+ * Chat SDK requires be a pure function of its argument, matching the pattern
+ * Discord uses (`discord:guildId:channelId:...`, isDM = `guildId === '@me'`)
+ * and Slack uses (channel ID prefix `D`).
+ */
+export function encodeLarkThreadId(data: LarkThreadId): string {
+ if (data.chatType === 'p2p' || data.chatType === 'group') {
+ return `${data.platform}:${data.chatType}:${data.chatId}`;
+ }
+ return `${data.platform}:${data.chatId}`;
+}
+
+/**
+ * Decode a Lark/Feishu thread ID. Accepts BOTH the new 3-segment format
+ * (`<platform>:<chatType>:<chatId>`) and the legacy 2-segment format
+ * (`<platform>:<chatId>`) so threadIds persisted in Redis from before the
+ * encoded-type rollout still resolve correctly.
+ *
+ * Exported as a standalone helper so the server-side bot platform clients
+ * (which extract `chatId` for outbound API calls) share a single source of
+ * truth with the adapter and don't have to duplicate the parsing rules.
+ */
+export function decodeLarkThreadId(
+ threadId: string,
+ defaultPlatform: 'lark' | 'feishu' = 'lark',
+): LarkThreadId {
+ const colonIdx = threadId.indexOf(':');
+ if (colonIdx === -1) {
+ return { chatId: threadId, platform: defaultPlatform };
+ }
+ const prefix = threadId.slice(0, colonIdx);
+ const rest = threadId.slice(colonIdx + 1);
+ const platform = prefix === 'lark' || prefix === 'feishu' ? prefix : defaultPlatform;
+
+ // New format: `<platform>:<chatType>:<chatId>` — only when the second
+ // segment is a recognized chat type. Otherwise treat the whole tail as
+ // the chat ID (legacy 2-segment format) so old persisted IDs still decode.
+ const nextColon = rest.indexOf(':');
+ if (nextColon !== -1) {
+ const maybeType = rest.slice(0, nextColon);
+ if (maybeType === 'p2p' || maybeType === 'group') {
+ return {
+ chatId: rest.slice(nextColon + 1),
+ chatType: maybeType,
+ platform,
+ };
+ }
+ }
+
+ return { chatId: rest, platform };
+}
+
+/**
+ * Walk a raw Feishu/Lark message and produce metadata-only attachments — no
+ * downloads. Used by `LarkAdapter.parseMessage` and `parseRawEvent` so the
+ * inbound parse path stays cheap: media bytes are downloaded later, on
+ * demand, by the server-side `Feishu*Client.extractFiles`.
+ *
+ * Why metadata-only at parse time:
+ * 1. The chat-sdk's `Message.toJSON` strips both `buffer` AND `fetchData`
+ * from attachments whenever the message is enqueued (debounce always;
+ * queue when busy). Eager downloads OR lazy fetchData closures are
+ * both wasted across a Redis round-trip.
+ * 2. Most inbound messages in group chats are not addressed to the bot —
+ * pre-downloading them is pure CPU/bandwidth waste for the 99% case.
+ * 3. Concentrating the download path in one place (the server-side
+ * `extractFiles`) makes the data flow easier to reason about.
+ *
+ * The returned fields all survive `Message.toJSON` (type/mimeType/name in
+ * its allowlist), so downstream consumers still get a count + descriptive
+ * metadata for each attachment.
+ */
+export function extractMediaMetadata(raw: LarkRawMessage): Attachment[] {
+ const messageType = raw.message_type;
+ if (messageType === 'text' || messageType === 'post') return [];
+
+ let content: Record<string, string>;
+ try {
+ content = JSON.parse(raw.content);
+ } catch {
+ return [];
+ }
+
+ switch (messageType) {
+ case 'image': {
+ if (!content.image_key) return [];
+ return [{ mimeType: 'image/jpeg', name: 'image.jpg', type: 'image' } as Attachment];
+ }
+ case 'file': {
+ if (!content.file_key) return [];
+ return [
+ {
+ mimeType: 'application/octet-stream',
+ name: content.file_name || 'file',
+ type: 'file',
+ } as Attachment,
+ ];
+ }
+ case 'audio': {
+ if (!content.file_key) return [];
+ return [{ mimeType: 'audio/ogg', name: 'audio.ogg', type: 'audio' } as Attachment];
+ }
+ case 'media': {
+ if (!content.file_key) return [];
+ return [{ mimeType: 'video/mp4', name: 'video.mp4', type: 'video' } as Attachment];
+ }
+ case 'sticker': {
+ if (!content.file_key) return [];
+ return [{ mimeType: 'image/png', name: 'sticker.png', type: 'image' } as Attachment];
+ }
+ default: {
+ return [];
+ }
+ }
+}
+
+/**
+ * Standalone helper that downloads media for a raw Feishu/Lark message,
+ * returning attachments with `buffer` populated. This is the primary
+ * download path used by the server-side `Feishu*Client.extractFiles` to
+ * materialize media on demand after a chat-sdk Redis round-trip has
+ * stripped any in-memory data.
+ *
+ * Pure function — owns no state, takes the api client + raw message + an
+ * optional logger. Per-item errors are caught and logged so a single
+ * failed download doesn't drop the rest of the message's attachments.
+ */
+export async function downloadMediaFromRawMessage(
+ api: LarkApiClient,
+ raw: LarkRawMessage,
+ logger?: Pick<Logger, 'warn'>,
+): Promise<Attachment[]> {
+ const warn: WarnFn = logger?.warn?.bind(logger) ?? (() => {});
+
+ const messageType = raw.message_type;
+ if (messageType === 'text' || messageType === 'post') return [];
+
+ let content: Record<string, string>;
+ try {
+ content = JSON.parse(raw.content);
+ } catch {
+ return [];
+ }
+
+ const messageId = raw.message_id;
+ const attachments: Attachment[] = [];
+
+ try {
+ switch (messageType) {
+ case 'image': {
+ const imageKey = content.image_key;
+ if (!imageKey) break;
+ const buffer = await api.downloadResource(messageId, imageKey, 'image');
+ attachments.push({
+ buffer,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ } as Attachment);
+ break;
+ }
+ case 'file': {
+ const fileKey = content.file_key;
+ if (!fileKey) break;
+ const buffer = await api.downloadResource(messageId, fileKey, 'file');
+ attachments.push({
+ buffer,
+ mimeType: 'application/octet-stream',
+ name: content.file_name || 'file',
+ type: 'file',
+ } as Attachment);
+ break;
+ }
+ case 'audio': {
+ const fileKey = content.file_key;
+ if (!fileKey) break;
+ const buffer = await api.downloadResource(messageId, fileKey, 'file');
+ attachments.push({
+ buffer,
+ mimeType: 'audio/ogg',
+ name: 'audio.ogg',
+ type: 'audio',
+ } as Attachment);
+ break;
+ }
+ case 'media': {
+ // Video: has file_key (video) and image_key (thumbnail)
+ const fileKey = content.file_key;
+ if (!fileKey) break;
+ const buffer = await api.downloadResource(messageId, fileKey, 'file');
+ attachments.push({
+ buffer,
+ mimeType: 'video/mp4',
+ name: 'video.mp4',
+ type: 'video',
+ } as Attachment);
+ break;
+ }
+ case 'sticker': {
+ const fileKey = content.file_key;
+ if (!fileKey) break;
+ const buffer = await api.downloadResource(messageId, fileKey, 'image');
+ attachments.push({
+ buffer,
+ mimeType: 'image/png',
+ name: 'sticker.png',
+ type: 'image',
+ } as Attachment);
+ break;
+ }
+ }
+ } catch (error) {
+ warn('Failed to download %s media for message %s: %s', messageType, messageId, error);
+ }
+
+ return attachments;
+}
+
export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
readonly name: string;
private readonly api: LarkApiClient;
@@ -48,6 +279,20 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
return this._botUserId;
}
+ /**
+ * Legacy fallback for `isDM`. New code emits the chat type into the
+ * threadId itself (`lark:p2p:oc_xxx`) so `isDM` can be a pure function,
+ * but threadIds persisted in Redis from before this change still use the
+ * 2-segment format `lark:oc_xxx` and have no type info to decode.
+ *
+ * To avoid losing isDM correctness for those legacy IDs, we still record
+ * P2P chat IDs as we see them on incoming webhook events. `isDM` consults
+ * this set only when the threadId has no encoded type. The set rebuilds
+ * itself from live traffic after a restart, and can be retired entirely
+ * once no legacy threadIds remain in Redis.
+ */
+ private p2pChatIds = new Set<string>();
+
constructor(config: LarkAdapterConfig & { logger?: Logger; userName?: string }) {
this.platform = config.platform || 'lark';
this.name = this.platform;
@@ -141,27 +386,53 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
return Response.json({ ok: true });
}
- // Only handle text messages for now
- if (message.message_type !== 'text') {
- return Response.json({ ok: true });
+ // Record P2P chats in the legacy fallback set so `isDM` still answers
+ // correctly for any pre-migration threadId in the 2-segment format that
+ // doesn't carry an encoded chat type. New threadIds emitted below carry
+ // the type inline, so they don't need this lookup.
+ if (message.chat_type === 'p2p') {
+ this.p2pChatIds.add(message.chat_id);
}
- // Extract text content
+ // Extract text content (for text messages) or media description
+ const messageType = message.message_type;
let messageText = '';
+ let hasMedia = false;
+
try {
const content = JSON.parse(message.content);
- messageText = content.text || '';
+ switch (messageType) {
+ case 'text': {
+ messageText = content.text || '';
+ break;
+ }
+ case 'image':
+ case 'file':
+ case 'audio':
+ case 'media':
+ case 'sticker': {
+ hasMedia = true;
+ break;
+ }
+ }
} catch {
// malformed content
}
- if (!messageText.trim()) {
+ if (!messageText.trim() && !hasMedia) {
return Response.json({ ok: true });
}
- // Build thread ID
+ // Build thread ID — encode chat type so the sync `isDM(threadId)` the
+ // Chat SDK calls during dispatch can derive the answer purely from the
+ // threadId, with no side cache. `chat_type` is set by Lark on every
+ // receive event: 'p2p' for single-chat with the bot, 'group' for groups.
const threadId = this.encodeThreadId({
chatId: message.chat_id,
+ chatType:
+ message.chat_type === 'p2p' || message.chat_type === 'group'
+ ? message.chat_type
+ : undefined,
platform: this.platform,
});
@@ -277,8 +548,13 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
platform: this.platform,
});
+ // Metadata-only attachments — actual binary download happens later, on
+ // demand, in the server-side `Feishu*Client.extractFiles`. See
+ // `extractMediaMetadata` (top of file) for why we don't pre-download.
+ const attachments = extractMediaMetadata(raw);
+
return new Message({
- attachments: [],
+ attachments,
author: {
fullName: 'Unknown',
isBot: false,
@@ -288,6 +564,7 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
},
formatted,
id: raw.message_id,
+ isMention: this.detectBotMention(raw),
metadata: {
dateSent: new Date(Number(raw.create_time)),
edited: false,
@@ -337,19 +614,11 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
// ------------------------------------------------------------------
encodeThreadId(data: LarkThreadId): string {
- return `${data.platform}:${data.chatId}`;
+ return encodeLarkThreadId(data);
}
decodeThreadId(threadId: string): LarkThreadId {
- const colonIdx = threadId.indexOf(':');
- if (colonIdx === -1) {
- return { chatId: threadId, platform: this.platform };
- }
- const prefix = threadId.slice(0, colonIdx);
- const chatId = threadId.slice(colonIdx + 1);
-
- const platform = prefix === 'lark' || prefix === 'feishu' ? prefix : this.platform;
- return { chatId, platform };
+ return decodeLarkThreadId(threadId, this.platform);
}
channelIdFromThreadId(threadId: string): string {
@@ -357,8 +626,12 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
}
isDM(threadId: string): boolean {
- // Can't determine from threadId alone; default false
- return false;
+ const { chatId, chatType } = this.decodeThreadId(threadId);
+ // New 3-segment threadIds carry the type inline — pure-function path.
+ if (chatType !== undefined) return chatType === 'p2p';
+ // Legacy 2-segment threadId — fall back to the per-process P2P set
+ // populated from incoming webhook events. See `p2pChatIds` for context.
+ return this.p2pChatIds.has(chatId);
}
// ------------------------------------------------------------------
@@ -399,11 +672,17 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
userName: displayName,
};
+ // Metadata-only attachments — actual binary download happens later, on
+ // demand, in the server-side `Feishu*Client.extractFiles`. See
+ // `extractMediaMetadata` (top of file) for why we don't pre-download.
+ const attachments = extractMediaMetadata(message);
+
return new Message({
- attachments: [],
+ attachments,
author,
formatted,
id: message.message_id,
+ isMention: this.detectBotMention(message),
metadata: {
dateSent: new Date(Number(message.create_time)),
edited: false,
@@ -414,6 +693,25 @@ export class LarkAdapter implements Adapter<LarkThreadId, LarkRawMessage> {
});
}
+ /**
+ * Detect whether the bot is @-mentioned in a Lark message.
+ *
+ * Lark renders @-mentions in raw text as `@_user_N` placeholders that the
+ * adapter strips before display, so the Chat SDK's text-based mention
+ * detection (which regexes `@username`) never matches. The authoritative
+ * signal is the `mentions[]` array on the event payload — each entry has
+ * the mentioned user's `open_id`. We compare against the bot's own
+ * `_botUserId` (loaded during `initialize()` via `getBotInfo`).
+ *
+ * Returns false when `_botUserId` is unknown (e.g. bot info fetch failed)
+ * to avoid false positives from comparing against `undefined`.
+ */
+ private detectBotMention(message: LarkMessageBody): boolean {
+ const botUserId = this._botUserId;
+ if (!botUserId) return false;
+ return message.mentions?.some((m) => m.id?.open_id === botUserId) === true;
+ }
+
private async resolveSenderName(openId: string): Promise<string | undefined> {
// Skip API calls if we already know permission is denied
if (this.senderNamePermissionDenied) return undefined;
diff --git a/packages/chat-adapter-feishu/src/api.ts b/packages/chat-adapter-feishu/src/api.ts
index 1e23251637a..1c649746580 100644
--- a/packages/chat-adapter-feishu/src/api.ts
+++ b/packages/chat-adapter-feishu/src/api.ts
@@ -123,6 +123,39 @@ export class LarkApiClient {
return name ? { name } : null;
}
+ // ------------------------------------------------------------------
+ // Media / Resource download
+ // ------------------------------------------------------------------
+
+ /**
+ * Download a message resource (image, file, audio, video, sticker).
+ *
+ * @see https://open.feishu.cn/document/server-docs/im-v1/message-attachment/get
+ * @param messageId - The message_id that contains the resource
+ * @param fileKey - file_key or image_key from the message content
+ * @param type - Resource type: 'image' | 'file'
+ */
+ async downloadResource(
+ messageId: string,
+ fileKey: string,
+ type: 'image' | 'file',
+ ): Promise<Buffer> {
+ const token = await this.getTenantAccessToken();
+ const url = `${this.baseUrl}/im/v1/messages/${messageId}/resources/${fileKey}?type=${type}`;
+
+ const response = await fetch(url, {
+ headers: { Authorization: `Bearer ${token}` },
+ method: 'GET',
+ });
+
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(`Lark downloadResource failed: ${response.status} ${text}`);
+ }
+
+ return Buffer.from(await response.arrayBuffer());
+ }
+
// ------------------------------------------------------------------
// Auth
// ------------------------------------------------------------------
diff --git a/packages/chat-adapter-feishu/src/index.ts b/packages/chat-adapter-feishu/src/index.ts
index 1385ad7e67a..7d16cbb7e81 100644
--- a/packages/chat-adapter-feishu/src/index.ts
+++ b/packages/chat-adapter-feishu/src/index.ts
@@ -1,4 +1,11 @@
-export { createLarkAdapter, LarkAdapter } from './adapter';
+export {
+ createLarkAdapter,
+ decodeLarkThreadId,
+ downloadMediaFromRawMessage,
+ encodeLarkThreadId,
+ extractMediaMetadata,
+ LarkAdapter,
+} from './adapter';
export { LarkApiClient } from './api';
export { decryptLarkEvent } from './crypto';
export { LarkFormatConverter } from './format-converter';
diff --git a/packages/chat-adapter-feishu/src/types.ts b/packages/chat-adapter-feishu/src/types.ts
index e635b893cec..6d9cf21687d 100644
--- a/packages/chat-adapter-feishu/src/types.ts
+++ b/packages/chat-adapter-feishu/src/types.ts
@@ -22,6 +22,14 @@ export interface LarkAdapterConfig {
export interface LarkThreadId {
/** Lark chat ID (group or P2P) */
chatId: string;
+ /**
+ * Lark chat type, encoded into the threadId so the sync `isDM(threadId)`
+ * the Chat SDK requires can derive the answer without a side cache.
+ * `undefined` means unknown — produced by paths that don't have the chat
+ * type at hand (e.g. `parseMessage` for historical fetches), and decoded
+ * back from the legacy 2-segment threadId format for backward compat.
+ */
+ chatType?: 'p2p' | 'group';
/** Platform variant */
platform: 'lark' | 'feishu';
}
diff --git a/packages/chat-adapter-feishu/vitest.config.mts b/packages/chat-adapter-feishu/vitest.config.mts
new file mode 100644
index 00000000000..5b40bc079f3
--- /dev/null
+++ b/packages/chat-adapter-feishu/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ all: false,
+ },
+ environment: 'node',
+ },
+});
diff --git a/packages/chat-adapter-qq/src/adapter.test.ts b/packages/chat-adapter-qq/src/adapter.test.ts
new file mode 100644
index 00000000000..7075417e19b
--- /dev/null
+++ b/packages/chat-adapter-qq/src/adapter.test.ts
@@ -0,0 +1,445 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createQQAdapter, QQAdapter } from './adapter';
+import type { QQAttachment, QQRawMessage, QQWebhookPayload } from './types';
+import { QQ_EVENT_TYPES, QQ_OP_CODES } from './types';
+
+// ---- helpers ----
+
+function makeQQRawMessage(overrides: Partial<QQRawMessage> = {}): QQRawMessage {
+ return {
+ author: { id: 'user_123' },
+ content: 'hello',
+ id: 'msg_001',
+ timestamp: '2024-01-01T00:00:00Z',
+ ...overrides,
+ };
+}
+
+function makeWebhookPayload(eventType: string, data: Record<string, any>): QQWebhookPayload {
+ return {
+ d: {
+ author: { id: 'user_123' },
+ content: 'hello',
+ group_openid: 'group_abc',
+ id: 'msg_001',
+ timestamp: '2024-01-01T00:00:00Z',
+ ...data,
+ },
+ id: 'event_001',
+ op: QQ_OP_CODES.DISPATCH,
+ t: eventType,
+ };
+}
+
+function makeRequest(body: unknown): Request {
+ return new Request('http://localhost/webhook', {
+ body: JSON.stringify(body),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+}
+
+function makeAttachment(overrides: Partial<QQAttachment> = {}): QQAttachment {
+ return {
+ content_type: 'image/png',
+ filename: 'image.png',
+ height: 600,
+ size: 248736,
+ url: 'https://multimedia.nt.qq.com.cn/test-image',
+ width: 800,
+ ...overrides,
+ };
+}
+
+// ---- tests ----
+
+describe('QQAdapter', () => {
+ let adapter: QQAdapter;
+
+ const mockChat = {
+ getLogger: vi.fn(() => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ })),
+ getUserName: vi.fn(() => 'TestBot'),
+ processMessage: vi.fn(),
+ };
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ adapter = new QQAdapter({ appId: 'test_app', clientSecret: 'test_secret' });
+ // Mock API to avoid real network calls
+ vi.spyOn((adapter as any).api, 'getAccessToken').mockResolvedValue('mock_token');
+ adapter.initialize(mockChat as any);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // ---------- constructor ----------
+
+ describe('constructor', () => {
+ it('should default userName to "qq-bot"', () => {
+ const a = new QQAdapter({ appId: 'a', clientSecret: 's' });
+ expect(a.userName).toBe('qq-bot');
+ });
+
+ it('should use custom userName if provided', () => {
+ const a = new QQAdapter({ appId: 'a', clientSecret: 's', userName: 'MyBot' });
+ expect(a.userName).toBe('MyBot');
+ });
+ });
+
+ // ---------- thread ID encoding/decoding ----------
+
+ describe('encodeThreadId / decodeThreadId', () => {
+ it('should encode group thread ID', () => {
+ const encoded = adapter.encodeThreadId({ id: 'group_1', type: 'group' });
+ expect(encoded).toBe('qq:group:group_1');
+ });
+
+ it('should encode guild thread ID with guildId', () => {
+ const encoded = adapter.encodeThreadId({ guildId: 'g1', id: 'ch1', type: 'guild' });
+ expect(encoded).toBe('qq:guild:ch1:g1');
+ });
+
+ it('should decode group thread ID', () => {
+ const decoded = adapter.decodeThreadId('qq:group:group_1');
+ expect(decoded).toEqual({ guildId: undefined, id: 'group_1', type: 'group' });
+ });
+
+ it('should decode guild thread ID with guildId', () => {
+ const decoded = adapter.decodeThreadId('qq:guild:ch1:g1');
+ expect(decoded).toEqual({ guildId: 'g1', id: 'ch1', type: 'guild' });
+ });
+
+ it('should round-trip encode/decode for c2c', () => {
+ const original = { id: 'user_1', type: 'c2c' as const };
+ const encoded = adapter.encodeThreadId(original);
+ const decoded = adapter.decodeThreadId(encoded);
+ expect(decoded.id).toBe('user_1');
+ expect(decoded.type).toBe('c2c');
+ });
+ });
+
+ // ---------- isDM ----------
+
+ describe('isDM', () => {
+ it('should return true for c2c type', () => {
+ expect(adapter.isDM('qq:c2c:user_1')).toBe(true);
+ });
+
+ it('should return true for dms type', () => {
+ expect(adapter.isDM('qq:dms:guild_1')).toBe(true);
+ });
+
+ it('should return false for group type', () => {
+ expect(adapter.isDM('qq:group:group_1')).toBe(false);
+ });
+ });
+
+ // ---------- handleWebhook ----------
+
+ describe('handleWebhook', () => {
+ it('should return 400 for invalid JSON', async () => {
+ const req = new Request('http://localhost/webhook', {
+ body: 'not json',
+ method: 'POST',
+ });
+ const res = await adapter.handleWebhook(req);
+ expect(res.status).toBe(400);
+ });
+
+ it('should handle webhook verification (op: 13)', async () => {
+ vi.spyOn(await import('./crypto'), 'signWebhookResponse').mockReturnValue('mock_sig');
+ const body: QQWebhookPayload = {
+ d: { event_ts: '12345', plain_token: 'tok' },
+ id: 'v1',
+ op: QQ_OP_CODES.VERIFY,
+ t: undefined as any,
+ };
+ const res = await adapter.handleWebhook(makeRequest(body));
+ const data = await res.json();
+ expect(data.plain_token).toBe('tok');
+ expect(data.signature).toBe('mock_sig');
+ });
+
+ it('should skip non-message events', async () => {
+ const body: QQWebhookPayload = {
+ d: {} as any,
+ id: 'e1',
+ op: QQ_OP_CODES.DISPATCH,
+ t: 'GUILD_CREATE',
+ };
+ const res = await adapter.handleWebhook(makeRequest(body));
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).not.toHaveBeenCalled();
+ });
+
+ it('should process group message', async () => {
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {});
+ const res = await adapter.handleWebhook(makeRequest(payload));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should skip empty content with no attachments', async () => {
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ content: ' ',
+ });
+ const res = await adapter.handleWebhook(makeRequest(payload));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).not.toHaveBeenCalled();
+ });
+
+ it('should process message with empty content but attachments', async () => {
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ attachments: [makeAttachment()],
+ content: '',
+ });
+ const res = await adapter.handleWebhook(makeRequest(payload));
+
+ expect(res.status).toBe(200);
+ expect(mockChat.processMessage).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ // ---------- attachment mapping ----------
+
+ describe('attachment mapping', () => {
+ it('should map image attachments from webhook', async () => {
+ const attachment = makeAttachment({
+ content_type: 'image/png',
+ filename: 'screenshot.png',
+ height: 600,
+ size: 100000,
+ url: 'https://multimedia.nt.qq.com.cn/test.png',
+ width: 800,
+ });
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ attachments: [attachment],
+ content: 'check this',
+ });
+ await adapter.handleWebhook(makeRequest(payload));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments).toHaveLength(1);
+ expect(message?.attachments[0].type).toBe('image');
+ expect(message?.attachments[0].mimeType).toBe('image/png');
+ expect(message?.attachments[0].name).toBe('screenshot.png');
+ expect(message?.attachments[0].size).toBe(100000);
+ expect(message?.attachments[0].width).toBe(800);
+ expect(message?.attachments[0].height).toBe(600);
+ expect(message?.attachments[0].url).toBe('https://multimedia.nt.qq.com.cn/test.png');
+ expect(message?.attachments[0].fetchData).toBeTypeOf('function');
+ });
+
+ it('should map video attachments', async () => {
+ const attachment = makeAttachment({
+ content_type: 'video/mp4',
+ filename: 'clip.mp4',
+ size: 5000000,
+ });
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ attachments: [attachment],
+ content: 'video',
+ });
+ await adapter.handleWebhook(makeRequest(payload));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments[0].type).toBe('video');
+ expect(message?.attachments[0].mimeType).toBe('video/mp4');
+ });
+
+ it('should map audio attachments', async () => {
+ const attachment = makeAttachment({
+ content_type: 'audio/mp3',
+ filename: 'voice.mp3',
+ });
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ attachments: [attachment],
+ content: 'audio',
+ });
+ await adapter.handleWebhook(makeRequest(payload));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments[0].type).toBe('audio');
+ });
+
+ it('should map file attachments with unknown content type', async () => {
+ const attachment = makeAttachment({
+ content_type: 'application/pdf',
+ filename: 'doc.pdf',
+ });
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ attachments: [attachment],
+ content: 'file',
+ });
+ await adapter.handleWebhook(makeRequest(payload));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments[0].type).toBe('file');
+ });
+
+ it('should map multiple attachments', async () => {
+ const attachments = [
+ makeAttachment({ content_type: 'image/png', filename: 'a.png' }),
+ makeAttachment({ content_type: 'video/mp4', filename: 'b.mp4' }),
+ ];
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ attachments,
+ content: 'multi',
+ });
+ await adapter.handleWebhook(makeRequest(payload));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments).toHaveLength(2);
+ expect(message?.attachments[0].type).toBe('image');
+ expect(message?.attachments[1].type).toBe('video');
+ });
+
+ it('should return empty attachments when none provided', async () => {
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {});
+ await adapter.handleWebhook(makeRequest(payload));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.attachments).toEqual([]);
+ });
+
+ it('should store attachments in raw message', async () => {
+ const attachment = makeAttachment();
+ const payload = makeWebhookPayload(QQ_EVENT_TYPES.GROUP_AT_MESSAGE_CREATE, {
+ attachments: [attachment],
+ content: 'test',
+ });
+ await adapter.handleWebhook(makeRequest(payload));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(message?.raw.attachments).toHaveLength(1);
+ expect(message?.raw.attachments?.[0].url).toBe(attachment.url);
+ });
+ });
+
+ // ---------- parseMessage attachment mapping ----------
+
+ describe('parseMessage', () => {
+ it('should parse text message with no attachments', () => {
+ const raw = makeQQRawMessage({ group_openid: 'g1' });
+ const message = adapter.parseMessage(raw);
+
+ expect(message.text).toBe('hello');
+ expect(message.attachments).toEqual([]);
+ });
+
+ it('should map attachments in parseMessage', () => {
+ const raw = makeQQRawMessage({
+ attachments: [makeAttachment()],
+ group_openid: 'g1',
+ });
+ const message = adapter.parseMessage(raw);
+
+ expect(message.attachments).toHaveLength(1);
+ expect(message.attachments[0].type).toBe('image');
+ expect(message.attachments[0].mimeType).toBe('image/png');
+ expect(message.attachments[0].name).toBe('image.png');
+ expect(message.attachments[0].fetchData).toBeTypeOf('function');
+ });
+
+ it('should build thread ID from group_openid', () => {
+ const raw = makeQQRawMessage({ group_openid: 'group_abc' });
+ const message = adapter.parseMessage(raw);
+ expect(message.threadId).toBe('qq:group:group_abc');
+ });
+
+ it('should build thread ID from channel_id', () => {
+ const raw = makeQQRawMessage({ channel_id: 'ch1', guild_id: 'g1' });
+ const message = adapter.parseMessage(raw);
+ expect(message.threadId).toBe('qq:guild:ch1:g1');
+ });
+
+ it('should build thread ID from author for c2c', () => {
+ const raw = makeQQRawMessage();
+ const message = adapter.parseMessage(raw);
+ expect(message.threadId).toBe('qq:c2c:user_123');
+ });
+ });
+
+ // ---------- fetchAttachmentData ----------
+
+ describe('fetchAttachmentData', () => {
+ it('should fetch attachment data via fetchData callback', async () => {
+ const imageBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValueOnce(new Response(imageBytes, { status: 200 })),
+ );
+
+ const raw = makeQQRawMessage({
+ attachments: [makeAttachment({ url: 'https://example.com/test.png' })],
+ group_openid: 'g1',
+ });
+ const message = adapter.parseMessage(raw);
+ const data = await message.attachments[0].fetchData!();
+
+ expect(data).toBeInstanceOf(Buffer);
+ expect(data.length).toBe(4);
+
+ vi.unstubAllGlobals();
+ });
+ });
+
+ // ---------- no-op methods ----------
+
+ describe('no-op methods', () => {
+ it('addReaction should resolve', async () => {
+ await expect(adapter.addReaction('t', 'msg', 'emoji')).resolves.toBeUndefined();
+ });
+
+ it('removeReaction should resolve', async () => {
+ await expect(adapter.removeReaction('t', 'msg', 'emoji')).resolves.toBeUndefined();
+ });
+
+ it('startTyping should resolve', async () => {
+ await expect(adapter.startTyping('t')).resolves.toBeUndefined();
+ });
+ });
+
+ // ---------- fetchMessages ----------
+
+ describe('fetchMessages', () => {
+ it('should return empty result', async () => {
+ const result = await adapter.fetchMessages('any');
+ expect(result).toEqual({ messages: [], nextCursor: undefined });
+ });
+ });
+});
+
+// ---------- createQQAdapter factory ----------
+
+describe('createQQAdapter', () => {
+ it('should return a QQAdapter instance', () => {
+ const adapter = createQQAdapter({ appId: 'a', clientSecret: 's' });
+ expect(adapter).toBeInstanceOf(QQAdapter);
+ expect(adapter.name).toBe('qq');
+ });
+});
diff --git a/packages/chat-adapter-qq/src/adapter.ts b/packages/chat-adapter-qq/src/adapter.ts
index c2cf5246f20..95059f65813 100644
--- a/packages/chat-adapter-qq/src/adapter.ts
+++ b/packages/chat-adapter-qq/src/adapter.ts
@@ -1,6 +1,7 @@
import type {
Adapter,
AdapterPostableMessage,
+ Attachment,
Author,
ChatInstance,
EmojiValue,
@@ -17,8 +18,10 @@ import { Message, parseMarkdown } from 'chat';
import { QQApiClient } from './api';
import { signWebhookResponse } from './crypto';
import { QQFormatConverter } from './format-converter';
+import { QQGatewayConnection } from './gateway';
import type {
QQAdapterConfig,
+ QQAttachment,
QQRawMessage,
QQThreadId,
QQWebhookEventData,
@@ -117,9 +120,10 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {
return Response.json({ ok: true });
}
- // Extract message content
+ // Extract message content — allow through if there are attachments
const content = eventData.content;
- if (!content?.trim()) {
+ const hasAttachments = eventData.attachments && eventData.attachments.length > 0;
+ if (!content?.trim() && !hasAttachments) {
return Response.json({ ok: true });
}
@@ -178,6 +182,33 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {
}
}
+ // ------------------------------------------------------------------
+ // Gateway listener (WebSocket mode)
+ // ------------------------------------------------------------------
+
+ /**
+ * Start a persistent WebSocket gateway connection.
+ * Dispatch events are forwarded to the webhookUrl as HTTP POSTs,
+ * preserving compatibility with the existing handleWebhook() pipeline.
+ */
+ async startGatewayListener(
+ options: { waitUntil: (task: Promise<any>) => void },
+ durationMs: number,
+ abortSignal: AbortSignal,
+ webhookUrl: string,
+ ): Promise<void> {
+ const gateway = new QQGatewayConnection(this.api, {
+ abortSignal,
+ durationMs,
+ log: (msg: string, ...rest: any[]) => this.logger.info(msg, ...rest),
+ webhookUrl,
+ });
+
+ const gatewayTask = gateway.connect();
+ options.waitUntil(gatewayTask);
+ await gatewayTask;
+ }
+
// ------------------------------------------------------------------
// Message operations
// ------------------------------------------------------------------
@@ -281,8 +312,10 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {
threadId = this.encodeThreadId({ id: raw.author.id, type: 'c2c' });
}
+ const attachments = this.mapQQAttachments(raw.attachments);
+
return new Message({
- attachments: [],
+ attachments,
author: {
fullName: 'Unknown',
isBot: false,
@@ -323,6 +356,7 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {
};
const raw: QQRawMessage = {
+ attachments: data.attachments,
author: data.author || { id: 'unknown' },
channel_id: data.channel_id,
content,
@@ -332,8 +366,10 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {
timestamp: data.timestamp || new Date().toISOString(),
};
+ const attachments = this.mapQQAttachments(data.attachments);
+
return new Message({
- attachments: [],
+ attachments,
author,
formatted,
id: data.id || '',
@@ -347,6 +383,47 @@ export class QQAdapter implements Adapter<QQThreadId, QQRawMessage> {
});
}
+ // ------------------------------------------------------------------
+ // Attachment mapping
+ // ------------------------------------------------------------------
+
+ /**
+ * Map QQ attachments to Chat SDK Attachment objects.
+ * QQ provides direct URLs for media files.
+ */
+ private mapQQAttachments(qqAttachments?: QQAttachment[]): Attachment[] {
+ if (!qqAttachments || qqAttachments.length === 0) return [];
+
+ return qqAttachments.map((a) => {
+ const type = this.resolveAttachmentType(a.content_type);
+ return {
+ fetchData: () => this.fetchAttachmentData(a.url),
+ height: a.height,
+ mimeType: a.content_type,
+ name: a.filename,
+ size: a.size,
+ type,
+ url: a.url,
+ width: a.width,
+ } as Attachment;
+ });
+ }
+
+ private resolveAttachmentType(contentType: string): 'image' | 'video' | 'audio' | 'file' {
+ if (contentType.startsWith('image/')) return 'image';
+ if (contentType.startsWith('video/')) return 'video';
+ if (contentType.startsWith('audio/')) return 'audio';
+ return 'file';
+ }
+
+ private async fetchAttachmentData(url: string): Promise<Buffer> {
+ const response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
+ if (!response.ok) {
+ throw new Error(`Failed to fetch QQ attachment: ${response.status}`);
+ }
+ return Buffer.from(await response.arrayBuffer());
+ }
+
// ------------------------------------------------------------------
// Reactions (not supported by QQ Bot API)
// ------------------------------------------------------------------
diff --git a/packages/chat-adapter-qq/src/api.ts b/packages/chat-adapter-qq/src/api.ts
index 8bd2b249542..6a0767cdbe3 100644
--- a/packages/chat-adapter-qq/src/api.ts
+++ b/packages/chat-adapter-qq/src/api.ts
@@ -1,4 +1,9 @@
-import type { QQAccessTokenResponse, QQSendMessageParams, QQSendMessageResponse } from './types';
+import type {
+ QQAccessTokenResponse,
+ QQGatewayUrlResponse,
+ QQSendMessageParams,
+ QQSendMessageResponse,
+} from './types';
import { QQ_MSG_TYPE } from './types';
const AUTH_URL = 'https://bots.qq.com/app/getAppAccessToken';
@@ -174,6 +179,13 @@ export class QQApiClient {
return this.call<QQSendMessageResponse>('POST', `/dms/${guildId}/messages`, params);
}
+ /**
+ * Get the WebSocket gateway URL for establishing a persistent connection.
+ */
+ async getGatewayUrl(): Promise<QQGatewayUrlResponse> {
+ return this.call<QQGatewayUrlResponse>('GET', '/gateway');
+ }
+
/**
* Get bot information
*/
diff --git a/packages/chat-adapter-qq/src/gateway.test.ts b/packages/chat-adapter-qq/src/gateway.test.ts
new file mode 100644
index 00000000000..395f7b0f641
--- /dev/null
+++ b/packages/chat-adapter-qq/src/gateway.test.ts
@@ -0,0 +1,460 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { QQGatewayOptions } from './gateway';
+import { QQGatewayConnection } from './gateway';
+import { QQ_WS_OP_CODES } from './types';
+
+// ---- Mock WebSocket ----
+
+class MockWebSocket {
+ static OPEN = 1;
+ static CLOSED = 3;
+ static instances: MockWebSocket[] = [];
+
+ readyState = MockWebSocket.OPEN;
+ url: string;
+ private listeners: Map<string, Array<(...args: any[]) => void>> = new Map();
+ sentMessages: string[] = [];
+
+ constructor(url: string) {
+ this.url = url;
+ MockWebSocket.instances.push(this);
+ // Simulate async open
+ setTimeout(() => this.emit('open', {}), 0);
+ }
+
+ addEventListener(event: string, fn: (...args: any[]) => void) {
+ const list = this.listeners.get(event) || [];
+ list.push(fn);
+ this.listeners.set(event, list);
+ }
+
+ removeEventListener(event: string, fn: (...args: any[]) => void) {
+ const list = this.listeners.get(event) || [];
+ this.listeners.set(
+ event,
+ list.filter((f) => f !== fn),
+ );
+ }
+
+ send(data: string) {
+ this.sentMessages.push(data);
+ }
+
+ close(code?: number, reason?: string) {
+ this.readyState = MockWebSocket.CLOSED;
+ this.emit('close', { code: code ?? 1000, reason: reason ?? '' });
+ }
+
+ // Test helpers
+ emit(event: string, data: any) {
+ const list = this.listeners.get(event) || [];
+ for (const fn of list) fn(data);
+ }
+
+ simulateMessage(payload: Record<string, any>) {
+ this.emit('message', { data: JSON.stringify(payload) });
+ }
+
+ getLastSentPayload(): Record<string, any> | undefined {
+ const last = this.sentMessages.at(-1);
+ return last ? JSON.parse(last) : undefined;
+ }
+}
+
+// ---- Mock API Client ----
+
+function createMockApi() {
+ return {
+ getAccessToken: vi.fn().mockResolvedValue('mock_access_token'),
+ getGatewayUrl: vi.fn().mockResolvedValue({ url: 'wss://mock-gateway.qq.com/websocket/' }),
+ } as any;
+}
+
+// ---- Tests ----
+
+describe('QQGatewayConnection', () => {
+ beforeEach(() => {
+ MockWebSocket.instances = [];
+ vi.stubGlobal('WebSocket', MockWebSocket);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('ok', { status: 200 })));
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ function createConnection(overrides?: Partial<QQGatewayOptions>) {
+ const api = createMockApi();
+ const options: QQGatewayOptions = {
+ log: vi.fn(),
+ webhookUrl: 'http://localhost:3000/api/agent/webhooks/qq/test_app',
+ ...overrides,
+ };
+ const conn = new QQGatewayConnection(api, options);
+ return { api, conn, options };
+ }
+
+ async function connectAndGetWs(overrides?: Partial<QQGatewayOptions>) {
+ const result = createConnection(overrides);
+ const connectPromise = result.conn.connect();
+
+ // Let the WebSocket open
+ await vi.advanceTimersByTimeAsync(10);
+
+ const ws = MockWebSocket.instances[0];
+ return { ...result, connectPromise, ws };
+ }
+
+ describe('connect', () => {
+ it('should fetch gateway URL and open WebSocket', async () => {
+ const { api, connectPromise, ws } = await connectAndGetWs();
+
+ expect(api.getGatewayUrl).toHaveBeenCalled();
+ expect(ws.url).toBe('wss://mock-gateway.qq.com/websocket/');
+
+ // Simulate Hello → Identify → Ready
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+
+ await connectPromise;
+ });
+
+ it('should send Identify after receiving Hello', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ const identifyPayload = ws.getLastSentPayload();
+ expect(identifyPayload?.op).toBe(QQ_WS_OP_CODES.IDENTIFY);
+ expect(identifyPayload?.d.token).toBe('QQBot mock_access_token');
+ expect(identifyPayload?.d.intents).toBeTypeOf('number');
+ expect(identifyPayload?.d.shard).toEqual([0, 1]);
+
+ // Complete the connection
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+ });
+
+ it('should resolve when abortSignal is already aborted', async () => {
+ const abort = new AbortController();
+ abort.abort();
+ const { conn } = createConnection({ abortSignal: abort.signal });
+ await conn.connect(); // Should resolve immediately
+ });
+
+ it('should reject when identify fails before READY', async () => {
+ const { api, connectPromise, ws } = await connectAndGetWs();
+ vi.mocked(api.getAccessToken).mockRejectedValueOnce(new Error('bad token'));
+ const rejection = expect(connectPromise).rejects.toThrow('bad token');
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ await rejection;
+ });
+ });
+
+ describe('heartbeat', () => {
+ it('should send heartbeat after jittered interval', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ // Complete READY
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ // Advance past jitter + interval to trigger heartbeat
+ await vi.advanceTimersByTimeAsync(50000);
+
+ const heartbeats = ws.sentMessages
+ .map((m) => JSON.parse(m))
+ .filter((p) => p.op === QQ_WS_OP_CODES.HEARTBEAT);
+
+ expect(heartbeats.length).toBeGreaterThanOrEqual(1);
+ expect(heartbeats[0].d).toBe(1); // seq from READY
+ });
+
+ it('should handle heartbeat ACK', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ // Send heartbeat ACK
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HEARTBEAT_ACK });
+ // Should not crash — just marks ACK as received
+ });
+ });
+
+ describe('dispatch event forwarding', () => {
+ it('should forward message events to webhook URL', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ // Simulate a message event
+ ws.simulateMessage({
+ d: {
+ author: { id: 'user_1' },
+ content: 'hello',
+ group_openid: 'group_1',
+ id: 'msg_1',
+ timestamp: '2024-01-01T00:00:00Z',
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 2,
+ t: 'GROUP_AT_MESSAGE_CREATE',
+ });
+
+ await vi.advanceTimersByTimeAsync(10);
+
+ expect(fetch).toHaveBeenCalledWith(
+ 'http://localhost:3000/api/agent/webhooks/qq/test_app',
+ expect.objectContaining({
+ body: expect.any(String),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ }),
+ );
+
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
+ const body = JSON.parse(fetchCall[1]!.body as string);
+ expect(body.op).toBe(0);
+ expect(body.t).toBe('GROUP_AT_MESSAGE_CREATE');
+ expect(body.d.content).toBe('hello');
+ });
+ });
+
+ describe('reconnection', () => {
+ it('should handle server reconnect request (OP 7)', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ // Server requests reconnect
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.RECONNECT });
+
+ // WebSocket should be closed
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+
+ it('should handle invalid session (OP 9) with canResume=false', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ // Invalid session, cannot resume
+ ws.simulateMessage({ d: false, op: QQ_WS_OP_CODES.INVALID_SESSION });
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+
+ it('should reconnect after a post-READY close', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ ws.close(4000, 'network reset');
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(MockWebSocket.instances).toHaveLength(2);
+ });
+ });
+
+ describe('close', () => {
+ it('should clean up on close()', async () => {
+ const { conn, connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ conn.close();
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+
+ it('should stop on abort signal', async () => {
+ const abort = new AbortController();
+ const { connectPromise, ws } = await connectAndGetWs({ abortSignal: abort.signal });
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ abort.abort();
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+ });
+
+ describe('sequence tracking', () => {
+ it('should track sequence numbers from dispatch events', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ op: QQ_WS_OP_CODES.HELLO, d: { heartbeat_interval: 45000 } });
+ await vi.advanceTimersByTimeAsync(10);
+
+ ws.simulateMessage({
+ d: {
+ session_id: 'sess_1',
+ shard: [0, 1],
+ user: { bot: true, id: 'bot_1', username: 'TestBot' },
+ version: 1,
+ },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 1,
+ t: 'READY',
+ });
+ await connectPromise;
+
+ // Send another event with s=5
+ ws.simulateMessage({
+ d: { content: 'test' },
+ op: QQ_WS_OP_CODES.DISPATCH,
+ s: 5,
+ t: 'GROUP_AT_MESSAGE_CREATE',
+ });
+
+ // Advance to trigger heartbeat
+ await vi.advanceTimersByTimeAsync(50000);
+
+ const heartbeats = ws.sentMessages
+ .map((m) => JSON.parse(m))
+ .filter((p) => p.op === QQ_WS_OP_CODES.HEARTBEAT);
+
+ // Latest heartbeat should use seq=5
+ const lastHeartbeat = heartbeats.at(-1);
+ expect(lastHeartbeat?.d).toBe(5);
+ });
+ });
+});
diff --git a/packages/chat-adapter-qq/src/gateway.ts b/packages/chat-adapter-qq/src/gateway.ts
new file mode 100644
index 00000000000..6a1caa761b2
--- /dev/null
+++ b/packages/chat-adapter-qq/src/gateway.ts
@@ -0,0 +1,477 @@
+import type { QQApiClient } from './api';
+import type {
+ QQGatewayHelloData,
+ QQGatewayPayload,
+ QQGatewayReadyData,
+ QQGatewayUrlResponse,
+} from './types';
+import { QQ_INTENTS, QQ_WS_OP_CODES } from './types';
+
+export type GatewayLogger = (...args: any[]) => void;
+
+// Default no-op logger
+const noop: GatewayLogger = () => {};
+
+const RECONNECT_BASE_DELAY_MS = 1000;
+const RECONNECT_MAX_DELAY_MS = 60_000;
+const MAX_RECONNECT_ATTEMPTS = 10;
+
+// Heartbeat interval bounds — sanitize values from gateway to avoid unbounded timers
+const HEARTBEAT_MIN_INTERVAL_MS = 1_000;
+const HEARTBEAT_MAX_INTERVAL_MS = 300_000;
+const HEARTBEAT_DEFAULT_INTERVAL_MS = 45_000;
+
+/**
+ * Default intents for message-handling bots:
+ * - PUBLIC_GUILD_MESSAGES: @bot mentions in public guild channels
+ * - DIRECT_MESSAGE: Direct messages
+ * - GROUP_AND_C2C_EVENT: Group and C2C (friend) messages
+ */
+const DEFAULT_INTENTS =
+ QQ_INTENTS.PUBLIC_GUILD_MESSAGES | QQ_INTENTS.DIRECT_MESSAGE | QQ_INTENTS.GROUP_AND_C2C_EVENT;
+
+export interface QQGatewayOptions {
+ /** AbortSignal to cancel the gateway connection */
+ abortSignal?: AbortSignal;
+ /** Duration in ms before the connection auto-closes (caller restarts) */
+ durationMs?: number;
+ /** Bitmask of intents to subscribe to */
+ intents?: number;
+ /** Optional logger function (defaults to no-op) */
+ log?: GatewayLogger;
+ /** Shard configuration [shard_id, total_shards] */
+ shard?: [number, number];
+ /** URL to forward dispatch events to (POST) */
+ webhookUrl: string;
+}
+
+/**
+ * Manages a persistent WebSocket connection to the QQ Bot Gateway.
+ *
+ * Lifecycle: connect → Hello → Identify → Ready → heartbeat loop + event dispatch.
+ * Supports resume on disconnect using stored session_id + seq.
+ */
+export class QQGatewayConnection {
+ private readonly api: QQApiClient;
+ private readonly intents: number;
+ private readonly log: GatewayLogger;
+ private readonly shard: [number, number];
+ private readonly webhookUrl: string;
+ private readonly abortSignal?: AbortSignal;
+ private readonly durationMs?: number;
+
+ private ws: WebSocket | null = null;
+ private sessionId: string | null = null;
+ private seq: number | null = null;
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
+ private heartbeatAcked = true;
+ private reconnectAttempts = 0;
+ private gatewayUrl: string | null = null;
+ private resumeGatewayUrl: string | null = null;
+ private closed = false;
+ private openConnectionError: Error | null = null;
+ private hasConnected = false;
+
+ constructor(api: QQApiClient, options: QQGatewayOptions) {
+ this.api = api;
+ this.intents = options.intents ?? DEFAULT_INTENTS;
+ this.log = options.log ?? noop;
+ this.shard = options.shard ?? [0, 1];
+ this.webhookUrl = options.webhookUrl;
+ this.abortSignal = options.abortSignal;
+ this.durationMs = options.durationMs;
+ }
+
+ /**
+ * Start the gateway connection. Resolves once the READY event is received.
+ * Rejects if the initial connection or identification fails.
+ */
+ async connect(): Promise<void> {
+ if (this.abortSignal?.aborted) return;
+
+ // Fetch gateway URL
+ const gatewayInfo: QQGatewayUrlResponse = await this.api.getGatewayUrl();
+ this.gatewayUrl = gatewayInfo.url;
+
+ this.log('Gateway URL: %s (shards: %d)', this.gatewayUrl, gatewayInfo.shards ?? 1);
+
+ return this.openConnection(this.gatewayUrl, false);
+ }
+
+ /**
+ * Gracefully close the gateway connection.
+ */
+ close(): void {
+ this.closed = true;
+ this.stopHeartbeat();
+ if (this.ws) {
+ this.ws.close(1000, 'Client shutdown');
+ this.ws = null;
+ }
+ }
+
+ // ---------- Connection Management ----------
+
+ private openConnection(url: string, isResume: boolean): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ if (this.abortSignal?.aborted || this.closed) {
+ resolve();
+ return;
+ }
+
+ const ws = new WebSocket(url);
+ this.ws = ws;
+
+ let resolved = false;
+ this.openConnectionError = null;
+
+ const onAbort = () => {
+ this.close();
+ if (!resolved) {
+ resolved = true;
+ resolve();
+ }
+ };
+
+ this.abortSignal?.addEventListener('abort', onAbort, { once: true });
+
+ ws.addEventListener('open', () => {
+ this.log('WebSocket connected (resume=%s)', isResume);
+ this.reconnectAttempts = 0;
+ });
+
+ ws.addEventListener('message', (event) => {
+ const data =
+ typeof event.data === 'string'
+ ? event.data
+ : new TextDecoder().decode(event.data as ArrayBuffer);
+ let payload: QQGatewayPayload;
+ try {
+ payload = JSON.parse(data);
+ } catch {
+ this.log('Failed to parse gateway message: %s', data);
+ return;
+ }
+
+ this.handlePayload(payload, isResume, (err?: Error) => {
+ if (resolved) return;
+ resolved = true;
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+
+ ws.addEventListener('close', (event) => {
+ this.log('WebSocket closed: code=%d reason=%s', event.code, event.reason);
+ this.stopHeartbeat();
+ this.abortSignal?.removeEventListener('abort', onAbort);
+
+ if (!resolved) {
+ resolved = true;
+ const error = this.openConnectionError;
+ this.openConnectionError = null;
+
+ if (error) {
+ reject(error);
+ } else if (this.closed || this.abortSignal?.aborted || this.hasConnected) {
+ resolve();
+ } else {
+ reject(
+ new Error(
+ `QQ gateway socket closed before ${isResume ? 'RESUMED' : 'READY'}: ` +
+ `code=${event.code} reason=${event.reason || 'unknown'}`,
+ ),
+ );
+ }
+ }
+
+ if (this.hasConnected && !this.closed && !this.abortSignal?.aborted) {
+ this.attemptReconnect();
+ }
+ });
+
+ ws.addEventListener('error', (event) => {
+ this.log('WebSocket error: %O', event);
+ if (!resolved) {
+ resolved = true;
+ reject(new Error('WebSocket connection failed'));
+ }
+ });
+
+ // Auto-close after durationMs
+ if (this.durationMs) {
+ setTimeout(() => {
+ if (!this.closed && !this.abortSignal?.aborted) {
+ this.log('Duration elapsed (%dms), closing', this.durationMs);
+ this.close();
+ }
+ }, this.durationMs);
+ }
+ });
+ }
+
+ // ---------- Payload Handling ----------
+
+ private handlePayload(
+ payload: QQGatewayPayload,
+ isResume: boolean,
+ onReady: (err?: Error) => void,
+ ): void {
+ // Track sequence number for heartbeat and resume
+ if (payload.s !== undefined && payload.s !== null) {
+ this.seq = payload.s;
+ }
+
+ switch (payload.op) {
+ case QQ_WS_OP_CODES.HELLO: {
+ this.handleHello(payload.d as QQGatewayHelloData, isResume);
+ break;
+ }
+
+ case QQ_WS_OP_CODES.DISPATCH: {
+ this.handleDispatch(payload, onReady);
+ break;
+ }
+
+ case QQ_WS_OP_CODES.HEARTBEAT_ACK: {
+ this.heartbeatAcked = true;
+ break;
+ }
+
+ case QQ_WS_OP_CODES.RECONNECT: {
+ this.log('Server requested reconnect');
+ this.ws?.close(4000, 'Server reconnect');
+ break;
+ }
+
+ case QQ_WS_OP_CODES.INVALID_SESSION: {
+ const canResume = payload.d === true;
+ this.log('Invalid session (canResume=%s)', canResume);
+ if (!canResume) {
+ // Clear session — must re-identify
+ this.sessionId = null;
+ this.seq = null;
+ }
+ this.ws?.close(4000, 'Invalid session');
+ break;
+ }
+
+ case QQ_WS_OP_CODES.HEARTBEAT: {
+ // Server may request an immediate heartbeat
+ this.sendHeartbeat();
+ break;
+ }
+
+ default: {
+ this.log('Unhandled OP code: %d', payload.op);
+ }
+ }
+ }
+
+ private handleHello(data: QQGatewayHelloData, isResume: boolean): void {
+ // Clamp gateway-provided interval into a safe range to prevent resource exhaustion
+ const rawInterval = data.heartbeat_interval;
+ const safeInterval = Number.isFinite(rawInterval)
+ ? Math.min(Math.max(rawInterval, HEARTBEAT_MIN_INTERVAL_MS), HEARTBEAT_MAX_INTERVAL_MS)
+ : HEARTBEAT_DEFAULT_INTERVAL_MS;
+
+ this.log('Hello received, heartbeat_interval=%dms (effective=%dms)', rawInterval, safeInterval);
+ this.startHeartbeat(safeInterval);
+
+ if (isResume && this.sessionId) {
+ this.sendResume();
+ } else {
+ this.sendIdentify();
+ }
+ }
+
+ private handleDispatch(payload: QQGatewayPayload, onReady: (err?: Error) => void): void {
+ const eventType = payload.t;
+
+ if (eventType === 'READY') {
+ const readyData = payload.d as QQGatewayReadyData;
+ this.sessionId = readyData.session_id;
+ this.hasConnected = true;
+ this.log('Ready: session_id=%s user=%s', this.sessionId, readyData.user?.username);
+ onReady();
+ return;
+ }
+
+ if (eventType === 'RESUMED') {
+ this.hasConnected = true;
+ this.log('Session resumed');
+ onReady();
+ return;
+ }
+
+ // Forward all other dispatch events to the webhook URL
+ this.forwardEvent(payload);
+ }
+
+ // ---------- Send Operations ----------
+
+ private sendIdentify(): void {
+ this.api
+ .getAccessToken()
+ .then((token) => {
+ const identifyPayload: QQGatewayPayload = {
+ d: {
+ intents: this.intents,
+ properties: {
+ $browser: 'lobehub-gateway',
+ $device: 'lobehub-gateway',
+ $os: 'linux',
+ },
+ shard: this.shard,
+ token: `QQBot ${token}`,
+ },
+ op: QQ_WS_OP_CODES.IDENTIFY,
+ };
+
+ this.send(identifyPayload);
+ this.log('Identify sent (intents=%d, shard=%o)', this.intents, this.shard);
+ })
+ .catch((err) => {
+ this.log('Failed to get access token for identify: %O', err);
+ this.openConnectionError =
+ err instanceof Error ? err : new Error('Failed to get access token for identify');
+ this.ws?.close(4000, 'Identify failed');
+ });
+ }
+
+ private sendResume(): void {
+ this.api
+ .getAccessToken()
+ .then((token) => {
+ const resumePayload: QQGatewayPayload = {
+ d: {
+ seq: this.seq,
+ session_id: this.sessionId,
+ token: `QQBot ${token}`,
+ },
+ op: QQ_WS_OP_CODES.RESUME,
+ };
+
+ this.send(resumePayload);
+ this.log('Resume sent (session_id=%s, seq=%d)', this.sessionId, this.seq);
+ })
+ .catch((err) => {
+ this.log('Failed to get access token for resume: %O', err);
+ this.openConnectionError =
+ err instanceof Error ? err : new Error('Failed to get access token for resume');
+ this.ws?.close(4000, 'Resume failed');
+ });
+ }
+
+ private sendHeartbeat(): void {
+ const heartbeatPayload: QQGatewayPayload = {
+ d: this.seq,
+ op: QQ_WS_OP_CODES.HEARTBEAT,
+ };
+ this.send(heartbeatPayload);
+ }
+
+ private send(payload: QQGatewayPayload): void {
+ if (this.ws?.readyState === WebSocket.OPEN) {
+ this.ws.send(JSON.stringify(payload));
+ }
+ }
+
+ // ---------- Heartbeat ----------
+
+ private startHeartbeat(intervalMs: number): void {
+ this.stopHeartbeat();
+ this.heartbeatAcked = true;
+
+ // Send first heartbeat after a random jitter (as per spec)
+ const jitter = Math.random() * intervalMs;
+ setTimeout(() => {
+ if (this.closed || this.abortSignal?.aborted) return;
+ this.sendHeartbeat();
+
+ this.heartbeatTimer = setInterval(() => {
+ if (this.closed || this.abortSignal?.aborted) {
+ this.stopHeartbeat();
+ return;
+ }
+
+ if (!this.heartbeatAcked) {
+ this.log('Heartbeat ACK missed — zombie connection, reconnecting');
+ this.ws?.close(4000, 'Heartbeat timeout');
+ return;
+ }
+
+ this.heartbeatAcked = false;
+ this.sendHeartbeat();
+ }, intervalMs);
+ }, jitter);
+ }
+
+ private stopHeartbeat(): void {
+ if (this.heartbeatTimer) {
+ clearInterval(this.heartbeatTimer);
+ this.heartbeatTimer = null;
+ }
+ }
+
+ // ---------- Event Forwarding ----------
+
+ private forwardEvent(payload: QQGatewayPayload): void {
+ // Construct a webhook-compatible payload:
+ // The handleWebhook() expects { op: 0, t: eventType, d: eventData, id, s }
+ const webhookPayload = {
+ d: payload.d,
+ id: payload.id || `gw_${Date.now()}`,
+ op: 0,
+ s: payload.s,
+ t: payload.t,
+ };
+
+ fetch(this.webhookUrl, {
+ body: JSON.stringify(webhookPayload),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal: AbortSignal.timeout(30_000),
+ }).catch((err) => {
+ this.log('Failed to forward event %s to webhook: %O', payload.t, err);
+ });
+ }
+
+ // ---------- Reconnection ----------
+
+ private attemptReconnect(): void {
+ if (this.reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
+ this.log('Max reconnect attempts reached (%d), giving up', MAX_RECONNECT_ATTEMPTS);
+ return;
+ }
+
+ this.reconnectAttempts++;
+ const delay = Math.min(
+ RECONNECT_BASE_DELAY_MS * 2 ** (this.reconnectAttempts - 1),
+ RECONNECT_MAX_DELAY_MS,
+ );
+
+ this.log(
+ 'Reconnecting in %dms (attempt %d/%d)',
+ delay,
+ this.reconnectAttempts,
+ MAX_RECONNECT_ATTEMPTS,
+ );
+
+ setTimeout(() => {
+ if (this.closed || this.abortSignal?.aborted) return;
+
+ const canResume = !!this.sessionId;
+ const url = canResume && this.resumeGatewayUrl ? this.resumeGatewayUrl : this.gatewayUrl;
+
+ if (!url) {
+ this.log('No gateway URL available for reconnect');
+ return;
+ }
+
+ this.openConnection(url, canResume).catch((err) => {
+ this.log('Reconnect failed: %O', err);
+ });
+ }, delay);
+ }
+}
diff --git a/packages/chat-adapter-qq/src/index.ts b/packages/chat-adapter-qq/src/index.ts
index 0dac2bfc158..56b1c5913d5 100644
--- a/packages/chat-adapter-qq/src/index.ts
+++ b/packages/chat-adapter-qq/src/index.ts
@@ -2,11 +2,17 @@ export { createQQAdapter, QQAdapter } from './adapter';
export { QQApiClient } from './api';
export { signWebhookResponse } from './crypto';
export { QQFormatConverter } from './format-converter';
+export type { GatewayLogger, QQGatewayOptions } from './gateway';
+export { QQGatewayConnection } from './gateway';
export type {
QQAccessTokenResponse,
QQAdapterConfig,
QQAttachment,
QQAuthor,
+ QQGatewayHelloData,
+ QQGatewayPayload,
+ QQGatewayReadyData,
+ QQGatewayUrlResponse,
QQMessageType,
QQRawMessage,
QQSendMessageParams,
@@ -16,4 +22,4 @@ export type {
QQWebhookPayload,
QQWebhookVerifyData,
} from './types';
-export { QQ_EVENT_TYPES, QQ_MSG_TYPE, QQ_OP_CODES } from './types';
+export { QQ_EVENT_TYPES, QQ_INTENTS, QQ_MSG_TYPE, QQ_OP_CODES, QQ_WS_OP_CODES } from './types';
diff --git a/packages/chat-adapter-qq/src/types.ts b/packages/chat-adapter-qq/src/types.ts
index 66236383e54..f1dd999a754 100644
--- a/packages/chat-adapter-qq/src/types.ts
+++ b/packages/chat-adapter-qq/src/types.ts
@@ -57,6 +57,7 @@ export interface QQWebhookPayload {
}
export interface QQWebhookEventData {
+ attachments?: QQAttachment[];
author?: QQAuthor;
channel_id?: string;
content?: string;
@@ -121,3 +122,64 @@ export const QQ_OP_CODES = {
HTTP_CALLBACK_ACK: 12,
VERIFY: 13,
} as const;
+
+// ---- WebSocket Gateway OP Codes ----
+
+export const QQ_WS_OP_CODES = {
+ DISPATCH: 0,
+ HEARTBEAT: 1,
+ IDENTIFY: 2,
+ RESUME: 6,
+ RECONNECT: 7,
+ INVALID_SESSION: 9,
+ HELLO: 10,
+ HEARTBEAT_ACK: 11,
+} as const;
+
+// ---- WebSocket Gateway Intents ----
+
+export const QQ_INTENTS = {
+ AUDIO_ACTION: 1 << 29,
+ DIRECT_MESSAGE: 1 << 12,
+ FORUMS_EVENT: 1 << 28,
+ GROUP_AND_C2C_EVENT: 1 << 25,
+ GUILD_MEMBERS: 1 << 1,
+ GUILD_MESSAGE_REACTIONS: 1 << 10,
+ GUILD_MESSAGES: 1 << 9,
+ GUILDS: 1 << 0,
+ INTERACTION: 1 << 26,
+ MESSAGE_AUDIT: 1 << 27,
+ PUBLIC_GUILD_MESSAGES: 1 << 30,
+} as const;
+
+// ---- WebSocket Gateway Types ----
+
+export interface QQGatewayPayload {
+ d: any;
+ id?: string;
+ op: number;
+ s?: number;
+ t?: string;
+}
+
+export interface QQGatewayHelloData {
+ heartbeat_interval: number;
+}
+
+export interface QQGatewayReadyData {
+ session_id: string;
+ shard: [number, number];
+ user: { bot: boolean; id: string; username: string };
+ version: number;
+}
+
+export interface QQGatewayUrlResponse {
+ session_start_limit?: {
+ max_concurrency: number;
+ remaining: number;
+ reset_after: number;
+ total: number;
+ };
+ shards?: number;
+ url: string;
+}
diff --git a/packages/chat-adapter-qq/vitest.config.mts b/packages/chat-adapter-qq/vitest.config.mts
new file mode 100644
index 00000000000..5b40bc079f3
--- /dev/null
+++ b/packages/chat-adapter-qq/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ all: false,
+ },
+ environment: 'node',
+ },
+});
diff --git a/packages/chat-adapter-wechat/src/adapter.test.ts b/packages/chat-adapter-wechat/src/adapter.test.ts
index 0133cceb885..83c0f86489b 100644
--- a/packages/chat-adapter-wechat/src/adapter.test.ts
+++ b/packages/chat-adapter-wechat/src/adapter.test.ts
@@ -1,6 +1,8 @@
+import type { MockInstance } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { createWechatAdapter, WechatAdapter } from './adapter';
+import { createWechatAdapter, downloadMediaFromRawMessage, WechatAdapter } from './adapter';
+import { WechatApiClient } from './api';
import type { WechatRawMessage } from './types';
import { MessageItemType, MessageState, MessageType } from './types';
@@ -290,9 +292,18 @@ describe('WechatAdapter', () => {
expect(message.text).toBe('line1\nline2');
});
- it('should download image from CDN and return raw buffer', async () => {
- const imageBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
- vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(imageBytes);
+ // -------------------- parseRawEvent (webhook path) --------------------
+ //
+ // The inbound parse path is metadata-only — it does NOT call the WeChat
+ // CDN. Eager downloading was removed because the chat-sdk's
+ // `Message.toJSON` strips `att.buffer` whenever the message is enqueued,
+ // making any pre-downloaded buffer pure waste. Server-side
+ // `WechatGatewayClient.extractFiles` is now the sole download path; it
+ // walks `message.raw.item_list` on demand via the standalone
+ // `downloadMediaFromRawMessage` helper (separately tested below).
+
+ it('should produce metadata-only image attachment without calling CDN', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadCdnMedia');
const raw = makeRawMessage({
item_list: [
@@ -311,9 +322,9 @@ describe('WechatAdapter', () => {
const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
const message = await factory?.();
+ expect(downloadSpy).not.toHaveBeenCalled();
expect(message?.attachments).toEqual([
{
- buffer: imageBytes,
mimeType: 'image/jpeg',
name: 'image.jpg',
type: 'image',
@@ -321,35 +332,12 @@ describe('WechatAdapter', () => {
},
]);
expect(message?.text).toBe('');
+ // raw is preserved so server-side extractFiles can re-fetch from file_id.
+ expect(message?.raw).toBeDefined();
});
- it('should return empty attachments when CDN download fails', async () => {
- vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockRejectedValueOnce(
- new Error('CDN download failed: 500'),
- );
-
- const raw = makeRawMessage({
- item_list: [
- {
- image_item: {
- media: { aes_key: 'ABEiM0RVZneImaq7zN3u/w==', encrypt_query_param: 'AAFFtest' },
- },
- type: MessageItemType.IMAGE,
- },
- ],
- });
-
- await adapter.handleWebhook(makeRequest(raw));
-
- const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
- const message = await factory?.();
-
- expect(message?.attachments).toEqual([]);
- });
-
- it('should infer MIME type from filename for file attachments', async () => {
- const fileBytes = Buffer.from([0x25, 0x50, 0x44, 0x46]); // %PDF magic bytes
- vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(fileBytes);
+ it('should produce metadata-only file attachment with inferred mimeType + size', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadCdnMedia');
const raw = makeRawMessage({
item_list: [
@@ -369,9 +357,9 @@ describe('WechatAdapter', () => {
const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
const message = await factory?.();
+ expect(downloadSpy).not.toHaveBeenCalled();
expect(message?.attachments).toEqual([
{
- buffer: fileBytes,
mimeType: 'application/pdf',
name: 'report.pdf',
size: 4,
@@ -381,10 +369,7 @@ describe('WechatAdapter', () => {
]);
});
- it('should infer MIME type for xlsx files', async () => {
- const fileBytes = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
- vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(fileBytes);
-
+ it('should infer MIME type for xlsx files (metadata-only)', async () => {
const raw = makeRawMessage({
item_list: [
{
@@ -408,9 +393,6 @@ describe('WechatAdapter', () => {
});
it('should fall back to application/octet-stream for unknown file extensions', async () => {
- const fileBytes = Buffer.from([0x00, 0x01, 0x02]);
- vi.spyOn((adapter as any).api, 'downloadCdnMedia').mockResolvedValueOnce(fileBytes);
-
const raw = makeRawMessage({
item_list: [
{
@@ -430,6 +412,58 @@ describe('WechatAdapter', () => {
expect(message?.attachments?.[0]?.mimeType).toBe('application/octet-stream');
});
+
+ it('should produce metadata-only video attachment with size', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadCdnMedia');
+
+ const raw = makeRawMessage({
+ item_list: [
+ {
+ type: MessageItemType.VIDEO,
+ video_item: {
+ media: { aes_key: 'k', encrypt_query_param: 'q' },
+ video_size: '12345',
+ },
+ },
+ ],
+ });
+
+ await adapter.handleWebhook(makeRequest(raw));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(message?.attachments).toEqual([
+ { mimeType: 'video/mp4', size: 12_345, type: 'video', url: '' },
+ ]);
+ });
+
+ it('should produce metadata-only audio attachment for voice items', async () => {
+ const downloadSpy = vi.spyOn((adapter as any).api, 'downloadCdnMedia');
+
+ const raw = makeRawMessage({
+ item_list: [
+ {
+ type: MessageItemType.VOICE,
+ voice_item: {
+ media: { aes_key: 'k', encrypt_query_param: 'q' },
+ text: 'transcribed',
+ },
+ },
+ ],
+ });
+
+ await adapter.handleWebhook(makeRequest(raw));
+
+ const factory = vi.mocked(mockChat.processMessage).mock.calls[0]?.[2];
+ const message = await factory?.();
+
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(message?.attachments).toEqual([{ mimeType: 'audio/silk', type: 'audio', url: '' }]);
+ // The transcription text should still flow into message.text via extractText
+ expect(message?.text).toBe('transcribed');
+ });
});
// ---------- context token management ----------
@@ -500,3 +534,233 @@ describe('createWechatAdapter', () => {
expect(adapter.name).toBe('wechat');
});
});
+
+// ---------- downloadMediaFromRawMessage (the on-demand download path) ----------
+//
+// This is the helper called by server-side `WechatGatewayClient.extractFiles`
+// to materialize media after a chat-sdk Redis round-trip has stripped any
+// in-memory buffers. It walks `msg.item_list` and downloads each media item
+// via the `WechatApiClient.downloadCdnMedia` method, returning attachments
+// with `buffer` populated.
+
+describe('downloadMediaFromRawMessage', () => {
+ let api: WechatApiClient;
+ let downloadSpy: MockInstance<WechatApiClient['downloadCdnMedia']>;
+
+ beforeEach(() => {
+ api = new WechatApiClient('tok', 'bot_123');
+ downloadSpy = vi.spyOn(api, 'downloadCdnMedia') as MockInstance<
+ WechatApiClient['downloadCdnMedia']
+ >;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('downloads an image via CDN main media', async () => {
+ const imageBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
+ downloadSpy.mockResolvedValueOnce(imageBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ {
+ image_item: {
+ aeskey: '00112233445566778899aabbccddeeff',
+ media: { aes_key: 'k', encrypt_query_param: 'q' },
+ },
+ type: MessageItemType.IMAGE,
+ },
+ ],
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([
+ {
+ buffer: imageBytes,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ url: '',
+ },
+ ]);
+ });
+
+ it('falls back to CDN thumbnail when main media download fails', async () => {
+ const thumbBytes = Buffer.from([0x47, 0x49, 0x46, 0x38]);
+ downloadSpy
+ .mockRejectedValueOnce(new Error('main CDN failed'))
+ .mockResolvedValueOnce(thumbBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ {
+ image_item: {
+ aeskey: 'aeskey',
+ media: { aes_key: 'k', encrypt_query_param: 'main' },
+ thumb_media: { aes_key: 'k', encrypt_query_param: 'thumb' },
+ },
+ type: MessageItemType.IMAGE,
+ },
+ ],
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledTimes(2);
+ expect((result?.[0] as any)?.buffer).toEqual(thumbBytes);
+ });
+
+ it('downloads a file with inferred mimeType + size', async () => {
+ const pdfBytes = Buffer.from([0x25, 0x50, 0x44, 0x46]);
+ downloadSpy.mockResolvedValueOnce(pdfBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ {
+ file_item: {
+ file_name: 'doc.pdf',
+ len: '4',
+ media: { aes_key: 'k', encrypt_query_param: 'q' },
+ },
+ type: MessageItemType.FILE,
+ },
+ ],
+ }),
+ );
+
+ expect(result).toEqual([
+ {
+ buffer: pdfBytes,
+ mimeType: 'application/pdf',
+ name: 'doc.pdf',
+ size: 4,
+ type: 'file',
+ url: '',
+ },
+ ]);
+ });
+
+ it('downloads a video', async () => {
+ const videoBytes = Buffer.from([0x00, 0x00, 0x00, 0x18]);
+ downloadSpy.mockResolvedValueOnce(videoBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ {
+ type: MessageItemType.VIDEO,
+ video_item: {
+ media: { aes_key: 'k', encrypt_query_param: 'q' },
+ video_size: '24',
+ },
+ },
+ ],
+ }),
+ );
+
+ expect(result).toEqual([
+ { buffer: videoBytes, mimeType: 'video/mp4', size: 24, type: 'video', url: '' },
+ ]);
+ });
+
+ it('downloads voice as audio/silk', async () => {
+ const voiceBytes = Buffer.from([0x46]);
+ downloadSpy.mockResolvedValueOnce(voiceBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ {
+ type: MessageItemType.VOICE,
+ voice_item: {
+ media: { aes_key: 'k', encrypt_query_param: 'q' },
+ },
+ },
+ ],
+ }),
+ );
+
+ expect(result).toEqual([
+ { buffer: voiceBytes, mimeType: 'audio/silk', type: 'audio', url: '' },
+ ]);
+ });
+
+ it('returns empty array when CDN media is missing on every item', async () => {
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ { image_item: {}, type: MessageItemType.IMAGE },
+ { type: MessageItemType.VIDEO, video_item: {} },
+ ],
+ }),
+ );
+ expect(downloadSpy).not.toHaveBeenCalled();
+ expect(result).toEqual([]);
+ });
+
+ it('skips a single failing item without dropping the others', async () => {
+ const goodBytes = Buffer.from([0xff, 0xd8]);
+ downloadSpy.mockRejectedValueOnce(new Error('first failed')).mockResolvedValueOnce(goodBytes);
+
+ const result = await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ {
+ type: MessageItemType.VOICE,
+ voice_item: { media: { aes_key: 'k', encrypt_query_param: 'bad' } },
+ },
+ {
+ file_item: {
+ file_name: 'good.bin',
+ media: { aes_key: 'k', encrypt_query_param: 'good' },
+ },
+ type: MessageItemType.FILE,
+ },
+ ],
+ }),
+ );
+
+ expect(downloadSpy).toHaveBeenCalledTimes(2);
+ expect(result).toEqual([
+ {
+ buffer: goodBytes,
+ mimeType: 'application/octet-stream',
+ name: 'good.bin',
+ size: undefined,
+ type: 'file',
+ url: '',
+ },
+ ]);
+ });
+
+ it('forwards warnings to the optional logger', async () => {
+ downloadSpy.mockRejectedValue(new Error('boom'));
+ const warn = vi.fn();
+
+ await downloadMediaFromRawMessage(
+ api,
+ makeRawMessage({
+ item_list: [
+ {
+ image_item: { media: { aes_key: 'k', encrypt_query_param: 'q' } },
+ type: MessageItemType.IMAGE,
+ },
+ ],
+ }),
+ { warn },
+ );
+
+ expect(warn).toHaveBeenCalled();
+ });
+});
diff --git a/packages/chat-adapter-wechat/src/adapter.ts b/packages/chat-adapter-wechat/src/adapter.ts
index 940be75b0b7..acce50bfb1b 100644
--- a/packages/chat-adapter-wechat/src/adapter.ts
+++ b/packages/chat-adapter-wechat/src/adapter.ts
@@ -85,6 +85,227 @@ function hasCdnMedia(item: WechatRawMessage['item_list'][number]): boolean {
}
}
+/**
+ * Walk a raw WeChat message and produce metadata-only attachments — no
+ * downloads, no decryption. Used by `WechatAdapter.parseRawEvent` so the
+ * inbound parse path stays cheap: media bytes are downloaded later, on
+ * demand, by the server-side `WechatGatewayClient.extractFiles`.
+ *
+ * Why metadata-only at parse time:
+ * 1. The chat-sdk's `Message.toJSON` strips `buffer` from attachments
+ * whenever the message is enqueued (debounce always; queue when busy),
+ * so any eager-downloaded buffer is wasted on the serialization round-trip.
+ * 2. Most inbound messages in group chats are not addressed to the bot —
+ * pre-downloading them is pure CPU/bandwidth waste for the 99% case.
+ * 3. Concentrating the download path in one place (the server-side
+ * `extractFiles`) makes the data flow easier to reason about.
+ *
+ * The fields populated here all survive `Message.toJSON` (type/mimeType/
+ * name/size are in its allowlist), so downstream consumers still get a
+ * count + descriptive metadata for each attachment.
+ */
+export function extractMediaMetadata(msg: WechatRawMessage): Attachment[] {
+ const attachments: Attachment[] = [];
+
+ for (const item of msg.item_list) {
+ switch (item.type) {
+ case MessageItemType.IMAGE: {
+ if (!item.image_item) break;
+ attachments.push({
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ url: '',
+ } as Attachment);
+ break;
+ }
+ case MessageItemType.VOICE: {
+ if (!item.voice_item) break;
+ attachments.push({
+ mimeType: 'audio/silk',
+ type: 'audio',
+ url: '',
+ } as Attachment);
+ break;
+ }
+ case MessageItemType.FILE: {
+ if (!item.file_item) break;
+ const fileName = item.file_item.file_name;
+ const fileMimeType = (fileName && mime.getType(fileName)) || 'application/octet-stream';
+ attachments.push({
+ mimeType: fileMimeType,
+ name: fileName,
+ size: parseOptionalNumber(item.file_item.len),
+ type: 'file',
+ url: '',
+ } as Attachment);
+ break;
+ }
+ case MessageItemType.VIDEO: {
+ if (!item.video_item) break;
+ attachments.push({
+ mimeType: 'video/mp4',
+ size: parseOptionalNumber(item.video_item.video_size),
+ type: 'video',
+ url: '',
+ } as Attachment);
+ break;
+ }
+ }
+ }
+
+ return attachments;
+}
+
+/**
+ * Standalone helper that downloads + decrypts media for a raw WeChat
+ * message, returning attachments with `buffer` populated. This is the
+ * primary download path used by the server-side `WechatGatewayClient.extractFiles`
+ * to materialize media on demand after a chat-sdk Redis round-trip has
+ * stripped any in-memory buffers.
+ *
+ * Pure function — owns no state, takes the api client + raw message + an
+ * optional logger. Includes the cascading image fallback (CDN main → thumb
+ * → direct URL).
+ */
+type WarnFn = (message: string, ...args: unknown[]) => void;
+
+export async function downloadMediaFromRawMessage(
+ api: WechatApiClient,
+ msg: WechatRawMessage,
+ logger?: Pick<Logger, 'warn'>,
+): Promise<Attachment[]> {
+ const warn: WarnFn = logger?.warn?.bind(logger) ?? (() => {});
+ const attachments: Attachment[] = [];
+
+ for (const item of msg.item_list) {
+ try {
+ switch (item.type) {
+ case MessageItemType.IMAGE: {
+ const attachment = await downloadImageItemFromRaw(api, item, warn);
+ if (attachment) attachments.push(attachment);
+ break;
+ }
+ case MessageItemType.VOICE: {
+ if (!hasCdnMedia(item) || !item.voice_item?.media) break;
+ const voiceBuf = await api.downloadCdnMedia(item.voice_item.media);
+ attachments.push({
+ buffer: voiceBuf,
+ mimeType: 'audio/silk',
+ type: 'audio',
+ url: '',
+ } as Attachment);
+ break;
+ }
+ case MessageItemType.FILE: {
+ if (!hasCdnMedia(item) || !item.file_item?.media) break;
+ const fileBuf = await api.downloadCdnMedia(item.file_item.media);
+ const fileName = item.file_item?.file_name;
+ const fileMimeType = (fileName && mime.getType(fileName)) || 'application/octet-stream';
+ attachments.push({
+ buffer: fileBuf,
+ mimeType: fileMimeType,
+ name: fileName,
+ size: parseOptionalNumber(item.file_item?.len),
+ type: 'file',
+ url: '',
+ } as Attachment);
+ break;
+ }
+ case MessageItemType.VIDEO: {
+ if (!hasCdnMedia(item) || !item.video_item?.media) break;
+ const videoBuf = await api.downloadCdnMedia(item.video_item.media);
+ attachments.push({
+ buffer: videoBuf,
+ mimeType: 'video/mp4',
+ size: parseOptionalNumber(item.video_item?.video_size),
+ type: 'video',
+ url: '',
+ } as Attachment);
+ break;
+ }
+ }
+ } catch (error) {
+ warn('Failed to download %s media from CDN: %s', MessageItemType[item.type], error);
+ }
+ }
+
+ return attachments;
+}
+
+/**
+ * Image-specific helper used by {@link downloadMediaFromRawMessage}. Cascades:
+ * 1. CDN main media (image_item.media)
+ * 2. CDN thumbnail (image_item.thumb_media)
+ * 3. Direct URL (image_item.url)
+ */
+async function downloadImageItemFromRaw(
+ api: WechatApiClient,
+ item: WechatRawMessage['item_list'][number],
+ warn: WarnFn,
+): Promise<Attachment | undefined> {
+ const imageItem = item.image_item;
+ if (!imageItem) return undefined;
+
+ // 1. Try CDN download from main media
+ if (imageItem.media?.encrypt_query_param) {
+ try {
+ const buf = await api.downloadCdnMedia(imageItem.media, imageItem.aeskey);
+ return {
+ buffer: buf,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ url: '',
+ } as Attachment;
+ } catch (error) {
+ warn('CDN image download failed: %s', error);
+ }
+ }
+
+ // 2. Try CDN thumbnail as fallback
+ if (imageItem.thumb_media?.encrypt_query_param) {
+ try {
+ const buf = await api.downloadCdnMedia(imageItem.thumb_media, imageItem.aeskey);
+ return {
+ buffer: buf,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ url: '',
+ } as Attachment;
+ } catch (error) {
+ warn('CDN thumbnail download failed: %s', error);
+ }
+ }
+
+ // 3. Fall back to direct url field
+ if (imageItem.url) {
+ try {
+ const response = await fetch(imageItem.url, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (response.ok) {
+ const buf = Buffer.from(await response.arrayBuffer());
+ const contentType = response.headers.get('content-type') || 'image/jpeg';
+ return {
+ buffer: buf,
+ mimeType: contentType,
+ name: 'image.jpg',
+ type: 'image',
+ url: '',
+ } as Attachment;
+ }
+ warn('Image url fallback failed: HTTP %d', response.status);
+ } catch (error) {
+ warn('Image url fallback failed: %s', error);
+ }
+ }
+
+ warn('No image source available (no CDN media, no thumb, no url)');
+ return undefined;
+}
+
/**
* WeChat (iLink) adapter for Chat SDK.
*
@@ -167,7 +388,7 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>
const threadId = this.encodeThreadId({ id: msg.from_user_id, type: 'single' });
this.contextTokens.set(threadId, msg.context_token);
- const messageFactory = () => this.parseRawEvent(msg, threadId, text);
+ const messageFactory = async () => this.parseRawEvent(msg, threadId, text);
this.chat.processMessage(this, threadId, messageFactory, options);
return Response.json({ ok: true });
@@ -243,7 +464,9 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>
const formatted = parseMarkdown(text);
const threadId = this.encodeThreadId({ id: raw.from_user_id, type: 'single' });
- // parseMessage is synchronous — CDN download happens in parseRawEvent instead.
+ // No attachments here — neither this nor `parseRawEvent` downloads media
+ // anymore. Server-side `WechatGatewayClient.extractFiles` is the sole
+ // download path; it walks `message.raw.item_list` on demand.
return new Message({
attachments: [],
author: {
@@ -265,15 +488,17 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>
});
}
- private async parseRawEvent(
+ private parseRawEvent(
msg: WechatRawMessage,
threadId: string,
text: string,
- ): Promise<Message<WechatRawMessage>> {
+ ): Message<WechatRawMessage> {
const formatted = parseMarkdown(text);
- // Download and decrypt media from WeChat CDN (protocol-spec §8.3).
- const attachments = await this.downloadMediaAttachments(msg);
+ // Metadata-only attachments — actual binary download happens later, on
+ // demand, in the server-side `WechatGatewayClient.extractFiles`. See
+ // `extractMediaMetadata` for why we don't pre-download here.
+ const attachments = extractMediaMetadata(msg);
const author: Author = {
fullName: msg.from_user_id,
@@ -298,166 +523,6 @@ export class WechatAdapter implements Adapter<WechatThreadId, WechatRawMessage>
});
}
- /**
- * Download media items and return attachments.
- *
- * Strategy per item type:
- * 1. If CDN media is available, download + AES decrypt (protocol-spec §8.3).
- * 2. For images: fall back to `image_item.url` if CDN is unavailable or fails.
- *
- * When uploadMedia is configured, files are uploaded directly to S3 and the
- * attachment carries a `fileId` so execAgent can skip re-uploading.
- */
- private async downloadMediaAttachments(msg: WechatRawMessage): Promise<Attachment[]> {
- const attachments: Attachment[] = [];
-
- for (const item of msg.item_list) {
- try {
- switch (item.type) {
- case MessageItemType.IMAGE: {
- const attachment = await this.downloadImageItem(item);
- if (attachment) attachments.push(attachment);
- break;
- }
- case MessageItemType.VOICE: {
- if (!hasCdnMedia(item) || !item.voice_item?.media) break;
- const voiceBuf = await this.api.downloadCdnMedia(item.voice_item.media);
- const voice = this.normalizeMedia(voiceBuf, 'audio/silk');
- attachments.push({
- buffer: voice.buffer,
- mimeType: voice.mimeType,
- type: 'audio',
- url: voice.url,
- } as Attachment);
- break;
- }
- case MessageItemType.FILE: {
- if (!hasCdnMedia(item) || !item.file_item?.media) break;
- const fileBuf = await this.api.downloadCdnMedia(item.file_item.media);
- const fileName = item.file_item?.file_name;
- const fileMimeType = (fileName && mime.getType(fileName)) || 'application/octet-stream';
- const file = this.normalizeMedia(fileBuf, fileMimeType);
- attachments.push({
- buffer: file.buffer,
- mimeType: file.mimeType,
- name: fileName,
- size: parseOptionalNumber(item.file_item?.len),
- type: 'file',
- url: file.url,
- } as Attachment);
- break;
- }
- case MessageItemType.VIDEO: {
- if (!hasCdnMedia(item) || !item.video_item?.media) break;
- const videoBuf = await this.api.downloadCdnMedia(item.video_item.media);
- const video = this.normalizeMedia(videoBuf, 'video/mp4');
- attachments.push({
- buffer: video.buffer,
- mimeType: video.mimeType,
- size: parseOptionalNumber(item.video_item?.video_size),
- type: 'video',
- url: video.url,
- } as Attachment);
- break;
- }
- }
- } catch (error) {
- this.logger.warn(
- 'Failed to download %s media from CDN: %s',
- MessageItemType[item.type],
- error,
- );
- }
- }
-
- return attachments;
- }
-
- /**
- * Download an image item with cascading fallback:
- * 1. CDN main media (image_item.media)
- * 2. CDN thumbnail (image_item.thumb_media)
- * 3. Direct URL (image_item.url)
- */
- private async downloadImageItem(
- item: WechatRawMessage['item_list'][number],
- ): Promise<Attachment | undefined> {
- const imageItem = item.image_item;
- if (!imageItem) return undefined;
-
- // 1. Try CDN download from main media
- if (imageItem.media?.encrypt_query_param) {
- try {
- const buf = await this.api.downloadCdnMedia(imageItem.media, imageItem.aeskey);
- const img = this.normalizeMedia(buf, 'image/jpeg');
- return {
- buffer: img.buffer,
- mimeType: img.mimeType,
- name: 'image.jpg',
- type: 'image',
- url: img.url,
- } as Attachment;
- } catch (error) {
- this.logger.warn('CDN image download failed: %s', error);
- }
- }
-
- // 2. Try CDN thumbnail as fallback
- if (imageItem.thumb_media?.encrypt_query_param) {
- try {
- const buf = await this.api.downloadCdnMedia(imageItem.thumb_media, imageItem.aeskey);
- const img = this.normalizeMedia(buf, 'image/jpeg');
- return {
- buffer: img.buffer,
- mimeType: img.mimeType,
- name: 'image.jpg',
- type: 'image',
- url: img.url,
- } as Attachment;
- } catch (error) {
- this.logger.warn('CDN thumbnail download failed: %s', error);
- }
- }
-
- // 3. Fall back to direct url field
- if (imageItem.url) {
- try {
- const response = await fetch(imageItem.url, {
- signal: AbortSignal.timeout(15_000),
- });
- if (response.ok) {
- const buf = Buffer.from(await response.arrayBuffer());
- const contentType = response.headers.get('content-type') || 'image/jpeg';
- const img = this.normalizeMedia(buf, contentType);
- return {
- buffer: img.buffer,
- mimeType: img.mimeType,
- name: 'image.jpg',
- type: 'image',
- url: img.url,
- } as Attachment;
- }
- this.logger.warn('Image url fallback failed: HTTP %d', response.status);
- } catch (error) {
- this.logger.warn('Image url fallback failed: %s', error);
- }
- }
-
- this.logger.warn('No image source available (no CDN media, no thumb, no url)');
- return undefined;
- }
-
- /**
- * Wrap raw buffer into the shape expected by attachment objects.
- * Server-side ingestAttachment handles compression, upload, and record creation.
- */
- private normalizeMedia(
- buffer: Buffer,
- mimeType: string,
- ): { buffer: Buffer; mimeType: string; url: string } {
- return { buffer, mimeType, url: '' };
- }
-
// ------------------------------------------------------------------
// Reactions & typing (limited support)
// ------------------------------------------------------------------
diff --git a/packages/chat-adapter-wechat/src/index.ts b/packages/chat-adapter-wechat/src/index.ts
index 502e14d60cb..1260a5b6b6a 100644
--- a/packages/chat-adapter-wechat/src/index.ts
+++ b/packages/chat-adapter-wechat/src/index.ts
@@ -1,4 +1,4 @@
-export { createWechatAdapter, WechatAdapter } from './adapter';
+export { createWechatAdapter, downloadMediaFromRawMessage, WechatAdapter } from './adapter';
export type { QrCodeResponse, QrStatusResponse } from './api';
export { DEFAULT_BASE_URL, fetchQrCode, pollQrStatus, WechatApiClient } from './api';
export { WechatFormatConverter } from './format-converter';
diff --git a/src/app/(backend)/api/agent/gateway/route.ts b/src/app/(backend)/api/agent/gateway/route.ts
index b15ed79f958..3cd48d81a6c 100644
--- a/src/app/(backend)/api/agent/gateway/route.ts
+++ b/src/app/(backend)/api/agent/gateway/route.ts
@@ -6,12 +6,8 @@ import { getServerDB } from '@/database/core/db-adaptor';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
-import type {
- BotPlatformRuntimeContext,
- BotProviderConfig,
- PlatformDefinition,
-} from '@/server/services/bot/platforms';
-import { platformRegistry } from '@/server/services/bot/platforms';
+import type { BotPlatformRuntimeContext, BotProviderConfig } from '@/server/services/bot/platforms';
+import { getEffectiveConnectionMode, platformRegistry } from '@/server/services/bot/platforms';
import { BotConnectQueue } from '@/server/services/gateway/botConnectQueue';
const log = debug('lobe-server:bot:gateway:cron');
@@ -28,12 +24,6 @@ const waitUntil = (task: Promise<unknown>) => {
after(() => task);
};
-function getGatewayPlatforms(): PlatformDefinition[] {
- return platformRegistry
- .listPlatforms()
- .filter((platform) => (platform.connectionMode ?? 'webhook') === 'persistent');
-}
-
function createRuntimeContext(): BotPlatformRuntimeContext {
return {
appUrl: process.env.APP_URL,
@@ -45,21 +35,19 @@ function createGatewayBot(
platform: string,
applicationId: string,
credentials: Record<string, string>,
+ settings: Record<string, unknown> | null | undefined,
) {
const config: BotProviderConfig = {
applicationId,
credentials,
platform,
- settings: {},
+ settings: (settings as Record<string, unknown>) || {},
};
return platformRegistry.createClient(platform, config, createRuntimeContext());
}
-async function processConnectQueue(
- remainingMs: number,
- gatewayPlatformIds: Set<string>,
-): Promise<number> {
+async function processConnectQueue(remainingMs: number): Promise<number> {
const queue = new BotConnectQueue();
const items = await queue.popAll();
@@ -73,8 +61,9 @@ async function processConnectQueue(
for (const item of items) {
try {
- if (!gatewayPlatformIds.has(item.platform)) {
- log('Skipping queued non-gateway platform=%s appId=%s', item.platform, item.applicationId);
+ const definition = platformRegistry.getPlatform(item.platform);
+ if (!definition) {
+ log('Skipping queued unknown platform=%s appId=%s', item.platform, item.applicationId);
await queue.remove(item.platform, item.applicationId);
continue;
}
@@ -88,7 +77,23 @@ async function processConnectQueue(
continue;
}
- const bot = createGatewayBot(item.platform, provider.applicationId, provider.credentials);
+ const effectiveMode = getEffectiveConnectionMode(definition, provider.settings);
+ if (effectiveMode === 'webhook') {
+ log(
+ 'Skipping queued webhook-mode provider platform=%s appId=%s',
+ item.platform,
+ item.applicationId,
+ );
+ await queue.remove(item.platform, item.applicationId);
+ continue;
+ }
+
+ const bot = createGatewayBot(
+ item.platform,
+ provider.applicationId,
+ provider.credentials,
+ provider.settings,
+ );
await bot.start({
durationMs: remainingMs,
@@ -118,8 +123,7 @@ export async function GET(request: NextRequest) {
return new Response('Unauthorized', { status: 401 });
}
- const platforms = getGatewayPlatforms();
- const gatewayPlatformIds = new Set(platforms.map((platform) => platform.id));
+ const platforms = platformRegistry.listPlatforms();
const serverDB = await getServerDB();
const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
@@ -138,13 +142,24 @@ export async function GET(request: NextRequest) {
log('Found %d enabled %s providers', providers.length, platform.name);
let platformStarted = 0;
- total += providers.length;
+ let platformTotal = 0;
for (const provider of providers) {
- const { applicationId, credentials } = provider;
+ const { applicationId, credentials, settings } = provider;
+
+ // Per-provider mode overrides the platform default. Webhook providers
+ // never need a persistent listener even if the platform default is gateway.
+ const effectiveMode = getEffectiveConnectionMode(platform, settings);
+ if (effectiveMode === 'webhook') {
+ log('Skipping webhook-mode provider platform=%s appId=%s', platform.id, applicationId);
+ continue;
+ }
+
+ platformTotal++;
+ total++;
try {
- const bot = createGatewayBot(platform.id, applicationId, credentials);
+ const bot = createGatewayBot(platform.id, applicationId, credentials, settings);
await bot.start({
durationMs: GATEWAY_DURATION_MS,
@@ -164,10 +179,10 @@ export async function GET(request: NextRequest) {
}
}
- stats.push({ platform: platform.id, started: platformStarted, total: providers.length });
+ stats.push({ platform: platform.id, started: platformStarted, total: platformTotal });
}
- const queued = await processConnectQueue(GATEWAY_DURATION_MS, gatewayPlatformIds);
+ const queued = await processConnectQueue(GATEWAY_DURATION_MS);
after(async () => {
const pollEnd = Date.now() + GATEWAY_DURATION_MS;
@@ -177,7 +192,7 @@ export async function GET(request: NextRequest) {
if (Date.now() >= pollEnd) break;
const remainingMs = pollEnd - Date.now();
- await processConnectQueue(remainingMs, gatewayPlatformIds);
+ await processConnectQueue(remainingMs);
}
});
diff --git a/src/locales/default/agent.ts b/src/locales/default/agent.ts
index bb946fcb409..4bb1fdf16f3 100644
--- a/src/locales/default/agent.ts
+++ b/src/locales/default/agent.ts
@@ -46,6 +46,9 @@ export default {
'channel.endpointUrlHint':
'Please copy this URL and paste it into the <bold>{{fieldName}}</bold> field in the {{name}} Developer Portal.',
'channel.feishu.description': 'Connect this assistant to Feishu for private and group chats.',
+ 'channel.feishu.webhookMigrationTitle': 'Consider migrating to WebSocket mode',
+ 'channel.feishu.webhookMigrationDesc':
+ 'WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket in Advanced Settings. No additional configuration is needed on the Feishu/Lark Open Platform.',
'channel.lark.description': 'Connect this assistant to Lark for private and group chats.',
'channel.openPlatform': 'Open Platform',
'channel.platforms': 'Platforms',
@@ -54,6 +57,9 @@ export default {
'channel.publicKeyPlaceholder': 'Required for interaction verification',
'channel.qq.appIdHint': 'Your QQ Bot App ID from QQ Open Platform',
'channel.qq.description': 'Connect this assistant to QQ for group chats and direct messages.',
+ 'channel.qq.webhookMigrationTitle': 'Consider migrating to WebSocket mode',
+ 'channel.qq.webhookMigrationDesc':
+ 'WebSocket mode provides real-time event delivery and automatic reconnection without needing a callback URL. To migrate, create a new bot on QQ Open Platform without configuring a callback URL, then switch the Connection Mode to WebSocket in Advanced Settings.',
'channel.wechat.description':
'Connect this assistant to WeChat via iLink Bot for private and group chats.',
'channel.wechatQrExpired': 'QR code expired. Please refresh to get a new one.',
@@ -82,8 +88,14 @@ export default {
'channel.saved': 'Configuration saved successfully',
'channel.secretToken': 'Webhook Secret Token',
'channel.slack.appIdHint': 'Your Slack App ID from the Slack API dashboard (starts with A).',
+ 'channel.slack.appToken': 'App-Level Token',
+ 'channel.slack.appTokenHint':
+ 'Required for Socket Mode (WebSocket). Generate an app-level token (xapp-...) under Basic Information in your Slack app settings.',
'channel.slack.description':
'Connect this assistant to Slack for channel conversations and direct messages.',
+ 'channel.slack.webhookMigrationTitle': 'Consider migrating to Socket Mode (WebSocket)',
+ 'channel.slack.webhookMigrationDesc':
+ 'Socket Mode provides real-time event delivery via WebSocket without exposing a public HTTP endpoint. To migrate, enable Socket Mode in your Slack app settings, generate an App-Level Token, then switch the Connection Mode to WebSocket in Advanced Settings.',
'channel.secretTokenHint': 'Optional. Used to verify webhook requests from Telegram.',
'channel.secretTokenPlaceholder': 'Optional secret for webhook verification',
'channel.telegram.description': 'Connect this assistant to Telegram for private and group chats.',
@@ -98,6 +110,11 @@ export default {
'channel.appSecretHint':
'The App Secret of your bot application. It will be encrypted and stored securely.',
+ 'channel.connectionMode': 'Connection Mode',
+ 'channel.connectionModeHint':
+ 'WebSocket is recommended for new bots. Use Webhook if your bot already has a callback URL configured on QQ Open Platform.',
+ 'channel.connectionModeWebSocket': 'WebSocket',
+ 'channel.connectionModeWebhook': 'Webhook',
'channel.charLimit': 'Character Limit',
'channel.charLimitHint': 'Maximum number of characters per message',
'channel.concurrency': 'Concurrency Mode',
diff --git a/src/routes/(main)/agent/channel/detail/Footer.tsx b/src/routes/(main)/agent/channel/detail/Footer.tsx
index 1b7cb888120..10ca973e7af 100644
--- a/src/routes/(main)/agent/channel/detail/Footer.tsx
+++ b/src/routes/(main)/agent/channel/detail/Footer.tsx
@@ -84,6 +84,10 @@ const Footer = memo<FooterProps>(
const platformId = platformDef.id;
const applicationId = AntdForm.useWatch('applicationId', form);
+ const settingsConnectionMode = AntdForm.useWatch(['settings', 'connectionMode'], form);
+
+ const showWebhookUrl = platformDef.showWebhookUrl || settingsConnectionMode === 'webhook';
+
const webhookUrl = applicationId
? `${origin}/api/agent/webhooks/${platformId}/${applicationId}`
: `${origin}/api/agent/webhooks/${platformId}`;
@@ -163,7 +167,37 @@ const Footer = memo<FooterProps>(
/>
)}
- {hasConfig && platformDef.showWebhookUrl && (
+ {hasConfig && showWebhookUrl && platformId === 'qq' && (
+ <Alert
+ closable
+ showIcon
+ description={t('channel.qq.webhookMigrationDesc')}
+ message={t('channel.qq.webhookMigrationTitle')}
+ type="warning"
+ />
+ )}
+
+ {hasConfig && showWebhookUrl && platformId === 'slack' && (
+ <Alert
+ closable
+ showIcon
+ description={t('channel.slack.webhookMigrationDesc')}
+ message={t('channel.slack.webhookMigrationTitle')}
+ type="warning"
+ />
+ )}
+
+ {hasConfig && showWebhookUrl && (platformId === 'feishu' || platformId === 'lark') && (
+ <Alert
+ closable
+ showIcon
+ description={t('channel.feishu.webhookMigrationDesc')}
+ message={t('channel.feishu.webhookMigrationTitle')}
+ type="warning"
+ />
+ )}
+
+ {hasConfig && showWebhookUrl && (
<Flexbox gap={8}>
<Flexbox horizontal align="center" gap={8}>
<span style={{ fontWeight: 600 }}>{t('channel.endpointUrl')}</span>
diff --git a/src/server/routers/lambda/agentBotProvider.ts b/src/server/routers/lambda/agentBotProvider.ts
index e5244a4d808..0cb32f15bfe 100644
--- a/src/server/routers/lambda/agentBotProvider.ts
+++ b/src/server/routers/lambda/agentBotProvider.ts
@@ -63,7 +63,7 @@ export const agentBotProviderRouter = router({
// Stop running client and invalidate cached bot
if (existing) {
const service = new GatewayService();
- await service.stopClient(existing.platform, existing.applicationId);
+ await service.stopClient(existing.platform, existing.applicationId, ctx.userId);
await getBotMessageRouter().invalidateBot(existing.platform, existing.applicationId);
}
@@ -201,7 +201,7 @@ export const agentBotProviderRouter = router({
if (shouldStopRuntime) {
const service = new GatewayService();
- await service.stopClient(existing.platform, existing.applicationId);
+ await service.stopClient(existing.platform, existing.applicationId, ctx.userId);
}
await getBotMessageRouter().invalidateBot(existing.platform, existing.applicationId);
diff --git a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
index ccde5974bea..1e290d78cbc 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts
@@ -3,11 +3,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
-const { mockMessageCreate, mockCreateOperation, mockIngestAttachment } = vi.hoisted(() => ({
- mockCreateOperation: vi.fn(),
- mockIngestAttachment: vi.fn(),
- mockMessageCreate: vi.fn(),
-}));
+const { mockMessageCreate, mockCreateOperation, mockIngestAttachment, mockParseFile } = vi.hoisted(
+ () => ({
+ mockCreateOperation: vi.fn(),
+ mockIngestAttachment: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockParseFile: vi.fn(),
+ }),
+);
vi.mock('@/libs/trusted-client', () => ({
generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
@@ -104,6 +107,12 @@ vi.mock('../ingestAttachment', () => ({
ingestAttachment: mockIngestAttachment,
}));
+vi.mock('@/server/services/document', () => ({
+ DocumentService: vi.fn().mockImplementation(() => ({
+ parseFile: mockParseFile,
+ })),
+}));
+
vi.mock('@/server/modules/Mecha', () => ({
createServerAgentToolsEngine: vi.fn().mockReturnValue({
generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
@@ -147,6 +156,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {
operationId: 'op-123',
success: true,
});
+ mockParseFile.mockResolvedValue({ content: '' });
service = new AiAgentService(mockDb, userId);
});
@@ -160,6 +170,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {
mockIngestAttachment.mockResolvedValue({
fileId: 'file-abc',
isImage: true,
+ isVideo: false,
key: 'files/test-user-id/xxx/photo.png',
resolvedUrl: 'https://s3.example.com/files/test-user-id/xxx/photo.png',
});
@@ -193,6 +204,7 @@ describe('AiAgentService.execAgent - file upload handling', () => {
mockIngestAttachment.mockResolvedValue({
fileId: 'file-img',
isImage: true,
+ isVideo: false,
key: 'files/test-user-id/xxx/screenshot.jpg',
resolvedUrl: 'https://s3.example.com/files/test-user-id/xxx/screenshot.jpg',
});
@@ -227,13 +239,60 @@ describe('AiAgentService.execAgent - file upload handling', () => {
]);
});
- it('should not include imageList for non-image files', async () => {
+ it('should route videos to videoList instead of fileList', async () => {
+ mockIngestAttachment.mockResolvedValue({
+ fileId: 'file-vid',
+ isImage: false,
+ isVideo: true,
+ key: 'files/test-user-id/xxx/clip.mp4',
+ resolvedUrl: 'https://s3.example.com/files/test-user-id/xxx/clip.mp4',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ files: [
+ {
+ mimeType: 'video/mp4',
+ name: 'clip.mp4',
+ size: 67_890,
+ url: 'https://cdn.discordapp.com/attachments/123/456/clip.mp4',
+ },
+ ],
+ prompt: 'Describe this video',
+ });
+
+ // parseFile must NOT be invoked for videos — there is no document content
+ // to extract, only the URL gets passed to video-capable models.
+ expect(mockParseFile).not.toHaveBeenCalled();
+
+ const createOpArgs = mockCreateOperation.mock.calls[0][0];
+ const lastMessage = createOpArgs.initialMessages.at(-1);
+
+ // Video should land in videoList, not imageList or fileList
+ expect(lastMessage.imageList).toBeUndefined();
+ expect(lastMessage.fileList).toBeUndefined();
+ expect(lastMessage.videoList).toEqual([
+ {
+ alt: 'clip.mp4',
+ id: 'file-vid',
+ url: 'https://s3.example.com/files/test-user-id/xxx/clip.mp4',
+ },
+ ]);
+
+ // The fileId is still tracked on the user message record
+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
+ expect(userMessageCall![0].files).toEqual(['file-vid']);
+ });
+
+ it('should parse non-image files and surface them via fileList for the LLM', async () => {
mockIngestAttachment.mockResolvedValue({
fileId: 'file-pdf',
isImage: false,
+ isVideo: false,
key: 'files/test-user-id/xxx/doc.pdf',
resolvedUrl: '',
});
+ mockParseFile.mockResolvedValue({ content: 'parsed pdf body text' });
await service.execAgent({
agentId: 'agent-1',
@@ -241,16 +300,72 @@ describe('AiAgentService.execAgent - file upload handling', () => {
{
mimeType: 'application/pdf',
name: 'doc.pdf',
+ size: 4096,
url: 'https://cdn.discordapp.com/attachments/123/456/doc.pdf',
},
],
prompt: 'Summarize this document',
});
+ // DocumentService.parseFile must be invoked so the documents table is
+ // populated and history queries can resurface the same content later.
+ expect(mockParseFile).toHaveBeenCalledWith('file-pdf');
+
const createOpArgs = mockCreateOperation.mock.calls[0][0];
const lastMessage = createOpArgs.initialMessages.at(-1);
+ // imageList stays undefined for a non-image file …
expect(lastMessage.imageList).toBeUndefined();
+ // … but fileList is now populated so MessageContentProcessor can inject
+ // the parsed content via filesPrompts() XML.
+ expect(lastMessage.fileList).toEqual([
+ {
+ content: 'parsed pdf body text',
+ fileType: 'application/pdf',
+ id: 'file-pdf',
+ name: 'doc.pdf',
+ size: 4096,
+ url: '',
+ },
+ ]);
+ });
+
+ it('continues with empty content when parseFile fails (e.g. binary file)', async () => {
+ mockIngestAttachment.mockResolvedValue({
+ fileId: 'file-bin',
+ isImage: false,
+ isVideo: false,
+ key: 'files/test-user-id/xxx/blob.bin',
+ resolvedUrl: '',
+ });
+ mockParseFile.mockRejectedValue(new Error('unsupported binary'));
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ files: [
+ {
+ mimeType: 'application/octet-stream',
+ name: 'blob.bin',
+ size: 10,
+ url: 'https://cdn.example/blob.bin',
+ },
+ ],
+ prompt: 'What is in this?',
+ });
+
+ const createOpArgs = mockCreateOperation.mock.calls[0][0];
+ const lastMessage = createOpArgs.initialMessages.at(-1);
+
+ expect(lastMessage.fileList).toEqual([
+ {
+ content: undefined,
+ fileType: 'application/octet-stream',
+ id: 'file-bin',
+ name: 'blob.bin',
+ size: 10,
+ url: '',
+ },
+ ]);
});
});
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 7f11e48252d..e2ee29168ae 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -18,7 +18,9 @@ import type {
import { SkillEngine } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import type {
+ ChatFileItem,
ChatTopicBotContext,
+ ChatVideoItem,
ExecAgentParams,
ExecAgentResult,
ExecGroupAgentParams,
@@ -55,6 +57,7 @@ import { AgentRuntimeService } from '@/server/services/agentRuntime';
import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';
import { type AgentHook } from '@/server/services/agentRuntime/hooks/types';
import { type StepLifecycleCallbacks } from '@/server/services/agentRuntime/types';
+import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { KlavisService } from '@/server/services/klavis';
import { MarketService } from '@/server/services/market';
@@ -884,10 +887,15 @@ export class AiAgentService {
// 12. Upload external files to S3 and collect file IDs
let fileIds: string[] | undefined;
let imageList: Array<{ alt: string; id: string; url: string }> | undefined;
+ let videoList: ChatVideoItem[] | undefined;
+ let fileList: ChatFileItem[] | undefined;
if (files && files.length > 0) {
fileIds = [];
imageList = [];
+ videoList = [];
+ fileList = [];
+ const documentService = new DocumentService(this.db, this.userId);
for (const file of files) {
await throwIfExecutionAborted('file upload');
@@ -902,16 +910,61 @@ export class AiAgentService {
id: result.fileId,
url: result.resolvedUrl,
});
+ continue;
}
+
+ if (result.isVideo) {
+ videoList.push({
+ alt: file.name || 'video',
+ id: result.fileId,
+ url: result.resolvedUrl,
+ });
+ continue;
+ }
+
+ // Non-image / non-video: parse file content into the documents table so
+ // the MessageContentProcessor can inject it via filesPrompts(). Mirrors
+ // what the web upload path does, ensuring bot-uploaded PDFs / text /
+ // JSON / .skill files are actually visible to the LLM (instead of
+ // being silently uploaded but never read).
+ let content: string | undefined;
+ try {
+ const document = await documentService.parseFile(result.fileId);
+ content = document.content ?? undefined;
+ } catch (parseError) {
+ log(
+ 'execAgent: parseFile failed for %s (fileId=%s): %O',
+ file.name,
+ result.fileId,
+ parseError,
+ );
+ }
+
+ fileList.push({
+ content,
+ fileType: file.mimeType ?? 'application/octet-stream',
+ id: result.fileId,
+ name: file.name ?? 'file',
+ size: file.size ?? 0,
+ url: result.resolvedUrl || '',
+ });
} catch (error) {
log('execAgent: failed to ingest file %s: %O', file.name || file.url, error);
}
}
if (fileIds.length > 0) {
- log('execAgent: uploaded %d files to S3', fileIds.length);
+ log(
+ 'execAgent: uploaded %d files to S3 (%d images, %d videos, %d documents)',
+ fileIds.length,
+ imageList.length,
+ videoList.length,
+ fileList.length,
+ );
}
if (imageList.length === 0) imageList = undefined;
+ if (videoList.length === 0) videoList = undefined;
+ if (fileList.length === 0) fileList = undefined;
}
await throwIfExecutionAborted('message creation');
@@ -947,8 +1000,17 @@ export class AiAgentService {
log('execAgent: created assistant message %s', assistantMessageRecord.id);
assistantMessageRef.current = assistantMessageRecord.id;
- // Create user message object for processing (include imageList for vision models)
- const userMessage = { content: prompt, imageList, role: 'user' as const };
+ // Create user message object for processing.
+ // - imageList: vision models render these as image_url parts
+ // - videoList: video-capable models render these as video parts
+ // - fileList: MessageContentProcessor injects content via filesPrompts() XML
+ const userMessage = {
+ content: prompt,
+ fileList,
+ imageList,
+ role: 'user' as const,
+ videoList,
+ };
// Combine history messages with user message
const allMessages = resume ? historyMessages : [...historyMessages, userMessage];
diff --git a/src/server/services/aiAgent/ingestAttachment.ts b/src/server/services/aiAgent/ingestAttachment.ts
index e20633a9a64..22b285aa4c7 100644
--- a/src/server/services/aiAgent/ingestAttachment.ts
+++ b/src/server/services/aiAgent/ingestAttachment.ts
@@ -31,6 +31,7 @@ export interface AttachmentSource {
export interface IngestResult {
fileId: string;
isImage: boolean;
+ isVideo: boolean;
key: string;
resolvedUrl: string;
}
@@ -93,6 +94,15 @@ export async function ingestAttachment(
fileService: FileService,
userId: string,
): Promise<IngestResult> {
+ log(
+ 'ingestAttachment: input name=%s, mimeType=%s, hasBuffer=%s, hasUrl=%s, size=%s',
+ source.name,
+ source.mimeType,
+ !!source.buffer,
+ !!source.url,
+ source.size,
+ );
+
let buffer: Buffer;
let mimeType = source.mimeType || 'application/octet-stream';
@@ -117,7 +127,11 @@ export async function ingestAttachment(
// 2. MIME correction from filename
if (mimeType === 'application/octet-stream' && source.name) {
- mimeType = mime.getType(source.name) || mimeType;
+ const inferred = mime.getType(source.name);
+ if (inferred) {
+ log('ingestAttachment: inferred mimeType from filename: %s -> %s', source.name, inferred);
+ mimeType = inferred;
+ }
}
// 3. Compress images
@@ -128,14 +142,34 @@ export async function ingestAttachment(
mimeType = compressed.mimeType;
}
+ // Videos are not compressed, but we still need a resolved URL so the
+ // MessageContentProcessor can pass the video to vision/video-capable models.
+ const isVideo = !isImage && mimeType.startsWith('video/');
+
+ log(
+ 'ingestAttachment: classified name=%s, finalMimeType=%s, isImage=%s, isVideo=%s, bufferSize=%d',
+ source.name,
+ mimeType,
+ isImage,
+ isVideo,
+ buffer.length,
+ );
+
// 4. Upload + create record
const ext = source.name?.split('.').pop() || 'bin';
const { nanoid } = await import('@lobechat/utils');
const pathname = `files/${userId}/${nanoid()}/${source.name || `file.${ext}`}`;
const { fileId, key } = await fileService.uploadFromBuffer(buffer, mimeType, pathname);
- // 5. Resolve full URL for images (presigned or public)
- const resolvedUrl = isImage ? await fileService.getFullFileUrl(key) : '';
+ // 5. Resolve full URL for images and videos (presigned or public)
+ const resolvedUrl = isImage || isVideo ? await fileService.getFullFileUrl(key) : '';
+
+ log(
+ 'ingestAttachment: uploaded fileId=%s, key=%s, resolvedUrl=%s',
+ fileId,
+ key,
+ resolvedUrl ? 'set' : '(empty)',
+ );
- return { fileId, isImage, key, resolvedUrl };
+ return { fileId, isImage, isVideo, key, resolvedUrl };
}
diff --git a/src/server/services/bot/AgentBridgeService.ts b/src/server/services/bot/AgentBridgeService.ts
index e212c0b7895..7a9c62f7438 100644
--- a/src/server/services/bot/AgentBridgeService.ts
+++ b/src/server/services/bot/AgentBridgeService.ts
@@ -66,14 +66,16 @@ function extractErrorMessage(err: unknown): string {
}
/**
- * Fire-and-forget wrapper for reaction operations.
- * Reactions should never block or fail the main flow.
+ * Fire-and-forget wrapper for non-essential side effects (reactions, typing
+ * indicators, subscribe, etc.). These are UX niceties — a transient platform
+ * network error must NEVER abort the main message flow, because the abort
+ * would skip the cleanup of `activeThreads` and freeze the thread.
*/
-async function safeReaction(fn: () => Promise<void>, label: string): Promise<void> {
+async function safeSideEffect(fn: () => Promise<unknown>, label: string): Promise<void> {
try {
await fn();
} catch (error) {
- log('safeReaction [%s] failed: %O', label, error);
+ log('safeSideEffect [%s] failed: %O', label, error);
}
}
@@ -88,6 +90,18 @@ interface ThreadState {
}
interface BridgeHandlerOpts {
+ /**
+ * Internal: when true, the caller already holds the `activeThreads` flag
+ * for this thread, so the callee must skip its own activeThreads check /
+ * add / delete (the parent caller owns the lifecycle).
+ *
+ * Used by `handleSubscribedMessage` when it recursively calls
+ * `handleMention` on a stale-topic reset or FK violation. Without this,
+ * the recursive call would either (a) trip its own activeThreads check
+ * and silently skip the message (race-prone) or (b) try to delete the
+ * flag in its finally and leave the parent's finally double-deleting.
+ */
+ _activeFlagHeldByCaller?: boolean;
agentId: string;
botContext?: ChatTopicBotContext;
charLimit?: number;
@@ -253,10 +267,11 @@ export class AgentBridgeService {
const { agentId, botContext, charLimit, displayToolCalls } = opts;
log(
- 'handleMention: agentId=%s, user=%s, text=%s',
+ 'handleMention: agentId=%s, user=%s, text=%s, attachments=%d',
agentId,
this.userId,
message.text.slice(0, 80),
+ ((message as any).attachments as unknown[] | undefined)?.length ?? 0,
);
// Skip if there's already an active execution for this thread
@@ -265,54 +280,62 @@ export class AgentBridgeService {
return;
}
- AgentBridgeService.activeThreads.add(thread.id);
-
- // Immediate feedback: mark as received + show typing
const { client } = opts;
- const reactionThreadId = client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;
- await safeReaction(
- () => thread.adapter.addReaction(reactionThreadId, message.id, RECEIVED_EMOJI),
- 'add eyes',
- );
+ const queueMode = isQueueAgentRuntimeEnabled();
+ let queueHandoffSucceeded = false;
- // Auto-subscribe to thread (platforms can opt out, e.g. Discord top-level channels)
- const subscribe = client?.shouldSubscribe?.(thread.id) ?? true;
- if (subscribe) {
- await thread.subscribe();
- }
+ // Mark the thread as active and run the rest inside a try/finally so the
+ // active flag is ALWAYS released even if a side-effect call (subscribe /
+ // startTyping / addReaction) throws on a transient platform network error.
+ AgentBridgeService.activeThreads.add(thread.id);
- await thread.startTyping();
+ try {
+ // Immediate feedback: mark as received + show typing. Both are
+ // non-essential UX niceties; a transient platform network error here
+ // (e.g. ECONNRESET to api.telegram.org) must NOT abort the main flow.
+ const reactionThreadId =
+ client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;
+ await safeSideEffect(
+ () => thread.adapter.addReaction(reactionThreadId, message.id, RECEIVED_EMOJI),
+ 'add eyes',
+ );
- // Fetch channel context for Discord context injection
- const channelContext = await this.fetchChannelContext(thread);
+ // Auto-subscribe to thread (platforms can opt out, e.g. Discord top-level channels)
+ const subscribe = client?.shouldSubscribe?.(thread.id) ?? true;
+ if (subscribe) {
+ await safeSideEffect(() => thread.subscribe(), 'subscribe');
+ }
- const queueMode = isQueueAgentRuntimeEnabled();
- let queueHandoffSucceeded = false;
+ await safeSideEffect(() => thread.startTyping(), 'startTyping');
- try {
- // executeWithCallback handles progress message (post + edit at each step)
- // The final reply is edited into the progress message by onComplete
- const { topicId } = await this.executeWithCallback(thread, message, {
- agentId,
- botContext,
- channelContext,
- charLimit,
- client,
- displayToolCalls,
- trigger: RequestTrigger.Bot,
- });
- queueHandoffSucceeded = queueMode;
+ // Fetch channel context for Discord context injection
+ const channelContext = await this.fetchChannelContext(thread);
- // Persist topic mapping and channel context in thread state for follow-up messages
- // Skip if the platform opted out of auto-subscribe (no subscribe = no follow-up)
- if (topicId && subscribe) {
- await thread.setState({ channelContext, topicId });
- log('handleMention: stored topicId=%s in thread=%s state', topicId, thread.id);
+ try {
+ // executeWithCallback handles progress message (post + edit at each step)
+ // The final reply is edited into the progress message by onComplete
+ const { topicId } = await this.executeWithCallback(thread, message, {
+ agentId,
+ botContext,
+ channelContext,
+ charLimit,
+ client,
+ displayToolCalls,
+ trigger: RequestTrigger.Bot,
+ });
+ queueHandoffSucceeded = queueMode;
+
+ // Persist topic mapping and channel context in thread state for follow-up messages
+ // Skip if the platform opted out of auto-subscribe (no subscribe = no follow-up)
+ if (topicId && subscribe) {
+ await thread.setState({ channelContext, topicId });
+ log('handleMention: stored topicId=%s in thread=%s state', topicId, thread.id);
+ }
+ } catch (error) {
+ log('handleMention error: %O', error);
+ const msg = error instanceof Error ? error.message : String(error);
+ await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);
}
- } catch (error) {
- log('handleMention error: %O', error);
- const msg = error instanceof Error ? error.message : String(error);
- await thread.post(`**Agent Execution Failed**\n\`\`\`\n${msg}\n\`\`\``);
} finally {
AgentBridgeService.activeThreads.delete(thread.id);
// In queue mode, the callback owns cleanup only after webhook handoff succeeds.
@@ -335,7 +358,13 @@ export class AgentBridgeService {
const threadState = await thread.state;
const topicId = threadState?.topicId;
- log('handleSubscribedMessage: agentId=%s, thread=%s, topicId=%s', agentId, thread.id, topicId);
+ log(
+ 'handleSubscribedMessage: agentId=%s, thread=%s, topicId=%s, attachments=%d',
+ agentId,
+ thread.id,
+ topicId,
+ ((message as any).attachments as unknown[] | undefined)?.length ?? 0,
+ );
if (!topicId) {
log('handleSubscribedMessage: no topicId in thread state, treating as new mention');
@@ -382,55 +411,64 @@ export class AgentBridgeService {
);
}
- AgentBridgeService.activeThreads.add(thread.id);
-
// Read cached channel context from thread state
const channelContext = threadState?.channelContext;
const queueMode = isQueueAgentRuntimeEnabled();
let queueHandoffSucceeded = false;
- // Immediate feedback: mark as received + show typing
- const reactionThreadId =
- opts.client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;
- await safeReaction(
- () => thread.adapter.addReaction(reactionThreadId, message.id, RECEIVED_EMOJI),
- 'add eyes',
- );
- await thread.startTyping();
+ // Mark the thread as active and run the rest inside a try/finally so the
+ // active flag is ALWAYS released. Earlier this `add` happened outside the
+ // try block, and a network error from `thread.startTyping()` would escape
+ // before we entered the try — leaving the thread permanently locked
+ // ("already has an active execution") until process restart.
+ AgentBridgeService.activeThreads.add(thread.id);
try {
- // executeWithCallback handles progress message (post + edit at each step)
- await this.executeWithCallback(thread, message, {
- agentId,
- botContext,
- channelContext,
- charLimit,
- client: opts.client,
- displayToolCalls,
- topicId,
- trigger: RequestTrigger.Bot,
- });
- queueHandoffSucceeded = queueMode;
- } catch (error) {
- // If the cached topicId references a deleted topic (FK violation),
- // clear thread state and retry as a fresh mention instead of surfacing the DB error.
- const cause = (error as any)?.cause;
- const isFKViolation =
- cause?.code === PG_FOREIGN_KEY_VIOLATION && cause?.constraint?.includes('topic_id');
- const errMsg = error instanceof Error ? error.message : String(error);
- if (isFKViolation) {
- log(
- 'handleSubscribedMessage: stale topicId=%s, resetting and retrying as new mention',
+ // Immediate feedback: mark as received + show typing. Both are
+ // non-essential UX niceties; a transient platform network error here
+ // (e.g. ECONNRESET to api.telegram.org) must NOT abort the main flow.
+ const reactionThreadId =
+ opts.client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;
+ await safeSideEffect(
+ () => thread.adapter.addReaction(reactionThreadId, message.id, RECEIVED_EMOJI),
+ 'add eyes',
+ );
+ await safeSideEffect(() => thread.startTyping(), 'startTyping');
+
+ try {
+ // executeWithCallback handles progress message (post + edit at each step)
+ await this.executeWithCallback(thread, message, {
+ agentId,
+ botContext,
+ channelContext,
+ charLimit,
+ client: opts.client,
+ displayToolCalls,
topicId,
- );
- AgentBridgeService.activeThreads.delete(thread.id);
- await thread.setState({ ...threadState, topicId: undefined });
- return this.handleMention(thread, message, opts);
- }
+ trigger: RequestTrigger.Bot,
+ });
+ queueHandoffSucceeded = queueMode;
+ } catch (error) {
+ // If the cached topicId references a deleted topic (FK violation),
+ // clear thread state and retry as a fresh mention instead of surfacing the DB error.
+ const cause = (error as any)?.cause;
+ const isFKViolation =
+ cause?.code === PG_FOREIGN_KEY_VIOLATION && cause?.constraint?.includes('topic_id');
+ const errMsg = error instanceof Error ? error.message : String(error);
+ if (isFKViolation) {
+ log(
+ 'handleSubscribedMessage: stale topicId=%s, resetting and retrying as new mention',
+ topicId,
+ );
+ AgentBridgeService.activeThreads.delete(thread.id);
+ await thread.setState({ ...threadState, topicId: undefined });
+ return this.handleMention(thread, message, opts);
+ }
- log('handleSubscribedMessage error: %O', error);
- await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);
+ log('handleSubscribedMessage error: %O', error);
+ await thread.post(`**Agent Execution Failed**. Details:\n\`\`\`\n${errMsg}\n\`\`\``);
+ }
} finally {
AgentBridgeService.activeThreads.delete(thread.id);
// In queue mode, the callback owns cleanup only after webhook handoff succeeds.
@@ -472,13 +510,22 @@ export class AgentBridgeService {
}
}
- const { agentId, botContext, channelContext, charLimit, client, displayToolCalls, topicId, trigger } = opts;
+ const {
+ agentId,
+ botContext,
+ channelContext,
+ charLimit,
+ client,
+ displayToolCalls,
+ topicId,
+ trigger,
+ } = opts;
const queueMode = isQueueAgentRuntimeEnabled();
const aiAgentService = new AiAgentService(this.db, this.userId);
const timezone = await this.loadTimezone();
- await thread.startTyping();
+ await safeSideEffect(() => thread.startTyping(), 'startTyping (executeWithWebhooks)');
let progressMessage: SentMessage | undefined;
try {
@@ -487,7 +534,7 @@ export class AgentBridgeService {
log('executeWithCallback: failed to post initial placeholder message: %O', error);
}
- const files = this.extractFiles(userMessage);
+ const files = await this.resolveFiles(userMessage, client);
const prompt = this.formatPrompt(userMessage, client);
// Build webhook config for production mode
@@ -1030,70 +1077,31 @@ export class AgentBridgeService {
}
/**
- * Extract file attachment metadata from Chat SDK message for passing to execAgent.
- * Includes attachments from both the message itself and any referenced (quoted) message.
+ * Resolve attachments on an inbound message into `AttachmentSource[]` by
+ * delegating to the platform client's own `extractFiles`. Each platform
+ * owns its own attachment quirks (auth, file_id paths, mime/name
+ * inference, quoted-msg handling, post-Redis refetch); the bridge stays
+ * platform-agnostic.
+ *
+ * Returns undefined when no client is provided or the client returns no
+ * attachments. (The legacy bridge fallback `extractFiles` was deleted
+ * once all 6 platforms migrated to per-client extraction — see Step 2
+ * of the per-platform extractFiles refactor.)
*/
- private extractFiles(message: Message):
+ private async resolveFiles(
+ message: Message,
+ client?: PlatformClient,
+ ): Promise<
| Array<{
buffer?: Buffer;
mimeType?: string;
name?: string;
size?: number;
- url: string;
+ url?: string;
}>
- | undefined {
- type AttachmentLike = {
- buffer?: Buffer;
- content_type?: string;
- filename?: string;
- mimeType?: string;
- name?: string;
- size?: number;
- type?: string;
- url?: string;
- };
-
- const files: Array<{
- buffer?: Buffer;
- mimeType?: string;
- name?: string;
- size?: number;
- url: string;
- }> = [];
-
- // 1. Direct attachments from the message (parsed by Chat SDK)
- const directAttachments = (message as any).attachments as AttachmentLike[] | undefined;
- if (directAttachments?.length) {
- for (const att of directAttachments) {
- if (att.url || att.buffer) {
- files.push({
- buffer: att.buffer,
- mimeType: att.mimeType,
- name: att.name,
- size: att.size,
- url: att.url || '',
- });
- }
- }
- }
-
- // 2. Attachments from referenced (quoted/replied-to) message (Discord raw payload)
- const raw = (message as any).raw as Record<string, any> | undefined;
- const refAttachments = raw?.referenced_message?.attachments as AttachmentLike[] | undefined;
- if (refAttachments?.length) {
- for (const att of refAttachments) {
- if (att.url) {
- files.push({
- mimeType: att.content_type,
- name: att.filename,
- size: att.size,
- url: att.url,
- });
- }
- }
- }
-
- return files.length > 0 ? files : undefined;
+ | undefined
+ > {
+ return client?.extractFiles?.(message);
}
/**
@@ -1135,7 +1143,7 @@ export class AgentBridgeService {
client?: PlatformClient,
): Promise<void> {
const reactionThreadId = client?.resolveReactionThreadId?.(thread.id, message.id) ?? thread.id;
- await safeReaction(
+ await safeSideEffect(
() => thread.adapter.removeReaction(reactionThreadId, message.id, RECEIVED_EMOJI),
'remove eyes',
);
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index 94b9eede666..7d675bcf9f0 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -24,6 +24,35 @@ import {
const log = debug('lobe-server:bot:message-router');
+/**
+ * Compact summary of a Chat SDK Message's attachments for debug logging.
+ * Lets us trace exactly what the platform adapter handed us at the point
+ * where the bot router receives it (before merge / extractFiles run).
+ */
+const summarizeMessageAttachments = (message: Message): Array<Record<string, unknown>> => {
+ const attachments = (message as any).attachments as
+ | Array<{
+ buffer?: Buffer;
+ fetchData?: () => Promise<Buffer>;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ type?: string;
+ url?: string;
+ }>
+ | undefined;
+ if (!attachments?.length) return [];
+ return attachments.map((att) => ({
+ hasBuffer: !!att.buffer,
+ hasFetchData: typeof att.fetchData === 'function',
+ hasUrl: !!att.url,
+ mimeType: att.mimeType,
+ name: att.name,
+ size: att.size,
+ type: att.type,
+ }));
+};
+
interface ResolvedAgentInfo {
agentId: string;
userId: string;
@@ -228,7 +257,13 @@ export class BotMessageRouter {
const commands = this.buildCommands(serverDB, { agentId, platform, userId });
- const concurrencyStrategy = (settings.concurrency as string) || 'debounce';
+ // Default to 'queue' for legacy providers that don't have `concurrency`
+ // in their saved settings. Historically this defaulted to 'debounce', but
+ // chat-sdk's debounce semantics are "drop all but the latest" (Lodash-style),
+ // which silently evicts media messages when followed by a quick text query.
+ // 'queue' preserves all pending messages and merges them via
+ // `mergeSkippedMessages`, which is the right default for chat UX.
+ const concurrencyStrategy = (settings.concurrency as string) || 'queue';
const debounceMs = (settings.debounceMs as number) || DEFAULT_BOT_DEBOUNCE_MS;
const chatBot = this.createChatBot(
adapters,
@@ -395,15 +430,36 @@ export class BotMessageRouter {
bot.onNewMention(async (thread, message, context?: MessageContext) => {
if (await tryDispatch(thread, message.text)) return;
+ log(
+ 'onNewMention raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
+ agentId,
+ platform,
+ message.id,
+ message.text?.length ?? 0,
+ summarizeMessageAttachments(message),
+ context?.skipped?.length ?? 0,
+ );
+ if (context?.skipped?.length) {
+ log(
+ 'onNewMention skipped messages: %o',
+ context.skipped.map((m) => ({
+ attachments: summarizeMessageAttachments(m),
+ id: m.id,
+ textLen: m.text?.length ?? 0,
+ })),
+ );
+ }
+
const merged = BotMessageRouter.mergeSkippedMessages(message, context);
log(
- 'onNewMention: agent=%s, platform=%s, author=%s, thread=%s, merged=%d',
+ 'onNewMention: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
agentId,
platform,
message.author.userName,
thread.id,
(context?.skipped?.length ?? 0) + 1,
+ ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
);
await bridge.handleMention(thread, merged, {
agentId,
@@ -418,15 +474,58 @@ export class BotMessageRouter {
if (message.author.isBot === true) return;
if (await tryDispatch(thread, message.text)) return;
+ // Group / channel / thread policy: only respond when the bot is @-mentioned.
+ // DMs are 1:1 conversations, so every message is implicitly addressed to the bot.
+ // Without this guard, the bot would reply to every follow-up in a subscribed
+ // thread — including messages between other users — and hijack the conversation.
+ // Skipped (debounced) messages are also inspected so a mention queued behind a
+ // non-mention still triggers a reply.
+ const isAddressedToBot =
+ thread.isDM ||
+ message.isMention === true ||
+ context?.skipped?.some((m) => m.isMention === true) === true;
+
+ if (!isAddressedToBot) {
+ log(
+ 'onSubscribedMessage: skip non-mention in group thread, agent=%s, platform=%s, author=%s, thread=%s',
+ agentId,
+ platform,
+ message.author.userName,
+ thread.id,
+ );
+ return;
+ }
+
+ log(
+ 'onSubscribedMessage raw: agent=%s, platform=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
+ agentId,
+ platform,
+ message.id,
+ message.text?.length ?? 0,
+ summarizeMessageAttachments(message),
+ context?.skipped?.length ?? 0,
+ );
+ if (context?.skipped?.length) {
+ log(
+ 'onSubscribedMessage skipped messages: %o',
+ context.skipped.map((m) => ({
+ attachments: summarizeMessageAttachments(m),
+ id: m.id,
+ textLen: m.text?.length ?? 0,
+ })),
+ );
+ }
+
const merged = BotMessageRouter.mergeSkippedMessages(message, context);
log(
- 'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s, merged=%d',
+ 'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
agentId,
platform,
message.author.userName,
thread.id,
(context?.skipped?.length ?? 0) + 1,
+ ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
);
await bridge.handleSubscribedMessage(thread, merged, {
@@ -450,15 +549,36 @@ export class BotMessageRouter {
// Skip text-based slash commands — already handled by registerCommands
if (BotMessageRouter.dispatchTextCommand(message.text, commands)) return;
+ log(
+ 'onNewMessage raw (%s catch-all): agent=%s, msgId=%s, textLen=%d, attachments=%o, skipped=%d',
+ platform,
+ agentId,
+ message.id,
+ message.text?.length ?? 0,
+ summarizeMessageAttachments(message),
+ context?.skipped?.length ?? 0,
+ );
+ if (context?.skipped?.length) {
+ log(
+ 'onNewMessage skipped messages: %o',
+ context.skipped.map((m) => ({
+ attachments: summarizeMessageAttachments(m),
+ id: m.id,
+ textLen: m.text?.length ?? 0,
+ })),
+ );
+ }
+
const merged = BotMessageRouter.mergeSkippedMessages(message, context);
log(
- 'onNewMessage (%s catch-all): agent=%s, author=%s, thread=%s, text=%s',
+ 'onNewMessage (%s catch-all): agent=%s, author=%s, thread=%s, text=%s, mergedAttachments=%d',
platform,
agentId,
message.author.userName,
thread.id,
message.text?.slice(0, 80),
+ ((merged as any).attachments as unknown[] | undefined)?.length ?? 0,
);
await bridge.handleMention(thread, merged, {
diff --git a/src/server/services/bot/__tests__/AgentBridgeService.test.ts b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
index 26dc213ad1b..2236eee76ff 100644
--- a/src/server/services/bot/__tests__/AgentBridgeService.test.ts
+++ b/src/server/services/bot/__tests__/AgentBridgeService.test.ts
@@ -172,4 +172,171 @@ describe('AgentBridgeService', () => {
}),
);
});
+
+ describe('activeThreads cleanup on side-effect failure', () => {
+ // Regression test for the "already has an active execution" lockup:
+ // a transient network error from `thread.startTyping()` (or any other
+ // pre-execution side effect) used to escape the handler before the
+ // try/finally cleanup, leaving the thread permanently in `activeThreads`.
+ // After the fix, side-effect errors are swallowed AND the active flag
+ // is released no matter what.
+
+ it('handleSubscribedMessage releases activeThreads when startTyping throws', async () => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread({ topicId: 'topic-1' });
+ thread.startTyping = vi
+ .fn()
+ .mockRejectedValue(new Error('Network error calling Telegram sendChatAction'));
+ const message = createMessage();
+ const client = createClient();
+
+ await service.handleSubscribedMessage(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client,
+ });
+
+ // The error must NOT escape and the active flag must be cleared.
+ // (startTyping is called twice: once at handler entry as a UX hint,
+ // and once inside executeWithWebhooks — both must be safely swallowed.)
+ expect(thread.startTyping).toHaveBeenCalled();
+ expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);
+ });
+
+ it('handleSubscribedMessage releases activeThreads when addReaction throws', async () => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread({ topicId: 'topic-1' });
+ thread.adapter.addReaction = vi
+ .fn()
+ .mockRejectedValue(new Error('Network error calling Telegram setMessageReaction'));
+ const message = createMessage();
+ const client = createClient();
+
+ await service.handleSubscribedMessage(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client,
+ });
+
+ expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);
+ });
+
+ it('handleMention releases activeThreads when subscribe throws', async () => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread();
+ thread.subscribe = vi.fn().mockRejectedValue(new Error('subscribe network down'));
+ const message = createMessage();
+ const client = createClient();
+
+ await service.handleMention(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client,
+ });
+
+ expect(thread.subscribe).toHaveBeenCalledTimes(1);
+ expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);
+ });
+
+ it('handleMention releases activeThreads when startTyping throws', async () => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const thread = createThread();
+ thread.startTyping = vi.fn().mockRejectedValue(new Error('startTyping network down'));
+ const message = createMessage();
+ const client = createClient();
+
+ await service.handleMention(thread, message, {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client,
+ });
+
+ expect(thread.startTyping).toHaveBeenCalled();
+ expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);
+ });
+
+ it('back-to-back messages on the same thread are not blocked after a side-effect failure', async () => {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const client = createClient();
+
+ // First message: startTyping throws → should NOT lock the thread.
+ const thread1 = createThread({ topicId: 'topic-1' });
+ thread1.startTyping = vi.fn().mockRejectedValue(new Error('boom'));
+ await service.handleSubscribedMessage(thread1, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client,
+ });
+ // Sanity: the active flag must have been released after thread1.
+ expect((AgentBridgeService as any).activeThreads.has(THREAD_ID)).toBe(false);
+
+ // Second message on the same thread: must be processed, NOT skipped.
+ // (If the thread were locked, the handler would early-return without
+ // ever calling thread2.startTyping.)
+ const thread2 = createThread({ topicId: 'topic-1' });
+ await service.handleSubscribedMessage(thread2, createMessage(), {
+ agentId: 'agent-1',
+ botContext: { platformThreadId: THREAD_ID } as any,
+ client,
+ });
+
+ expect(thread2.startTyping).toHaveBeenCalled();
+ });
+ });
+
+ describe('resolveFiles dispatcher', () => {
+ // The bridge no longer has its own attachment extraction logic — every
+ // platform owns its own `client.extractFiles`. resolveFiles is just a
+ // thin delegate. Per-platform attachment shape coverage lives in the
+ // platform's own client.test.ts (e.g. telegram/client.test.ts,
+ // wechat/client.test.ts, slack/client.test.ts, etc.).
+ function callResolve(messageOverrides: Record<string, unknown>, client?: unknown) {
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const message = { id: MESSAGE_ID, text: 'hi', ...messageOverrides } as any;
+ return (service as any).resolveFiles(message, client) as Promise<
+ Array<{ buffer?: Buffer; mimeType?: string; name?: string; size?: number; url?: string }>
+ >;
+ }
+
+ it('delegates to client.extractFiles when the client implements it', async () => {
+ const clientResult = [
+ { buffer: Buffer.from('via-client'), mimeType: 'image/jpeg', name: 'pic.jpg' },
+ ];
+ const clientExtractFiles = vi.fn().mockResolvedValue(clientResult);
+
+ const message = { id: MESSAGE_ID, text: 'hi', attachments: [] } as any;
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+ const result = await (service as any).resolveFiles(message, {
+ extractFiles: clientExtractFiles,
+ });
+
+ expect(clientExtractFiles).toHaveBeenCalledWith(message);
+ expect(result).toBe(clientResult);
+ });
+
+ it('returns undefined when client is missing extractFiles method', async () => {
+ // Defensive: a client that doesn't implement the optional method should
+ // produce no files, not throw.
+ const result = await callResolve({ attachments: [] }, { id: 'discord' });
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when no client is passed', async () => {
+ const result = await callResolve({ attachments: [] }, undefined);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns the client result as-is even when it is an empty array', async () => {
+ const clientExtractFiles = vi.fn().mockResolvedValue([]);
+ const service = new AgentBridgeService(FAKE_DB, USER_ID);
+
+ const message = { id: MESSAGE_ID, text: 'hi' } as any;
+ const result = await (service as any).resolveFiles(message, {
+ extractFiles: clientExtractFiles,
+ });
+
+ expect(clientExtractFiles).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([]);
+ });
+ });
});
diff --git a/src/server/services/bot/__tests__/BotMessageRouter.test.ts b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
index 0118be2ed4e..00d9af401f9 100644
--- a/src/server/services/bot/__tests__/BotMessageRouter.test.ts
+++ b/src/server/services/bot/__tests__/BotMessageRouter.test.ts
@@ -58,10 +58,13 @@ vi.mock('@/server/services/aiAgent', () => ({
})),
}));
+const mockHandleMention = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const mockHandleSubscribedMessage = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+
vi.mock('../AgentBridgeService', () => ({
AgentBridgeService: vi.fn().mockImplementation(() => ({
- handleMention: vi.fn().mockResolvedValue(undefined),
- handleSubscribedMessage: vi.fn().mockResolvedValue(undefined),
+ handleMention: mockHandleMention,
+ handleSubscribedMessage: mockHandleSubscribedMessage,
})),
}));
@@ -132,6 +135,8 @@ describe('BotMessageRouter', () => {
mockGetServerDB.mockResolvedValue(FAKE_DB);
mockInitWithEnvKey.mockResolvedValue(FAKE_GATEKEEPER);
mockFindEnabledByPlatform.mockResolvedValue([]);
+ mockHandleMention.mockResolvedValue(undefined);
+ mockHandleSubscribedMessage.mockResolvedValue(undefined);
});
describe('getWebhookHandler', () => {
@@ -271,4 +276,100 @@ describe('BotMessageRouter', () => {
expect(mockOnNewMessage).toHaveBeenCalledTimes(1);
});
});
+
+ describe('onSubscribedMessage policy', () => {
+ /**
+ * Boot the router so its handler registration runs, then return the
+ * `onSubscribedMessage` handler that was registered with the Chat SDK
+ * so tests can invoke it directly with synthetic thread/message objects.
+ */
+ async function loadSubscribedHandler() {
+ mockFindEnabledByPlatform.mockResolvedValue([makeProvider({ applicationId: 'app-1' })]);
+ const router = new BotMessageRouter();
+ const webhookHandler = router.getWebhookHandler('telegram', 'app-1');
+ const req = new Request('https://example.com/webhook', { body: '{}', method: 'POST' });
+ await webhookHandler(req);
+
+ const lastCall = mockOnSubscribedMessage.mock.calls.at(-1);
+ if (!lastCall) throw new Error('onSubscribedMessage was not registered');
+ return lastCall[0] as (thread: any, message: any, ctx?: any) => Promise<void>;
+ }
+
+ function makeThread(overrides: Partial<{ id: string; isDM: boolean }> = {}) {
+ return {
+ id: 'telegram:chat-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ setState: vi.fn().mockResolvedValue(undefined),
+ ...overrides,
+ };
+ }
+
+ function makeMessage(overrides: Partial<{ isMention: boolean; text: string }> = {}) {
+ return {
+ author: { isBot: false, userName: 'alice' },
+ isMention: false,
+ text: 'hello there',
+ ...overrides,
+ };
+ }
+
+ it('should skip non-mention messages in group threads', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: false, text: 'just chatting with bob' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+
+ it('should respond to @-mentions in group threads', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = makeMessage({ isMention: true, text: '@bot what about this' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should respond to every message in DM threads (no mention required)', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: true });
+ const message = makeMessage({ isMention: false, text: 'hi' });
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should respond when a debounced/skipped earlier message contained the mention', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const skipped = [
+ makeMessage({ isMention: true, text: '@bot first question' }),
+ makeMessage({ isMention: false, text: 'and one more thing' }),
+ ];
+ const message = makeMessage({ isMention: false, text: 'last bit' });
+
+ await handler(thread, message, { skipped, totalSinceLastHandler: 3 });
+
+ expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('should ignore messages from other bots', async () => {
+ const handler = await loadSubscribedHandler();
+ const thread = makeThread({ isDM: false });
+ const message = {
+ author: { isBot: true, userName: 'other-bot' },
+ isMention: true,
+ text: '@bot hi',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/server/services/bot/platforms/discord/client.test.ts b/src/server/services/bot/platforms/discord/client.test.ts
index e849c77689d..28d76bc307c 100644
--- a/src/server/services/bot/platforms/discord/client.test.ts
+++ b/src/server/services/bot/platforms/discord/client.test.ts
@@ -33,4 +33,149 @@ describe('DiscordGatewayClient', () => {
expect(client.shouldSubscribe?.('discord:@me:dm-channel-1')).toBe(true);
});
});
+
+ describe('extractFiles', () => {
+ // Discord is the easy case: attachments come with public CDN URLs that
+ // require no auth and survive `Message.toJSON` unchanged. extractFiles
+ // just walks `att.url` and (Discord-specific) digs into
+ // `raw.referenced_message.attachments` for quoted-message attachments.
+
+ const makeMessage = (overrides: Record<string, unknown>) =>
+ ({
+ attachments: [],
+ id: 'msg-1',
+ text: '',
+ ...overrides,
+ }) as any;
+
+ it('returns undefined when no attachments are present', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(makeMessage({ attachments: [] }));
+ expect(result).toBeUndefined();
+ });
+
+ it('forwards direct attachments by URL with metadata', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [
+ {
+ mimeType: 'image/png',
+ name: 'screenshot.png',
+ size: 4321,
+ type: 'image',
+ url: 'https://cdn.discordapp.com/attachments/123/456/screenshot.png',
+ },
+ ],
+ }),
+ );
+
+ expect(result).toEqual([
+ {
+ mimeType: 'image/png',
+ name: 'screenshot.png',
+ size: 4321,
+ url: 'https://cdn.discordapp.com/attachments/123/456/screenshot.png',
+ },
+ ]);
+ });
+
+ it('skips direct attachments missing url', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [
+ { mimeType: 'image/png', name: 'orphan.png', type: 'image' },
+ {
+ mimeType: 'image/png',
+ name: 'good.png',
+ type: 'image',
+ url: 'https://cdn.discordapp.com/attachments/123/456/good.png',
+ },
+ ],
+ }),
+ );
+ expect(result).toEqual([
+ {
+ mimeType: 'image/png',
+ name: 'good.png',
+ size: undefined,
+ url: 'https://cdn.discordapp.com/attachments/123/456/good.png',
+ },
+ ]);
+ });
+
+ it('picks up referenced (quoted) message attachments via raw payload', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [],
+ raw: {
+ referenced_message: {
+ attachments: [
+ {
+ content_type: 'image/jpeg',
+ filename: 'quoted.jpg',
+ size: 100,
+ url: 'https://cdn.discordapp.com/attachments/123/456/quoted.jpg',
+ },
+ ],
+ },
+ },
+ }),
+ );
+
+ expect(result).toEqual([
+ {
+ mimeType: 'image/jpeg',
+ name: 'quoted.jpg',
+ size: 100,
+ url: 'https://cdn.discordapp.com/attachments/123/456/quoted.jpg',
+ },
+ ]);
+ });
+
+ it('combines direct and referenced attachments in order', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [
+ {
+ mimeType: 'image/png',
+ name: 'direct.png',
+ type: 'image',
+ url: 'https://cdn.discordapp.com/attachments/123/456/direct.png',
+ },
+ ],
+ raw: {
+ referenced_message: {
+ attachments: [
+ {
+ content_type: 'image/jpeg',
+ filename: 'quoted.jpg',
+ size: 100,
+ url: 'https://cdn.discordapp.com/attachments/123/456/quoted.jpg',
+ },
+ ],
+ },
+ },
+ }),
+ );
+
+ expect(result).toHaveLength(2);
+ expect(result?.[0]?.name).toBe('direct.png');
+ expect(result?.[1]?.name).toBe('quoted.jpg');
+ });
+
+ it('returns undefined when neither direct nor referenced attachments have urls', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ mimeType: 'image/png', name: 'no-url.png', type: 'image' }],
+ raw: { referenced_message: { attachments: [] } },
+ }),
+ );
+ expect(result).toBeUndefined();
+ });
+ });
});
diff --git a/src/server/services/bot/platforms/discord/client.ts b/src/server/services/bot/platforms/discord/client.ts
index d1d8dd49071..42cde1e83bd 100644
--- a/src/server/services/bot/platforms/discord/client.ts
+++ b/src/server/services/bot/platforms/discord/client.ts
@@ -1,8 +1,9 @@
import type { DiscordAdapter } from '@chat-adapter/discord';
import { createDiscordAdapter } from '@chat-adapter/discord';
-import type { Chat as ChatBot } from 'chat';
+import type { Chat as ChatBot, Message } from 'chat';
import debug from 'debug';
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
import {
BOT_RUNTIME_STATUSES,
getRuntimeStatusErrorMessage,
@@ -218,6 +219,77 @@ class DiscordGatewayClient implements PlatformClient {
};
}
+ /**
+ * Resolve attachments on an inbound Discord message into `AttachmentSource[]`.
+ *
+ * Discord is the easiest case: attachments come with a public CDN URL
+ * (`https://cdn.discordapp.com/...`) that requires no auth, and the URL
+ * field IS preserved by `Message.toJSON`. So this method just walks the
+ * surviving attachment metadata and forwards URLs to `ingestAttachment`,
+ * which `fetch()`es them with no special handling.
+ *
+ * Discord ALSO has the `referenced_message.attachments` quirk: if a user
+ * @-mentions the bot while replying to an earlier message that had
+ * attachments, the chat-sdk only exposes the current message's
+ * attachments. We dig into `message.raw.referenced_message.attachments`
+ * to recover the quoted message's files. The Discord webhook payload
+ * uses snake_case (`content_type`, `filename`), so we normalize them.
+ */
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ type DiscordRefAttachment = {
+ content_type?: string;
+ filename?: string;
+ size?: number;
+ url?: string;
+ };
+ type DirectAttachment = {
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ type?: string;
+ url?: string;
+ };
+
+ const directAttachments = (message as any).attachments as DirectAttachment[] | undefined;
+ const raw = (message as any).raw as Record<string, any> | undefined;
+ const refAttachments = raw?.referenced_message?.attachments as
+ | DiscordRefAttachment[]
+ | undefined;
+
+ log(
+ 'extractFiles: msgId=%s, direct=%d, referenced=%d',
+ (message as any).id,
+ directAttachments?.length ?? 0,
+ refAttachments?.length ?? 0,
+ );
+
+ const results: AttachmentSource[] = [];
+
+ // 1. Direct attachments on the current message
+ for (const att of directAttachments ?? []) {
+ if (!att.url) continue;
+ results.push({
+ mimeType: att.mimeType,
+ name: att.name,
+ size: att.size,
+ url: att.url,
+ });
+ }
+
+ // 2. Attachments from a quoted (referenced) message
+ for (const att of refAttachments ?? []) {
+ if (!att.url) continue;
+ results.push({
+ mimeType: att.content_type,
+ name: att.filename,
+ size: att.size,
+ url: att.url,
+ });
+ }
+
+ return results.length > 0 ? results : undefined;
+ }
+
extractChatId(platformThreadId: string): string {
return extractChannelId(platformThreadId);
}
diff --git a/src/server/services/bot/platforms/discord/const.ts b/src/server/services/bot/platforms/discord/const.ts
index 2b3a8456e9f..fc667853539 100644
--- a/src/server/services/bot/platforms/discord/const.ts
+++ b/src/server/services/bot/platforms/discord/const.ts
@@ -1,2 +1,4 @@
/** Discord API allows max 100 messages per request. */
export const MAX_DISCORD_HISTORY_LIMIT = 100;
+
+export const DEFAULT_DISCORD_CONNECTION_MODE = 'websocket';
diff --git a/src/server/services/bot/platforms/discord/definition.ts b/src/server/services/bot/platforms/discord/definition.ts
index c5d2aaa2efb..333ba8cc07d 100644
--- a/src/server/services/bot/platforms/discord/definition.ts
+++ b/src/server/services/bot/platforms/discord/definition.ts
@@ -1,11 +1,12 @@
import type { PlatformDefinition } from '../types';
import { DiscordClientFactory } from './client';
+import { DEFAULT_DISCORD_CONNECTION_MODE } from './const';
import { schema } from './schema';
export const discord: PlatformDefinition = {
id: 'discord',
name: 'Discord',
- connectionMode: 'persistent',
+ connectionMode: DEFAULT_DISCORD_CONNECTION_MODE,
description: 'Connect a Discord bot',
documentation: {
portalUrl: 'https://discord.com/developers/applications',
diff --git a/src/server/services/bot/platforms/feishu/client.test.ts b/src/server/services/bot/platforms/feishu/client.test.ts
new file mode 100644
index 00000000000..f4c0c4dc825
--- /dev/null
+++ b/src/server/services/bot/platforms/feishu/client.test.ts
@@ -0,0 +1,198 @@
+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'));
+
+vi.mock('@lobechat/chat-adapter-feishu', () => ({
+ createLarkAdapter: mockCreateLarkAdapter,
+ downloadMediaFromRawMessage: mockDownloadMediaFromRawMessage,
+ LarkApiClient: vi.fn().mockImplementation(() => ({
+ getTenantAccessToken: mockGetTenantAccessToken,
+ })),
+}));
+
+vi.mock('@/server/services/gateway/runtimeStatus', () => ({
+ BOT_RUNTIME_STATUSES: {
+ connected: 'connected',
+ disconnected: 'disconnected',
+ failed: 'failed',
+ starting: 'starting',
+ },
+ getRuntimeStatusErrorMessage: (e: any) => String(e?.message ?? e),
+ updateBotRuntimeStatus: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('./gateway', () => ({
+ FeishuWSConnection: vi.fn().mockImplementation(() => ({
+ close: vi.fn(),
+ start: vi.fn().mockResolvedValue(undefined),
+ })),
+}));
+
+const { FeishuClientFactory } = await import('./client');
+
+describe('FeishuWebhookClient.extractFiles', () => {
+ // Verifies the post-Redis re-download path: when Feishu messages
+ // round-trip through the chat-sdk debounce/queue, `Message.toJSON`
+ // strips both `att.buffer` and `att.fetchData`. We recover by walking
+ // `message.raw.content` (JSON) and re-running the same download logic
+ // via the package-exported helper.
+
+ const createClient = (platform: 'feishu' | 'lark' = 'feishu') =>
+ new FeishuClientFactory().createClient(
+ {
+ applicationId: 'cli_test_app',
+ credentials: { appSecret: 'sec', encryptKey: 'enc' },
+ platform,
+ // No connectionMode → defaults to webhook
+ settings: {},
+ },
+ { appUrl: 'https://example.com' },
+ );
+
+ /** Build a fake Chat SDK Message with a Lark raw payload. */
+ const makeMessage = (raw: Record<string, unknown>, id = 'om_test_msg_001') =>
+ ({ id, attachments: [], raw, text: '' }) as any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('returns undefined when message has no raw payload', async () => {
+ const client = createClient();
+ const message = { id: 'm', attachments: [], text: '' } as any;
+ const result = await client.extractFiles!(message);
+ expect(mockDownloadMediaFromRawMessage).not.toHaveBeenCalled();
+ expect(result).toBeUndefined();
+ });
+
+ it('delegates to downloadMediaFromRawMessage and maps the result', async () => {
+ const buffer = Buffer.from('lark-image-bytes');
+ mockDownloadMediaFromRawMessage.mockResolvedValue([
+ {
+ buffer,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ },
+ ]);
+
+ const client = createClient();
+ const raw = {
+ chat_id: 'oc_test',
+ content: JSON.stringify({ image_key: 'img_1' }),
+ create_time: '1700000000000',
+ message_id: 'om_test_msg_001',
+ message_type: 'image',
+ };
+ const result = await client.extractFiles!(makeMessage(raw));
+
+ expect(mockDownloadMediaFromRawMessage).toHaveBeenCalledTimes(1);
+ expect(mockDownloadMediaFromRawMessage).toHaveBeenCalledWith(
+ expect.anything(), // LarkApiClient instance
+ raw,
+ );
+ expect(result).toEqual([
+ { buffer, mimeType: 'image/jpeg', name: 'image.jpg', size: undefined },
+ ]);
+ });
+
+ it('returns undefined when downloadMediaFromRawMessage resolves to empty array', async () => {
+ mockDownloadMediaFromRawMessage.mockResolvedValue([]);
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ message_id: 'm',
+ message_type: 'text',
+ content: JSON.stringify({ text: 'hi' }),
+ }),
+ );
+ expect(mockDownloadMediaFromRawMessage).toHaveBeenCalledTimes(1);
+ expect(result).toBeUndefined();
+ });
+
+ it('maps file attachments preserving name + size', async () => {
+ const buffer = Buffer.from('pdf-bytes');
+ mockDownloadMediaFromRawMessage.mockResolvedValue([
+ {
+ buffer,
+ mimeType: 'application/pdf',
+ name: 'report.pdf',
+ size: 4096,
+ type: 'file',
+ },
+ ]);
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ message_id: 'm',
+ message_type: 'file',
+ content: JSON.stringify({ file_key: 'f', file_name: 'report.pdf' }),
+ }),
+ );
+ expect(result).toEqual([
+ { buffer, mimeType: 'application/pdf', name: 'report.pdf', size: 4096 },
+ ]);
+ });
+
+ it('caches LarkApiClient across multiple extractFiles calls (token cache hot)', async () => {
+ const { LarkApiClient } = await import('@lobechat/chat-adapter-feishu');
+ const ctorSpy = vi.mocked(LarkApiClient);
+ const ctorCallCountBefore = ctorSpy.mock.calls.length;
+
+ const client = createClient();
+ mockDownloadMediaFromRawMessage.mockResolvedValue([]);
+
+ await client.extractFiles!(
+ makeMessage({ message_id: 'm1', message_type: 'text', content: '{}' }),
+ );
+ await client.extractFiles!(
+ makeMessage({ message_id: 'm2', message_type: 'text', content: '{}' }),
+ );
+
+ // The lazy `_api` getter should construct LarkApiClient at most ONCE per
+ // FeishuWebhookClient instance, so the second extractFiles call reuses
+ // the same instance (and its tenant token cache).
+ expect(ctorSpy.mock.calls.length - ctorCallCountBefore).toBeLessThanOrEqual(1);
+ });
+
+ it('propagates errors from downloadMediaFromRawMessage as-is', async () => {
+ mockDownloadMediaFromRawMessage.mockRejectedValue(new Error('helper crashed'));
+ const client = createClient();
+ await expect(
+ client.extractFiles!(
+ makeMessage({
+ message_id: 'm',
+ message_type: 'image',
+ content: JSON.stringify({ image_key: 'k' }),
+ }),
+ ),
+ ).rejects.toThrow('helper crashed');
+ });
+
+ it('works the same for lark platform variant', async () => {
+ const buffer = Buffer.from('lark');
+ mockDownloadMediaFromRawMessage.mockResolvedValue([
+ { buffer, mimeType: 'image/jpeg', name: 'image.jpg', type: 'image' },
+ ]);
+
+ const client = createClient('lark');
+ const raw = {
+ chat_id: 'oc_test',
+ content: JSON.stringify({ image_key: 'img_1' }),
+ create_time: '1700000000000',
+ message_id: 'om_test_msg_001',
+ message_type: 'image',
+ };
+ const result = await client.extractFiles!(makeMessage(raw));
+
+ expect(result).toEqual([
+ { buffer, mimeType: 'image/jpeg', name: 'image.jpg', size: undefined },
+ ]);
+ });
+});
diff --git a/src/server/services/bot/platforms/feishu/client.ts b/src/server/services/bot/platforms/feishu/client.ts
index f7af72ef28e..886cb37d96d 100644
--- a/src/server/services/bot/platforms/feishu/client.ts
+++ b/src/server/services/bot/platforms/feishu/client.ts
@@ -1,6 +1,14 @@
-import { createLarkAdapter, LarkApiClient } from '@lobechat/chat-adapter-feishu';
+import {
+ createLarkAdapter,
+ decodeLarkThreadId,
+ downloadMediaFromRawMessage,
+ LarkApiClient,
+ type LarkRawMessage,
+} from '@lobechat/chat-adapter-feishu';
+import type { Chat as ChatBot, Message } from 'chat';
import debug from 'debug';
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
import {
BOT_RUNTIME_STATUSES,
getRuntimeStatusErrorMessage,
@@ -18,11 +26,24 @@ import {
type ValidationResult,
} from '../types';
import { formatUsageStats } from '../utils';
+import { FeishuWSConnection } from './gateway';
const log = debug('bot-platform:feishu:client');
+const CONNECTED_STATUS_TTL_BUFFER_MS = 60 * 1000;
+const DEFAULT_DURATION_MS = 8 * 60 * 60 * 1000; // 8 hours
+
+export interface GatewayListenerOptions {
+ durationMs?: number;
+ waitUntil?: (task: Promise<any>) => void;
+}
+
function extractChatId(platformThreadId: string): string {
- return platformThreadId.split(':')[1];
+ // Delegate to the adapter's shared decoder so this stays in sync with the
+ // threadId format. New format is `lark:p2p:oc_xxx` / `lark:group:oc_xxx`,
+ // legacy is `lark:oc_xxx` — naive `split(':')[1]` would return `'p2p'` /
+ // `'group'` for the new format and break outbound API calls.
+ return decodeLarkThreadId(platformThreadId).chatId;
}
/** Resolve the Lark/Feishu domain from the platform id. */
@@ -30,12 +51,80 @@ function resolveDomain(platform: string): 'lark' | 'feishu' {
return platform === 'lark' ? 'lark' : 'feishu';
}
+// ---------- Shared runtime operations ----------
+
+function createMessenger(
+ config: BotProviderConfig,
+ domain: 'lark' | 'feishu',
+ platformThreadId: string,
+): PlatformMessenger {
+ const api = new LarkApiClient(config.applicationId, config.credentials.appSecret, domain);
+ const chatId = extractChatId(platformThreadId);
+ return {
+ createMessage: (content) => api.sendMessage(chatId, content).then(() => {}),
+ editMessage: (messageId, content) => api.editMessage(messageId, content).then(() => {}),
+ removeReaction: () => Promise.resolve(),
+ triggerTyping: () => Promise.resolve(),
+ };
+}
+
+/**
+ * Resolve attachments on an inbound Feishu/Lark message into
+ * `AttachmentSource[]`. Shared by both webhook and websocket clients.
+ *
+ * Why we re-download instead of trusting the in-message buffer or fetchData:
+ * the chat-adapter-feishu used to set `fetchData` (sync `parseMessage` path)
+ * or `buffer` (async `parseRawEvent` path) on attachments, but
+ * `Message.toJSON` strips both whenever the message is enqueued (debounce
+ * always; queue when busy). So whenever a message round-trips through the
+ * queue, the in-memory data is gone and we have to re-fetch via the Lark
+ * resource API ourselves. After the adapter refactor, attachments are now
+ * metadata-only at parse time and `extractFiles` is the sole download path.
+ *
+ * The original `LarkRawMessage` (with `message_id` + `content` JSON
+ * carrying `image_key` / `file_key` / etc.) IS preserved in `message.raw`
+ * because `toJSON` keeps it intact. We hand that and a `LarkApiClient` to
+ * the package-exported `downloadMediaFromRawMessage` helper.
+ */
+async function feishuExtractFiles(
+ api: LarkApiClient,
+ message: Message,
+): Promise<AttachmentSource[] | undefined> {
+ const raw = (message as any).raw as LarkRawMessage | undefined;
+ if (!raw) return undefined;
+
+ log('extractFiles: msgId=%s, message_type=%s', (message as any).id, raw.message_type);
+
+ const attachments = await downloadMediaFromRawMessage(api, raw);
+ if (attachments.length === 0) {
+ log('extractFiles: no media items resolved for msgId=%s', (message as any).id);
+ return undefined;
+ }
+
+ log(
+ 'extractFiles: resolved %d media item(s) for msgId=%s',
+ attachments.length,
+ (message as any).id,
+ );
+
+ return attachments.map((att: any) => ({
+ buffer: att.buffer,
+ mimeType: att.mimeType,
+ name: att.name,
+ size: att.size,
+ }));
+}
+
+// ---------- Webhook Client (existing behavior) ----------
+
class FeishuWebhookClient implements PlatformClient {
readonly id: string;
readonly applicationId: string;
private config: BotProviderConfig;
private domain: 'lark' | 'feishu';
+ /** Lazy-cached LarkApiClient — keeps the tenant token cache hot across calls. */
+ private _api?: LarkApiClient;
constructor(config: BotProviderConfig, _context: BotPlatformRuntimeContext) {
this.config = config;
@@ -44,10 +133,19 @@ class FeishuWebhookClient implements PlatformClient {
this.domain = resolveDomain(config.platform);
}
- // --- Lifecycle ---
+ private get api(): LarkApiClient {
+ if (!this._api) {
+ this._api = new LarkApiClient(
+ this.config.applicationId,
+ this.config.credentials.appSecret,
+ this.domain,
+ );
+ }
+ return this._api;
+ }
async start(): Promise<void> {
- log('Starting FeishuClient appId=%s domain=%s', this.applicationId, this.domain);
+ log('Starting FeishuClient (webhook) appId=%s domain=%s', this.applicationId, this.domain);
await updateBotRuntimeStatus({
applicationId: this.applicationId,
platform: this.id,
@@ -68,7 +166,7 @@ class FeishuWebhookClient implements PlatformClient {
status: BOT_RUNTIME_STATUSES.connected,
});
- log('FeishuClient appId=%s credentials verified', this.applicationId);
+ log('FeishuClient (webhook) appId=%s credentials verified', this.applicationId);
} catch (error) {
await updateBotRuntimeStatus({
applicationId: this.applicationId,
@@ -81,7 +179,7 @@ class FeishuWebhookClient implements PlatformClient {
}
async stop(): Promise<void> {
- log('Stopping FeishuClient appId=%s', this.applicationId);
+ log('Stopping FeishuClient (webhook) appId=%s', this.applicationId);
await updateBotRuntimeStatus({
applicationId: this.applicationId,
platform: this.id,
@@ -89,8 +187,6 @@ class FeishuWebhookClient implements PlatformClient {
});
}
- // --- Runtime Operations ---
-
createAdapter(): Record<string, any> {
return {
[this.config.platform]: createLarkAdapter({
@@ -104,20 +200,209 @@ class FeishuWebhookClient implements PlatformClient {
}
getMessenger(platformThreadId: string): PlatformMessenger {
- const api = new LarkApiClient(
- this.config.applicationId,
- this.config.credentials.appSecret,
- this.domain,
+ return createMessenger(this.config, this.domain, platformThreadId);
+ }
+
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ return feishuExtractFiles(this.api, message);
+ }
+
+ extractChatId(platformThreadId: string): string {
+ return extractChatId(platformThreadId);
+ }
+
+ formatMarkdown(markdown: string): string {
+ return stripMarkdown(markdown);
+ }
+
+ formatReply(body: string, stats?: UsageStats): string {
+ if (!stats || !this.config.settings?.showUsageStats) return body;
+ return `${body}\n\n${formatUsageStats(stats)}`;
+ }
+
+ parseMessageId(compositeId: string): string {
+ return compositeId;
+ }
+}
+
+// ---------- WebSocket Client (persistent, using Lark SDK WSClient) ----------
+
+class FeishuWSClientImpl implements PlatformClient {
+ readonly id: string;
+ readonly applicationId: string;
+
+ private config: BotProviderConfig;
+ private context: BotPlatformRuntimeContext;
+ private domain: 'lark' | 'feishu';
+ private gateway: FeishuWSConnection | null = null;
+ private bot: ChatBot<any> | null = null;
+ private refreshTimer: ReturnType<typeof setTimeout> | null = null;
+ private stopped = false;
+ /** Lazy-cached LarkApiClient — keeps the tenant token cache hot across calls. */
+ private _api?: LarkApiClient;
+
+ constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {
+ this.config = config;
+ this.context = context;
+ this.id = config.platform;
+ this.applicationId = config.applicationId;
+ this.domain = resolveDomain(config.platform);
+ }
+
+ private get api(): LarkApiClient {
+ if (!this._api) {
+ this._api = new LarkApiClient(
+ this.config.applicationId,
+ this.config.credentials.appSecret,
+ this.domain,
+ );
+ }
+ return this._api;
+ }
+
+ async start(options?: GatewayListenerOptions): Promise<void> {
+ log('Starting FeishuClient (ws) appId=%s domain=%s', this.applicationId, this.domain);
+
+ this.stopped = false;
+ const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;
+ const runtimeStatusTtlMs = durationMs + CONNECTED_STATUS_TTL_BUFFER_MS;
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.starting,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
);
- const chatId = extractChatId(platformThreadId);
+
+ try {
+ if (this.bot) {
+ await this.bot.shutdown().catch(() => {});
+ this.bot = null;
+ }
+
+ const adapter = createLarkAdapter({
+ appId: this.config.applicationId,
+ appSecret: this.config.credentials.appSecret,
+ encryptKey: this.config.credentials.encryptKey,
+ platform: this.domain,
+ verificationToken: this.config.credentials.verificationToken,
+ });
+
+ const { Chat, ConsoleLogger } = await import('chat');
+
+ const chatConfig: any = {
+ adapters: { [this.config.platform]: adapter },
+ userName: `lobehub-gateway-${this.applicationId}`,
+ };
+
+ if (this.context.redisClient) {
+ const { createIoRedisState } = await import('@chat-adapter/state-ioredis');
+ chatConfig.state = createIoRedisState({
+ client: this.context.redisClient as any,
+ logger: new ConsoleLogger(),
+ });
+ }
+
+ const bot = new Chat(chatConfig);
+ this.bot = bot;
+ await bot.initialize();
+
+ const webhookUrl = `${(this.context.appUrl || '').trim()}/api/agent/webhooks/${this.config.platform}/${this.applicationId}`;
+
+ this.gateway = new FeishuWSConnection({
+ appId: this.config.applicationId,
+ appSecret: this.config.credentials.appSecret,
+ domain: this.domain,
+ verificationToken: this.config.credentials.verificationToken,
+ webhookUrl,
+ });
+
+ await this.gateway.start();
+
+ if (!options) {
+ this.refreshTimer = setTimeout(() => {
+ if (this.stopped) return;
+
+ log(
+ 'FeishuClient appId=%s duration elapsed (%dh), refreshing...',
+ this.applicationId,
+ durationMs / 3_600_000,
+ );
+ this.gateway?.close();
+ this.start().catch((err) => {
+ log('Failed to refresh FeishuClient appId=%s: %O', this.applicationId, err);
+ });
+ }, durationMs);
+ }
+
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.connected,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+
+ log('FeishuClient (ws) appId=%s started', this.applicationId);
+ } catch (error) {
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ errorMessage: getRuntimeStatusErrorMessage(error),
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.failed,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+ throw error;
+ }
+ }
+
+ async stop(): Promise<void> {
+ log('Stopping FeishuClient (ws) appId=%s', this.applicationId);
+ this.stopped = true;
+ if (this.refreshTimer) {
+ clearTimeout(this.refreshTimer);
+ this.refreshTimer = null;
+ }
+ this.gateway?.close();
+ this.gateway = null;
+ if (this.bot) {
+ await this.bot.shutdown().catch(() => {});
+ this.bot = null;
+ }
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.disconnected,
+ },
+ { redisClient: this.context.redisClient as any },
+ );
+ }
+
+ createAdapter(): Record<string, any> {
return {
- createMessage: (content) => api.sendMessage(chatId, content).then(() => {}),
- editMessage: (messageId, content) => api.editMessage(messageId, content).then(() => {}),
- removeReaction: () => Promise.resolve(),
- triggerTyping: () => Promise.resolve(),
+ [this.config.platform]: createLarkAdapter({
+ appId: this.config.applicationId,
+ appSecret: this.config.credentials.appSecret,
+ encryptKey: this.config.credentials.encryptKey,
+ platform: this.domain,
+ verificationToken: this.config.credentials.verificationToken,
+ }),
};
}
+ getMessenger(platformThreadId: string): PlatformMessenger {
+ return createMessenger(this.config, this.domain, platformThreadId);
+ }
+
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ return feishuExtractFiles(this.api, message);
+ }
+
extractChatId(platformThreadId: string): string {
return extractChatId(platformThreadId);
}
@@ -136,8 +421,17 @@ class FeishuWebhookClient implements PlatformClient {
}
}
+// ---------- Factory ----------
+
export class FeishuClientFactory extends ClientFactory {
createClient(config: BotProviderConfig, context: BotPlatformRuntimeContext): PlatformClient {
+ // Fall back to 'webhook' to preserve behavior for legacy provider rows
+ // that pre-date the connectionMode field. New providers always go through
+ // the form which seeds connectionMode from the schema default.
+ const mode = (config.settings?.connectionMode as string) || 'webhook';
+ if (mode === 'websocket') {
+ return new FeishuWSClientImpl(config, context);
+ }
return new FeishuWebhookClient(config, context);
}
diff --git a/src/server/services/bot/platforms/feishu/const.ts b/src/server/services/bot/platforms/feishu/const.ts
index 5b184de240a..62b93f0697b 100644
--- a/src/server/services/bot/platforms/feishu/const.ts
+++ b/src/server/services/bot/platforms/feishu/const.ts
@@ -1,2 +1,4 @@
/** Feishu API allows max 50 messages per request. */
export const MAX_FEISHU_HISTORY_LIMIT = 50;
+
+export const DEFAULT_FEISHU_CONNECTION_MODE = 'websocket';
diff --git a/src/server/services/bot/platforms/feishu/definitions/feishu.ts b/src/server/services/bot/platforms/feishu/definitions/feishu.ts
index f1fd90c1f02..d8eb8ce3667 100644
--- a/src/server/services/bot/platforms/feishu/definitions/feishu.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/feishu.ts
@@ -1,17 +1,18 @@
import type { PlatformDefinition } from '../../types';
+import { DEFAULT_FEISHU_CONNECTION_MODE } from '../const';
import { sharedSchema } from './schema';
import { sharedClientFactory } from './shared';
export const feishu: PlatformDefinition = {
id: 'feishu',
name: 'Feishu',
+ connectionMode: DEFAULT_FEISHU_CONNECTION_MODE,
description: 'Connect a Feishu bot',
documentation: {
portalUrl: 'https://open.feishu.cn/app',
setupGuideUrl: 'https://lobehub.com/docs/usage/channels/feishu',
},
schema: sharedSchema,
- showWebhookUrl: true,
supportsMarkdown: false,
clientFactory: sharedClientFactory,
};
diff --git a/src/server/services/bot/platforms/feishu/definitions/lark.ts b/src/server/services/bot/platforms/feishu/definitions/lark.ts
index e798e3ae1af..62197a43f8a 100644
--- a/src/server/services/bot/platforms/feishu/definitions/lark.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/lark.ts
@@ -1,17 +1,18 @@
import type { PlatformDefinition } from '../../types';
+import { DEFAULT_FEISHU_CONNECTION_MODE } from '../const';
import { sharedSchema } from './schema';
import { sharedClientFactory } from './shared';
export const lark: PlatformDefinition = {
id: 'lark',
name: 'Lark',
+ connectionMode: DEFAULT_FEISHU_CONNECTION_MODE,
description: 'Connect a Lark bot',
documentation: {
portalUrl: 'https://open.larksuite.com/app',
setupGuideUrl: 'https://lobehub.com/docs/usage/channels/lark',
},
schema: sharedSchema,
- showWebhookUrl: true,
supportsMarkdown: false,
clientFactory: sharedClientFactory,
};
diff --git a/src/server/services/bot/platforms/feishu/definitions/schema.ts b/src/server/services/bot/platforms/feishu/definitions/schema.ts
index 6571b26456d..7cec9950094 100644
--- a/src/server/services/bot/platforms/feishu/definitions/schema.ts
+++ b/src/server/services/bot/platforms/feishu/definitions/schema.ts
@@ -7,7 +7,7 @@ import {
import { displayToolCallsField, userIdField } from '../../const';
import type { FieldSchema } from '../../types';
-import { MAX_FEISHU_HISTORY_LIMIT } from '../const';
+import { DEFAULT_FEISHU_CONNECTION_MODE, MAX_FEISHU_HISTORY_LIMIT } from '../const';
export const sharedSchema: FieldSchema[] = [
{
@@ -49,6 +49,15 @@ export const sharedSchema: FieldSchema[] = [
key: 'settings',
label: 'channel.settings',
properties: [
+ {
+ key: 'connectionMode',
+ default: DEFAULT_FEISHU_CONNECTION_MODE,
+ description: 'channel.connectionModeHint',
+ enum: ['websocket', 'webhook'],
+ enumLabels: ['channel.connectionModeWebSocket', 'channel.connectionModeWebhook'],
+ label: 'channel.connectionMode',
+ type: 'string',
+ },
{
key: 'charLimit',
default: 4000,
diff --git a/src/server/services/bot/platforms/feishu/gateway.test.ts b/src/server/services/bot/platforms/feishu/gateway.test.ts
new file mode 100644
index 00000000000..00ced52ef33
--- /dev/null
+++ b/src/server/services/bot/platforms/feishu/gateway.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { FeishuWSConnection } from './gateway';
+
+// ---- Mock @larksuiteoapi/node-sdk ----
+
+const mockStart = vi.fn().mockResolvedValue(undefined);
+const mockClose = vi.fn();
+let capturedEventHandlers: Record<string, (...args: any[]) => any> = {};
+
+vi.mock('@larksuiteoapi/node-sdk', () => {
+ class MockEventDispatcher {
+ register(handles: Record<string, (...args: any[]) => any>) {
+ capturedEventHandlers = { ...capturedEventHandlers, ...handles };
+ return this;
+ }
+ }
+
+ class MockWSClient {
+ close = mockClose;
+ start = mockStart;
+ constructor() {}
+ }
+
+ return {
+ Domain: { Feishu: 0, Lark: 1 },
+ EventDispatcher: MockEventDispatcher,
+ LoggerLevel: { info: 3 },
+ WSClient: MockWSClient,
+ };
+});
+
+// ---- Tests ----
+
+describe('FeishuWSConnection', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ capturedEventHandlers = {};
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('ok', { status: 200 })));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ function createConnection(
+ overrides?: Partial<Parameters<(typeof FeishuWSConnection)['prototype']['start']>>,
+ ) {
+ return new FeishuWSConnection({
+ appId: 'cli_test',
+ appSecret: 'test_secret',
+ domain: 'feishu',
+ webhookUrl: 'http://localhost:3000/api/agent/webhooks/feishu/test_app',
+ });
+ }
+
+ describe('start', () => {
+ it('should call WSClient.start with EventDispatcher', async () => {
+ const conn = createConnection();
+ await conn.start();
+
+ expect(mockStart).toHaveBeenCalledWith(
+ expect.objectContaining({ eventDispatcher: expect.any(Object) }),
+ );
+ });
+
+ it('should register im.message.receive_v1 handler', async () => {
+ const conn = createConnection();
+ await conn.start();
+
+ expect(capturedEventHandlers['im.message.receive_v1']).toBeTypeOf('function');
+ });
+ });
+
+ describe('event forwarding', () => {
+ it('should forward im.message.receive_v1 events to webhook URL', async () => {
+ const conn = createConnection();
+ await conn.start();
+
+ const eventData = {
+ message: {
+ chat_id: 'oc_test',
+ content: '{"text":"hello"}',
+ message_type: 'text',
+ },
+ sender: { sender_id: { open_id: 'ou_test' } },
+ };
+
+ await capturedEventHandlers['im.message.receive_v1'](eventData);
+
+ expect(fetch).toHaveBeenCalledWith(
+ 'http://localhost:3000/api/agent/webhooks/feishu/test_app',
+ expect.objectContaining({
+ body: expect.any(String),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ }),
+ );
+
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
+ const body = JSON.parse(fetchCall[1]!.body as string);
+ expect(body.schema).toBe('2.0');
+ expect(body.header.event_type).toBe('im.message.receive_v1');
+ expect(body.event).toEqual(eventData);
+ });
+ });
+
+ describe('close', () => {
+ it('should call wsClient.close()', async () => {
+ const conn = createConnection();
+ await conn.start();
+
+ conn.close();
+ expect(mockClose).toHaveBeenCalledWith({ force: true });
+ });
+
+ it('should be safe to call close() without starting', () => {
+ const conn = createConnection();
+ conn.close(); // Should not throw
+ });
+ });
+});
diff --git a/src/server/services/bot/platforms/feishu/gateway.ts b/src/server/services/bot/platforms/feishu/gateway.ts
new file mode 100644
index 00000000000..2a8b6a79d0d
--- /dev/null
+++ b/src/server/services/bot/platforms/feishu/gateway.ts
@@ -0,0 +1,111 @@
+import debug from 'debug';
+
+const log = debug('bot-platform:feishu:gateway');
+
+export interface FeishuWSOptions {
+ appId: string;
+ appSecret: string;
+ /** 'feishu' or 'lark' — determines the API domain */
+ domain: 'feishu' | 'lark';
+ /**
+ * Verification token configured by the user. When provided, it is injected
+ * into the forwarded webhook payload's `header.token` so the downstream
+ * webhook handler's token check passes.
+ */
+ verificationToken?: string;
+ /** URL to forward events to (POST) */
+ webhookUrl: string;
+}
+
+/**
+ * Wraps the official Lark SDK's WSClient to manage a persistent WebSocket
+ * connection for Feishu/Lark bots.
+ *
+ * Events received via WebSocket are forwarded to the webhook URL as HTTP POSTs,
+ * preserving compatibility with the existing handleWebhook() pipeline.
+ */
+export class FeishuWSConnection {
+ private readonly options: FeishuWSOptions;
+ private wsClient: any = null;
+
+ constructor(options: FeishuWSOptions) {
+ this.options = options;
+ }
+
+ /**
+ * Start the WebSocket connection using the Lark SDK's WSClient.
+ * The SDK handles connect, ping, and reconnect internally.
+ */
+ async start(): Promise<void> {
+ const lark = await import('@larksuiteoapi/node-sdk');
+
+ const eventDispatcher = new lark.EventDispatcher({});
+
+ // Register handler for incoming messages
+ eventDispatcher.register({
+ 'im.message.receive_v1': async (data: any) => {
+ log('Received im.message.receive_v1 event');
+ await this.forwardEvent('im.message.receive_v1', data);
+ },
+ });
+
+ const domain = this.options.domain === 'lark' ? lark.Domain.Lark : lark.Domain.Feishu;
+
+ this.wsClient = new lark.WSClient({
+ appId: this.options.appId,
+ appSecret: this.options.appSecret,
+ domain,
+ loggerLevel: lark.LoggerLevel.info,
+ });
+
+ await this.wsClient.start({ eventDispatcher });
+ log('WSClient started (domain=%s, appId=%s)', this.options.domain, this.options.appId);
+ }
+
+ /**
+ * Close the WebSocket connection.
+ */
+ close(): void {
+ if (this.wsClient) {
+ this.wsClient.close({ force: true });
+ this.wsClient = null;
+ log('WSClient closed');
+ }
+ }
+
+ /**
+ * Forward an event to the webhook URL.
+ * The webhook handler expects the Lark event payload wrapped in the standard format.
+ *
+ * Note: events received via WebSocket are pre-authenticated by the SDK, but the
+ * downstream webhook handler still validates `header.token` against the user's
+ * configured `verificationToken`. We inject the configured token into the payload
+ * so the check passes.
+ */
+ private async forwardEvent(eventType: string, data: any): Promise<void> {
+ // Construct a webhook-compatible payload matching what handleWebhook() expects
+ const header: Record<string, string> = {
+ event_type: eventType,
+ };
+ if (this.options.verificationToken) {
+ header.token = this.options.verificationToken;
+ }
+
+ const webhookPayload = {
+ event: data,
+ header,
+ schema: '2.0',
+ };
+
+ try {
+ await fetch(this.options.webhookUrl, {
+ body: JSON.stringify(webhookPayload),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch (err) {
+ log('Failed to forward event %s to webhook: %O', eventType, err);
+ }
+ }
+}
diff --git a/src/server/services/bot/platforms/index.ts b/src/server/services/bot/platforms/index.ts
index bed6b9bf8b5..7564b7fbac5 100644
--- a/src/server/services/bot/platforms/index.ts
+++ b/src/server/services/bot/platforms/index.ts
@@ -14,6 +14,7 @@ export type {
BotPlatformRedisClient,
BotPlatformRuntimeContext,
BotProviderConfig,
+ ConnectionMode,
FieldSchema,
PlatformClient,
PlatformDefinition,
@@ -30,6 +31,7 @@ export {
formatDuration,
formatTokens,
formatUsageStats,
+ getEffectiveConnectionMode,
mergeWithDefaults,
parseRuntimeKey,
} from './utils';
diff --git a/src/server/services/bot/platforms/qq/client.test.ts b/src/server/services/bot/platforms/qq/client.test.ts
new file mode 100644
index 00000000000..b7b46972477
--- /dev/null
+++ b/src/server/services/bot/platforms/qq/client.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@lobechat/chat-adapter-qq', () => ({
+ createQQAdapter: vi.fn(),
+ QQApiClient: vi.fn().mockImplementation(() => ({})),
+}));
+
+vi.mock('@/server/services/gateway/runtimeStatus', () => ({
+ BOT_RUNTIME_STATUSES: {
+ connected: 'connected',
+ disconnected: 'disconnected',
+ failed: 'failed',
+ starting: 'starting',
+ },
+ getRuntimeStatusErrorMessage: (e: any) => String(e?.message ?? e),
+ updateBotRuntimeStatus: vi.fn().mockResolvedValue(undefined),
+}));
+
+const { QQClientFactory } = await import('./client');
+
+describe('QQGatewayClient.extractFiles', () => {
+ // QQ is the simplest case among all platforms — public CDN URLs survive
+ // serialization unchanged. extractFiles just walks `att.url` and forwards
+ // them to ingestAttachment, which fetch()es with no special handling.
+
+ const createClient = (connectionMode: 'webhook' | 'websocket' = 'websocket') =>
+ new QQClientFactory().createClient(
+ {
+ applicationId: 'qq-app',
+ credentials: { appSecret: 'sec' },
+ platform: 'qq',
+ settings: { connectionMode },
+ },
+ { appUrl: 'https://example.com' },
+ );
+
+ /** Build a fake Chat SDK Message with QQ attachments. */
+ const makeMessage = (attachments: Array<Record<string, unknown>>, id = '12345') =>
+ ({
+ attachments,
+ id,
+ raw: {},
+ text: '',
+ }) as any;
+
+ it('returns undefined when no attachments are present', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(makeMessage([]));
+ expect(result).toBeUndefined();
+ });
+
+ it('forwards image attachments by URL', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'image/jpeg',
+ name: 'photo.jpg',
+ size: 12_345,
+ type: 'image',
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=abc',
+ },
+ ]),
+ );
+
+ expect(result).toEqual([
+ {
+ mimeType: 'image/jpeg',
+ name: 'photo.jpg',
+ size: 12_345,
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=abc',
+ },
+ ]);
+ });
+
+ it('forwards video attachments by URL', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'video/mp4',
+ name: 'clip.mp4',
+ size: 100_000,
+ type: 'video',
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=def',
+ },
+ ]),
+ );
+
+ expect(result).toEqual([
+ {
+ mimeType: 'video/mp4',
+ name: 'clip.mp4',
+ size: 100_000,
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=def',
+ },
+ ]);
+ });
+
+ it('skips attachments missing url', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ { mimeType: 'image/jpeg', name: 'orphan.jpg', type: 'image' },
+ {
+ mimeType: 'image/jpeg',
+ name: 'good.jpg',
+ type: 'image',
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=good',
+ },
+ ]),
+ );
+
+ expect(result).toEqual([
+ {
+ mimeType: 'image/jpeg',
+ name: 'good.jpg',
+ size: undefined,
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=good',
+ },
+ ]);
+ });
+
+ it('handles multiple attachments in order', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'image/jpeg',
+ name: 'a.jpg',
+ type: 'image',
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=a',
+ },
+ {
+ mimeType: 'application/pdf',
+ name: 'b.pdf',
+ type: 'file',
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=b',
+ },
+ ]),
+ );
+
+ expect(result).toHaveLength(2);
+ expect(result?.[0]?.name).toBe('a.jpg');
+ expect(result?.[1]?.name).toBe('b.pdf');
+ });
+
+ it('returns undefined when all attachments lack urls', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([{ mimeType: 'image/jpeg', name: 'no-url.jpg', type: 'image' }]),
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('works the same for webhook connection mode', async () => {
+ const client = createClient('webhook');
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'image/jpeg',
+ name: 'a.jpg',
+ type: 'image',
+ url: 'https://multimedia.nt.qq.com.cn/download?fileid=a',
+ },
+ ]),
+ );
+ expect(result).toHaveLength(1);
+ });
+});
diff --git a/src/server/services/bot/platforms/qq/client.ts b/src/server/services/bot/platforms/qq/client.ts
index 91a2b569d23..916dcebe54c 100644
--- a/src/server/services/bot/platforms/qq/client.ts
+++ b/src/server/services/bot/platforms/qq/client.ts
@@ -1,6 +1,9 @@
+import type { QQAdapter } from '@lobechat/chat-adapter-qq';
import { createQQAdapter, QQApiClient } from '@lobechat/chat-adapter-qq';
+import type { Chat as ChatBot, Message } from 'chat';
import debug from 'debug';
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
import {
BOT_RUNTIME_STATUSES,
getRuntimeStatusErrorMessage,
@@ -21,6 +24,14 @@ import { formatUsageStats } from '../utils';
const log = debug('bot-platform:qq:bot');
+const CONNECTED_STATUS_TTL_BUFFER_MS = 60 * 1000;
+const DEFAULT_DURATION_MS = 8 * 60 * 60 * 1000; // 8 hours
+
+export interface GatewayListenerOptions {
+ durationMs?: number;
+ waitUntil?: (task: Promise<any>) => void;
+}
+
function extractChatId(platformThreadId: string): string {
return platformThreadId.split(':')[2];
}
@@ -58,6 +69,234 @@ async function sendQQMessage(
}
}
+/**
+ * Resolve attachments on an inbound QQ message into `AttachmentSource[]`.
+ *
+ * QQ is the simplest case: attachments come with public CDN URLs (`https://multimedia.nt.qq.com.cn/...`)
+ * that require no auth and survive `Message.toJSON` unchanged. We just walk
+ * the surviving attachment metadata and forward URLs to `ingestAttachment`,
+ * which `fetch()`es them with no special handling.
+ *
+ * No `referenced_message` quirk like Discord, no auth like Slack, no
+ * file_id download like Telegram/WeChat/Feishu — just URLs.
+ */
+function qqExtractFiles(message: Message): AttachmentSource[] | undefined {
+ const attachments = (message as any).attachments as
+ | Array<{
+ height?: number;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ type?: string;
+ url?: string;
+ width?: number;
+ }>
+ | undefined;
+ if (!attachments?.length) return undefined;
+
+ log('extractFiles: msgId=%s, attachments=%d', (message as any).id, attachments.length);
+
+ const results: AttachmentSource[] = [];
+ for (const att of attachments) {
+ if (!att.url) continue;
+ results.push({
+ mimeType: att.mimeType,
+ name: att.name,
+ size: att.size,
+ url: att.url,
+ });
+ }
+
+ return results.length > 0 ? results : undefined;
+}
+
+class QQGatewayClient implements PlatformClient {
+ readonly id = 'qq';
+ readonly applicationId: string;
+
+ private abort = new AbortController();
+ private bot: ChatBot<any> | null = null;
+ private config: BotProviderConfig;
+ private context: BotPlatformRuntimeContext;
+ private refreshTimer: ReturnType<typeof setTimeout> | null = null;
+ private stopped = false;
+
+ constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {
+ this.config = config;
+ this.context = context;
+ this.applicationId = config.applicationId;
+ }
+
+ // --- Lifecycle ---
+
+ async start(options?: GatewayListenerOptions): Promise<void> {
+ log('Starting QQBot appId=%s', this.applicationId);
+
+ this.stopped = false;
+ this.abort = new AbortController();
+ const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;
+ const runtimeStatusTtlMs = durationMs + CONNECTED_STATUS_TTL_BUFFER_MS;
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.starting,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+
+ try {
+ if (this.bot) {
+ await this.bot.shutdown().catch(() => {});
+ this.bot = null;
+ }
+
+ const adapter = createQQAdapter({
+ appId: this.config.applicationId,
+ clientSecret: this.config.credentials.appSecret,
+ });
+
+ const { Chat, ConsoleLogger } = await import('chat');
+
+ const chatConfig: any = {
+ adapters: { qq: adapter },
+ userName: `lobehub-gateway-${this.applicationId}`,
+ };
+
+ if (this.context.redisClient) {
+ const { createIoRedisState } = await import('@chat-adapter/state-ioredis');
+ chatConfig.state = createIoRedisState({
+ client: this.context.redisClient as any,
+ logger: new ConsoleLogger(),
+ });
+ }
+
+ const bot = new Chat(chatConfig);
+ this.bot = bot;
+ await bot.initialize();
+
+ const qqAdapter = (bot as any).adapters.get('qq') as QQAdapter;
+ const waitUntil = options?.waitUntil ?? ((task: Promise<any>) => task.catch(() => {}));
+
+ const webhookUrl = `${(this.context.appUrl || '').trim()}/api/agent/webhooks/qq/${this.applicationId}`;
+
+ await qqAdapter.startGatewayListener(
+ { waitUntil },
+ durationMs,
+ this.abort.signal,
+ webhookUrl,
+ );
+
+ if (!options) {
+ this.refreshTimer = setTimeout(() => {
+ if (this.abort.signal.aborted || this.stopped) return;
+
+ log(
+ 'QQBot appId=%s duration elapsed (%dh), refreshing...',
+ this.applicationId,
+ durationMs / 3_600_000,
+ );
+ this.abort.abort();
+ this.start().catch((err) => {
+ log('Failed to refresh QQBot appId=%s: %O', this.applicationId, err);
+ });
+ }, durationMs);
+ }
+
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.connected,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+
+ log('QQBot appId=%s started, webhookUrl=%s', this.applicationId, webhookUrl);
+ } catch (error) {
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ errorMessage: getRuntimeStatusErrorMessage(error),
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.failed,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+ throw error;
+ }
+ }
+
+ async stop(): Promise<void> {
+ log('Stopping QQBot appId=%s', this.applicationId);
+ this.stopped = true;
+ if (this.refreshTimer) {
+ clearTimeout(this.refreshTimer);
+ this.refreshTimer = null;
+ }
+ this.abort.abort();
+ if (this.bot) {
+ await this.bot.shutdown().catch(() => {});
+ this.bot = null;
+ }
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.disconnected,
+ },
+ { redisClient: this.context.redisClient as any },
+ );
+ }
+
+ // --- Runtime Operations ---
+
+ createAdapter(): Record<string, any> {
+ return {
+ qq: createQQAdapter({
+ appId: this.config.applicationId,
+ clientSecret: this.config.credentials.appSecret,
+ }),
+ };
+ }
+
+ getMessenger(platformThreadId: string): PlatformMessenger {
+ const api = new QQApiClient(this.config.applicationId, this.config.credentials.appSecret);
+ const targetId = extractChatId(platformThreadId);
+ const threadType = extractThreadType(platformThreadId);
+ return {
+ createMessage: (content) => sendQQMessage(api, threadType, targetId, content),
+ editMessage: (_messageId, content) =>
+ // QQ does not support editing — send a new message as fallback
+ sendQQMessage(api, threadType, targetId, content),
+ // QQ Bot API doesn't support reactions or typing
+ removeReaction: () => Promise.resolve(),
+ triggerTyping: () => Promise.resolve(),
+ };
+ }
+
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ return qqExtractFiles(message);
+ }
+
+ extractChatId(platformThreadId: string): string {
+ return extractChatId(platformThreadId);
+ }
+
+ formatMarkdown(markdown: string): string {
+ return stripMarkdown(markdown);
+ }
+
+ formatReply(body: string, stats?: UsageStats): string {
+ if (!stats || !this.config.settings?.showUsageStats) return body;
+ return `${body}\n\n${formatUsageStats(stats)}`;
+ }
+
+ parseMessageId(compositeId: string): string {
+ return compositeId;
+ }
+}
+
class QQWebhookClient implements PlatformClient {
readonly id = 'qq';
readonly applicationId: string;
@@ -72,7 +311,7 @@ class QQWebhookClient implements PlatformClient {
// --- Lifecycle ---
async start(): Promise<void> {
- log('Starting QQBot appId=%s', this.applicationId);
+ log('Starting QQBot (webhook) appId=%s', this.applicationId);
await updateBotRuntimeStatus({
applicationId: this.applicationId,
platform: this.id,
@@ -90,7 +329,7 @@ class QQWebhookClient implements PlatformClient {
status: BOT_RUNTIME_STATUSES.connected,
});
- log('QQBot appId=%s credentials verified', this.applicationId);
+ log('QQBot (webhook) appId=%s credentials verified', this.applicationId);
} catch (error) {
await updateBotRuntimeStatus({
applicationId: this.applicationId,
@@ -103,8 +342,7 @@ class QQWebhookClient implements PlatformClient {
}
async stop(): Promise<void> {
- log('Stopping QQBot appId=%s', this.applicationId);
- // No cleanup needed — webhook is configured in QQ Open Platform
+ log('Stopping QQBot (webhook) appId=%s', this.applicationId);
await updateBotRuntimeStatus({
applicationId: this.applicationId,
platform: this.id,
@@ -129,15 +367,16 @@ class QQWebhookClient implements PlatformClient {
const threadType = extractThreadType(platformThreadId);
return {
createMessage: (content) => sendQQMessage(api, threadType, targetId, content),
- editMessage: (_messageId, content) =>
- // QQ does not support editing — send a new message as fallback
- sendQQMessage(api, threadType, targetId, content),
- // QQ Bot API doesn't support reactions or typing
+ editMessage: (_messageId, content) => sendQQMessage(api, threadType, targetId, content),
removeReaction: () => Promise.resolve(),
triggerTyping: () => Promise.resolve(),
};
}
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ return qqExtractFiles(message);
+ }
+
extractChatId(platformThreadId: string): string {
return extractChatId(platformThreadId);
}
@@ -158,7 +397,15 @@ class QQWebhookClient implements PlatformClient {
export class QQClientFactory extends ClientFactory {
createClient(config: BotProviderConfig, context: BotPlatformRuntimeContext): PlatformClient {
- return new QQWebhookClient(config, context);
+ // Fall back to 'webhook' to preserve behavior for legacy provider rows
+ // that pre-date the connectionMode field (QQ shipped as webhook-only
+ // before websocket support was added). New providers always go through
+ // the form which seeds connectionMode from the schema default.
+ const mode = (config.settings?.connectionMode as string) || 'webhook';
+ if (mode === 'webhook') {
+ return new QQWebhookClient(config, context);
+ }
+ return new QQGatewayClient(config, context);
}
async validateCredentials(
diff --git a/src/server/services/bot/platforms/qq/const.ts b/src/server/services/bot/platforms/qq/const.ts
new file mode 100644
index 00000000000..fed338459ad
--- /dev/null
+++ b/src/server/services/bot/platforms/qq/const.ts
@@ -0,0 +1 @@
+export const DEFAULT_QQ_CONNECTION_MODE = 'websocket';
diff --git a/src/server/services/bot/platforms/qq/definition.ts b/src/server/services/bot/platforms/qq/definition.ts
index 5db9dadd2f2..a6e678f43a5 100644
--- a/src/server/services/bot/platforms/qq/definition.ts
+++ b/src/server/services/bot/platforms/qq/definition.ts
@@ -1,17 +1,18 @@
import type { PlatformDefinition } from '../types';
import { QQClientFactory } from './client';
+import { DEFAULT_QQ_CONNECTION_MODE } from './const';
import { schema } from './schema';
export const qq: PlatformDefinition = {
id: 'qq',
name: 'QQ',
+ connectionMode: DEFAULT_QQ_CONNECTION_MODE,
description: 'Connect a QQ bot',
documentation: {
portalUrl: 'https://q.qq.com/',
setupGuideUrl: 'https://lobehub.com/docs/usage/channels/qq',
},
schema,
- showWebhookUrl: true,
supportsMarkdown: false,
supportsMessageEdit: false,
clientFactory: new QQClientFactory(),
diff --git a/src/server/services/bot/platforms/qq/schema.ts b/src/server/services/bot/platforms/qq/schema.ts
index 1bbc305a0a5..aa55a9b315c 100644
--- a/src/server/services/bot/platforms/qq/schema.ts
+++ b/src/server/services/bot/platforms/qq/schema.ts
@@ -2,6 +2,7 @@ import { MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';
import { displayToolCallsField, userIdField } from '../const';
import type { FieldSchema } from '../types';
+import { DEFAULT_QQ_CONNECTION_MODE } from './const';
export const schema: FieldSchema[] = [
{
@@ -29,6 +30,15 @@ export const schema: FieldSchema[] = [
key: 'settings',
label: 'channel.settings',
properties: [
+ {
+ key: 'connectionMode',
+ default: DEFAULT_QQ_CONNECTION_MODE,
+ description: 'channel.connectionModeHint',
+ enum: ['websocket', 'webhook'],
+ enumLabels: ['channel.connectionModeWebSocket', 'channel.connectionModeWebhook'],
+ label: 'channel.connectionMode',
+ type: 'string',
+ },
{
key: 'charLimit',
default: 2000,
@@ -40,7 +50,7 @@ export const schema: FieldSchema[] = [
},
{
key: 'concurrency',
- default: 'debounce',
+ default: 'queue',
description: 'channel.concurrencyHint',
enum: ['queue', 'debounce'],
enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
diff --git a/src/server/services/bot/platforms/slack/api.ts b/src/server/services/bot/platforms/slack/api.ts
index 8c44105eb6f..22097fdf985 100644
--- a/src/server/services/bot/platforms/slack/api.ts
+++ b/src/server/services/bot/platforms/slack/api.ts
@@ -1,9 +1,29 @@
+import { defaultEmojiResolver } from 'chat';
import debug from 'debug';
const log = debug('bot-platform:slack:client');
export const SLACK_API_BASE = 'https://slack.com/api';
+/**
+ * Normalize an emoji input to the shortcode that Slack's reactions API
+ * expects (e.g. `eyes`, not the unicode `👀` and not `:eyes:`).
+ *
+ * Callers may pass any of:
+ * - A unicode emoji like `👀` (e.g. BotCallbackService.removeEyesReaction)
+ * - A normalized name like `thumbs_up` (which maps to Slack's `+1`)
+ * - A Slack shortcode like `eyes` (already correct, idempotent pass-through)
+ *
+ * `defaultEmojiResolver.fromGChat` returns the EmojiValue for the unicode
+ * (or a raw EmojiValue with the input as name if no mapping), and `toSlack`
+ * then converts to the Slack format (or returns the input unchanged for
+ * unknown names — keeping custom Slack emoji like `:meow_party:` working).
+ */
+function normalizeSlackEmoji(input: string): string {
+ const stripped = input.replaceAll(':', '');
+ return defaultEmojiResolver.toSlack(defaultEmojiResolver.fromGChat(stripped));
+}
+
/**
* Lightweight Slack Web API client for outbound messaging operations
* used by callback and extension flows outside the Chat SDK adapter surface.
@@ -41,8 +61,21 @@ export class SlackApi {
}
async removeReaction(channel: string, timestamp: string, name: string): Promise<void> {
- log('removeReaction: channel=%s, ts=%s, name=%s', channel, timestamp, name);
- await this.call('reactions.remove', { channel, name, timestamp });
+ const slackName = normalizeSlackEmoji(name);
+ log('removeReaction: channel=%s, ts=%s, name=%s', channel, timestamp, slackName);
+ try {
+ await this.call('reactions.remove', { channel, name: slackName, timestamp });
+ } catch (error) {
+ // `no_reaction` is benign: the reaction may have been removed already
+ // (concurrent callback, user removed it manually) or never added in
+ // the first place (e.g. an earlier reactions.add failed). Swallow it
+ // so the callback path doesn't surface a misleading error.
+ if (error instanceof Error && error.message.includes('no_reaction')) {
+ log('removeReaction: no_reaction (already gone) ts=%s, name=%s', timestamp, slackName);
+ return;
+ }
+ throw error;
+ }
}
// ==================== Message Operations ====================
@@ -82,8 +115,9 @@ export class SlackApi {
// ==================== Reactions ====================
async addReaction(channel: string, timestamp: string, name: string): Promise<void> {
- log('addReaction: channel=%s, ts=%s, name=%s', channel, timestamp, name);
- await this.call('reactions.add', { channel, name, timestamp });
+ const slackName = normalizeSlackEmoji(name);
+ log('addReaction: channel=%s, ts=%s, name=%s', channel, timestamp, slackName);
+ await this.call('reactions.add', { channel, name: slackName, timestamp });
}
async getReactions(
@@ -151,6 +185,44 @@ export class SlackApi {
return { messages: data.messages ?? [] };
}
+ // ==================== File Download ====================
+
+ /**
+ * Download a Slack file by its `url_private` URL using the bot token.
+ *
+ * Slack's file URLs (`https://files.slack.com/files-pri/...`) require Bearer
+ * auth — fetching them without the bot token returns an HTML login page
+ * (which we explicitly detect and report). The chat-adapter-slack normally
+ * encloses the bot token in a `fetchData` closure on each Attachment, but
+ * the closure is stripped by `Message.toJSON` when messages round-trip
+ * through the chat-sdk debounce/queue. This method is the post-Redis
+ * recovery path used by `SlackWebhookClient.extractFiles` and
+ * `SlackSocketModeClient.extractFiles`.
+ */
+ async downloadFile(url: string): Promise<Buffer> {
+ log('downloadFile: url=%s', url);
+ const response = await fetch(url, {
+ headers: { Authorization: `Bearer ${this.botToken}` },
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to download Slack file: ${response.status} ${response.statusText}`);
+ }
+
+ // Slack returns an HTML login page (not a 4xx) when auth fails or the
+ // bot lacks `files:read`. Detect that explicitly so the error is
+ // actionable instead of getting a corrupted "buffer" of HTML bytes.
+ const contentType = response.headers.get('content-type') ?? '';
+ if (contentType.includes('text/html')) {
+ throw new Error(
+ `Failed to download file from Slack: received HTML login page instead of file data. ` +
+ `Ensure your Slack app has the "files:read" OAuth scope. URL: ${url}`,
+ );
+ }
+
+ return Buffer.from(await response.arrayBuffer());
+ }
+
// ------------------------------------------------------------------
private truncateText(text: string): string {
diff --git a/src/server/services/bot/platforms/slack/client.test.ts b/src/server/services/bot/platforms/slack/client.test.ts
new file mode 100644
index 00000000000..e9e7572e491
--- /dev/null
+++ b/src/server/services/bot/platforms/slack/client.test.ts
@@ -0,0 +1,253 @@
+import type { MockInstance } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SlackApi } from './api';
+
+const mockCreateSlackAdapter = vi.hoisted(() => vi.fn());
+
+vi.mock('@chat-adapter/slack', () => ({
+ createSlackAdapter: mockCreateSlackAdapter,
+}));
+
+vi.mock('@/server/services/gateway/runtimeStatus', () => ({
+ BOT_RUNTIME_STATUSES: {
+ connected: 'connected',
+ disconnected: 'disconnected',
+ failed: 'failed',
+ starting: 'starting',
+ },
+ getRuntimeStatusErrorMessage: (e: any) => String(e?.message ?? e),
+ updateBotRuntimeStatus: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('./gateway', () => ({
+ SlackSocketModeConnection: vi.fn().mockImplementation(() => ({
+ close: vi.fn(),
+ connect: vi.fn().mockResolvedValue(undefined),
+ })),
+}));
+
+const { SlackClientFactory } = await import('./client');
+
+describe('SlackWebhookClient.extractFiles', () => {
+ // Verifies the post-Redis re-download path: when Slack messages
+ // round-trip through the chat-sdk debounce/queue, `Message.toJSON`
+ // strips the `att.fetchData` closure that the chat-adapter-slack uses
+ // to authenticate against `url_private`. The URL ITSELF survives
+ // serialization (it's in the toJSON allowlist), so we can re-fetch by
+ // calling `SlackApi.downloadFile(att.url)` with the bot token.
+
+ let downloadFileSpy: MockInstance<SlackApi['downloadFile']>;
+
+ const createClient = () =>
+ new SlackClientFactory().createClient(
+ {
+ applicationId: 'A0AR7CK6PU4',
+ credentials: {
+ appToken: 'xapp-test',
+ botToken: 'xoxb-test',
+ signingSecret: 'secret',
+ },
+ platform: 'slack',
+ // No connectionMode → defaults to webhook
+ settings: {},
+ },
+ { appUrl: 'https://example.com' },
+ );
+
+ /** Build a fake Chat SDK Message with Slack attachments. */
+ const makeMessage = (attachments: Array<Record<string, unknown>>, id = '1234567890.123456') =>
+ ({
+ attachments,
+ id,
+ raw: { event: { files: [] } },
+ text: '',
+ }) as any;
+
+ beforeEach(() => {
+ downloadFileSpy = vi.spyOn(SlackApi.prototype, 'downloadFile') as MockInstance<
+ SlackApi['downloadFile']
+ >;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('returns undefined when no attachments are present', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(makeMessage([]));
+ expect(downloadFileSpy).not.toHaveBeenCalled();
+ expect(result).toBeUndefined();
+ });
+
+ it('downloads an image attachment via SlackApi.downloadFile(url_private)', async () => {
+ // Reproduces the bug: post-Redis state has `url` (auth-required) and
+ // mimeType/name/size, but `fetchData` is gone. We use the URL directly.
+ const buffer = Buffer.from('feedback-mp4-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ height: 720,
+ mimeType: 'image/png',
+ name: 'screenshot.png',
+ size: 12_345,
+ type: 'image',
+ url: 'https://files.slack.com/files-pri/T0AMPF07X45-F0AR5E3E007/screenshot.png',
+ width: 1280,
+ },
+ ]),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledTimes(1);
+ expect(downloadFileSpy).toHaveBeenCalledWith(
+ 'https://files.slack.com/files-pri/T0AMPF07X45-F0AR5E3E007/screenshot.png',
+ );
+ expect(result).toEqual([
+ {
+ buffer,
+ mimeType: 'image/png',
+ name: 'screenshot.png',
+ size: 12_345,
+ },
+ ]);
+ });
+
+ it('downloads a video attachment (mp4)', async () => {
+ const buffer = Buffer.from('mp4-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'video/mp4',
+ name: 'feedback.mp4',
+ size: 1_507_745,
+ type: 'video',
+ url: 'https://files.slack.com/files-pri/T/F/feedback.mp4',
+ },
+ ]),
+ );
+
+ expect(result).toEqual([
+ { buffer, mimeType: 'video/mp4', name: 'feedback.mp4', size: 1_507_745 },
+ ]);
+ });
+
+ it('falls back to buffer.length when att.size is undefined', async () => {
+ const buffer = Buffer.from('payload');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'application/pdf',
+ name: 'doc.pdf',
+ type: 'file',
+ url: 'https://files.slack.com/files-pri/T/F/doc.pdf',
+ },
+ ]),
+ );
+
+ expect(result?.[0]?.size).toBe(buffer.length);
+ });
+
+ it('skips attachments with no url and continues with the rest', async () => {
+ const buffer = Buffer.from('good');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ // Missing url — should be skipped without calling downloadFile
+ { mimeType: 'image/png', name: 'orphan.png', type: 'image' },
+ {
+ mimeType: 'image/png',
+ name: 'good.png',
+ size: 100,
+ type: 'image',
+ url: 'https://files.slack.com/files-pri/T/F/good.png',
+ },
+ ]),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledTimes(1);
+ expect(downloadFileSpy).toHaveBeenCalledWith('https://files.slack.com/files-pri/T/F/good.png');
+ expect(result).toEqual([{ buffer, mimeType: 'image/png', name: 'good.png', size: 100 }]);
+ });
+
+ it('skips a single failing download without dropping the others', async () => {
+ const goodBuffer = Buffer.from('good');
+ downloadFileSpy
+ .mockRejectedValueOnce(new Error('files:read scope missing'))
+ .mockResolvedValueOnce(goodBuffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'image/png',
+ name: 'bad.png',
+ type: 'image',
+ url: 'https://files.slack.com/files-pri/T/F/bad.png',
+ },
+ {
+ mimeType: 'image/png',
+ name: 'good.png',
+ size: 50,
+ type: 'image',
+ url: 'https://files.slack.com/files-pri/T/F/good.png',
+ },
+ ]),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledTimes(2);
+ expect(result).toEqual([
+ { buffer: goodBuffer, mimeType: 'image/png', name: 'good.png', size: 50 },
+ ]);
+ });
+
+ it('returns undefined when all downloads fail', async () => {
+ downloadFileSpy.mockRejectedValue(new Error('network down'));
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage([
+ {
+ mimeType: 'image/png',
+ name: 'a.png',
+ type: 'image',
+ url: 'https://files.slack.com/files-pri/T/F/a.png',
+ },
+ ]),
+ );
+
+ expect(result).toBeUndefined();
+ });
+
+ it('caches SlackApi across multiple extractFiles calls', async () => {
+ const buffer = Buffer.from('x');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ await client.extractFiles!(
+ makeMessage([
+ { mimeType: 'image/png', name: 'a.png', type: 'image', url: 'https://files.slack.com/a' },
+ ]),
+ );
+ await client.extractFiles!(
+ makeMessage([
+ { mimeType: 'image/png', name: 'b.png', type: 'image', url: 'https://files.slack.com/b' },
+ ]),
+ );
+
+ // Both extractFiles calls go through the lazy `_api` getter, so SlackApi
+ // is constructed at most once per SlackWebhookClient instance.
+ expect(downloadFileSpy).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/server/services/bot/platforms/slack/client.ts b/src/server/services/bot/platforms/slack/client.ts
index 42febffc080..a975539ebe4 100644
--- a/src/server/services/bot/platforms/slack/client.ts
+++ b/src/server/services/bot/platforms/slack/client.ts
@@ -1,6 +1,8 @@
import { createSlackAdapter } from '@chat-adapter/slack';
+import type { Chat as ChatBot, Message } from 'chat';
import debug from 'debug';
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
import {
BOT_RUNTIME_STATUSES,
getRuntimeStatusErrorMessage,
@@ -18,12 +20,20 @@ import {
} from '../types';
import { formatUsageStats } from '../utils';
import { SLACK_API_BASE, SlackApi } from './api';
+import { SlackSocketModeConnection } from './gateway';
import { markdownToSlackMrkdwn } from './markdownToMrkdwn';
const log = debug('bot-platform:slack:bot');
+const CONNECTED_STATUS_TTL_BUFFER_MS = 60 * 1000;
+const DEFAULT_DURATION_MS = 8 * 60 * 60 * 1000; // 8 hours
+
+export interface GatewayListenerOptions {
+ durationMs?: number;
+ waitUntil?: (task: Promise<any>) => void;
+}
+
function extractChannelId(platformThreadId: string): string {
- // Slack thread IDs from Chat SDK: "slack:<channel>:<threadTs>"
return platformThreadId.split(':')[1];
}
@@ -31,23 +41,115 @@ function extractThreadTs(platformThreadId: string): string | undefined {
return platformThreadId.split(':')[2];
}
+// ---------- Shared runtime operations mixin ----------
+
+function createMessenger(config: BotProviderConfig, platformThreadId: string): PlatformMessenger {
+ const slack = new SlackApi(config.credentials.botToken);
+ const channelId = extractChannelId(platformThreadId);
+ const threadTs = extractThreadTs(platformThreadId);
+
+ return {
+ createMessage: (content) =>
+ threadTs
+ ? slack.postMessageInThread(channelId, threadTs, content).then(() => {})
+ : slack.postMessage(channelId, content).then(() => {}),
+ editMessage: (messageId, content) => slack.updateMessage(channelId, messageId, content),
+ removeReaction: (messageId, emoji) => slack.removeReaction(channelId, messageId, emoji),
+ triggerTyping: () => Promise.resolve(),
+ };
+}
+
+/**
+ * Resolve attachments on an inbound Slack message into `AttachmentSource[]`.
+ * Shared by both webhook and socket-mode clients.
+ *
+ * Slack is the easy case among the platforms that need re-fetching: the
+ * adapter sets `att.url = file.url_private`, and `url` IS preserved by
+ * `Message.toJSON`. So we don't need to dig into `message.raw` — we can
+ * read the URL straight off each attachment after the round-trip.
+ *
+ * What we DO need is auth: `url_private` returns an HTML login page when
+ * fetched without `Authorization: Bearer <bot_token>`. The adapter normally
+ * encloses the bot token in a per-attachment `fetchData` closure, but the
+ * closure dies on `Message.toJSON`. We use the bot token from `this.config`
+ * via `SlackApi.downloadFile` instead.
+ */
+async function slackExtractFiles(
+ api: SlackApi,
+ message: Message,
+): Promise<AttachmentSource[] | undefined> {
+ const attachments = (message as any).attachments as
+ | Array<{
+ height?: number;
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ type?: string;
+ url?: string;
+ width?: number;
+ }>
+ | undefined;
+ if (!attachments?.length) return undefined;
+
+ log('extractFiles: msgId=%s, attachments=%d', (message as any).id, attachments.length);
+
+ const results: AttachmentSource[] = [];
+
+ for (const att of attachments) {
+ if (!att.url) {
+ log(
+ 'extractFiles: skipping attachment with no url_private (type=%s, name=%s)',
+ att.type,
+ att.name,
+ );
+ continue;
+ }
+ try {
+ const buffer = await api.downloadFile(att.url);
+ results.push({
+ buffer,
+ mimeType: att.mimeType,
+ name: att.name,
+ size: att.size ?? buffer.length,
+ });
+ log(
+ 'extractFiles: downloaded %s (%d bytes) for type=%s',
+ att.name ?? 'attachment',
+ buffer.length,
+ att.type,
+ );
+ } catch (error) {
+ log('extractFiles: downloadFile failed for %s: %O', att.name ?? 'attachment', error);
+ }
+ }
+
+ return results.length > 0 ? results : undefined;
+}
+
+// ---------- Webhook Client (existing behavior) ----------
+
class SlackWebhookClient implements PlatformClient {
readonly id = 'slack';
readonly applicationId: string;
private config: BotProviderConfig;
- private context: BotPlatformRuntimeContext;
+ /** Lazy-cached SlackApi — keeps no state but avoids repeated allocs. */
+ private _api?: SlackApi;
- constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {
+ constructor(config: BotProviderConfig, _context: BotPlatformRuntimeContext) {
this.config = config;
- this.context = context;
this.applicationId = config.applicationId;
}
- // --- Lifecycle ---
+ private get api(): SlackApi {
+ if (!this._api) {
+ this._api = new SlackApi(this.config.credentials.botToken);
+ }
+ return this._api;
+ }
async start(): Promise<void> {
- log('Starting SlackBot appId=%s', this.applicationId);
+ log('Starting SlackBot (webhook) appId=%s', this.applicationId);
await updateBotRuntimeStatus({
applicationId: this.applicationId,
platform: this.id,
@@ -55,14 +157,12 @@ class SlackWebhookClient implements PlatformClient {
});
try {
- // Slack uses Events API with webhook — no explicit registration needed.
- // The webhook URL is configured manually in Slack App settings.
await updateBotRuntimeStatus({
applicationId: this.applicationId,
platform: this.id,
status: BOT_RUNTIME_STATUSES.connected,
});
- log('SlackBot appId=%s started', this.applicationId);
+ log('SlackBot (webhook) appId=%s started', this.applicationId);
} catch (error) {
await updateBotRuntimeStatus({
applicationId: this.applicationId,
@@ -75,8 +175,7 @@ class SlackWebhookClient implements PlatformClient {
}
async stop(): Promise<void> {
- log('Stopping SlackBot appId=%s', this.applicationId);
- // No cleanup needed for webhook mode
+ log('Stopping SlackBot (webhook) appId=%s', this.applicationId);
await updateBotRuntimeStatus({
applicationId: this.applicationId,
platform: this.id,
@@ -84,8 +183,6 @@ class SlackWebhookClient implements PlatformClient {
});
}
- // --- Runtime Operations ---
-
createAdapter(): Record<string, any> {
return {
slack: createSlackAdapter({
@@ -96,21 +193,206 @@ class SlackWebhookClient implements PlatformClient {
}
getMessenger(platformThreadId: string): PlatformMessenger {
- const slack = new SlackApi(this.config.credentials.botToken);
- const channelId = extractChannelId(platformThreadId);
- const threadTs = extractThreadTs(platformThreadId);
+ return createMessenger(this.config, platformThreadId);
+ }
+
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ return slackExtractFiles(this.api, message);
+ }
+
+ extractChatId(platformThreadId: string): string {
+ return extractChannelId(platformThreadId);
+ }
+
+ formatMarkdown(markdown: string): string {
+ return markdownToSlackMrkdwn(markdown);
+ }
+
+ formatReply(body: string, stats?: UsageStats): string {
+ if (!stats || !this.config.settings?.showUsageStats) return body;
+ return `${body}\n\n${formatUsageStats(stats)}`;
+ }
+
+ parseMessageId(compositeId: string): string {
+ return compositeId;
+ }
+
+ sanitizeUserInput(text: string): string {
+ return text.replaceAll(/<@[A-Z\d]+>\s*/g, '').trim();
+ }
+}
+
+// ---------- Socket Mode Client (persistent) ----------
+
+class SlackSocketModeClient implements PlatformClient {
+ readonly id = 'slack';
+ readonly applicationId: string;
+
+ private abort = new AbortController();
+ private bot: ChatBot<any> | null = null;
+ private config: BotProviderConfig;
+ private context: BotPlatformRuntimeContext;
+ private gateway: SlackSocketModeConnection | null = null;
+ private refreshTimer: ReturnType<typeof setTimeout> | null = null;
+ private stopped = false;
+ /** Lazy-cached SlackApi — keeps no state but avoids repeated allocs. */
+ private _api?: SlackApi;
+
+ constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {
+ this.config = config;
+ this.context = context;
+ this.applicationId = config.applicationId;
+ }
+
+ private get api(): SlackApi {
+ if (!this._api) {
+ this._api = new SlackApi(this.config.credentials.botToken);
+ }
+ return this._api;
+ }
+
+ async start(options?: GatewayListenerOptions): Promise<void> {
+ log('Starting SlackBot (socket mode) appId=%s', this.applicationId);
+
+ this.stopped = false;
+ this.abort = new AbortController();
+ const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;
+ const runtimeStatusTtlMs = durationMs + CONNECTED_STATUS_TTL_BUFFER_MS;
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.starting,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+
+ try {
+ if (this.bot) {
+ await this.bot.shutdown().catch(() => {});
+ this.bot = null;
+ }
+
+ const adapter = createSlackAdapter({
+ botToken: this.config.credentials.botToken,
+ signingSecret: this.config.credentials.signingSecret,
+ });
+
+ const { Chat, ConsoleLogger } = await import('chat');
+
+ const chatConfig: any = {
+ adapters: { slack: adapter },
+ userName: `lobehub-gateway-${this.applicationId}`,
+ };
+
+ if (this.context.redisClient) {
+ const { createIoRedisState } = await import('@chat-adapter/state-ioredis');
+ chatConfig.state = createIoRedisState({
+ client: this.context.redisClient as any,
+ logger: new ConsoleLogger(),
+ });
+ }
+
+ const bot = new Chat(chatConfig);
+ this.bot = bot;
+ await bot.initialize();
+
+ const webhookUrl = `${(this.context.appUrl || '').trim()}/api/agent/webhooks/slack/${this.applicationId}`;
+
+ this.gateway = new SlackSocketModeConnection({
+ abortSignal: this.abort.signal,
+ appToken: this.config.credentials.appToken,
+ durationMs,
+ signingSecret: this.config.credentials.signingSecret,
+ webhookUrl,
+ });
+
+ const waitUntil = options?.waitUntil ?? ((task: Promise<any>) => task.catch(() => {}));
+ const gatewayTask = this.gateway.connect();
+ waitUntil(gatewayTask);
+ await gatewayTask;
+
+ if (!options) {
+ this.refreshTimer = setTimeout(() => {
+ if (this.abort.signal.aborted || this.stopped) return;
+
+ log(
+ 'SlackBot appId=%s duration elapsed (%dh), refreshing...',
+ this.applicationId,
+ durationMs / 3_600_000,
+ );
+ this.abort.abort();
+ this.start().catch((err) => {
+ log('Failed to refresh SlackBot appId=%s: %O', this.applicationId, err);
+ });
+ }, durationMs);
+ }
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.connected,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+
+ log('SlackBot (socket mode) appId=%s started, webhookUrl=%s', this.applicationId, webhookUrl);
+ } catch (error) {
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ errorMessage: getRuntimeStatusErrorMessage(error),
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.failed,
+ },
+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },
+ );
+ throw error;
+ }
+ }
+
+ async stop(): Promise<void> {
+ log('Stopping SlackBot (socket mode) appId=%s', this.applicationId);
+ this.stopped = true;
+ if (this.refreshTimer) {
+ clearTimeout(this.refreshTimer);
+ this.refreshTimer = null;
+ }
+ this.abort.abort();
+ this.gateway?.close();
+ this.gateway = null;
+ if (this.bot) {
+ await this.bot.shutdown().catch(() => {});
+ this.bot = null;
+ }
+ await updateBotRuntimeStatus(
+ {
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.disconnected,
+ },
+ { redisClient: this.context.redisClient as any },
+ );
+ }
+
+ createAdapter(): Record<string, any> {
return {
- createMessage: (content) =>
- threadTs
- ? slack.postMessageInThread(channelId, threadTs, content).then(() => {})
- : slack.postMessage(channelId, content).then(() => {}),
- editMessage: (messageId, content) => slack.updateMessage(channelId, messageId, content),
- removeReaction: (messageId, emoji) => slack.removeReaction(channelId, messageId, emoji),
- triggerTyping: () => Promise.resolve(), // Slack has no typing indicator API for bots
+ slack: createSlackAdapter({
+ botToken: this.config.credentials.botToken,
+ signingSecret: this.config.credentials.signingSecret,
+ }),
};
}
+ getMessenger(platformThreadId: string): PlatformMessenger {
+ return createMessenger(this.config, platformThreadId);
+ }
+
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ return slackExtractFiles(this.api, message);
+ }
+
extractChatId(platformThreadId: string): string {
return extractChannelId(platformThreadId);
}
@@ -129,13 +411,21 @@ class SlackWebhookClient implements PlatformClient {
}
sanitizeUserInput(text: string): string {
- // Remove bot mention artifacts like <@U12345>
return text.replaceAll(/<@[A-Z\d]+>\s*/g, '').trim();
}
}
+// ---------- Factory ----------
+
export class SlackClientFactory extends ClientFactory {
createClient(config: BotProviderConfig, context: BotPlatformRuntimeContext): PlatformClient {
+ // Fall back to 'webhook' to preserve behavior for legacy provider rows
+ // that pre-date the connectionMode field. New providers always go through
+ // the form which seeds connectionMode from the schema default.
+ const mode = (config.settings?.connectionMode as string) || 'webhook';
+ if (mode === 'websocket' && config.credentials.appToken) {
+ return new SlackSocketModeClient(config, context);
+ }
return new SlackWebhookClient(config, context);
}
@@ -163,10 +453,34 @@ export class SlackClientFactory extends ClientFactory {
const data = (await res.json()) as { ok: boolean; error?: string; bot_id?: string };
if (!data.ok) throw new Error(data.error || 'auth.test failed');
+ // Validate app token if provided
+ if (credentials.appToken) {
+ const appRes = await fetch(`${SLACK_API_BASE}/apps.connections.open`, {
+ headers: {
+ 'Authorization': `Bearer ${credentials.appToken}`,
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ method: 'POST',
+ });
+ if (!appRes.ok) throw new Error(`HTTP ${appRes.status}`);
+
+ const appData = (await appRes.json()) as { ok: boolean; error?: string };
+ if (!appData.ok) {
+ return {
+ errors: [
+ { field: 'appToken', message: `App Token validation failed: ${appData.error}` },
+ ],
+ valid: false,
+ };
+ }
+ }
+
return { valid: true };
- } catch {
+ } catch (error: any) {
return {
- errors: [{ field: 'botToken', message: 'Failed to authenticate with Slack API' }],
+ errors: [
+ { field: 'botToken', message: error.message || 'Failed to authenticate with Slack API' },
+ ],
valid: false,
};
}
diff --git a/src/server/services/bot/platforms/slack/const.ts b/src/server/services/bot/platforms/slack/const.ts
index 2d049ceec5f..46c5719d8b6 100644
--- a/src/server/services/bot/platforms/slack/const.ts
+++ b/src/server/services/bot/platforms/slack/const.ts
@@ -1,2 +1,4 @@
/** Slack API allows max 999 messages per request. */
export const MAX_SLACK_HISTORY_LIMIT = 999;
+
+export const DEFAULT_SLACK_CONNECTION_MODE = 'websocket';
diff --git a/src/server/services/bot/platforms/slack/definition.ts b/src/server/services/bot/platforms/slack/definition.ts
index 4ba7c11d030..aef0141f928 100644
--- a/src/server/services/bot/platforms/slack/definition.ts
+++ b/src/server/services/bot/platforms/slack/definition.ts
@@ -1,16 +1,17 @@
import type { PlatformDefinition } from '../types';
import { SlackClientFactory } from './client';
+import { DEFAULT_SLACK_CONNECTION_MODE } from './const';
import { schema } from './schema';
export const slack: PlatformDefinition = {
id: 'slack',
name: 'Slack',
+ connectionMode: DEFAULT_SLACK_CONNECTION_MODE,
description: 'Connect a Slack bot',
documentation: {
portalUrl: 'https://api.slack.com/apps',
setupGuideUrl: 'https://lobehub.com/docs/usage/channels/slack',
},
schema,
- showWebhookUrl: true,
clientFactory: new SlackClientFactory(),
};
diff --git a/src/server/services/bot/platforms/slack/gateway.test.ts b/src/server/services/bot/platforms/slack/gateway.test.ts
new file mode 100644
index 00000000000..09d750f0976
--- /dev/null
+++ b/src/server/services/bot/platforms/slack/gateway.test.ts
@@ -0,0 +1,341 @@
+import { createHmac } from 'node:crypto';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { SlackSocketModeOptions } from './gateway';
+import { SlackSocketModeConnection } from './gateway';
+
+// ---- Mock WebSocket ----
+
+class MockWebSocket {
+ static OPEN = 1;
+ static CLOSED = 3;
+ static instances: MockWebSocket[] = [];
+
+ readyState = MockWebSocket.OPEN;
+ url: string;
+ private listeners: Map<string, Array<(...args: any[]) => void>> = new Map();
+ sentMessages: string[] = [];
+
+ constructor(url: string) {
+ this.url = url;
+ MockWebSocket.instances.push(this);
+ setTimeout(() => this.emit('open', {}), 0);
+ }
+
+ addEventListener(event: string, fn: (...args: any[]) => void) {
+ const list = this.listeners.get(event) || [];
+ list.push(fn);
+ this.listeners.set(event, list);
+ }
+
+ removeEventListener(event: string, fn: (...args: any[]) => void) {
+ const list = this.listeners.get(event) || [];
+ this.listeners.set(
+ event,
+ list.filter((f) => f !== fn),
+ );
+ }
+
+ send(data: string) {
+ this.sentMessages.push(data);
+ }
+
+ close(code?: number, reason?: string) {
+ this.readyState = MockWebSocket.CLOSED;
+ this.emit('close', { code: code ?? 1000, reason: reason ?? '' });
+ }
+
+ emit(event: string, data: any) {
+ const list = this.listeners.get(event) || [];
+ for (const fn of list) fn(data);
+ }
+
+ simulateMessage(payload: Record<string, any>) {
+ this.emit('message', { data: JSON.stringify(payload) });
+ }
+
+ getLastSentPayload(): Record<string, any> | undefined {
+ const last = this.sentMessages.at(-1);
+ return last ? JSON.parse(last) : undefined;
+ }
+}
+
+// ---- Tests ----
+
+describe('SlackSocketModeConnection', () => {
+ beforeEach(() => {
+ MockWebSocket.instances = [];
+ vi.stubGlobal('WebSocket', MockWebSocket);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockImplementation((url: string) => {
+ if (url.includes('apps.connections.open')) {
+ return Promise.resolve(
+ new Response(
+ JSON.stringify({ ok: true, url: 'wss://mock-slack.com/link/?ticket=test' }),
+ { headers: { 'Content-Type': 'application/json' }, status: 200 },
+ ),
+ );
+ }
+ return Promise.resolve(new Response('ok', { status: 200 }));
+ }),
+ );
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ function createConnection(overrides?: Partial<SlackSocketModeOptions>) {
+ const options: SlackSocketModeOptions = {
+ appToken: 'xapp-test-token',
+ signingSecret: 'test-signing-secret',
+ webhookUrl: 'http://localhost:3000/api/agent/webhooks/slack/test_app',
+ ...overrides,
+ };
+ return new SlackSocketModeConnection(options);
+ }
+
+ async function connectAndGetWs(overrides?: Partial<SlackSocketModeOptions>) {
+ const conn = createConnection(overrides);
+ const connectPromise = conn.connect();
+ await vi.advanceTimersByTimeAsync(10);
+ const ws = MockWebSocket.instances[0];
+ return { conn, connectPromise, ws };
+ }
+
+ describe('connect', () => {
+ it('should call apps.connections.open and connect to WSS URL', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ expect(fetch).toHaveBeenCalledWith(
+ expect.stringContaining('apps.connections.open'),
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ Authorization: 'Bearer xapp-test-token',
+ }),
+ }),
+ );
+ expect(ws.url).toBe('wss://mock-slack.com/link/?ticket=test');
+
+ ws.simulateMessage({ type: 'hello', connection_info: { app_id: 'A123' } });
+ await connectPromise;
+ });
+
+ it('should resolve on hello message', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+ });
+
+ it('should resolve immediately when abortSignal is already aborted', async () => {
+ const abort = new AbortController();
+ abort.abort();
+ const conn = createConnection({ abortSignal: abort.signal });
+ await conn.connect();
+ });
+ });
+
+ describe('event handling', () => {
+ function getForwardCall() {
+ return vi
+ .mocked(fetch)
+ .mock.calls.find(
+ (call) => typeof call[0] === 'string' && call[0].includes('webhooks/slack'),
+ );
+ }
+
+ function expectSlackSignature(forwardCall: ReturnType<typeof getForwardCall>, body: string) {
+ const headers = forwardCall?.[1]?.headers as Record<string, string>;
+ const timestamp = headers['x-slack-request-timestamp'];
+ const expectedSignature =
+ 'v0=' +
+ createHmac('sha256', 'test-signing-secret').update(`v0:${timestamp}:${body}`).digest('hex');
+
+ expect(headers['x-slack-signature']).toBe(expectedSignature);
+ expect(Number(timestamp)).toBeGreaterThan(0);
+ }
+
+ it('should acknowledge events by sending envelope_id', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ ws.simulateMessage({
+ accepts_response_payload: false,
+ envelope_id: 'env_123',
+ payload: { event: { type: 'app_mention', text: 'hello' } },
+ type: 'events_api',
+ });
+
+ const ack = ws.getLastSentPayload();
+ expect(ack).toEqual({ envelope_id: 'env_123' });
+ });
+
+ it('should forward events to webhook URL', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ const eventPayload = { event: { text: 'hello', type: 'app_mention' } };
+ ws.simulateMessage({
+ envelope_id: 'env_456',
+ payload: eventPayload,
+ type: 'events_api',
+ });
+
+ await vi.advanceTimersByTimeAsync(10);
+
+ const forwardCall = getForwardCall();
+ expect(forwardCall).toBeDefined();
+
+ const body = forwardCall![1]!.body as string;
+ expect(JSON.parse(body)).toEqual(eventPayload);
+ expect(forwardCall![1]!.headers).toEqual(
+ expect.objectContaining({ 'Content-Type': 'application/json' }),
+ );
+ expectSlackSignature(forwardCall, body);
+ });
+
+ it('should forward slash commands as form-urlencoded payloads', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ ws.simulateMessage({
+ envelope_id: 'env_cmd',
+ payload: {
+ channel_id: 'C123',
+ command: '/new',
+ text: 'hello world',
+ trigger_id: 'trigger-123',
+ user_id: 'U123',
+ },
+ type: 'slash_commands',
+ });
+
+ await vi.advanceTimersByTimeAsync(10);
+
+ const forwardCall = getForwardCall();
+ expect(forwardCall).toBeDefined();
+
+ const body = forwardCall![1]!.body as string;
+ const params = new URLSearchParams(body);
+
+ expect(forwardCall![1]!.headers).toEqual(
+ expect.objectContaining({ 'Content-Type': 'application/x-www-form-urlencoded' }),
+ );
+ expect(params.get('command')).toBe('/new');
+ expect(params.get('text')).toBe('hello world');
+ expect(params.get('channel_id')).toBe('C123');
+ expectSlackSignature(forwardCall, body);
+ });
+
+ it('should forward interactive payloads as form-urlencoded payload field', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ const payload = {
+ actions: [{ action_id: 'retry', value: '1' }],
+ type: 'block_actions',
+ };
+
+ ws.simulateMessage({
+ envelope_id: 'env_int',
+ payload,
+ type: 'interactive',
+ });
+
+ await vi.advanceTimersByTimeAsync(10);
+
+ const forwardCall = getForwardCall();
+ expect(forwardCall).toBeDefined();
+
+ const body = forwardCall![1]!.body as string;
+ const params = new URLSearchParams(body);
+
+ expect(forwardCall![1]!.headers).toEqual(
+ expect.objectContaining({ 'Content-Type': 'application/x-www-form-urlencoded' }),
+ );
+ expect(JSON.parse(params.get('payload') || '')).toEqual(payload);
+ expectSlackSignature(forwardCall, body);
+ });
+
+ it('should acknowledge slash_commands', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ ws.simulateMessage({
+ envelope_id: 'env_cmd',
+ payload: { command: '/new' },
+ type: 'slash_commands',
+ });
+
+ const ack = ws.getLastSentPayload();
+ expect(ack).toEqual({ envelope_id: 'env_cmd' });
+ });
+
+ it('should acknowledge interactive payloads', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ ws.simulateMessage({
+ envelope_id: 'env_int',
+ payload: { type: 'block_actions' },
+ type: 'interactive',
+ });
+
+ const ack = ws.getLastSentPayload();
+ expect(ack).toEqual({ envelope_id: 'env_int' });
+ });
+ });
+
+ describe('disconnect handling', () => {
+ it('should close on link_disabled disconnect', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ ws.simulateMessage({ reason: 'link_disabled', type: 'disconnect' });
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+
+ it('should reconnect on refresh_requested disconnect', async () => {
+ const { connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ ws.simulateMessage({ reason: 'refresh_requested', type: 'disconnect' });
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+ });
+
+ describe('close', () => {
+ it('should clean up on close()', async () => {
+ const { conn, connectPromise, ws } = await connectAndGetWs();
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ conn.close();
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+
+ it('should stop on abort signal', async () => {
+ const abort = new AbortController();
+ const { connectPromise, ws } = await connectAndGetWs({ abortSignal: abort.signal });
+ ws.simulateMessage({ type: 'hello' });
+ await connectPromise;
+
+ abort.abort();
+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);
+ });
+ });
+});
diff --git a/src/server/services/bot/platforms/slack/gateway.ts b/src/server/services/bot/platforms/slack/gateway.ts
new file mode 100644
index 00000000000..bd9e14fee8b
--- /dev/null
+++ b/src/server/services/bot/platforms/slack/gateway.ts
@@ -0,0 +1,344 @@
+import { createHmac } from 'node:crypto';
+
+import debug from 'debug';
+
+import { SLACK_API_BASE } from './api';
+
+const log = debug('bot-platform:slack:gateway');
+
+const RECONNECT_BASE_DELAY_MS = 1000;
+const RECONNECT_MAX_DELAY_MS = 60_000;
+const MAX_RECONNECT_ATTEMPTS = 10;
+const SLACK_SIGNATURE_VERSION = 'v0';
+
+export interface SlackSocketModeOptions {
+ /** AbortSignal to cancel the connection */
+ abortSignal?: AbortSignal;
+ /** App-level token (xapp-*) for apps.connections.open */
+ appToken: string;
+ /** Duration in ms before the connection auto-closes (caller restarts) */
+ durationMs?: number;
+ /** Signing secret used to synthesize Slack-compatible webhook signatures */
+ signingSecret: string;
+ /** URL to forward events to (POST) */
+ webhookUrl: string;
+}
+
+interface SlackSocketEnvelope {
+ accepts_response_payload?: boolean;
+ envelope_id: string;
+ payload: any;
+ reason?: string;
+ type: string;
+}
+
+/**
+ * Manages a persistent WebSocket connection to Slack via Socket Mode.
+ *
+ * Lifecycle: apps.connections.open → WSS connect → hello → receive events → acknowledge → forward.
+ * Handles disconnect/refresh messages by reconnecting with a new WSS URL.
+ */
+export class SlackSocketModeConnection {
+ private readonly appToken: string;
+ private readonly abortSignal?: AbortSignal;
+ private readonly durationMs?: number;
+ private readonly signingSecret: string;
+ private readonly webhookUrl: string;
+
+ private ws: WebSocket | null = null;
+ private closed = false;
+ private reconnectAttempts = 0;
+
+ constructor(options: SlackSocketModeOptions) {
+ this.appToken = options.appToken;
+ this.abortSignal = options.abortSignal;
+ this.durationMs = options.durationMs;
+ this.signingSecret = options.signingSecret;
+ this.webhookUrl = options.webhookUrl;
+ }
+
+ /**
+ * Start the Socket Mode connection.
+ * Resolves once the `hello` message is received.
+ */
+ async connect(): Promise<void> {
+ if (this.abortSignal?.aborted) return;
+
+ const url = await this.getSocketUrl();
+ log('Socket Mode URL obtained');
+
+ return this.openConnection(url);
+ }
+
+ /**
+ * Gracefully close the connection.
+ */
+ close(): void {
+ this.closed = true;
+ if (this.ws) {
+ this.ws.close(1000, 'Client shutdown');
+ this.ws = null;
+ }
+ }
+
+ // ---------- Socket URL ----------
+
+ private async getSocketUrl(): Promise<string> {
+ const response = await fetch(`${SLACK_API_BASE}/apps.connections.open`, {
+ headers: {
+ 'Authorization': `Bearer ${this.appToken}`,
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ throw new Error(`apps.connections.open failed: ${response.status}`);
+ }
+
+ const data = (await response.json()) as { ok: boolean; url?: string; error?: string };
+ if (!data.ok || !data.url) {
+ throw new Error(`apps.connections.open failed: ${data.error || 'no url returned'}`);
+ }
+
+ return data.url;
+ }
+
+ // ---------- Connection Management ----------
+
+ private openConnection(url: string): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ if (this.abortSignal?.aborted || this.closed) {
+ resolve();
+ return;
+ }
+
+ const ws = new WebSocket(url);
+ this.ws = ws;
+
+ let resolved = false;
+
+ const onAbort = () => {
+ this.close();
+ if (!resolved) {
+ resolved = true;
+ resolve();
+ }
+ };
+
+ this.abortSignal?.addEventListener('abort', onAbort, { once: true });
+
+ ws.addEventListener('open', () => {
+ log('WebSocket connected');
+ this.reconnectAttempts = 0;
+ });
+
+ ws.addEventListener('message', (event) => {
+ const data =
+ typeof event.data === 'string'
+ ? event.data
+ : new TextDecoder().decode(event.data as ArrayBuffer);
+
+ let envelope: SlackSocketEnvelope;
+ try {
+ envelope = JSON.parse(data);
+ } catch {
+ log('Failed to parse message: %s', data);
+ return;
+ }
+
+ this.handleEnvelope(envelope, (err?: Error) => {
+ if (resolved) return;
+ resolved = true;
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+
+ ws.addEventListener('close', (event) => {
+ log('WebSocket closed: code=%d reason=%s', event.code, event.reason);
+ this.abortSignal?.removeEventListener('abort', onAbort);
+
+ if (!resolved) {
+ resolved = true;
+ resolve();
+ }
+
+ if (!this.closed && !this.abortSignal?.aborted) {
+ this.attemptReconnect();
+ }
+ });
+
+ ws.addEventListener('error', (event) => {
+ log('WebSocket error: %O', event);
+ if (!resolved) {
+ resolved = true;
+ reject(new Error('WebSocket connection failed'));
+ }
+ });
+
+ // Auto-close after durationMs
+ if (this.durationMs) {
+ setTimeout(() => {
+ if (!this.closed && !this.abortSignal?.aborted) {
+ log('Duration elapsed (%dms), closing', this.durationMs);
+ this.close();
+ }
+ }, this.durationMs);
+ }
+ });
+ }
+
+ // ---------- Envelope Handling ----------
+
+ private handleEnvelope(envelope: SlackSocketEnvelope, onReady: (err?: Error) => void): void {
+ switch (envelope.type) {
+ case 'hello': {
+ log('Hello received');
+ onReady();
+ break;
+ }
+
+ case 'disconnect': {
+ log('Disconnect: reason=%s', envelope.reason);
+ if (envelope.reason === 'link_disabled') {
+ // App disabled Socket Mode — stop reconnecting
+ this.close();
+ } else {
+ // refresh_requested or warning — reconnect
+ this.ws?.close(1000, 'Reconnecting');
+ }
+ break;
+ }
+
+ case 'events_api':
+ case 'slash_commands':
+ case 'interactive': {
+ // Acknowledge immediately — Slack retries if not acked
+ this.acknowledge(envelope.envelope_id);
+ // Forward the event payload to webhook URL
+ this.forwardEvent(envelope);
+ break;
+ }
+
+ default: {
+ // Acknowledge unknown types to prevent retries
+ if (envelope.envelope_id) {
+ this.acknowledge(envelope.envelope_id);
+ }
+ log('Unhandled envelope type: %s', envelope.type);
+ }
+ }
+ }
+
+ private acknowledge(envelopeId: string): void {
+ if (this.ws?.readyState === WebSocket.OPEN) {
+ this.ws.send(JSON.stringify({ envelope_id: envelopeId }));
+ }
+ }
+
+ // ---------- Event Forwarding ----------
+
+ private forwardEvent(envelope: SlackSocketEnvelope): void {
+ const forwardedRequest = this.buildForwardedRequest(envelope);
+
+ fetch(this.webhookUrl, {
+ body: forwardedRequest.body,
+ headers: forwardedRequest.headers,
+ method: 'POST',
+ signal: AbortSignal.timeout(30_000),
+ }).catch((err) => {
+ log('Failed to forward event to webhook: %O', err);
+ });
+ }
+
+ private buildForwardedRequest(envelope: SlackSocketEnvelope) {
+ const body = this.serializePayload(envelope);
+ const timestamp = Math.floor(Date.now() / 1_000).toString();
+ const signature = this.signBody(body, timestamp);
+
+ return {
+ body,
+ headers: {
+ 'Content-Type': this.getContentType(envelope.type),
+ 'x-slack-request-timestamp': timestamp,
+ 'x-slack-signature': signature,
+ },
+ };
+ }
+
+ private getContentType(envelopeType: SlackSocketEnvelope['type']) {
+ switch (envelopeType) {
+ case 'interactive':
+ case 'slash_commands': {
+ return 'application/x-www-form-urlencoded';
+ }
+ default: {
+ return 'application/json';
+ }
+ }
+ }
+
+ private serializePayload(envelope: SlackSocketEnvelope) {
+ switch (envelope.type) {
+ case 'interactive': {
+ return new URLSearchParams({ payload: JSON.stringify(envelope.payload) }).toString();
+ }
+ case 'slash_commands': {
+ const params = new URLSearchParams();
+
+ for (const [key, value] of Object.entries(envelope.payload)) {
+ if (value === undefined || value === null) continue;
+ params.append(key, String(value));
+ }
+
+ return params.toString();
+ }
+ default: {
+ return JSON.stringify(envelope.payload);
+ }
+ }
+ }
+
+ private signBody(body: string, timestamp: string) {
+ const baseString = `${SLACK_SIGNATURE_VERSION}:${timestamp}:${body}`;
+ const digest = createHmac('sha256', this.signingSecret).update(baseString).digest('hex');
+
+ return `${SLACK_SIGNATURE_VERSION}=${digest}`;
+ }
+
+ // ---------- Reconnection ----------
+
+ private attemptReconnect(): void {
+ if (this.reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
+ log('Max reconnect attempts reached (%d), giving up', MAX_RECONNECT_ATTEMPTS);
+ return;
+ }
+
+ this.reconnectAttempts++;
+ const delay = Math.min(
+ RECONNECT_BASE_DELAY_MS * 2 ** (this.reconnectAttempts - 1),
+ RECONNECT_MAX_DELAY_MS,
+ );
+
+ log(
+ 'Reconnecting in %dms (attempt %d/%d)',
+ delay,
+ this.reconnectAttempts,
+ MAX_RECONNECT_ATTEMPTS,
+ );
+
+ setTimeout(async () => {
+ if (this.closed || this.abortSignal?.aborted) return;
+
+ try {
+ // Get a fresh WSS URL for each reconnect
+ const url = await this.getSocketUrl();
+ await this.openConnection(url);
+ } catch (err) {
+ log('Reconnect failed: %O', err);
+ this.attemptReconnect();
+ }
+ }, delay);
+ }
+}
diff --git a/src/server/services/bot/platforms/slack/schema.ts b/src/server/services/bot/platforms/slack/schema.ts
index 6d42817a590..786d45f3688 100644
--- a/src/server/services/bot/platforms/slack/schema.ts
+++ b/src/server/services/bot/platforms/slack/schema.ts
@@ -7,7 +7,7 @@ import {
import { displayToolCallsField, serverIdField, userIdField } from '../const';
import type { FieldSchema } from '../types';
-import { MAX_SLACK_HISTORY_LIMIT } from './const';
+import { DEFAULT_SLACK_CONNECTION_MODE, MAX_SLACK_HISTORY_LIMIT } from './const';
export const schema: FieldSchema[] = [
{
@@ -35,6 +35,13 @@ export const schema: FieldSchema[] = [
required: true,
type: 'password',
},
+ {
+ key: 'appToken',
+ description: 'channel.slack.appTokenHint',
+ label: 'channel.slack.appToken',
+ placeholder: 'xapp-...',
+ type: 'password',
+ },
],
type: 'object',
},
@@ -42,6 +49,15 @@ export const schema: FieldSchema[] = [
key: 'settings',
label: 'channel.settings',
properties: [
+ {
+ key: 'connectionMode',
+ default: DEFAULT_SLACK_CONNECTION_MODE,
+ description: 'channel.connectionModeHint',
+ enum: ['websocket', 'webhook'],
+ enumLabels: ['channel.connectionModeWebSocket', 'channel.connectionModeWebhook'],
+ label: 'channel.connectionMode',
+ type: 'string',
+ },
{
key: 'charLimit',
default: 4000,
diff --git a/src/server/services/bot/platforms/telegram/api.ts b/src/server/services/bot/platforms/telegram/api.ts
index 86b6939bac6..0e97557aceb 100644
--- a/src/server/services/bot/platforms/telegram/api.ts
+++ b/src/server/services/bot/platforms/telegram/api.ts
@@ -115,6 +115,44 @@ export class TelegramApi {
return data.result;
}
+ // ==================== File Download ====================
+
+ /**
+ * Resolve a Telegram `file_id` to a `file_path` so it can be downloaded.
+ * Two-step Bot API flow: getFile → fetch from /file/bot<token>/<file_path>.
+ */
+ async getFile(fileId: string): Promise<{ file_path?: string; file_size?: number }> {
+ log('getFile: fileId=%s', fileId);
+ const data = await this.call('getFile', { file_id: fileId });
+ return data.result;
+ }
+
+ /**
+ * Download a Telegram media attachment by file_id.
+ *
+ * The Chat SDK's `Attachment.fetchData` closure is stripped when messages
+ * are serialized into the queue/Redis (functions are not JSON-serializable),
+ * so we need a way to re-download the original media after a debounce
+ * round-trip. This is the platform-native fallback path used by
+ * `TelegramWebhookClient.refetchAttachment`.
+ */
+ async downloadFile(fileId: string): Promise<Buffer> {
+ const file = await this.getFile(fileId);
+ if (!file.file_path) {
+ throw new Error(`Telegram getFile returned no file_path for ${fileId}`);
+ }
+ const url = `${TELEGRAM_API_BASE}/file/bot${this.botToken}/${file.file_path}`;
+ log('downloadFile: fileId=%s, file_path=%s', fileId, file.file_path);
+ const response = await fetch(url);
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ throw new Error(
+ `Failed to download Telegram file ${fileId}: ${response.status} ${text}`.trim(),
+ );
+ }
+ return Buffer.from(await response.arrayBuffer());
+ }
+
// ==================== Forum Topics (Threads) ====================
async createForumTopic(
diff --git a/src/server/services/bot/platforms/telegram/client.test.ts b/src/server/services/bot/platforms/telegram/client.test.ts
new file mode 100644
index 00000000000..efbbd67a9e1
--- /dev/null
+++ b/src/server/services/bot/platforms/telegram/client.test.ts
@@ -0,0 +1,298 @@
+import type { MockInstance } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TelegramApi } from './api';
+import { TelegramClientFactory } from './client';
+
+const BOT_TOKEN = 'test-bot-token';
+
+const createClient = () =>
+ new TelegramClientFactory().createClient(
+ {
+ applicationId: '8654315085',
+ credentials: { botToken: BOT_TOKEN },
+ platform: 'telegram',
+ settings: {},
+ },
+ {},
+ );
+
+/** Build a fake Chat SDK Message with attachments + raw payload. */
+const makeMessage = (overrides: {
+ attachments?: Array<Record<string, unknown>>;
+ raw?: Record<string, unknown>;
+ id?: string;
+}) =>
+ ({
+ attachments: overrides.attachments ?? [],
+ id: overrides.id ?? '7019597964:158',
+ raw: overrides.raw ?? {},
+ text: '',
+ }) as any;
+
+describe('TelegramWebhookClient.extractFiles', () => {
+ let downloadFileSpy: MockInstance<TelegramApi['downloadFile']>;
+
+ beforeEach(() => {
+ downloadFileSpy = vi.spyOn(TelegramApi.prototype, 'downloadFile') as MockInstance<
+ TelegramApi['downloadFile']
+ >;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('extracts a Telegram photo using file_id from raw.photo[] (largest variant)', async () => {
+ // Reproduces the original Telegram-photo bug: the chat-adapter emits a
+ // photo attachment with no buffer/fetchData/url that survives Redis, only
+ // a `type: 'image'` discriminant. We must dig the file_id out of raw.photo
+ // and download it ourselves, picking the largest variant.
+ const buffer = Buffer.from('largest-photo-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ size: 16_388, type: 'image' }],
+ raw: {
+ chat: { id: 7019597964 },
+ message_id: 158,
+ photo: [
+ { file_id: 'small-thumb', file_size: 1234, height: 90, width: 90 },
+ { file_id: 'medium', file_size: 8000, height: 320, width: 320 },
+ { file_id: 'large', file_size: 16_388, height: 1280, width: 1280 },
+ ],
+ },
+ }),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledTimes(1);
+ expect(downloadFileSpy).toHaveBeenCalledWith('large');
+ expect(result).toEqual([
+ {
+ buffer,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ size: 16_388,
+ },
+ ]);
+ });
+
+ it('extracts a Telegram video using file_id from raw.video', async () => {
+ const buffer = Buffer.from('video-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ mimeType: 'video/mp4', name: 'star.mp4', size: 932_036, type: 'video' }],
+ raw: {
+ video: {
+ file_id: 'tg-video-1',
+ file_name: 'star.mp4',
+ file_size: 932_036,
+ mime_type: 'video/mp4',
+ },
+ },
+ }),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledWith('tg-video-1');
+ expect(result).toEqual([{ buffer, mimeType: 'video/mp4', name: 'star.mp4', size: 932_036 }]);
+ });
+
+ it('extracts a Telegram document using file_id from raw.document', async () => {
+ const buffer = Buffer.from('pdf-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [
+ {
+ mimeType: 'application/pdf',
+ name: 'report.pdf',
+ size: 4096,
+ type: 'file',
+ },
+ ],
+ raw: {
+ document: {
+ file_id: 'tg-doc-1',
+ file_name: 'report.pdf',
+ file_size: 4096,
+ mime_type: 'application/pdf',
+ },
+ },
+ }),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledWith('tg-doc-1');
+ expect(result).toEqual([
+ { buffer, mimeType: 'application/pdf', name: 'report.pdf', size: 4096 },
+ ]);
+ });
+
+ it('extracts a Telegram voice note (raw.voice) under the audio type', async () => {
+ const buffer = Buffer.from('voice-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ mimeType: 'audio/ogg', size: 4321, type: 'audio' }],
+ raw: {
+ voice: { file_id: 'tg-voice-1', file_size: 4321, mime_type: 'audio/ogg' },
+ },
+ }),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledWith('tg-voice-1');
+ expect(result?.[0]?.mimeType).toBe('audio/ogg');
+ });
+
+ it('extracts a Telegram audio file (raw.audio) under the audio type', async () => {
+ const buffer = Buffer.from('mp3-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [
+ {
+ mimeType: 'audio/mpeg',
+ name: 'Erik Lund - Summertime.mp3',
+ size: 7_699_566,
+ type: 'audio',
+ },
+ ],
+ raw: {
+ audio: {
+ file_id: 'tg-audio-1',
+ file_name: 'Erik Lund - Summertime.mp3',
+ file_size: 7_699_566,
+ mime_type: 'audio/mpeg',
+ },
+ },
+ }),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledWith('tg-audio-1');
+ expect(result?.[0]?.name).toBe('Erik Lund - Summertime.mp3');
+ });
+
+ it('returns undefined when no attachments are present', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(makeMessage({ attachments: [] }));
+ expect(downloadFileSpy).not.toHaveBeenCalled();
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when attachment type has no matching media field in raw', async () => {
+ // Defensive case: attachment claims type 'image' but raw.photo is missing.
+ // We should NOT throw and NOT call downloadFile.
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ type: 'image' }],
+ raw: {},
+ }),
+ );
+ expect(downloadFileSpy).not.toHaveBeenCalled();
+ expect(result).toBeUndefined();
+ });
+
+ it('falls back to image/jpeg + image.jpg when att.mimeType and att.name are missing', async () => {
+ // Telegram's Bot API does not return mime_type or file_name for `photo`
+ // payloads — they are always JPEG by spec. This is the original bug:
+ // without inference, downstream classifies as application/octet-stream
+ // and routes to fileList instead of imageList.
+ const buffer = Buffer.from('photo-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ size: 16_388, type: 'image' }],
+ raw: { photo: [{ file_id: 'tg-photo' }] },
+ }),
+ );
+
+ expect(result).toEqual([
+ {
+ buffer,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ size: 16_388,
+ },
+ ]);
+ });
+
+ it('uses the explicit mimeType / name from the attachment when present', async () => {
+ // Quicktime video shouldn't be coerced to video/mp4 — Telegram fills
+ // in mime_type for non-photo media, and we should respect it.
+ const buffer = Buffer.from('quicktime-bytes');
+ downloadFileSpy.mockResolvedValue(buffer);
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ mimeType: 'video/quicktime', name: 'clip.mov', size: 100, type: 'video' }],
+ raw: { video: { file_id: 'tg-video-mov' } },
+ }),
+ );
+
+ expect(result?.[0]?.mimeType).toBe('video/quicktime');
+ expect(result?.[0]?.name).toBe('clip.mov');
+ });
+
+ it('skips a single failing attachment without dropping the others', async () => {
+ // First message has photo only, second has document only — they're
+ // separate Messages, but the test exercises the per-attachment try/catch
+ // by giving one Message two attachments where the first errors.
+ const goodBuffer = Buffer.from('good');
+ downloadFileSpy
+ .mockRejectedValueOnce(new Error('telegram getFile 404'))
+ .mockResolvedValueOnce(goodBuffer);
+
+ const client = createClient();
+ // Construct a synthetic two-attachment message — in practice Telegram
+ // only sends one media field per update, but the resolver iterates the
+ // attachment list, and we want to verify it's resilient.
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ type: 'image' }, { type: 'file' }],
+ raw: {
+ document: { file_id: 'doc-good', file_name: 'good.pdf' },
+ photo: [{ file_id: 'photo-bad' }],
+ },
+ }),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledTimes(2);
+ expect(result).toEqual([
+ {
+ buffer: goodBuffer,
+ mimeType: 'application/octet-stream',
+ name: 'file.bin',
+ size: goodBuffer.length,
+ },
+ ]);
+ });
+
+ it('returns undefined and does not throw when downloadFile rejects entirely', async () => {
+ downloadFileSpy.mockRejectedValue(new Error('network down'));
+
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ attachments: [{ type: 'image' }],
+ raw: { photo: [{ file_id: 'tg-photo' }] },
+ }),
+ );
+
+ expect(downloadFileSpy).toHaveBeenCalledTimes(1);
+ expect(result).toBeUndefined();
+ });
+});
diff --git a/src/server/services/bot/platforms/telegram/client.ts b/src/server/services/bot/platforms/telegram/client.ts
index a413fd8c20c..0214adfd032 100644
--- a/src/server/services/bot/platforms/telegram/client.ts
+++ b/src/server/services/bot/platforms/telegram/client.ts
@@ -1,6 +1,8 @@
import { createTelegramAdapter } from '@chat-adapter/telegram';
+import type { Message } from 'chat';
import debug from 'debug';
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
import {
BOT_RUNTIME_STATUSES,
getRuntimeStatusErrorMessage,
@@ -32,6 +34,47 @@ function parseTelegramMessageId(compositeId: string): number {
return colonIdx !== -1 ? Number(compositeId.slice(colonIdx + 1)) : Number(compositeId);
}
+/**
+ * Default mime / name when the chat-adapter didn't fill them in. Telegram's
+ * Bot API does not return `mime_type` or `file_name` for `photo` payloads
+ * (photos are always JPEG by spec), so we have to backfill from `att.type`.
+ * Other media (video / audio / document) usually carry their own mime/name,
+ * but we still provide defaults so the LLM gets a recognizable filename.
+ */
+const defaultMimeForType = (type: string | undefined): string => {
+ switch (type) {
+ case 'image': {
+ return 'image/jpeg';
+ }
+ case 'video': {
+ return 'video/mp4';
+ }
+ case 'audio': {
+ return 'audio/ogg';
+ }
+ default: {
+ return 'application/octet-stream';
+ }
+ }
+};
+
+const defaultNameForType = (type: string | undefined): string => {
+ switch (type) {
+ case 'image': {
+ return 'image.jpg';
+ }
+ case 'video': {
+ return 'video.mp4';
+ }
+ case 'audio': {
+ return 'audio.ogg';
+ }
+ default: {
+ return 'file.bin';
+ }
+ }
+};
+
class TelegramWebhookClient implements PlatformClient {
readonly id = 'telegram';
readonly applicationId: string;
@@ -143,6 +186,100 @@ class TelegramWebhookClient implements PlatformClient {
log('TelegramBot appId=%s registered %d commands', this.applicationId, commands.length);
}
+ /**
+ * Resolve a Chat SDK `Message` into `AttachmentSource[]` by re-downloading
+ * each media attachment via the Telegram Bot API.
+ *
+ * Why we always download from `file_id` instead of trusting the chat-adapter:
+ * the chat-adapter sets `fetchData: () => downloadFile(fileId)` as a closure,
+ * but `Message.toJSON` strips functions (and buffers) when the message is
+ * enqueued into Redis for the debounce strategy. Telegram photos in
+ * particular have neither `url` nor `buffer` to fall back on after a
+ * round-trip, so we own the download path here.
+ *
+ * For each attachment we look up the original `file_id` in `message.raw`
+ * (which IS preserved by `toJSON`), call `TelegramApi.downloadFile`, and
+ * build an `AttachmentSource` with sensible mime/name defaults — Telegram's
+ * Bot API does not return `mime_type` / `file_name` for `photo` payloads,
+ * so we must provide them.
+ *
+ * Per-attachment errors are swallowed and logged so a single failed
+ * download doesn't drop the rest of the message's attachments.
+ */
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ const attachments = (message as any).attachments as
+ | Array<{
+ mimeType?: string;
+ name?: string;
+ size?: number;
+ type?: string;
+ }>
+ | undefined;
+ if (!attachments?.length) return undefined;
+
+ const raw = (message as any).raw as Record<string, any> | undefined;
+ log('extractFiles: msgId=%s, attachments=%d', (message as any).id, attachments.length);
+
+ const telegram = new TelegramApi(this.config.credentials.botToken);
+ const results: AttachmentSource[] = [];
+
+ for (const att of attachments) {
+ const fileId = TelegramWebhookClient.resolveTelegramFileId(raw, att.type);
+ if (!fileId) {
+ log('extractFiles: no file_id for type=%s in raw payload (skipping)', att.type);
+ continue;
+ }
+ try {
+ const buffer = await telegram.downloadFile(fileId);
+ results.push({
+ buffer,
+ mimeType: att.mimeType ?? defaultMimeForType(att.type),
+ name: att.name ?? defaultNameForType(att.type),
+ size: att.size ?? buffer.length,
+ });
+ log(
+ 'extractFiles: downloaded type=%s fileId=%s, %d bytes',
+ att.type,
+ fileId,
+ buffer.length,
+ );
+ } catch (error) {
+ log('extractFiles: downloadFile failed for type=%s fileId=%s: %O', att.type, fileId, error);
+ }
+ }
+
+ return results.length > 0 ? results : undefined;
+ }
+
+ static resolveTelegramFileId(
+ raw: Record<string, any> | undefined,
+ type: string | undefined,
+ ): string | undefined {
+ if (!raw) return undefined;
+ switch (type) {
+ case 'image': {
+ // Telegram returns photos as an array of size variants — pick the largest.
+ const photos = raw.photo;
+ if (Array.isArray(photos) && photos.length > 0) {
+ return photos.at(-1)?.file_id;
+ }
+ return undefined;
+ }
+ case 'video': {
+ return raw.video?.file_id;
+ }
+ case 'audio': {
+ return raw.audio?.file_id ?? raw.voice?.file_id;
+ }
+ case 'file': {
+ return raw.document?.file_id;
+ }
+ default: {
+ return undefined;
+ }
+ }
+ }
+
formatMarkdown(markdown: string): string {
return markdownToTelegramHTML(markdown);
}
diff --git a/src/server/services/bot/platforms/telegram/definition.ts b/src/server/services/bot/platforms/telegram/definition.ts
index 5034893f69b..1369f6fd8f8 100644
--- a/src/server/services/bot/platforms/telegram/definition.ts
+++ b/src/server/services/bot/platforms/telegram/definition.ts
@@ -5,6 +5,7 @@ import { schema } from './schema';
export const telegram: PlatformDefinition = {
id: 'telegram',
name: 'Telegram',
+ connectionMode: 'webhook',
description: 'Connect a Telegram bot',
documentation: {
portalUrl: 'https://t.me/BotFather',
diff --git a/src/server/services/bot/platforms/telegram/schema.ts b/src/server/services/bot/platforms/telegram/schema.ts
index a0b20cb2b0e..c5af9446190 100644
--- a/src/server/services/bot/platforms/telegram/schema.ts
+++ b/src/server/services/bot/platforms/telegram/schema.ts
@@ -48,7 +48,7 @@ export const schema: FieldSchema[] = [
},
{
key: 'concurrency',
- default: 'debounce',
+ default: 'queue',
description: 'channel.concurrencyHint',
enum: ['queue', 'debounce'],
enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.ts
index fa564d588d9..16470f42ac7 100644
--- a/src/server/services/bot/platforms/types.ts
+++ b/src/server/services/bot/platforms/types.ts
@@ -1,9 +1,21 @@
-import type { Chat } from 'chat';
+import type { Chat, Message } from 'chat';
+
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
// ============================================================================
// Bot Platform Core Types
// ============================================================================
+// --------------- Connection Mode ---------------
+
+/**
+ * How the platform communicates with the server.
+ * - 'webhook': stateless HTTP callbacks (can run in serverless)
+ * - 'websocket': persistent WebSocket connection (e.g. Discord, QQ)
+ * - 'polling': persistent long-polling connection (e.g. WeChat)
+ */
+export type ConnectionMode = 'polling' | 'webhook' | 'websocket';
+
// --------------- Field Schema ---------------
/**
@@ -99,6 +111,19 @@ export interface PlatformClient {
/** Extract the chat/channel ID from a composite platformThreadId. */
extractChatId: (platformThreadId: string) => string;
+ /**
+ * Resolve attachments on an inbound `Message` into `AttachmentSource[]` for
+ * ingestion by the bridge. Each platform owns its own attachment quirks
+ * here: data-source priority, type-only metadata inference, quoted-message
+ * handling, and re-download paths for data lost during chat-sdk Redis
+ * serialization (functions and buffers don't survive `Message.toJSON`).
+ *
+ * Optional — when omitted, the bridge falls back to its legacy
+ * `extractFiles` implementation. Eventually all platforms will implement
+ * this and the bridge fallback will be deleted.
+ */
+ extractFiles?: (message: Message) => Promise<AttachmentSource[] | undefined>;
+
/**
* Transform outbound Markdown content into a format the platform can render.
* Called before `formatReply` and `splitMessage`.
@@ -117,11 +142,11 @@ export interface PlatformClient {
*/
formatReply?: (body: string, stats?: UsageStats) => string;
+ // --- Runtime Operations ---
+
/** Get a messenger for a specific thread (outbound messaging). */
getMessenger: (platformThreadId: string) => PlatformMessenger;
- // --- Runtime Operations ---
-
readonly id: string;
/** Parse a composite message ID into the platform-native format. */
@@ -258,10 +283,20 @@ export interface PlatformDefinition {
/**
* Connection mode: how the platform communicates with the server.
* - 'webhook': stateless HTTP callbacks (can run in serverless)
- * - 'persistent': requires a long-running client (e.g. websocket or long-polling)
- * Defaults to 'webhook'.
+ * - 'websocket': persistent WebSocket connection (e.g. Discord, QQ)
+ * - 'polling': persistent long-polling connection (e.g. WeChat)
+ *
+ * For single-mode platforms this is the runtime mode. For multi-mode
+ * platforms where users can pick per-provider via `settings.connectionMode`,
+ * this represents the *recommended* default for new providers (form initial
+ * value + cron coarse filter).
+ *
+ * For platforms that added multi-mode support after launch (Slack/Feishu/
+ * Lark/QQ), legacy provider rows without an explicit setting fall back to
+ * `'webhook'` instead — see `LEGACY_WEBHOOK_PLATFORMS` and
+ * `getEffectiveConnectionMode` in `./utils.ts`.
*/
- connectionMode?: 'persistent' | 'webhook';
+ connectionMode: ConnectionMode;
/** The description of the platform. */
description?: string;
diff --git a/src/server/services/bot/platforms/utils.ts b/src/server/services/bot/platforms/utils.ts
index b622ee9afa9..36cd87119fc 100644
--- a/src/server/services/bot/platforms/utils.ts
+++ b/src/server/services/bot/platforms/utils.ts
@@ -1,6 +1,6 @@
import { merge } from '@lobechat/utils';
-import type { FieldSchema, UsageStats } from './types';
+import type { ConnectionMode, FieldSchema, PlatformDefinition, UsageStats } from './types';
// --------------- Settings defaults ---------------
@@ -50,6 +50,48 @@ export function mergeWithDefaults(
return merge(defaults, userSettings) as Record<string, unknown>;
}
+// --------------- Connection mode resolution ---------------
+
+/**
+ * Platforms that historically shipped as webhook-only and added multi-mode
+ * (websocket) support later. Provider rows created before the upgrade have no
+ * `settings.connectionMode` field, and must keep running on webhook to
+ * preserve their original behavior — otherwise upgrading would silently break
+ * every legacy bot.
+ *
+ * **Do NOT add brand-new multi-mode platforms here.** A platform that ships
+ * with multi-mode support from day one has no legacy data to preserve, so it
+ * should use `platform.connectionMode` as its runtime fallback like every
+ * other platform. This list is strictly for backward-compat with rows that
+ * pre-date the `connectionMode` field on a given platform.
+ */
+const LEGACY_WEBHOOK_PLATFORMS: ReadonlySet<string> = new Set(['slack', 'feishu', 'lark', 'qq']);
+
+/**
+ * Resolve the effective connection mode for a single provider.
+ *
+ * Resolution order:
+ * 1. Explicit `settings.connectionMode` (set when the user saves the form)
+ * 2. For platforms in `LEGACY_WEBHOOK_PLATFORMS`, fall back to `'webhook'` so
+ * legacy provider rows keep their original behavior.
+ * 3. Otherwise fall back to `platform.connectionMode`, which is the platform's
+ * default runtime mode (single-mode platforms) or the recommended default
+ * for new providers (any future multi-mode platform with no legacy data).
+ */
+export function getEffectiveConnectionMode(
+ platform: PlatformDefinition | undefined,
+ settings: Record<string, unknown> | null | undefined,
+): ConnectionMode {
+ const fromSettings = settings?.connectionMode as ConnectionMode | undefined;
+ if (fromSettings) return fromSettings;
+
+ if (platform && LEGACY_WEBHOOK_PLATFORMS.has(platform.id)) {
+ return 'webhook';
+ }
+
+ return platform?.connectionMode ?? 'webhook';
+}
+
// --------------- Runtime key helpers ---------------
/**
diff --git a/src/server/services/bot/platforms/wechat/client.test.ts b/src/server/services/bot/platforms/wechat/client.test.ts
index 70187d1e9a8..be23f2fba5d 100644
--- a/src/server/services/bot/platforms/wechat/client.test.ts
+++ b/src/server/services/bot/platforms/wechat/client.test.ts
@@ -3,11 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mockCreateWechatAdapter = vi.hoisted(() => vi.fn());
const mockGetUpdates = vi.hoisted(() => vi.fn());
const mockStartTyping = vi.hoisted(() => vi.fn());
+const mockDownloadMediaFromRawMessage = vi.hoisted(() => vi.fn());
const MessageState = vi.hoisted(() => ({ FINISH: 2 }));
const MessageType = vi.hoisted(() => ({ BOT: 2, USER: 1 }));
vi.mock('@lobechat/chat-adapter-wechat', () => ({
createWechatAdapter: mockCreateWechatAdapter,
+ downloadMediaFromRawMessage: mockDownloadMediaFromRawMessage,
MessageState,
MessageType,
WechatApiClient: vi.fn().mockImplementation(() => ({
@@ -166,4 +168,151 @@ describe('WechatGatewayClient', () => {
),
).toThrowError('Bot Token is required');
});
+
+ describe('extractFiles', () => {
+ // Verifies the post-Redis re-download path: when WeChat messages
+ // round-trip through the chat-sdk debounce/queue, `Message.toJSON`
+ // strips the `att.buffer` field that the adapter pre-populated. We
+ // recover by walking `message.raw.item_list` and re-running the same
+ // download logic via the package-exported helper.
+ const createClient = () =>
+ new WechatClientFactory().createClient(
+ {
+ applicationId: 'wechat-app',
+ credentials: { botId: 'bot-id', botToken: 'bot-token' },
+ platform: 'wechat',
+ settings: {},
+ },
+ { appUrl: 'https://example.com', redisClient: runtimeRedis as any },
+ );
+
+ /** Build a fake Chat SDK Message with a WeChat raw payload. */
+ const makeMessage = (raw: Record<string, unknown>, id = 'wechat-msg-1') =>
+ ({ id, attachments: [], raw, text: '' }) as any;
+
+ it('returns undefined when raw has no item_list', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(makeMessage({}));
+ expect(mockDownloadMediaFromRawMessage).not.toHaveBeenCalled();
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when item_list is empty', async () => {
+ const client = createClient();
+ const result = await client.extractFiles!(makeMessage({ item_list: [] }));
+ expect(mockDownloadMediaFromRawMessage).not.toHaveBeenCalled();
+ expect(result).toBeUndefined();
+ });
+
+ it('delegates to downloadMediaFromRawMessage and maps the result to AttachmentSource[]', async () => {
+ const buffer = Buffer.from('wechat-image-bytes');
+ mockDownloadMediaFromRawMessage.mockResolvedValue([
+ {
+ buffer,
+ mimeType: 'image/jpeg',
+ name: 'image.jpg',
+ type: 'image',
+ url: '',
+ },
+ ]);
+
+ const client = createClient();
+ const raw = {
+ item_list: [
+ {
+ image_item: {
+ aeskey: 'hex-key',
+ media: { encrypt_query_param: 'enc-1' },
+ },
+ type: 1, // MessageItemType.IMAGE
+ },
+ ],
+ };
+ const result = await client.extractFiles!(makeMessage(raw));
+
+ expect(mockDownloadMediaFromRawMessage).toHaveBeenCalledTimes(1);
+ // Confirm we pass the api client + raw payload (the helper handles the rest).
+ expect(mockDownloadMediaFromRawMessage).toHaveBeenCalledWith(
+ expect.anything(), // WechatApiClient instance
+ raw,
+ );
+ expect(result).toEqual([
+ { buffer, mimeType: 'image/jpeg', name: 'image.jpg', size: undefined },
+ ]);
+ });
+
+ it('returns undefined when downloadMediaFromRawMessage resolves to an empty array', async () => {
+ mockDownloadMediaFromRawMessage.mockResolvedValue([]);
+ const client = createClient();
+ const result = await client.extractFiles!(makeMessage({ item_list: [{ type: 99 }] }));
+ expect(mockDownloadMediaFromRawMessage).toHaveBeenCalledTimes(1);
+ expect(result).toBeUndefined();
+ });
+
+ it('maps file attachments preserving name + size', async () => {
+ const buffer = Buffer.from('pdf-bytes');
+ mockDownloadMediaFromRawMessage.mockResolvedValue([
+ {
+ buffer,
+ mimeType: 'application/pdf',
+ name: 'report.pdf',
+ size: 4096,
+ type: 'file',
+ url: '',
+ },
+ ]);
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ item_list: [
+ {
+ file_item: {
+ file_name: 'report.pdf',
+ len: '4096',
+ media: { encrypt_query_param: 'enc-pdf' },
+ },
+ type: 4, // MessageItemType.FILE
+ },
+ ],
+ }),
+ );
+ expect(result).toEqual([
+ { buffer, mimeType: 'application/pdf', name: 'report.pdf', size: 4096 },
+ ]);
+ });
+
+ it('maps multiple attachments in a single message', async () => {
+ const imageBuf = Buffer.from('img');
+ 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: '' },
+ ]);
+ const client = createClient();
+ const result = await client.extractFiles!(
+ makeMessage({
+ item_list: [
+ { image_item: { media: { encrypt_query_param: 'a' } }, type: 1 },
+ { type: 2, voice_item: { media: { encrypt_query_param: 'b' } } },
+ ],
+ }),
+ );
+ expect(result).toEqual([
+ { buffer: imageBuf, mimeType: 'image/jpeg', name: 'image.jpg', size: undefined },
+ { buffer: voiceBuf, mimeType: 'audio/silk', name: undefined, size: undefined },
+ ]);
+ });
+
+ it('propagates errors from downloadMediaFromRawMessage as undefined gracefully', async () => {
+ // The helper itself swallows per-item errors; if it throws as a whole,
+ // that's an unexpected programmer error and we let it propagate.
+ // This test verifies we DON'T silently swallow whole-helper failures —
+ // we want them to surface in logs / be debuggable.
+ mockDownloadMediaFromRawMessage.mockRejectedValue(new Error('helper crashed'));
+ const client = createClient();
+ await expect(
+ client.extractFiles!(makeMessage({ item_list: [{ image_item: {}, type: 1 }] })),
+ ).rejects.toThrow('helper crashed');
+ });
+ });
});
diff --git a/src/server/services/bot/platforms/wechat/client.ts b/src/server/services/bot/platforms/wechat/client.ts
index 58fbe4845a6..608a0615245 100644
--- a/src/server/services/bot/platforms/wechat/client.ts
+++ b/src/server/services/bot/platforms/wechat/client.ts
@@ -1,12 +1,15 @@
import type { WechatRawMessage } from '@lobechat/chat-adapter-wechat';
import {
createWechatAdapter,
+ downloadMediaFromRawMessage,
MessageState,
MessageType,
WechatApiClient,
} from '@lobechat/chat-adapter-wechat';
+import type { Message } from 'chat';
import debug from 'debug';
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
import {
BOT_RUNTIME_STATUSES,
getRuntimeStatusErrorMessage,
@@ -323,6 +326,51 @@ class WechatGatewayClient implements PlatformClient {
};
}
+ /**
+ * Resolve attachments on an inbound WeChat message into `AttachmentSource[]`.
+ *
+ * Why we re-download instead of trusting the in-message buffer:
+ * the chat-adapter-wechat pre-downloads CDN media into `att.buffer` at parse
+ * time, but `Message.toJSON` strips `buffer` from attachments when the
+ * message is enqueued into Redis (see [email protected]/dist/index.js:300-344).
+ * So whenever a message round-trips through the queue (debounce always,
+ * queue when the lock is busy), the in-memory buffer is gone and we have
+ * to re-fetch from the WeChat CDN ourselves.
+ *
+ * Fortunately the original `WechatRawMessage` (with all `item_list[].media`
+ * descriptors — `encrypt_query_param` + `aes_key` + image `aeskey`) IS
+ * preserved in `message.raw` because `toJSON` keeps it intact. We hand
+ * that and our `WechatApiClient` instance to the package-exported
+ * `downloadMediaFromRawMessage` helper, which is the same code path
+ * `parseRawEvent` runs at adapter parse time — including the cascading
+ * image fallback (CDN main → thumb → direct URL).
+ */
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ const raw = (message as any).raw as WechatRawMessage | undefined;
+ if (!raw?.item_list?.length) return undefined;
+
+ log('extractFiles: msgId=%s, items=%d', (message as any).id, raw.item_list.length);
+
+ const attachments = await downloadMediaFromRawMessage(this.api, raw);
+ if (attachments.length === 0) {
+ log('extractFiles: no media items resolved for msgId=%s', (message as any).id);
+ return undefined;
+ }
+
+ log(
+ 'extractFiles: resolved %d media item(s) for msgId=%s',
+ attachments.length,
+ (message as any).id,
+ );
+
+ return attachments.map((att: any) => ({
+ buffer: att.buffer,
+ mimeType: att.mimeType,
+ name: att.name,
+ size: att.size,
+ }));
+ }
+
getMessenger(platformThreadId: string): PlatformMessenger {
const targetId = extractChatId(platformThreadId);
diff --git a/src/server/services/bot/platforms/wechat/definition.ts b/src/server/services/bot/platforms/wechat/definition.ts
index a685554eb81..b3d4cc939fb 100644
--- a/src/server/services/bot/platforms/wechat/definition.ts
+++ b/src/server/services/bot/platforms/wechat/definition.ts
@@ -5,7 +5,7 @@ import { schema } from './schema';
export const wechat: PlatformDefinition = {
id: 'wechat',
name: 'WeChat',
- connectionMode: 'persistent',
+ connectionMode: 'polling',
description: 'Connect a WeChat bot via iLink API',
documentation: {
setupGuideUrl: 'https://lobehub.com/docs/usage/channels/wechat',
diff --git a/src/server/services/bot/platforms/wechat/schema.ts b/src/server/services/bot/platforms/wechat/schema.ts
index 6e351729ac4..d67f0c62e3e 100644
--- a/src/server/services/bot/platforms/wechat/schema.ts
+++ b/src/server/services/bot/platforms/wechat/schema.ts
@@ -20,7 +20,7 @@ export const schema: FieldSchema[] = [
},
{
key: 'concurrency',
- default: 'debounce',
+ default: 'queue',
description: 'channel.concurrencyHint',
enum: ['queue', 'debounce'],
enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
diff --git a/src/server/services/gateway/GatewayManager.test.ts b/src/server/services/gateway/GatewayManager.test.ts
index 34fa95ffb89..1ab0afc87dd 100644
--- a/src/server/services/gateway/GatewayManager.test.ts
+++ b/src/server/services/gateway/GatewayManager.test.ts
@@ -60,6 +60,7 @@ const createFakeDefinition = (
credentials: [],
name: id,
id,
+ schema: [],
}) as any;
describe('GatewayManager', () => {
diff --git a/src/server/services/gateway/__tests__/GatewayManager.test.ts b/src/server/services/gateway/__tests__/GatewayManager.test.ts
index 6a853d7fa0f..df2ebeafeed 100644
--- a/src/server/services/gateway/__tests__/GatewayManager.test.ts
+++ b/src/server/services/gateway/__tests__/GatewayManager.test.ts
@@ -51,6 +51,7 @@ const fakeDefinition: PlatformDefinition = {
credentials: [],
name: 'Fake Platform',
id: 'fakeplatform',
+ schema: [],
} as any;
const FAKE_DB = {} as any;
diff --git a/src/server/services/gateway/index.ts b/src/server/services/gateway/index.ts
index 5da7e0e4509..17a0f9e4afe 100644
--- a/src/server/services/gateway/index.ts
+++ b/src/server/services/gateway/index.ts
@@ -1,6 +1,11 @@
import debug from 'debug';
-import { platformRegistry } from '../bot/platforms';
+import { getServerDB } from '@/database/core/db-adaptor';
+import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+
+import type { ConnectionMode } from '../bot/platforms';
+import { getEffectiveConnectionMode, platformRegistry } from '../bot/platforms';
import { BOT_CONNECT_QUEUE_EXPIRE_MS, BotConnectQueue } from './botConnectQueue';
import { createGatewayManager, getGatewayManager } from './GatewayManager';
import { BOT_RUNTIME_STATUSES, updateBotRuntimeStatus } from './runtimeStatus';
@@ -37,10 +42,18 @@ export class GatewayService {
userId: string,
): Promise<'started' | 'queued'> {
if (isVercel) {
+ // Load the provider so we can resolve per-provider connection mode.
+ // The platform default is only a fallback — Slack/Feishu (default websocket)
+ // can be configured for webhook mode per provider, and vice versa.
const definition = platformRegistry.getPlatform(platform);
- const connectionMode = definition?.connectionMode || 'webhook';
+ const serverDB = await getServerDB();
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const model = new AgentBotProviderModel(serverDB, userId, gateKeeper);
+ const provider = await model.findEnabledByApplicationId(platform, applicationId);
+
+ const connectionMode = getEffectiveConnectionMode(definition, provider?.settings);
- if (connectionMode === 'persistent') {
+ if (connectionMode !== 'webhook') {
// Persistent platforms (e.g. Discord gateway or WeChat long-polling) cannot run in a
// serverless function — queue for the long-running cron gateway.
const queue = new BotConnectQueue();
@@ -79,11 +92,24 @@ export class GatewayService {
return 'started';
}
- async stopClient(platform: string, applicationId: string): Promise<void> {
+ async stopClient(platform: string, applicationId: string, userId?: string): Promise<void> {
if (isVercel) {
+ // Without a userId we cannot resolve per-provider settings; fall back to the
+ // platform default to decide if a queue cleanup is even worth attempting.
+ // queue.remove is a no-op for absent keys, so a stale check is harmless.
+ let connectionMode: ConnectionMode;
const definition = platformRegistry.getPlatform(platform);
- const connectionMode = definition?.connectionMode || 'webhook';
- if (connectionMode === 'persistent') {
+ if (userId) {
+ const serverDB = await getServerDB();
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const model = new AgentBotProviderModel(serverDB, userId, gateKeeper);
+ const provider = await model.findEnabledByApplicationId(platform, applicationId);
+ connectionMode = getEffectiveConnectionMode(definition, provider?.settings);
+ } else {
+ connectionMode = getEffectiveConnectionMode(definition, undefined);
+ }
+
+ if (connectionMode !== 'webhook') {
const queue = new BotConnectQueue();
await queue.remove(platform, applicationId);
}