botsService.privateSync.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import type { BotsConfigFile, BotsStateFile, ZCodeStreamEvent } from "@zcode/shared";
  3. import * as f from "./botsService.fixtures.js";
  4. const services: ReturnType<typeof f.createBotsService>[] = [];
  5. afterEach(async () => {
  6. for (const service of services.splice(0)) await service.disposeAllAndWait();
  7. });
  8. function setup(config: BotsConfigFile = f.telegramConfig) {
  9. const bot = config.bots[0]!;
  10. const state: BotsStateFile = {
  11. version: 3,
  12. bots: Object.fromEntries(
  13. config.bots.map((item) => [
  14. item.id,
  15. {
  16. botId: item.id,
  17. mode: "task",
  18. activeTaskId: "task-1",
  19. workspacePath: "/tmp/workspace",
  20. updatedAt: 1,
  21. },
  22. ]),
  23. ),
  24. };
  25. const repo = f.createMemoryRepo(config, state);
  26. const listeners = new Map<string, (event: ZCodeStreamEvent) => Promise<void> | void>();
  27. const tasks = f.createLegacyTaskService();
  28. const subscribe = vi.fn(
  29. (address: { taskId: string }) =>
  30. (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  31. listeners.set(address.taskId, listener);
  32. return { dispose: vi.fn(() => listeners.delete(address.taskId)) };
  33. },
  34. );
  35. Object.assign(tasks, { onDynamicTaskEvent: subscribe });
  36. const sent: Array<{ url: string; method?: string; body: Record<string, unknown> }> = [];
  37. const fetchMock = vi.fn(async (url: string, options?: RequestInit) => {
  38. const body = JSON.parse(String(options?.body ?? "{}"));
  39. sent.push({ url: String(url), method: options?.method, body });
  40. if (String(url).includes("tenant_access_token"))
  41. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant", expire: 7200 }));
  42. return new Response(
  43. JSON.stringify({
  44. ok: true,
  45. ret: 0,
  46. code: 0,
  47. data: { message_id: `msg-${sent.length}`, reaction_id: `reaction-${sent.length}` },
  48. result: { message_id: sent.length },
  49. }),
  50. );
  51. });
  52. vi.stubGlobal("fetch", fetchMock);
  53. const credentials = f.createCredentialService({
  54. "telegram-token": "token",
  55. "feishu-secret": "secret",
  56. "weixin-token": "token",
  57. });
  58. const service = f.createBotsService({
  59. repo: repo as never,
  60. legacyTaskService: tasks,
  61. credentialService: credentials,
  62. runStartupBackgroundTasks: false,
  63. });
  64. services.push(service);
  65. const actor = {
  66. botId: bot.id,
  67. provider: bot.provider,
  68. providerUserId: bot.providerUserId!,
  69. chatType: "private" as const,
  70. };
  71. const emit = async (type: string, run: string, extras: Record<string, unknown> = {}) => {
  72. await listeners.get("task-1")?.({
  73. type,
  74. taskId: "task-1",
  75. traceId: run,
  76. inputId: run,
  77. ...extras,
  78. } as ZCodeStreamEvent);
  79. };
  80. const run = async (id: string, content: string, origin = "desktop") => {
  81. await emit("task_run_started", id, { inputOrigin: origin, startedAt: Date.now() });
  82. await emit("agent_message_chunk", id, { content });
  83. await emit("task_complete", id, { stopReason: "end_turn" });
  84. };
  85. return { service, repo, tasks, actor, emit, run, sent, subscribe, credentials, fetchMock };
  86. }
  87. describe("private task continuous delivery", () => {
  88. it("keeps private Typing until each run completes, including a reused subscription", async () => {
  89. const h = setup(f.feishuConfig);
  90. for (const id of ["first", "followup"]) {
  91. const messageId = `om-private-typing-${id}`;
  92. const response = await h.service.handleProviderCallbackResponse("feishu", {
  93. botId: h.actor.botId,
  94. event: {
  95. sender: { sender_type: "user", sender_id: { open_id: h.actor.providerUserId } },
  96. message: {
  97. message_id: messageId,
  98. chat_type: "p2p",
  99. message_type: "text",
  100. content: JSON.stringify({ text: "你好" }),
  101. },
  102. },
  103. });
  104. expect(response.ok).toBe(true);
  105. const reactions = () =>
  106. h.sent.filter((item) => item.url.includes(`/messages/${messageId}/reactions`));
  107. expect(reactions().filter((item) => item.method === "POST")).toHaveLength(1);
  108. expect(reactions().filter((item) => item.method === "DELETE")).toHaveLength(0);
  109. await h.emit("task_run_started", id, { inputOrigin: "desktop", startedAt: Date.now() });
  110. await h.emit("agent_message_chunk", id, { content: "正在处理" });
  111. expect(reactions().filter((item) => item.method === "DELETE")).toHaveLength(0);
  112. await h.emit("task_complete", id, { stopReason: "end_turn" });
  113. await vi.waitFor(() =>
  114. expect(reactions().filter((item) => item.method === "DELETE")).toHaveLength(1),
  115. );
  116. }
  117. expect(h.subscribe).toHaveBeenCalledTimes(1);
  118. });
  119. it.each([
  120. f.telegramConfig,
  121. f.feishuConfig,
  122. {
  123. ...f.weixinConfig,
  124. bots: f.weixinConfig.bots.map((bot) => ({ ...bot, providerUserId: "wx_user" })),
  125. },
  126. ])(
  127. "delivers IM then desktop and mobile turns independently: $bots.0.provider",
  128. async (config) => {
  129. const h = setup(config);
  130. await h.service.handleInboundMessage({
  131. botId: h.actor.botId,
  132. actor: { ...h.actor, providerContextToken: "latest-token" },
  133. text: "first input",
  134. });
  135. await h.run("im", "FIRST");
  136. await h.run("desktop", "SECOND");
  137. await h.run("mobile", "THIRD", "mobile");
  138. const replies = h.sent.filter((item) =>
  139. /sendMessage|sendmessage|im\/v1\/messages(?:\?|$)/.test(item.url),
  140. );
  141. expect(replies).toHaveLength(3);
  142. expect(JSON.stringify(replies[1])).toContain("SECOND");
  143. expect(JSON.stringify(replies[1])).not.toContain("FIRST");
  144. expect(JSON.stringify(replies[2])).toContain("THIRD");
  145. expect(h.subscribe).toHaveBeenCalledOnce();
  146. },
  147. );
  148. it("restores an existing binding on enable and invalidates it on disable", async () => {
  149. const h = setup();
  150. await h.service.saveConfig(await h.repo.readConfig());
  151. await h.run("desktop", "RESTORED");
  152. expect(h.sent.some((item) => JSON.stringify(item.body).includes("RESTORED"))).toBe(true);
  153. await h.service.saveConfig({
  154. ...f.telegramConfig,
  155. bots: f.telegramConfig.bots.map((bot) => ({ ...bot, enabled: false })),
  156. });
  157. const count = h.sent.length;
  158. await h.run("late", "MUST_NOT_SEND");
  159. expect(h.sent).toHaveLength(count);
  160. });
  161. it("fans out a shared task to both bound bots without duplicating subscriptions", async () => {
  162. const h = setup({ version: 3, bots: [...f.telegramConfig.bots, ...f.feishuConfig.bots] });
  163. await h.service.saveConfig(await h.repo.readConfig());
  164. await h.run("desktop", "BOTH");
  165. expect(h.subscribe).toHaveBeenCalledOnce();
  166. expect(
  167. h.sent.filter((item) => /sendMessage|im\/v1\/messages(?:\?|$)/.test(item.url)),
  168. ).toHaveLength(2);
  169. });
  170. it("keeps automation summary delivery unique and restores normal streaming on the next run", async () => {
  171. const h = setup();
  172. await h.service.saveConfig(await h.repo.readConfig());
  173. await h.service.watchAutomationRun({
  174. target: h.actor,
  175. taskId: "task-1",
  176. workspacePath: "/tmp/workspace",
  177. });
  178. await h.emit("task_run_started", "cron", { startedAt: 1 });
  179. await h.emit("agent_message_chunk", "cron", { content: "CRON" });
  180. expect(h.sent.filter((item) => item.url.includes("sendMessage"))).toHaveLength(0);
  181. await h.emit("task_complete", "cron", { stopReason: "end_turn" });
  182. await h.emit("task_complete", "cron", { stopReason: "end_turn" });
  183. expect(h.sent.filter((item) => item.url.includes("sendMessage"))).toHaveLength(1);
  184. await h.run("next", "NEXT");
  185. expect(h.sent.filter((item) => item.url.includes("sendMessage"))).toHaveLength(2);
  186. expect(h.subscribe).toHaveBeenCalledOnce();
  187. });
  188. it("does not expose desktop or mobile questions as actionable IM prompts", async () => {
  189. const h = setup();
  190. await h.service.saveConfig(await h.repo.readConfig());
  191. await h.emit("task_run_started", "desktop", { inputOrigin: "desktop", startedAt: 1 });
  192. await h.emit("elicitation_request", "desktop", {
  193. requestId: "question",
  194. message: "PRIVATE",
  195. options: [],
  196. });
  197. await h.emit("permission_request", "desktop", { requestId: "permission", options: [] });
  198. expect(h.sent).toHaveLength(0);
  199. });
  200. it("uses the latest Weixin token and restores it with the same credential service", async () => {
  201. const h = setup({
  202. ...f.weixinConfig,
  203. bots: f.weixinConfig.bots.map((bot) => ({ ...bot, providerUserId: "bot-self" })),
  204. });
  205. const actor = { ...h.actor, providerUserId: "wx-user", providerContextToken: "token-1" };
  206. await h.service.handleInboundMessage({ botId: actor.botId, actor, text: "/status" });
  207. await h.run("first", "FIRST");
  208. await h.service.handleInboundMessage({
  209. botId: actor.botId,
  210. actor: { ...actor, providerContextToken: "token-2" },
  211. text: "/status",
  212. });
  213. await h.run("second", "SECOND");
  214. let replies = h.sent.filter((item) => item.url.includes("sendmessage"));
  215. expect(JSON.stringify(replies[0])).toContain("token-1");
  216. expect(JSON.stringify(replies[1])).toContain("token-2");
  217. expect(JSON.stringify(await h.service.getBotStates())).not.toContain("token-2");
  218. await h.service.disposeAllAndWait();
  219. const restarted = f.createBotsService({
  220. repo: h.repo as never,
  221. legacyTaskService: h.tasks,
  222. credentialService: h.credentials,
  223. runStartupBackgroundTasks: false,
  224. });
  225. services.push(restarted);
  226. await restarted.saveConfig(await h.repo.readConfig());
  227. await h.run("third", "THIRD");
  228. replies = h.sent.filter((item) => item.url.includes("sendmessage"));
  229. expect(replies).toHaveLength(3);
  230. expect(JSON.stringify(replies[2])).toContain("token-2");
  231. });
  232. it("stops forwarding old tasks after switching the binding", async () => {
  233. const h = setup();
  234. await h.service.saveConfig(await h.repo.readConfig());
  235. vi.mocked(h.tasks.listTasks).mockResolvedValue([
  236. { taskId: "task-2", title: "Second", provider: "glm" },
  237. ] as never);
  238. await h.service.handleInboundMessage({
  239. botId: h.actor.botId,
  240. actor: h.actor,
  241. text: "/task task-2",
  242. });
  243. await h.run("old", "DO_NOT_FORWARD");
  244. expect(h.sent.filter((item) => item.url.includes("sendMessage"))).toHaveLength(0);
  245. });
  246. it("exposes failed delivery and retries explicitly with the refreshed Weixin token", async () => {
  247. const h = setup({
  248. ...f.weixinConfig,
  249. bots: f.weixinConfig.bots.map((bot) => ({ ...bot, providerUserId: "bot-self" })),
  250. });
  251. const actor = { ...h.actor, providerUserId: "wx-user", providerContextToken: "expired" };
  252. await h.service.handleInboundMessage({ botId: actor.botId, actor, text: "/status" });
  253. h.fetchMock.mockImplementation(async (url, options) => {
  254. h.sent.push({ url: String(url), body: JSON.parse(String(options?.body ?? "{}")) });
  255. return new Response(
  256. JSON.stringify(
  257. String(options?.body).includes("expired") && String(url).includes("sendmessage")
  258. ? { ret: -2, errmsg: "prepare failed" }
  259. : { ret: 0 },
  260. ),
  261. );
  262. });
  263. await h.run("failed", "RETRY_ME");
  264. const runtime = (await h.service.getStatus()).botRuntime[0]!;
  265. expect(runtime.deliveryError).toContain("微信");
  266. expect(runtime.deliveryRetryId).toBeTruthy();
  267. const count = h.sent.filter((item) => item.url.includes("sendmessage")).length;
  268. await h.service.handleInboundMessage({
  269. botId: actor.botId,
  270. actor: { ...actor, providerContextToken: "fresh" },
  271. text: "/status",
  272. });
  273. expect(h.sent.filter((item) => item.url.includes("sendmessage"))).toHaveLength(count);
  274. await h.service.retryPrivateDelivery!({
  275. botId: actor.botId,
  276. deliveryId: runtime.deliveryRetryId!,
  277. });
  278. expect(JSON.stringify(h.sent.at(-1))).toContain("fresh");
  279. expect(JSON.stringify(h.sent.at(-1))).toContain("RETRY_ME");
  280. expect((await h.service.getStatus()).botRuntime[0]?.deliveryRetryId).toBeUndefined();
  281. });
  282. it("does not let a queued automation change an unrelated current run", async () => {
  283. const h = setup();
  284. await h.service.saveConfig(await h.repo.readConfig());
  285. await h.emit("task_run_started", "current", { startedAt: 1 });
  286. await h.service.watchAutomationRun({
  287. target: h.actor,
  288. taskId: "task-1",
  289. workspacePath: "/tmp/workspace",
  290. runId: "cron-queued",
  291. });
  292. await h.emit("agent_message_chunk", "current", { content: "LIVE_CURRENT\n\n" });
  293. await h.emit("tool_call", "current", {
  294. toolId: "tool-current",
  295. name: "read",
  296. status: "running",
  297. });
  298. expect(h.sent.some((item) => JSON.stringify(item.body).includes("LIVE_CURRENT"))).toBe(true);
  299. await h.emit("task_complete", "current", { stopReason: "end_turn" });
  300. const before = h.sent.length;
  301. await h.emit("task_run_started", "cron-queued", { startedAt: 2 });
  302. await h.emit("agent_message_chunk", "cron-queued", { content: "CRON_FINAL\n\n" });
  303. await h.emit("tool_call", "cron-queued", {
  304. toolId: "tool-cron",
  305. name: "read",
  306. status: "running",
  307. });
  308. expect(h.sent).toHaveLength(before);
  309. await h.emit("task_complete", "cron-queued", { stopReason: "end_turn" });
  310. expect(h.sent).toHaveLength(before + 1);
  311. });
  312. it("invalidates a saved retry when the binding is removed", async () => {
  313. const h = setup();
  314. await h.service.saveConfig(await h.repo.readConfig());
  315. h.fetchMock.mockImplementation(
  316. async () =>
  317. new Response(JSON.stringify({ ok: false, description: "blocked" }), { status: 403 }),
  318. );
  319. await h.run("failed", "FAILED");
  320. const id = (await h.service.getStatus()).botRuntime[0]!.deliveryRetryId!;
  321. expect(id).toBeTruthy();
  322. await h.service.resetBotState(h.actor.botId);
  323. await expect(
  324. h.service.retryPrivateDelivery!({ botId: h.actor.botId, deliveryId: id }),
  325. ).rejects.toThrow("no longer available");
  326. });
  327. it("records retry state for failures delivered inside a workspace mirror batch", async () => {
  328. const h = setup();
  329. await h.service.saveConfig(await h.repo.readConfig());
  330. h.fetchMock.mockImplementation(
  331. async () =>
  332. new Response(JSON.stringify({ ok: false, description: "blocked" }), { status: 403 }),
  333. );
  334. const base = { taskId: "task-1", traceId: "mirror", inputId: "mirror" };
  335. await h.emit("task_stream_mirror_batch", "mirror", {
  336. ops: [
  337. {
  338. kind: "stream_event",
  339. event: { ...base, type: "task_run_started", startedAt: 1, inputOrigin: "mobile" },
  340. },
  341. {
  342. kind: "stream_event",
  343. event: { ...base, type: "agent_message_chunk", content: "MIRRORED" },
  344. },
  345. { kind: "stream_event", event: { ...base, type: "task_complete", stopReason: "end_turn" } },
  346. ],
  347. });
  348. expect((await h.service.getStatus()).botRuntime[0]?.deliveryRetryId).toBeTruthy();
  349. });
  350. });