conversation-session-model-switch-auto-compact.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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. countUpstreamRequests,
  26. countUpstreamRequestsContainingAll,
  27. getUpstreamRequestRecordCount,
  28. waitForUpstreamRequestContaining,
  29. } from "../../../helpers/conversation-session-network.js";
  30. import {
  31. clickV4Stop,
  32. getV4CompactMarkers,
  33. getV4ConfigProjection,
  34. getV4PaneSnapshot,
  35. prepareV4ConversationE2E,
  36. sendV4Prompt,
  37. startNewV4Draft,
  38. waitForV4Pane,
  39. waitForV4QueueCount,
  40. waitForV4TimelineContaining,
  41. type V4CompactMarkerSnapshot,
  42. } from "../../../helpers/v4-conversation.js";
  43. const AUTO_ACTION_MARKER = "E2E_AUTO_ACTIONS";
  44. const COMPACT_REQUEST_SENTINEL = "CRITICAL: Respond with TEXT ONLY";
  45. const E2E_REPLY_TOKEN = "upstream-e2e-ok";
  46. const MODEL_SWITCH_GUARD_TITLE_ZH = "需要压缩上下文后再切换模型";
  47. const MODEL_SWITCH_GUARD_TITLE_EN = "Compress context before switching models";
  48. interface UpstreamCaptureQuery {
  49. afterIndex?: number;
  50. excludes?: readonly string[];
  51. includes: readonly string[];
  52. }
  53. describe("会话区模型切换与 Auto Compact 交集 E2E", () => {
  54. let runId = 0;
  55. before(async () => {
  56. await prepareV4ConversationE2E();
  57. await ensureUpstreamModelForE2E(UPSTREAM_SECONDARY_MODEL);
  58. runId = Date.now();
  59. });
  60. beforeEach(async () => {
  61. await startNewV4Draft();
  62. await selectUpstreamConfig(UPSTREAM_MODEL, UPSTREAM_THOUGHT_LEVEL);
  63. });
  64. afterEach(async () => {
  65. await stopIfBusy();
  66. });
  67. after(async () => {
  68. await browser.electron.restoreAllMocks();
  69. await clearAppData();
  70. });
  71. it("completed 后切到过小目标模型,应弹出压缩确认并执行 guard compact", async function () {
  72. this.timeout(220000);
  73. const seedMarker = `${AUTO_ACTION_MARKER}_MODEL_SWITCH_GUARD_CONTEXT_${runId}`;
  74. const seedPrompt = buildModelSwitchGuardSeedPrompt(seedMarker);
  75. await sendV4Prompt(seedPrompt);
  76. await waitForUpstreamRequestContaining(seedMarker);
  77. await waitForV4Idle("model switch guard compact seed 没有完成", 90000);
  78. await waitForActiveTaskContextUsedAbove(
  79. 0,
  80. "model switch guard compact seed 完成后没有正数 context usage",
  81. );
  82. const requestStartIndex = await getUpstreamRequestStartIndex();
  83. await selectUpstreamModelByIdWithGuardConfirm(UPSTREAM_SECONDARY_MODEL);
  84. const compactMarker = await waitForV4CompactMarkerMatch(
  85. ["running", "success"],
  86. "manual",
  87. undefined,
  88. 30000,
  89. );
  90. const compactRecord = await waitForUpstreamCaptureRecord(
  91. {
  92. afterIndex: requestStartIndex,
  93. includes: [COMPACT_REQUEST_SENTINEL, seedMarker],
  94. },
  95. "模型切换 guard 确认压缩后没有捕获到 compact 请求",
  96. 60000,
  97. );
  98. assertUpstreamConfig(compactRecord, COMPACT_REQUEST_SENTINEL, {
  99. model: UPSTREAM_MODEL,
  100. thoughtLevel: UPSTREAM_THOUGHT_LEVEL,
  101. });
  102. assertStreamingCompactRequest(compactRecord);
  103. assertCaptureIncludesText(compactRecord.requestJson, seedMarker);
  104. expect(
  105. await countUpstreamRequests(
  106. { includes: [COMPACT_REQUEST_SENTINEL, seedMarker] },
  107. { afterIndex: requestStartIndex },
  108. ),
  109. ).toBe(1);
  110. const completedMarker =
  111. compactMarker.status === "success"
  112. ? compactMarker
  113. : await waitForV4CompactMarkerMatch(
  114. ["success"],
  115. "manual",
  116. compactMarker.rowId,
  117. 90000,
  118. );
  119. expect(completedMarker.rowId).not.toBeNull();
  120. await waitForV4Idle("模型切换 guard compact 终态后会话没有回到 idle", 90000);
  121. await waitForModelSwitchIdle("模型切换 guard compact 完成后 pending 状态没有结束");
  122. await waitForModelSwitchCompressionDialogClosed();
  123. });
  124. it("completed 后切到过小目标模型并取消压缩,应保持原模型且不发 compact", async function () {
  125. this.timeout(120000);
  126. const seedMarker = `${AUTO_ACTION_MARKER}_MODEL_SWITCH_CANCEL_CONTEXT_${runId}`;
  127. const seedPrompt = buildModelSwitchGuardSeedPrompt(seedMarker);
  128. await sendV4Prompt(seedPrompt);
  129. await waitForUpstreamRequestContaining(seedMarker);
  130. await waitForV4Idle("model switch guard cancel seed 没有完成", 90000);
  131. await waitForActiveTaskContextUsedAbove(
  132. 0,
  133. "model switch guard cancel seed 完成后没有正数 context usage",
  134. );
  135. const compactRequestsBefore = await countUpstreamRequestsContainingAll([
  136. COMPACT_REQUEST_SENTINEL,
  137. seedMarker,
  138. ]);
  139. await selectUpstreamModelByIdWithGuardCancel(UPSTREAM_SECONDARY_MODEL);
  140. await expectToolbarConfig(UPSTREAM_MODEL, UPSTREAM_THOUGHT_LEVEL);
  141. await waitForModelSwitchCompressionDialogClosed();
  142. await browser.pause(800);
  143. expect(await countUpstreamRequestsContainingAll([COMPACT_REQUEST_SENTINEL, seedMarker])).toBe(
  144. compactRequestsBefore,
  145. );
  146. });
  147. it("auto compact started 后切 secondary,不中断 compact;若切换抢先完成则 pending prompt 使用 latest secondary", async function () {
  148. this.timeout(220000);
  149. const seedMarker = `${AUTO_ACTION_MARKER}_CONTEXT_SEED_${runId}`;
  150. const seedPrompt = `${seedMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  151. await sendV4Prompt(seedPrompt);
  152. await waitForUpstreamRequestContaining(seedMarker);
  153. await waitForV4Idle("model switch auto compact seed 没有完成", 90000);
  154. const requestStartIndex = await getUpstreamRequestStartIndex();
  155. const compactRequestsBefore = await countUpstreamRequestsContainingAll([
  156. COMPACT_REQUEST_SENTINEL,
  157. AUTO_ACTION_MARKER,
  158. ]);
  159. const pendingMarker = `${AUTO_ACTION_MARKER}_PENDING_TEXT_${runId}`;
  160. const pendingPrompt = `${pendingMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  161. await sendV4Prompt(pendingPrompt);
  162. await waitForV4TimelineContaining(pendingPrompt);
  163. const startedMarker = await waitForV4CompactMarkerMatch(
  164. ["running", "success", "noop"],
  165. "auto",
  166. undefined,
  167. 15000,
  168. ).catch(() => null);
  169. if (!startedMarker || startedMarker.status === "noop") {
  170. // 修复原因:manual-review live capture 使用真实线上模型时,短上下文不一定
  171. // 达到 needsCompact 阈值;该候选 case 不能把“没有触发 auto compact”误报成
  172. // 产品失败。这里记录 no-op 路径,仍证明 pending 请求没有被卡住或伪造 compact。
  173. await waitForUpstreamCaptureRecord(
  174. {
  175. afterIndex: requestStartIndex,
  176. excludes: [COMPACT_REQUEST_SENTINEL],
  177. includes: [pendingMarker],
  178. },
  179. "auto compact 未触发时没有继续 pending 主请求",
  180. 90000,
  181. );
  182. await waitForV4Idle("auto compact 未触发时 pending 文本没有回到 idle", 90000);
  183. expect(
  184. await countUpstreamRequestsContainingAll([COMPACT_REQUEST_SENTINEL, AUTO_ACTION_MARKER]),
  185. ).toBe(compactRequestsBefore);
  186. return;
  187. }
  188. expect(startedMarker.origin).toBe("auto");
  189. await browser.waitUntil(
  190. async () =>
  191. (await countUpstreamRequestsContainingAll([
  192. COMPACT_REQUEST_SENTINEL,
  193. AUTO_ACTION_MARKER,
  194. ])) ===
  195. compactRequestsBefore + 1,
  196. {
  197. timeout: 10000,
  198. timeoutMsg: "没有观察到 auto compact 请求发出",
  199. },
  200. );
  201. const switchResult = await trySelectUpstreamConfig(
  202. UPSTREAM_SECONDARY_MODEL,
  203. UPSTREAM_SECONDARY_THOUGHT_LEVEL,
  204. { closeOnFailure: false },
  205. );
  206. const compactCompletedBeforeSwitch = (await getV4CompactMarkers()).some((marker) =>
  207. matchesV4CompactMarker(marker, ["success"], "auto", startedMarker.rowId),
  208. );
  209. const autoCompactRecord = await waitForUpstreamCaptureRecord(
  210. {
  211. afterIndex: requestStartIndex,
  212. includes: [COMPACT_REQUEST_SENTINEL, AUTO_ACTION_MARKER],
  213. },
  214. "auto compact 完成后没有捕获到完整请求",
  215. 10000,
  216. );
  217. assertUpstreamConfig(autoCompactRecord, COMPACT_REQUEST_SENTINEL, {
  218. model: UPSTREAM_MODEL,
  219. thoughtLevel: UPSTREAM_THOUGHT_LEVEL,
  220. });
  221. assertStreamingCompactRequest(autoCompactRecord);
  222. expect(
  223. await countUpstreamRequestsContainingAll([COMPACT_REQUEST_SENTINEL, AUTO_ACTION_MARKER]),
  224. ).toBe(compactRequestsBefore + 1);
  225. await waitForV4Idle("auto compact 终态后会话没有回到 idle", 90000);
  226. const completedMarker = (await getV4CompactMarkers()).find((marker) =>
  227. matchesV4CompactMarker(marker, ["success"], "auto", startedMarker.rowId),
  228. );
  229. if (completedMarker) {
  230. expect(completedMarker.origin).toBe("auto");
  231. expect(completedMarker.rowId).not.toBeNull();
  232. }
  233. const pendingRecord = await findUpstreamCaptureRecord({
  234. afterIndex: requestStartIndex,
  235. excludes: [COMPACT_REQUEST_SENTINEL],
  236. includes: [pendingMarker],
  237. });
  238. const pendingModel = pendingRecord ? readCaptureModel(pendingRecord) : null;
  239. if (
  240. pendingRecord &&
  241. pendingModel === UPSTREAM_SECONDARY_MODEL &&
  242. switchResult.ok &&
  243. !compactCompletedBeforeSwitch
  244. ) {
  245. assertUpstreamConfig(pendingRecord, pendingMarker, {
  246. model: UPSTREAM_SECONDARY_MODEL,
  247. thoughtLevel: UPSTREAM_SECONDARY_THOUGHT_LEVEL,
  248. });
  249. }
  250. });
  251. });
  252. function buildModelSwitchGuardSeedPrompt(seedMarker: string) {
  253. return `${seedMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  254. }
  255. async function selectUpstreamConfig(model: string, thoughtLevel: string) {
  256. await selectUpstreamModelById(model);
  257. await selectUpstreamThoughtLevelValue(thoughtLevel);
  258. await expectToolbarConfig(model, thoughtLevel);
  259. }
  260. async function trySelectUpstreamConfig(
  261. model: string,
  262. thoughtLevel: string,
  263. options: { closeOnFailure?: boolean } = {},
  264. ) {
  265. try {
  266. await selectUpstreamConfig(model, thoughtLevel);
  267. return { ok: true };
  268. } catch (error) {
  269. if (options.closeOnFailure !== false) {
  270. await browser.keys("Escape").catch(() => undefined);
  271. }
  272. return {
  273. error: error instanceof Error ? error.message : String(error),
  274. ok: false,
  275. };
  276. }
  277. }
  278. async function selectUpstreamModelByIdWithGuardConfirm(modelId: string) {
  279. await selectUpstreamModelById(modelId, {
  280. afterModelItemClick: async () => {
  281. await confirmModelSwitchCompressionDialog();
  282. return true;
  283. },
  284. });
  285. }
  286. async function selectUpstreamModelByIdWithGuardCancel(modelId: string) {
  287. await selectUpstreamModelById(modelId, {
  288. afterModelItemClick: async () => {
  289. await cancelModelSwitchCompressionDialog();
  290. return true;
  291. },
  292. });
  293. await waitForModelSwitchIdle(`模型 ${modelId} guard 取消后 pending 状态没有结束`);
  294. }
  295. async function confirmModelSwitchCompressionDialog() {
  296. await browser.waitUntil(async () => hasModelSwitchCompressionDialog(), {
  297. timeout: 15000,
  298. timeoutMsg: "没有出现模型切换前的上下文压缩确认弹窗",
  299. });
  300. const result = await browser.execute(() => {
  301. const dialog =
  302. document.querySelector<HTMLElement>('[role="dialog"]') ?? document.body;
  303. const buttons = Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"));
  304. const readLabels = (button: HTMLButtonElement) =>
  305. [
  306. button.innerText,
  307. button.textContent,
  308. button.getAttribute("aria-label"),
  309. button.getAttribute("title"),
  310. ]
  311. .map((value) => (value ?? "").replace(/\s+/g, " ").trim())
  312. .filter(Boolean);
  313. const labels = buttons.map((button) => readLabels(button).join(" / "));
  314. const confirmButton = buttons.find((button) =>
  315. readLabels(button).some(
  316. (text) =>
  317. text === "压缩" ||
  318. text === "继续" ||
  319. text === "Compress" ||
  320. text === "Continue" ||
  321. text.includes("压缩") ||
  322. text.startsWith("Compress"),
  323. ),
  324. );
  325. confirmButton?.click();
  326. return { clicked: Boolean(confirmButton), labels };
  327. });
  328. if (!result.clicked) {
  329. throw new Error(`没有找到模型切换压缩弹窗确认按钮: ${result.labels.join(" | ")}`);
  330. }
  331. }
  332. async function cancelModelSwitchCompressionDialog() {
  333. await browser.waitUntil(async () => hasModelSwitchCompressionDialog(), {
  334. timeout: 15000,
  335. timeoutMsg: "没有出现模型切换前的上下文压缩确认弹窗",
  336. });
  337. const result = await browser.execute(() => {
  338. const dialog =
  339. document.querySelector<HTMLElement>('[role="dialog"]') ?? document.body;
  340. const buttons = Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"));
  341. const readLabels = (button: HTMLButtonElement) =>
  342. [
  343. button.innerText,
  344. button.textContent,
  345. button.getAttribute("aria-label"),
  346. button.getAttribute("title"),
  347. ]
  348. .map((value) => (value ?? "").replace(/\s+/g, " ").trim())
  349. .filter(Boolean);
  350. const labels = buttons.map((button) => readLabels(button).join(" / "));
  351. const cancelButton = buttons.find((button) =>
  352. readLabels(button).some(
  353. (text) =>
  354. text === "取消" ||
  355. text === "Cancel" ||
  356. text.startsWith("取消 ") ||
  357. text.startsWith("Cancel "),
  358. ),
  359. );
  360. cancelButton?.click();
  361. return { clicked: Boolean(cancelButton), labels };
  362. });
  363. if (!result.clicked) {
  364. throw new Error(`没有找到模型切换压缩弹窗取消按钮: ${result.labels.join(" | ")}`);
  365. }
  366. }
  367. async function hasModelSwitchCompressionDialog() {
  368. return browser.execute((titleZh, titleEn) => {
  369. const bodyText = document.body.innerText;
  370. return bodyText.includes(titleZh) || bodyText.includes(titleEn);
  371. }, MODEL_SWITCH_GUARD_TITLE_ZH, MODEL_SWITCH_GUARD_TITLE_EN);
  372. }
  373. async function waitForModelSwitchCompressionDialogClosed() {
  374. await browser.waitUntil(async () => !(await hasModelSwitchCompressionDialog()), {
  375. timeout: 5000,
  376. timeoutMsg: "模型切换压缩确认弹窗取消后没有关闭",
  377. });
  378. }
  379. async function expectToolbarConfig(model: string, thoughtLevel: string) {
  380. const modelLabel = await getSelectedUpstreamModelLabel();
  381. const acceptedModelValues = [`e2e-upstream/${model}`, `custom:e2e-upstream:${model}`, model];
  382. if (modelLabel.currentValue) {
  383. expect(acceptedModelValues).toContain(modelLabel.currentValue);
  384. } else {
  385. expect(Object.values(modelLabel).join("\n")).toContain(model);
  386. }
  387. if (!thoughtLevel) {
  388. return;
  389. }
  390. const thoughtLabel = await getSelectedUpstreamThoughtLevelLabel();
  391. const labelCandidates = Object.values(thoughtLabel)
  392. .map((value) => value.replace(/\s+/g, " ").trim().toLowerCase())
  393. .filter(Boolean);
  394. const expectedLabels = [
  395. thoughtLevel,
  396. ...getUpstreamThoughtLevelLabels(thoughtLevel),
  397. ].map((label) => label.replace(/\s+/g, " ").trim().toLowerCase());
  398. if (!labelCandidates.some((label) => expectedLabels.includes(label))) {
  399. throw new Error(
  400. `思考深度未精确匹配 ${thoughtLevel}: ${JSON.stringify({
  401. expectedLabels,
  402. thoughtLabel,
  403. })}`,
  404. );
  405. }
  406. }
  407. function assertUpstreamConfig(
  408. record: E2ENetworkCaptureRecord,
  409. expectedText: string,
  410. {
  411. model,
  412. thoughtLevel,
  413. }: {
  414. model: string;
  415. thoughtLevel: string;
  416. },
  417. ) {
  418. assertUpstreamRequestCapture(record, { expectedText, model });
  419. if (thoughtLevel) {
  420. assertUpstreamThoughtLevelCapture(record, thoughtLevel);
  421. }
  422. }
  423. function assertStreamingCompactRequest(record: E2ENetworkCaptureRecord) {
  424. const request = asRecord(record.requestJson);
  425. expect(request.stream).toBe(true);
  426. expect(record.statusCode).toBeGreaterThanOrEqual(200);
  427. expect(record.statusCode).toBeLessThan(300);
  428. expect(String(record.responseHeaders["content-type"] ?? "").toLowerCase()).toContain(
  429. "text/event-stream",
  430. );
  431. }
  432. function assertCaptureIncludesText(value: unknown, expected: string) {
  433. if (captureContainsText(value, expected)) {
  434. return;
  435. }
  436. throw new Error(`抓包请求没有包含预期文本: ${expected}`);
  437. }
  438. async function getUpstreamRequestStartIndex() {
  439. return (await getUpstreamRequestRecordCount()) - 1;
  440. }
  441. async function waitForUpstreamCaptureRecord(
  442. query: UpstreamCaptureQuery,
  443. timeoutMsg: string,
  444. timeout: number,
  445. ): Promise<E2ENetworkCaptureRecord> {
  446. let latestRecords: Array<{
  447. id: string;
  448. model: string | null;
  449. status: string;
  450. statusCode?: number;
  451. }> = [];
  452. let matchingRecord: E2ENetworkCaptureRecord | undefined;
  453. await browser.waitUntil(
  454. async () => {
  455. const records = await readUpstreamCaptureRecords();
  456. matchingRecord = findLastUpstreamCaptureRecord(records, query);
  457. latestRecords = records.slice(-8).map((record) => ({
  458. id: record.id,
  459. model: readCaptureModel(record),
  460. status: record.status,
  461. statusCode: record.statusCode,
  462. }));
  463. return Boolean(matchingRecord);
  464. },
  465. {
  466. timeout,
  467. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latestRecords)}`,
  468. },
  469. );
  470. if (!matchingRecord) {
  471. throw new Error(timeoutMsg);
  472. }
  473. return matchingRecord;
  474. }
  475. async function findUpstreamCaptureRecord(query: UpstreamCaptureQuery) {
  476. return findLastUpstreamCaptureRecord(await readUpstreamCaptureRecords(), query);
  477. }
  478. async function readUpstreamCaptureRecords(): Promise<E2ENetworkCaptureRecord[]> {
  479. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  480. if (!capturePath) {
  481. throw new Error("Upstream e2e capture path is not configured");
  482. }
  483. try {
  484. const artifact = JSON.parse(await readFile(capturePath, "utf-8")) as E2ENetworkCaptureArtifact;
  485. return artifact.records;
  486. } catch (error) {
  487. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  488. return [];
  489. }
  490. throw error;
  491. }
  492. }
  493. function findLastUpstreamCaptureRecord(
  494. records: readonly E2ENetworkCaptureRecord[],
  495. query: UpstreamCaptureQuery,
  496. ) {
  497. for (let index = records.length - 1; index >= 0; index -= 1) {
  498. const record = records[index];
  499. if (record && matchesUpstreamCaptureRecord(record, index, query)) {
  500. return record;
  501. }
  502. }
  503. return undefined;
  504. }
  505. function matchesUpstreamCaptureRecord(
  506. record: E2ENetworkCaptureRecord,
  507. index: number,
  508. query: UpstreamCaptureQuery,
  509. ) {
  510. return (
  511. (query.afterIndex === undefined || index > query.afterIndex) &&
  512. record.status === "complete" &&
  513. record.method === "POST" &&
  514. Boolean(record.statusCode && record.statusCode >= 200 && record.statusCode < 300) &&
  515. (record.path.includes("/messages") || record.path.includes("/chat/completions")) &&
  516. !captureContainsText(record.requestJson, "Generate a concise title") &&
  517. query.includes.every((text) => captureContainsText(record.requestJson, text)) &&
  518. !(query.excludes ?? []).some((text) => captureContainsText(record.requestJson, text))
  519. );
  520. }
  521. function readCaptureModel(record: E2ENetworkCaptureRecord) {
  522. const request = asRecord(record.requestJson);
  523. return typeof request.model === "string" ? request.model : null;
  524. }
  525. function matchesV4CompactMarker(
  526. marker: V4CompactMarkerSnapshot,
  527. statuses: readonly string[],
  528. origin: "manual" | "auto",
  529. rowId?: number | null,
  530. ) {
  531. return (
  532. statuses.includes(marker.status ?? "") &&
  533. marker.origin === origin &&
  534. (rowId == null || marker.rowId === rowId)
  535. );
  536. }
  537. async function waitForActiveTaskContextUsedAbove(threshold: number, timeoutMsg: string) {
  538. let latest: Awaited<ReturnType<typeof getV4ConfigProjection>> | null = null;
  539. try {
  540. await browser.waitUntil(
  541. async () => {
  542. latest = await getV4ConfigProjection();
  543. return latest.usageUsed > threshold;
  544. },
  545. {
  546. timeout: 15000,
  547. timeoutMsg,
  548. },
  549. );
  550. } catch {
  551. throw new Error(`${timeoutMsg}: latest=${JSON.stringify(latest)}`);
  552. }
  553. return latest;
  554. }
  555. async function waitForV4CompactMarkerMatch(
  556. statuses: readonly string[],
  557. origin: "manual" | "auto",
  558. rowId: number | null | undefined,
  559. timeout: number,
  560. ) {
  561. let latestMarkers: V4CompactMarkerSnapshot[] = [];
  562. await browser.waitUntil(
  563. async () => {
  564. latestMarkers = await getV4CompactMarkers();
  565. return latestMarkers.some((marker) =>
  566. matchesV4CompactMarker(marker, statuses, origin, rowId),
  567. );
  568. },
  569. {
  570. timeout,
  571. timeoutMsg: `没有等到 v4 compact marker statuses=${statuses.join(
  572. ",",
  573. )}, origin=${origin}, latest=${JSON.stringify(latestMarkers, null, 2)}`,
  574. },
  575. );
  576. const marker = latestMarkers.find((candidate) =>
  577. matchesV4CompactMarker(candidate, statuses, origin, rowId),
  578. );
  579. if (!marker) {
  580. throw new Error(`v4 compact marker statuses=${statuses.join(",")} 在等待完成后仍不存在`);
  581. }
  582. return marker;
  583. }
  584. async function waitForV4Idle(timeoutMsg: string, timeout: number) {
  585. await waitForV4Pane(
  586. (snapshot) =>
  587. !snapshot.canStop && snapshot.sessionId !== "draft" && snapshot.sessionId !== null,
  588. timeoutMsg,
  589. timeout,
  590. );
  591. await waitForV4QueueCount(0, timeout);
  592. }
  593. async function stopIfBusy() {
  594. await browser.keys("Escape").catch(() => undefined);
  595. const snapshot = await getV4PaneSnapshot();
  596. if (!snapshot.canStop) {
  597. return;
  598. }
  599. await clickV4Stop().catch(() => undefined);
  600. await waitForV4Pane(
  601. (candidate) => !candidate.canStop,
  602. "模型切换 auto compact case 停止后没有退出 streaming",
  603. 30000,
  604. ).catch(() => undefined);
  605. }
  606. function captureContainsText(value: unknown, expected: string): boolean {
  607. if (typeof value === "string") {
  608. return value.includes(expected);
  609. }
  610. if (Array.isArray(value)) {
  611. return value.some((item) => captureContainsText(item, expected));
  612. }
  613. if (!value || typeof value !== "object") {
  614. return false;
  615. }
  616. return Object.values(value).some((child) => captureContainsText(child, expected));
  617. }
  618. function asRecord(value: unknown): Record<string, unknown> {
  619. return value && typeof value === "object" && !Array.isArray(value)
  620. ? (value as Record<string, unknown>)
  621. : {};
  622. }