feishu-streaming-card-lifecycle.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import { readFile } from "node:fs/promises";
  2. import type { BotsConfigFile, BotsStateFile, ZCodeStreamEvent } from "@zcode/shared";
  3. import { createBotsService } from "@zcode/services/node";
  4. import { createBotModelSelectionView } from "./helpers/bots-service-harness.js";
  5. import { resolveE2ERuntimePath } from "../helpers/e2e-runtime-paths.js";
  6. const E2E_BOT_WORKSPACE = resolveE2ERuntimePath("bots", "e2e-bot-workspace");
  7. type LifecycleFixture = {
  8. caseId: string;
  9. classification: "synthetic";
  10. syntheticReason: string;
  11. prompt: string;
  12. events: Array<Record<string, unknown> & { type: ZCodeStreamEvent["type"] }>;
  13. expectedTimeline: string[];
  14. forbiddenCardMarkers: string[];
  15. };
  16. type RecordedRequest = {
  17. url: string;
  18. method: string;
  19. body?: string;
  20. };
  21. const FIXTURE_URL = new URL(
  22. "../fixtures/bots/feishu-streaming-card-lifecycle.json",
  23. import.meta.url,
  24. );
  25. describe("BOT-E2E-SC-01 Feishu streaming card lifecycle", () => {
  26. const originalFetch = globalThis.fetch;
  27. let service: ReturnType<typeof createBotsService> | undefined;
  28. afterEach(() => {
  29. service?.disposeAll();
  30. service = undefined;
  31. globalThis.fetch = originalFetch;
  32. });
  33. it("keeps callback, controlled task stream, typing and terminal output on one card", async () => {
  34. const fixture = JSON.parse(await readFile(FIXTURE_URL, "utf8")) as LifecycleFixture;
  35. expect(fixture.classification).toBe("synthetic");
  36. expect(fixture.syntheticReason.length).toBeGreaterThan(20);
  37. const requests: RecordedRequest[] = [];
  38. globalThis.fetch = createFeishuApiMock(requests);
  39. let config = createBotConfig();
  40. let state: BotsStateFile = { version: 3, bots: {} };
  41. const createTaskCalls: unknown[] = [];
  42. const sendPromptCalls: unknown[] = [];
  43. const subscriptions: Array<{
  44. params: Record<string, unknown>;
  45. listener: (event: ZCodeStreamEvent) => Promise<void> | void;
  46. }> = [];
  47. const zcodeTaskService = {
  48. listTasks: async () => [],
  49. createTask: async (params: unknown) => {
  50. createTaskCalls.push(params);
  51. return {
  52. taskId: "task-e2e-bot-streaming-card",
  53. title: "E2E Bot Streaming Card",
  54. workspacePath: E2E_BOT_WORKSPACE,
  55. provider: "glm",
  56. };
  57. },
  58. sendPrompt: async (params: unknown) => {
  59. sendPromptCalls.push(params);
  60. },
  61. setMode: async () => undefined,
  62. setConfigOption: async () => [],
  63. setModel: async () => [],
  64. setAutomationSessionConfig: async () => [],
  65. getTaskConfigOptions: async () => [],
  66. getTaskSnapshot: async () => null,
  67. getTaskTokenUsage: async () => ({
  68. sessionId: "task-e2e-bot-streaming-card",
  69. totalTokens: 0,
  70. inputTokens: 0,
  71. outputTokens: 0,
  72. reasoningTokens: 0,
  73. cacheCreationTokens: 0,
  74. cacheReadTokens: 0,
  75. modelRequestCount: 0,
  76. modelErrorCount: 0,
  77. inputBaselineBySource: {},
  78. }),
  79. resumeTask: async () => ({
  80. taskId: "task-e2e-bot-streaming-card",
  81. title: "E2E Bot Streaming Card",
  82. workspacePath: E2E_BOT_WORKSPACE,
  83. provider: "glm",
  84. }),
  85. respondPermission: async () => true,
  86. respondElicitation: async () => true,
  87. stopGeneration: async () => undefined,
  88. onDynamicTaskEvent:
  89. (params: Record<string, unknown>) =>
  90. (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  91. subscriptions.push({ params, listener });
  92. return { dispose() {} };
  93. },
  94. onDynamicStreamEvent: () => () => ({ dispose() {} }),
  95. };
  96. service = createBotsService({
  97. credentialService: {
  98. load: async (key: string) => (key === "feishu-secret" ? "app-secret" : null),
  99. save: async () => undefined,
  100. delete: async () => undefined,
  101. },
  102. zcodeTaskService,
  103. settingService: {
  104. get: async () => ({
  105. locale: "zh-CN",
  106. recentProjects: [E2E_BOT_WORKSPACE],
  107. lastWorkspaceSession: [{ kind: "local", workspacePath: E2E_BOT_WORKSPACE }],
  108. enabledBuiltinAgentCliProviders: ["glm"],
  109. }),
  110. update: async () => undefined,
  111. updateDataBaseDir: async () => undefined,
  112. ensureDefaultProject: async (path: string) => ({ path, created: false }),
  113. },
  114. repo: {
  115. readConfig: async () => config,
  116. writeConfig: async (next: BotsConfigFile) => (config = next),
  117. readState: async () => state,
  118. writeState: async (next: BotsStateFile) => (state = next),
  119. },
  120. modelSelectionService: {
  121. getView: async () => createBotModelSelectionView(),
  122. },
  123. runStartupBackgroundTasks: false,
  124. warmCandidateCachesOnStartup: false,
  125. } as never);
  126. const callbackResult = await service.handleProviderCallbackResponse("feishu", {
  127. botId: "feishu-e2e",
  128. event: {
  129. sender: { sender_id: { open_id: "ou_e2e_user" } },
  130. message: {
  131. chat_id: "oc_e2e_private",
  132. message_id: "om_e2e_inbound",
  133. chat_type: "p2p",
  134. message_type: "text",
  135. content: JSON.stringify({ text: fixture.prompt }),
  136. },
  137. },
  138. });
  139. expect(callbackResult.ok).toBe(true);
  140. expect(createTaskCalls).toHaveLength(1);
  141. expect(sendPromptCalls).toHaveLength(1);
  142. expect(JSON.stringify(sendPromptCalls[0])).toContain(fixture.prompt);
  143. expect(subscriptions).toHaveLength(1);
  144. expect(subscriptions[0]?.params).toMatchObject({
  145. taskId: "task-e2e-bot-streaming-card",
  146. deliveryKind: "bot-channel-continuous",
  147. });
  148. await waitForRequest(
  149. requests,
  150. (request) =>
  151. request.method === "POST" && request.url.endsWith("/messages/om_e2e_inbound/reactions"),
  152. "Typing reaction creation",
  153. );
  154. const listener = subscriptions[0]?.listener;
  155. expect(listener).toBeDefined();
  156. for (let index = 0; index < fixture.events.length; index += 1) {
  157. const event = {
  158. ...fixture.events[index],
  159. taskId: "task-e2e-bot-streaming-card",
  160. traceId: `trace-e2e-bot-${index}`,
  161. } as ZCodeStreamEvent;
  162. await listener?.(event);
  163. }
  164. await waitForRequest(
  165. requests,
  166. (request) => request.method === "DELETE" && request.url.endsWith("/reactions/reaction-e2e"),
  167. "Typing reaction cleanup",
  168. );
  169. const creates = requests.filter(
  170. (request) =>
  171. request.method === "POST" &&
  172. request.url.includes("/open-apis/im/v1/messages?receive_id_type=open_id"),
  173. );
  174. const updates = requests.filter(
  175. (request) => request.method === "PATCH" && request.url.endsWith("/messages/om_e2e_streaming"),
  176. );
  177. expect(creates).toHaveLength(1);
  178. expect(updates.length).toBeGreaterThanOrEqual(2);
  179. const runningCards = updates
  180. .map(readCardFromRequest)
  181. .filter((card) => JSON.stringify(card).includes("工具摘要"));
  182. expect(
  183. runningCards.some((card) =>
  184. readCardElements(card).some(
  185. (element) => element.tag === "collapsible_panel" && element.expanded === true,
  186. ),
  187. ),
  188. ).toBe(true);
  189. const finalCard = readCardFromRequest(updates.at(-1));
  190. const finalElements = readCardElements(finalCard);
  191. const timeline = finalElements.map((element) =>
  192. element.tag === "collapsible_panel"
  193. ? `tools:${String(readPanelTitle(element))}:${String(element.expanded)}`
  194. : `message:${String(element.content)}`,
  195. );
  196. expect(timeline).toEqual(fixture.expectedTimeline);
  197. expect(
  198. finalElements
  199. .filter((element) => element.tag === "collapsible_panel")
  200. .every((element) => element.expanded === false),
  201. ).toBe(true);
  202. const finalCardJson = JSON.stringify(finalCard);
  203. for (const forbidden of fixture.forbiddenCardMarkers) {
  204. expect(finalCardJson).not.toContain(forbidden);
  205. }
  206. });
  207. });
  208. function createBotConfig(): BotsConfigFile {
  209. return {
  210. version: 3,
  211. bots: [
  212. {
  213. id: "feishu-e2e",
  214. name: "Feishu E2E",
  215. provider: "feishu",
  216. enabled: true,
  217. credentialRef: "feishu-secret",
  218. feishuAppId: "cli_e2e",
  219. providerUserId: "ou_e2e_user",
  220. allowedWorkspaces: ["*"],
  221. allowedCommands: {
  222. status: true,
  223. new: true,
  224. workspace: true,
  225. model: true,
  226. thoughtLevel: true,
  227. sandboxMode: true,
  228. approvalPolicy: true,
  229. reply: true,
  230. },
  231. currentOptions: {},
  232. replyMode: "streaming_card",
  233. },
  234. ],
  235. };
  236. }
  237. function createFeishuApiMock(requests: RecordedRequest[]): typeof fetch {
  238. return async (input, init) => {
  239. const url = String(input);
  240. const method = init?.method ?? "GET";
  241. requests.push({
  242. url,
  243. method,
  244. ...(typeof init?.body === "string" ? { body: init.body } : {}),
  245. });
  246. if (url.endsWith("/tenant_access_token/internal")) {
  247. return new Response(JSON.stringify({ code: 0, tenant_access_token: "tenant-token-e2e" }));
  248. }
  249. if (url.endsWith("/messages/om_e2e_inbound/reactions") && method === "POST") {
  250. return new Response(JSON.stringify({ code: 0, data: { reaction_id: "reaction-e2e" } }));
  251. }
  252. if (url.includes("/open-apis/im/v1/messages?receive_id_type=open_id")) {
  253. return new Response(JSON.stringify({ code: 0, data: { message_id: "om_e2e_streaming" } }));
  254. }
  255. if (url.includes("/contact/v3/users/")) {
  256. return new Response(JSON.stringify({ code: 0, data: { user: { name: "E2E User" } } }));
  257. }
  258. return new Response(JSON.stringify({ code: 0 }));
  259. };
  260. }
  261. async function waitForRequest(
  262. requests: RecordedRequest[],
  263. predicate: (request: RecordedRequest) => boolean,
  264. label: string,
  265. ) {
  266. const deadline = Date.now() + 10_000;
  267. while (Date.now() < deadline) {
  268. if (requests.some(predicate)) {
  269. return;
  270. }
  271. await new Promise((resolve) => setTimeout(resolve, 10));
  272. }
  273. throw new Error(`Timed out waiting for ${label}`);
  274. }
  275. function readCardFromRequest(request: RecordedRequest | undefined): Record<string, unknown> {
  276. const body = JSON.parse(request?.body ?? "{}") as { content?: string };
  277. return JSON.parse(body.content ?? "{}") as Record<string, unknown>;
  278. }
  279. function readCardElements(card: Record<string, unknown>): Array<Record<string, unknown>> {
  280. return (card.body as { elements?: Array<Record<string, unknown>> } | undefined)?.elements ?? [];
  281. }
  282. function readPanelTitle(element: Record<string, unknown>): string | undefined {
  283. return (element.header as { title?: { content?: string } } | undefined)?.title?.content;
  284. }