返回 CodeWhale
dispatch-concurrency.test.mjs
根目录 / integrations / telegram-bridge / test / dispatch-concurrency.test.mjs
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import fs from "node:fs/promises";
4 import path from "node:path";
5 import { fileURLToPath } from "node:url";
6
7 const __dirname = path.dirname(fileURLToPath(import.meta.url));
8
9 async function readBridgeSource() {
10 return fs.readFile(path.join(__dirname, "../src/index.mjs"), "utf8");
11 }
12
13 function extractFunction(source, name) {
14 const asyncMarker = `async function ${name}`;
15 const marker = source.includes(asyncMarker) ? asyncMarker : `function ${name}`;
16 const start = source.indexOf(marker);
17 assert.notEqual(start, -1, `${name} should exist`);
18
19 let depth = 0;
20 let opened = false;
21 const bodyStart = source.indexOf("{", source.indexOf(")", start));
22 for (let index = bodyStart; index < source.length; index += 1) {
23 const char = source[index];
24 if (char === "{") {
25 depth += 1;
26 opened = true;
27 } else if (char === "}") {
28 depth -= 1;
29 if (opened && depth === 0) {
30 return source.slice(start, index + 1);
31 }
32 }
33 }
34 assert.fail(`${name} body should close`);
35 }
36
37 test("prompt command persists admission before starting background recovery", async () => {
38 const source = await readBridgeSource();
39 const handleCommand = extractFunction(source, "handleCommand");
40 const promptCase = handleCommand.slice(handleCommand.indexOf('case "prompt":'));
41
42 assert.match(source, /const activeTurnTasks = new Map\(\);/);
43 assert.match(promptCase, /await startPromptTurn\(chatId, action\.prompt, identity\);/);
44 assert.doesNotMatch(promptCase, /await\s+runPrompt\(/);
45
46 const starter = extractFunction(source, "startPromptTurn");
47 assert.ok(
48 starter.indexOf("await threadStore.recordMessage") < starter.lastIndexOf("startTrackedTurnStream(chatId)"),
49 "prompt and inbound receipt must be durable before admission starts"
50 );
51 });
52
53 test("stale callback acknowledgements cannot skip modal actions", async () => {
54 const source = await readBridgeSource();
55 const callbackHandler = extractFunction(source, "handleCallbackQuery");
56
57 assert.doesNotMatch(callbackHandler, /await\s+answerCallback\(query\.id,\s*"Working\.\.\."\)/);
58 assert.match(callbackHandler, /answerCallback\(query\.id,\s*"Working\.\.\."\)\.catch/);
59 assert.match(callbackHandler, /await handleModalAction\(identity\.chatId, action, query, identity\);/);
60 });
61
62 test("polling persists offsets only after successful update handling", async () => {
63 const source = await readBridgeSource();
64 const startup = source.slice(
65 source.indexOf("const threadStore = await ThreadStore.open"),
66 source.indexOf("function requestStop")
67 );
68 const pollTelegram = extractFunction(source, "pollTelegram");
69 const markUpdateHandled = extractFunction(source, "markUpdateHandled");
70
71 assert.match(
72 startup,
73 /let updateOffset = threadStore\.getCursor\(\s*"telegram\.update_offset",\s*Number\(process\.env\.TELEGRAM_UPDATE_OFFSET \|\| 0\)\s*\);/
74 );
75 assert.doesNotMatch(pollTelegram, /updateOffset = Math\.max\(updateOffset, update\.update_id \+ 1\)/);
76 assert.match(pollTelegram, /await handleIncomingUpdate\(update\);\s*await markUpdateHandled\(update\);/);
77 assert.match(
78 pollTelegram,
79 /catch \(error\) {\s*console\.error\("failed to handle incoming Telegram update", error\);\s*if \(isPermanentTelegramError\(error\)\) {\s*await markUpdateHandled\(update\);\s*continue;\s*}\s*await delay\(telegramRetryDelayMs\(error\)\);\s*break;\s*}/
80 );
81 assert.match(markUpdateHandled, /const nextOffset = Math\.max\(updateOffset, Number\(update\.update_id\) \+ 1\);/);
82 assert.match(markUpdateHandled, /await threadStore\.setCursor\("telegram\.update_offset", updateOffset\);/);
83 });
84
85 test("polling conflicts use bounded escalation instead of a flat retry loop", async () => {
86 const source = await readBridgeSource();
87 const pollTelegram = extractFunction(source, "pollTelegram");
88
89 assert.match(source, /telegramPollingConflictDelayMs/);
90 assert.match(pollTelegram, /let pollingConflictAttempts = 0;/);
91 assert.match(pollTelegram, /telegramPollingConflictDelayMs\(pollingConflictAttempts\)/);
92 assert.match(pollTelegram, /pollingConflictAttempts \+= 1;/);
93 assert.match(pollTelegram, /throw new Error\(/);
94 assert.doesNotMatch(pollTelegram, /Retrying in 10s/);
95 assert.doesNotMatch(pollTelegram, /await delay\(10000\)/);
96 });
97
98 test("callback replay is ignored before modal dispatch", async () => {
99 const source = await readBridgeSource();
100 const incomingHandler = extractFunction(source, "handleIncomingUpdate");
101 const replayHelper = extractFunction(source, "isReplayCallbackUpdate");
102 const storedAction = extractFunction(source, "handleStoredAction");
103 const resumeCase = storedAction.slice(storedAction.indexOf('if (stored.kind === "resume")'));
104
105 assert.match(incomingHandler, /if \(await isReplayCallbackUpdate\(update\)\) return;\s*await handleCallbackQuery\(update\.callback_query\);/);
106 assert.match(replayHelper, /if \(update\.update_id == null\) return false;/);
107 assert.match(replayHelper, /return threadStore\.recordMessage\(`callback:\$\{update\.update_id\}`\);/);
108 assert.ok(
109 resumeCase.indexOf("await threadStore.takeAction(action.token, owner);") <
110 resumeCase.indexOf("await resumeThread(chatId, stored.threadId, identity);"),
111 "resume callback actions should be consumed before dispatch"
112 );
113 });
114
115 test("reattached streams are detached and shutdown preserves active turn state", async () => {
116 const source = await readBridgeSource();
117 const reattach = extractFunction(source, "reattachActiveTurns");
118 const runPrompt = extractFunction(source, "runPrompt");
119
120 assert.match(reattach, /startTrackedTurnStream\(chatId\);/);
121 assert.doesNotMatch(reattach, /await\s+streamTurnEvents\(/);
122 assert.match(source, /async function clearActiveTurn\(chatId\)/);
123 assert.match(runPrompt, /if \(state\.turnTerminal \|\| await streamTurnEvents/);
124 assert.match(runPrompt, /await clearActiveTurn\(chatId\);/);
125
126 const trackedStream = extractFunction(source, "startTrackedTurnStream");
127 assert.doesNotMatch(trackedStream, /clearActiveTurn/);
128 assert.match(trackedStream, /while \(!stopping && !controller\.signal\.aborted\)/);
129 });
130
131 test("turn update sends retry without ending the stream", async () => {
132 const source = await readBridgeSource();
133 const streamTurnEvents = extractFunction(source, "streamTurnEvents");
134 const sendTurnText = extractFunction(source, "sendTurnText");
135 const telegramApi = extractFunction(source, "telegramApi");
136
137 assert.doesNotMatch(streamTurnEvents, /await\s+sendText\(/);
138 assert.match(streamTurnEvents, /await\s+sendTurnText\(/);
139 assert.match(sendTurnText, /catch \(error\) {\s*console\.error\("failed to send Telegram turn update"/);
140 assert.match(telegramApi, /method === "sendMessage" \? telegramSendRetryDelayMs\(error, attempt\) : null/);
141 });
142
143 test("turn streams keep Telegram typing visible and pause while waiting for approval", async () => {
144 const source = await readBridgeSource();
145 const streamTurnEvents = extractFunction(source, "streamTurnEvents");
146 const sendTypingAction = extractFunction(source, "sendTypingAction");
147 const telegramApiOnce = extractFunction(source, "telegramApiOnce");
148
149 assert.match(source, /const TYPING_INTERVAL_MS = 2000;/);
150 assert.match(source, /const TYPING_TIMEOUT_MS = 1500;/);
151 assert.match(streamTurnEvents, /let typingPaused = false;/);
152 assert.match(streamTurnEvents, /let typingInFlight = false;/);
153 assert.match(streamTurnEvents, /const typingTimer = setInterval\(\(\) => {\s*void tickTyping\(\);/);
154 assert.match(streamTurnEvents, /void tickTyping\(\);/);
155 assert.match(streamTurnEvents, /const stopTypingEvent =/);
156 assert.match(streamTurnEvents, /if \(typingPaused && !\["approval\.required", "user_input\.required"\]\.includes\(record\.event\) && !stopTypingEvent\)/);
157 assert.match(streamTurnEvents, /typingPaused = true;/);
158 assert.match(streamTurnEvents, /clearInterval\(typingTimer\);/);
159 assert.match(sendTypingAction, /telegramApi\(\s*"sendChatAction"/);
160 assert.match(sendTypingAction, /action: "typing"/);
161 assert.match(sendTypingAction, /setTimeout\(\(\) => controller\.abort\(\), TYPING_TIMEOUT_MS\)/);
162 assert.match(telegramApiOnce, /signal: options\.signal/);
163 });
164
165 test("turn streams debounce last-seq writes and flush before exit", async () => {
166 const source = await readBridgeSource();
167 const streamTurnEvents = extractFunction(source, "streamTurnEvents");
168 const flushLastSeq = extractFunction(source, "flushLastSeq");
169 const streamWithoutFlushHelper = streamTurnEvents.replace(flushLastSeq, "");
170
171 assert.match(source, /const LAST_SEQ_FLUSH_INTERVAL_MS = 2000;/);
172 assert.doesNotMatch(
173 streamWithoutFlushHelper,
174 /await threadStore\.patchChat\(chatId, \{ lastSeq: latestSeq, responseText, turnTerminal \}\);/
175 );
176 assert.match(streamTurnEvents, /await flushLastSeq\(false\);/);
177 assert.match(streamTurnEvents, /await flushLastSeq\(true\);/);
178 assert.match(flushLastSeq, /if \(latestSeq <= flushedSeq\) return;/);
179 assert.match(flushLastSeq, /Date\.now\(\) - lastSeqFlushAt < LAST_SEQ_FLUSH_INTERVAL_MS/);
180 assert.match(flushLastSeq, /await threadStore\.patchChat\(chatId, \{ lastSeq: latestSeq, responseText, turnTerminal \}\);/);
181 assert.match(flushLastSeq, /flushedSeq = latestSeq;/);
182 });
183
184 test("Telegram sends MarkdownV2 with plain-text fallback on parse errors", async () => {
185 const source = await readBridgeSource();
186 const sendText = extractFunction(source, "sendText");
187
188 assert.match(sendText, /telegramMessageBody\(chunk, \{ markdown: true, maxChars: config\.maxReplyChars \}\)/);
189 assert.match(sendText, /isTelegramMarkdownParseError\(error\)/);
190 assert.match(sendText, /telegramMessageBody\(chunk, \{ markdown: false, maxChars: config\.maxReplyChars \}\)/);
191 assert.match(sendText, /await telegramApi\("sendMessage", fallbackBody\);/);
192 });
193
193 lines Plain Text