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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import { clearAppData } from "#e2e/helpers/desktop-app";
  2. import {
  3. assertUpstreamRequestCapture,
  4. assertUpstreamThoughtLevelCapture,
  5. waitForUpstreamNetworkCapture,
  6. } from "#e2e/helpers/upstream-capture";
  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 "#e2e/helpers/upstream-provider";
  20. import {
  21. E2E_REPLY_TOKEN,
  22. clickV4Stop,
  23. getV4ConversationState,
  24. prepareV4ConversationE2E,
  25. sendV4Prompt,
  26. startNewV4Draft,
  27. waitForV4AssistantMessageContaining,
  28. waitForV4ConversationState,
  29. waitForV4ComposerText,
  30. waitForV4UserMessageContaining,
  31. } from "#e2e/helpers/v4-conversation";
  32. import { forkV4AssistantContaining as clickForkButtonForAssistantContaining } from "#e2e/helpers/v4-message-actions";
  33. import { editV4UserMessageContaining as editUserMessageContaining } from "#e2e/helpers/v4-message-actions";
  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 prepareV4ConversationE2E();
  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 sendV4Prompt(simpleReplyPrompt(editSourceMarker));
  57. await waitForV4ComposerText("", "model switch edit: source 发送后输入框没有清空");
  58. await waitForV4UserMessageContaining(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 waitForV4ComposerText("", "model switch edit: rerun 提交后输入框没有清空");
  64. await waitForV4UserMessageContaining(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 sendV4Prompt(simpleReplyPrompt(forkSourceMarker));
  71. await waitForV4ComposerText("", "model switch fork: source 发送后输入框没有清空");
  72. await waitForV4UserMessageContaining(forkSourceMarker);
  73. const sourceSnapshot = await waitForV4ConversationState(
  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 waitForV4ConversationState(
  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 waitForV4ConversationState(
  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 sendV4Prompt(simpleReplyPrompt(forkFollowupMarker));
  103. await waitForV4ComposerText("", "model switch fork: followup 发送后输入框没有清空");
  104. await waitForV4UserMessageContaining(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 startNewV4Draft();
  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 waitForV4ConversationState(
  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 = document.querySelector<HTMLElement>('[role="dialog"]') ?? document.body;
  148. const buttons = Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"));
  149. const confirmButton = buttons.find((button) => {
  150. const text = button.innerText.replace(/\s+/g, " ").trim();
  151. return (
  152. text === "压缩" ||
  153. text === "继续" ||
  154. text === "Compress" ||
  155. text === "Continue" ||
  156. text.includes("压缩")
  157. );
  158. });
  159. confirmButton?.click();
  160. return Boolean(confirmButton);
  161. });
  162. expect(clicked).toBe(true);
  163. }
  164. async function waitForModelSwitchCompressionDialog(timeout: number) {
  165. await browser.waitUntil(
  166. async () =>
  167. browser.execute(
  168. (titleZh, titleEn) => {
  169. const bodyText = document.body.innerText;
  170. return bodyText.includes(titleZh) || bodyText.includes(titleEn);
  171. },
  172. MODEL_SWITCH_GUARD_TITLE_ZH,
  173. MODEL_SWITCH_GUARD_TITLE_EN,
  174. ),
  175. {
  176. timeout,
  177. timeoutMsg: "没有出现模型切换前的上下文压缩确认弹窗",
  178. },
  179. );
  180. return true;
  181. }
  182. function simpleReplyPrompt(marker: string) {
  183. return `${marker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  184. }
  185. async function waitForCompletedAssistant(timeoutMsg: string) {
  186. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  187. await waitForV4ConversationState(
  188. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  189. timeoutMsg,
  190. 90000,
  191. );
  192. }
  193. async function expectToolbarConfig(model: string, thoughtLevel: string) {
  194. const modelLabel = await getSelectedUpstreamModelLabel();
  195. const acceptedModelValues = [`e2e-upstream/${model}`, `custom:e2e-upstream:${model}`, model];
  196. if (modelLabel.currentValue) {
  197. expect(acceptedModelValues).toContain(modelLabel.currentValue);
  198. } else {
  199. expect(Object.values(modelLabel).join("\n")).toContain(model);
  200. }
  201. if (!thoughtLevel) {
  202. return;
  203. }
  204. const thoughtLabel = await getSelectedUpstreamThoughtLevelLabel();
  205. const labelCandidates = Object.values(thoughtLabel)
  206. .map((value) => value.replace(/\s+/g, " ").trim().toLowerCase())
  207. .filter(Boolean);
  208. const expectedLabels = [thoughtLevel, ...getUpstreamThoughtLevelLabels(thoughtLevel)].map(
  209. (label) => label.replace(/\s+/g, " ").trim().toLowerCase(),
  210. );
  211. const matchedThoughtLevel = labelCandidates.some((label) =>
  212. expectedLabels.some(
  213. (expectedLabel) => label === expectedLabel || label.includes(expectedLabel),
  214. ),
  215. );
  216. if (!matchedThoughtLevel) {
  217. throw new Error(
  218. `思考深度未精确匹配 ${thoughtLevel}: ${JSON.stringify({
  219. expectedLabels,
  220. thoughtLabel,
  221. })}`,
  222. );
  223. }
  224. }
  225. function assertPrimaryConfig(
  226. record: Awaited<ReturnType<typeof waitForUpstreamNetworkCapture>>,
  227. expectedText: string,
  228. ) {
  229. assertUpstreamRequestCapture(record, {
  230. expectedText,
  231. model: UPSTREAM_MODEL,
  232. });
  233. if (UPSTREAM_THOUGHT_LEVEL) {
  234. assertUpstreamThoughtLevelCapture(record, UPSTREAM_THOUGHT_LEVEL);
  235. }
  236. }
  237. function assertSecondaryConfig(
  238. record: Awaited<ReturnType<typeof waitForUpstreamNetworkCapture>>,
  239. expectedText: string,
  240. ) {
  241. assertUpstreamRequestCapture(record, {
  242. expectedText,
  243. model: UPSTREAM_SECONDARY_MODEL,
  244. });
  245. assertUpstreamThoughtLevelCapture(record, UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  246. }
  247. async function stopIfBusy() {
  248. const snapshot = await getV4ConversationState().catch(() => null);
  249. if (snapshot?.state !== "streaming") {
  250. return;
  251. }
  252. await clickV4Stop().catch(() => undefined);
  253. await waitForV4ConversationState(
  254. (candidate) => candidate.state !== "streaming",
  255. "afterEach stop 后没有退出 streaming",
  256. 30000,
  257. ).catch(() => undefined);
  258. }