|
| 1 | +/** Verifies the ingress replay guard reads the visible-reply fact of its own attempt. */ |
| 2 | +import type { Message } from "grammy/types"; |
| 3 | +import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts"; |
| 4 | +import { createDeferred } from "openclaw/plugin-sdk/extension-shared"; |
| 5 | +import { resetPluginStateStoreForTests } from "openclaw/plugin-sdk/plugin-state-test-runtime"; |
| 6 | +import { getChildLogger } from "openclaw/plugin-sdk/runtime-env"; |
| 7 | +import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env"; |
| 8 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 9 | +import { defaultTelegramBotDeps } from "./bot-deps.js"; |
| 10 | +import { |
| 11 | + createTelegramMessagePipeline, |
| 12 | + type TelegramMessagePipeline, |
| 13 | +} from "./bot-handlers.message-pipeline.js"; |
| 14 | +import type { RegisterTelegramHandlerParams } from "./bot-handlers.types.js"; |
| 15 | +import { |
| 16 | + markTelegramVisibleReplyDelivered, |
| 17 | + runWithTelegramUpdateProcessingFrame, |
| 18 | + type TelegramMessageProcessingResult, |
| 19 | +} from "./bot-processing-outcome.js"; |
| 20 | +import type { TelegramContext } from "./bot/types.js"; |
| 21 | + |
| 22 | +type SettleSpooledReplay = ( |
| 23 | + result: TelegramMessageProcessingResult, |
| 24 | +) => Promise<TelegramMessageProcessingResult>; |
| 25 | + |
| 26 | +const BOT_USER_ID = 99; |
| 27 | +const SPOOLED_MESSAGE = { |
| 28 | + message_id: 12949, |
| 29 | + date: 1736380800, |
| 30 | + chat: { id: 4242, type: "private" }, |
| 31 | + from: { id: 77, is_bot: false, first_name: "Operator" }, |
| 32 | + text: "does this answer twice?", |
| 33 | +} as Message; |
| 34 | + |
| 35 | +const tempDirs = useAutoCleanupTempDirTracker(afterEach); |
| 36 | +let previousStateDir: string | undefined; |
| 37 | + |
| 38 | +beforeEach(() => { |
| 39 | + previousStateDir = process.env.OPENCLAW_STATE_DIR; |
| 40 | + process.env.OPENCLAW_STATE_DIR = tempDirs.make("openclaw-telegram-replay-guard-"); |
| 41 | + resetPluginStateStoreForTests({ closeDatabase: false }); |
| 42 | +}); |
| 43 | + |
| 44 | +afterEach(() => { |
| 45 | + resetPluginStateStoreForTests(); |
| 46 | + if (previousStateDir === undefined) { |
| 47 | + delete process.env.OPENCLAW_STATE_DIR; |
| 48 | + } else { |
| 49 | + process.env.OPENCLAW_STATE_DIR = previousStateDir; |
| 50 | + } |
| 51 | +}); |
| 52 | + |
| 53 | +/** |
| 54 | + * Builds the real pipeline over the real dispatch-dedupe guard. The stubbed |
| 55 | + * message processor hands back the retained `finalizeSpooledReplayResult` and |
| 56 | + * then stays pending, exactly as a deferred turn does while the reply queue owns |
| 57 | + * it, so the test can settle the attempt from a context the attempt never owned. |
| 58 | + */ |
| 59 | +function createPipelineUnderTest(): { |
| 60 | + pipeline: TelegramMessagePipeline; |
| 61 | + dispatched: Promise<SettleSpooledReplay>; |
| 62 | + replyDuringDispatch: { enabled: boolean }; |
| 63 | + turnResult: ReturnType<typeof createDeferred<TelegramMessageProcessingResult>>; |
| 64 | +} { |
| 65 | + const dispatched = createDeferred<SettleSpooledReplay>(); |
| 66 | + const turnResult = createDeferred<TelegramMessageProcessingResult>(); |
| 67 | + const replyDuringDispatch = { enabled: false }; |
| 68 | + const cfg = { channels: { telegram: { dmPolicy: "open", allowFrom: ["*"] } } } as OpenClawConfig; |
| 69 | + const processMessage = vi.fn(async (args: { turnContext?: Record<string, unknown> }) => { |
| 70 | + if (replyDuringDispatch.enabled) { |
| 71 | + markTelegramVisibleReplyDelivered(); |
| 72 | + } |
| 73 | + dispatched.resolve(args.turnContext?.finalizeSpooledReplayResult as SettleSpooledReplay); |
| 74 | + return await turnResult.promise; |
| 75 | + }); |
| 76 | + const params = { |
| 77 | + accountId: "default", |
| 78 | + ownerAgentId: "main", |
| 79 | + bot: { api: {} } as RegisterTelegramHandlerParams["bot"], |
| 80 | + cfg, |
| 81 | + mediaMaxBytes: 1, |
| 82 | + opts: { token: "tok" }, |
| 83 | + telegramCfg: {}, |
| 84 | + logger: getChildLogger({ module: "telegram/replay-guard-test" }), |
| 85 | + runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() }, |
| 86 | + shouldSkipUpdate: () => false, |
| 87 | + resolveGroupPolicy: () => ({ allowlistEnabled: false, allowed: true }), |
| 88 | + resolveGroupActivation: () => undefined, |
| 89 | + resolveGroupRequireMention: () => false, |
| 90 | + resolveTelegramGroupConfig: () => ({ groupConfig: undefined, topicConfig: undefined }), |
| 91 | + processMessage: processMessage as unknown as RegisterTelegramHandlerParams["processMessage"], |
| 92 | + telegramDeps: { |
| 93 | + ...defaultTelegramBotDeps, |
| 94 | + getRuntimeConfig: () => cfg, |
| 95 | + wasSentByBot: () => false, |
| 96 | + readChannelAllowFromStore: async () => [], |
| 97 | + }, |
| 98 | + } as unknown as RegisterTelegramHandlerParams; |
| 99 | + return { |
| 100 | + pipeline: createTelegramMessagePipeline(params), |
| 101 | + dispatched: dispatched.promise, |
| 102 | + replyDuringDispatch, |
| 103 | + turnResult, |
| 104 | + }; |
| 105 | +} |
| 106 | + |
| 107 | +function dispatchSpooledAttempt( |
| 108 | + pipeline: TelegramMessagePipeline, |
| 109 | + claims: Awaited<ReturnType<TelegramMessagePipeline["claimMessageDispatchDedupe"]>>, |
| 110 | +) { |
| 111 | + return runWithTelegramUpdateProcessingFrame( |
| 112 | + async () => |
| 113 | + await pipeline.processMessageWithReplyChain({ |
| 114 | + ctx: { message: SPOOLED_MESSAGE, update: { update_id: 991 } } as unknown as TelegramContext, |
| 115 | + msg: SPOOLED_MESSAGE, |
| 116 | + allMedia: [], |
| 117 | + storeAllowFrom: [], |
| 118 | + options: { spooledReplay: true }, |
| 119 | + dispatchDedupeClaims: claims.process ? claims.claims : [], |
| 120 | + }), |
| 121 | + ); |
| 122 | +} |
| 123 | + |
| 124 | +describe("Telegram spooled ingress replay guard", () => { |
| 125 | + it("suppresses the redelivery of an attempt that replied before the queue abandoned it", async () => { |
| 126 | + // The reviewer-requested sequence in one trace: confirmed send -> abandonment |
| 127 | + // settled on the queue's own chain (outside this update's frame) -> the spool |
| 128 | + // redelivery of the same logical message is refused as a duplicate. |
| 129 | + const trace: string[] = []; |
| 130 | + const { pipeline, dispatched, replyDuringDispatch, turnResult } = createPipelineUnderTest(); |
| 131 | + const claimed = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID); |
| 132 | + trace.push(`claim attempt=1 process=${claimed.process}`); |
| 133 | + |
| 134 | + replyDuringDispatch.enabled = true; |
| 135 | + const dispatch = dispatchSpooledAttempt(pipeline, claimed); |
| 136 | + const settleFromQueueChain = await dispatched; |
| 137 | + trace.push(`outbound send ok chatId=${SPOOLED_MESSAGE.chat.id} replyToMessageId=<redacted>`); |
| 138 | + |
| 139 | + const settled = await settleFromQueueChain({ |
| 140 | + kind: "failed-retryable", |
| 141 | + error: new Error("turn-abandoned"), |
| 142 | + }); |
| 143 | + turnResult.resolve(settled); |
| 144 | + await dispatch; |
| 145 | + trace.push(`settled kind=${settled.kind}`); |
| 146 | + |
| 147 | + const redelivered = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID); |
| 148 | + trace.push(`claim attempt=2 process=${redelivered.process}`); |
| 149 | + |
| 150 | + expect(trace).toEqual([ |
| 151 | + "claim attempt=1 process=true", |
| 152 | + "outbound send ok chatId=4242 replyToMessageId=<redacted>", |
| 153 | + "settled kind=failed-retryable", |
| 154 | + "claim attempt=2 process=false", |
| 155 | + ]); |
| 156 | + }); |
| 157 | + |
| 158 | + it("redelivers an abandoned attempt that never replied, even while another update's frame is current", async () => { |
| 159 | + // Settlement runs on the followup drain chain, whose frame belongs to |
| 160 | + // whichever update rooted it. Committing on that update's reply would drop |
| 161 | + // this message without ever answering it. |
| 162 | + const trace: string[] = []; |
| 163 | + const { pipeline, dispatched, turnResult } = createPipelineUnderTest(); |
| 164 | + const claimed = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID); |
| 165 | + trace.push(`claim attempt=1 process=${claimed.process}`); |
| 166 | + |
| 167 | + const dispatch = dispatchSpooledAttempt(pipeline, claimed); |
| 168 | + const settleFromQueueChain = await dispatched; |
| 169 | + |
| 170 | + const foreign = await runWithTelegramUpdateProcessingFrame(async () => { |
| 171 | + markTelegramVisibleReplyDelivered(); |
| 172 | + trace.push("outbound send ok update=other-attempt"); |
| 173 | + return await settleFromQueueChain({ |
| 174 | + kind: "failed-retryable", |
| 175 | + error: new Error("turn-abandoned"), |
| 176 | + }); |
| 177 | + }); |
| 178 | + turnResult.resolve(foreign.value); |
| 179 | + await dispatch; |
| 180 | + trace.push(`settled kind=${foreign.value.kind}`); |
| 181 | + |
| 182 | + const redelivered = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID); |
| 183 | + trace.push(`claim attempt=2 process=${redelivered.process}`); |
| 184 | + |
| 185 | + expect(trace).toEqual([ |
| 186 | + "claim attempt=1 process=true", |
| 187 | + "outbound send ok update=other-attempt", |
| 188 | + "settled kind=failed-retryable", |
| 189 | + "claim attempt=2 process=true", |
| 190 | + ]); |
| 191 | + }); |
| 192 | +}); |
0 commit comments