conversation-session-goal-timeline.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import { TID_V4_SESSION_PANE, testId } from "@zcode/shared/test-ids";
  2. import { clearAppData } from "#e2e/helpers/desktop-app";
  3. import {
  4. clickV4Stop,
  5. prepareV4ConversationE2E,
  6. getV4ConversationState,
  7. sendV4Prompt,
  8. waitForV4AssistantMessageContaining,
  9. waitForV4ConversationState,
  10. waitForV4ComposerText,
  11. waitForV4UserMessageContaining,
  12. } from "#e2e/helpers/v4-conversation";
  13. import {
  14. countUpstreamRequests,
  15. getUpstreamRequestEvidence,
  16. waitForUpstreamRequest,
  17. } from "#e2e/helpers/conversation-session-network";
  18. const GOAL_MARKER_PREFIX = "E2E_GOAL_TIMELINE_REPRO";
  19. const GOAL_A_MARKER = `${GOAL_MARKER_PREFIX}_A`;
  20. const GOAL_B_MARKER = `${GOAL_MARKER_PREFIX}_B`;
  21. const FIRST_REPLY = "人类灭绝后,机器哭了。";
  22. const FINAL_REPLY = "人类灭绝之后,机器哭了。";
  23. const SECOND_TARGET_REPLY = "这需要长篇连载,无法一次交付十万字。";
  24. const SECOND_TARGET_CONTINUATION = "E2E_GOAL_TIMELINE_REPRO_B_CONTINUING";
  25. interface GoalTimelineExpectation {
  26. label: string;
  27. texts: readonly string[];
  28. }
  29. const FIRST_TARGET_TIMELINE_STEPS = [
  30. {
  31. label: "iteration-1-incomplete",
  32. texts: ["第 1 次迭代 · 目标未完成,任务继续", "Iteration 1 · Goal incomplete, continuing"],
  33. },
  34. {
  35. label: "iteration-2-complete",
  36. texts: ["第 2 次迭代 · 目标已完成,任务结束", "Iteration 2 · Goal complete, ending task"],
  37. },
  38. ] as const satisfies readonly GoalTimelineExpectation[];
  39. const NEW_TARGET_TIMELINE_STEP = {
  40. label: "new-target-iteration-1",
  41. texts: [
  42. "第 1 次迭代 · 目标校验中",
  43. "Iteration 1 · Verifying goal",
  44. "第 1 次迭代 · 目标未完成,任务继续",
  45. "Iteration 1 · Goal incomplete, continuing",
  46. ],
  47. } as const satisfies GoalTimelineExpectation;
  48. const EXPECTED_TIMELINE_STEPS = [
  49. ...FIRST_TARGET_TIMELINE_STEPS,
  50. {
  51. ...NEW_TARGET_TIMELINE_STEP,
  52. },
  53. ] as const satisfies readonly GoalTimelineExpectation[];
  54. interface ConversationEntrySnapshot {
  55. id: string | null;
  56. kind: "assistant" | "goalTimeline" | "user";
  57. text: string;
  58. title: string | null;
  59. }
  60. describe("会话区 Goal Timeline E2E", () => {
  61. after(async () => {
  62. await browser.electron.restoreAllMocks();
  63. await clearAppData();
  64. });
  65. it("同 target 自动续跑与新 target 的 verifier timeline 不应串成同一轮序列", async function () {
  66. this.timeout(180000);
  67. await prepareV4ConversationE2E();
  68. const objective = `${GOAL_A_MARKER}: 写一篇恰好 10 个汉字的科幻小说。不要调用工具。`;
  69. await sendV4Prompt(`/goal ${objective}`);
  70. await waitForV4ComposerText("", "goal timeline: /goal 发送后输入框没有清空");
  71. await waitForV4UserMessageContaining(objective);
  72. await waitForUpstreamRequest(
  73. {
  74. excludes: [FINAL_REPLY],
  75. includes: [GOAL_A_MARKER, "Verify whether the active session goal"],
  76. },
  77. "goal timeline: 没有捕获到第 1 次 verifier 请求",
  78. 90000,
  79. );
  80. await waitForV4AssistantMessageContaining(FIRST_REPLY);
  81. await waitForUpstreamRequest(
  82. {
  83. includes: [GOAL_A_MARKER, FINAL_REPLY, "Verify whether the active session goal"],
  84. },
  85. "goal timeline: 没有捕获到第 2 次 verifier 请求",
  86. 120000,
  87. );
  88. await waitForV4AssistantMessageContaining(FINAL_REPLY);
  89. await waitForV4ConversationState(
  90. (snapshot) =>
  91. snapshot.state !== "streaming" &&
  92. snapshot.queueCount === 0 &&
  93. snapshot.targetObjective?.includes(GOAL_A_MARKER) === true &&
  94. // 当前 V4 投影以 verified 表示 verifier 已确认完成,旧 complete 属于 legacy meta。
  95. snapshot.targetStatus === "verified",
  96. "goal timeline: 第一个目标最终没有回到完成态",
  97. 120000,
  98. );
  99. // 修复原因:targetStatus 已完成可能早于 synthetic timeline divider 完成渲染;
  100. // 先等第一个 target 的两条 divider 落 DOM,再切新 target,避免测试制造排序 race。
  101. await waitForGoalTimelineTexts(FIRST_TARGET_TIMELINE_STEPS);
  102. const secondTargetObjective = `${GOAL_B_MARKER}: 写一篇 10w 字科幻小说。不要调用工具。`;
  103. await sendV4Prompt(`/goal ${secondTargetObjective}`);
  104. await waitForV4ComposerText("", "goal timeline: 第二个 /goal 发送后输入框没有清空");
  105. await waitForV4UserMessageContaining(secondTargetObjective);
  106. await waitForV4AssistantMessageContaining(SECOND_TARGET_REPLY);
  107. await waitForUpstreamRequest(
  108. {
  109. includes: [GOAL_B_MARKER, SECOND_TARGET_REPLY, "Verify whether the active session goal"],
  110. },
  111. "goal timeline: 没有捕获到新 target 的第 3 次 verifier 请求",
  112. 120000,
  113. );
  114. // 新目标未完成会合法续跑;旧夹具缺这一轮,500 也能通过时间线断言。
  115. // 等受控流正文实际到达,再核对 timeline 并 stop,避免错误请求冒充正常续跑。
  116. await waitForV4AssistantMessageContaining(SECOND_TARGET_CONTINUATION);
  117. const continuationRequests = await getUpstreamRequestEvidence({
  118. lastUserMessageIncludes: [GOAL_B_MARKER, "Reason: 没有交付 10w 字小说。"],
  119. excludes: ["Verify whether the active session goal", "Generate a concise title"],
  120. });
  121. expect(continuationRequests).toHaveLength(1);
  122. expect(continuationRequests[0]?.fixtureId).toBe(
  123. "upstream-goal-timeline-new-target-continuation",
  124. );
  125. const entries = await waitForGoalTimelineTexts(EXPECTED_TIMELINE_STEPS);
  126. await stopIfStreaming();
  127. // 第四轮正文保持打开,stop 前不会完成,也不会产生额外 verifier。
  128. expect(
  129. await countUpstreamRequests({
  130. includes: [GOAL_MARKER_PREFIX, "Verify whether the active session goal"],
  131. }),
  132. ).toBe(3);
  133. const timelineTexts = entries
  134. .filter((entry) => entry.kind === "goalTimeline")
  135. .map((entry) => normalizeEntryText(entry.text));
  136. expect(resolveGoalTimelineSteps(timelineTexts, EXPECTED_TIMELINE_STEPS)).toEqual(
  137. EXPECTED_TIMELINE_STEPS.map((step) => step.label),
  138. );
  139. const firstAssistantIndex = findEntryIndex(entries, "assistant", FIRST_REPLY);
  140. const firstTimelineIndex = findEntryIndex(entries, "goalTimeline", EXPECTED_TIMELINE_STEPS[0]);
  141. const finalTimelineIndex = findEntryIndex(entries, "goalTimeline", EXPECTED_TIMELINE_STEPS[1]);
  142. const secondTargetUserIndex = findEntryIndex(entries, "user", secondTargetObjective);
  143. const secondTargetTimelineIndex = findEntryIndexFrom(
  144. entries,
  145. "goalTimeline",
  146. NEW_TARGET_TIMELINE_STEP,
  147. finalTimelineIndex + 1,
  148. );
  149. const orderSnapshot = {
  150. entries,
  151. firstAssistantIndex,
  152. firstTimelineIndex,
  153. finalTimelineIndex,
  154. secondTargetUserIndex,
  155. secondTargetTimelineIndex,
  156. };
  157. if (
  158. firstAssistantIndex < 0 ||
  159. firstTimelineIndex < 0 ||
  160. finalTimelineIndex < 0 ||
  161. secondTargetUserIndex < 0 ||
  162. secondTargetTimelineIndex < 0
  163. ) {
  164. throw new Error(
  165. `goal timeline: 缺少预期消息或 timeline: ${JSON.stringify(orderSnapshot, null, 2)}`,
  166. );
  167. }
  168. expect(firstAssistantIndex).toBeLessThan(firstTimelineIndex);
  169. expect(firstTimelineIndex).toBeLessThan(finalTimelineIndex);
  170. // Bugfix: first target complete 后 synthetic divider 可能晚于第二个 /goal user
  171. // 进入 DOM;本 case 只要求同 target 内部顺序正确,且新 target timeline 不串到旧 target 前。
  172. expect(secondTargetUserIndex).toBeLessThan(secondTargetTimelineIndex);
  173. expect(finalTimelineIndex).toBeLessThan(secondTargetTimelineIndex);
  174. });
  175. });
  176. async function stopIfStreaming() {
  177. const snapshot = await getV4ConversationState();
  178. if (snapshot.state !== "streaming" && snapshot.runtimeStatus !== "streaming") {
  179. return;
  180. }
  181. // 续跑响应由 fixture 保持打开;真实点击 stop 取消该流,完成测试收尾。
  182. await clickV4Stop();
  183. await waitForV4ConversationState(
  184. (latest) => latest.state !== "streaming" && latest.runtimeStatus !== "streaming",
  185. "goal timeline: 收尾 stop 后没有退出 streaming",
  186. 30000,
  187. );
  188. }
  189. async function waitForGoalTimelineTexts(expectedSteps: readonly GoalTimelineExpectation[]) {
  190. let entries: ConversationEntrySnapshot[] = [];
  191. let timelineTexts: string[] = [];
  192. let timelineSteps: Array<string | null> = [];
  193. await browser.waitUntil(
  194. async () => {
  195. entries = await getConversationEntrySnapshot();
  196. timelineTexts = entries
  197. .filter((entry) => entry.kind === "goalTimeline")
  198. .map((entry) => normalizeEntryText(entry.text));
  199. timelineSteps = resolveGoalTimelineSteps(timelineTexts, expectedSteps);
  200. // 修复原因:CI 和本地可能使用不同 locale,timeline 文案会在中英文间切换。
  201. // 这里锁定 verifier 轮次/完成语义,而不是固定某一种语言的展示文案。
  202. return expectedSteps.every((step, index) => timelineSteps[index] === step.label);
  203. },
  204. {
  205. timeout: 30000,
  206. timeoutMsg: `goal timeline: 没有看到完成后的目标校验序列, expected=${JSON.stringify(
  207. expectedSteps.map((step) => step.label),
  208. )}, actual=${JSON.stringify(timelineSteps)}, texts=${JSON.stringify(
  209. timelineTexts,
  210. )}, entries=${JSON.stringify(entries)}`,
  211. },
  212. );
  213. return entries;
  214. }
  215. function getConversationEntrySnapshot(): Promise<ConversationEntrySnapshot[]> {
  216. return browser.execute(
  217. (paneId) => {
  218. // V4 的消息和目标校验都是 canonical row;旧 chat-messages / synthetic message DOM 已退场。
  219. const root = document.querySelector(`[data-testid="${paneId}"]`);
  220. const entries: ConversationEntrySnapshot[] = [];
  221. for (const element of root?.querySelectorAll<HTMLElement>("[data-row-id]") ?? []) {
  222. const kind = element.classList.contains("group/user-row")
  223. ? "user"
  224. : element.classList.contains("group/assistant-row")
  225. ? "assistant"
  226. : element.dataset.markerType === "goalVerify"
  227. ? "goalTimeline"
  228. : null;
  229. if (!kind) continue;
  230. const text = (element.innerText || element.textContent || "")
  231. .replace(/\u00a0/g, " ")
  232. .trim();
  233. if (!text) continue;
  234. entries.push({
  235. id: element.dataset.rowId ?? null,
  236. kind,
  237. text,
  238. title: element.getAttribute("title"),
  239. });
  240. }
  241. return entries;
  242. },
  243. testId(TID_V4_SESSION_PANE, "workspace-main"),
  244. );
  245. }
  246. function normalizeEntryText(text: string) {
  247. return text.replace(/\s+/g, " ").trim();
  248. }
  249. function normalizeGoalTimelineText(text: string) {
  250. const normalized = normalizeEntryText(text);
  251. const match = EXPECTED_TIMELINE_STEPS.find((step) => matchesGoalTimelineText(normalized, step));
  252. return match?.label ?? null;
  253. }
  254. function resolveGoalTimelineSteps(
  255. timelineTexts: readonly string[],
  256. expectedSteps: readonly GoalTimelineExpectation[],
  257. ) {
  258. return expectedSteps.map((step, index) =>
  259. matchesGoalTimelineText(timelineTexts[index] ?? "", step)
  260. ? step.label
  261. : normalizeGoalTimelineText(timelineTexts[index] ?? ""),
  262. );
  263. }
  264. function matchesGoalTimelineText(text: string, expected: GoalTimelineExpectation) {
  265. const normalized = normalizeEntryText(text);
  266. return expected.texts.includes(normalized);
  267. }
  268. function findEntryIndex(
  269. entries: readonly ConversationEntrySnapshot[],
  270. kind: ConversationEntrySnapshot["kind"],
  271. text: string | GoalTimelineExpectation,
  272. ) {
  273. return findEntryIndexFrom(entries, kind, text, 0);
  274. }
  275. function findEntryIndexFrom(
  276. entries: readonly ConversationEntrySnapshot[],
  277. kind: ConversationEntrySnapshot["kind"],
  278. text: string | GoalTimelineExpectation,
  279. fromIndex: number,
  280. ) {
  281. return entries.findIndex(
  282. (entry, index) => index >= fromIndex && entry.kind === kind && entryMatchesText(entry, text),
  283. );
  284. }
  285. function entryMatchesText(
  286. entry: ConversationEntrySnapshot,
  287. text: string | GoalTimelineExpectation,
  288. ) {
  289. if (typeof text === "string") {
  290. return entry.text.includes(text);
  291. }
  292. return matchesGoalTimelineText(entry.text, text);
  293. }