conversation-session-model-switch-edit-fork.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import { clearAppData } from "../../../helpers/desktop-app.js";
  2. import {
  3. assertUpstreamRequestCapture,
  4. assertUpstreamThoughtLevelCapture,
  5. waitForUpstreamNetworkCapture,
  6. } from "../../../helpers/upstream-capture.js";
  7. import {
  8. UPSTREAM_MODEL,
  9. UPSTREAM_SECONDARY_MODEL,
  10. UPSTREAM_SECONDARY_THOUGHT_LEVEL,
  11. UPSTREAM_THOUGHT_LEVEL,
  12. ensureUpstreamModelForE2E,
  13. getUpstreamThoughtLevelLabels,
  14. getSelectedUpstreamModelLabel,
  15. getSelectedUpstreamThoughtLevelLabel,
  16. selectUpstreamModelById,
  17. selectUpstreamThoughtLevelValue,
  18. waitForUpstreamModelSelected,
  19. } from "../../../helpers/upstream-provider.js";
  20. import {
  21. E2E_REPLY_TOKEN,
  22. clickChatStop,
  23. clickForkButtonForAssistantContaining,
  24. editUserMessageContaining,
  25. getChatRootSnapshot,
  26. prepareConversationE2E,
  27. sendPrompt,
  28. startNewTask,
  29. waitForAssistantMessageContaining,
  30. waitForChatState,
  31. waitForComposerText,
  32. waitForUserMessageContaining,
  33. } from "../../../helpers/conversation-session.js";
  34. const MODEL_SWITCH_EDIT_FORK_TIMEOUT_MS = 180000;
  35. const MODEL_SWITCH_GUARD_TITLE_ZH = "需要压缩上下文后再切换模型";
  36. const MODEL_SWITCH_GUARD_TITLE_EN = "Compress context before switching models";
  37. describe("会话区 completed 后模型切换 Edit/Fork E2E", () => {
  38. before(async function () {
  39. this.timeout(MODEL_SWITCH_EDIT_FORK_TIMEOUT_MS);
  40. await prepareConversationE2E();
  41. await ensureUpstreamModelForE2E(UPSTREAM_SECONDARY_MODEL);
  42. });
  43. afterEach(async () => {
  44. await stopIfBusy();
  45. });
  46. after(async () => {
  47. await browser.electron.restoreAllMocks();
  48. await clearAppData();
  49. });
  50. it("completed 后切 secondary 再 edit/fork,后续请求应使用 secondary 配置", async function () {
  51. this.timeout(MODEL_SWITCH_EDIT_FORK_TIMEOUT_MS);
  52. const runId = Date.now();
  53. await startNewTaskWithPrimaryConfig();
  54. const editSourceMarker = `E2E_MODEL_SWITCH_EDIT_SOURCE_${runId}`;
  55. const editRerunMarker = `E2E_MODEL_SWITCH_EDIT_RERUN_${runId}`;
  56. await sendPrompt(simpleReplyPrompt(editSourceMarker));
  57. await waitForComposerText("", "model switch edit: source 发送后输入框没有清空");
  58. await waitForUserMessageContaining(editSourceMarker);
  59. assertPrimaryConfig(await waitForUpstreamNetworkCapture(editSourceMarker), editSourceMarker);
  60. await waitForCompletedAssistant("model switch edit: source 没有完成");
  61. await switchToSecondaryConfig();
  62. await editUserMessageContaining(editSourceMarker, simpleReplyPrompt(editRerunMarker));
  63. await waitForComposerText("", "model switch edit: rerun 提交后输入框没有清空");
  64. await waitForUserMessageContaining(editRerunMarker);
  65. assertSecondaryConfig(await waitForUpstreamNetworkCapture(editRerunMarker), editRerunMarker);
  66. await waitForCompletedAssistant("model switch edit: rerun 没有完成");
  67. await startNewTaskWithPrimaryConfig();
  68. const forkSourceMarker = `E2E_MODEL_SWITCH_FORK_SOURCE_${runId}`;
  69. const forkFollowupMarker = `E2E_MODEL_SWITCH_FORK_FOLLOWUP_${runId}`;
  70. await sendPrompt(simpleReplyPrompt(forkSourceMarker));
  71. await waitForComposerText("", "model switch fork: source 发送后输入框没有清空");
  72. await waitForUserMessageContaining(forkSourceMarker);
  73. const sourceSnapshot = await waitForChatState(
  74. (snapshot) => Boolean(snapshot.sessionId || snapshot.taskId),
  75. "model switch fork: source 没有创建 session",
  76. 30000,
  77. );
  78. assertPrimaryConfig(await waitForUpstreamNetworkCapture(forkSourceMarker), forkSourceMarker);
  79. await waitForCompletedAssistant("model switch fork: source 没有完成");
  80. await switchToSecondaryConfig();
  81. await clickForkButtonForAssistantContaining(E2E_REPLY_TOKEN);
  82. const sourceSessionId = sourceSnapshot.sessionId || sourceSnapshot.taskId;
  83. const forkedSnapshot = await waitForChatState(
  84. (snapshot) =>
  85. Boolean(snapshot.sessionId || snapshot.taskId) &&
  86. (snapshot.sessionId || snapshot.taskId) !== sourceSessionId,
  87. "model switch fork: 点击 fork 后没有切换到派生 session",
  88. 30000,
  89. );
  90. expect(forkedSnapshot.queueCount).toBe(0);
  91. const forkedSessionId = forkedSnapshot.sessionId || forkedSnapshot.taskId;
  92. expect(forkedSessionId).toBeTruthy();
  93. await waitForChatState(
  94. (snapshot) =>
  95. (snapshot.sessionId || snapshot.taskId) === forkedSessionId &&
  96. snapshot.state === "idle" &&
  97. snapshot.runtimeStatus !== "restoring",
  98. "model switch fork: 派生 session 没有恢复完成",
  99. 60000,
  100. );
  101. await expectToolbarConfig(UPSTREAM_SECONDARY_MODEL, UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  102. await sendPrompt(simpleReplyPrompt(forkFollowupMarker));
  103. await waitForComposerText("", "model switch fork: followup 发送后输入框没有清空");
  104. await waitForUserMessageContaining(forkFollowupMarker);
  105. assertSecondaryConfig(
  106. await waitForUpstreamNetworkCapture(forkFollowupMarker),
  107. forkFollowupMarker,
  108. );
  109. await waitForCompletedAssistant("model switch fork: followup 没有完成");
  110. });
  111. });
  112. async function startNewTaskWithPrimaryConfig() {
  113. await startNewTask();
  114. await selectUpstreamModelById(UPSTREAM_MODEL);
  115. if (UPSTREAM_THOUGHT_LEVEL) {
  116. await selectUpstreamThoughtLevelValue(UPSTREAM_THOUGHT_LEVEL);
  117. }
  118. await expectToolbarConfig(UPSTREAM_MODEL, UPSTREAM_THOUGHT_LEVEL);
  119. }
  120. async function switchToSecondaryConfig() {
  121. await selectUpstreamModelById(UPSTREAM_SECONDARY_MODEL, {
  122. afterModelItemClick: () =>
  123. confirmModelSwitchCompressionDialogIfPresent(UPSTREAM_SECONDARY_MODEL),
  124. });
  125. await selectUpstreamThoughtLevelValue(UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  126. await expectToolbarConfig(UPSTREAM_SECONDARY_MODEL, UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  127. }
  128. async function confirmModelSwitchCompressionDialogIfPresent(modelId: string) {
  129. // Bugfix: completed 历史切到小上下文模型时 guard 会异步弹出;P0-10 不验证 guard 本身,
  130. // 但必须接管确认,否则 edit/fork 的“最新模型配置”断言会停在 pending 切换状态。
  131. const hasDialog = await waitForModelSwitchCompressionDialog(250).catch(() => false);
  132. if (!hasDialog) {
  133. return false;
  134. }
  135. await confirmModelSwitchCompressionDialog();
  136. await waitForChatState(
  137. (snapshot) => !snapshot.modelSwitchPending,
  138. `模型 ${modelId} guard 压缩后切换 pending 状态没有结束`,
  139. 120000,
  140. );
  141. await waitForUpstreamModelSelected(modelId);
  142. return true;
  143. }
  144. async function confirmModelSwitchCompressionDialog() {
  145. await waitForModelSwitchCompressionDialog(15000);
  146. const clicked = await browser.execute(() => {
  147. const dialog =
  148. document.querySelector<HTMLElement>('[role="dialog"]') ?? document.body;
  149. const buttons = Array.from(
  150. dialog.querySelectorAll<HTMLButtonElement>("button"),
  151. );
  152. const confirmButton = buttons.find((button) => {
  153. const text = button.innerText.replace(/\s+/g, " ").trim();
  154. return (
  155. text === "压缩" ||
  156. text === "继续" ||
  157. text === "Compress" ||
  158. text === "Continue" ||
  159. text.includes("压缩")
  160. );
  161. });
  162. confirmButton?.click();
  163. return Boolean(confirmButton);
  164. });
  165. expect(clicked).toBe(true);
  166. }
  167. async function waitForModelSwitchCompressionDialog(timeout: number) {
  168. await browser.waitUntil(
  169. async () =>
  170. browser.execute(
  171. (titleZh, titleEn) => {
  172. const bodyText = document.body.innerText;
  173. return bodyText.includes(titleZh) || bodyText.includes(titleEn);
  174. },
  175. MODEL_SWITCH_GUARD_TITLE_ZH,
  176. MODEL_SWITCH_GUARD_TITLE_EN,
  177. ),
  178. {
  179. timeout,
  180. timeoutMsg: "没有出现模型切换前的上下文压缩确认弹窗",
  181. },
  182. );
  183. return true;
  184. }
  185. function simpleReplyPrompt(marker: string) {
  186. return `${marker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  187. }
  188. async function waitForCompletedAssistant(timeoutMsg: string) {
  189. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  190. await waitForChatState(
  191. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  192. timeoutMsg,
  193. 90000,
  194. );
  195. }
  196. async function expectToolbarConfig(model: string, thoughtLevel: string) {
  197. const modelLabel = await getSelectedUpstreamModelLabel();
  198. const acceptedModelValues = [`e2e-upstream/${model}`, `custom:e2e-upstream:${model}`, model];
  199. if (modelLabel.currentValue) {
  200. expect(acceptedModelValues).toContain(modelLabel.currentValue);
  201. } else {
  202. expect(Object.values(modelLabel).join("\n")).toContain(model);
  203. }
  204. if (!thoughtLevel) {
  205. return;
  206. }
  207. const thoughtLabel = await getSelectedUpstreamThoughtLevelLabel();
  208. const labelCandidates = Object.values(thoughtLabel)
  209. .map((value) => value.replace(/\s+/g, " ").trim().toLowerCase())
  210. .filter(Boolean);
  211. const expectedLabels = [
  212. thoughtLevel,
  213. ...getUpstreamThoughtLevelLabels(thoughtLevel),
  214. ].map((label) => label.replace(/\s+/g, " ").trim().toLowerCase());
  215. const matchedThoughtLevel = labelCandidates.some((label) =>
  216. expectedLabels.some((expectedLabel) => label === expectedLabel || label.includes(expectedLabel)),
  217. );
  218. if (!matchedThoughtLevel) {
  219. throw new Error(
  220. `思考深度未精确匹配 ${thoughtLevel}: ${JSON.stringify({
  221. expectedLabels,
  222. thoughtLabel,
  223. })}`,
  224. );
  225. }
  226. }
  227. function assertPrimaryConfig(
  228. record: Awaited<ReturnType<typeof waitForUpstreamNetworkCapture>>,
  229. expectedText: string,
  230. ) {
  231. assertUpstreamRequestCapture(record, {
  232. expectedText,
  233. model: UPSTREAM_MODEL,
  234. });
  235. if (UPSTREAM_THOUGHT_LEVEL) {
  236. assertUpstreamThoughtLevelCapture(record, UPSTREAM_THOUGHT_LEVEL);
  237. }
  238. }
  239. function assertSecondaryConfig(
  240. record: Awaited<ReturnType<typeof waitForUpstreamNetworkCapture>>,
  241. expectedText: string,
  242. ) {
  243. assertUpstreamRequestCapture(record, {
  244. expectedText,
  245. model: UPSTREAM_SECONDARY_MODEL,
  246. });
  247. assertUpstreamThoughtLevelCapture(record, UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  248. }
  249. async function stopIfBusy() {
  250. const snapshot = await getChatRootSnapshot().catch(() => null);
  251. if (snapshot?.state !== "streaming") {
  252. return;
  253. }
  254. await clickChatStop().catch(() => undefined);
  255. await waitForChatState(
  256. (candidate) => candidate.state !== "streaming",
  257. "afterEach stop 后没有退出 streaming",
  258. 30000,
  259. ).catch(() => undefined);
  260. }