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

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