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

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