conversation-session-model-switch-compact.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. waitForModelSwitchIdle,
  19. } from "../../../helpers/upstream-provider.js";
  20. import type {
  21. E2ENetworkCaptureArtifact,
  22. E2ENetworkCaptureRecord,
  23. } from "../../../helpers/network-capture-proxy.js";
  24. import {
  25. E2E_REPLY_TOKEN,
  26. clickChatStop,
  27. getCompactMarkers,
  28. getChatRootSnapshot,
  29. getUpstreamRequestRecordCount,
  30. prepareConversationE2E,
  31. sendPrompt,
  32. startNewTask,
  33. waitForChatState,
  34. waitForComposerText,
  35. waitForUpstreamRequestContaining,
  36. } from "../../../helpers/conversation-session.js";
  37. const COMPACT_REQUEST_SENTINEL = "CRITICAL: Respond with TEXT ONLY";
  38. const MODEL_SWITCH_GUARD_TITLE_ZH = "需要压缩上下文后再切换模型";
  39. const MODEL_SWITCH_GUARD_TITLE_EN = "Compress context before switching models";
  40. const SECONDARY_COMPACT_MODEL = withOneMillionContextSuffix(UPSTREAM_SECONDARY_MODEL);
  41. const SECONDARY_COMPACT_REQUEST_MODEL = stripLocalModelSuffix(SECONDARY_COMPACT_MODEL);
  42. type CompactMarker = Awaited<ReturnType<typeof getCompactMarkers>>[number];
  43. interface UpstreamCaptureQuery {
  44. afterIndex?: number;
  45. excludes?: readonly string[];
  46. includes: readonly string[];
  47. }
  48. describe("会话区模型切换与 Compact 交集 E2E", () => {
  49. let runId = 0;
  50. before(async () => {
  51. await prepareConversationE2E();
  52. await ensureUpstreamModelForE2E(SECONDARY_COMPACT_MODEL);
  53. runId = Date.now();
  54. });
  55. beforeEach(async () => {
  56. await startNewTask();
  57. await selectUpstreamConfig(UPSTREAM_MODEL, UPSTREAM_THOUGHT_LEVEL);
  58. });
  59. afterEach(async () => {
  60. await stopIfBusy();
  61. });
  62. after(async () => {
  63. await browser.electron.restoreAllMocks();
  64. await clearAppData();
  65. });
  66. it("completed 后切 secondary 再 /compact,summary 请求使用 secondary model 和 compact summary 思考档", async function () {
  67. this.timeout(180000);
  68. const seedMarker = `E2E_STOP_HELD_QUEUE_FIRST_MODEL_SWITCH_MANUAL_${runId}`;
  69. const seedPrompt = `${seedMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  70. await sendPrompt(seedPrompt);
  71. await waitForComposerText("", "model switch manual compact seed 发送后输入框没有清空");
  72. await waitForUpstreamRequestContaining(seedMarker);
  73. await waitForChatState(
  74. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  75. "model switch manual compact seed 没有完成",
  76. 90000,
  77. );
  78. await selectUpstreamConfig(
  79. SECONDARY_COMPACT_MODEL,
  80. UPSTREAM_SECONDARY_THOUGHT_LEVEL,
  81. { proveModelWithCapture: true },
  82. );
  83. const manualCompactInputIdsBefore = await getManualCompactInputIds();
  84. const requestStartIndex = await getUpstreamRequestStartIndex();
  85. await sendPrompt("/compact");
  86. await waitForComposerText("", "model switch manual /compact 发送后输入框没有清空");
  87. const startedMarker = await waitForNewManualCompactMarker(
  88. ["started", "completed"],
  89. manualCompactInputIdsBefore,
  90. );
  91. expect(startedMarker.trigger).toBe("manual");
  92. expect(startedMarker.inputId).toBeTruthy();
  93. const compactRecord = await waitForUpstreamCaptureRecord(
  94. {
  95. afterIndex: requestStartIndex,
  96. includes: [COMPACT_REQUEST_SENTINEL],
  97. },
  98. "没有捕获到 secondary manual compact 请求",
  99. 60000,
  100. );
  101. assertUpstreamConfig(compactRecord, COMPACT_REQUEST_SENTINEL, {
  102. model: SECONDARY_COMPACT_REQUEST_MODEL,
  103. // 修复原因:该 case 的用户动作会把 toolbar 切到 secondary/max,
  104. // 但 compact summary 请求由压缩摘要链路发起,线上请求保持默认 high;
  105. // 这里锁定真正的产品合同:summary 使用 secondary 模型,thought 不误判成模型切换失败。
  106. thoughtLevel: UPSTREAM_THOUGHT_LEVEL,
  107. });
  108. assertNonStreamingCompactRequest(compactRecord);
  109. assertCaptureIncludesText(compactRecord.requestJson, seedMarker);
  110. const completedMarker =
  111. startedMarker.status === "completed"
  112. ? startedMarker
  113. : await waitForNewManualCompactMarker(
  114. ["completed"],
  115. manualCompactInputIdsBefore,
  116. startedMarker.inputId,
  117. );
  118. expect(completedMarker.trigger).toBe("manual");
  119. expect(completedMarker.operationId).toBeTruthy();
  120. });
  121. });
  122. interface SelectUpstreamConfigOptions {
  123. proveModelWithCapture?: boolean;
  124. }
  125. async function selectUpstreamConfig(
  126. model: string,
  127. thoughtLevel: string,
  128. { proveModelWithCapture = false }: SelectUpstreamConfigOptions = {},
  129. ) {
  130. await selectUpstreamModelById(
  131. model,
  132. proveModelWithCapture
  133. ? {
  134. afterModelItemClick: async () => {
  135. // 修复原因:该 manual-review case 的核心合同是后续 /compact
  136. // 请求使用 secondary 配置。模型 Select 关闭动画或上下文 guard 弹窗期间,
  137. // toolbar 的 data-model-current-value 可能短暂落后于用户可见 UI;这里
  138. // 只收敛真实阻塞状态,最终仍由线上请求抓包严格证明模型。
  139. // 当前 case 不测“小窗口模型切换 guard”,因此 secondary 选用 [1m]
  140. // 本地能力后缀;agent 发送 provider 请求前会剥掉后缀,抓包仍断言原始模型。
  141. await settleModelSwitchAfterModelItemClick(model);
  142. return true;
  143. },
  144. }
  145. : {},
  146. );
  147. await waitForNoBlockingDialog(`上游 模型 ${model} 切换后`);
  148. await selectUpstreamThoughtLevelValue(thoughtLevel);
  149. await expectToolbarConfig(model, thoughtLevel, {
  150. checkModel: !proveModelWithCapture,
  151. });
  152. }
  153. async function expectToolbarConfig(
  154. model: string,
  155. thoughtLevel: string,
  156. { checkModel = true }: { checkModel?: boolean } = {},
  157. ) {
  158. if (checkModel) {
  159. const modelLabel = await getSelectedUpstreamModelLabel();
  160. const acceptedModelValues = [`e2e-upstream/${model}`, `custom:e2e-upstream:${model}`, model];
  161. if (modelLabel.currentValue) {
  162. expect(acceptedModelValues).toContain(modelLabel.currentValue);
  163. } else {
  164. expect(Object.values(modelLabel).join("\n")).toContain(model);
  165. }
  166. }
  167. if (!thoughtLevel) {
  168. return;
  169. }
  170. const thoughtLabel = await getSelectedUpstreamThoughtLevelLabel();
  171. const labelCandidates = Object.values(thoughtLabel)
  172. .map((value) => value.replace(/\s+/g, " ").trim().toLowerCase())
  173. .filter(Boolean);
  174. const expectedLabels = [
  175. thoughtLevel,
  176. ...getUpstreamThoughtLevelLabels(thoughtLevel),
  177. ].map((label) => label.replace(/\s+/g, " ").trim().toLowerCase());
  178. if (!labelCandidates.some((label) => expectedLabels.includes(label))) {
  179. throw new Error(
  180. `思考深度未精确匹配 ${thoughtLevel}: ${JSON.stringify({
  181. expectedLabels,
  182. thoughtLabel,
  183. })}`,
  184. );
  185. }
  186. }
  187. async function settleModelSwitchAfterModelItemClick(model: string) {
  188. await browser.pause(500);
  189. if (await confirmModelSwitchCompressionDialogIfPresent()) {
  190. await waitForModelSwitchCompressionDialogClosed("模型切换压缩确认弹窗确认后没有关闭");
  191. await waitForChatState(
  192. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  193. "模型切换 guard compact 终态后会话没有回到 idle",
  194. 90000,
  195. );
  196. await waitForModelSwitchIdle("模型切换 guard compact 完成后 pending 状态没有结束");
  197. await waitForNoBlockingDialog("模型切换 guard compact 完成后");
  198. return;
  199. }
  200. await waitForModelSwitchIdle(`上游 模型 ${model} 切换动画没有结束`).catch(() => undefined);
  201. }
  202. async function confirmModelSwitchCompressionDialogIfPresent() {
  203. const snapshot = await readOpenDialogSnapshot();
  204. if (!snapshot.hasOverlay && snapshot.dialogs.length === 0) {
  205. return false;
  206. }
  207. if (!snapshot.hasModelSwitchCompressionDialog) {
  208. throw new Error(`模型切换后出现了非预期弹窗: ${JSON.stringify(snapshot)}`);
  209. }
  210. const result = await browser.execute(() => {
  211. const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>("button"));
  212. const labels = buttons.map((button) => button.innerText.replace(/\s+/g, " ").trim());
  213. const confirmButton = buttons.find((button) => {
  214. const text = button.innerText.replace(/\s+/g, " ").trim();
  215. return (
  216. text === "压缩" ||
  217. text === "继续" ||
  218. text.startsWith("Compress") ||
  219. text.startsWith("Continue") ||
  220. text.includes("压缩")
  221. );
  222. });
  223. confirmButton?.click();
  224. return { clicked: Boolean(confirmButton), labels };
  225. });
  226. if (!result.clicked) {
  227. throw new Error(`没有找到模型切换压缩弹窗确认按钮: ${result.labels.join(" | ")}`);
  228. }
  229. return true;
  230. }
  231. async function waitForModelSwitchCompressionDialogClosed(timeoutMsg: string) {
  232. await browser.waitUntil(
  233. async () => !(await readOpenDialogSnapshot()).hasModelSwitchCompressionDialog,
  234. {
  235. timeout: 10000,
  236. timeoutMsg,
  237. },
  238. );
  239. }
  240. async function waitForNoBlockingDialog(context: string) {
  241. let latest: OpenDialogSnapshot | null = null;
  242. try {
  243. await browser.waitUntil(
  244. async () => {
  245. latest = await readOpenDialogSnapshot();
  246. return !latest.hasOverlay && latest.dialogs.length === 0;
  247. },
  248. {
  249. timeout: 10000,
  250. timeoutMsg: `${context} 仍有弹窗遮挡`,
  251. },
  252. );
  253. } catch (error) {
  254. latest = await readOpenDialogSnapshot();
  255. throw new Error(`${context} 仍有弹窗遮挡: ${JSON.stringify(latest)}`, {
  256. cause: error,
  257. });
  258. }
  259. }
  260. interface OpenDialogSnapshot {
  261. bodyText: string;
  262. buttonLabels: string[];
  263. dialogs: Array<{
  264. ariaLabel: string;
  265. text: string;
  266. }>;
  267. hasModelSwitchCompressionDialog: boolean;
  268. hasOverlay: boolean;
  269. }
  270. function readOpenDialogSnapshot(): Promise<OpenDialogSnapshot> {
  271. return browser.execute((titleZh, titleEn) => {
  272. const normalizeText = (value: string) => value.replace(/\s+/g, " ").trim();
  273. const bodyText = normalizeText(document.body.innerText).slice(0, 2000);
  274. const dialogs = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"]')).map(
  275. (dialog) => ({
  276. ariaLabel: dialog.getAttribute("aria-label") ?? "",
  277. text: normalizeText(dialog.innerText).slice(0, 1000),
  278. }),
  279. );
  280. return {
  281. bodyText,
  282. buttonLabels: Array.from(document.querySelectorAll<HTMLButtonElement>("button")).map(
  283. (button) => normalizeText(button.innerText),
  284. ),
  285. dialogs,
  286. hasModelSwitchCompressionDialog: bodyText.includes(titleZh) || bodyText.includes(titleEn),
  287. hasOverlay: Boolean(document.querySelector('[data-slot="dialog-overlay"][data-state="open"]')),
  288. };
  289. }, MODEL_SWITCH_GUARD_TITLE_ZH, MODEL_SWITCH_GUARD_TITLE_EN);
  290. }
  291. async function getManualCompactInputIds() {
  292. return new Set(
  293. (await getCompactMarkers())
  294. .filter((marker) => marker.trigger === "manual" && marker.inputId)
  295. .map((marker) => marker.inputId),
  296. );
  297. }
  298. async function waitForNewManualCompactMarker(
  299. statuses: readonly string[],
  300. existingInputIds: ReadonlySet<string | null>,
  301. inputId?: string | null,
  302. ): Promise<CompactMarker> {
  303. const statusSet = new Set(statuses);
  304. let latestMarkers: CompactMarker[] = [];
  305. await browser.waitUntil(
  306. async () => {
  307. latestMarkers = await getCompactMarkers();
  308. return latestMarkers.some((marker) =>
  309. isExpectedManualCompactMarker(marker, statusSet, existingInputIds, inputId),
  310. );
  311. },
  312. {
  313. timeout: statusSet.has("started") ? 20000 : 90000,
  314. timeoutMsg: `没有等到新的 manual compact marker statuses=${statuses.join(
  315. ",",
  316. )}, latest=${JSON.stringify(latestMarkers, null, 2)}`,
  317. },
  318. );
  319. const marker = latestMarkers.find((candidate) =>
  320. isExpectedManualCompactMarker(candidate, statusSet, existingInputIds, inputId),
  321. );
  322. if (!marker) {
  323. throw new Error(`新的 manual compact marker statuses=${statuses.join(",")} 在等待完成后仍不存在`);
  324. }
  325. return marker;
  326. }
  327. function isExpectedManualCompactMarker(
  328. marker: CompactMarker,
  329. statusSet: ReadonlySet<string>,
  330. existingInputIds: ReadonlySet<string | null>,
  331. inputId?: string | null,
  332. ) {
  333. return (
  334. statusSet.has(marker.status ?? "") &&
  335. marker.trigger === "manual" &&
  336. Boolean(marker.inputId) &&
  337. (inputId ? marker.inputId === inputId : !existingInputIds.has(marker.inputId))
  338. );
  339. }
  340. function withOneMillionContextSuffix(model: string) {
  341. const trimmed = model.trim();
  342. return /\[1m\]$/iu.test(trimmed) ? trimmed : `${trimmed}[1m]`;
  343. }
  344. function stripLocalModelSuffix(model: string) {
  345. return model.trim().replace(/-?\[[^\]]*\]$/u, "");
  346. }
  347. function assertUpstreamConfig(
  348. record: E2ENetworkCaptureRecord,
  349. expectedText: string,
  350. {
  351. model,
  352. thoughtLevel,
  353. }: {
  354. model: string;
  355. thoughtLevel: string;
  356. },
  357. ) {
  358. assertUpstreamRequestCapture(record, { expectedText, model });
  359. if (thoughtLevel) {
  360. assertUpstreamThoughtLevelCapture(record, thoughtLevel);
  361. }
  362. }
  363. function assertNonStreamingCompactRequest(record: E2ENetworkCaptureRecord) {
  364. const request = asRecord(record.requestJson);
  365. expect(request.stream).not.toBe(true);
  366. expect(record.responseHeaders["content-type"]).not.toContain("text/event-stream");
  367. }
  368. function assertCaptureIncludesText(value: unknown, expected: string) {
  369. if (captureContainsText(value, expected)) {
  370. return;
  371. }
  372. throw new Error(`抓包请求没有包含预期文本: ${expected}`);
  373. }
  374. async function getUpstreamRequestStartIndex() {
  375. return (await getUpstreamRequestRecordCount()) - 1;
  376. }
  377. async function waitForUpstreamCaptureRecord(
  378. query: UpstreamCaptureQuery,
  379. timeoutMsg: string,
  380. timeout: number,
  381. ): Promise<E2ENetworkCaptureRecord> {
  382. let latestRecords: Array<{
  383. id: string;
  384. model: string | null;
  385. status: string;
  386. statusCode?: number;
  387. }> = [];
  388. let matchingRecord: E2ENetworkCaptureRecord | undefined;
  389. await browser.waitUntil(
  390. async () => {
  391. const records = await readUpstreamCaptureRecords();
  392. matchingRecord = findLastUpstreamCaptureRecord(records, query);
  393. latestRecords = records.slice(-8).map((record) => ({
  394. id: record.id,
  395. model: readCaptureModel(record),
  396. status: record.status,
  397. statusCode: record.statusCode,
  398. }));
  399. return Boolean(matchingRecord);
  400. },
  401. {
  402. timeout,
  403. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latestRecords)}`,
  404. },
  405. );
  406. if (!matchingRecord) {
  407. throw new Error(timeoutMsg);
  408. }
  409. return matchingRecord;
  410. }
  411. async function readUpstreamCaptureRecords(): Promise<E2ENetworkCaptureRecord[]> {
  412. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  413. if (!capturePath) {
  414. throw new Error("Upstream e2e capture path is not configured");
  415. }
  416. try {
  417. const artifact = JSON.parse(await readFile(capturePath, "utf-8")) as E2ENetworkCaptureArtifact;
  418. return artifact.records;
  419. } catch (error) {
  420. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  421. return [];
  422. }
  423. throw error;
  424. }
  425. }
  426. function findLastUpstreamCaptureRecord(
  427. records: readonly E2ENetworkCaptureRecord[],
  428. query: UpstreamCaptureQuery,
  429. ) {
  430. for (let index = records.length - 1; index >= 0; index -= 1) {
  431. const record = records[index];
  432. if (record && matchesUpstreamCaptureRecord(record, index, query)) {
  433. return record;
  434. }
  435. }
  436. return undefined;
  437. }
  438. function matchesUpstreamCaptureRecord(
  439. record: E2ENetworkCaptureRecord,
  440. index: number,
  441. query: UpstreamCaptureQuery,
  442. ) {
  443. return (
  444. (query.afterIndex === undefined || index > query.afterIndex) &&
  445. record.status === "complete" &&
  446. record.method === "POST" &&
  447. Boolean(record.statusCode && record.statusCode >= 200 && record.statusCode < 300) &&
  448. (record.path.includes("/messages") || record.path.includes("/chat/completions")) &&
  449. !captureContainsText(record.requestJson, "Generate a concise title") &&
  450. query.includes.every((text) => captureContainsText(record.requestJson, text)) &&
  451. !(query.excludes ?? []).some((text) => captureContainsText(record.requestJson, text))
  452. );
  453. }
  454. function readCaptureModel(record: E2ENetworkCaptureRecord) {
  455. const request = asRecord(record.requestJson);
  456. return typeof request.model === "string" ? request.model : null;
  457. }
  458. async function stopIfBusy() {
  459. await browser.keys("Escape").catch(() => undefined);
  460. const snapshot = await getChatRootSnapshot();
  461. if (snapshot.state !== "streaming") {
  462. return;
  463. }
  464. await clickChatStop().catch(() => undefined);
  465. await waitForChatState(
  466. (candidate) => candidate.state !== "streaming",
  467. "模型切换 compact case 停止后没有退出 streaming",
  468. 30000,
  469. ).catch(() => undefined);
  470. }
  471. function captureContainsText(value: unknown, expected: string): boolean {
  472. if (typeof value === "string") {
  473. return value.includes(expected);
  474. }
  475. if (Array.isArray(value)) {
  476. return value.some((item) => captureContainsText(item, expected));
  477. }
  478. if (!value || typeof value !== "object") {
  479. return false;
  480. }
  481. return Object.values(value).some((child) => captureContainsText(child, expected));
  482. }
  483. function asRecord(value: unknown): Record<string, unknown> {
  484. return value && typeof value === "object" && !Array.isArray(value)
  485. ? (value as Record<string, unknown>)
  486. : {};
  487. }