botsTelegramProvider.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import type { BotConfig } from "@zcode/shared";
  3. import { createTelegramBotProvider } from "../src/bots/providers/telegramProvider.js";
  4. const bot: BotConfig = {
  5. id: "telegram-1",
  6. name: "Telegram",
  7. provider: "telegram",
  8. enabled: true,
  9. credentialRef: "token-key",
  10. allowedWorkspaces: ["*"],
  11. allowedCommands: {
  12. status: true,
  13. new: true,
  14. workspace: true,
  15. model: true,
  16. thoughtLevel: true,
  17. sandboxMode: true,
  18. approvalPolicy: true,
  19. reply: true,
  20. },
  21. currentOptions: {},
  22. replyMode: "assistant_changes",
  23. };
  24. describe("telegram bot provider", () => {
  25. afterEach(() => {
  26. vi.restoreAllMocks();
  27. });
  28. it("uses short numeric callback data for long option ids", async () => {
  29. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  30. vi.stubGlobal("fetch", fetchMock);
  31. const provider = createTelegramBotProvider({
  32. loadCredential: vi.fn(async () => "token"),
  33. });
  34. await provider.send(bot, {
  35. botId: bot.id,
  36. provider: "telegram",
  37. providerUserId: "chat-1",
  38. text: "选择 workspace",
  39. selection: {
  40. id: "workspace-select",
  41. title: "选择 workspace",
  42. cancelLabel: "Cancel",
  43. action: "workspace.set",
  44. options: [
  45. {
  46. id: `ssh://host/${"very-long-path/".repeat(10)}`,
  47. label: "Remote Workspace",
  48. },
  49. ],
  50. },
  51. });
  52. const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
  53. reply_markup?: { inline_keyboard?: Array<Array<{ text?: string; callback_data?: string }>> };
  54. };
  55. expect(body.reply_markup?.inline_keyboard?.[0]?.[0]?.callback_data).toBe("zc:workspace:1");
  56. expect(body.reply_markup?.inline_keyboard?.[1]?.[0]).toEqual({
  57. text: "Cancel",
  58. callback_data: "zc:cancel",
  59. });
  60. });
  61. it("sends Telegram messages with Markdown parse mode", async () => {
  62. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  63. vi.stubGlobal("fetch", fetchMock);
  64. const provider = createTelegramBotProvider({
  65. loadCredential: vi.fn(async () => "token"),
  66. });
  67. await provider.send(bot, {
  68. botId: bot.id,
  69. provider: "telegram",
  70. providerUserId: "chat-1",
  71. text: "*Done*\n\n```ts\nconst value = 1;\n```",
  72. });
  73. expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
  74. chat_id: "chat-1",
  75. text: "*Done*\n\n```ts\nconst value = 1;\n```",
  76. parse_mode: "Markdown",
  77. });
  78. });
  79. it("parses Telegram media messages with captions into attachments", () => {
  80. const provider = createTelegramBotProvider({
  81. loadCredential: vi.fn(async () => "token"),
  82. });
  83. expect(
  84. provider.parseCallback({
  85. botId: "telegram-1",
  86. update: {
  87. message: {
  88. message_id: 101,
  89. caption: "看这张图",
  90. chat: { id: "chat-1", type: "private" },
  91. from: { id: "user-1", username: "alice" },
  92. photo: [
  93. { file_id: "small", file_size: 10 },
  94. { file_id: "large", file_size: 20 },
  95. ],
  96. },
  97. },
  98. }),
  99. ).toEqual([
  100. expect.objectContaining({
  101. text: "看这张图",
  102. attachments: [
  103. expect.objectContaining({
  104. kind: "image",
  105. providerFileId: "large",
  106. filename: "telegram-photo.jpg",
  107. }),
  108. ],
  109. }),
  110. ]);
  111. });
  112. it("downloads Telegram attachments through getFile", async () => {
  113. const fetchMock = vi
  114. .fn()
  115. .mockResolvedValueOnce(
  116. new Response(
  117. JSON.stringify({ ok: true, result: { file_path: "photos/file.jpg", file_size: 3 } }),
  118. ),
  119. )
  120. .mockResolvedValueOnce(new Response(new Uint8Array([1, 2, 3])));
  121. vi.stubGlobal("fetch", fetchMock);
  122. const provider = createTelegramBotProvider({
  123. loadCredential: vi.fn(async () => "token"),
  124. });
  125. await expect(
  126. provider.downloadAttachment?.(bot, {
  127. id: "file-1",
  128. kind: "image",
  129. filename: "photo.jpg",
  130. mimeType: "image/jpeg",
  131. providerFileId: "file-1",
  132. }),
  133. ).resolves.toEqual({
  134. attachment: expect.objectContaining({ sizeBytes: 3 }),
  135. data: new Uint8Array([1, 2, 3]),
  136. });
  137. expect(String(fetchMock.mock.calls[0]?.[0])).toContain("/getFile");
  138. expect(String(fetchMock.mock.calls[1]?.[0])).toContain("/file/bottoken/photos/file.jpg");
  139. });
  140. it("falls back to plain text when Telegram rejects Markdown", async () => {
  141. const fetchMock = vi
  142. .fn()
  143. .mockResolvedValueOnce(new Response(JSON.stringify({ ok: false }), { status: 400 }))
  144. .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true })));
  145. vi.stubGlobal("fetch", fetchMock);
  146. const provider = createTelegramBotProvider({
  147. loadCredential: vi.fn(async () => "token"),
  148. });
  149. await provider.send(bot, {
  150. botId: bot.id,
  151. provider: "telegram",
  152. providerUserId: "chat-1",
  153. text: "*unclosed",
  154. });
  155. expect(fetchMock).toHaveBeenCalledTimes(2);
  156. expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toEqual({
  157. chat_id: "chat-1",
  158. text: "*unclosed",
  159. });
  160. });
  161. it.each([403, 429, 500, 200])(
  162. "does not retry non-format rejection or report it as success: %s",
  163. async (status) => {
  164. const fetchMock = vi.fn(
  165. async () =>
  166. new Response(
  167. JSON.stringify({
  168. ok: false,
  169. error_code: status === 200 ? 403 : status,
  170. description: "rejected",
  171. }),
  172. { status },
  173. ),
  174. );
  175. vi.stubGlobal("fetch", fetchMock);
  176. const provider = createTelegramBotProvider({ loadCredential: async () => "token" });
  177. await expect(
  178. provider.send(bot, {
  179. botId: bot.id,
  180. provider: "telegram",
  181. providerUserId: "chat",
  182. text: "hello",
  183. }),
  184. ).rejects.toThrow("rejected");
  185. expect(fetchMock).toHaveBeenCalledOnce();
  186. },
  187. );
  188. it("reports rejected plain-text fallback", async () => {
  189. const fetchMock = vi
  190. .fn()
  191. .mockResolvedValueOnce(
  192. new Response(JSON.stringify({ ok: false, description: "can't parse entities" }), {
  193. status: 400,
  194. }),
  195. )
  196. .mockResolvedValueOnce(
  197. new Response(JSON.stringify({ ok: false, description: "blocked" }), { status: 403 }),
  198. );
  199. vi.stubGlobal("fetch", fetchMock);
  200. const provider = createTelegramBotProvider({ loadCredential: async () => "token" });
  201. await expect(
  202. provider.send(bot, {
  203. botId: bot.id,
  204. provider: "telegram",
  205. providerUserId: "chat",
  206. text: "hello",
  207. }),
  208. ).rejects.toThrow("blocked");
  209. expect(fetchMock).toHaveBeenCalledTimes(2);
  210. });
  211. it("resolves Telegram bot name from getMe", async () => {
  212. const fetchMock = vi.fn(
  213. async () =>
  214. new Response(
  215. JSON.stringify({ ok: true, result: { first_name: "ZCode Bot", username: "zcode_bot" } }),
  216. ),
  217. );
  218. vi.stubGlobal("fetch", fetchMock);
  219. const provider = createTelegramBotProvider({
  220. loadCredential: vi.fn(async () => "token"),
  221. });
  222. await expect(provider.resolveName?.(bot)).resolves.toBe("ZCode Bot");
  223. await expect(provider.test(bot)).resolves.toMatchObject({
  224. ok: true,
  225. name: "ZCode Bot",
  226. });
  227. });
  228. it("syncs Telegram bot menu with all supported commands", async () => {
  229. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  230. vi.stubGlobal("fetch", fetchMock);
  231. const provider = createTelegramBotProvider({
  232. loadCredential: vi.fn(async () => "token"),
  233. });
  234. await provider.syncCommands?.(bot);
  235. expect(fetchMock).toHaveBeenCalledWith(
  236. "https://api.telegram.org/bottoken/setMyCommands",
  237. expect.objectContaining({
  238. method: "POST",
  239. body: JSON.stringify({
  240. commands: [
  241. { command: "help", description: "Show help" },
  242. { command: "status", description: "Show current status" },
  243. { command: "new", description: "Create a new task" },
  244. { command: "project", description: "Select project" },
  245. { command: "model", description: "Select model" },
  246. { command: "mode", description: "Select mode" },
  247. { command: "think", description: "Select thinking level" },
  248. { command: "reply", description: "Select reply detail" },
  249. { command: "bind", description: "Bind this chat" },
  250. ],
  251. }),
  252. }),
  253. );
  254. expect(fetchMock).toHaveBeenCalledTimes(1);
  255. });
  256. it("clears Telegram bot menu when bot is disabled", async () => {
  257. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  258. vi.stubGlobal("fetch", fetchMock);
  259. const provider = createTelegramBotProvider({
  260. loadCredential: vi.fn(async () => "token"),
  261. });
  262. await provider.syncCommands?.({ ...bot, enabled: false });
  263. expect(fetchMock).toHaveBeenCalledWith(
  264. "https://api.telegram.org/bottoken/deleteMyCommands",
  265. expect.objectContaining({
  266. method: "POST",
  267. body: JSON.stringify({}),
  268. }),
  269. );
  270. });
  271. it("uses command callback data for permission buttons", async () => {
  272. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  273. vi.stubGlobal("fetch", fetchMock);
  274. const provider = createTelegramBotProvider({
  275. loadCredential: vi.fn(async () => "token"),
  276. });
  277. await provider.send(bot, {
  278. botId: bot.id,
  279. provider: "telegram",
  280. providerUserId: "chat-1",
  281. text: "需要权限:Run command",
  282. selection: {
  283. id: "permission-req-1",
  284. title: "需要权限:Run command",
  285. action: "permission.respond",
  286. showCancel: false,
  287. options: [
  288. {
  289. id: "/approve req-1 allow",
  290. label: "允许",
  291. },
  292. {
  293. id: "/deny req-1",
  294. label: "拒绝",
  295. },
  296. ],
  297. },
  298. });
  299. const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
  300. reply_markup?: { inline_keyboard?: Array<Array<{ callback_data?: string }>> };
  301. };
  302. expect(body.reply_markup?.inline_keyboard?.[0]?.[0]?.callback_data).toBe("zc:permission:1");
  303. expect(body.reply_markup?.inline_keyboard?.[1]?.[0]?.callback_data).toBe("zc:permission:2");
  304. expect(body.reply_markup?.inline_keyboard).toHaveLength(2);
  305. });
  306. it("parses callback data back into a numbered command", () => {
  307. const provider = createTelegramBotProvider({
  308. loadCredential: vi.fn(async () => "token"),
  309. });
  310. expect(
  311. provider.parseCallback({
  312. botId: "telegram-1",
  313. update: {
  314. callback_query: {
  315. data: "zc:workspace:1",
  316. from: { id: 42, username: "user" },
  317. message: { chat: { id: 42, type: "private" } },
  318. },
  319. },
  320. }),
  321. ).toMatchObject([
  322. {
  323. botId: "telegram-1",
  324. text: "/workspace 1",
  325. actor: {
  326. provider: "telegram",
  327. providerUserId: "42",
  328. chatType: "private",
  329. },
  330. },
  331. ]);
  332. });
  333. it("parses permission callback data back into a numbered permission command", () => {
  334. const provider = createTelegramBotProvider({
  335. loadCredential: vi.fn(async () => "token"),
  336. });
  337. expect(
  338. provider.parseCallback({
  339. botId: "telegram-1",
  340. update: {
  341. callback_query: {
  342. data: "zc:permission:1",
  343. from: { id: 42, username: "user" },
  344. message: { chat: { id: 42, type: "private" } },
  345. },
  346. },
  347. }),
  348. ).toMatchObject([{ text: "/permission 1" }]);
  349. });
  350. it("uses short callback data for elicitation buttons", async () => {
  351. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  352. vi.stubGlobal("fetch", fetchMock);
  353. const provider = createTelegramBotProvider({
  354. loadCredential: vi.fn(async () => "token"),
  355. });
  356. await provider.send(bot, {
  357. botId: bot.id,
  358. provider: "telegram",
  359. providerUserId: "chat-1",
  360. text: "请选择",
  361. selection: {
  362. id: "elicitation-long-request",
  363. token: "abc123def456",
  364. title: "请选择",
  365. action: "elicitation.respond",
  366. options: [{ id: `answer-${"x".repeat(100)}`, label: "很长的选项" }],
  367. },
  368. });
  369. const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
  370. reply_markup?: { inline_keyboard?: Array<Array<{ callback_data?: string }>> };
  371. };
  372. expect(body.reply_markup?.inline_keyboard?.[0]?.[0]?.callback_data).toBe("zc:e:abc123def456:1");
  373. });
  374. it("attaches interactive buttons to the final chunk of a long Plan", async () => {
  375. const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => {
  376. const body = JSON.parse(String(init?.body)) as { text?: string; parse_mode?: string };
  377. const isFinalMarkdownChunk =
  378. body.parse_mode === "Markdown" && body.text?.includes("Review this implementation plan.");
  379. return new Response(JSON.stringify({ ok: !isFinalMarkdownChunk }), {
  380. status: isFinalMarkdownChunk ? 400 : 200,
  381. });
  382. });
  383. vi.stubGlobal("fetch", fetchMock);
  384. const provider = createTelegramBotProvider({
  385. loadCredential: vi.fn(async () => "token"),
  386. });
  387. await provider.send(bot, {
  388. botId: bot.id,
  389. provider: "telegram",
  390. providerUserId: "chat-1",
  391. text: `${"Plan context. ".repeat(320)}\n\n------\n\nReview this implementation plan.`,
  392. selection: {
  393. id: "plan-approval",
  394. token: "abc123def456",
  395. title: "Review this implementation plan.",
  396. action: "elicitation.respond",
  397. options: [{ id: "approve", label: "Approve" }],
  398. },
  399. });
  400. const bodies = fetchMock.mock.calls.map(
  401. ([, init]) =>
  402. JSON.parse(String(init?.body)) as {
  403. text?: string;
  404. parse_mode?: string;
  405. reply_markup?: unknown;
  406. },
  407. );
  408. expect(bodies).toHaveLength(3);
  409. expect(bodies[0]?.reply_markup).toBeUndefined();
  410. expect(bodies[1]).toMatchObject({
  411. parse_mode: "Markdown",
  412. reply_markup: expect.any(Object),
  413. });
  414. expect(bodies[2]?.parse_mode).toBeUndefined();
  415. expect(bodies[2]?.reply_markup).toEqual(expect.any(Object));
  416. expect(bodies[1]?.text).toContain("Review this implementation plan.");
  417. expect(bodies[2]?.text).toBe(bodies[1]?.text);
  418. });
  419. it("parses elicitation callback data back into a numbered command", () => {
  420. const provider = createTelegramBotProvider({
  421. loadCredential: vi.fn(async () => "token"),
  422. });
  423. expect(
  424. provider.parseCallback({
  425. botId: "telegram-1",
  426. update: {
  427. callback_query: {
  428. id: "callback-1",
  429. data: "zc:e:abc123def456:2",
  430. from: { id: 42, username: "user" },
  431. message: { chat: { id: 42, type: "private" } },
  432. },
  433. },
  434. }),
  435. ).toMatchObject([
  436. {
  437. text: "/elicitation abc123def456 2",
  438. actor: { providerMessageId: "callback-1" },
  439. },
  440. ]);
  441. });
  442. it("parses cancel callback data back into explicit cancel command", () => {
  443. const provider = createTelegramBotProvider({
  444. loadCredential: vi.fn(async () => "token"),
  445. });
  446. expect(
  447. provider.parseCallback({
  448. botId: "telegram-1",
  449. update: {
  450. callback_query: {
  451. data: "zc:cancel",
  452. from: { id: 42, username: "user" },
  453. message: { chat: { id: 42, type: "private" } },
  454. },
  455. },
  456. }),
  457. ).toMatchObject([{ text: "/cancel" }]);
  458. });
  459. it("sends Telegram typing chat action", async () => {
  460. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  461. vi.stubGlobal("fetch", fetchMock);
  462. const provider = createTelegramBotProvider({
  463. loadCredential: vi.fn(async () => "token"),
  464. });
  465. await provider.sendTyping?.(bot, { providerUserId: "chat-1" });
  466. expect(fetchMock).toHaveBeenCalledWith(
  467. "https://api.telegram.org/bottoken/sendChatAction",
  468. expect.objectContaining({
  469. method: "POST",
  470. body: JSON.stringify({
  471. chat_id: "chat-1",
  472. action: "typing",
  473. }),
  474. }),
  475. );
  476. });
  477. it("acknowledges callback queries", async () => {
  478. const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true })));
  479. vi.stubGlobal("fetch", fetchMock);
  480. const provider = createTelegramBotProvider({
  481. loadCredential: vi.fn(async () => "token"),
  482. });
  483. await provider.acknowledgeCallback?.(
  484. bot,
  485. {
  486. botId: "telegram-1",
  487. update: {
  488. callback_query: {
  489. id: "callback-1",
  490. data: "zc:permission:1",
  491. message: { message_id: 100, chat: { id: "chat-1", type: "private" } },
  492. },
  493. },
  494. },
  495. "已提交权限响应。",
  496. );
  497. expect(fetchMock).toHaveBeenCalledWith(
  498. "https://api.telegram.org/bottoken/answerCallbackQuery",
  499. expect.objectContaining({
  500. method: "POST",
  501. body: JSON.stringify({
  502. callback_query_id: "callback-1",
  503. text: "已提交权限响应。",
  504. }),
  505. }),
  506. );
  507. expect(fetchMock).toHaveBeenCalledWith(
  508. "https://api.telegram.org/bottoken/editMessageReplyMarkup",
  509. expect.objectContaining({
  510. method: "POST",
  511. body: JSON.stringify({
  512. chat_id: "chat-1",
  513. message_id: 100,
  514. reply_markup: { inline_keyboard: [] },
  515. }),
  516. }),
  517. );
  518. });
  519. });