marketing-touch-delivery.test.ts 68 KB

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