conversation-session-v4-rewind-files.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // PV4-21/PV4-22:editUserQuery(workspaceMode=rewind) 的文件事务与冲突降级。
  2. // 证据层 L3:真实 Read/Write checkpoint + 行内三按钮 + Agent preview/apply +
  3. // same-session branch cut。冲突路径还断言 blocked 期间文件/对话/provider request 均不变。
  4. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { TID_V4_FEEDBACK_LIKE } from "@zcode/shared/test-ids";
  7. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  8. import { countUpstreamRequestsContaining } from "#e2e/helpers/conversation-session-network";
  9. import {
  10. approveV4Permission,
  11. beginFirstV4UserQueryEdit,
  12. clickV4EditConflictConversationOnly,
  13. clickV4EditWorkspaceReset,
  14. getV4PaneSnapshot,
  15. prepareV4ConversationE2E,
  16. sendV4Prompt,
  17. switchV4Mode,
  18. waitForV4Edit,
  19. waitForV4EditWorkspaceConflict,
  20. waitForLatestV4CommandAck,
  21. waitForV4Pane,
  22. waitForV4PermissionDialog,
  23. waitForV4TimelineContaining,
  24. } from "#e2e/helpers/v4-conversation";
  25. import {
  26. beginConversationTelemetryCapture,
  27. readAllEventReportRequests,
  28. type ConversationTelemetryCaptureHandle,
  29. type ConversationTelemetryReport,
  30. } from "#e2e/helpers/conversation-telemetry-parity-capture";
  31. const CASE_ROOT = join(DEFAULT_WORKSPACE, "v4-rewind-files-e2e");
  32. const SAFE_RELATIVE_PATH = "v4-rewind-files-e2e/safe.txt";
  33. const CONFLICT_RELATIVE_PATH = "v4-rewind-files-e2e/conflict.txt";
  34. const SAFE_PATH = join(DEFAULT_WORKSPACE, SAFE_RELATIVE_PATH);
  35. const CONFLICT_PATH = join(DEFAULT_WORKSPACE, CONFLICT_RELATIVE_PATH);
  36. // fixtures/upstream/conversation-session/conversation-session-v4-rewind-files.json 里 PV4-21 原轮的两个工具调用。
  37. const SAFE_READ_TOOL_ID = "toolu_v4_rewind_files_safe_read";
  38. const SAFE_WRITE_TOOL_ID = "toolu_v4_rewind_files_safe_write";
  39. describe("PV4-21/PV4-22 conversation + file rewind", () => {
  40. afterEach(async () => {
  41. await rm(CASE_ROOT, { force: true, recursive: true });
  42. });
  43. after(async () => {
  44. await browser.electron.restoreAllMocks();
  45. await clearAppData();
  46. });
  47. it("PV4-21 safe checkpoint 倒序恢复文件后才提交 same-session branch", async function () {
  48. this.timeout(150000);
  49. await prepareFileCase(SAFE_PATH);
  50. const capture = await beginConversationTelemetryCapture();
  51. await sendV4Prompt("E2E_V4_REWIND_FILE_SAFE 请更新 safe.txt");
  52. await approvePendingFileWriteIfRequired();
  53. await waitForV4TimelineContaining("V4_REWIND_FILE_SAFE_ORIGINAL_REPLY", 90000);
  54. await waitForFileContent(SAFE_PATH, "safe-after\n");
  55. const originalSessionId = (await getV4PaneSnapshot()).sessionId;
  56. // 点赞埋点要关联到所在轮:先赞原回复,编辑重发后再赞新回复(MR E source_message_id)。
  57. await clickOnlyFeedbackLike();
  58. await waitForV4Edit();
  59. const rowId = await beginFirstV4UserQueryEdit("E2E_V4_REWIND_FILE_SAFE_EDITED 文件恢复后重发");
  60. await clickV4EditWorkspaceReset(rowId);
  61. const rewindAck = await waitForLatestV4CommandAck("editUserQuery", 30000).catch(
  62. async (error) => {
  63. const fileState = await readFile(SAFE_PATH, "utf8").catch(() => "<missing>");
  64. throw new Error(
  65. `${error instanceof Error ? error.message : String(error)}; safe.txt=${JSON.stringify(fileState)}`,
  66. );
  67. },
  68. );
  69. expect(rewindAck.status).toBe("accepted");
  70. await waitForV4TimelineContaining("V4_REWIND_FILE_SAFE_EDITED_REPLY", 90000);
  71. await waitForV4Pane((snapshot) => !snapshot.canStop, "safe 组合 rewind 没有回到 idle", 60000);
  72. expect(await readFile(SAFE_PATH, "utf8")).toBe("safe-before\n");
  73. const finalSnapshot = await getV4PaneSnapshot();
  74. expect(finalSnapshot.sessionId).toBe(originalSessionId);
  75. expect(finalSnapshot.timelineText).not.toContain("V4_REWIND_FILE_SAFE_ORIGINAL_REPLY");
  76. expect(finalSnapshot.timelineText).not.toContain("Conversation rewind applied");
  77. await clickOnlyFeedbackLike();
  78. // 再点一次取消:上报 reaction=none,同样带所在轮。
  79. await clickOnlyFeedbackLike(false);
  80. // 编辑重发轮与普通发送一样有 send_btn / completion(send_type=edit),并记一条回退结果。
  81. const { reports, rewinds } = await waitForEditTelemetry(capture, 1);
  82. const original = reports.find(
  83. (r) => r.element_name === "send_btn" && detail(r).send_type === "normal",
  84. );
  85. expect(rewinds[0]!.talk_id).toBe(original?.talk_id);
  86. expect(detail(rewinds[0]!)).toMatchObject({
  87. action: "edit_resend",
  88. workspace_mode: "rewind",
  89. result: "accepted",
  90. blocked_reason: "",
  91. target_message_id: original?.message_id,
  92. target_turn_state: "completedSuccess",
  93. discarded_turns: "1",
  94. });
  95. expectEditTurnReported(reports, String(rewinds[0]!.message_id));
  96. // 反馈的 message_id 是 assistant 行 entityId;source_message_id 才是所在轮的
  97. // send_btn / message_completion message_id:原回复对应普通发送,新回复对应编辑重发轮。
  98. const { all, feedbacks } = await waitForFeedbackReports(capture, 3);
  99. expect(feedbacks).toHaveLength(3);
  100. expect(detail(feedbacks[0]!)).toMatchObject({
  101. reaction: "like",
  102. source_message_id: original?.message_id,
  103. });
  104. for (const [index, reaction] of [
  105. [1, "like"],
  106. [2, "none"],
  107. ] as const) {
  108. expect(detail(feedbacks[index]!)).toMatchObject({
  109. reaction,
  110. source_message_id: rewinds[0]!.message_id,
  111. });
  112. expect(feedbacks[index]!.message_id).toBe(feedbacks[1]!.message_id);
  113. }
  114. for (const feedback of feedbacks) {
  115. expect(feedback.talk_id).toBe(original?.talk_id);
  116. expect(feedback.message_id).toBeTruthy();
  117. expect(feedback.message_id).not.toBe(detail(feedback).source_message_id);
  118. }
  119. expect(feedbacks[0]!.message_id).not.toBe(feedbacks[1]!.message_id);
  120. // 数据侧真正要的是按这个 ID 找到该轮的分析事件:原轮的 completion 与 Read、Write 两个工具 step
  121. // 都要以同一个 message_id 上报(按 fixture 的 tool_call_id 逐个核对,只数条数分不出重复的 Read);
  122. // 编辑重发轮的 fixture 只回文本,它只核对 send_btn / completion(expectEditTurnReported)。
  123. const sourceId = detail(feedbacks[0]!).source_message_id;
  124. const turnEvents = (name: string) =>
  125. all.filter(
  126. (r) =>
  127. r.element_name === name && r.message_id === sourceId && r.talk_id === original?.talk_id,
  128. );
  129. expect(turnEvents("message_completion")).toHaveLength(1);
  130. const toolCallIds = turnEvents("agent_step")
  131. .filter((r) => detail(r).step_type === "tool_call")
  132. .map((r) => detail(r).tool_call_id);
  133. expect(toolCallIds).toEqual(expect.arrayContaining([SAFE_READ_TOOL_ID, SAFE_WRITE_TOOL_ID]));
  134. });
  135. it("PV4-22 external modified 先 blocked,新 commandId 降级后只裁对话", async function () {
  136. this.timeout(150000);
  137. await prepareFileCase(CONFLICT_PATH);
  138. const capture = await beginConversationTelemetryCapture();
  139. await sendV4Prompt("E2E_V4_REWIND_FILE_CONFLICT 请更新 conflict.txt");
  140. await approvePendingFileWriteIfRequired();
  141. await waitForV4TimelineContaining("V4_REWIND_FILE_CONFLICT_ORIGINAL_REPLY", 90000);
  142. await waitForFileContent(CONFLICT_PATH, "conflict-after\n");
  143. await writeFile(CONFLICT_PATH, "external-wins\n", "utf8");
  144. const editedMarker = "E2E_V4_REWIND_FILE_CONFLICT_EDITED";
  145. const requestsBefore = await countUpstreamRequestsContaining(editedMarker);
  146. await waitForV4Edit();
  147. const rowId = await beginFirstV4UserQueryEdit(`${editedMarker} 只重置对话`);
  148. await clickV4EditWorkspaceReset(rowId);
  149. await waitForV4EditWorkspaceConflict(60000);
  150. expect(await readFile(CONFLICT_PATH, "utf8")).toBe("external-wins\n");
  151. expect((await getV4PaneSnapshot()).timelineText).toContain(
  152. "V4_REWIND_FILE_CONFLICT_ORIGINAL_REPLY",
  153. );
  154. expect(await countUpstreamRequestsContaining(editedMarker)).toBe(requestsBefore);
  155. await clickV4EditConflictConversationOnly();
  156. await waitForV4TimelineContaining("V4_REWIND_FILE_CONFLICT_EDITED_REPLY", 90000);
  157. expect(await readFile(CONFLICT_PATH, "utf8")).toBe("external-wins\n");
  158. const finalSnapshot = await getV4PaneSnapshot();
  159. expect(finalSnapshot.timelineText).not.toContain("V4_REWIND_FILE_CONFLICT_ORIGINAL_REPLY");
  160. expect(await countUpstreamRequestsContaining(editedMarker)).toBe(requestsBefore + 1);
  161. // 冲突那次只记 blocked、不产生 send_btn;降级后的「只重置对话」才是真正的编辑重发轮。
  162. const { reports, rewinds } = await waitForEditTelemetry(capture, 2);
  163. expect(detail(rewinds[0]!)).toMatchObject({
  164. action: "edit_resend",
  165. workspace_mode: "rewind",
  166. result: "blocked",
  167. });
  168. expect(["unsafe_files", "apply_conflict"]).toContain(detail(rewinds[0]!).blocked_reason);
  169. expect(detail(rewinds[1]!)).toMatchObject({
  170. action: "edit_resend",
  171. workspace_mode: "preserve",
  172. result: "accepted",
  173. target_turn_state: "completedSuccess",
  174. target_message_id: detail(rewinds[0]!).target_message_id,
  175. });
  176. expect(
  177. reports.filter(
  178. (r) => r.element_name === "send_btn" && r.message_id === rewinds[0]!.message_id,
  179. ),
  180. ).toHaveLength(0);
  181. expectEditTurnReported(reports, String(rewinds[1]!.message_id));
  182. });
  183. });
  184. async function prepareFileCase(filePath: string) {
  185. await rm(CASE_ROOT, { force: true, recursive: true });
  186. await mkdir(CASE_ROOT, { recursive: true });
  187. await writeFile(filePath, filePath === SAFE_PATH ? "safe-before\n" : "conflict-before\n", "utf8");
  188. await prepareV4ConversationE2E();
  189. await switchV4Mode("yolo");
  190. }
  191. async function waitForFileContent(filePath: string, expected: string) {
  192. await browser.waitUntil(
  193. async () => (await readFile(filePath, "utf8").catch(() => "")) === expected,
  194. { timeout: 60000, timeoutMsg: `${filePath} 没有收敛到期望内容` },
  195. );
  196. }
  197. async function approvePendingFileWriteIfRequired() {
  198. try {
  199. await waitForV4PermissionDialog(15000);
  200. expect(await approveV4Permission()).toBe(true);
  201. } catch {
  202. // yolo 模式会直接执行;不同 permission registry 状态下也可能显式请求一次授权。
  203. }
  204. }
  205. function detail(report: ConversationTelemetryReport): Record<string, string> {
  206. return (report.event_extra_detail ?? {}) as Record<string, string>;
  207. }
  208. async function waitForEditTelemetry(
  209. capture: ConversationTelemetryCaptureHandle,
  210. rewindCount: number,
  211. ) {
  212. let reports: ConversationTelemetryReport[] = [];
  213. const editCompletions = () =>
  214. reports.filter(
  215. (r) => r.element_name === "message_completion" && detail(r).send_type === "edit",
  216. );
  217. await browser.waitUntil(
  218. async () => {
  219. reports = await readAllEventReportRequests(capture);
  220. return (
  221. reports.filter((r) => r.element_name === "conversation_rewind").length >= rewindCount &&
  222. editCompletions().length >= 1
  223. );
  224. },
  225. { timeout: 30000, timeoutMsg: "编辑重发的 conversation_rewind / message_completion 没有上报" },
  226. );
  227. return { reports, rewinds: reports.filter((r) => r.element_name === "conversation_rewind") };
  228. }
  229. function expectEditTurnReported(reports: ConversationTelemetryReport[], messageId: string) {
  230. const sends = reports.filter((r) => r.element_name === "send_btn" && r.message_id === messageId);
  231. expect(sends).toHaveLength(1);
  232. expect(detail(sends[0]!).send_type).toBe("edit");
  233. const completion = reports.find(
  234. (r) => r.element_name === "message_completion" && r.message_id === messageId,
  235. );
  236. expect(completion && detail(completion)).toMatchObject({ send_type: "edit", status: "success" });
  237. }
  238. /** 时间线里此刻只有一条可反馈的回复:悬停轮尾露出操作栏后点赞(或取消),等按钮状态变化。 */
  239. async function clickOnlyFeedbackLike(expectPressed = true) {
  240. const selector = `[data-testid^="${TID_V4_FEEDBACK_LIKE}-"]`;
  241. await browser.waitUntil(async () => (await $$(selector).length) === 1, {
  242. timeout: 30000,
  243. timeoutMsg: "时间线里应恰好有一个点赞按钮",
  244. });
  245. const button = await $(selector);
  246. // 操作栏平时透明,悬停所在轮才显现;先滚到视口中间再悬停,避免点到输入框上。
  247. await browser.execute((element) => element.scrollIntoView({ block: "center" }), button);
  248. await button.moveTo();
  249. await button.waitForClickable({ timeout: 10000 });
  250. await button.click();
  251. await browser.waitUntil(
  252. async () => (await button.getAttribute("aria-pressed")) === String(expectPressed),
  253. { timeout: 10000, timeoutMsg: `点击后点赞按钮 aria-pressed 没有变成 ${String(expectPressed)}` },
  254. );
  255. }
  256. async function waitForFeedbackReports(capture: ConversationTelemetryCaptureHandle, count: number) {
  257. let all: ConversationTelemetryReport[] = [];
  258. const feedbacks = () => all.filter((r) => r.element_name === "assistant_message_feedback");
  259. await browser.waitUntil(
  260. async () => {
  261. all = await readAllEventReportRequests(capture);
  262. return feedbacks().length >= count;
  263. },
  264. { timeout: 30000, timeoutMsg: "assistant_message_feedback 没有上报" },
  265. );
  266. return { all, feedbacks: feedbacks() };
  267. }