marketing-touch-delivery.test.ts 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  1. import { readFile, readdir, stat } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { BUILTIN_MODEL_PROVIDER_IDS, marketingPopupSchema } from "@zcode/shared";
  4. import { waitForDefaultWorkspaceReady, getE2EAppDataPaths } from "../helpers/desktop-app.js";
  5. const byId = (id: string) => $(`[data-testid="${id}"]`);
  6. // 原截图写入系统临时目录,违反运行目录隔离;统一归档到本轮报告目录。
  7. const screenshotPath = (name: string) => {
  8. const directory = process.env.ZCODE_E2E_ARTIFACT_DIR;
  9. if (!directory) throw new Error("Missing E2E artifact directory");
  10. return join(directory, name);
  11. };
  12. const bannerAction = () =>
  13. byId("marketing-banner").$('button[aria-label="Open"], button[aria-label="打开"]');
  14. const bannerClose = () =>
  15. byId("marketing-banner").$('button[aria-label="Close"], button[aria-label="关闭"]');
  16. const origin = () => {
  17. const value = process.env.ZCODE_CODING_PLAN_UPGRADE_MOCK_BASE_URL;
  18. if (!value) throw new Error("Missing isolated marketing fixture");
  19. return value;
  20. };
  21. async function ledger() {
  22. return (await (await fetch(`${origin()}/__e2e/marketing/state`)).json()) as {
  23. pendingQueries: number;
  24. events: Array<{ campaign_id: string; action_type: string }>;
  25. requests: string[];
  26. requestDetails: Array<{
  27. method: string;
  28. path: string;
  29. seq: string | null;
  30. timestamp: number;
  31. headers: {
  32. deviceMid?: string;
  33. language?: string;
  34. appVersion?: string;
  35. authenticated: boolean;
  36. };
  37. }>;
  38. };
  39. }
  40. let currentActionCampaignId = "";
  41. async function deliverAction(action: unknown) {
  42. const response = await fetch(`${origin()}/__e2e/marketing/action-delivery`, {
  43. method: "POST",
  44. body: JSON.stringify(action),
  45. });
  46. currentActionCampaignId = ((await response.json()) as { campaignId: string }).campaignId;
  47. await browser.execute(() => window.dispatchEvent(new Event("online")));
  48. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15_000 });
  49. expect(await byId("cloud-content-dialog").getText()).toContain(
  50. `E2E actions ${currentActionCampaignId}`,
  51. );
  52. }
  53. async function connectionSettings() {
  54. const settings = JSON.parse(
  55. await readFile(join(getE2EAppDataPaths().appDataDir, "setting.json"), "utf8"),
  56. );
  57. const selections = settings.providerFamilyConnectionSelections;
  58. // 旧字段已删除;先验证真实快照非空,避免 undefined 与 undefined 的假通过。
  59. expect(selections).toBeDefined();
  60. expect(Object.keys(selections).length).toBeGreaterThan(0);
  61. return selections;
  62. }
  63. async function fixtureAssets() {
  64. return (await (await fetch(`${origin()}/__e2e/marketing/assets`)).json()) as Record<
  65. | "image"
  66. | "darkImage"
  67. | "invalidImage"
  68. | "invalidZip"
  69. | "bundle"
  70. | "faultBundle"
  71. | "brokenPng"
  72. | "brokenMp4",
  73. { src: string; sha256: string }
  74. >;
  75. }
  76. async function imageDataUri(asset: { src: string }) {
  77. const bytes = Buffer.from(await (await fetch(asset.src)).arrayBuffer());
  78. return `data:image/png;base64,${bytes.toString("base64")}`;
  79. }
  80. async function deliverHero(hero: unknown) {
  81. const response = await fetch(`${origin()}/__e2e/marketing/rich-delivery`, {
  82. method: "POST",
  83. body: JSON.stringify(
  84. marketingPopupSchema.parse({
  85. layout: "v1",
  86. title: { format: "plaintext", content: "E2E media boundary" },
  87. description: { format: "plaintext", content: "Media boundary fixture" },
  88. hero,
  89. buttons: [
  90. { text: { format: "plaintext", content: "Close media" }, action: { type: "close" } },
  91. ],
  92. }),
  93. ),
  94. });
  95. const result = (await response.json()) as { campaignId: string };
  96. await browser.execute(() => window.dispatchEvent(new Event("online")));
  97. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 20_000 });
  98. return result.campaignId;
  99. }
  100. describe("Marketing Touch delivery", () => {
  101. before(async () => {
  102. await waitForDefaultWorkspaceReady();
  103. expect(await byId("cloud-content-preview-entry").isExisting()).toBe(false);
  104. });
  105. after(async () => {
  106. await fetch(`${origin()}/__e2e/marketing/release`, { method: "POST" });
  107. });
  108. beforeEach(async function () {
  109. const title = this.currentTest!.title;
  110. await fetch(`${origin()}/__e2e/marketing/reset`, {
  111. method: "POST",
  112. body: JSON.stringify({
  113. popup:
  114. title.startsWith("MTC-01/") ||
  115. title.startsWith("MTC-07/08:") ||
  116. title.startsWith("MTE-04 independent") ||
  117. title.startsWith("MTE-06 stale popup") ||
  118. title.startsWith("MTE-08:") ||
  119. title.startsWith("MTE-09:"),
  120. banner: title.startsWith("MTC-11:") || title.startsWith("MTE-06 stale banner"),
  121. }),
  122. });
  123. // 每例从真实新窗口启动;旧失败 modal、导航请求和缓存不能污染下一个 case。
  124. await browser.reloadSession();
  125. await waitForDefaultWorkspaceReady();
  126. const back = $('button[aria-label="Back to workspace"]');
  127. if (await back.isDisplayed()) await back.click();
  128. });
  129. for (const source of ["X", "Escape", "overlay"] as const) {
  130. const dismiss = async () => {
  131. if (source === "X") {
  132. await byId("cloud-content-dialog").$('[data-slot="dialog-close"]').click();
  133. } else if (source === "Escape") {
  134. const focus = await browser.execute(() => ({
  135. tag: document.activeElement?.tagName,
  136. testId: document.activeElement?.getAttribute("data-testid"),
  137. }));
  138. expect(focus).not.toMatchObject({ tag: "IFRAME" });
  139. await browser.keys("Escape");
  140. } else {
  141. // 从遮罩边角实际点击,不调用组件回调,避免误点居中的内容。
  142. await browser
  143. .action("pointer")
  144. .move({ x: 8, y: 80, origin: "viewport" })
  145. .down()
  146. .up()
  147. .perform();
  148. }
  149. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  150. };
  151. it(`MTE-04 independent ${source}: reports one cancel through the actual dismissal surface`, async () => {
  152. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15_000 });
  153. await dismiss();
  154. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  155. // 再次按 Esc 不能对已关闭的投放重复上报。
  156. await browser.keys("Escape");
  157. expect((await ledger()).events).toEqual([
  158. { campaign_id: "independent", action_type: "cancel" },
  159. ]);
  160. expect(
  161. (await ledger()).requests.filter((path) => path.endsWith("/billing/claim")),
  162. ).toHaveLength(0);
  163. });
  164. }
  165. it("MTE-17 image: switches the prepared resource with the App theme", async () => {
  166. const assets = await fixtureAssets();
  167. const [light, dark] = await Promise.all([
  168. imageDataUri(assets.image),
  169. imageDataUri(assets.darkImage),
  170. ]);
  171. expect(light).not.toBe(dark);
  172. const campaignId = await deliverHero({
  173. type: "image",
  174. image: { default: assets.image, dark: assets.darkImage },
  175. });
  176. const initialDark = await browser.execute(() =>
  177. document.documentElement.classList.contains("dark"),
  178. );
  179. try {
  180. await browser.execute(() => document.documentElement.classList.remove("dark"));
  181. await browser.waitUntil(
  182. async () => (await byId("cloud-dialog-image-hero").$("img").getAttribute("src")) === light,
  183. );
  184. await browser.execute(() => document.documentElement.classList.add("dark"));
  185. await browser.waitUntil(
  186. async () => (await byId("cloud-dialog-image-hero").$("img").getAttribute("src")) === dark,
  187. );
  188. expect(await byId("cloud-dialog-image-hero").getAttribute("data-status")).toBe("ready");
  189. } finally {
  190. await browser.execute(
  191. (dark) => document.documentElement.classList.toggle("dark", dark),
  192. initialDark,
  193. );
  194. }
  195. await byId("cloud-dialog-action").click();
  196. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  197. expect((await ledger()).events).toEqual([{ campaign_id: campaignId, action_type: "cancel" }]);
  198. });
  199. it("MTE-17 invalid dark image: retains the valid default resource", async () => {
  200. const assets = await fixtureAssets();
  201. const light = await imageDataUri(assets.image);
  202. await deliverHero({
  203. type: "image",
  204. image: { default: assets.image, dark: assets.invalidImage },
  205. });
  206. const initialDark = await browser.execute(() =>
  207. document.documentElement.classList.contains("dark"),
  208. );
  209. try {
  210. await browser.execute(() => document.documentElement.classList.add("dark"));
  211. await browser.waitUntil(
  212. async () => (await byId("cloud-dialog-image-hero").$("img").getAttribute("src")) === light,
  213. );
  214. expect(await byId("cloud-dialog-image-hero").getAttribute("data-status")).toBe("ready");
  215. } finally {
  216. await browser.execute(
  217. (dark) => document.documentElement.classList.toggle("dark", dark),
  218. initialDark,
  219. );
  220. }
  221. expect((await ledger()).requests).toContain("/marketing-assets/invalid.png");
  222. });
  223. async function deliverText(format: "html" | "markdown", content: string) {
  224. const response = await fetch(`${origin()}/__e2e/marketing/rich-delivery`, {
  225. method: "POST",
  226. body: JSON.stringify(
  227. marketingPopupSchema.parse({
  228. layout: "v1",
  229. hero: null,
  230. title: {
  231. format: "html",
  232. content: '<p><a href="https://example.com/title">Safe title</a></p>',
  233. },
  234. description: { format, content },
  235. buttons: [
  236. {
  237. text: {
  238. format: "html",
  239. content: '<p><a href="https://example.com/button">Close text</a></p>',
  240. },
  241. action: { type: "close" },
  242. },
  243. ],
  244. }),
  245. ),
  246. });
  247. const campaign = ((await response.json()) as { campaignId: string }).campaignId;
  248. await browser.execute(() => window.dispatchEvent(new Event("online")));
  249. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15_000 });
  250. return campaign;
  251. }
  252. it("MTE-16 security: sanitizes HTML and routes a safe link through App", async () => {
  253. const open = await browser.electron.mock("shell", "openExternal");
  254. await open.mockResolvedValue(undefined);
  255. try {
  256. const campaign = await deliverText(
  257. "html",
  258. `<script>window.e2eUnsafeExecuted=true</script><svg onload="window.e2eUnsafeExecuted=true"></svg><!-- ignored -->
  259. <p onclick="window.e2eUnsafeExecuted=true">Safe body</p>
  260. <a href="javascript:window.e2eUnsafeExecuted=true">Bad protocol</a>
  261. <a href="https://user:pass@example.com">Credentials</a><a href="https://[">Bad URL</a>
  262. <a href="https://example.com/marketing?source=e2e" title="Safe destination">Open safe link</a>`,
  263. );
  264. const description = byId("cloud-dialog-description");
  265. expect(await description.$$("a")).toHaveLength(1);
  266. expect(await description.$$("script, svg, [onclick], [onload]")).toHaveLength(0);
  267. expect(await description.getText()).toContain("Bad protocol");
  268. expect(
  269. await byId("cloud-content-dialog").$$('[data-slot="dialog-title"] a, button a, button p'),
  270. ).toHaveLength(0);
  271. expect(
  272. await browser.execute(() =>
  273. Boolean((window as typeof window & { e2eUnsafeExecuted?: boolean }).e2eUnsafeExecuted),
  274. ),
  275. ).toBe(false);
  276. expect((await ledger()).events).toEqual([]);
  277. await description.$("a").click();
  278. await browser.waitUntil(async () => {
  279. await open.update();
  280. return open.mock.calls.length === 1;
  281. });
  282. expect(open.mock.calls[0]?.[0]).toBe("https://example.com/marketing?source=e2e");
  283. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  284. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  285. expect((await ledger()).events).toEqual([{ campaign_id: campaign, action_type: "confirm" }]);
  286. } finally {
  287. await browser.electron.restoreAllMocks();
  288. }
  289. });
  290. it("MTE-16 markdown: renders structure but keeps embedded HTML literal", async () => {
  291. await deliverText(
  292. "markdown",
  293. "# Heading\n\n- First\n- Second\n\n<strong>Literal HTML</strong>",
  294. );
  295. const description = byId("cloud-dialog-description");
  296. expect(await description.$("h1").getText()).toBe("Heading");
  297. expect(await description.$$("li")).toHaveLength(2);
  298. expect(await description.$$("strong")).toHaveLength(0);
  299. expect(await description.getText()).toContain("<strong>Literal HTML</strong>");
  300. expect((await ledger()).events).toEqual([]);
  301. });
  302. it("MTE-16 deep HTML: falls back to literal text beyond depth limit", async () => {
  303. const html = "<span>".repeat(34) + "Deep content" + "</span>".repeat(34);
  304. await deliverText("html", html);
  305. const description = byId("cloud-dialog-description");
  306. expect(await description.getText()).toBe(html);
  307. expect(await description.$$("span")).toHaveLength(0);
  308. expect((await ledger()).events).toEqual([]);
  309. });
  310. for (const surface of ["banner", "popup"] as const) {
  311. it(`MTE-06 stale ${surface}: ignores pre-close response and accepts fresh redelivery`, async () => {
  312. const content = byId(surface === "banner" ? "marketing-banner" : "cloud-content-dialog");
  313. await content.waitForDisplayed({ timeout: 15_000 });
  314. const control = async (action: string) => {
  315. expect(
  316. (await fetch(`${origin()}/__e2e/marketing/query-${action}`, { method: "POST" })).ok,
  317. ).toBe(true);
  318. };
  319. const queries = async () =>
  320. (await ledger()).requests.filter((p) => p === "/api/v1/marketing/touch").length;
  321. await control("hold");
  322. try {
  323. await browser.execute(() => window.dispatchEvent(new Event("online")));
  324. await browser.waitUntil(async () => (await ledger()).pendingQueries === 1);
  325. const count = await queries();
  326. if (surface === "banner") await bannerClose().click();
  327. else await content.$('[data-slot="dialog-close"]').click();
  328. await content.waitForExist({ reverse: true });
  329. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  330. await browser.execute(() => {
  331. for (let i = 0; i < 3; i++) window.dispatchEvent(new Event("online"));
  332. });
  333. expect(await queries()).toBe(count);
  334. await control("release-one");
  335. await browser.waitUntil(
  336. async () => (await queries()) === count + 1 && (await ledger()).pendingQueries === 1,
  337. );
  338. expect(await content.isExisting()).toBe(false);
  339. expect((await ledger()).events).toEqual([
  340. { campaign_id: surface === "banner" ? "banner-1" : "independent", action_type: "cancel" },
  341. ]);
  342. } finally {
  343. await control("release-all");
  344. }
  345. await fetch(`${origin()}/__e2e/marketing/redeliver-${surface}`, { method: "POST" });
  346. await browser.execute(() => window.dispatchEvent(new Event("online")));
  347. await content.waitForDisplayed({ timeout: 15_000 });
  348. expect((await ledger()).events).toHaveLength(1);
  349. });
  350. }
  351. it("MTE-06 stale prepared bundle is discarded after popup close", async () => {
  352. await deliverAction({ type: "close" });
  353. const closedCampaign = currentActionCampaignId;
  354. const control = (name: string) =>
  355. fetch(`${origin()}/__e2e/marketing/${name}`, { method: "POST" });
  356. await control("asset-hold");
  357. try {
  358. await control("bundle-banner");
  359. await browser.execute(() => window.dispatchEvent(new Event("online")));
  360. await browser.waitUntil(async () => {
  361. const state = (await (await fetch(`${origin()}/__e2e/marketing/asset-state`)).json()) as {
  362. pending: number;
  363. };
  364. return state.pending === 1;
  365. });
  366. expect(await byId("marketing-banner").isExisting()).toBe(false);
  367. await byId("cloud-content-dialog").$('[data-slot="dialog-close"]').click();
  368. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  369. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  370. await control("query-hold");
  371. await browser.execute(() => window.dispatchEvent(new Event("online")));
  372. await control("asset-release");
  373. // 下一 GET 已进入服务端,证明旧资源准备已收口,不用睡眠猜测迟到结果。
  374. await browser.waitUntil(async () => (await ledger()).pendingQueries === 1);
  375. expect(await byId("marketing-banner").isExisting()).toBe(false);
  376. expect((await ledger()).events).toEqual([
  377. { campaign_id: closedCampaign, action_type: "cancel" },
  378. ]);
  379. await control("query-release-all");
  380. await byId("marketing-banner").waitForDisplayed({ timeout: 15_000 });
  381. expect(await byId("marketing-banner").$("iframe").getAttribute("data-status")).toBe("ready");
  382. expect((await ledger()).events).toHaveLength(1);
  383. } finally {
  384. await control("asset-release");
  385. await control("query-release-all");
  386. }
  387. });
  388. for (const kind of ["image", "video", "video-fallback"] as const) {
  389. it(`MTE-17 decoder ${kind}: preserves text when the browser rejects valid-signature media`, async () => {
  390. const assets = await fixtureAssets();
  391. await deliverHero(
  392. kind === "image"
  393. ? { type: "image", image: { default: assets.brokenPng } }
  394. : {
  395. type: "video",
  396. video: {
  397. src: assets.brokenMp4,
  398. fallback: kind === "video-fallback" ? assets.image : assets.brokenPng,
  399. },
  400. },
  401. );
  402. expect(await byId("cloud-content-dialog").getText()).toContain("Media boundary fixture");
  403. expect(await byId("cloud-dialog-hero-slot").isExisting()).toBe(kind === "video-fallback");
  404. if (kind === "video-fallback")
  405. expect(await byId("cloud-dialog-hero-slot").$("img").getAttribute("src")).toBe(
  406. await imageDataUri(assets.image),
  407. );
  408. const path = new URL(kind === "image" ? assets.brokenPng.src : assets.brokenMp4.src).pathname;
  409. expect((await ledger()).requests).toContain(path);
  410. expect((await ledger()).events).toEqual([]);
  411. });
  412. }
  413. for (const mode of ["error", "silent"] as const) {
  414. for (const fallback of [false, true]) {
  415. it(`MTE-11 handshake ${mode} fallback=${fallback}`, async () => {
  416. const assets = await fixtureAssets();
  417. const campaign = await deliverHero({
  418. type: "bundle",
  419. args: { mode },
  420. bundle: {
  421. bundle: assets.faultBundle,
  422. entry: "index.html",
  423. ...(fallback ? { fallback: assets.image } : {}),
  424. },
  425. });
  426. const slot = byId("cloud-dialog-hero-slot");
  427. if (fallback) {
  428. await slot.$("img").waitForDisplayed({ timeout: 10_000 });
  429. expect(await slot.$("img").getAttribute("src")).toBe(await imageDataUri(assets.image));
  430. } else await byId("cloud-dialog-hero-error").waitForDisplayed({ timeout: 10_000 });
  431. expect(await byId("cloud-dialog-interactive-hero").isExisting()).toBe(false);
  432. expect((await ledger()).events).toEqual([]);
  433. await byId("cloud-content-dialog").$('[data-slot="dialog-close"]').click();
  434. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  435. expect((await ledger()).events).toEqual([{ campaign_id: campaign, action_type: "cancel" }]);
  436. });
  437. }
  438. }
  439. it("MTE-11 wrong instance ready cannot bypass handshake timeout", async () => {
  440. const assets = await fixtureAssets();
  441. await deliverHero({
  442. type: "bundle",
  443. args: { mode: "wrong-instance" },
  444. bundle: { bundle: assets.faultBundle, entry: "index.html", fallback: assets.image },
  445. });
  446. const frame = byId("cloud-dialog-interactive-hero");
  447. await frame.waitForExist();
  448. await browser.switchFrame(await frame);
  449. try {
  450. await browser.waitUntil(
  451. async () => (await $("html").getAttribute("data-sent")) === "wrong-instance",
  452. );
  453. } finally {
  454. await browser.switchFrame(null);
  455. }
  456. const fallback = byId("cloud-dialog-hero-slot").$("img");
  457. await fallback.waitForDisplayed({ timeout: 10_000 });
  458. expect(await fallback.getAttribute("src")).toBe(await imageDataUri(assets.image));
  459. expect(await frame.isExisting()).toBe(false);
  460. expect((await ledger()).events).toEqual([]);
  461. });
  462. it("MTE-11 invalid messages from the actual iframe preserve ready state", async () => {
  463. const assets = await fixtureAssets();
  464. const campaign = await deliverHero({
  465. type: "bundle",
  466. bundle: { bundle: assets.bundle, entry: "index.html" },
  467. });
  468. const frame = byId("cloud-dialog-interactive-hero");
  469. await browser.waitUntil(async () => (await frame.getAttribute("data-status")) === "ready");
  470. const instanceId = await frame.getAttribute("data-instance-id");
  471. await browser.switchFrame(await frame);
  472. try {
  473. await browser.execute((instanceId) => {
  474. const base = { channel: "zcode-cloud-hero-v1", instanceId };
  475. for (const message of [
  476. null,
  477. { ...base, type: "error", code: "wrong-instance", instanceId: `${instanceId}-other` },
  478. { ...base, type: "error", code: "wrong-channel", channel: "other" },
  479. { ...base, type: "error", code: 42 },
  480. { ...base, type: "action", id: 42 },
  481. { ...base, type: "resize", height: Number.NaN },
  482. { ...base, type: "unsupported" },
  483. ])
  484. parent.postMessage(message, "*");
  485. }, instanceId);
  486. } finally {
  487. await browser.switchFrame(null);
  488. }
  489. // 消息来自真正的 sandbox iframe,父窗口绘制后再验证忽略结果。
  490. await browser.executeAsync((done) =>
  491. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  492. );
  493. expect(await frame.getAttribute("data-status")).toBe("ready");
  494. expect(await byId("cloud-dialog-hero-error").isExisting()).toBe(false);
  495. expect((await ledger()).events).toEqual([]);
  496. await byId("cloud-content-dialog").$('[data-slot="dialog-close"]').click();
  497. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  498. expect((await ledger()).events).toEqual([{ campaign_id: campaign, action_type: "cancel" }]);
  499. });
  500. it("MTE-11 forged parent message cannot invalidate a ready iframe", async () => {
  501. const assets = await fixtureAssets();
  502. await deliverHero({ type: "bundle", bundle: { bundle: assets.bundle, entry: "index.html" } });
  503. const frame = byId("cloud-dialog-interactive-hero");
  504. await browser.waitUntil(async () => (await frame.getAttribute("data-status")) === "ready");
  505. const instanceId = await frame.getAttribute("data-instance-id");
  506. await browser.executeAsync((instanceId, done) => {
  507. window.postMessage(
  508. { channel: "zcode-cloud-hero-v1", instanceId, type: "error", code: "forged" },
  509. "*",
  510. );
  511. // 等待浏览器消息派发后的绘制,不用固定延迟代替状态同步。
  512. requestAnimationFrame(() => requestAnimationFrame(() => done()));
  513. }, instanceId);
  514. expect(await frame.getAttribute("data-status")).toBe("ready");
  515. expect(await byId("cloud-dialog-hero-error").isExisting()).toBe(false);
  516. expect((await ledger()).events).toEqual([]);
  517. });
  518. for (const fallback of [false, true]) {
  519. it(`MTE-10 invalid zip: ${fallback ? "uses the prepared fallback" : "omits the unavailable hero"}`, async () => {
  520. const assets = await fixtureAssets();
  521. const campaignId = await deliverHero({
  522. type: "bundle",
  523. bundle: {
  524. bundle: assets.invalidZip,
  525. entry: "index.html",
  526. ...(fallback ? { fallback: assets.image } : {}),
  527. },
  528. });
  529. expect(await byId("cloud-dialog-interactive-hero").isExisting()).toBe(false);
  530. expect(await byId("cloud-dialog-hero-slot").isExisting()).toBe(fallback);
  531. if (fallback)
  532. await browser.waitUntil(
  533. async () =>
  534. (await byId("cloud-dialog-image-hero").getAttribute("data-status")) === "ready",
  535. );
  536. expect((await ledger()).requests).toContain("/marketing-assets/invalid.zip");
  537. await byId("cloud-dialog-action").click();
  538. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  539. expect((await ledger()).events).toEqual([{ campaign_id: campaignId, action_type: "cancel" }]);
  540. });
  541. }
  542. it("MTE-17 invalid default image: shows dialog text without broken media", async () => {
  543. const assets = await fixtureAssets();
  544. await deliverHero({ type: "image", image: { default: assets.invalidImage } });
  545. expect(await byId("cloud-dialog-hero-slot").isExisting()).toBe(false);
  546. expect(await byId("cloud-content-dialog").getText()).toContain("E2E media boundary");
  547. expect((await ledger()).requests).toContain("/marketing-assets/invalid.png");
  548. });
  549. it("MTE-08: starts seq at zero, carries required headers and does not count action reports", async () => {
  550. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15_000 });
  551. const queries = (state: Awaited<ReturnType<typeof ledger>>) =>
  552. state.requestDetails.filter((request) => request.path === "/api/v1/marketing/touch");
  553. const initial = queries(await ledger());
  554. expect(initial.length).toBeGreaterThan(0);
  555. expect(initial[0]?.seq).toBe("0");
  556. for (const request of initial) {
  557. expect(request.method).toBe("GET");
  558. expect(request.headers.deviceMid?.length).toBeGreaterThan(0);
  559. expect(request.headers.language).toBe("en-US");
  560. expect(request.headers.appVersion?.length).toBeGreaterThan(0);
  561. expect(request.headers.authenticated).toBe(true);
  562. }
  563. await byId("cloud-dialog-action").click();
  564. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  565. await browser.execute(() => window.dispatchEvent(new Event("online")));
  566. await browser.waitUntil(async () => queries(await ledger()).length > initial.length);
  567. const state = await ledger();
  568. expect(queries(state).map((request) => Number(request.seq))).toEqual(
  569. queries(state).map((_, index) => index),
  570. );
  571. const reports = state.requestDetails.filter((request) =>
  572. request.path.endsWith("/touch/action"),
  573. );
  574. expect(reports).toHaveLength(1);
  575. expect(reports[0]).toMatchObject({ method: "POST", seq: null });
  576. expect(await byId("cloud-content-dialog").isExisting()).toBe(false);
  577. });
  578. it("MTE-09: a failed report does not block dismissal or automatically retry", async () => {
  579. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15_000 });
  580. await fetch(`${origin()}/__e2e/marketing/faults`, {
  581. method: "POST",
  582. body: JSON.stringify({ reportStatus: 500 }),
  583. });
  584. await byId("cloud-dialog-action").click();
  585. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  586. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  587. // 用新一轮真实查询作为完成屏障:服务端仍投放同 ID,客户端可以再次显示,但不能自动重报。
  588. await browser.execute(() => window.dispatchEvent(new Event("online")));
  589. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15_000 });
  590. expect((await ledger()).events).toEqual([
  591. { campaign_id: "independent", action_type: "cancel" },
  592. ]);
  593. await fetch(`${origin()}/__e2e/marketing/faults`, { method: "POST", body: "{}" });
  594. await byId("cloud-dialog-action").click();
  595. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  596. await browser.waitUntil(async () => (await ledger()).events.length === 2);
  597. expect((await ledger()).events).toEqual(
  598. Array.from({ length: 2 }, () => ({ campaign_id: "independent", action_type: "cancel" })),
  599. );
  600. });
  601. it("MTE-07: recovers from query failure on online and keeps monotonic sequence", async () => {
  602. await fetch(`${origin()}/__e2e/marketing/faults`, {
  603. method: "POST",
  604. body: JSON.stringify({ queryStatus: 503 }),
  605. });
  606. const count = () =>
  607. ledger().then(
  608. (state) =>
  609. state.requestDetails.filter((request) => request.path === "/api/v1/marketing/touch")
  610. .length,
  611. );
  612. const before = await count();
  613. await browser.execute(() => window.dispatchEvent(new Event("online")));
  614. await browser.waitUntil(async () => (await count()) > before);
  615. expect(await byId("marketing-banner").isExisting()).toBe(false);
  616. expect(await byId("cloud-content-dialog").isExisting()).toBe(false);
  617. await fetch(`${origin()}/__e2e/marketing/faults`, { method: "POST", body: "{}" });
  618. await deliverAction({ type: "close" });
  619. await byId("cloud-dialog-action").click();
  620. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  621. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  622. const queries = (await ledger()).requestDetails.filter(
  623. (request) => request.path === "/api/v1/marketing/touch",
  624. );
  625. expect(queries.map((request) => Number(request.seq))).toEqual(queries.map((_, index) => index));
  626. });
  627. it("MTC-01/07/08: opens the independent popup and reports cancel exactly once", async () => {
  628. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 40_000 });
  629. expect(await byId("cloud-content-dialog").getText()).toContain("E2E independent popup");
  630. const closeButton = byId("cloud-content-dialog").$('[data-slot="dialog-close"]');
  631. const palette = await browser.execute(() => {
  632. const root = document.documentElement;
  633. const original = root.className;
  634. try {
  635. return [false, true].map((dark) => {
  636. root.classList.toggle("dark", dark);
  637. const button = document.querySelector(
  638. '[data-testid="cloud-content-dialog"] [data-slot="dialog-close"]',
  639. )!;
  640. const style = getComputedStyle(button);
  641. return { color: style.color, border: style.borderTopWidth };
  642. });
  643. } finally {
  644. root.className = original;
  645. }
  646. });
  647. expect(palette).toEqual([0, 1].map(() => ({ color: "rgb(255, 255, 255)", border: "0px" })));
  648. expect((await closeButton.getCSSProperty("background-color")).value).toBe("rgba(0,0,0,0.5)");
  649. expect((await closeButton.getCSSProperty("color")).parsed.hex).toBe("#ffffff");
  650. expect((await closeButton.getCSSProperty("border-top-width")).value).toBe("0px");
  651. await closeButton.moveTo();
  652. await browser.waitUntil(
  653. async () =>
  654. (await closeButton.getCSSProperty("background-color")).value === "rgba(0,0,0,0.65)",
  655. );
  656. await byId("cloud-content-dialog").$("h2").moveTo();
  657. await browser.waitUntil(
  658. async () =>
  659. (await closeButton.getCSSProperty("background-color")).value === "rgba(0,0,0,0.5)",
  660. );
  661. await byId("cloud-dialog-action").click();
  662. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  663. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  664. expect((await ledger()).events).toEqual([
  665. { campaign_id: "independent", action_type: "cancel" },
  666. ]);
  667. });
  668. it("MTC-11: polls a closed campaign again and reports the next close", async () => {
  669. await byId("marketing-banner").waitForDisplayed();
  670. await bannerClose().click();
  671. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  672. await fetch(`${origin()}/__e2e/marketing/redeliver-banner`, { method: "POST" });
  673. await byId("marketing-banner").waitForDisplayed({ timeout: 45_000 });
  674. await bannerClose().click();
  675. await byId("marketing-banner").waitForExist({ reverse: true });
  676. await browser.waitUntil(async () => (await ledger()).events.length === 2);
  677. expect((await ledger()).events[1]).toEqual({ campaign_id: "banner-1", action_type: "cancel" });
  678. });
  679. it("MTC-07/08: reopens and reports the same independent popup only after server redelivery", async () => {
  680. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15000 });
  681. await byId("cloud-dialog-action").click();
  682. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  683. await fetch(`${origin()}/__e2e/marketing/redeliver-popup`, { method: "POST" });
  684. await browser.execute(() => window.dispatchEvent(new Event("online")));
  685. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15_000 });
  686. expect(await byId("cloud-content-dialog").getText()).toContain("E2E independent popup");
  687. await byId("cloud-dialog-action").click();
  688. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  689. await browser.waitUntil(async () => (await ledger()).events.length === 2);
  690. expect((await ledger()).events[1]).toEqual({
  691. campaign_id: "independent",
  692. action_type: "cancel",
  693. });
  694. });
  695. it("MTA-01: copies exact plaintext repeatedly, retains popup and reports close separately", async () => {
  696. const baseline = (await ledger()).events.length;
  697. const text = " <b>E2E copy</b>\nsecond line ";
  698. await deliverAction({ type: "copy_text", args: { text } });
  699. const button = byId("cloud-content-dialog").$('button[data-testid="cloud-dialog-action"]');
  700. expect(await button.$("svg").isExisting()).toBe(false);
  701. await button.click();
  702. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 1);
  703. expect(await byId("cloud-content-dialog").isDisplayed()).toBe(true);
  704. expect(await browser.execute(() => navigator.clipboard.readText())).toBe(text);
  705. expect(await button.$("svg").isExisting()).toBe(false);
  706. await button.click();
  707. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 2);
  708. await byId("cloud-content-dialog").$("button=Close campaign").click();
  709. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 3);
  710. expect((await ledger()).events.slice(baseline).map((event) => event.action_type)).toEqual([
  711. "confirm",
  712. "confirm",
  713. "cancel",
  714. ]);
  715. });
  716. it("MTA-02: navigates to appearance before closing and confirming", async () => {
  717. const baseline = (await ledger()).events.length;
  718. await deliverAction({ type: "navigate", args: { page: "settings", section: "appearance" } });
  719. await byId("cloud-content-dialog").$("button=Run action").click();
  720. await byId("cloud-content-dialog").waitForExist({ reverse: true, timeout: 15_000 });
  721. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 1);
  722. expect(await browser.execute(() => localStorage.getItem("zcode-settings-last-section"))).toBe(
  723. "appearance",
  724. );
  725. expect((await ledger()).events[baseline]).toEqual({
  726. campaign_id: currentActionCampaignId,
  727. action_type: "confirm",
  728. });
  729. });
  730. it("MTA-03: reuses settings for every supported section", async () => {
  731. const sections = {
  732. general: "general",
  733. appearance: "appearance",
  734. models: "modelProvider",
  735. browser: "browser",
  736. computer_use: "computerUse",
  737. memory: "memory",
  738. subagents: "subagents",
  739. plugins: "plugin",
  740. mcp: "mcp",
  741. skills: "skill",
  742. commands: "commands",
  743. hooks: "hooks",
  744. usage: "usage",
  745. };
  746. for (const [section, internal] of Object.entries(sections)) {
  747. const baseline = (await ledger()).events.length;
  748. await deliverAction({ type: "navigate", args: { page: "settings", section } });
  749. await byId("cloud-content-dialog").$("button=Run action").click();
  750. await byId("cloud-content-dialog").waitForExist({ reverse: true, timeout: 15_000 });
  751. expect(await $(`[data-active-section="${internal}"]`).isDisplayed()).toBe(true);
  752. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 1);
  753. }
  754. });
  755. it("MTA-04: opens marketplace and keeps failed detail navigation retryable without confirming", async () => {
  756. await deliverAction({ type: "navigate", args: { page: "plugin_marketplace" } });
  757. await byId("cloud-content-dialog").$("button=Run action").click();
  758. await byId("cloud-content-dialog").waitForExist({ reverse: true, timeout: 35_000 });
  759. expect(await byId("plugin-store-root").isDisplayed()).toBe(true);
  760. const pluginId = await byId("plugin-store-card").getAttribute("data-plugin-id");
  761. expect(pluginId).toContain("@");
  762. await deliverAction({
  763. type: "navigate",
  764. args: { page: "plugin_marketplace", plugin_id: pluginId },
  765. });
  766. await byId("cloud-content-dialog").$("button=Run action").click();
  767. await byId("cloud-content-dialog").waitForExist({ reverse: true, timeout: 35_000 });
  768. expect(await byId("plugin-store-root").getAttribute("data-view")).toBe("detail");
  769. const baseline = (await ledger()).events.length;
  770. await deliverAction({
  771. type: "navigate",
  772. args: { page: "plugin_marketplace", plugin_id: "not-present@not-present" },
  773. });
  774. await byId("cloud-content-dialog").$("button=Run action").click();
  775. await byId("cloud-content-dialog").$('[role="alert"]').waitForDisplayed({ timeout: 35_000 });
  776. expect((await ledger()).events.length).toBe(baseline);
  777. await byId("cloud-content-dialog").$("button=Close campaign").click();
  778. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  779. });
  780. it("MTA-05: locates a model provider without switching connection and rejects missing providers", async () => {
  781. const before = await connectionSettings();
  782. await deliverAction({
  783. type: "navigate",
  784. args: {
  785. page: "settings",
  786. section: "models",
  787. provider_id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  788. },
  789. });
  790. await byId("cloud-content-dialog").$("button=Run action").click();
  791. await byId("cloud-content-dialog").waitForExist({ reverse: true, timeout: 35_000 });
  792. expect(await $('[data-active-section="modelProvider"]').isDisplayed()).toBe(true);
  793. expect(await connectionSettings()).toEqual(before);
  794. expect(
  795. await $(
  796. `[data-testid="model-provider-nav-item-preset:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}"][aria-selected="true"]`,
  797. ).isDisplayed(),
  798. ).toBe(true);
  799. const baseline = (await ledger()).events.length;
  800. await deliverAction({
  801. type: "navigate",
  802. args: { page: "settings", section: "models", provider_id: "missing-provider" },
  803. });
  804. await byId("cloud-content-dialog").$("button=Run action").click();
  805. await byId("cloud-content-dialog").$('[role="alert"]').waitForDisplayed({ timeout: 35_000 });
  806. expect((await ledger()).events.length).toBe(baseline);
  807. await byId("cloud-content-dialog").$("button=Close campaign").click();
  808. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  809. });
  810. it("MTE-02 custom provider navigation preserves the active connection and model", async () => {
  811. const connections = await connectionSettings();
  812. const model = await byId("chat-model-select-trigger").getAttribute("data-model-current-value");
  813. expect(model).not.toBeNull();
  814. await deliverAction({ type: "navigate", args: { page: "settings", section: "models" } });
  815. await byId("cloud-content-dialog").$("button=Run action").click();
  816. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  817. await byId("model-provider-add-provider-button").click();
  818. await byId("model-provider-template-item-custom").click();
  819. const selected = $('[data-testid^="model-provider-nav-item-custom:"][aria-selected="true"]');
  820. await selected.waitForDisplayed({ timeout: 15_000 });
  821. const nodeId = await selected.getAttribute("data-testid");
  822. if (!nodeId) throw new Error("Custom provider navigation node is missing its id");
  823. const providerId = nodeId.replace("model-provider-nav-item-custom:", "");
  824. expect(providerId.length).toBeGreaterThan(0);
  825. try {
  826. await deliverAction({ type: "navigate", args: { page: "settings", section: "appearance" } });
  827. await byId("cloud-content-dialog").$("button=Run action").click();
  828. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  829. const previousEvents = (await ledger()).events.length;
  830. await deliverAction({
  831. type: "navigate",
  832. args: { page: "settings", section: "models", provider_id: providerId },
  833. });
  834. await byId("cloud-content-dialog").$("button=Run action").click();
  835. await byId("cloud-content-dialog").waitForExist({ reverse: true, timeout: 35_000 });
  836. expect(await byId(nodeId).getAttribute("aria-selected")).toBe("true");
  837. await byId("model-provider-base-url-input").waitForDisplayed();
  838. await browser.waitUntil(async () => (await ledger()).events.length === previousEvents + 1);
  839. expect((await ledger()).events.at(-1)).toEqual({
  840. campaign_id: currentActionCampaignId,
  841. action_type: "confirm",
  842. });
  843. expect(await connectionSettings()).toEqual(connections);
  844. await $('button[aria-label="Back to workspace"]').click();
  845. expect(await byId("chat-model-select-trigger").getAttribute("data-model-current-value")).toBe(
  846. model,
  847. );
  848. } finally {
  849. if (await byId("cloud-content-dialog").isExisting())
  850. await byId("cloud-content-dialog").$('[data-slot="dialog-close"]').click();
  851. await deliverAction({
  852. type: "navigate",
  853. args: { page: "settings", section: "models", provider_id: providerId },
  854. });
  855. await byId("cloud-content-dialog").$("button=Run action").click();
  856. await byId("cloud-content-dialog").waitForExist({ reverse: true, timeout: 35_000 });
  857. await $('[data-model-provider-detail-scroll="true"] button:has(svg.lucide-trash-2)').click();
  858. await byId("confirm-dialog-confirm").click();
  859. await byId(nodeId).waitForExist({ reverse: true });
  860. }
  861. });
  862. it("MTA-06: clipboard denial retains content and never shows copied or confirms", async () => {
  863. const baseline = (await ledger()).events.length;
  864. await deliverAction({ type: "copy_text", args: { text: "denied fixture" } });
  865. await browser.execute(() => {
  866. Object.defineProperty(navigator.clipboard, "writeText", {
  867. configurable: true,
  868. value: async () => {
  869. throw new DOMException("Denied", "NotAllowedError");
  870. },
  871. });
  872. });
  873. try {
  874. await byId("cloud-content-dialog").$("button=Run action").click();
  875. await byId("cloud-content-dialog").$('[role="alert"]').waitForDisplayed();
  876. expect(await byId("cloud-content-dialog").$("button=Run action").isEnabled()).toBe(true);
  877. expect((await ledger()).events.length).toBe(baseline);
  878. } finally {
  879. await browser.execute(() => {
  880. Reflect.deleteProperty(navigator.clipboard, "writeText");
  881. });
  882. await byId("cloud-content-dialog").$("button=Close campaign").click();
  883. }
  884. await byId("cloud-content-dialog").waitForExist({ reverse: true });
  885. });
  886. for (const closeBeforeLate of [false, true]) {
  887. it(`MTE-13 clipboard timeout closed=${closeBeforeLate}: ignores late success`, async () => {
  888. await deliverAction({ type: "copy_text", args: { text: "E2E deferred clipboard" } });
  889. const campaignId = currentActionCampaignId;
  890. await browser.execute(() => {
  891. const target = window as typeof window & {
  892. e2eResolveCopy?: () => void;
  893. e2eCopyCalls?: number;
  894. };
  895. target.e2eCopyCalls = 0;
  896. Object.defineProperty(navigator.clipboard, "writeText", {
  897. configurable: true,
  898. value: () =>
  899. new Promise<void>((resolve) => {
  900. target.e2eCopyCalls! += 1;
  901. target.e2eResolveCopy = resolve;
  902. }),
  903. });
  904. });
  905. const popup = byId("cloud-content-dialog");
  906. try {
  907. await popup.$("button=Run action").click();
  908. await browser.waitUntil(
  909. async () =>
  910. await browser.execute(
  911. () => (window as typeof window & { e2eCopyCalls?: number }).e2eCopyCalls === 1,
  912. ),
  913. );
  914. expect(await popup.$("button=Run action").isEnabled()).toBe(false);
  915. await popup.$('[data-slot="dialog-close"]').click();
  916. expect(await popup.isDisplayed()).toBe(true);
  917. expect((await ledger()).events).toEqual([]);
  918. await popup.$('[role="alert"]').waitForDisplayed({ timeout: 15_000 });
  919. expect(await popup.$("button=Run action").isEnabled()).toBe(true);
  920. if (closeBeforeLate) {
  921. await popup.$('[data-slot="dialog-close"]').click();
  922. await popup.waitForExist({ reverse: true });
  923. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  924. }
  925. await browser.executeAsync((done) => {
  926. (window as typeof window & { e2eResolveCopy?: () => void }).e2eResolveCopy?.();
  927. // 兑现平台 Promise 后等待微任务与真实绘制,不提前伪造 App 成功。
  928. requestAnimationFrame(() => requestAnimationFrame(() => done()));
  929. });
  930. expect(await popup.isExisting()).toBe(!closeBeforeLate);
  931. if (!closeBeforeLate) {
  932. expect(await popup.$("button=Run action").isEnabled()).toBe(true);
  933. expect(await popup.$('[role="alert"]').isDisplayed()).toBe(true);
  934. expect((await ledger()).events).toEqual([]);
  935. await popup.$('[data-slot="dialog-close"]').click();
  936. await browser.waitUntil(async () => (await ledger()).events.length === 1);
  937. }
  938. expect((await ledger()).events).toEqual([
  939. { campaign_id: campaignId, action_type: "cancel" },
  940. ]);
  941. expect(
  942. await browser.execute(
  943. () => (window as typeof window & { e2eCopyCalls?: number }).e2eCopyCalls,
  944. ),
  945. ).toBe(1);
  946. } finally {
  947. await browser.execute(() => {
  948. const target = window as typeof window & {
  949. e2eResolveCopy?: () => void;
  950. e2eCopyCalls?: number;
  951. };
  952. target.e2eResolveCopy?.();
  953. delete target.e2eResolveCopy;
  954. delete target.e2eCopyCalls;
  955. Reflect.deleteProperty(navigator.clipboard, "writeText");
  956. });
  957. }
  958. });
  959. }
  960. it("MTA-07: opens the existing upgrade webview and reports navigation, not purchase", async () => {
  961. const baseline = (await ledger()).events.length;
  962. await deliverAction({ type: "navigate", args: { page: "upgrade" } });
  963. await byId("cloud-content-dialog").$("button=Run action").click();
  964. await byId("coding-plan-upgrade-surface").waitForDisplayed({ timeout: 35_000 });
  965. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 1, {
  966. timeout: 35_000,
  967. });
  968. expect(await byId("cloud-content-dialog").isExisting()).toBe(false);
  969. expect(await byId("coding-plan-embedded-webview").isDisplayed()).toBe(true);
  970. expect((await ledger()).events[baseline]).toEqual({
  971. campaign_id: currentActionCampaignId,
  972. action_type: "confirm",
  973. });
  974. await byId("coding-plan-upgrade-surface").$('button[aria-label="Close"]').click();
  975. await byId("coding-plan-upgrade-surface").waitForExist({ reverse: true });
  976. expect((await ledger()).events.length).toBe(baseline + 1);
  977. });
  978. for (const failure of ["network", "close", "timeout"] as const) {
  979. it(`MTE-15 upgrade ${failure}: restores popup and requires explicit retry`, async () => {
  980. const mode = (mode: string) =>
  981. fetch(`${origin()}/__e2e/coding-plan/webview-mode`, {
  982. method: "POST",
  983. body: JSON.stringify({ mode }),
  984. });
  985. await mode(failure === "network" ? "fail" : "hold");
  986. await deliverAction({ type: "navigate", args: { page: "upgrade" } });
  987. const campaignId = currentActionCampaignId;
  988. const popup = byId("cloud-content-dialog");
  989. const upgrade = byId("coding-plan-upgrade-surface");
  990. try {
  991. await popup.$("button=Run action").click();
  992. if (failure !== "network") {
  993. await upgrade.waitForDisplayed({ timeout: 15_000 });
  994. await browser.waitUntil(async () => {
  995. const state = (await (
  996. await fetch(`${origin()}/__e2e/coding-plan/webview-state`)
  997. ).json()) as { pending: number };
  998. return state.pending === 1;
  999. });
  1000. expect((await ledger()).events).toEqual([]);
  1001. if (failure === "close") await upgrade.$('button[aria-label="Close"]').click();
  1002. }
  1003. // 升级期间原实例被卸载;恢复应重新定位 Popup,导航失败由外层 toast 提示。
  1004. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 35_000 });
  1005. expect(await byId("cloud-content-dialog").getText()).toContain("E2E actions");
  1006. expect(await upgrade.isExisting()).toBe(false);
  1007. expect(await popup.$("button=Run action").isEnabled()).toBe(true);
  1008. expect((await ledger()).events).toEqual([]);
  1009. await mode("ready");
  1010. await browser.executeAsync((done) =>
  1011. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  1012. );
  1013. expect((await ledger()).events).toEqual([]);
  1014. await popup.$("button=Run action").click();
  1015. await upgrade.waitForDisplayed({ timeout: 15_000 });
  1016. await browser.waitUntil(async () => (await ledger()).events.length === 1, {
  1017. timeout: 35_000,
  1018. });
  1019. expect((await ledger()).events).toEqual([
  1020. { campaign_id: campaignId, action_type: "confirm" },
  1021. ]);
  1022. expect(await popup.isExisting()).toBe(false);
  1023. } finally {
  1024. await mode("ready");
  1025. if (await upgrade.isDisplayed()) await upgrade.$('button[aria-label="Close"]').click();
  1026. }
  1027. });
  1028. }
  1029. it("MTC-BUNDLE: loads a cached ZIP banner, syncs theme/data and reports host actions", async () => {
  1030. const baseline = (await ledger()).events.length;
  1031. const downloads = (await ledger()).requests.filter((p) => p.endsWith("hero.zip")).length;
  1032. const response = await fetch(`${origin()}/__e2e/marketing/bundle-banner`, { method: "POST" });
  1033. const { campaignId } = (await response.json()) as { campaignId: string };
  1034. await browser.execute(() => window.dispatchEvent(new Event("online")));
  1035. await byId("marketing-banner").waitForDisplayed({ timeout: 15000 });
  1036. const frame = byId("marketing-banner").$("iframe");
  1037. const leaseUrl = await frame.getAttribute("src");
  1038. if (!leaseUrl) throw new Error("Missing bundle lease URL");
  1039. const assets = await fixtureAssets();
  1040. const cacheRoot = join(getE2EAppDataPaths().appDataDir, "cache", "content-bundles");
  1041. const cacheSnapshot = async () => {
  1042. const files = (await readdir(cacheRoot, { recursive: true })).filter((file) =>
  1043. file.endsWith(join(assets.bundle.sha256, "index.html")),
  1044. );
  1045. expect(files).toHaveLength(1);
  1046. const file = join(cacheRoot, files[0]!);
  1047. const info = await stat(file);
  1048. return {
  1049. path: file,
  1050. mtime: info.mtimeMs,
  1051. size: info.size,
  1052. content: await readFile(file, "utf8"),
  1053. };
  1054. };
  1055. const coldCache = await cacheSnapshot();
  1056. expect(await frame.getAttribute("data-status")).toBe("ready");
  1057. expect(await frame.getAttribute("tabindex")).toBe("-1");
  1058. const geometry = await browser.execute(() => {
  1059. const f = document.querySelector('[data-testid="marketing-banner"] iframe')!;
  1060. const bounds = f.getBoundingClientRect();
  1061. return {
  1062. height: bounds.height,
  1063. background: getComputedStyle(f).backgroundColor,
  1064. pointer: getComputedStyle(f).pointerEvents,
  1065. };
  1066. });
  1067. expect(geometry.height).toBe(94);
  1068. expect(geometry.background).toBe("rgba(0, 0, 0, 0)");
  1069. expect(geometry.pointer).toBe("none");
  1070. const clipping = await browser.execute(() => {
  1071. const button = document.querySelector('[data-testid="marketing-banner"] > button')!;
  1072. const rect = button.getBoundingClientRect();
  1073. const style = getComputedStyle(button);
  1074. return {
  1075. border: style.borderTopWidth,
  1076. radius: style.borderTopLeftRadius,
  1077. overflow: style.overflow,
  1078. cornerHitsButton: document.elementFromPoint(rect.left + 1, rect.top + 1) === button,
  1079. };
  1080. });
  1081. expect(clipping).toEqual({
  1082. border: "1px",
  1083. radius: "12px",
  1084. overflow: "hidden",
  1085. cornerHitsButton: false,
  1086. });
  1087. const original = await browser.execute(() => document.documentElement.className);
  1088. try {
  1089. for (const dark of [true, false]) {
  1090. await browser.execute(
  1091. (dark) => document.documentElement.classList.toggle("dark", dark),
  1092. dark,
  1093. );
  1094. await browser.switchFrame(await frame);
  1095. try {
  1096. await browser.waitUntil(() =>
  1097. browser.execute(
  1098. (dark) => document.documentElement.dataset.theme === (dark ? "dark" : "light"),
  1099. dark,
  1100. ),
  1101. );
  1102. // ready 表示握手完成,票券仍可能在入场翻转;数据校验不依赖可见文本提取。
  1103. const content = await browser.execute(() => document.body.textContent ?? "");
  1104. expect(content).toContain("321");
  1105. expect(
  1106. await browser.execute(() => document.getElementById("plan-name")?.textContent),
  1107. ).toBe("E2E Bundle Banner");
  1108. await browser.waitUntil(
  1109. () =>
  1110. browser.execute(
  1111. () => !document.getElementById("ticket-flip")!.classList.contains("is-entering"),
  1112. ),
  1113. { timeout: 5000 },
  1114. );
  1115. } finally {
  1116. await browser.switchFrame(null);
  1117. }
  1118. }
  1119. } finally {
  1120. await browser.execute((original) => {
  1121. document.documentElement.className = original;
  1122. }, original);
  1123. }
  1124. await browser.saveScreenshot(screenshotPath("marketing-bundle-banner.png"));
  1125. // 宿主隔离了 iframe 指针,必须经真实 postMessage 转交 hover,不能放开点击隔离。
  1126. await browser.switchFrame(await frame);
  1127. await browser.execute(() => {
  1128. window.addEventListener("message", (event) => {
  1129. if (event.source === parent && event.data?.type === "hover") {
  1130. document.body.dataset.hostHovered = String(event.data.hovered);
  1131. }
  1132. });
  1133. });
  1134. await browser.switchFrame(null);
  1135. const expectHover = async (hovered: boolean) => {
  1136. await browser.switchFrame(await frame);
  1137. try {
  1138. await browser.waitUntil(() =>
  1139. browser.execute((value) => document.body.dataset.hostHovered === String(value), hovered),
  1140. );
  1141. } finally {
  1142. await browser.switchFrame(null);
  1143. }
  1144. };
  1145. await browser.action("pointer").move({ x: 8, y: 80, origin: "viewport" }).perform();
  1146. await bannerAction().moveTo();
  1147. await expectHover(true);
  1148. await browser.action("pointer").move({ x: 8, y: 80, origin: "viewport" }).perform();
  1149. await expectHover(false);
  1150. expect((await ledger()).events.length).toBe(baseline);
  1151. await bannerAction().click();
  1152. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 1);
  1153. expect((await ledger()).events[baseline]).toEqual({
  1154. campaign_id: campaignId,
  1155. action_type: "confirm",
  1156. });
  1157. await bannerClose().click();
  1158. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 2);
  1159. expect((await ledger()).events[baseline + 1]).toEqual({
  1160. campaign_id: campaignId,
  1161. action_type: "cancel",
  1162. });
  1163. // release 完成后旧 iframe URL 失效;只观测已分配 lease,不访问任意本机资源。
  1164. await browser.waitUntil(async () => (await fetch(leaseUrl)).status === 404);
  1165. expect((await ledger()).requests.filter((p) => p.endsWith("hero.zip"))).toHaveLength(
  1166. downloads + 1,
  1167. );
  1168. // 冷加载之后重新下发同 SHA;独立 case 自己建立热缓存,不依赖前例领取结果。
  1169. await fetch(`${origin()}/__e2e/marketing/bundle-banner`, { method: "POST" });
  1170. await browser.execute(() => window.dispatchEvent(new Event("online")));
  1171. await byId("marketing-banner").waitForDisplayed({ timeout: 15000 });
  1172. expect(await byId("marketing-banner").$("iframe").getAttribute("data-status")).toBe("ready");
  1173. expect(await cacheSnapshot()).toEqual(coldCache);
  1174. expect((await ledger()).requests.filter((p) => p.endsWith("hero.zip"))).toHaveLength(
  1175. downloads + 1,
  1176. );
  1177. });
  1178. it("MTC-RICH: formats title, description and buttons, then plays a video Banner", async () => {
  1179. const response = await fetch(`${origin()}/__e2e/marketing/rich-delivery`, {
  1180. method: "POST",
  1181. body: JSON.stringify({
  1182. title: { format: "html", content: '<b class="underline">Rich title</b>' },
  1183. description: {
  1184. format: "markdown",
  1185. content: "## Markdown\n\n**Formatted** text\n\n- One\n- Two",
  1186. },
  1187. buttons: [
  1188. { text: { format: "markdown", content: "**Close rich**" }, action: { type: "close" } },
  1189. ],
  1190. }),
  1191. });
  1192. const { campaignId } = (await response.json()) as { campaignId: string };
  1193. await browser.execute(() => window.dispatchEvent(new Event("online")));
  1194. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15000 });
  1195. expect(await byId("cloud-content-dialog").$("h2 b.underline").getText()).toBe("Rich title");
  1196. expect(await byId("cloud-dialog-description").$("strong").getText()).toBe("Formatted");
  1197. expect(await byId("cloud-dialog-description").$$("li").length).toBe(2);
  1198. expect(await byId("cloud-dialog-action").$("strong").getText()).toBe("Close rich");
  1199. const layouts = await browser.execute(() => {
  1200. const root = document.documentElement;
  1201. const original = root.className;
  1202. const dialog = document.querySelector<HTMLElement>('[data-testid="cloud-content-dialog"]')!;
  1203. const width = dialog.style.width;
  1204. try {
  1205. return ["theme-zai-light", "theme-zai-dark"].flatMap((theme) => {
  1206. root.classList.remove("theme-zai-light", "theme-zai-dark");
  1207. root.classList.add(theme);
  1208. root.classList.toggle("dark", theme === "theme-zai-dark");
  1209. return [358, 480].map((size) => {
  1210. dialog.style.width = `${size}px`;
  1211. const button = dialog.querySelector('[data-testid="cloud-dialog-action"]')!;
  1212. return {
  1213. overflow: dialog.scrollWidth > dialog.clientWidth,
  1214. inherited:
  1215. getComputedStyle(button).color ===
  1216. getComputedStyle(button.querySelector("strong")!).color,
  1217. };
  1218. });
  1219. });
  1220. } finally {
  1221. root.className = original;
  1222. dialog.style.width = width;
  1223. }
  1224. });
  1225. expect(layouts).toEqual(
  1226. Array.from({ length: 4 }, () => ({ overflow: false, inherited: true })),
  1227. );
  1228. await byId("cloud-dialog-action").$("strong").click();
  1229. await browser.waitUntil(async () =>
  1230. (await ledger()).events.some(
  1231. (e) => e.campaign_id === campaignId && e.action_type === "cancel",
  1232. ),
  1233. );
  1234. // 素材契约只接受 MP4;在 Electron 内生成,不能用 WebM 绕过宿主格式校验。
  1235. const video = await browser.executeAsync((done: (value: string) => void) => {
  1236. const canvas = document.createElement("canvas");
  1237. canvas.width = 32;
  1238. canvas.height = 32;
  1239. const context = canvas.getContext("2d")!;
  1240. context.fillRect(0, 0, 32, 32);
  1241. const stream = canvas.captureStream(10);
  1242. const recorder = new MediaRecorder(stream, { mimeType: "video/mp4" });
  1243. const chunks: Blob[] = [];
  1244. // 静态画布只产一帧,MP4 时长可能为零;持续绘制以验证真正的循环播放。
  1245. let frame = 0;
  1246. const draw = setInterval(() => {
  1247. context.fillStyle = `rgb(${++frame % 255}, 0, 0)`;
  1248. context.fillRect(0, 0, 32, 32);
  1249. }, 50);
  1250. recorder.ondataavailable = (event) => chunks.push(event.data);
  1251. recorder.onstop = () => {
  1252. clearInterval(draw);
  1253. stream.getTracks().forEach((track) => track.stop());
  1254. const reader = new FileReader();
  1255. reader.onload = () => done(String(reader.result).split(",")[1]!);
  1256. reader.readAsDataURL(new Blob(chunks, { type: "video/mp4" }));
  1257. };
  1258. recorder.start();
  1259. setTimeout(() => recorder.stop(), 500);
  1260. });
  1261. const delivered = await fetch(`${origin()}/__e2e/marketing/video-banner`, {
  1262. method: "POST",
  1263. body: JSON.stringify({ video }),
  1264. });
  1265. const bannerId = ((await delivered.json()) as { campaignId: string }).campaignId;
  1266. await browser.execute(() => window.dispatchEvent(new Event("online")));
  1267. await byId("marketing-banner").$("video").waitForExist({ timeout: 15000 });
  1268. try {
  1269. await browser.waitUntil(async () =>
  1270. browser.execute(() => {
  1271. const video = document.querySelector<HTMLVideoElement>(
  1272. '[data-testid="marketing-banner"] video',
  1273. );
  1274. return Boolean(video && video.readyState >= 2 && !video.paused);
  1275. }),
  1276. );
  1277. } catch (error) {
  1278. const state = await browser.execute(() => {
  1279. const video = document.querySelector<HTMLVideoElement>(
  1280. '[data-testid="marketing-banner"] video',
  1281. );
  1282. return {
  1283. ready: video?.readyState,
  1284. paused: video?.paused,
  1285. duration: video?.duration,
  1286. time: video?.currentTime,
  1287. error: video?.error?.message,
  1288. visibility: document.visibilityState,
  1289. reduced: matchMedia("(prefers-reduced-motion: reduce)").matches,
  1290. };
  1291. });
  1292. throw new Error(`Video runtime ${JSON.stringify(state)}`, { cause: error });
  1293. }
  1294. const media = await browser.execute(() => {
  1295. const video = document.querySelector<HTMLVideoElement>(
  1296. '[data-testid="marketing-banner"] video',
  1297. )!;
  1298. return {
  1299. controls: video.controls,
  1300. muted: video.muted,
  1301. loop: video.loop,
  1302. height: video.closest("button")!.getBoundingClientRect().height,
  1303. };
  1304. });
  1305. expect(media).toEqual({ controls: false, muted: true, loop: true, height: 96 });
  1306. const rendererUrl = await browser.getUrl();
  1307. const puppeteer = await browser.getPuppeteer();
  1308. const page = (await puppeteer.pages()).find((candidate) => candidate.url() === rendererUrl);
  1309. if (!page) throw new Error("Marketing renderer page is missing for media emulation");
  1310. const videoNode = await byId("marketing-banner").$("video");
  1311. const eventsBeforeMotion = (await ledger()).events;
  1312. try {
  1313. for (const reduced of [true, false]) {
  1314. await page.emulateMediaFeatures([
  1315. { name: "prefers-reduced-motion", value: reduced ? "reduce" : "no-preference" },
  1316. ]);
  1317. await browser.waitUntil(async () =>
  1318. browser.execute((reduced) => {
  1319. const video = document.querySelector<HTMLVideoElement>(
  1320. '[data-testid="marketing-banner"] video',
  1321. );
  1322. return (
  1323. matchMedia("(prefers-reduced-motion: reduce)").matches === reduced &&
  1324. video?.paused === reduced &&
  1325. video.autoplay === !reduced
  1326. );
  1327. }, reduced),
  1328. );
  1329. expect((await byId("marketing-banner").$("video")).elementId).toBe(videoNode.elementId);
  1330. expect((await ledger()).events).toEqual(eventsBeforeMotion);
  1331. }
  1332. } finally {
  1333. await page.emulateMediaFeatures([]);
  1334. }
  1335. await byId("marketing-banner").$('button[aria-label="Copy video"]').click();
  1336. await browser.waitUntil(async () =>
  1337. (await ledger()).events.some(
  1338. (e) => e.campaign_id === bannerId && e.action_type === "confirm",
  1339. ),
  1340. );
  1341. });
  1342. it("MTC-HTML: server classes and inline styles render across themes and narrow layout", async () => {
  1343. const baseline = (await ledger()).events.length;
  1344. const response = await fetch(`${origin()}/__e2e/marketing/html-delivery`, {
  1345. method: "POST",
  1346. body: JSON.stringify(
  1347. '<p class="text-center text-ui-base/relaxed text-foreground-subtle remote-unknown" style="margin-top:8px;position:fixed"><b class="font-semibold text-foreground">GLM-5.3-Flash</b> 将于 <span class="whitespace-nowrap font-semibold text-foreground underline decoration-foreground-subtle decoration-dashed underline-offset-4">2026年9月12日 00:00</span> 生效。</p><p class="font-semibold" style="font-weight:400;color:var(--color-foreground);line-height:1.5">Inline style</p>',
  1348. ),
  1349. });
  1350. const { campaignId } = (await response.json()) as { campaignId: string };
  1351. await browser.execute(() => window.dispatchEvent(new Event("online")));
  1352. await byId("cloud-content-dialog").waitForDisplayed({ timeout: 15000 });
  1353. const originalClass = await browser.execute(() => document.documentElement.className);
  1354. try {
  1355. for (const theme of ["theme-zai-light", "theme-zai-dark"]) {
  1356. const result = await browser.execute((theme) => {
  1357. document.documentElement.classList.remove("theme-zai-light", "theme-zai-dark");
  1358. document.documentElement.classList.add(theme);
  1359. const description = document.querySelector('[data-testid="cloud-dialog-description"]')!;
  1360. const p = description.querySelector("p")!;
  1361. const date = p.querySelector("span")!;
  1362. const inline = description.querySelectorAll("p")[1]!;
  1363. const button = Array.from(
  1364. document.querySelectorAll<HTMLButtonElement>(
  1365. '[data-testid="cloud-content-dialog"] button',
  1366. ),
  1367. ).find((button) => button.textContent === "Close campaign")!;
  1368. const s = getComputedStyle(date);
  1369. return {
  1370. unknown: p.classList.contains("remote-unknown"),
  1371. margin: getComputedStyle(p).marginTop,
  1372. position: p.style.position,
  1373. weight: s.fontWeight,
  1374. whitespace: s.whiteSpace,
  1375. decoration: s.textDecorationStyle,
  1376. line: s.textDecorationLine,
  1377. offset: s.textUnderlineOffset,
  1378. color: s.color,
  1379. modelColor: getComputedStyle(p.querySelector("b")!).color,
  1380. inlineWeight: getComputedStyle(inline).fontWeight,
  1381. buttonVariant: button.dataset.variant,
  1382. buttonRounded: button.classList.contains("rounded-lg"),
  1383. buttonWeight: getComputedStyle(button).fontWeight,
  1384. buttonPosition: button.style.position,
  1385. };
  1386. }, theme);
  1387. expect(result).toMatchObject({
  1388. unknown: true,
  1389. margin: "8px",
  1390. position: "",
  1391. weight: "600",
  1392. whitespace: "nowrap",
  1393. decoration: "dashed",
  1394. line: "underline",
  1395. offset: "4px",
  1396. inlineWeight: "400",
  1397. buttonVariant: "outline",
  1398. buttonRounded: true,
  1399. buttonWeight: "400",
  1400. buttonPosition: "",
  1401. });
  1402. expect(result.color).toBe(result.modelColor);
  1403. }
  1404. // 约束为手机宽度的内容区,检查不换行日期仍可容纳;不冒充手机实机。
  1405. await browser.execute(() => {
  1406. const dialog = document.querySelector(
  1407. '[data-testid="cloud-content-dialog"]',
  1408. ) as HTMLElement;
  1409. dialog.style.width = "358px";
  1410. });
  1411. await browser.waitUntil(
  1412. async () =>
  1413. browser.execute(() => {
  1414. const dialog = document.querySelector(
  1415. '[data-testid="cloud-content-dialog"]',
  1416. ) as HTMLElement;
  1417. return (
  1418. Math.abs(dialog.getBoundingClientRect().width - 358) < 1 &&
  1419. dialog.scrollWidth <= dialog.clientWidth
  1420. );
  1421. }),
  1422. { timeout: 3000, timeoutMsg: "窄屏布局未收敛或存在横向溢出" },
  1423. );
  1424. await browser.saveScreenshot(screenshotPath("marketing-html-styles.png"));
  1425. } finally {
  1426. await browser.execute((value) => {
  1427. document.documentElement.className = value;
  1428. }, originalClass);
  1429. }
  1430. expect((await ledger()).events.length).toBe(baseline);
  1431. await byId("cloud-content-dialog").$("button=Close campaign").click();
  1432. await browser.waitUntil(async () => (await ledger()).events.length === baseline + 1);
  1433. expect((await ledger()).events[baseline]).toEqual({
  1434. campaign_id: campaignId,
  1435. action_type: "cancel",
  1436. });
  1437. });
  1438. });