conversation-session-plan-approval-feedback-user-message.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { getLatestUpstreamToolResultByToolCallId } from "#e2e/helpers/conversation-session-network";
  2. import { readFile } from "node:fs/promises";
  3. import type { E2ENetworkCaptureArtifact } from "#e2e/helpers/network-capture-proxy";
  4. import { clearAppData } from "#e2e/helpers/desktop-app";
  5. import {
  6. getV4Messages,
  7. prepareV4ConversationE2E,
  8. sendV4Prompt,
  9. waitForV4AssistantMessageContaining,
  10. waitForV4ComposerText,
  11. waitForV4UserMessageContaining,
  12. } from "#e2e/helpers/v4-conversation";
  13. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  14. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  15. const PROMPT_MARKER = "E2E_PLAN_APPROVAL_FEEDBACK_USER_MESSAGE";
  16. const ENTER_MARKER = "E2E_PLAN_APPROVAL_ENTER_PLAN";
  17. const EXIT_MARKER = "E2E_PLAN_APPROVAL_EXIT_PLAN";
  18. const FEEDBACK_MARKER = "E2E_PLAN_APPROVAL_FEEDBACK";
  19. const EXIT_TOOL_CALL_ID = "toolu_e2e_plan_approval_exit_plan_mode";
  20. const EXIT_PLAN_DENIED_MESSAGE = "The plan was not approved by the user.";
  21. describe("conversation session plan approval feedback user message", () => {
  22. after(async () => {
  23. await browser.electron.restoreAllMocks();
  24. await clearAppData();
  25. });
  26. it("persists custom ExitPlanMode feedback as a visible user message", async () => {
  27. await prepareV4ConversationE2E();
  28. const runId = Date.now();
  29. const prompt = [
  30. `${PROMPT_MARKER}_${runId}: enter plan mode and request approval.`,
  31. `${ENTER_MARKER}: call EnterPlanMode before drafting.`,
  32. `${EXIT_MARKER}: call ExitPlanMode with the proposed plan.`,
  33. ].join(" ");
  34. const feedback = `${FEEDBACK_MARKER}_${runId}: add explicit test coverage before implementation.`;
  35. await sendV4Prompt(prompt);
  36. await waitForV4ComposerText("", "composer should clear after sending prompt");
  37. await waitForV4UserMessageContaining(PROMPT_MARKER);
  38. await waitForUpstreamRequest(
  39. {
  40. includes: [PROMPT_MARKER, ENTER_MARKER, EXIT_MARKER],
  41. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  42. },
  43. "initial plan-mode request",
  44. 60_000,
  45. );
  46. // EnterPlanMode 是隐藏的控制工具;用真实结果证明进入计划模式。
  47. await browser.waitUntil(
  48. async () =>
  49. (await getLatestUpstreamToolResultByToolCallId("toolu_e2e_plan_approval_enter_plan_mode"))
  50. ?.isError === false,
  51. { timeout: 60000, timeoutMsg: "EnterPlanMode 没有成功执行" },
  52. );
  53. await waitForUpstreamRequest(
  54. {
  55. includes: [EXIT_MARKER, "toolu_e2e_plan_approval_enter_plan_mode"],
  56. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  57. },
  58. "exit plan-mode request",
  59. 60_000,
  60. );
  61. await waitForToolCallBlockByToolName("ExitPlanMode", 60_000);
  62. await waitForPlanApprovalDialog(60_000);
  63. await submitCustomElicitationAnswer(feedback);
  64. await waitForUpstreamRequest(
  65. {
  66. includes: [feedback, EXIT_MARKER, EXIT_TOOL_CALL_ID, EXIT_PLAN_DENIED_MESSAGE],
  67. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  68. },
  69. "plan feedback continuation request",
  70. 60_000,
  71. );
  72. await waitForV4UserMessageContaining(feedback);
  73. await waitForUserMessageNotContaining(feedback, "Conversation steered");
  74. await waitForUserMessageNotContaining(feedback, "已引导对话");
  75. const ordering = await waitForPlanFeedbackProviderOrdering(feedback, EXIT_TOOL_CALL_ID, 10_000);
  76. expect(ordering.feedbackIndex).toBeGreaterThan(ordering.toolResultIndex);
  77. expect(ordering.toolResultText).toContain(EXIT_PLAN_DENIED_MESSAGE);
  78. expect(ordering.toolResultText).not.toContain(feedback);
  79. await waitForV4AssistantMessageContaining("upstream-e2e-ok");
  80. });
  81. });
  82. async function waitForPlanApprovalDialog(timeoutMs: number) {
  83. const expectedText = ["Approve", "批准", "Implementation plan", "实施计划"];
  84. await browser.waitUntil(
  85. async () => {
  86. const body = await $("[data-elicitation-dialog-body='true']");
  87. if (!(await body.isExisting())) {
  88. return false;
  89. }
  90. const input = await $("[data-elicitation-dialog-body='true'] textarea");
  91. if (!(await input.isExisting())) {
  92. return false;
  93. }
  94. const footer = await $("[data-elicitation-dialog-footer='true']");
  95. if (!(await footer.isExisting())) {
  96. return false;
  97. }
  98. const bodyText = await body.getText();
  99. // 修复原因:plan approval 选项会走 i18n,本地/CI 语言不同时不能只等英文 Approve。
  100. return expectedText.some((text) => bodyText.includes(text));
  101. },
  102. {
  103. timeout: timeoutMs,
  104. timeoutMsg: "Timed out waiting for plan approval elicitation dialog",
  105. },
  106. );
  107. }
  108. async function waitForUserMessageNotContaining(requiredText: string, forbiddenText: string) {
  109. await browser.waitUntil(
  110. async () => {
  111. const message = await findUserMessageTextContaining(requiredText);
  112. return message !== null && !message.includes(forbiddenText);
  113. },
  114. {
  115. timeout: 30_000,
  116. timeoutMsg: `Timed out waiting for user message containing ${requiredText} without ${forbiddenText}`,
  117. },
  118. );
  119. }
  120. async function findUserMessageTextContaining(text: string): Promise<string | null> {
  121. // 反馈已进入 V4 用户消息;旧 chat-user-message 节点不再渲染。
  122. return (await getV4Messages("user")).find((message) => message.text.includes(text))?.text ?? null;
  123. }
  124. async function submitCustomElicitationAnswer(answer: string) {
  125. const input = await $("[data-elicitation-dialog-body='true'] textarea");
  126. await input.waitForDisplayed({ timeout: 30_000 });
  127. await input.setValue(answer);
  128. const submitButton = await $("//button[contains(., 'Submit') or contains(., '提交')]");
  129. await submitButton.waitForEnabled({ timeout: 30_000 });
  130. await submitButton.click();
  131. }
  132. type ProviderOrdering = {
  133. feedbackIndex: number;
  134. toolResultIndex: number;
  135. toolResultText: string;
  136. };
  137. async function waitForPlanFeedbackProviderOrdering(
  138. feedback: string,
  139. toolCallId: string,
  140. timeoutMs: number,
  141. ): Promise<ProviderOrdering> {
  142. let latestError = "";
  143. await browser.waitUntil(
  144. async () => {
  145. try {
  146. const ordering = await readPlanFeedbackProviderOrdering(feedback, toolCallId);
  147. if (ordering.toolResultIndex >= 0 && ordering.feedbackIndex > ordering.toolResultIndex) {
  148. return true;
  149. }
  150. latestError = JSON.stringify(ordering);
  151. return false;
  152. } catch (error) {
  153. latestError = error instanceof Error ? error.message : String(error);
  154. return false;
  155. }
  156. },
  157. {
  158. timeout: timeoutMs,
  159. timeoutMsg: `Timed out waiting for provider ordering: ${latestError}`,
  160. },
  161. );
  162. return readPlanFeedbackProviderOrdering(feedback, toolCallId);
  163. }
  164. async function readPlanFeedbackProviderOrdering(
  165. feedback: string,
  166. toolCallId: string,
  167. ): Promise<ProviderOrdering> {
  168. const artifact = await readCaptureArtifact();
  169. const matchingRecord = [...artifact.records].reverse().find((record) => {
  170. const requestJson = record.requestJson;
  171. return (
  172. requestJson !== undefined &&
  173. captureContainsText(requestJson, feedback) &&
  174. captureContainsText(requestJson, toolCallId)
  175. );
  176. });
  177. if (!matchingRecord?.requestJson) {
  178. throw new Error("No provider request contains both feedback and tool call id");
  179. }
  180. const blocks = flattenProviderMessageBlocks(matchingRecord.requestJson);
  181. const toolResultIndex = blocks.findIndex((block) => block.toolUseId === toolCallId);
  182. const feedbackIndex = blocks.findIndex(
  183. (block) => block.role === "user" && block.text.includes(feedback),
  184. );
  185. const toolResultText = toolResultIndex >= 0 ? (blocks[toolResultIndex]?.text ?? "") : "";
  186. return {
  187. feedbackIndex,
  188. toolResultIndex,
  189. toolResultText,
  190. };
  191. }
  192. async function readCaptureArtifact(): Promise<E2ENetworkCaptureArtifact> {
  193. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH;
  194. if (!capturePath) {
  195. throw new Error("E2E_PROVIDER_CAPTURE_PATH is not set");
  196. }
  197. return JSON.parse(await readFile(capturePath, "utf8")) as E2ENetworkCaptureArtifact;
  198. }
  199. function captureContainsText(value: unknown, needle: string): boolean {
  200. if (typeof value === "string") {
  201. return value.includes(needle);
  202. }
  203. if (Array.isArray(value)) {
  204. return value.some((item) => captureContainsText(item, needle));
  205. }
  206. if (value && typeof value === "object") {
  207. return Object.values(value).some((item) => captureContainsText(item, needle));
  208. }
  209. return false;
  210. }
  211. type ProviderBlock = {
  212. role: string;
  213. text: string;
  214. toolUseId?: string;
  215. };
  216. function flattenProviderMessageBlocks(requestJson: unknown): ProviderBlock[] {
  217. const messages = readMessages(requestJson);
  218. const blocks: ProviderBlock[] = [];
  219. for (const message of messages) {
  220. const role = readStringProperty(message, "role") ?? "";
  221. const content = readProperty(message, "content");
  222. if (Array.isArray(content)) {
  223. for (const block of content) {
  224. blocks.push({
  225. role,
  226. text: readProviderText(block),
  227. toolUseId: readStringProperty(block, "tool_use_id"),
  228. });
  229. }
  230. continue;
  231. }
  232. blocks.push({
  233. role,
  234. text: readProviderText(content),
  235. });
  236. }
  237. return blocks;
  238. }
  239. function readMessages(requestJson: unknown): unknown[] {
  240. const messages = readProperty(requestJson, "messages");
  241. return Array.isArray(messages) ? messages : [];
  242. }
  243. function readProviderText(value: unknown): string {
  244. if (typeof value === "string") {
  245. return value;
  246. }
  247. if (Array.isArray(value)) {
  248. return value.map(readProviderText).join("\n");
  249. }
  250. if (value && typeof value === "object") {
  251. const text = readStringProperty(value, "text");
  252. if (text !== undefined) {
  253. return text;
  254. }
  255. return JSON.stringify(value);
  256. }
  257. return "";
  258. }
  259. function readProperty(value: unknown, key: string): unknown {
  260. if (!value || typeof value !== "object") {
  261. return undefined;
  262. }
  263. return (value as Record<string, unknown>)[key];
  264. }
  265. function readStringProperty(value: unknown, key: string): string | undefined {
  266. const property = readProperty(value, key);
  267. return typeof property === "string" ? property : undefined;
  268. }