Skip to content

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

πŸ› fix(bot): stop a deferred message from replaying itself in a loop (#23147)

Arvin Xu876f41af636e
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.ts
index 1cf2cc5761b..5a3604914ea 100644
--- a/apps/server/src/modules/Redis/keys.ts
+++ b/apps/server/src/modules/Redis/keys.ts
@@ -40,6 +40,11 @@ export const RedisKeyNamespace = {
* silent-wake budget and the per-channel wake scheduler.
*/
BOT_WAKE: 'bot-wake',
+ /**
+ * Replay bookkeeping for bot messages parked while their topic was busy: how many times each
+ * parked message reached a run, so one that keeps coming back stops looping.
+ */
+ BOT_DEFERRED: 'bot-deferred',
/**
* Short-lived reply routes an IM platform hands out with an inbound message
* (DingTalk's `sessionWebhook`), kept so the process that posts the reply
@@ -124,6 +129,15 @@ export const RedisKeys = {
nightlyTopics: (userId: string, localDate: string): string =>
`nightly_topics:v1:${userId}:${localDate}`,
},
+ /** Bot deferred-replay scope β€” see {@link RedisKeyNamespace.BOT_DEFERRED}. */
+ botDeferred: {
+ /**
+ * Times one parked message (by its origin platform id) was replayed into a run.
+ * Full key: bot-deferred:replays:v1:{applicationId}:{threadId}:{messageId}
+ */
+ replays: (applicationId: string, threadId: string, messageId: string): string =>
+ `replays:v1:${applicationId}:${threadId}:${messageId}`,
+ },
/** Bot reply-route scope β€” see {@link RedisKeyNamespace.BOT_REPLY}. */
botReply: {
/**
@@ -368,6 +382,7 @@ export const RedisKeyScopeNamespace = {
agentSignal: RedisKeyNamespace.AGENT_SIGNAL,
agentSteer: RedisKeyNamespace.AGENT_STEER,
aiGeneration: RedisKeyNamespace.AI_GENERATION,
+ botDeferred: RedisKeyNamespace.BOT_DEFERRED,
botReply: RedisKeyNamespace.BOT_REPLY,
botWake: RedisKeyNamespace.BOT_WAKE,
integrations: RedisKeyNamespace.INTEGRATIONS,
diff --git a/apps/server/src/services/bot/__tests__/deferredMessages.replayLoop.test.ts b/apps/server/src/services/bot/__tests__/deferredMessages.replayLoop.test.ts
new file mode 100644
index 00000000000..2b14674c883
--- /dev/null
+++ b/apps/server/src/services/bot/__tests__/deferredMessages.replayLoop.test.ts
@@ -0,0 +1,236 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mockGetAgentRuntimeRedisClient = vi.hoisted(() => vi.fn());
+
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: mockGetAgentRuntimeRedisClient,
+}));
+
+// Replay counts go through `redisService.botDeferred`; only its connection seam is faked.
+const serviceClient = vi.hoisted(() => ({ current: null as unknown }));
+vi.mock('@/server/services/redis/client', () => ({
+ getRedisServiceClient: async () => serviceClient.current,
+}));
+
+const { MAX_REPLAYS_PER_MESSAGE, deferBotMessages, replayDeferredBotMessages } =
+ await import('../deferredMessages');
+const { getOriginMessageId } = await import('../mergeMessages');
+
+/**
+ * In-memory Redis: the list commands the deferred queue sends to the agent-runtime client, and
+ * (as `service`) the counter commands `redisService.botDeferred` sends to its own client.
+ */
+function createStatefulRedis() {
+ const lists = new Map<string, string[]>();
+ /** Set to lose every acknowledgement, the way a crash between the run and the `LREM` would. */
+ const faults = { loseAcks: false };
+ const counters = new Map<string, number>();
+ const ttls = new Map<string, number>();
+ const list = (key: string) => {
+ if (!lists.has(key)) lists.set(key, []);
+ return lists.get(key)!;
+ };
+ const commands = {
+ expire: () => 1,
+ lrem: (key: string, count: number, value: string) => {
+ const items = list(key);
+ const index = items.indexOf(value);
+ if (faults.loseAcks || count !== 1 || index === -1) return 0;
+ items.splice(index, 1);
+ return 1;
+ },
+ ltrim: (key: string, start: number, stop: number) => {
+ const items = list(key);
+ lists.set(
+ key,
+ items.slice(start < 0 ? Math.max(items.length + start, 0) : start, stop + 1 || undefined),
+ );
+ return 'OK';
+ },
+ rpush: (key: string, ...values: string[]) => list(key).push(...values),
+ };
+ return {
+ counters,
+ faults,
+ lists,
+ service: {
+ mget: async (...keys: string[]) =>
+ keys.map((key) => (counters.has(key) ? String(counters.get(key)) : null)),
+ pipeline: () => {
+ const queued: Array<() => unknown> = [];
+ const add = (key: string, by: number) => {
+ const next = (counters.get(key) ?? 0) + by;
+ counters.set(key, next);
+ return next;
+ };
+ const chain: any = {
+ decr: (key: string) => (queued.push(() => add(key, -1)), chain),
+ exec: async () => queued.map((run) => [null, run()]),
+ expire: (key: string, seconds: number) => (
+ queued.push(() => ttls.set(key, seconds)),
+ chain
+ ),
+ incr: (key: string) => (queued.push(() => add(key, 1)), chain),
+ };
+ return chain;
+ },
+ },
+ ttls,
+ lrange: async (key: string) => [...list(key)],
+ multi: () => {
+ const queued: Array<() => unknown> = [];
+ const chain: any = {
+ exec: async () => queued.map((run) => [null, run()]),
+ };
+ for (const [name, run] of Object.entries(commands)) {
+ chain[name] = (...args: any[]) => {
+ queued.push(() => (run as (...a: any[]) => unknown)(...args));
+ return chain;
+ };
+ }
+ return chain;
+ },
+ };
+}
+
+const KEY = 'bot:deferred-messages:app-1:feishu:group:oc_1';
+
+const asMessage = (id: string) =>
+ ({ id, toJSON: () => ({ _type: 'chat:Message', id, text: 'build the tasks' }) }) as any;
+
+describe('deferred replay loop', () => {
+ let redis: ReturnType<typeof createStatefulRedis>;
+
+ beforeEach(() => {
+ redis = createStatefulRedis();
+ mockGetAgentRuntimeRedisClient.mockReturnValue(redis);
+ serviceClient.current = redis.service;
+ });
+
+ /**
+ * Production incident (feishu, 24 runs for one message): the completion callback replays a
+ * parked message while its own run is still marked live, so the bridge parks the replay
+ * again, sees the run gone on its post-enqueue recheck and replays the queue from inside the
+ * outer replay. That inner read still holds the outer, unacknowledged copy: one copy starts a
+ * run, the other finds the topic busy and is parked a third time. Every completion repeated it.
+ */
+ it('runs a message parked again by its own replay once and leaves nothing queued', async () => {
+ await deferBotMessages('app-1', 'feishu:group:oc_1', [asMessage('om_1')]);
+
+ const runs: string[] = [];
+ let topicBusy = true; // the completing run has not released the topic yet
+
+ const deliver = async (entries: { id: string }[]): Promise<void> => {
+ for (const entry of entries) {
+ const replayed = asMessage(`${getOriginMessageId(entry)}:replay:${Date.now()}:0`);
+ if (topicBusy) {
+ await deferBotMessages('app-1', 'feishu:group:oc_1', [replayed]);
+ // Post-enqueue recheck: the run has settled by now, so the bridge replays at once.
+ if (runs.length === 0 && topicBusy) {
+ topicBusy = false;
+ await replayDeferredBotMessages('app-1', 'feishu:group:oc_1', deliver);
+ }
+ continue;
+ }
+ runs.push(replayed.id);
+ topicBusy = true; // the run it started owns the topic
+ }
+ };
+
+ await replayDeferredBotMessages('app-1', 'feishu:group:oc_1', deliver);
+
+ expect(runs).toHaveLength(1);
+ expect(redis.lists.get(KEY)).toEqual([]);
+ });
+
+ it('collapses every queued copy of one message into a single replay', async () => {
+ await deferBotMessages('app-1', 'feishu:group:oc_1', [
+ asMessage('om_1'),
+ asMessage('om_2'),
+ asMessage('om_1:replay:100:0'),
+ ]);
+ const replay = vi.fn().mockResolvedValue(undefined);
+
+ await replayDeferredBotMessages('app-1', 'feishu:group:oc_1', replay);
+
+ expect(replay).toHaveBeenCalledTimes(1);
+ expect(replay.mock.calls[0][0].map((entry: { id: string }) => entry.id)).toEqual([
+ 'om_1:replay:100:0',
+ 'om_2',
+ ]);
+ expect(redis.lists.get(KEY)).toEqual([]);
+ });
+
+ it('drops a message once it has been run the maximum number of times', async () => {
+ // A loop the collapse cannot see: every lap runs the message, and it is never removed.
+ redis.faults.loseAcks = true;
+ await deferBotMessages('app-1', 'feishu:group:oc_1', [asMessage('om_1')]);
+ const replay = vi.fn().mockResolvedValue(undefined);
+
+ for (let round = 0; round < MAX_REPLAYS_PER_MESSAGE + 2; round++) {
+ await replayDeferredBotMessages('app-1', 'feishu:group:oc_1', replay);
+ }
+
+ expect(replay).toHaveBeenCalledTimes(MAX_REPLAYS_PER_MESSAGE);
+ });
+
+ it('keeps the budget of messages parked again while other senders take the runs', async () => {
+ const senders = ['om_a', 'om_b', 'om_c', 'om_d', 'om_e'];
+ await deferBotMessages('app-1', 'feishu:group:oc_1', senders.map(asMessage));
+ const runs: string[] = [];
+
+ // Each completion drains the queue: one sender's message starts the run, and every other
+ // sender's message finds the topic busy and is parked again under a replay id.
+ const deliver = async (entries: { id: string }[]): Promise<void> => {
+ const [first, ...rest] = entries;
+ runs.push(getOriginMessageId(first));
+ await deferBotMessages(
+ 'app-1',
+ 'feishu:group:oc_1',
+ rest.map((entry) => asMessage(`${getOriginMessageId(entry)}:replay:${runs.length}:0`)),
+ );
+ };
+
+ for (let completion = 0; completion < senders.length + 2; completion++) {
+ await replayDeferredBotMessages('app-1', 'feishu:group:oc_1', deliver);
+ }
+
+ expect(runs).toEqual(senders);
+ expect(redis.lists.get(KEY)).toEqual([]);
+ });
+
+ it('does not spend the budget on deliveries that fail before the SDK takes the message', async () => {
+ await deferBotMessages('app-1', 'feishu:group:oc_1', [asMessage('om_1')]);
+ const replay = vi.fn().mockRejectedValue(new Error('Bot adapter unavailable for feishu'));
+
+ // More failed attempts than the budget allows (the retry job schedules up to eight).
+ for (let attempt = 0; attempt < MAX_REPLAYS_PER_MESSAGE + 2; attempt++) {
+ await expect(replayDeferredBotMessages('app-1', 'feishu:group:oc_1', replay)).rejects.toThrow(
+ 'Bot adapter unavailable',
+ );
+ }
+ replay.mockResolvedValueOnce(undefined);
+ await replayDeferredBotMessages('app-1', 'feishu:group:oc_1', replay);
+
+ expect(replay).toHaveBeenCalledTimes(MAX_REPLAYS_PER_MESSAGE + 3);
+ expect(replay.mock.lastCall?.[0].map((entry: { id: string }) => entry.id)).toEqual(['om_1']);
+ expect(redis.lists.get(KEY)).toEqual([]);
+ });
+
+ it('keeps each message counter under its own TTL instead of one per-thread record', async () => {
+ const replay = vi.fn().mockResolvedValue(undefined);
+ for (const id of ['om_1', 'om_2']) {
+ await deferBotMessages('app-1', 'feishu:group:oc_1', [asMessage(id)]);
+ await replayDeferredBotMessages('app-1', 'feishu:group:oc_1', replay);
+ }
+
+ // Traffic on the thread only refreshes the counter of the message it replays, so an old
+ // message's counter still expires while the thread stays busy.
+ const counterKeys = [...redis.counters.keys()];
+ expect(counterKeys).toEqual([
+ 'replays:v1:app-1:feishu:group:oc_1:om_1',
+ 'replays:v1:app-1:feishu:group:oc_1:om_2',
+ ]);
+ for (const key of counterKeys) expect(redis.ttls.get(key)).toBe(30 * 60);
+ });
+});
diff --git a/apps/server/src/services/bot/__tests__/deferredMessages.test.ts b/apps/server/src/services/bot/__tests__/deferredMessages.test.ts
index 09029c49682..f69e0097f55 100644
--- a/apps/server/src/services/bot/__tests__/deferredMessages.test.ts
+++ b/apps/server/src/services/bot/__tests__/deferredMessages.test.ts
@@ -6,6 +6,9 @@ vi.mock('@/server/modules/AgentRuntime/redis', () => ({
getAgentRuntimeRedisClient: mockGetAgentRuntimeRedisClient,
}));
+// No `redisService` connection: the replay budget fails open, as it does without Redis.
+vi.mock('@/server/services/redis/client', () => ({ getRedisServiceClient: async () => null }));
+
const {
buildDeferredMessagesKey,
deferBotMessages,
@@ -25,7 +28,12 @@ function createRedis(execResult: unknown = []) {
});
}
chain.exec = vi.fn().mockResolvedValue(execResult);
- return { calls, chain, lrange: vi.fn().mockResolvedValue([]), multi: vi.fn(() => chain) };
+ return {
+ calls,
+ chain,
+ lrange: vi.fn().mockResolvedValue([]),
+ multi: vi.fn(() => chain),
+ };
}
const makeMessage = (id: string) => ({ id, toJSON: () => ({ _type: 'chat:Message', id }) }) as any;
@@ -91,13 +99,14 @@ describe('deferredMessages', () => {
.fn()
.mockRejectedValueOnce(new Error('adapter unavailable'))
.mockResolvedValueOnce(undefined);
+ const acknowledged = () => redis.calls.filter(([cmd]) => cmd === 'lrem');
await expect(replayDeferredBotMessages('app-1', 't', replay)).rejects.toThrow(
'adapter unavailable',
);
- expect(redis.calls).toEqual([]);
+ expect(acknowledged()).toEqual([]);
await replayDeferredBotMessages('app-1', 't', replay);
expect(replay).toHaveBeenNthCalledWith(2, [{ id: '1' }, { id: '2' }]);
- expect(redis.calls).toEqual(
+ expect(acknowledged()).toEqual(
payloads.map((payload) => ['lrem', 'bot:deferred-messages:app-1:t', 1, payload]),
);
});
diff --git a/apps/server/src/services/bot/deferredMessages.ts b/apps/server/src/services/bot/deferredMessages.ts
index 31881b09ecb..9131bc785a9 100644
--- a/apps/server/src/services/bot/deferredMessages.ts
+++ b/apps/server/src/services/bot/deferredMessages.ts
@@ -2,6 +2,9 @@ import type { Message } from 'chat';
import debug from 'debug';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+import { redisService } from '@/server/services/redis';
+
+import { getOriginMessageId, isReplayMessage } from './mergeMessages';
const log = debug('lobe-server:bot:deferred-messages');
@@ -40,6 +43,14 @@ export const MAX_DEFERRED_PER_THREAD = 20;
export const buildDeferredMessagesKey = (applicationId: string, platformThreadId: string): string =>
`bot:deferred-messages:${applicationId}:${platformThreadId}`;
+/**
+ * How many times one platform message may be delivered to a run. A replay parked again because the
+ * topic is still busy (another sender's message took the run) did not run, and gets its lap back
+ * when it is parked; one that keeps being run and coming back is looping (each lap is a full agent
+ * run and a reply in the chat) and is dropped instead.
+ */
+export const MAX_REPLAYS_PER_MESSAGE = 3;
+
/**
* Whether deferral is available at all β€” it needs Redis because the replay
* happens in the callback process, not the one that received the message.
@@ -74,6 +85,15 @@ export async function deferBotMessages(
.exec();
const failure = results?.find(([error]) => error)?.[0];
if (!results || failure) throw failure ?? new Error('Deferred write aborted');
+ // A replay parked again was delivered without running: give back the lap its delivery is
+ // about to be counted for, so waiting behind other senders never spends the budget. Only once
+ // the park is stored; a lost refund costs one lap, never the message.
+ const reparked = messages.filter((message) => isReplayMessage(message));
+ await redisService.botDeferred.refundReplays(
+ applicationId,
+ platformThreadId,
+ reparked.map((message) => getOriginMessageId(message)),
+ );
log(
'deferred %d message(s) [%s] for thread=%s app=%s',
messages.length,
@@ -88,46 +108,115 @@ export async function deferBotMessages(
}
}
-/** Read a snapshot without removing messages before the SDK accepts them. */
-export async function readDeferredBotMessages(
+interface DeferredSnapshotEntry {
+ message: DeferredBotMessage;
+ /** The stored string, acknowledged as is: re-serializing a parsed entry may not match it. */
+ payload: string;
+}
+
+const readSnapshot = async (
applicationId: string,
platformThreadId: string,
-): Promise<DeferredBotMessage[]> {
+): Promise<DeferredSnapshotEntry[]> => {
const redis = getAgentRuntimeRedisClient();
if (!redis) return [];
const key = buildDeferredMessagesKey(applicationId, platformThreadId);
- const entries = await redis.lrange(key, 0, -1);
- const messages: DeferredBotMessage[] = [];
- for (const entry of entries) {
+ const payloads = await redis.lrange(key, 0, -1);
+ const entries: DeferredSnapshotEntry[] = [];
+ for (const payload of payloads) {
try {
- messages.push(JSON.parse(entry) as DeferredBotMessage);
+ entries.push({ message: JSON.parse(payload) as DeferredBotMessage, payload });
} catch (error) {
log('Invalid deferred payload for thread=%s: %O', platformThreadId, error);
}
}
- return messages;
+ return entries;
+};
+
+/** Read a snapshot without removing messages before the SDK accepts them. */
+export async function readDeferredBotMessages(
+ applicationId: string,
+ platformThreadId: string,
+): Promise<DeferredBotMessage[]> {
+ const entries = await readSnapshot(applicationId, platformThreadId);
+ return entries.map((entry) => entry.message);
}
+/**
+ * One entry per platform message. A replay parked again while the snapshot it came from is still
+ * unacknowledged sits in the queue next to that snapshot's copy; replaying both starts one run and
+ * parks the other again, which is how a single message looped. Keeps the first copy's position
+ * (chronological order) and the newest copy's payload.
+ */
+const latestPerOrigin = (messages: DeferredBotMessage[]): DeferredBotMessage[] => {
+ const byOrigin = new Map<string, DeferredBotMessage>();
+ for (const message of messages) byOrigin.set(getOriginMessageId(message), message);
+ return [...byOrigin.values()];
+};
+
+/**
+ * Drop the messages whose replay budget is spent. Only reads the counts: a delivery that fails
+ * before the SDK takes the message (no adapter, Redis hiccup) must not use up the budget, or the
+ * retry job would drop a message it was meant to deliver. A count that cannot be read fails open:
+ * the per-origin collapse above already stops the known loop.
+ */
+const withinReplayBudget = async (
+ applicationId: string,
+ platformThreadId: string,
+ messages: DeferredBotMessage[],
+): Promise<DeferredBotMessage[]> => {
+ const counts = await redisService.botDeferred.replayCounts(
+ applicationId,
+ platformThreadId,
+ messages.map((message) => getOriginMessageId(message)),
+ );
+ if (!counts) return messages;
+ return messages.filter((message, index) => {
+ if (counts[index] < MAX_REPLAYS_PER_MESSAGE) return true;
+ log(
+ 'Dropping message=%s on thread=%s: replayed %d times without leaving the queue',
+ getOriginMessageId(message),
+ platformThreadId,
+ counts[index],
+ );
+ return false;
+ });
+};
+
/**
* Acknowledge only the snapshot successfully handed to the SDK. New arrivals
* remain queued. A failure (including process/Redis failure) leaves the original
* entries available for retry. Delivery is at-least-once if a batch partially
- * succeeds or completion callbacks overlap.
+ * succeeds or completion callbacks overlap; copies of one message are replayed
+ * once, and a message is delivered at most {@link MAX_REPLAYS_PER_MESSAGE} times
+ * (failed deliveries and replays parked again while the topic is busy do not count).
*/
export async function replayDeferredBotMessages(
applicationId: string,
platformThreadId: string,
replay: (entries: DeferredBotMessage[]) => Promise<void>,
): Promise<void> {
- const entries = await readDeferredBotMessages(applicationId, platformThreadId);
- if (entries.length === 0) return;
- await replay(entries);
+ const snapshot = await readSnapshot(applicationId, platformThreadId);
+ if (snapshot.length === 0) return;
+ const due = await withinReplayBudget(
+ applicationId,
+ platformThreadId,
+ latestPerOrigin(snapshot.map((entry) => entry.message)),
+ );
+ if (due.length > 0) {
+ await replay(due);
+ await redisService.botDeferred.countReplays(
+ applicationId,
+ platformThreadId,
+ due.map((message) => getOriginMessageId(message)),
+ );
+ }
const redis = getAgentRuntimeRedisClient();
if (!redis) throw new Error('Redis unavailable while acknowledging deferred messages');
const key = buildDeferredMessagesKey(applicationId, platformThreadId);
const transaction = redis.multi();
- for (const entry of entries) transaction.lrem(key, 1, JSON.stringify(entry));
+ for (const entry of snapshot) transaction.lrem(key, 1, entry.payload);
const results = await transaction.exec();
const failure = results?.find(([error]) => error)?.[0];
if (!results || failure) throw failure ?? new Error('Deferred replay acknowledgement aborted');
diff --git a/apps/server/src/services/fileParse/worker.chunk.test.ts b/apps/server/src/services/fileParse/worker.chunk.test.ts
index 997bbfecd07..c86bfce8817 100644
--- a/apps/server/src/services/fileParse/worker.chunk.test.ts
+++ b/apps/server/src/services/fileParse/worker.chunk.test.ts
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
import { isFileParseBudgetError } from '@lobechat/file-loaders';
import { buildTestZip } from '@lobechat/file-loaders/src/loaders/excel/testUtils';
import { Workbook } from 'exceljs';
-import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { ChunkingLoader } from '@/libs/document-loaders';
@@ -227,9 +227,18 @@ describe('chunking in the parse worker', () => {
expect(error).toMatchObject({ code: 'TIMEOUT', name: 'FileParseError' });
// The promise only settled after the thread really exited: the slot is back already.
expect(runner.stats()).toEqual({ active: 0, queued: 0 });
- await expect(
- runner.run({ content: new TextEncoder().encode('after'), filename: 'a.txt', kind: 'chunk' }),
- ).resolves.toHaveLength(1);
+ // The next task takes the freed slot at once. Its own result is not asserted: on a loaded CI
+ // runner a fresh worker can need more than this runner's 500ms just to start.
+ const onStart = vi.fn();
+ const next = runner
+ .run(
+ { content: new TextEncoder().encode('after'), filename: 'a.txt', kind: 'chunk' },
+ { onStart },
+ )
+ .catch(() => undefined);
+ expect(runner.stats()).toEqual({ active: 1, queued: 0 });
+ await vi.waitFor(() => expect(onStart).toHaveBeenCalledOnce());
+ await next;
}, 60_000);
it('gives a chunk job its own scratch directory and removes it once the thread has exited', async () => {
diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.md
index 3ac3916471d..44a08d3775b 100644
--- a/apps/server/src/services/redis/README.md
+++ b/apps/server/src/services/redis/README.md
@@ -53,6 +53,11 @@ Existing raw-client and client-lib consumers remain explicit migration debt in E
Move them domain by domain; runtime state requires a deployment/keyspace compatibility plan.
This foundation does not migrate existing runtime, bot or OAuth stores.
+- `botDeferred`: how many times each bot message parked behind a busy topic was replayed into a
+ run, one key per origin message for 30 minutes. The deferred-message replay drops a message
+ past its cap; a replay parked again gets its lap back. Reads return `undefined` without Redis,
+ and the replay then proceeds without the cap.
+
- `botWake`: channel state for passive bot waking β€” when the bot and its owner last spoke, the
follow-up window, the silent-wake count (reset when the bot speaks), classifier calls per bot
per UTC hour, and the per-channel wake scheduler state (updated under a short lock). Channel
diff --git a/apps/server/src/services/redis/botDeferred.test.ts b/apps/server/src/services/redis/botDeferred.test.ts
new file mode 100644
index 00000000000..f5148ee704e
--- /dev/null
+++ b/apps/server/src/services/redis/botDeferred.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { botDeferred } from './botDeferred';
+
+const counters = new Map<string, number>();
+const ttls = new Map<string, number>();
+const redis = vi.hoisted(() => ({ client: null as any, scope: undefined as string | undefined }));
+vi.mock('./client', () => ({
+ getRedisServiceClient: async (scope: string) => {
+ redis.scope = scope;
+ return redis.client;
+ },
+}));
+
+const memoryClient = {
+ mget: vi.fn(async (...keys: string[]) =>
+ keys.map((key) => (counters.has(key) ? String(counters.get(key)) : null)),
+ ),
+ pipeline: () => {
+ const queued: Array<() => void> = [];
+ const add = (key: string, by: number) => counters.set(key, (counters.get(key) ?? 0) + by);
+ const chain: any = {
+ decr: (key: string) => (queued.push(() => add(key, -1)), chain),
+ exec: async () => queued.map((run) => [null, run()]),
+ expire: (key: string, seconds: number) => (queued.push(() => ttls.set(key, seconds)), chain),
+ incr: (key: string) => (queued.push(() => add(key, 1)), chain),
+ };
+ return chain;
+ },
+};
+
+const KEY = 'replays:v1:app-1:feishu:group:oc_1:om_1';
+
+beforeEach(() => {
+ counters.clear();
+ ttls.clear();
+ vi.clearAllMocks();
+ redis.client = memoryClient;
+});
+
+describe('redisService.botDeferred', () => {
+ it('counts replays per message under the bot-deferred scope, each key for 30 minutes', async () => {
+ await botDeferred.countReplays('app-1', 'feishu:group:oc_1', ['om_1', 'om_2']);
+ await botDeferred.countReplays('app-1', 'feishu:group:oc_1', ['om_1']);
+
+ expect(redis.scope).toBe('botDeferred');
+ expect(
+ await botDeferred.replayCounts('app-1', 'feishu:group:oc_1', ['om_1', 'om_2', 'om_3']),
+ ).toEqual([2, 1, 0]);
+ expect(ttls.get(KEY)).toBe(30 * 60);
+ expect(ttls.get('replays:v1:app-1:feishu:group:oc_1:om_2')).toBe(30 * 60);
+ });
+
+ it('gives a lap back on refund', async () => {
+ await botDeferred.countReplays('app-1', 'feishu:group:oc_1', ['om_1']);
+ await botDeferred.refundReplays('app-1', 'feishu:group:oc_1', ['om_1']);
+
+ expect(await botDeferred.replayCounts('app-1', 'feishu:group:oc_1', ['om_1'])).toEqual([0]);
+ expect(ttls.get(KEY)).toBe(30 * 60);
+ });
+
+ it('reports no counts without Redis and treats writes as no-ops', async () => {
+ redis.client = null;
+
+ await expect(
+ botDeferred.countReplays('app-1', 'feishu:group:oc_1', ['om_1']),
+ ).resolves.toBeUndefined();
+ expect(await botDeferred.replayCounts('app-1', 'feishu:group:oc_1', ['om_1'])).toBeUndefined();
+ });
+
+ it('reports no counts when the read fails, so the caller fails open', async () => {
+ memoryClient.mget.mockRejectedValueOnce(new Error('connection reset'));
+
+ expect(await botDeferred.replayCounts('app-1', 'feishu:group:oc_1', ['om_1'])).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/redis/botDeferred.ts b/apps/server/src/services/redis/botDeferred.ts
new file mode 100644
index 00000000000..29663b5dcf3
--- /dev/null
+++ b/apps/server/src/services/redis/botDeferred.ts
@@ -0,0 +1,75 @@
+import debug from 'debug';
+
+import { RedisKeys } from '@/server/modules/Redis';
+
+import { getRedisServiceClient } from './client';
+
+const log = debug('lobe-server:redis:bot-deferred');
+
+const getClient = () => getRedisServiceClient('botDeferred');
+
+// As long as a parked message can wait for its replay (`deferredMessages` TTL). Each message has
+// its own key, so traffic on a busy thread never keeps an old message's count alive.
+const REPLAY_COUNT_TTL_SECONDS = 30 * 60;
+
+/**
+ * Replay counts for bot messages parked while their topic was busy, by origin platform id.
+ *
+ * The bot's deferred-message replay reads them to stop a message that keeps coming back from
+ * running again, counts a delivery the SDK accepted, and gives a lap back when a replay is parked
+ * again without running. Without Redis reads return `undefined` and writes are no-ops: the caller
+ * then replays as it did before the budget existed.
+ */
+export const botDeferred = {
+ /** One count per message id (0 when never replayed), or `undefined` when Redis is unavailable. */
+ async replayCounts(
+ applicationId: string,
+ threadId: string,
+ messageIds: string[],
+ ): Promise<number[] | undefined> {
+ if (messageIds.length === 0) return [];
+ const redis = await getClient();
+ if (!redis) return undefined;
+ try {
+ const values = await redis.mget(
+ ...messageIds.map((id) => RedisKeys.botDeferred.replays(applicationId, threadId, id)),
+ );
+ return messageIds.map((_, index) => Number(values[index] ?? 0) || 0);
+ } catch (error) {
+ log('replayCounts failed for thread=%s: %O', threadId, error);
+ return undefined;
+ }
+ },
+
+ /** Count one replay of each message that reached the SDK. */
+ async countReplays(applicationId: string, threadId: string, messageIds: string[]) {
+ await adjust(applicationId, threadId, messageIds, 'incr');
+ },
+
+ /** Give back the lap of each replayed message parked again without running. */
+ async refundReplays(applicationId: string, threadId: string, messageIds: string[]) {
+ await adjust(applicationId, threadId, messageIds, 'decr');
+ },
+};
+
+const adjust = async (
+ applicationId: string,
+ threadId: string,
+ messageIds: string[],
+ command: 'decr' | 'incr',
+): Promise<void> => {
+ if (messageIds.length === 0) return;
+ const redis = await getClient();
+ if (!redis) return;
+ try {
+ const pipeline = redis.pipeline();
+ for (const id of messageIds) {
+ const key = RedisKeys.botDeferred.replays(applicationId, threadId, id);
+ pipeline[command](key);
+ pipeline.expire(key, REPLAY_COUNT_TTL_SECONDS);
+ }
+ await pipeline.exec();
+ } catch (error) {
+ log('%s replays failed for thread=%s: %O', command, threadId, error);
+ }
+};
diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.ts
index 3ef5a8c94bf..59d72dba79a 100644
--- a/apps/server/src/services/redis/index.ts
+++ b/apps/server/src/services/redis/index.ts
@@ -2,6 +2,7 @@ import { agentDocumentIndex } from './agentDocumentIndex';
import { agentIdentity } from './agentIdentity';
import { agentRunSlots } from './agentRunSlots';
import { agentSignal } from './agentSignal';
+import { botDeferred } from './botDeferred';
import { botReply } from './botReply';
import { botWake } from './botWake';
import { connectorOAuth } from './connectorOAuth';
@@ -23,6 +24,7 @@ export const redisService = {
agentIdentity,
agentRunSlots,
agentSignal,
+ botDeferred,
botReply,
botWake,
connectorOAuth,