conversation-session-model-switch-tool-edit-fork.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import { readFile } from "node:fs/promises";
  2. import { clearAppData } from "../../../helpers/desktop-app.js";
  3. import {
  4. assertUpstreamRequestCapture,
  5. assertUpstreamThoughtLevelCapture,
  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. buildReadonlyToolPrompt,
  23. clickChatStop,
  24. clickForkButtonForAssistantContaining,
  25. editUserMessageContaining,
  26. getChatRootSnapshot,
  27. prepareConversationE2E,
  28. sendPrompt,
  29. startNewTask,
  30. waitForAssistantMessageContaining,
  31. waitForChatState,
  32. waitForComposerText,
  33. waitForUserMessageContaining,
  34. } from "../../../helpers/conversation-session.js";
  35. import type {
  36. E2ENetworkCaptureArtifact,
  37. E2ENetworkCaptureRecord,
  38. } from "../../../helpers/network-capture-proxy.js";
  39. const MODEL_SWITCH_GUARD_TITLE_ZH = "需要压缩上下文后再切换模型";
  40. const MODEL_SWITCH_GUARD_TITLE_EN = "Compress context before switching models";
  41. describe("会话区模型切换 Tool/Edit/Fork 交集 E2E", () => {
  42. before(async function () {
  43. this.timeout(120000);
  44. await prepareConversationE2E();
  45. await ensureUpstreamModelForE2E(UPSTREAM_SECONDARY_MODEL);
  46. });
  47. afterEach(async () => {
  48. await stopIfBusy();
  49. });
  50. after(async () => {
  51. await browser.electron.restoreAllMocks();
  52. await clearAppData();
  53. });
  54. it("tool prompt 窗口切模型先保持可执行探针", async function () {
  55. this.timeout(180000);
  56. await startCaseWithPrimaryModel();
  57. const marker = `E2E_FIRST_SEND_MSW_TOOL_${Date.now()}`;
  58. await sendPrompt(buildReadonlyToolPrompt(marker));
  59. await waitForComposerText("", "tool model switch: 首发后输入框没有清空");
  60. await waitForUserMessageContaining(marker);
  61. await trySwitchToSecondaryModelDuringToolProbe();
  62. const requestRecord = await waitForUpstreamRecordContaining(
  63. [marker],
  64. `tool model switch: 没有捕获到 ${marker} 的请求`,
  65. 90000,
  66. );
  67. expect(readCaptureModel(requestRecord)).toBeTruthy();
  68. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  69. await waitForChatState(
  70. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  71. "tool model switch: 探针请求没有完成",
  72. 90000,
  73. );
  74. });
  75. it("completed 后切到 secondary 再 edit 旧 user query,重跑请求应使用 secondary", async function () {
  76. this.timeout(180000);
  77. await startCaseWithPrimaryModel();
  78. const runId = Date.now();
  79. const sourceMarker = `E2E_MSW_EDIT_SOURCE_${runId}`;
  80. const rerunMarker = `E2E_MSW_EDIT_RERUN_${runId}`;
  81. await sendPrompt(simpleReplyPrompt(sourceMarker));
  82. await waitForComposerText("", "edit model switch: source 发送后输入框没有清空");
  83. await waitForUserMessageContaining(sourceMarker);
  84. expect(readCaptureModel(await waitForUpstreamRecordContaining([sourceMarker]))).toBeTruthy();
  85. await waitForCompletedAssistant("edit model switch: source 没有完成");
  86. await switchToSecondaryModel();
  87. await editUserMessageContaining(sourceMarker, simpleReplyPrompt(rerunMarker));
  88. await waitForComposerText("", "edit model switch: edit 提交后输入框没有清空");
  89. await waitForUserMessageContaining(rerunMarker);
  90. const rerunRecord = await waitForUpstreamRecordContaining([rerunMarker]);
  91. assertUpstreamConfig(rerunRecord, rerunMarker, {
  92. model: UPSTREAM_SECONDARY_MODEL,
  93. thoughtLevel: UPSTREAM_SECONDARY_THOUGHT_LEVEL,
  94. });
  95. await waitForCompletedAssistant("edit model switch: rerun 没有完成");
  96. });
  97. it("completed 后切到 secondary 再 fork assistant,派生 session 后续请求应继承 secondary", async function () {
  98. this.timeout(180000);
  99. await startCaseWithPrimaryModel();
  100. const runId = Date.now();
  101. const sourceMarker = `E2E_MSW_FORK_SOURCE_${runId}`;
  102. const followupMarker = `E2E_MSW_FORK_FOLLOWUP_${runId}`;
  103. await sendPrompt(simpleReplyPrompt(sourceMarker));
  104. await waitForComposerText("", "fork model switch: source 发送后输入框没有清空");
  105. await waitForUserMessageContaining(sourceMarker);
  106. const sourceSnapshot = await waitForChatState(
  107. (snapshot) => Boolean(snapshot.sessionId || snapshot.taskId),
  108. "fork model switch: source 没有创建 session",
  109. 30000,
  110. );
  111. expect(readCaptureModel(await waitForUpstreamRecordContaining([sourceMarker]))).toBeTruthy();
  112. await waitForCompletedAssistant("fork model switch: source 没有完成");
  113. await switchToSecondaryModel();
  114. await clickForkButtonForAssistantContaining(E2E_REPLY_TOKEN);
  115. const forkedSnapshot = await waitForChatState(
  116. (snapshot) =>
  117. Boolean(snapshot.sessionId || snapshot.taskId) &&
  118. (snapshot.sessionId || snapshot.taskId) !==
  119. (sourceSnapshot.sessionId || sourceSnapshot.taskId),
  120. "fork model switch: 点击 fork 后没有切换到派生 session",
  121. 30000,
  122. );
  123. expect(forkedSnapshot.queueCount).toBe(0);
  124. const forkedSessionId = forkedSnapshot.sessionId || forkedSnapshot.taskId;
  125. expect(forkedSessionId).toBeTruthy();
  126. await waitForChatState(
  127. (snapshot) =>
  128. (snapshot.sessionId || snapshot.taskId) === forkedSessionId &&
  129. snapshot.state === "idle" &&
  130. snapshot.runtimeStatus !== "restoring",
  131. "fork model switch: 派生 session 没有恢复完成",
  132. 60000,
  133. );
  134. await expectToolbarConfig(UPSTREAM_SECONDARY_MODEL, UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  135. await sendPrompt(simpleReplyPrompt(followupMarker));
  136. await waitForComposerText("", "fork model switch: followup 发送后输入框没有清空");
  137. await waitForUserMessageContaining(followupMarker);
  138. const followupRecord = await waitForUpstreamRecordContaining([followupMarker]);
  139. assertUpstreamConfig(followupRecord, followupMarker, {
  140. model: UPSTREAM_SECONDARY_MODEL,
  141. thoughtLevel: UPSTREAM_SECONDARY_THOUGHT_LEVEL,
  142. });
  143. await waitForCompletedAssistant("fork model switch: followup 没有完成");
  144. });
  145. });
  146. async function startCaseWithPrimaryModel() {
  147. await startNewTask();
  148. await selectUpstreamModelById(UPSTREAM_MODEL);
  149. if (UPSTREAM_THOUGHT_LEVEL) {
  150. await selectUpstreamThoughtLevelValue(UPSTREAM_THOUGHT_LEVEL);
  151. }
  152. await expectToolbarConfig(UPSTREAM_MODEL, UPSTREAM_THOUGHT_LEVEL);
  153. }
  154. async function switchToSecondaryModel() {
  155. await selectUpstreamModelById(UPSTREAM_SECONDARY_MODEL, {
  156. afterModelItemClick: () =>
  157. confirmModelSwitchCompressionDialogIfPresent(UPSTREAM_SECONDARY_MODEL),
  158. });
  159. await selectUpstreamThoughtLevelValue(UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  160. await expectToolbarConfig(UPSTREAM_SECONDARY_MODEL, UPSTREAM_SECONDARY_THOUGHT_LEVEL);
  161. }
  162. async function trySwitchToSecondaryModelDuringToolProbe() {
  163. try {
  164. await switchToSecondaryModel();
  165. } catch (error) {
  166. const message = error instanceof Error ? error.message : String(error);
  167. if (isExpectedToolProbeModelSwitchError(message)) {
  168. // Bugfix: tool prompt 用例是运行中窗口的可执行探针,active task 期间
  169. // configOptions 可能只暴露当前模型,或只更新 workspace 默认模型而不改当前运行 task。
  170. // 这里必须继续等首轮请求完成,否则未收尾的 task 会串扰后面的 edit/fork 主断言。
  171. return;
  172. }
  173. throw error;
  174. }
  175. }
  176. function isExpectedToolProbeModelSwitchError(message: string) {
  177. return (
  178. message.includes(UPSTREAM_SECONDARY_MODEL) &&
  179. (message.includes("聊天工具栏没有出现") ||
  180. message.includes("上游 模型没有切换到"))
  181. );
  182. }
  183. async function confirmModelSwitchCompressionDialogIfPresent(modelId: string) {
  184. // Bugfix: edit/fork 用例不验证压缩弹窗本身,但历史 task 切到较小目标模型时
  185. // 会被 context guard 暂停;E2E 必须确认压缩,否则后续模型继承断言不会进入真实路径。
  186. const hasDialog = await waitForModelSwitchCompressionDialog(250).catch(
  187. () => false,
  188. );
  189. if (!hasDialog) {
  190. return false;
  191. }
  192. await confirmModelSwitchCompressionDialog();
  193. await waitForChatState(
  194. (snapshot) => !snapshot.modelSwitchPending,
  195. `模型 ${modelId} guard 压缩后切换 pending 状态没有结束`,
  196. 120000,
  197. );
  198. await waitForUpstreamModelSelected(modelId);
  199. return true;
  200. }
  201. async function confirmModelSwitchCompressionDialog() {
  202. await waitForModelSwitchCompressionDialog(15000);
  203. const clicked = await browser.execute(() => {
  204. const dialog =
  205. document.querySelector<HTMLElement>('[role="dialog"]') ?? document.body;
  206. const buttons = Array.from(
  207. dialog.querySelectorAll<HTMLButtonElement>("button"),
  208. );
  209. const confirmButton = buttons.find((button) => {
  210. const text = button.innerText.replace(/\s+/g, " ").trim();
  211. return (
  212. text === "压缩" ||
  213. text === "继续" ||
  214. text === "Compress" ||
  215. text === "Continue" ||
  216. text.includes("压缩")
  217. );
  218. });
  219. confirmButton?.click();
  220. return Boolean(confirmButton);
  221. });
  222. expect(clicked).toBe(true);
  223. }
  224. async function waitForModelSwitchCompressionDialog(timeout: number) {
  225. await browser.waitUntil(
  226. async () =>
  227. browser.execute(
  228. (titleZh, titleEn) => {
  229. const bodyText = document.body.innerText;
  230. return bodyText.includes(titleZh) || bodyText.includes(titleEn);
  231. },
  232. MODEL_SWITCH_GUARD_TITLE_ZH,
  233. MODEL_SWITCH_GUARD_TITLE_EN,
  234. ),
  235. {
  236. timeout,
  237. timeoutMsg: "没有出现模型切换前的上下文压缩确认弹窗",
  238. },
  239. );
  240. return true;
  241. }
  242. function simpleReplyPrompt(marker: string) {
  243. return `${marker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  244. }
  245. async function waitForCompletedAssistant(timeoutMsg: string) {
  246. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  247. await waitForChatState(
  248. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  249. timeoutMsg,
  250. 90000,
  251. );
  252. }
  253. async function expectToolbarConfig(model: string, thoughtLevel: string) {
  254. const modelLabel = await getSelectedUpstreamModelLabel();
  255. const acceptedModelValues = [`e2e-upstream/${model}`, `custom:e2e-upstream:${model}`, model];
  256. if (modelLabel.currentValue) {
  257. expect(acceptedModelValues).toContain(modelLabel.currentValue);
  258. } else {
  259. expect(Object.values(modelLabel).join("\n")).toContain(model);
  260. }
  261. if (!thoughtLevel) {
  262. return;
  263. }
  264. const thoughtLabel = await getSelectedUpstreamThoughtLevelLabel();
  265. const labelCandidates = Object.values(thoughtLabel)
  266. .map((value) => value.replace(/\s+/g, " ").trim().toLowerCase())
  267. .filter(Boolean);
  268. const expectedLabels = [
  269. thoughtLevel,
  270. ...getUpstreamThoughtLevelLabels(thoughtLevel),
  271. ].map((label) => label.replace(/\s+/g, " ").trim().toLowerCase());
  272. const matchedThoughtLevel = labelCandidates.some((label) =>
  273. expectedLabels.some((expectedLabel) => label === expectedLabel || label.includes(expectedLabel)),
  274. );
  275. if (!matchedThoughtLevel) {
  276. throw new Error(
  277. `思考深度未精确匹配 ${thoughtLevel}: ${JSON.stringify({
  278. expectedLabels,
  279. thoughtLabel,
  280. })}`,
  281. );
  282. }
  283. }
  284. function assertUpstreamConfig(
  285. record: E2ENetworkCaptureRecord,
  286. expectedText: string,
  287. {
  288. model,
  289. thoughtLevel,
  290. }: {
  291. model: string;
  292. thoughtLevel: string;
  293. },
  294. ) {
  295. assertUpstreamRequestCapture(record, { expectedText, model });
  296. if (thoughtLevel) {
  297. assertUpstreamThoughtLevelCapture(record, thoughtLevel);
  298. }
  299. }
  300. async function waitForUpstreamRecordContaining(
  301. includes: string[],
  302. timeoutMsg = `没有捕获到 上游 请求: ${includes.join(", ")}`,
  303. timeout = 60000,
  304. ) {
  305. let latestSummary: unknown = null;
  306. await browser.waitUntil(
  307. async () => {
  308. const artifact = await readUpstreamCaptureArtifact();
  309. latestSummary = summarizeUpstreamCaptureArtifact(artifact);
  310. return Boolean(findLastUpstreamRecord(artifact, includes));
  311. },
  312. {
  313. timeout,
  314. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latestSummary)}`,
  315. },
  316. );
  317. const record = findLastUpstreamRecord(await readUpstreamCaptureArtifact(), includes);
  318. if (!record) {
  319. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latestSummary)}`);
  320. }
  321. return record;
  322. }
  323. async function readUpstreamCaptureArtifact(): Promise<E2ENetworkCaptureArtifact | null> {
  324. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  325. if (!capturePath) {
  326. return null;
  327. }
  328. try {
  329. return JSON.parse(await readFile(capturePath, "utf-8")) as E2ENetworkCaptureArtifact;
  330. } catch (error) {
  331. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  332. return null;
  333. }
  334. throw error;
  335. }
  336. }
  337. function findLastUpstreamRecord(
  338. artifact: E2ENetworkCaptureArtifact | null,
  339. includes: string[],
  340. ) {
  341. const records = artifact?.records ?? [];
  342. for (let index = records.length - 1; index >= 0; index -= 1) {
  343. const record = records[index]!;
  344. if (matchesUpstreamRecord(record, includes)) {
  345. return record;
  346. }
  347. }
  348. return null;
  349. }
  350. function matchesUpstreamRecord(
  351. record: E2ENetworkCaptureRecord,
  352. includes: string[],
  353. ) {
  354. return (
  355. record.status === "complete" &&
  356. record.statusCode !== undefined &&
  357. record.method === "POST" &&
  358. (record.path.includes("/messages") || record.path.includes("/chat/completions")) &&
  359. !captureContainsText(record.requestJson, "Generate a concise title") &&
  360. includes.every((text) => captureContainsText(record.requestJson, text))
  361. );
  362. }
  363. function summarizeUpstreamCaptureArtifact(
  364. artifact: E2ENetworkCaptureArtifact | null,
  365. ) {
  366. return {
  367. configured: Boolean(process.env.E2E_PROVIDER_CAPTURE_PATH),
  368. recordCount: artifact?.records.length ?? 0,
  369. records: artifact?.records.slice(-8).map((record) => ({
  370. model: readCaptureModel(record),
  371. path: record.path,
  372. requestBodyBytes: record.requestBodyBytes,
  373. status: record.status,
  374. statusCode: record.statusCode,
  375. })),
  376. };
  377. }
  378. function readCaptureModel(record: E2ENetworkCaptureRecord) {
  379. const requestJson = record.requestJson;
  380. if (
  381. requestJson &&
  382. typeof requestJson === "object" &&
  383. "model" in requestJson &&
  384. typeof requestJson.model === "string"
  385. ) {
  386. return requestJson.model;
  387. }
  388. return null;
  389. }
  390. function captureContainsText(value: unknown, expected: string): boolean {
  391. if (typeof value === "string") {
  392. return value.includes(expected);
  393. }
  394. if (Array.isArray(value)) {
  395. return value.some((item) => captureContainsText(item, expected));
  396. }
  397. if (!value || typeof value !== "object") {
  398. return false;
  399. }
  400. return Object.values(value).some((child) => captureContainsText(child, expected));
  401. }
  402. async function stopIfBusy() {
  403. const snapshot = await getChatRootSnapshot().catch(() => null);
  404. if (snapshot?.state !== "streaming") {
  405. return;
  406. }
  407. await clickChatStop().catch(() => undefined);
  408. await waitForChatState(
  409. (candidate) => candidate.state !== "streaming",
  410. "afterEach stop 后没有退出 streaming",
  411. 30000,
  412. ).catch(() => undefined);
  413. }