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

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