conversation-session-highspeed-card.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import { MobileRpcFrameGate } from "#e2e/helpers/mobile-rpc-frame-gate";
  2. import { DatabaseSync } from "node:sqlite";
  3. import { dirname, join } from "node:path";
  4. import { readFile, writeFile } from "node:fs/promises";
  5. import { chromium } from "playwright-core";
  6. import { e2eMobileBrowserLaunchOptions } from "#e2e/helpers/e2e-mobile-browser-executable";
  7. import {
  8. getE2EAppDataPaths,
  9. setCurrentElectronRendererContentSize,
  10. } from "#e2e/helpers/desktop-app";
  11. import { getV4ModelConfig } from "#e2e/helpers/v4-conversation";
  12. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  13. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  14. import { assertUpstreamThoughtLevelCapture } from "#e2e/helpers/upstream-capture";
  15. import type {
  16. E2ENetworkCaptureArtifact,
  17. E2ENetworkCaptureRecord,
  18. } from "#e2e/helpers/network-capture-proxy";
  19. import { clearAppData } from "#e2e/helpers/desktop-app";
  20. import {
  21. prepareHighspeedDrawWorkspace,
  22. startHighspeedEntranceProbe,
  23. takeHighspeedEntranceProbe,
  24. waitForHighspeedComposer,
  25. waitForHighspeedComposerCleared,
  26. waitForHighspeedStatusTag,
  27. } from "#e2e/helpers/highspeed-card";
  28. import {
  29. getV4PaneSnapshot,
  30. selectV4TaskById,
  31. sendV4Prompt,
  32. startNewV4Draft,
  33. waitForV4Pane,
  34. waitForV4TimelineContaining,
  35. } from "#e2e/helpers/v4-conversation";
  36. // Host Mock 场景:hit-fast(按 spec 文件注入,见 helpers/highspeed-mock-env.ts)。
  37. const HIT_REPLY_TOKEN = "hs-card-hit-done";
  38. async function expectThought(sessionId: string, thought: string) {
  39. // Node SQLite 只有同步只读入口;只读取目标会话的一行配置。
  40. const db = new DatabaseSync(join(getE2EAppDataPaths().storageRoot, "cli", "db", "db.sqlite"), {
  41. readOnly: true,
  42. });
  43. try {
  44. await browser.waitUntil(
  45. () => {
  46. const row = db
  47. .prepare(
  48. "SELECT data FROM session_entry WHERE session_id=? AND type='runtime/model_selection' ORDER BY id DESC LIMIT 1",
  49. )
  50. .get(sessionId) as { data: string } | undefined;
  51. return Boolean(
  52. row && JSON.parse(row.data).modelSelection?.options?.reasoningLevel === thought,
  53. );
  54. },
  55. { timeout: 10000, timeoutMsg: `Highspeed 调档未写入 Session: ${thought}` },
  56. );
  57. } finally {
  58. db.close();
  59. }
  60. }
  61. describe("Highspeed card E2E", () => {
  62. after(async () => {
  63. await browser.electron.restoreAllMocks();
  64. await clearAppData();
  65. });
  66. it("HS-E2E-01/07: 抽卡恢复不重播,锁定模型仍可调档并等待 ACK", async function () {
  67. // 修复原因:Windows 上冷启动、Team 菜单就绪循环、抽卡、双宽度调档与手机配对串行执行,
  68. // 实测在调档阶段(尚未失败)即触达 180s 上限;放宽总时长,不改变任何断言。
  69. this.timeout(420000);
  70. await prepareHighspeedDrawWorkspace();
  71. // 发送前开始记录:draw 命中必须真的挂载扩散 Canvas,作为切回不重播断言的正向对照。
  72. await startHighspeedEntranceProbe();
  73. // Bug 根因:旧 prompt 内含回复标记,而 timelineText 包含用户消息,发送瞬间就会误判完成。
  74. // 回复标记只由数据面 fixture 返回(按 E2E_HIGHSPEED_CARD_HIT 命中)。
  75. await sendV4Prompt("E2E_HIGHSPEED_CARD_HIT: reply with the fixed hit token.");
  76. await waitForHighspeedComposer("抽卡命中后输入框没有进入 Highspeed 状态");
  77. await waitForV4TimelineContaining(HIT_REPLY_TOKEN);
  78. await waitForV4Pane(
  79. (snapshot) => !snapshot.canStop && snapshot.timelineText.includes(HIT_REPLY_TOKEN),
  80. "Highspeed mock turn 完成后 pane 仍处于运行态",
  81. 90000,
  82. );
  83. await waitForHighspeedStatusTag("完成态消息没有展示 Highspeed 标识");
  84. // draw 命中按 activation 入场播放扩散;入场方式跨 draft→session 保持,不被恢复链路改写。
  85. // 不断言 phase:窗口后台化时 rAF 可能节流,扩散收尾时机不属于本 case 的契约。
  86. const drawEntrance = await takeHighspeedEntranceProbe();
  87. expect(drawEntrance.entrance).toBe("activation");
  88. expect(drawEntrance.diffusionMounted).toBe(true);
  89. // 切到新草稿再切回:恢复入场从 stable 挂载,模型标识立即呈现,不重播扩散(spec §9.2)。
  90. const { sessionId } = await getV4PaneSnapshot();
  91. if (!sessionId || sessionId === "draft") {
  92. throw new Error("Highspeed 首轮完成后 pane 没有绑定 session");
  93. }
  94. await startNewV4Draft();
  95. await waitForHighspeedComposerCleared("新建草稿后输入框仍处于 Highspeed 状态");
  96. await startHighspeedEntranceProbe();
  97. await selectV4TaskById(sessionId);
  98. await waitForHighspeedComposer("切回 Task 后输入框没有恢复 Highspeed 状态");
  99. const restoreEntrance = await takeHighspeedEntranceProbe();
  100. expect(restoreEntrance).toEqual({
  101. diffusionMounted: false,
  102. entrance: "restore",
  103. modelIndicatorVisible: true,
  104. phase: "stable",
  105. });
  106. const endpoint = process.env.ZCODE_WEB_REMOTE_CONTROL_URL;
  107. if (!endpoint) throw new Error("HS-E2E-07 缺少手机 fixture");
  108. const pairingUrl = await obtainUnreadPairingUrl(new URL(endpoint).origin);
  109. // Highspeed 只锁模型身份。通过真实 RPC 门禁验证独立档位控件,不能注入草稿假装成功。
  110. const before = await getV4ModelConfig();
  111. await browser.execute(() => {
  112. const original = MessagePort.prototype.postMessage;
  113. const held: Array<() => void> = [];
  114. const probe = {
  115. count: 0,
  116. holding: true,
  117. release() {
  118. this.holding = false;
  119. held.splice(0).forEach((send) => send());
  120. },
  121. restore() {
  122. MessagePort.prototype.postMessage = original;
  123. this.release();
  124. },
  125. };
  126. (window as Window & { __hsConfigProbe?: typeof probe }).__hsConfigProbe = probe;
  127. MessagePort.prototype.postMessage = function (
  128. ...args: [unknown, (Transferable[] | StructuredSerializeOptions)?]
  129. ) {
  130. const data = args[0];
  131. const bytes =
  132. data instanceof ArrayBuffer
  133. ? new Uint8Array(data)
  134. : ArrayBuffer.isView(data)
  135. ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
  136. : null;
  137. const wire = bytes ? new TextDecoder().decode(bytes) : "";
  138. if (
  139. wire.includes("sendConversationCommandV4") &&
  140. wire.includes('"type":"switchModelConfig"')
  141. ) {
  142. probe.count++;
  143. if (probe.holding) {
  144. held.push(() => Reflect.apply(original, this, args));
  145. return;
  146. }
  147. }
  148. Reflect.apply(original, this, args);
  149. };
  150. });
  151. try {
  152. for (const width of [1280, 430]) {
  153. await browser.electron.execute((electron) => {
  154. const window = electron.BrowserWindow.getAllWindows().find((item) => item.isVisible());
  155. // 隔离 E2E 解除原生最小宽度,确保真正覆盖窄视口。
  156. window?.setMinimumSize(0, 0);
  157. });
  158. // 根因:Windows 分数缩放下外框 1280px 可对应内容区 1279px;按内容区与缩放校验视口。
  159. await setCurrentElectronRendererContentSize(width, 900);
  160. const trigger = $('[data-testid="chat-thought-level-select-trigger"]');
  161. await trigger.waitForClickable();
  162. await trigger.click();
  163. await $('[data-testid="chat-thought-level-select-item-max"]').click();
  164. if (width === 1280) {
  165. await browser.waitUntil(
  166. () =>
  167. browser.execute(
  168. () =>
  169. (window as Window & { __hsConfigProbe?: { count: number } }).__hsConfigProbe!
  170. .count === 1,
  171. ),
  172. { timeout: 10000, timeoutMsg: "Highspeed 调档未发出配置命令" },
  173. );
  174. expect(await trigger.isEnabled()).toBe(false);
  175. expect(await trigger.getAttribute("aria-expanded")).not.toBe("true");
  176. await browser.keys(["Control", "t"]);
  177. expect(
  178. await browser.execute(
  179. () =>
  180. (window as Window & { __hsConfigProbe?: { count: number } }).__hsConfigProbe!.count,
  181. ),
  182. ).toBe(1);
  183. await browser.execute(() =>
  184. (
  185. window as Window & { __hsConfigProbe?: { release(): void } }
  186. ).__hsConfigProbe!.release(),
  187. );
  188. }
  189. await expectThought(sessionId, "max");
  190. await trigger.waitForClickable();
  191. await browser.keys(["Control", "t"]);
  192. await expectThought(sessionId, "low");
  193. const current = await getV4ModelConfig();
  194. expect(current.provider).toBe(before.provider);
  195. expect(current.model).toBe(before.model);
  196. expect(await $('[data-highspeed-model-indicator="true"]').isExisting()).toBe(true);
  197. expect(await $('[data-testid="chat-model-select-trigger"]').isExisting()).toBe(false);
  198. }
  199. } finally {
  200. await browser.execute(() =>
  201. (window as Window & { __hsConfigProbe?: { restore(): void } }).__hsConfigProbe?.restore(),
  202. );
  203. await browser.electron.execute((electron) => {
  204. electron.BrowserWindow.getAllWindows()
  205. .find((window) => window.isVisible())
  206. ?.setSize(1280, 900);
  207. });
  208. }
  209. const chrome = await chromium.launch({
  210. ...e2eMobileBrowserLaunchOptions(),
  211. headless: true,
  212. });
  213. const gates = new Set<MobileRpcFrameGate>();
  214. const outboundMessages = new Set<string>();
  215. const heldCount = () => [...gates].reduce((count, gate) => count + gate.heldCount, 0);
  216. let holding = false;
  217. let configs = 0;
  218. const release = () => {
  219. holding = false;
  220. gates.forEach((gate) => gate.release());
  221. };
  222. try {
  223. const context = await chrome.newContext({
  224. viewport: { width: 390, height: 844 },
  225. isMobile: true,
  226. hasTouch: true,
  227. });
  228. await seedMobileFixtureLogin(context);
  229. const page = await context.newPage();
  230. page.setDefaultTimeout(15000);
  231. await page.routeWebSocket(/\/api\/v1\/remote\/ws2(?:\?|$)/u, (route) => {
  232. const server = route.connectToServer();
  233. const outbound = new MobileRpcFrameGate(
  234. (message) => server.send(message),
  235. outboundMessages,
  236. );
  237. gates.add(outbound);
  238. // 旧连接缓存随关闭销毁,避免释放时向已关闭 socket 发帧。
  239. const dispose = () => {
  240. outbound.dispose();
  241. gates.delete(outbound);
  242. };
  243. route.onClose((code, reason) => {
  244. dispose();
  245. return server.close({ code, reason });
  246. });
  247. server.onClose((code, reason) => {
  248. dispose();
  249. return route.close({ code, reason });
  250. });
  251. route.onMessage((message) =>
  252. outbound.receive(message, (payload, wire) => {
  253. const config =
  254. wire.includes("sendConversationCommandV4") &&
  255. wire.includes('"type":"switchModelConfig"');
  256. if (config && outbound.firstMessage(payload)) configs++;
  257. return holding && config;
  258. }),
  259. );
  260. server.onMessage((message) => route.send(message));
  261. });
  262. await openMobilePairingPage(page, pairingUrl, {
  263. artifactDir: process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/highspeed-thought",
  264. caseMarker: "HS-E2E-07",
  265. phase: "pairing",
  266. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  267. });
  268. await showMobileTaskHome(page);
  269. const toggles = page.getByTestId("virtual-project-toggle");
  270. for (let i = 0; i < (await toggles.count()); i++) {
  271. const toggle = toggles.nth(i);
  272. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  273. }
  274. await page.getByTestId(`task-item-${sessionId}`).first().click();
  275. await page.locator('[data-highspeed-model-indicator="true"]').waitFor();
  276. const input = page.getByTestId("v4-composer-input");
  277. const marker = "E2E_HIGHSPEED_CARD_HIT_NEXT";
  278. await input.fill(marker);
  279. const trigger = page.getByTestId("chat-thought-level-select-trigger");
  280. holding = true;
  281. await trigger.click();
  282. await page.getByTestId("chat-thought-level-select-item-max").click();
  283. await browser.waitUntil(() => heldCount() > 0, { timeout: 10000 });
  284. // 同 bridge 的后台目录 RPC 与未 ACK 重放不能解除门禁或增加逻辑命令数。
  285. await page.evaluate(() => window.dispatchEvent(new Event("focus")));
  286. await browser.waitUntil(
  287. () => heldCount() > 1 && [...gates].some((gate) => gate.replayedHeldFrames > 0),
  288. {
  289. timeout: 15000,
  290. timeoutMsg: "Highspeed 挂起期间未观察到后继 RPC 与原帧重放",
  291. },
  292. );
  293. expect(await trigger.isDisabled()).toBe(true);
  294. expect(await page.getByTestId("v4-composer-send").isDisabled()).toBe(true);
  295. await page.keyboard.press("Control+t");
  296. expect(configs).toBe(1);
  297. release();
  298. await expectThought(sessionId, "max");
  299. await browser.waitUntil(() => trigger.isEnabled(), { timeout: 10000 });
  300. await page.keyboard.press("Control+t");
  301. await expectThought(sessionId, "low");
  302. await browser.waitUntil(() => trigger.isEnabled(), { timeout: 10000 });
  303. await trigger.click();
  304. await page.getByTestId("chat-thought-level-select-item-max").click();
  305. await expectThought(sessionId, "max");
  306. await page.getByTestId("v4-composer-send").click();
  307. // 本场景保留 Coding Plan HTTPS Endpoint,实际请求在数据面代理而非普通 Provider 代理。
  308. const captureRoot = process.env.E2E_PROVIDER_CAPTURE_PATH;
  309. if (!captureRoot) throw new Error("缺少抓包目录");
  310. let capture: E2ENetworkCaptureRecord | undefined;
  311. await browser.waitUntil(
  312. async () => {
  313. const artifact = JSON.parse(
  314. await readFile(join(dirname(captureRoot), "coding-plan-data-plane.json"), "utf8"),
  315. ) as E2ENetworkCaptureArtifact;
  316. capture = artifact.records.find(
  317. (record) =>
  318. record.status === "complete" &&
  319. record.statusCode === 200 &&
  320. JSON.stringify(
  321. (record.requestJson as { messages?: unknown } | undefined)?.messages ?? [],
  322. ).includes(marker),
  323. );
  324. return Boolean(capture);
  325. },
  326. { timeout: 30000, timeoutMsg: "手机调档后未捕获到 Coding Plan 实际请求" },
  327. );
  328. const request = capture!.requestJson as Record<string, unknown>;
  329. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR;
  330. if (artifactDir) {
  331. await writeFile(
  332. join(artifactDir, "highspeed-thought-request.json"),
  333. JSON.stringify(
  334. {
  335. sessionId,
  336. marker,
  337. url: capture!.url,
  338. statusCode: capture!.statusCode,
  339. model: request.model,
  340. thinking: request.thinking,
  341. output_config: request.output_config,
  342. },
  343. null,
  344. 2,
  345. ),
  346. );
  347. }
  348. assertUpstreamThoughtLevelCapture(capture!, "max");
  349. await browser.waitUntil(() => page.getByTestId("v4-composer-send").isVisible(), {
  350. timeout: 30000,
  351. });
  352. } finally {
  353. release();
  354. await chrome.close();
  355. }
  356. });
  357. });