bot-automation-result-delivery.test.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type {
  5. ZCodeAutomationBotDeliveryTarget,
  6. ZCodeStreamEvent,
  7. } from "@zcode/shared";
  8. import { AutomationRepo, setDataBaseDir } from "@zcode/services/node";
  9. import {
  10. createBotsServiceHarness,
  11. createFeishuCallback,
  12. createFeishuConfig,
  13. createRecordingFeishuFetch,
  14. readBotSyntheticFixture,
  15. type RecordedRequest,
  16. } from "./helpers/bots-service-harness.js";
  17. describe("Bot automation terminal result delivery E2E", () => {
  18. const originalFetch = globalThis.fetch;
  19. let dataDir: string | null = null;
  20. let repo: AutomationRepo | null = null;
  21. let harness: ReturnType<typeof createBotsServiceHarness> | null = null;
  22. afterEach(async () => {
  23. harness?.service.disposeAll();
  24. harness = null;
  25. repo?.close();
  26. repo = null;
  27. setDataBaseDir(null);
  28. globalThis.fetch = originalFetch;
  29. if (dataDir) {
  30. await rm(dataDir, { recursive: true, force: true });
  31. dataDir = null;
  32. }
  33. });
  34. it("BOT-E2E-CR-01 persists the Bot target and delivers desktop run terminal events", async () => {
  35. const fixture = await readBotSyntheticFixture("automation-result-delivery.json");
  36. expect(fixture).toMatchObject({
  37. caseId: "BOT-E2E-CR-01",
  38. classification: "synthetic",
  39. timing: "controlled-stream",
  40. });
  41. expect(fixture.syntheticReason.length).toBeGreaterThan(20);
  42. const requests: RecordedRequest[] = [];
  43. globalThis.fetch = createRecordingFeishuFetch(requests);
  44. const config = createFeishuConfig();
  45. harness = createBotsServiceHarness({ config });
  46. const callback = await harness.service.handleProviderCallbackResponse(
  47. "feishu",
  48. createFeishuCallback(
  49. "feishu-e2e",
  50. `${fixture.promptMarker} 每天九点生成日报`,
  51. ),
  52. );
  53. expect(callback.ok).toBe(true);
  54. await waitFor(
  55. () => harness?.sendPromptCalls.length === 1,
  56. "Bot prompt dispatch",
  57. );
  58. const creationPrompt = harness.sendPromptCalls[0] as {
  59. botDeliveryTarget?: ZCodeAutomationBotDeliveryTarget;
  60. };
  61. expect(creationPrompt.botDeliveryTarget).toEqual({
  62. provider: "feishu",
  63. botId: "feishu-e2e",
  64. providerUserId: "ou_e2e_user",
  65. chatType: "private",
  66. });
  67. dataDir = await mkdtemp(join(tmpdir(), "zcode-bot-automation-e2e-"));
  68. setDataBaseDir(dataDir);
  69. repo = new AutomationRepo();
  70. const automation = await repo.create(
  71. {
  72. title: "Bot 日报",
  73. cronExpr: "0 9 * * *",
  74. prompt: "生成日报",
  75. workspacePath: "/workspace",
  76. targetTaskId: "task-e2e-bot",
  77. botDeliveryTarget: creationPrompt.botDeliveryTarget,
  78. recurring: true,
  79. },
  80. { nextRunAt: Date.now() + 60_000 },
  81. );
  82. repo.close();
  83. repo = new AutomationRepo();
  84. const persistedTarget = await repo.getBotDeliveryTarget(
  85. automation.automationId,
  86. automation.workspaceKey,
  87. );
  88. expect(persistedTarget).toEqual(creationPrompt.botDeliveryTarget);
  89. const subscriptionsBeforeRun = harness.subscriptions.length;
  90. await expect(
  91. harness.service.watchAutomationRun({
  92. target: persistedTarget!,
  93. workspacePath: automation.workspacePath,
  94. taskId: "task-e2e-automation-complete",
  95. }),
  96. ).resolves.toBeUndefined();
  97. // Host 只有在 watcher 已经进入 task service 后才允许继续 sendPrompt;快速终态不会漏回推。
  98. expect(harness.subscriptions).toHaveLength(subscriptionsBeforeRun + 1);
  99. const completionListener = harness.subscriptions.at(-1)?.listener;
  100. expect(completionListener).toBeDefined();
  101. await completionListener?.(streamEvent({
  102. type: "agent_message_chunk",
  103. taskId: "task-e2e-automation-complete",
  104. traceId: "trace-e2e-automation-complete",
  105. content: "日报已生成。",
  106. }));
  107. await completionListener?.(streamEvent({
  108. type: "task_complete",
  109. taskId: "task-e2e-automation-complete",
  110. traceId: "trace-e2e-automation-complete",
  111. stopReason: "end_turn",
  112. }));
  113. await waitFor(
  114. () => requests.some((request) => request.body?.includes("日报已生成")),
  115. "Feishu completion delivery",
  116. );
  117. await harness.service.watchAutomationRun({
  118. target: creationPrompt.botDeliveryTarget!,
  119. taskId: "task-e2e-automation-error",
  120. workspacePath: automation.workspacePath,
  121. });
  122. const errorListener = harness.subscriptions.at(-1)?.listener;
  123. await errorListener?.(streamEvent({
  124. type: "task_error",
  125. taskId: "task-e2e-automation-error",
  126. traceId: "trace-e2e-automation-error",
  127. error: "automation failed",
  128. }));
  129. await waitFor(
  130. () => requests.some((request) => request.body?.includes("automation failed")),
  131. "Feishu failure delivery",
  132. );
  133. const subscriptionsBeforeDisable = harness.subscriptions.length;
  134. config.bots = config.bots.map((bot) => ({ ...bot, enabled: false }));
  135. await expect(
  136. harness.service.watchAutomationRun({
  137. target: creationPrompt.botDeliveryTarget!,
  138. taskId: "task-e2e-automation-disabled",
  139. workspacePath: automation.workspacePath,
  140. }),
  141. ).resolves.toBeUndefined();
  142. expect(harness.subscriptions).toHaveLength(subscriptionsBeforeDisable);
  143. });
  144. });
  145. function streamEvent(event: ZCodeStreamEvent): ZCodeStreamEvent {
  146. return event;
  147. }
  148. async function waitFor(
  149. condition: () => boolean,
  150. label: string,
  151. timeoutMs = 5_000,
  152. ): Promise<void> {
  153. const startedAt = Date.now();
  154. while (!condition()) {
  155. if (Date.now() - startedAt >= timeoutMs) {
  156. throw new Error(`Timed out waiting for ${label}`);
  157. }
  158. await new Promise((resolve) => setTimeout(resolve, 10));
  159. }
  160. }