Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server): a redelivered chat message survives a server restart without running twice (#493)

Yaowei Zheng49e09f81e691
diff --git a/changelog/unreleased/2026-08-26-backward-compatibility.md b/changelog/unreleased/2026-08-26-backward-compatibility.md
index 2405f9f3..eec666a1 100644
--- a/changelog/unreleased/2026-08-26-backward-compatibility.md
+++ b/changelog/unreleased/2026-08-26-backward-compatibility.md
@@ -3,16 +3,17 @@
- **Date:** 2026-08-26
- **Type:** process
- **Scope:** `server`
-- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490), [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)
+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490), [#493](https://github.com/Prism-Shadow/penguin-harness/pull/493), [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)
- **Breaking:** yes — one-way for the database: after two Sessions have saved the same bot account, a build from before this change can no longer open that `web.db`
[中文版](2026-08-26-backward-compatibility.zh.md)
-This batch touches two things on an existing `web.db`, both on `messaging_bindings`: the
-`idx_messaging_account` unique index it carries (every database that has opened a build with
-messaging bindings in it — 0.2.5 and later), and one added column. Only the first needs a
-decision; the second is recorded so a reader looking here for "does my database need anything?"
-finds both answers in one place.
+This batch touches three things on an existing `web.db`, all on `messaging_bindings` and all
+carried by every database that has opened a build with messaging bindings in it (0.2.5 and
+later): the `idx_messaging_account` unique index, and the absence of two added columns,
+`last_inbound_message_id` and `line_per_message`. Only the index needs a decision; the two
+columns are recorded so a reader looking here for "does my database need anything?" finds every
+answer in one place.
## The retired unique account index
@@ -31,6 +32,27 @@ is a no-op).
Nothing is asked of the user: the drop is automatic, runs on the first open of an updated build,
and no binding, credential or remembered chat is altered.
+## The added inbound watermark column
+
+[The persisted redelivery watermark](2026-08-26-messaging-inbound-watermark.md) adds
+`last_inbound_message_id` to `messaging_bindings`. A `web.db` formed by 0.2.7 or earlier has the
+table but not the column, and `CREATE TABLE IF NOT EXISTS` never alters a table that already
+exists.
+
+Chosen: **ALTER it in on open**, one `ensureColumn(db, "messaging_bindings",
+"last_inbound_message_id", "TEXT")` in the list `openDatabase` already keeps for exactly this. The
+column is nullable with no default, so every existing binding grandfathers in as `NULL` — the
+honest value for a binding whose earlier messages this build never recorded an id for. The first
+inbound message after the upgrade fills it, and the duplicate guard covers that binding from then
+on.
+
+Nothing is asked of the user, and nothing else about a binding is read or rewritten: credentials,
+intent and the remembered chat are untouched.
+
+This half downgrades cleanly. An older build's `SELECT *` simply carries a column it does not map,
+and its own writes leave the value where it stood; the duplicate guard reverts to being
+process-local, which is what that build always did.
+
## The one-way half
The drop cannot be undone by an older build. A build from before this change recreates the unique
@@ -49,6 +71,10 @@ per open. It is removed only in a release that is allowed to break existing `web
should be removed together with the `idx_usage_session` drop that sits beside it, since both are
the same kind of debt.
+The `ensureColumn` line for `last_inbound_message_id` has the same lifetime and the same removal
+condition as every other entry in that list — it is the standing convention for an added column,
+not a tolerance of its own.
+
## The added `line_per_message` column
[One message per line](2026-08-26-messaging-line-per-message.md) added
@@ -65,7 +91,8 @@ No action is required. The first open of an updated build drops the index; bindi
and remembered chats are untouched, and a user who never saves one bot on two Sessions cannot tell
the difference.
-Before downgrading to a build from before this change, remove the extra rows if any account is now
+Before downgrading to a build from before this change, neither added column needs attention —
+but remove the extra rows if any account is now
saved on more than one Session — otherwise the older server fails to open the database. Check with:
```sql
diff --git a/changelog/unreleased/2026-08-26-backward-compatibility.zh.md b/changelog/unreleased/2026-08-26-backward-compatibility.zh.md
index bba2d4c1..0f27a7c3 100644
--- a/changelog/unreleased/2026-08-26-backward-compatibility.zh.md
+++ b/changelog/unreleased/2026-08-26-backward-compatibility.zh.md
@@ -3,14 +3,15 @@
- **Date:** 2026-08-26
- **Type:** process
- **Scope:** `server`
-- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490), [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)
+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490), [#493](https://github.com/Prism-Shadow/penguin-harness/pull/493), [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)
- **Breaking:** yes — 对数据库是单向的:一旦两个 Session 保存了同一个机器人账号,本次改动之前的构建就再也打不开那个 `web.db`
[English](2026-08-26-backward-compatibility.md)
-本批改动在存量 `web.db` 上触及两处,都在 `messaging_bindings` 上:它携带的 `idx_messaging_account`
-唯一索引(凡是打开过带消息绑定的构建——0.2.5 及以后——的数据库都有),以及新增的一列。只有前者需要
-决策;后者记在这里,是为了让来这里查「我的数据库需要做什么吗」的读者在同一处拿到两个答案。
+本批改动在存量 `web.db` 上触及三处,都在 `messaging_bindings` 上,也都被凡是打开过带消息绑定的构建
+(0.2.5 及以后)的数据库所携带:`idx_messaging_account` 唯一索引,以及尚不存在的两个新增列
+`last_inbound_message_id` 与 `line_per_message`。只有索引需要决策;两个新增列记在这里,是为了让来这里
+查「我的数据库需要做什么吗?」的读者在同一处拿到全部答案。
## 退役的账号唯一索引
@@ -27,6 +28,22 @@
用户无需做任何事:删除是自动的,在升级后第一次打开时执行,任何绑定、凭证与记住的会话都不改动。
+## 新增的入站水位列
+
+[持久化的重投水位](2026-08-26-messaging-inbound-watermark.zh.md)在 `messaging_bindings` 上新增了
+`last_inbound_message_id`。0.2.7 及更早形成的 `web.db` 有这张表但没有这一列,而
+`CREATE TABLE IF NOT EXISTS` 从不改动已经存在的表。
+
+选定方案:**打开时 ALTER 补上**,在 `openDatabase` 本就为此维护的清单里加一条
+`ensureColumn(db, "messaging_bindings", "last_inbound_message_id", "TEXT")`。该列可空且无默认值,
+因此所有存量绑定都以 `NULL` 沿用——对于本构建从未记录过消息 id 的绑定,这是诚实的取值。升级后的
+第一条入站消息会写入它,此后该绑定即受重复防护覆盖。
+
+用户无需做任何事,绑定的其余部分也不被读取或改写:凭证、意图与记住的会话都原样保留。
+
+这一半可以干净地降级。旧构建的 `SELECT *` 只是多带一列它不映射的值,它自己的写入也会让该值保持
+原样;重复防护退回为进程内有效,而那正是旧构建一贯的行为。
+
## 单向的那一半
删除无法被旧构建撤销。本次改动之前的构建会在自己的 `SCHEMA_SQL` 中重新创建该唯一索引,而一旦出
@@ -41,6 +58,9 @@
限期保留,代价是每次打开多执行一条空操作语句。它只在允许破坏存量 `web.db` 的版本中移除,并且应
当与紧挨着它的 `idx_usage_session` 删除语句一并清理,两者属于同一类债务。
+`last_inbound_message_id` 的 `ensureColumn` 一行与该清单中其他条目寿命相同、移除条件相同——它是
+新增列的既定惯例,而不是一份独立的兼容包袱。
+
## 新增的 `line_per_message` 列
[每行一条消息](2026-08-26-messaging-line-per-message.zh.md)新增了
@@ -55,8 +75,8 @@
无需任何操作。升级后第一次打开即删除该索引;绑定、凭证与记住的会话都不受影响,从不把同一个机器
人保存到两个 Session 的用户完全感觉不到差别。
-降级到本次改动之前的构建之前,若已有账号被保存在多个 Session 上,请先删除多余的行,否则旧服务端
-无法打开该数据库。可用以下语句检查:
+降级到本次改动之前的构建之前,两个新增列都无需处理;但若已有账号被保存在多个 Session 上,请先删除
+多余的行,否则旧服务端无法打开该数据库。可用以下语句检查:
```sql
SELECT channel, account_id, COUNT(*) FROM messaging_bindings
diff --git a/changelog/unreleased/2026-08-26-messaging-inbound-watermark.md b/changelog/unreleased/2026-08-26-messaging-inbound-watermark.md
new file mode 100644
index 00000000..ca1c213d
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-messaging-inbound-watermark.md
@@ -0,0 +1,55 @@
+# A redelivered chat message survives a server restart without running twice
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#493](https://github.com/Prism-Shadow/penguin-harness/pull/493)
+
+[中文版](2026-08-26-messaging-inbound-watermark.zh.md)
+
+The messaging bridge drops an inbound message its binding has already processed, so a channel
+replaying an event does not start the same Task again. That memory was in process only: a
+desktop-app relaunch or a runtime hot swap emptied it, and a channel replaying across the restart
+— which is what a channel does the moment a connection opens — ran the message a second time. The
+Session then answered twice, in the chat and in the Web App.
+
+## The watermark on the binding row
+
+`messaging_bindings` gained `last_inbound_message_id`: the channel id of the most recently
+processed inbound message. `MessagingBridge` folds the stored id back into the binding's in-memory
+ring when a connection opens, before the stream can deliver anything. The two are one memory rather
+than two guards: the ring holds the last 64 ids for as long as the process lives, the row holds the
+last one for as long as the binding does.
+
+The watermark is advanced by an `UPDATE` of its own, issued only once the message has become a Task
+— or been answered with the text-only notice. The write that records the message's chat as the
+binding's reply target still goes first, because the outbound relay reads that chat; the watermark
+could not join it. A busy Session's queued follow-up lives in memory only, so an id persisted ahead
+of the work would outlive that work whenever the process died in between, and the seeding above
+would then turn the channel's replay into a complete no-op — the message would never run and
+nothing would ever answer. A start that threw leaves the id unwritten, and the replay runs the
+message instead.
+
+The row remembers one id, which is what Feishu's long connection needs and all it needs: that
+stream replays events it never saw acknowledged, and the SDK acknowledges each one only after the
+bridge's handler returns, so at most the message in flight when the process ended is still owed.
+Telegram redelivers nothing across a restart — its poller advances past an update before handing it
+over, and a new connection drains whatever arrived while nothing was connected — so on that channel
+the row is carried and never consulted.
+
+Re-saving a binding onto a **different** bot account clears the watermark along with the remembered
+chat, as the other account's message ids mean nothing to the new one.
+
+## The dedupe memory no longer expires by age
+
+The in-memory ring bounded itself by count *and* by a ten-minute age. The age bound existed to
+tolerate a channel that reuses message ids; neither channel does — Feishu's `om_*` are globally
+unique, and Telegram's key is `chatId:message_id`, whose counter only climbs. With no reuse to
+guard against, expiry could only forget a redelivery still owed, and a channel resuming a stream
+after a long outage replays what it never saw acknowledged, however much later that is. The count
+bound stays and is what keeps the memory from growing.
+
+## Compatibility
+
+The added column is covered by the batch's
+[backward-compatibility entry](2026-08-26-backward-compatibility.md). No action is required.
diff --git a/changelog/unreleased/2026-08-26-messaging-inbound-watermark.zh.md b/changelog/unreleased/2026-08-26-messaging-inbound-watermark.zh.md
new file mode 100644
index 00000000..120e3b30
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-messaging-inbound-watermark.zh.md
@@ -0,0 +1,44 @@
+# 重投的聊天消息跨越服务端重启也不会被运行两次
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#493](https://github.com/Prism-Shadow/penguin-harness/pull/493)
+
+[English](2026-08-26-messaging-inbound-watermark.md)
+
+消息桥会丢弃绑定已经处理过的入站消息,使渠道重投同一事件时不再重新发起一次 Task。此前这份记忆只
+存在于进程内:桌面端重启或运行时热替换会将其清空,而渠道跨重启的重投——连接一打开渠道就会这么做
+——会让该消息第二次运行。于是同一个 Session 在聊天中与网页端各答复了两次。
+
+## 绑定行上的水位
+
+`messaging_bindings` 新增了 `last_inbound_message_id`:最近一条被处理的入站消息的渠道 id。连接打
+开时、事件流尚未投递任何内容之前,`MessagingBridge` 会把存储的 id 折回该绑定的内存环。二者是同一
+份记忆而非两道防线:环在进程存续期间保留最近 64 个 id,行在绑定存续期间保留最后一个。
+
+水位由一条独立的 `UPDATE` 推进,且只在消息已经变成 Task——或者已被「仅支持文本」的提示答复——之后
+才执行。把消息所在会话记为该绑定回复目标的那条写入仍然排在最前,因为出站转发要读取这个会话;水位
+则无法与它同行:忙碌 Session 排队的后续输入只存在于内存中,因此抢在工作之前落盘的 id,会在进程恰
+好死于这段间隙时比它所代表的工作活得更久,上面那段折回又会让渠道的重投彻底空转——消息永远不会运
+行,也永远不会有任何答复。而发起失败时这个 id 根本不会被写入,重投于是会把这条消息真正跑起来。
+
+行只记住一个 id,而这正是飞书长连接所需要的全部:该事件流会重投它未曾见到确认的事件,而 SDK 只在
+消息桥的处理函数返回之后才确认每一条,因此进程结束时最多只有正在处理的那一条尚未确认。Telegram 跨
+重启则不重投任何东西——它的轮询在把更新交给处理函数之前就已推进偏移量,而新连接会把无人连接期间到
+达的内容一并排空——所以在这个渠道上,这一行只是被带着走,从不会被查阅。
+
+把绑定改存到**另一个**机器人账号时,水位会与记住的会话一同清除——另一个账号的消息 id 对新账号毫无
+意义。
+
+## 去重记忆不再按时间过期
+
+内存环此前同时按数量和十分钟的时限来限定自身。时限是为了容忍会复用消息 id 的渠道;而两个渠道都不
+复用——飞书的 `om_*` 全局唯一,Telegram 的键是 `chatId:message_id`,其计数只增不减。既然没有复用
+需要防范,过期就只会遗忘仍然欠着的重投,而渠道在长时间中断后恢复事件流时,会重投它未曾见到确认的
+消息,无论那已经过去多久。数量上限保留,并由它来约束这份记忆的大小。
+
+## 兼容性
+
+新增的列由本批的[向后兼容条目](2026-08-26-backward-compatibility.zh.md)统一说明。用户无需任何操
+作。
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index 177983aa..9842e714 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -34,6 +34,7 @@ export function openDatabase(dbPath: string): DatabaseSync {
ensureColumn(db, "auth_sessions", "via", "TEXT");
ensureColumn(db, "trace_files", "page_stats", "TEXT");
ensureColumn(db, "messaging_bindings", "line_per_message", "INTEGER NOT NULL DEFAULT 0");
+ ensureColumn(db, "messaging_bindings", "last_inbound_message_id", "TEXT");
// Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on
// this database: the old index is a strict prefix of it, so every query it served is
// served identically. Dropping is safe — an index is derived, never data.
diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.ts
index c80c4fb4..d2d5c199 100644
--- a/packages/server/src/db/repos/messaging-bindings.ts
+++ b/packages/server/src/db/repos/messaging-bindings.ts
@@ -55,6 +55,13 @@ export interface MessagingBindingRow {
lastChatId: string | null;
/** Whether that chat is a direct chat; group chats prefer reply-to-message. */
lastChatIsDirect: boolean;
+ /**
+ * Channel id of the most recently processed inbound message (null until one arrives).
+ * The bridge's redelivery guard is in memory and dies with the process; this is the one
+ * fact that survives it, so a channel replaying an already-processed event across a
+ * restart is recognized rather than run again (see MessagingBridge's recentInbound).
+ */
+ lastInboundMessageId: string | null;
createdAt: string;
updatedAt: string;
}
@@ -78,6 +85,7 @@ function mapRow(r: Record<string, unknown>): MessagingBindingRow {
linePerMessage: Number(r.line_per_message) === 1,
lastChatId: (r.last_chat_id as string | null) ?? null,
lastChatIsDirect: Number(r.last_chat_is_direct) === 1,
+ lastInboundMessageId: (r.last_inbound_message_id as string | null) ?? null,
createdAt: r.created_at as string,
updatedAt: r.updated_at as string,
};
@@ -179,6 +187,7 @@ export class MessagingBindingsRepo {
line_per_message = COALESCE(?, line_per_message),
last_chat_id = CASE WHEN ? THEN last_chat_id ELSE NULL END,
last_chat_is_direct = CASE WHEN ? THEN last_chat_is_direct ELSE 1 END,
+ last_inbound_message_id = CASE WHEN ? THEN last_inbound_message_id ELSE NULL END,
updated_at = ?
WHERE session_id = ? AND channel = ?`,
)
@@ -189,6 +198,7 @@ export class MessagingBindingsRepo {
args.linePerMessage === undefined ? null : args.linePerMessage ? 1 : 0,
keepChat ? 1 : 0,
keepChat ? 1 : 0,
+ keepChat ? 1 : 0,
now,
args.sessionId,
args.channel,
@@ -220,6 +230,27 @@ export class MessagingBindingsRepo {
.run(chatId, isDirect ? 1 : 0, new Date().toISOString(), sessionId, channel);
}
+ /**
+ * Advance the bridge's durable redelivery watermark to a message it has FINISHED with.
+ * Deliberately its own statement, issued after the work rather than folded into
+ * recordChat: a watermark written first would, if the process died before the Task
+ * existed, mark as processed a message nothing ever ran — and the seeding in
+ * MessagingBridge.connect would then swallow the channel's replay of it.
+ *
+ * A null `messageId` (a channel that mints no message identity) leaves the column
+ * alone rather than clearing it: such a message opts out of the dedupe entirely, so it
+ * has nothing to say about the last message that did carry one.
+ */
+ recordInboundWatermark(sessionId: string, channel: string, messageId: string | null): void {
+ this.db
+ .prepare(
+ `UPDATE messaging_bindings
+ SET last_inbound_message_id = COALESCE(?, last_inbound_message_id), updated_at = ?
+ WHERE session_id = ? AND channel = ?`,
+ )
+ .run(messageId, new Date().toISOString(), sessionId, channel);
+ }
+
/** Drop one channel's config. */
delete(sessionId: string, channel: string): void {
this.db
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index ffc70f9b..46ceba2c 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -131,6 +131,7 @@ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel
line_per_message INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = every non-blank line of a relayed assistant reply is sent as its own message (a reply written as spoken lines arrives as spoken lines), 0 = one message per reply. Channel-agnostic, so it lives here rather than in config_json, which each connector owns
last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it)
last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)
+ last_inbound_message_id TEXT, -- channel id of the most recently PROCESSED inbound message (NULL until one arrives); the durable half of the bridge's redelivery guard, so a channel replaying an event this server already turned into a Task after a restart does not run it twice
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (session_id, channel)
diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.ts
index 86a9f4b9..46a8db1f 100644
--- a/packages/server/src/runtime/messaging/bridge.ts
+++ b/packages/server/src/runtime/messaging/bridge.ts
@@ -12,13 +12,15 @@
* stored config and the live connection never diverge).
*
* Inbound (channel → Session): a message the binding has already processed is dropped
- * first (see MESSAGING_INBOUND_DEDUPE_*) — channels redeliver, and nothing downstream of
- * here is idempotent. Then every inbound message records its chat as the
- * binding's reply target; a text message then starts a Task on the bound Session as an
- * ordinary user input — exactly as if typed into the web composer, no marker block and no
- * special sender (the model deliberately does not learn where the message came from) —
- * with `queueIfBusy`: a busy Session queues it as a follow-up, never 409. Any non-text
- * message gets a polite bilingual "text only" reply.
+ * first (see RecentInboundIds, seeded from the binding row so a restart does not forget) —
+ * channels redeliver, and nothing downstream of here is idempotent. Then every inbound
+ * message records its chat as the binding's reply target; a text message then starts a
+ * Task on the bound Session as an ordinary user input — exactly as if typed into the web
+ * composer, no marker block and no special sender (the model deliberately does not learn
+ * where the message came from) — with `queueIfBusy`: a busy Session queues it as a
+ * follow-up, never 409. Any non-text message gets a polite bilingual "text only" reply.
+ * Only once that work is done is the binding row's watermark advanced, so a process that
+ * dies mid-message has the channel replay it rather than find it already marked.
*
* Outbound (Session → channel): the bridge subscribes to the Session's in-process channel
* and relays each of the main conversation's completed assistant messages on its own, the
@@ -105,45 +107,50 @@ export const MESSAGING_TEST_MESSAGE =
"PenguinHarness test message: this Session's messaging binding works. 测试消息:该会话的消息绑定工作正常。";
/**
- * How many recently processed inbound message ids one binding remembers, and for how long.
+ * How many recently processed inbound message ids one binding remembers.
*
- * A redelivery arrives seconds after the original — a Feishu long connection replaying
- * across a reconnect, or any connector resuming a stream whose acknowledgement never
- * landed — so a short window over the last few messages catches every realistic one. The
- * bound is the point: an unbounded set on a server that runs for months is a leak.
+ * Count is the only bound. An unbounded set on a server that runs for months is a leak,
+ * so the ring has to end somewhere — but nothing expires by age, because neither channel
+ * ever reuses a message id (Feishu's `om_*` are globally unique; Telegram's key is
+ * `chatId:message_id`, and that counter only climbs). With no reuse to guard against, an
+ * age bound could only forget a redelivery still owed to us, and a channel resuming a
+ * stream after a long outage replays whatever it never saw acknowledged — which can
+ * arrive a great deal later than the message it repeats.
*/
const MESSAGING_INBOUND_DEDUPE_SIZE = 64;
-const MESSAGING_INBOUND_DEDUPE_WINDOW_MS = 10 * 60_000;
/**
- * The ids one binding has already processed, bounded by both count and age.
+ * The ids one binding has already processed, bounded by count.
*
* Identity is the channel's own message id (Feishu's `message_id`, Telegram's
* `chatId:message_id`), never the text: a user genuinely does send "status?" twice, and
* swallowing the second one is a worse failure than the duplicate it would prevent.
*
- * A `Map` iterates in insertion order, which is the ring: the oldest key is the first one
- * `keys()` yields, so eviction is a `delete` of that.
+ * A `Set` iterates in insertion order, which is the ring: the oldest id is the first one
+ * `values()` yields, so eviction is a `delete` of that. Re-adding an id already present
+ * leaves that order alone, which is what makes re-seeding on every reconnect free.
*/
class RecentInboundIds {
- private readonly seen = new Map<string, number>();
+ private readonly seen = new Set<string>();
- /** True when this id was already processed inside the window; records it otherwise. */
- check(messageId: string, now: number): boolean {
- const firstSeen = this.seen.get(messageId);
- if (firstSeen !== undefined && now - firstSeen <= MESSAGING_INBOUND_DEDUPE_WINDOW_MS) {
- return true;
- }
- // An id past the window is treated as new and re-dated, so a message id a channel
- // reuses after long enough is not silently dropped forever.
- this.seen.delete(messageId);
- this.seen.set(messageId, now);
+ /** True when this id was already processed; records it otherwise. */
+ check(messageId: string): boolean {
+ if (this.seen.has(messageId)) return true;
+ this.remember(messageId);
+ return false;
+ }
+
+ /**
+ * Records an id as processed without asking about it: how the binding row's persisted
+ * watermark re-enters this memory when a connection opens (see MessagingBridge.connect).
+ */
+ remember(messageId: string): void {
+ this.seen.add(messageId);
while (this.seen.size > MESSAGING_INBOUND_DEDUPE_SIZE) {
- const oldest = this.seen.keys().next();
+ const oldest = this.seen.values().next();
if (oldest.done === true) break;
this.seen.delete(oldest.value);
}
- return false;
}
}
@@ -279,11 +286,19 @@ export class MessagingBridge {
/**
* Processed inbound ids per BINDING (`sessionId:channel`), deliberately not per
* connection: re-saving an enabled binding restarts its connector, and a message
- * already turned into a Task must not run again because the connector is new. In memory
- * only — a server restart forgets, so a redelivery that survives a restart still
- * duplicates. Accepted: a channel replays within seconds of its own reconnect, and
- * persisting this would put a write on every inbound message to close a window the
- * restart itself has almost always already closed.
+ * already turned into a Task must not run again because the connector is new.
+ *
+ * This map dies with the process; `messaging_bindings.last_inbound_message_id` is the
+ * half that does not, and `connect` folds it back in here so the two are one memory
+ * rather than two guards. The row holds ONE id — the last message the bridge finished
+ * with — which is what Feishu's WebSocket resume needs and all it needs: that stream
+ * replays events it never saw acknowledged, and the SDK acknowledges each one only
+ * after our handler returns, so at most the one in flight when the process ended is
+ * still owed. Telegram redelivers nothing across a restart — its poller advances
+ * `offset` past an update before handing it over, and a fresh connection drains with
+ * `getUpdates({offset: -1})`, discarding whatever was sent while nobody was connected —
+ * so on that channel the row is still written and still seeded, and simply never has a
+ * replay to catch.
*/
private readonly recentInbound = new Map<string, RecentInboundIds>();
private readonly connectors: ReadonlyMap<string, MessagingChannelConnector>;
@@ -428,6 +443,13 @@ export class MessagingBridge {
sendChain: Promise.resolve(),
};
this.entries.set(row.sessionId, entry);
+ // Before the stream can hand over its first event: the binding row's watermark is the
+ // only thing that outlived the previous process, and a channel opening a connection is
+ // exactly when it replays what it never saw acknowledged. Without this, the first
+ // message of a re-enabled binding can be one the last server already ran.
+ if (row.lastInboundMessageId !== null) {
+ this.inboundMemoryOf(row.sessionId, row.channel).remember(row.lastInboundMessageId);
+ }
entry.unsubscribe = this.deps.channels
.get(row.sessionId)
.subscribe((evt) => this.observe(entry, evt));
@@ -502,15 +524,20 @@ export class MessagingBridge {
*/
private isRedelivery(entry: BridgeEntry, msg: MessagingInboundMessage): boolean {
if (msg.messageId === "") return false;
- const key = inboundKey(entry.sessionId, entry.channel);
+ if (!this.inboundMemoryOf(entry.sessionId, entry.channel).check(msg.messageId)) return false;
+ this.log(`[messaging] ${entry.channel} redelivered message ${msg.messageId}, ignored`);
+ return true;
+ }
+
+ /** Get-or-create one binding's processed-id memory (see recentInbound). */
+ private inboundMemoryOf(sessionId: string, channel: string): RecentInboundIds {
+ const key = inboundKey(sessionId, channel);
let recent = this.recentInbound.get(key);
if (recent === undefined) {
recent = new RecentInboundIds();
this.recentInbound.set(key, recent);
}
- if (!recent.check(msg.messageId, this.now())) return false;
- this.log(`[messaging] ${entry.channel} redelivered message ${msg.messageId}, ignored`);
- return true;
+ return recent;
}
private async onInbound(entry: BridgeEntry, msg: MessagingInboundMessage): Promise<void> {
@@ -519,19 +546,33 @@ export class MessagingBridge {
try {
const isDirect = msg.chatKind === "direct";
// The chat becomes the reply target BEFORE any processing: even a rejected message
- // type teaches the bridge where the user is.
+ // type teaches the bridge where the user is, and the run started below can emit its
+ // first assistant message before this returns — the outbound relay reads the chat
+ // off the row.
this.deps.repo.recordChat(entry.sessionId, entry.channel, msg.chatId, isDirect);
entry.lastInboundMessageId = isDirect ? null : msg.messageId;
if (msg.text === null || msg.text.trim() === "") {
await this.replyInbound(entry, msg, MESSAGING_TEXT_ONLY_NOTICE);
- return;
+ } else {
+ // An ordinary user input, exactly as if typed into the web composer: no marker
+ // block, no special sender — the model deliberately does not learn the message
+ // arrived through a messaging channel.
+ await this.deps.runner.startTask(entry.sessionId, [userText(msg.text)], {
+ queueIfBusy: true,
+ });
}
- // An ordinary user input, exactly as if typed into the web composer: no marker
- // block, no special sender — the model deliberately does not learn the message
- // arrived through a messaging channel.
- await this.deps.runner.startTask(entry.sessionId, [userText(msg.text)], {
- queueIfBusy: true,
- });
+ // The durable watermark goes LAST, and its own UPDATE is the price of that. What it
+ // marks is a message this process finished with: the follow-up a busy Session queues
+ // lives in memory only, so a watermark written first would — for a process that died
+ // in between — outlive the work it claims, and `connect`'s seeding would then make
+ // the channel's replay of that message a complete no-op. Written here, a throw above
+ // skips it and the replay runs the message instead: at-least-once rather than a
+ // silent swallow.
+ this.deps.repo.recordInboundWatermark(
+ entry.sessionId,
+ entry.channel,
+ msg.messageId === "" ? null : msg.messageId,
+ );
} catch (err) {
this.recordError(entry.sessionId, err, "messaging_inbound_failed");
}
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.ts
index beb0c5e9..3a1a6099 100644
--- a/packages/server/test/db-upgrade.test.ts
+++ b/packages/server/test/db-upgrade.test.ts
@@ -133,6 +133,49 @@ describe("openDatabase column upgrade", () => {
}
});
+ it("adds last_inbound_message_id to a messaging_bindings table formed before it existed", () => {
+ const dbPath = path.join(dir, "web.db");
+ // A database formed by 0.2.7 or earlier: messaging_bindings exists (it shipped in 0.2.5)
+ // but has no redelivery watermark. Derived from the real SCHEMA_SQL, then the one column
+ // this change adds is dropped back off, so the fixture cannot fork from the schema.
+ const old = new sqlite.DatabaseSync(dbPath);
+ try {
+ old.exec(SCHEMA_SQL);
+ old.exec("ALTER TABLE messaging_bindings DROP COLUMN last_inbound_message_id");
+ old
+ .prepare(
+ `INSERT INTO messaging_bindings
+ (session_id, channel, account_id, config_json, enabled, last_chat_id,
+ last_chat_is_direct, created_at, updated_at)
+ VALUES ('session-legacy-binding', 'feishu', 'cli_app', '{}', 1, 'oc_old', 1, ?, ?)`,
+ )
+ .run("2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
+ } finally {
+ old.close();
+ }
+
+ const db = openDatabase(dbPath);
+ try {
+ const repo = new MessagingBindingsRepo(db);
+ // The pre-existing binding survives with its credentials, its intent and its reply
+ // target; only the watermark is new, and it grandfathers in as null — the honest value
+ // for a binding whose past messages this build never saw an id for.
+ const legacy = repo.find("session-legacy-binding", "feishu");
+ expect(legacy?.lastChatId).toBe("oc_old");
+ expect(legacy?.enabled).toBe(true);
+ expect(legacy?.lastInboundMessageId).toBeNull();
+ // And the upgraded table takes the new write, which is the half a created-but-unused
+ // column would pass silently.
+ repo.recordChat("session-legacy-binding", "feishu", "oc_new", true);
+ repo.recordInboundWatermark("session-legacy-binding", "feishu", "om_first_after_upgrade");
+ expect(repo.find("session-legacy-binding", "feishu")?.lastInboundMessageId).toBe(
+ "om_first_after_upgrade",
+ );
+ } finally {
+ db.close();
+ }
+ });
+
it("is idempotent: reopening an already-upgraded database changes nothing", () => {
const dbPath = path.join(dir, "web.db");
openDatabase(dbPath).close();
diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.ts
index a4985f12..50055236 100644
--- a/packages/server/test/messaging.test.ts
+++ b/packages/server/test/messaging.test.ts
@@ -32,9 +32,12 @@ import {
MESSAGING_TEST_MESSAGE,
MESSAGING_TEXT_CHUNK_CHARS,
MESSAGING_TEXT_ONLY_NOTICE,
+ MessagingBridge,
chunkMessagingText,
splitReplyLines,
} from "../src/runtime/messaging/bridge.js";
+import type { MessagingTaskRunner } from "../src/runtime/messaging/bridge.js";
+import { FeishuConnector } from "../src/runtime/messaging/feishu-connector.js";
import type {
FeishuApiClient,
FeishuCredentials,
@@ -371,6 +374,21 @@ describe("messaging binding routes and bridge", () => {
expect((await api.post(`${BASE(sid)}/state`, { enabled: true })).status).toBe(200);
};
+ /**
+ * A second bridge over the SAME database with an empty in-memory ring: what a
+ * desktop-app relaunch — or a runtime hot swap, which stops the bridge and starts a
+ * fresh one — leaves behind. The caller stops the app's own bridge first.
+ */
+ const restartBridge = (runner: MessagingTaskRunner = t.deps.manager) =>
+ new MessagingBridge({
+ repo: t.deps.messagingRepo,
+ sessions: t.deps.sessionsRepo,
+ channels: t.deps.channels,
+ runner,
+ connectors: [new FeishuConnector(fake)],
+ errors: t.deps.errors,
+ });
+
/** The suite's app, rebuildable: the pacing test needs one whose per-line wait is not zero. */
const boot = async (opts: TestAppOptions = {}) => {
fake = new FakeSdk();
@@ -1352,6 +1370,168 @@ describe("messaging binding routes and bridge", () => {
expect(runs).toHaveLength(66);
});
+ it("a message with no channel id leaves the binding's watermark where it was", async () => {
+ await bindEnabled(SID);
+ const fire = (messageId: string, text: string) =>
+ fake.lastConnection().fire({
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId,
+ messageType: "text",
+ content: JSON.stringify({ text }),
+ });
+ await fire("om_identified", "deploy the build");
+ await waitFor(() => runs.length === 1);
+ // A connector that mints no message identity opts out of the dedupe entirely (see
+ // isRedelivery), so it has nothing to say about the last message that did carry one —
+ // and must not wipe the restart guard on its way past.
+ await fire("", "and again");
+ await waitFor(() => runs.length === 2);
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.lastInboundMessageId).toBe("om_identified");
+ });
+
+ it("remembers across a SERVER restart: the binding row's watermark survives the process", async () => {
+ await bindEnabled(SID);
+ const evt = {
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_across_restart_process",
+ messageType: "text",
+ content: JSON.stringify({ text: "deploy the build" }),
+ };
+ await fake.lastConnection().fire(evt);
+ await waitFor(() => runs.length === 1);
+ // The id of the message just processed is on the row, written by the same statement
+ // that recorded its chat.
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.lastInboundMessageId).toBe(
+ "om_across_restart_process",
+ );
+
+ // Feishu then replays, on the connection the successor has just opened, the event it
+ // never saw acknowledged.
+ t.deps.messaging.stop();
+ const successor = restartBridge();
+ try {
+ await successor.start();
+ await fake.lastConnection().fire(evt);
+ await settle(80);
+ expect(runs).toHaveLength(1);
+ // Control: the successor is not merely deaf. Seeding the ring has to silence the one
+ // replayed id and nothing else — a bridge that never wired onMessage, or one whose
+ // seeding poisoned the ring wholesale, passes the assertion above identically.
+ await fake.lastConnection().fire({
+ ...evt,
+ messageId: "om_after_restart",
+ content: JSON.stringify({ text: "and now this" }),
+ });
+ await waitFor(() => runs.length === 2);
+ expect(runs[1]![0]!.text).toBe("and now this");
+ } finally {
+ successor.stop();
+ }
+ });
+
+ it("a replayed non-text message does not re-send the text-only notice across a restart", async () => {
+ await bindEnabled(SID);
+ const sticker = {
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_sticker_restart",
+ messageType: "sticker",
+ content: JSON.stringify({}),
+ };
+ await fake.lastConnection().fire(sticker);
+ await waitFor(() => fake.allSends().length === 1);
+ // Sending the notice IS the work for a non-text message, so finishing it carries the
+ // binding's watermark forward exactly as a started Task does.
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.lastInboundMessageId).toBe(
+ "om_sticker_restart",
+ );
+
+ t.deps.messaging.stop();
+ const successor = restartBridge();
+ try {
+ await successor.start();
+ await fake.lastConnection().fire(sticker);
+ await settle(80);
+ expect(fake.allSends().filter((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE)).toHaveLength(1);
+ // Control: a sticker the binding has never seen still gets its notice.
+ await fake.lastConnection().fire({ ...sticker, messageId: "om_sticker_after_restart" });
+ await waitFor(
+ () => fake.allSends().filter((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE).length === 2,
+ );
+ } finally {
+ successor.stop();
+ }
+ });
+
+ it("a message whose Task never started is left unwatermarked, so the replay runs it", async () => {
+ await bindEnabled(SID);
+ const evt = {
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_start_threw",
+ messageType: "text",
+ content: JSON.stringify({ text: "deploy the build" }),
+ };
+ // The window the ordering guards. A message becomes a Task, and a busy Session's
+ // queued follow-up lives in memory only — so a watermark written ahead of the work
+ // would outlive it, and the successor's seeding would turn the channel's replay into a
+ // no-op: the message never runs and nothing ever answers. A runner that throws stands
+ // in for the process that died before the Task existed.
+ t.deps.messaging.stop();
+ const stillborn = restartBridge({
+ statusOf: () => "idle",
+ startTask: () => Promise.reject(new Error("the Session went away")),
+ });
+ try {
+ await stillborn.start();
+ await fake.lastConnection().fire(evt);
+ const row = t.deps.messagingRepo.find(SID, "feishu");
+ // The chat is remembered either way — the outbound relay reads it, and even a
+ // rejected message teaches the bridge where the user is.
+ expect(row?.lastChatId).toBe("oc_chat_1");
+ expect(row?.lastInboundMessageId).toBeNull();
+ } finally {
+ stillborn.stop();
+ }
+
+ const successor = restartBridge();
+ try {
+ await successor.start();
+ await fake.lastConnection().fire(evt);
+ await waitFor(() => runs.length === 1);
+ expect(runs[0]![0]!.text).toBe("deploy the build");
+ } finally {
+ successor.stop();
+ }
+ });
+
+ it("re-saving a binding onto a different bot account drops the watermark with the chat", () => {
+ const repo = t.deps.messagingRepo;
+ const save = (accountId: string) =>
+ repo.upsert({ sessionId: SID, channel: "feishu", accountId, config: { appId: accountId } });
+ expect(save("cli_before").accountId).toBe("cli_before");
+ repo.recordChat(SID, "feishu", "oc_group_1", false);
+ repo.recordInboundWatermark(SID, "feishu", "om_before_resave");
+ // Re-saving the SAME account is an ordinary settings edit — a rotated secret, say —
+ // and this bot's chat and its message ids still belong to this binding.
+ expect(save("cli_before").accountId).toBe("cli_before");
+ expect(repo.find(SID, "feishu")).toMatchObject({
+ lastChatId: "oc_group_1",
+ lastChatIsDirect: false,
+ lastInboundMessageId: "om_before_resave",
+ });
+ // A DIFFERENT account: a reply must never land in the old bot's conversation, and the
+ // old bot's message ids would only silence themselves.
+ expect(save("cli_after").accountId).toBe("cli_after");
+ expect(repo.find(SID, "feishu")).toMatchObject({
+ lastChatId: null,
+ lastChatIsDirect: true,
+ lastInboundMessageId: null,
+ });
+ });
+
it("remembers across a connector restart, so a re-enable does not replay a message", async () => {
await bindEnabled(SID);
const evt = {