feishu-group-runtime.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { skipOccupationOnboardingIfPresent } from "../../../helpers/occupation-onboarding.js";
  2. import { restartWithSeededOpenAIProviders } from "../../../helpers/custom-openai-provider.js";
  3. import {
  4. selectUpstreamProviderModelById,
  5. waitForUpstreamModelSelected,
  6. } from "../../../helpers/upstream-provider.js";
  7. import { startConversationModelProviderReplayServer } from "../../../helpers/model-provider-replay.js";
  8. import { mkdir, readFile, writeFile } from "node:fs/promises";
  9. import { DatabaseSync } from "node:sqlite";
  10. import { join } from "node:path";
  11. import type { BotInboundMessage } from "@zcode/shared";
  12. import { createFeishuConfig } from "../../helpers/bots-service-harness.js";
  13. import { resolveE2EStorageRoot } from "../../../helpers/e2e-runtime-paths.js";
  14. import { clearAppData } from "../../../helpers/desktop-app.js";
  15. import { getTaskStoreSnapshot } from "../../../helpers/conversation-session-store.js";
  16. import {
  17. prepareV4ConversationE2E,
  18. sendV4Prompt,
  19. waitForV4TimelineContaining,
  20. waitForV4Pane,
  21. getV4PaneSnapshot,
  22. waitForV4QueueCount,
  23. getV4QueueItems,
  24. clickV4QueueItemDelete,
  25. clickV4Stop,
  26. selectV4TaskById,
  27. setV4ElectronWindowSize,
  28. } from "../../../helpers/v4-conversation.js";
  29. describe("BOT-E2E-GR-02/04 real Host CLI group queue", () => {
  30. let replay: Awaited<ReturnType<typeof startConversationModelProviderReplayServer>>;
  31. before(async () => {
  32. // 使用本用例的可控慢流 fixture,manual-review 默认 capture 不能冒充确定性回放。
  33. replay = await startConversationModelProviderReplayServer("feishu-group-runtime");
  34. });
  35. after(async () => {
  36. if ((await getV4PaneSnapshot()).canStop) await clickV4Stop();
  37. await browser.electron.restoreAllMocks();
  38. await clearAppData();
  39. await replay?.stop();
  40. });
  41. it("projects trusted group input into Desktop's real queue and cancels without stopping", async () => {
  42. await skipOccupationOnboardingIfPresent();
  43. await prepareV4ConversationE2E({ skipProvider: true });
  44. const [provider] = await restartWithSeededOpenAIProviders([
  45. {
  46. modelId: "deepseek-v4-flash",
  47. providerId: "e2e-group-runtime",
  48. providerName: "Group Runtime E2E",
  49. },
  50. ]);
  51. if (!provider) throw new Error("Group runtime replay provider missing");
  52. await prepareV4ConversationE2E({ skipProvider: true });
  53. await selectUpstreamProviderModelById("deepseek-v4-flash", {
  54. includePlainModelFallback: false,
  55. providerId: provider.id,
  56. providerName: provider.name,
  57. });
  58. await waitForUpstreamModelSelected("deepseek-v4-flash", {
  59. includePlainModelFallback: false,
  60. providerId: provider.id,
  61. });
  62. await sendV4Prompt("E2E_GROUP_RUNTIME_SLOW 慢慢回答");
  63. await waitForV4TimelineContaining("V4_QUEUE_STREAMING", 45000);
  64. await waitForV4Pane(
  65. (s) => s.canStop && !!s.sessionId && s.sessionId !== "draft",
  66. "initial turn is not running",
  67. 45000,
  68. );
  69. const pane = await getV4PaneSnapshot();
  70. const turnId = await browser.execute(() =>
  71. document.querySelector("[data-turn-id]")?.getAttribute("data-turn-id"),
  72. );
  73. expect(turnId).toBeTruthy();
  74. const task = await getTaskStoreSnapshot(pane.sessionId!);
  75. const workspacePath = task.workspaceKey!;
  76. expect(workspacePath).toBeTruthy();
  77. // V4 不再写旧 renderer activeInputId;从真实 CLI 输入账本按持久消息关联读取命令身份。
  78. const inputDatabase = new DatabaseSync(
  79. join(resolveE2EStorageRoot(), "cli", "db", "db.sqlite"),
  80. { readOnly: true },
  81. );
  82. let sourceCommandId: string;
  83. try {
  84. const record = inputDatabase
  85. .prepare(
  86. "select id, payload from session_input where session_id = ? and promoted_message_id = ?",
  87. )
  88. .get(pane.sessionId!, turnId!) as { id: string; payload: string } | undefined;
  89. expect(record).toBeTruthy();
  90. sourceCommandId = JSON.parse(record!.payload).intent?.sourceCommandId ?? record!.id;
  91. } finally {
  92. inputDatabase.close();
  93. }
  94. expect(sourceCommandId).toBeTruthy();
  95. const botId = "feishu-runtime-e2e";
  96. const chatId = "oc_runtime_e2e";
  97. const root = join(resolveE2EStorageRoot(), "v2");
  98. await mkdir(root, { recursive: true });
  99. const config = createFeishuConfig("feishu", botId);
  100. // 本用例仅通过真实 Host 服务输入,不向飞书发送网络请求。
  101. delete config.bots[0]!.credentialRef;
  102. await writeFile(join(root, "bot-config.v3.json"), JSON.stringify(config));
  103. await writeFile(
  104. join(root, "bot-state.v3.json"),
  105. JSON.stringify({
  106. version: 3,
  107. bots: {
  108. [JSON.stringify([botId, chatId])]: {
  109. botId,
  110. workspacePath,
  111. workspaceId: workspacePath,
  112. mode: "task",
  113. activeTaskId: pane.sessionId,
  114. updatedAt: Date.now(),
  115. group: {
  116. chatId,
  117. name: "E2E 协作群",
  118. ownerId: "ou_e2e_user",
  119. enabled: true,
  120. authorizationId: "e2e-authorization",
  121. taskIds: [pane.sessionId],
  122. currentOptions: {},
  123. deliveries: {
  124. "e2e-unknown": {
  125. id: "e2e-unknown",
  126. sourceCommandId,
  127. taskId: pane.sessionId,
  128. text: "E2E_SAVED_GROUP_RESULT",
  129. status: "unknown",
  130. updatedAt: Date.now(),
  131. },
  132. },
  133. },
  134. },
  135. },
  136. }),
  137. );
  138. const input: BotInboundMessage = {
  139. botId,
  140. text: "E2E_GROUP_RUNTIME_QUEUE 测试需求",
  141. attachments: [
  142. {
  143. id: "group-file",
  144. kind: "file",
  145. filename: "group-e2e.txt",
  146. mimeType: "text/plain",
  147. dataBase64: "Z3JvdXAtZmlsZQ==",
  148. sizeBytes: 10,
  149. },
  150. ],
  151. actor: {
  152. botId,
  153. provider: "feishu",
  154. chatType: "group",
  155. chatId,
  156. providerUserId: "ou_member",
  157. displayName: "E2E 群成员",
  158. providerMessageId: "om_runtime_e2e",
  159. },
  160. };
  161. const reply = await browser.execute(async (message) => {
  162. const actions = (
  163. window as unknown as {
  164. __testActions: {
  165. sendBotMessage(input: BotInboundMessage): Promise<Array<{ text: string }>>;
  166. };
  167. }
  168. ).__testActions;
  169. return actions.sendBotMessage(message);
  170. }, input);
  171. expect(reply.map((r) => r.text).join("\n")).toMatch(/等待执行|Waiting to run/);
  172. await waitForV4QueueCount(1, 30000);
  173. const items = await getV4QueueItems();
  174. expect(items[0]?.text).toContain("E2E_GROUP_RUNTIME_QUEUE");
  175. await browser.waitUntil(
  176. async () =>
  177. browser.execute(
  178. () =>
  179. document
  180. .querySelector('[data-testid="v4-queue"]')
  181. ?.textContent?.includes("group-e2e.txt") === true,
  182. ),
  183. { timeout: 15000 },
  184. );
  185. await browser.waitUntil(
  186. async () => browser.execute(() => document.body.innerText.includes("E2E 群成员")),
  187. { timeout: 15000 },
  188. );
  189. // 姓名保留在原队列标签中;点击查看稳定身份,不展开结果或新增提示面板。
  190. const memberLabel = await $('[data-testid="v4-queue"] [data-bot-group-source]');
  191. expect(await memberLabel.getText()).toContain("E2E 群成员");
  192. await memberLabel.click();
  193. const memberDetails = await $("[data-bot-group-member-details]");
  194. await memberDetails.waitForDisplayed({ timeout: 5000 });
  195. expect(await memberDetails.getText()).toContain("ou_member");
  196. await browser.keys("Escape");
  197. // 恢复入口属于已完成回复,队列与输入框之间不能再插入投递面板。
  198. expect(await browser.execute(() => !!document.querySelector("[data-bot-group-task]"))).toBe(
  199. false,
  200. );
  201. expect(await clickV4QueueItemDelete(items[0]!.queueItemId)).toBe(true);
  202. await waitForV4QueueCount(0, 30000);
  203. expect((await getV4PaneSnapshot()).canStop).toBe(true);
  204. await clickV4Stop();
  205. await waitForV4Pane((state) => !state.canStop, "first task did not stop", 30000);
  206. const deliveryAction = await $("[data-bot-group-delivery]");
  207. await deliveryAction.waitForExist({ timeout: 15000 });
  208. expect(
  209. await browser.execute(() => {
  210. const action = document.querySelector("[data-bot-group-delivery]");
  211. return action?.closest("[data-turn-id]")?.getAttribute("data-turn-id");
  212. }),
  213. ).toBe(turnId);
  214. expect(
  215. await browser.execute(() => document.body.innerText.includes("E2E_SAVED_GROUP_RESULT")),
  216. ).toBe(false);
  217. const originalSize = await browser.execute(() => ({
  218. width: window.outerWidth,
  219. height: window.outerHeight,
  220. }));
  221. await setV4ElectronWindowSize(430, 900);
  222. await deliveryAction.click();
  223. expect(
  224. await browser.execute(() => {
  225. const actions = document.querySelector("[data-bot-group-delivery-actions]");
  226. const bounds = actions?.getBoundingClientRect();
  227. return !!bounds && bounds.left >= 0 && bounds.right <= window.innerWidth;
  228. }),
  229. ).toBe(true);
  230. const received = await $("[data-bot-group-delivery-actions] button");
  231. await received.waitForDisplayed({ timeout: 15000 });
  232. await received.click();
  233. await browser.waitUntil(
  234. async () => browser.execute(() => !document.querySelector("[data-bot-group-delivery]")),
  235. { timeout: 15000 },
  236. );
  237. await setV4ElectronWindowSize(originalSize.width, originalSize.height);
  238. const sendGroup = async (text: string, senderId: string) =>
  239. browser.execute(
  240. async (message) => {
  241. return (
  242. window as unknown as {
  243. __testActions: { sendBotMessage(input: BotInboundMessage): Promise<unknown> };
  244. }
  245. ).__testActions.sendBotMessage(message);
  246. },
  247. {
  248. botId,
  249. text,
  250. actor: { ...input.actor, providerUserId: senderId, providerMessageId: `om_${text}` },
  251. },
  252. );
  253. const readPermissions = (sessionId?: string) => {
  254. // Node SQLite 只提供同步查询;只读隔离 E2E 数据库的一行并立即关闭。
  255. const database = new DatabaseSync(join(resolveE2EStorageRoot(), "cli", "db", "db.sqlite"), {
  256. readOnly: true,
  257. });
  258. try {
  259. if (sessionId) {
  260. const row = database
  261. .prepare("select permission from session where id = ?")
  262. .get(sessionId) as { permission: string };
  263. return JSON.parse(row.permission);
  264. }
  265. return database
  266. .prepare(
  267. "select scope_id, value from local_setting where namespace = 'permission' and key = 'mode' order by scope_id",
  268. )
  269. .all();
  270. } finally {
  271. database.close();
  272. }
  273. };
  274. const projectModes = readPermissions();
  275. // 复现停止后 Bot 遗留审批缓存:CLI 已空闲,旧卡片不能继续阻止 /new。
  276. const stoppedState = JSON.parse(await readFile(join(root, "bot-state.v3.json"), "utf8"));
  277. stoppedState.bots[JSON.stringify([botId, chatId])].pendingPermissionOptions = [
  278. {
  279. requestId: "stale-after-stop",
  280. optionId: "allow_once",
  281. command: "approve",
  282. label: "Allow",
  283. response: { decision: "allow", reason: "Approved once" },
  284. },
  285. ];
  286. await writeFile(join(root, "bot-state.v3.json"), JSON.stringify(stoppedState));
  287. await sendGroup("/new", "ou_e2e_user");
  288. const draftState = JSON.parse(await readFile(join(root, "bot-state.v3.json"), "utf8"));
  289. expect(draftState.bots[JSON.stringify([botId, chatId])].activeTaskId).toBeNull();
  290. expect(
  291. draftState.bots[JSON.stringify([botId, chatId])].pendingPermissionOptions ?? [],
  292. ).toHaveLength(0);
  293. await sendGroup("/mode yolo", "ou_e2e_user");
  294. await sendGroup("E2E_GROUP_RUNTIME_SLOW new group task", "ou_member");
  295. const persisted = JSON.parse(await readFile(join(root, "bot-state.v3.json"), "utf8"));
  296. const createdId = persisted.bots[JSON.stringify([botId, chatId])].activeTaskId as string;
  297. expect(createdId).toBeTruthy();
  298. expect(createdId).not.toBe(pane.sessionId);
  299. expect(readPermissions(createdId)).toMatchObject({ scope: "session", mode: "yolo" });
  300. expect(readPermissions()).toEqual(projectModes);
  301. await selectV4TaskById(createdId);
  302. await waitForV4TimelineContaining("V4_QUEUE_STREAMING", 45000);
  303. const senderGap = await browser.execute(() => {
  304. const bubble = document.querySelector("[data-v4-user-input-bubble]");
  305. const label = bubble?.parentElement?.querySelector("[data-bot-group-source]");
  306. if (!bubble || !label) return null;
  307. return bubble.getBoundingClientRect().top - label.getBoundingClientRect().bottom;
  308. });
  309. expect(senderGap).not.toBeNull();
  310. expect(senderGap!).toBeGreaterThanOrEqual(8);
  311. expect(senderGap!).toBeLessThanOrEqual(12);
  312. await clickV4Stop();
  313. await waitForV4Pane((state) => !state.canStop, "group reply did not stop", 30000);
  314. const failedAction = await $("[data-bot-group-delivery]");
  315. await failedAction.waitForExist({ timeout: 15000 });
  316. const completedGroup = JSON.parse(await readFile(join(root, "bot-state.v3.json"), "utf8"));
  317. const stoppedInput = Object.values(
  318. completedGroup.bots[JSON.stringify([botId, chatId])].group.inputs,
  319. ).find((value) => (value as { taskId: string }).taskId === createdId) as {
  320. progress?: { status: string };
  321. };
  322. expect(stoppedInput.progress?.status).toBe("stopped");
  323. const deliveries = Object.values(
  324. completedGroup.bots[JSON.stringify([botId, chatId])].group.deliveries,
  325. ) as Array<{ taskId: string; text: string; replyToMessageId?: string }>;
  326. const stoppedReply = deliveries.find((delivery) => delivery.taskId === createdId)!;
  327. expect(stoppedReply.text).toBe("Task stopped.");
  328. expect(stoppedReply.replyToMessageId).toBe("om_E2E_GROUP_RUNTIME_SLOW new group task");
  329. await failedAction.click();
  330. await $("[data-bot-group-delivery-actions] button").waitForDisplayed({ timeout: 15000 });
  331. });
  332. });