Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

Feishu: catch up on messages sent while the app was offline

Marla9f47b8897f99
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.md
index 227649f..3a67c9c 100644
--- a/docs/design/background-tasks-and-proactive.md
+++ b/docs/design/background-tasks-and-proactive.md
@@ -667,6 +667,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);
| Job runs forever | Killed 30 minutes after the turn ended; the session is told at its next turn |
| Approval or question never answered | Blocking approval: rejected at its TTL; the task fails with 「批准超时」. Task question: stays in needs-you; no reminders; the task is archived after 14 days (Q9) |
| Delivery fails (Feishu API, channel logged out) | Retries at 5 s doubling to 300 s; after 3 failures: needs-you `delivery`. Dropped only when the conversation no longer exists |
+| Feishu messages sent while the app is offline | The long connection doesn't re-push them (the SDK reconnects with no position; the platform only re-pushes events it delivered that weren't acked within 3 s). On start and on every reconnect the app reads each Feishu chat active in the last 7 days from history: messages from the last 24 h after the last one it saw, at most 20 per chat, through the normal inbound pipeline and dedupe. Without the history scope it says so once and carries on |
| WeChat window closed or no quota | Held, piggybacked on the next inbound, shown in needs-you ([WeChat](#wechat-the-hard-constraint)) |
| A rule floods (bad instruction) | Coalescing, the daily cap, then a digest; 3 failures in a row pause it; the monthly budget pauses it |
| Rule edited during a run | The run finishes under its recorded version; the next run uses the new version |
diff --git a/docs/development.md b/docs/development.md
index 6fa2367..541681d 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -183,6 +183,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令
- `im:message.p2p_msg:readonly`(读取用户发给机器人的单聊消息)
- `im:message:send_as_bot`(以应用身份发消息)
- `cardkit:card:write`(创建与更新卡片,用于流式回复)
+ - `im:message.history:readonly`(读取会话历史消息:飞书长连接不补推离线时发来的消息,程序启动、断线重连时从历史里补上 7 天内有过来往的单聊里、24 小时内的消息,每个会话最多 20 条;没开也能用,只是补不上,会提示一次)
3. 先在本程序信息面板的「渠道 → 飞书」里填入 App ID / App Secret 并保存(长连接需要程序在线才能保存下一步)。
4. 事件与回调 → 订阅方式选「**使用长连接接收事件**」,添加事件 `im.message.receive_v1`。
5. 发布版本并在可用范围内添加自己,然后用你自己的飞书私聊机器人发一句话:连上后第一个发消息的人就是飞书主人(见「谁能使用机器人」)。
diff --git a/docs/development_en.md b/docs/development_en.md
index 20a8330..0fb6d4b 100644
--- a/docs/development_en.md
+++ b/docs/development_en.md
@@ -183,6 +183,7 @@ Each bot can turn computer use on or off, choose a backend and an approval mode
- `im:message.p2p_msg:readonly` (read one-to-one messages users send to the bot)
- `im:message:send_as_bot` (send messages as the app)
- `cardkit:card:write` (create and update cards, used for streaming replies)
+ - `im:message.history:readonly` (read chat history: the long connection doesn't re-push messages sent while the app was offline, so on start and after a reconnect the app catches up from history on chats active in the last 7 days, taking messages from the last 24 hours, at most 20 per chat. Without it everything else works, but nothing is caught up, and the app says so once)
3. First enter the App ID / App Secret in this app's info panel → Channels → Feishu and save (the long connection must be online before the next step can be saved).
4. Events & callbacks → subscription mode: "**Receive events through persistent connection**", and add the event `im.message.receive_v1`.
5. Publish a version, add yourself to the availability scope, then send the bot one line from your own Feishu: the first person to message it after it is connected becomes its Feishu owner (see "Who can use a bot").
diff --git a/src/app.ts b/src/app.ts
index c95319e..fb7d2ca 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -707,8 +707,10 @@ export class App {
this.channels.set(botId, ch);
if (bot.feishuAppId && bot.feishuAppSecret && !ch.feishu) {
const transport = this.opts.feishuTransport?.(bot) ?? new LarkTransport(bot.feishuAppId, bot.feishuAppSecret);
- ch.feishu = new FeishuChannel(bot.id, transport, this.runtime, this.queue, this.config.feishu.throttleMs, this.outbox);
+ ch.feishu = new FeishuChannel(bot.id, transport, this.runtime, this.queue, this.config.feishu.throttleMs, this.outbox, this.store);
ch.feishu.delivery = this.delivery;
+ // 读不了飞书的历史消息:离线时发来的补不上,提示一次
+ ch.feishu.onHistoryDenied = () => this.notice("warn", t("app.feishu_history_denied", { name: this.store.getBot(bot.id)?.name ?? bot.name }));
// 代理自己醒来的一轮(后台命令结束):经出站队列回复到这个会话最近收到的那条消息
const fs = ch.feishu;
this.runtime.registerReplier(bot.id, "feishu", (conv, handle, key) => (handle?.messageId ? { out: fs.followUp(conv.peerId, handle.messageId, key) } : undefined));
diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.ts
index 4e32656..ecc4472 100644
--- a/src/channels/feishu/channel.ts
+++ b/src/channels/feishu/channel.ts
@@ -1,7 +1,7 @@
import type { ChannelCapabilities, ChannelStatus, InboundEvent, Part, ReplySession } from "../../core/types.js";
import { Dedup, KeyedQueue } from "../../core/queue.js";
import type { BotRuntime } from "../../core/runtime.js";
-import type { FeishuMessageEvent, FeishuTransport } from "./transport.js";
+import { HistoryDenied, type FeishuMessageEvent, type FeishuTransport } from "./transport.js";
import { FeishuReply, deliverFeishu } from "./card.js";
import { Outbox, stableId } from "../../core/outbox.js";
import type { Delivery } from "../../core/delivery.js";
@@ -9,6 +9,11 @@ import type { Store } from "../../store/db.js";
import { logger } from "../../log.js";
import { t } from "../../i18n/index.js";
+/** 离线补消息:只看这么久之内有过来往的会话、这么久之内发的消息,每个会话最多这么多条 */
+export const CATCH_UP_ACTIVE_MS = 7 * 86400_000;
+export const CATCH_UP_WINDOW_MS = 24 * 3600_000;
+export const CATCH_UP_MAX = 20;
+
export const FEISHU_CAPS: ChannelCapabilities = {
streaming: true,
cards: true,
@@ -62,7 +67,11 @@ export class FeishuChannel {
readonly outbox: Outbox;
/** 主动消息的送达规则(App 设):对方发消息时,排着的主动消息先发,合成一条摘要 */
delivery: Delivery | undefined;
+ /** 读不了历史消息(离线时漏掉的补不上):App 显示一条提示;直到读得了之前只提示一次 */
+ onHistoryDenied: (() => void) | undefined;
private unregister: (() => void) | undefined;
+ /** 正在补离线时漏掉的消息 */
+ private catching: Promise<number> | undefined;
constructor(
private botId: string,
@@ -71,7 +80,7 @@ export class FeishuChannel {
private queue: KeyedQueue,
private throttleMs = 400,
outbox?: Outbox,
- store?: Store,
+ private store?: Store,
) {
if (outbox) this.outbox = outbox;
else {
@@ -89,6 +98,8 @@ export class FeishuChannel {
(state, detail) => {
this.status = { state, detail, since: Date.now() };
this.log.info(`bot ${this.botId} ws ${state}`, detail ? { detail } : undefined);
+ // 连上(启动、断线重连):长连接不补推离线时的事件,自己去会话历史里补
+ if (state === "connected") void this.catchUp().catch((e) => this.log.warn("feishu catch-up failed", { message: (e as Error).message.slice(0, 200) }));
},
(a) => this.runtime.cardAction(this.botId, a.value, `feishu:${a.operatorOpenId}`),
);
@@ -101,10 +112,11 @@ export class FeishuChannel {
this.status = { state: "disabled", since: Date.now() };
}
- /** 同步返回(ack),处理放入每会话串行队列。 */
- onMessage(ev: FeishuMessageEvent): void {
- if (!ev.messageId || !this.dedup.firstSeen(ev.messageId)) return;
- if (ev.chatType !== "p2p") return; // P1:仅单聊
+ /** 同步返回(ack),处理放入每会话串行队列。返回这条是不是第一次见到 */
+ onMessage(ev: FeishuMessageEvent): boolean {
+ if (!ev.messageId || !this.dedup.firstSeen(ev.messageId)) return false;
+ this.markSeen(ev);
+ if (ev.chatType !== "p2p") return true; // P1:仅单聊
const inbound: InboundEvent = {
id: ev.messageId,
channel: "feishu",
@@ -128,7 +140,7 @@ export class FeishuChannel {
this.pending.add(p);
void p.finally(() => this.pending.delete(p));
}
- if (intercepted.handled) return;
+ if (intercepted.handled) return true;
const p = this.queue.run(`feishu:${this.botId}:${ev.chatId}`, async () => {
const reply = new FeishuReply(this.transport, ev.messageId, this.throttleMs, { outbox: this.outbox, botId: this.botId, chatId: ev.chatId, key: ev.messageId });
try {
@@ -140,6 +152,75 @@ export class FeishuChannel {
});
this.pending.add(p);
void p.finally(() => this.pending.delete(p));
+ return true;
+ }
+
+ /** 这个会话见到的最后一条消息(离线补消息从它之后开始;存在 KV 里,重启也在) */
+ private seenKey(chatId: string): string {
+ return `feishu-seen:${this.botId}:${chatId}`;
+ }
+ private seen(chatId: string): { at: number; id: string } | undefined {
+ try {
+ const v = JSON.parse(this.store?.getKV(this.seenKey(chatId)) || "null");
+ return v && Number(v.at) > 0 ? { at: Number(v.at), id: String(v.id ?? "") } : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ private markSeen(ev: FeishuMessageEvent): void {
+ if (!this.store || !ev.chatId || !(ev.createTime > 0)) return;
+ if ((this.seen(ev.chatId)?.at ?? 0) > ev.createTime) return;
+ this.store.setKV(this.seenKey(ev.chatId), JSON.stringify({ at: ev.createTime, id: ev.messageId }));
+ }
+
+ /**
+ * 补离线时漏掉的消息(启动、断线重连时):飞书长连接不补推离线时发来的事件,从会话历史里取回来,和收到的一样走一遍
+ * (去重、准入、群里只认 @ 机器人的规则都照旧)。只看 7 天内有过来往的飞书会话,只取 24 小时内、见到的最后一条之后的,
+ * 每个会话最多 20 条。没有读历史消息的权限:记一次日志、提示一次,渠道照常。返回补了几条
+ */
+ catchUp(now = Date.now()): Promise<number> {
+ this.catching ??= this.catchUpOnce(now).finally(() => (this.catching = undefined));
+ return this.catching;
+ }
+
+ private async catchUpOnce(now: number): Promise<number> {
+ const store = this.store;
+ const list = this.transport.listMessages?.bind(this.transport);
+ if (!store || !list) return 0;
+ let fed = 0;
+ const convs = store.listConversations(this.botId).filter((c) => c.channel === "feishu" && c.updatedAt >= now - CATCH_UP_ACTIVE_MS);
+ for (const c of convs) {
+ // 见到的最后一条之后;还没记过(升级前的会话)就从最后一次来往之后
+ const seen = this.seen(c.peerId);
+ const since = Math.max(seen?.at ?? c.updatedAt, now - CATCH_UP_WINDOW_MS);
+ let missed: FeishuMessageEvent[];
+ try {
+ missed = await list(c.peerId, { since, limit: CATCH_UP_MAX, chatType: c.kind === "group" ? "group" : "p2p" });
+ } catch (e) {
+ if (e instanceof HistoryDenied) {
+ this.historyDenied(e.message);
+ return fed;
+ }
+ this.log.warn("feishu catch-up: could not read the chat history", { bot: this.botId, message: (e as Error).message.slice(0, 200) });
+ continue;
+ }
+ store.deleteKV(this.deniedKey);
+ for (const ev of missed.slice(-CATCH_UP_MAX)) if (ev.messageId !== seen?.id && this.onMessage({ ...ev, chatId: ev.chatId || c.peerId })) fed++;
+ }
+ if (fed) this.log.info("caught up on feishu messages sent while offline", { bot: this.botId, count: fed });
+ return fed;
+ }
+
+ private get deniedKey(): string {
+ return `feishu-history-denied:${this.botId}`;
+ }
+
+ /** 读不了历史消息:日志和提示各一次(读得了之后再没权限会再提示) */
+ private historyDenied(detail: string): void {
+ if (this.store?.getKV(this.deniedKey)) return;
+ this.store?.setKV(this.deniedKey, String(Date.now()));
+ this.log.warn("feishu catch-up: the app may not read chat history; messages sent while offline are not caught up", { bot: this.botId, detail: detail.slice(0, 200) });
+ this.onHistoryDenied?.();
}
/**
diff --git a/src/channels/feishu/transport.ts b/src/channels/feishu/transport.ts
index b82853d..cf3c6a5 100644
--- a/src/channels/feishu/transport.ts
+++ b/src/channels/feishu/transport.ts
@@ -23,6 +23,30 @@ export interface FeishuMessageEvent {
createTime: number;
}
+/** 读不了会话的历史消息(应用没开 im:message.history:readonly 这类权限、机器人不在群里、用户不在可用范围):离线补消息做不了 */
+export class HistoryDenied extends Error {}
+
+/** 飞书说的「没权限」:HTTP 403,缺权限范围(99991672 / 99991679)、缺必要权限(230027)、不在群里(230002)、不在可用范围(230013) */
+export function historyDenied(status: number | undefined, code: number | undefined, msg = ""): boolean {
+ if (status === 403) return true;
+ if (code !== undefined && [99991672, 99991679, 230027, 230002, 230013].includes(code)) return true;
+ return /scope|permission|access denied|权限/i.test(msg);
+}
+
+/** 会话历史里的一条(im.v1.message.list 的 item)→ FeishuMessageEvent;chatType 由调用方给(列表里没有) */
+export function historyEvent(m: any, chatType: string): FeishuMessageEvent {
+ return {
+ messageId: String(m?.message_id ?? ""),
+ chatId: String(m?.chat_id ?? ""),
+ chatType,
+ messageType: String(m?.msg_type ?? ""),
+ content: m?.body?.content ?? "{}",
+ senderOpenId: m?.sender?.id_type === "open_id" ? String(m.sender.id ?? "") : "",
+ mentions: (m?.mentions ?? []).map((x: any) => ({ key: x.key, name: x.name, openId: x.id_type === "open_id" ? x.id : undefined })),
+ createTime: Number(m?.create_time ?? 0),
+ };
+}
+
/**
* 飞书传输层抽象(便于离线测试用 mock 替换)。
* 真实实现:WSClient 长连接接收事件 + OpenAPI(CardKit 流式卡片 / 文本回复)。
@@ -54,6 +78,11 @@ export interface FeishuTransport {
replyFile?(replyToMessageId: string, filePath: string, uuid?: string): Promise<void>;
/** 主动发一条文本到会话(不是回复某条消息;用于余额提醒、使用请求通知) */
sendText?(chatId: string, text: string, uuid?: string): Promise<void>;
+ /**
+ * 离线时漏掉的消息(长连接不补推离线时的事件):会话里 since(毫秒)之后用户发的消息,旧的在前,最多 limit 条(最新的那几条);
+ * 机器人自己发的、撤回的不算。读不了历史消息时抛 HistoryDenied
+ */
+ listMessages?(chatId: string, o: { since: number; limit: number; chatType: string }): Promise<FeishuMessageEvent[]>;
}
export const CARD_ELEMENT_ID = "md";
@@ -173,6 +202,7 @@ export class LarkTransport implements FeishuTransport {
onReady: () => onState("connected"),
onError: (err: Error) => onState("error", err?.message),
onReconnecting: () => onState("connecting", "reconnecting"),
+ onReconnected: () => onState("connected", "reconnected"),
} as any);
await this.ws.start({ eventDispatcher: dispatcher });
}
@@ -265,6 +295,27 @@ export class LarkTransport implements FeishuTransport {
check(res, "im.message.reply(text)");
}
+ async listMessages(chatId: string, o: { since: number; limit: number; chatType: string }): Promise<FeishuMessageEvent[]> {
+ let res: any;
+ try {
+ res = await this.client.im.v1.message.list({
+ params: { container_id_type: "chat", container_id: chatId, start_time: String(Math.floor(o.since / 1000)), sort_type: "ByCreateTimeDesc", page_size: Math.min(50, Math.max(1, o.limit)) },
+ });
+ } catch (e) {
+ const r = (e as { response?: { status?: number; data?: { code?: number; msg?: string } } }).response;
+ if (historyDenied(r?.status, r?.data?.code, r?.data?.msg)) throw new HistoryDenied(`im.message.list denied: code=${r?.data?.code ?? r?.status} msg=${r?.data?.msg ?? ""}`);
+ throw e;
+ }
+ if (res?.code && historyDenied(undefined, res.code, res.msg)) throw new HistoryDenied(`im.message.list denied: code=${res.code} msg=${res.msg}`);
+ check(res, "im.message.list");
+ const items: any[] = res?.data?.items ?? [];
+ return items
+ .filter((m) => m?.sender?.sender_type === "user" && !m.deleted)
+ .map((m) => historyEvent(m, o.chatType))
+ .filter((ev) => ev.messageId && ev.createTime > o.since)
+ .reverse();
+ }
+
async sendText(chatId: string, text: string, uuid?: string): Promise<void> {
const res: any = await this.client.im.v1.message.create({
params: { receive_id_type: "chat_id" },
diff --git a/src/i18n/messages/app.ts b/src/i18n/messages/app.ts
index e56fba6..a386794 100644
--- a/src/i18n/messages/app.ts
+++ b/src/i18n/messages/app.ts
@@ -9,6 +9,7 @@ export const zh = {
default_bot_name: "我的助手",
default_bot_prompt: "你是一个乐于助人的中文助手,回答简洁准确。",
feishu_failed: "机器人「{name}」飞书长连接启动失败:{message}",
+ feishu_history_denied: "机器人「{name}」读不到飞书的历史消息,离线时发来的消息补不上。在飞书开放平台给应用开通 im:message.history:readonly 权限即可。",
weixin_expired: "机器人「{name}」微信登录已过期,请在信息面板的「渠道」里重新扫码",
weixin_connected: "机器人「{name}」微信已连接",
// 收到的消息里图片 / 文件 / 语音的占位(core/types.ts eventText)
@@ -33,6 +34,7 @@ export const en: Catalog<typeof zh> = {
default_bot_name: "My Assistant",
default_bot_prompt: "You are a helpful assistant. Answer concisely and accurately.",
feishu_failed: "Bot \"{name}\": Feishu long connection failed to start: {message}",
+ feishu_history_denied: "Bot \"{name}\" can't read Feishu message history, so messages sent while it was offline can't be caught up. Grant the app the im:message.history:readonly scope in the Feishu Open Platform.",
weixin_expired: "Bot \"{name}\": WeChat sign-in expired. Scan the QR code again under Channels in the info panel",
weixin_connected: "Bot \"{name}\": WeChat connected",
media_image: "Image",
diff --git a/test/feishu-catchup.e2e.test.ts b/test/feishu-catchup.e2e.test.ts
new file mode 100644
index 0000000..6db9cb2
--- /dev/null
+++ b/test/feishu-catchup.e2e.test.ts
@@ -0,0 +1,190 @@
+/**
+ * 飞书离线时漏掉的消息:长连接不补推离线时发来的事件(SDK 重连时不带任何位置,开放平台只对推了没回 200 的重推),
+ * 所以启动、断线重连时从会话历史里补。真实 App(纯对话 + mock 模型)+ 假飞书传输层:
+ * 只补见到的最后一条之后、24 小时内的,每个会话最多 20 条,7 天内有过来往的会话才看;补上的和收到的走同一条路
+ * (去重、准入、群里的规则照旧);没有读历史消息的权限时记一次、提示一次,渠道照常。另外:真实传输层怎么读历史、怎么认没权限。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { HistoryDenied, LarkTransport, historyDenied, historyEvent } from "../src/channels/feishu/transport.js";
+import { CATCH_UP_MAX } from "../src/channels/feishu/channel.js";
+import { FakeFeishu, feishuEvent, mockOpenAI, until } from "./helpers.js";
+
+const H = 3600_000;
+
+describe("飞书离线补消息(假传输层)", () => {
+ let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+ let app: App;
+ let dataDir: string;
+ const feishu = new FakeFeishu();
+ const ch = () => app.channels.get("default")!.feishu!;
+ /** 模型收到的每次请求里最后一条用户消息 */
+ const asked = (from = 0) => llm.calls.slice(from).map((c) => String(c.messages.at(-1)?.content ?? ""));
+ const settle = async () => {
+ await new Promise((r) => setTimeout(r, 50));
+ await ch().idle();
+ };
+ /** 一条历史里的用户消息 */
+ const msg = (chatId: string, id: string, text: string, at: number, extra: Record<string, unknown> = {}) => ({ ...feishuEvent(text, { chatId, messageId: id, createTime: at }), ...extra });
+
+ beforeAll(async () => {
+ llm = await mockOpenAI({ key: "gw-key" });
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-feishu-catchup-"));
+ process.env.FEISHU_APP_ID = "cli_test";
+ process.env.FEISHU_APP_SECRET = "secret_test";
+ app = new App(loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_FEISHU_THROTTLE_MS: "30", AMB_AGENT: "off" } }), {
+ feishuTransport: () => feishu,
+ printQrToTerminal: false,
+ });
+ await app.start();
+ delete process.env.FEISHU_APP_ID;
+ delete process.env.FEISHU_APP_SECRET;
+ });
+
+ afterAll(async () => {
+ await app?.stop();
+ await llm?.close();
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ it("离线时发来的:重连后从历史里补上、照常回复;只补见到的最后一条之后的,最多 20 条,按先后;再连一次、平台又推一次都不重复", async () => {
+ const now = Date.now();
+ // 主人在线时说过一句(连上后第一个发单聊的人就是主人)
+ const first = msg("oc_chat1", "om_first", "你好", now - 3 * H);
+ feishu.onMessage!(first);
+ await settle();
+ const before = llm.calls.length;
+ expect(asked(before - 1)).toEqual(["你好"]);
+ // 离线时:主人又发了 25 条;历史里还有机器人自己的一条和之前那条
+ const missed = Array.from({ length: 25 }, (_, i) => msg("oc_chat1", `om_off${i + 1}`, `离线 ${i + 1}`, now - 2 * H + i * 10_000));
+ feishu.history.set("oc_chat1", [first, ...missed, msg("oc_chat1", "om_bot", "机器人的回复", now - H, { senderType: "app" })]);
+ feishu.reconnect();
+ await until(() => llm.calls.length - before >= CATCH_UP_MAX, 15_000);
+ await settle();
+ // 最新的 20 条,按先后;每条都回复在它自己下面
+ expect(asked(before)).toEqual(missed.slice(-CATCH_UP_MAX).map((m) => m.content && JSON.parse(m.content).text));
+ const repliedTo = new Set(feishu.calls.filter((c) => c.op === "reply").map((c) => c.args[0]));
+ for (const m of missed.slice(-CATCH_UP_MAX)) expect(repliedTo.has(m.messageId)).toBe(true);
+ expect(feishu.listed.at(-1)).toMatchObject({ chatId: "oc_chat1", since: first.createTime, limit: CATCH_UP_MAX, chatType: "p2p" });
+ // 再连一次:从见到的最后一条之后取,什么都不补;平台把其中一条又推了一次:去重
+ const after = llm.calls.length;
+ feishu.reconnect();
+ await settle();
+ expect(feishu.listed.at(-1)!.since).toBe(missed.at(-1)!.createTime);
+ feishu.onMessage!(missed.at(-1)!);
+ await settle();
+ expect(llm.calls.length).toBe(after);
+ });
+
+ it("7 天内有过来往的会话才看;24 小时之前的不补;群聊和没被允许的人照常的规则:群消息不处理,陌生人只收到一句提示", async () => {
+ const now = Date.now();
+ const store = app.store;
+ const db = (store as any).db;
+ // 一个 8 天没来往的会话:不看
+ store.ensureConversation("default", "feishu", "oc_old", "老会话");
+ db.prepare("UPDATE conversations SET updated_at = ? WHERE id = ?").run(now - 8 * 24 * H, "default:feishu:oc_old");
+ feishu.history.set("oc_old", [msg("oc_old", "om_old1", "很久以前", now - H)]);
+ // 允许的人,最后见到的是 3 天前:只补 24 小时内的
+ app.access.allow("default", "feishu", "oc_day", "test");
+ store.ensureConversation("default", "feishu", "oc_day", "同事");
+ store.setKV("feishu-seen:default:oc_day", JSON.stringify({ at: now - 72 * H, id: "om_day0" }));
+ feishu.history.set("oc_day", [msg("oc_day", "om_day1", "两天前的", now - 30 * H), msg("oc_day", "om_day2", "两小时前的", now - 2 * H)]);
+ // 群聊(目前只处理单聊):@ 了机器人的也不处理
+ store.ensureConversation("default", "feishu", "oc_group", "群", "group");
+ store.setKV("feishu-seen:default:oc_group", JSON.stringify({ at: now - 3 * H, id: "om_g0" }));
+ feishu.history.set("oc_group", [msg("oc_group", "om_g1", "@小蓝 帮个忙", now - H, { mentions: [{ key: "@_user_1", name: "小蓝", openId: "ou_bot" }] })]);
+ // 不在允许名单里的人:照常只回一句,不进模型
+ store.ensureConversation("default", "feishu", "oc_stranger", "陌生人");
+ store.setKV("feishu-seen:default:oc_stranger", JSON.stringify({ at: now - 3 * H, id: "om_s0" }));
+ feishu.history.set("oc_stranger", [msg("oc_stranger", "om_s1", "在吗", now - H, { senderOpenId: "ou_stranger" })]);
+ // 还没记过见到哪一条(升级前就有的会话):从最后一次来往之后取,之前的不重放
+ store.ensureConversation("default", "feishu", "oc_new", "新会话");
+ app.access.allow("default", "feishu", "oc_new", "test");
+ feishu.history.set("oc_new", [msg("oc_new", "om_n1", "早就回过的", now - H)]);
+ const before = llm.calls.length;
+ const listedBefore = feishu.listed.length;
+ feishu.reconnect();
+ await until(() => llm.calls.length > before, 10_000);
+ await settle();
+ const listed = feishu.listed.slice(listedBefore);
+ expect(listed.map((l) => l.chatId).sort()).toEqual(["oc_chat1", "oc_day", "oc_group", "oc_new", "oc_stranger"]);
+ expect(listed.find((l) => l.chatId === "oc_group")!.chatType).toBe("group");
+ expect(now - 24 * H - listed.find((l) => l.chatId === "oc_day")!.since).toBeLessThanOrEqual(1000);
+ expect(asked(before)).toEqual(["两小时前的"]);
+ expect(feishu.texts.at(-1)).toMatch(/还没有被允许使用这个机器人/);
+ expect(feishu.calls.filter((c) => c.op === "text" && c.args[0] === "om_s1")).toHaveLength(1);
+ });
+
+ it("没有读历史消息的权限:记一次、提示一次,渠道照常收发;有了权限之后再没有,会再提示", async () => {
+ const notices = () => app.recentNotices.filter((n) => n.text.includes("读不到飞书的历史消息"));
+ feishu.denyHistory = true;
+ feishu.reconnect();
+ await settle();
+ feishu.reconnect();
+ await settle();
+ expect(notices()).toHaveLength(1);
+ expect(notices()[0]).toMatchObject({ level: "warn" });
+ expect(notices()[0].text).toContain("im:message.history:readonly");
+ expect(ch().status.state).toBe("connected");
+ // 渠道照常
+ const before = llm.calls.length;
+ feishu.onMessage!(msg("oc_chat1", "om_live", "还在吗", Date.now()));
+ await settle();
+ expect(asked(before)).toEqual(["还在吗"]);
+ // 开了权限:不再提示;之后又没了:再提示一次
+ feishu.denyHistory = false;
+ feishu.reconnect();
+ await settle();
+ feishu.denyHistory = true;
+ feishu.reconnect();
+ await settle();
+ expect(notices()).toHaveLength(2);
+ feishu.denyHistory = false;
+ });
+});
+
+describe("飞书传输层:读会话历史", () => {
+ const item = (id: string, at: number, extra: Record<string, unknown> = {}) => ({
+ message_id: id,
+ chat_id: "oc_1",
+ msg_type: "text",
+ create_time: String(at),
+ sender: { id: "ou_1", id_type: "open_id", sender_type: "user" },
+ body: { content: JSON.stringify({ text: id }) },
+ mentions: [{ key: "@_user_1", id: "ou_bot", id_type: "open_id", name: "小蓝" }],
+ ...extra,
+ });
+ const lark = (list: (payload: any) => Promise<any>) => {
+ const t = new LarkTransport("cli_x", "secret_x");
+ (t as any).client = { im: { v1: { message: { list } } } };
+ return t;
+ };
+
+ it("按秒问、最新的在前;只要用户发的、没撤回的、晚于上次见到的,旧的在前交回;事件的样子和收到的一样", async () => {
+ let params: any;
+ const t = lark(async (p) => {
+ params = p.params;
+ return { code: 0, data: { items: [item("om_4", 4500), item("om_bot", 4000, { sender: { id: "cli_x", id_type: "app_id", sender_type: "app" } }), item("om_del", 3500, { deleted: true }), item("om_2", 2500), item("om_1", 2000)] } };
+ });
+ const out = await t.listMessages("oc_1", { since: 2000, limit: 20, chatType: "p2p" });
+ expect(params).toEqual({ container_id_type: "chat", container_id: "oc_1", start_time: "2", sort_type: "ByCreateTimeDesc", page_size: 20 });
+ expect(out.map((e) => e.messageId)).toEqual(["om_2", "om_4"]);
+ expect(out[0]).toEqual({ messageId: "om_2", chatId: "oc_1", chatType: "p2p", messageType: "text", content: '{"text":"om_2"}', senderOpenId: "ou_1", mentions: [{ key: "@_user_1", name: "小蓝", openId: "ou_bot" }], createTime: 2500 });
+ expect(historyEvent({ message_id: "x", sender: { id: "u", id_type: "user_id" } }, "group")).toMatchObject({ senderOpenId: "", chatType: "group", content: "{}", mentions: [] });
+ });
+
+ it("没权限(HTTP 403、缺权限范围、缺必要权限、机器人不在群里)抛 HistoryDenied;别的错误照常抛", async () => {
+ const http = (status: number, code: number, msg: string) => lark(async () => Promise.reject(Object.assign(new Error(`Request failed with status code ${status}`), { response: { status, data: { code, msg } } })));
+ await expect(http(400, 99991672, "Access denied. One of the following scopes is required: [im:message.history:readonly]").listMessages("oc_1", { since: 0, limit: 20, chatType: "p2p" })).rejects.toBeInstanceOf(HistoryDenied);
+ await expect(http(403, 0, "forbidden").listMessages("oc_1", { since: 0, limit: 20, chatType: "p2p" })).rejects.toBeInstanceOf(HistoryDenied);
+ await expect(lark(async () => ({ code: 230027, msg: "Lack of necessary permissions." })).listMessages("oc_1", { since: 0, limit: 20, chatType: "p2p" })).rejects.toBeInstanceOf(HistoryDenied);
+ const other = lark(async () => ({ code: 230001, msg: "invalid param" })).listMessages("oc_1", { since: 0, limit: 20, chatType: "p2p" });
+ await expect(other).rejects.toThrow(/im.message.list failed: code=230001/);
+ await expect(other).rejects.not.toBeInstanceOf(HistoryDenied);
+ expect([historyDenied(undefined, 230002), historyDenied(undefined, 230013), historyDenied(500, 1, "internal error"), historyDenied(undefined, undefined, "缺少权限")]).toEqual([true, true, false, true]);
+ });
+});
diff --git a/test/helpers.ts b/test/helpers.ts
index 1760389..2297dd2 100644
--- a/test/helpers.ts
+++ b/test/helpers.ts
@@ -1,7 +1,7 @@
import http from "node:http";
import crypto from "node:crypto";
import type { AddressInfo } from "node:net";
-import type { FeishuMessageEvent, FeishuTransport } from "../src/channels/feishu/transport.js";
+import { HistoryDenied, type FeishuMessageEvent, type FeishuTransport } from "../src/channels/feishu/transport.js";
export async function listen(handler: http.RequestListener): Promise<{ url: string; port: number; close: () => Promise<void>; server: http.Server }> {
const server = http.createServer(handler);
@@ -224,11 +224,31 @@ export class FakeFeishu implements FeishuTransport {
failCreate = false;
failFinish = false;
onMessage: ((ev: FeishuMessageEvent) => void) | undefined;
+ private onState: ((s: "connecting" | "connected" | "error", d?: string) => void) | undefined;
private n = 0;
- async start(onMessage: (ev: FeishuMessageEvent) => void, onState: (s: "connecting" | "connected" | "error") => void) {
+ async start(onMessage: (ev: FeishuMessageEvent) => void, onState: (s: "connecting" | "connected" | "error", d?: string) => void) {
this.onMessage = onMessage;
+ this.onState = onState;
onState("connected");
}
+ /** 断线重连(长连接又连上了) */
+ reconnect() {
+ this.onState?.("connecting", "reconnecting");
+ this.onState?.("connected", "reconnected");
+ }
+ /** 会话历史(离线补消息):chatId → 消息(senderType 默认 user);denyHistory 时像没开权限一样抛 HistoryDenied */
+ history = new Map<string, Array<FeishuMessageEvent & { senderType?: string }>>();
+ denyHistory = false;
+ listed: Array<{ chatId: string; since: number; limit: number; chatType: string }> = [];
+ async listMessages(chatId: string, o: { since: number; limit: number; chatType: string }) {
+ this.listed.push({ chatId, ...o });
+ if (this.denyHistory) throw new HistoryDenied("im.message.list denied: code=99991672 msg=Access denied. One of the following scopes is required");
+ return (this.history.get(chatId) ?? [])
+ .filter((m) => (m.senderType ?? "user") === "user" && m.createTime > o.since)
+ .sort((a, b) => a.createTime - b.createTime)
+ .slice(-o.limit)
+ .map(({ senderType: _s, ...m }) => ({ ...m, chatType: o.chatType }));
+ }
async stop() {}
async createStreamingCard(initial: string) {
this.calls.push({ op: "create", args: [initial] });
@@ -270,7 +290,7 @@ export function feishuEvent(text: string, opts: Partial<FeishuMessageEvent> = {}
content: opts.content ?? JSON.stringify({ text }),
senderOpenId: opts.senderOpenId ?? "ou_user1",
mentions: opts.mentions ?? [],
- createTime: Date.now(),
+ createTime: opts.createTime ?? Date.now(),
};
}
diff --git a/ui/locales/en/info.js b/ui/locales/en/info.js
index 5a834bf..554ff45 100644
--- a/ui/locales/en/info.js
+++ b/ui/locales/en/info.js
@@ -25,7 +25,7 @@ export default {
disconnect: "Disconnect",
disconnectTitle: "Disconnect Feishu?",
disconnectBody: "This removes the bot's Feishu App ID and App Secret.",
- setupHint: "In the Feishu Open Platform, enable the Bot capability, set event subscription to “Receive events through long connection”, and subscribe to {event}. Permissions: {p1}, {p2}, {p3}.",
+ setupHint: "In the Feishu Open Platform, enable the Bot capability, set event subscription to “Receive events through long connection”, and subscribe to {event}. Permissions: {p1}, {p2}, {p3}, {p4}.",
},
weixin: {
sub: "Official iLink channel",
diff --git a/ui/locales/zh-CN/info.js b/ui/locales/zh-CN/info.js
index ef3b1b6..bed96f1 100644
--- a/ui/locales/zh-CN/info.js
+++ b/ui/locales/zh-CN/info.js
@@ -28,7 +28,7 @@ export default {
disconnectTitle: "断开飞书?",
disconnectBody: "会清除这个机器人的飞书 App ID 与 App Secret。",
/** {event} {p1} {p2} {p3} 是 <code> 包着的事件名 / 权限名 */
- setupHint: "在飞书开放平台启用「机器人」,事件订阅选「使用长连接接收事件」并订阅 {event};权限:{p1}、{p2}、{p3}。",
+ setupHint: "在飞书开放平台启用「机器人」,事件订阅选「使用长连接接收事件」并订阅 {event};权限:{p1}、{p2}、{p3}、{p4}。",
},
weixin: {
sub: "iLink 官方通道",
diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.js
index baf5d0e..0233cf9 100644
--- a/ui/screens/info-panel.js
+++ b/ui/screens/info-panel.js
@@ -70,7 +70,7 @@ function FeishuRow({ bot, st, owner, reload }) {
${bot.feishuAppId && html`<button type="button" class="text danger" onClick=${clear}>${t("info.feishu.disconnect")}</button>`}
</div>
${bot.feishuAppId && owner === null && html`<p class="hint">${t("info.feishu.bindHint")}</p>`}
- <p class="hint">${t("info.feishu.setupHint", { event: html`<code>im.message.receive_v1</code>`, p1: html`<code>im:message.p2p_msg:readonly</code>`, p2: html`<code>im:message:send_as_bot</code>`, p3: html`<code>cardkit:card:write</code>` })}</p>
+ <p class="hint">${t("info.feishu.setupHint", { event: html`<code>im.message.receive_v1</code>`, p1: html`<code>im:message.p2p_msg:readonly</code>`, p2: html`<code>im:message:send_as_bot</code>`, p3: html`<code>cardkit:card:write</code>`, p4: html`<code>im:message.history:readonly</code>` })}</p>
</div>`}`;
}