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

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