coding-plan-upgrade-webview.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import type { CodingPlanUpgradeMockRequest } from "./coding-plan-upgrade-mock-server.js";
  2. import { assertOverlayWindowControls } from "./overlay-window-controls.js";
  3. const TID_CODING_PLAN_EMBEDDED_WEBVIEW = "coding-plan-embedded-webview";
  4. interface CodingPlanWebviewSnapshot {
  5. body: string;
  6. readyState: string;
  7. title: string;
  8. url: string;
  9. }
  10. export async function waitForCodingPlanWebviewDisplayed() {
  11. await browser.waitUntil(
  12. async () =>
  13. (await browser.execute((testIdValue) => {
  14. const isVisible = (element: HTMLElement) => {
  15. const style = window.getComputedStyle(element);
  16. if (style.display === "none" || style.visibility === "hidden") {
  17. return false;
  18. }
  19. const rect = element.getBoundingClientRect();
  20. return rect.width > 0 && rect.height > 0;
  21. };
  22. return Array.from(
  23. document.querySelectorAll<HTMLElement>(`[data-testid="${testIdValue}"]`),
  24. ).some(isVisible);
  25. }, TID_CODING_PLAN_EMBEDDED_WEBVIEW)) === true,
  26. {
  27. timeout: 30000,
  28. timeoutMsg: "升级弹窗没有显示 Coding Plan embedded webview",
  29. },
  30. );
  31. await assertOverlayWindowControls('[data-testid="coding-plan-upgrade-surface"]');
  32. }
  33. export async function waitForCodingPlanWebviewBodyTextIncludes(expectedTexts: readonly string[]) {
  34. let latestSnapshot: CodingPlanWebviewSnapshot = {
  35. body: "",
  36. readyState: "unknown",
  37. title: "",
  38. url: "",
  39. };
  40. await browser.waitUntil(
  41. async () => {
  42. const webContentsId = await readCodingPlanWebviewContentsId();
  43. latestSnapshot = (await browser.electron.execute((electron, id) => {
  44. const guest = electron.webContents.fromId(id);
  45. if (!guest || guest.isDestroyed()) {
  46. return {
  47. body: "",
  48. readyState: "destroyed",
  49. title: "",
  50. url: "",
  51. };
  52. }
  53. return guest.executeJavaScript(
  54. `({
  55. body: document.body?.innerText ?? "",
  56. readyState: document.readyState,
  57. title: document.title,
  58. url: window.location.href
  59. })`,
  60. true,
  61. );
  62. }, webContentsId)) as unknown as CodingPlanWebviewSnapshot;
  63. return expectedTexts.some((text) => latestSnapshot.body.includes(text));
  64. },
  65. {
  66. timeout: 30000,
  67. timeoutMsg: `Coding Plan webview 没有显示预期文案: ${expectedTexts.join(" / ")},url=${latestSnapshot.url},readyState=${latestSnapshot.readyState},title=${latestSnapshot.title},当前内容: ${latestSnapshot.body}`,
  68. },
  69. );
  70. }
  71. export async function readCodingPlanWebviewLocalStorage(
  72. keys: readonly string[],
  73. ): Promise<Record<string, string | null>> {
  74. await waitForCodingPlanWebviewDisplayed();
  75. const webContentsId = await readCodingPlanWebviewContentsId();
  76. return (await browser.electron.execute(
  77. async (electron, id, storageKeys) => {
  78. const guest = electron.webContents.fromId(id);
  79. if (!guest || guest.isDestroyed()) {
  80. throw new Error("Coding Plan webview is not available");
  81. }
  82. return guest.executeJavaScript(
  83. `(() => {
  84. const keys = ${JSON.stringify(storageKeys)};
  85. return Object.fromEntries(keys.map((key) => [
  86. key,
  87. window.localStorage.getItem(key)
  88. ]));
  89. })()`,
  90. true,
  91. );
  92. },
  93. webContentsId,
  94. keys,
  95. )) as Record<string, string | null>;
  96. }
  97. export async function waitForCodingPlanWebviewClosed() {
  98. await browser.waitUntil(
  99. async () =>
  100. (await browser.execute((testIdValue) => {
  101. const isVisible = (element: HTMLElement) => {
  102. const style = window.getComputedStyle(element);
  103. if (style.display === "none" || style.visibility === "hidden") {
  104. return false;
  105. }
  106. const rect = element.getBoundingClientRect();
  107. return rect.width > 0 && rect.height > 0;
  108. };
  109. return !Array.from(
  110. document.querySelectorAll<HTMLElement>(`[data-testid="${testIdValue}"]`),
  111. ).some(isVisible);
  112. }, TID_CODING_PLAN_EMBEDDED_WEBVIEW)) === true,
  113. {
  114. timeout: 15000,
  115. timeoutMsg: "购买完成后 Coding Plan embedded webview 没有关闭",
  116. },
  117. );
  118. }
  119. export async function triggerCodingPlanWebviewPurchaseComplete(provider: "bigmodel" | "zai") {
  120. await waitForCodingPlanWebviewDisplayed();
  121. await markCodingPlanUpgradeMockPurchaseComplete(readCodingPlanUpgradeMockControlBaseUrl());
  122. const webContentsId = await readCodingPlanWebviewContentsId();
  123. let result: {
  124. body?: string;
  125. ok: boolean;
  126. readyState?: string;
  127. reason?: string;
  128. title?: string;
  129. url?: string;
  130. } = {
  131. ok: false,
  132. reason: "not-started",
  133. };
  134. try {
  135. await browser.waitUntil(
  136. async () => {
  137. result = (await browser.electron.execute(
  138. async (electron, id, expectedProvider) => {
  139. const guest = electron.webContents.fromId(id);
  140. if (!guest) {
  141. return { ok: false, reason: "webview-missing" };
  142. }
  143. try {
  144. return await guest.executeJavaScript(
  145. `(() => {
  146. const expectedProvider = ${JSON.stringify(expectedProvider)};
  147. const body = document.body?.innerText?.slice(0, 500) ?? "";
  148. const readyState = document.readyState;
  149. const title = document.title;
  150. const url = window.location.href;
  151. if (expectedProvider !== "zai" && expectedProvider !== "bigmodel") {
  152. return { ok: false, reason: "invalid-provider", body, readyState, title, url };
  153. }
  154. const bridge = window.zcodeBridge;
  155. if (!bridge || typeof bridge.notifyPurchaseComplete !== "function") {
  156. return { ok: false, reason: "bridge-missing", body, readyState, title, url };
  157. }
  158. // E2E 触发必须先把 ok 返回给 WebDriver,再异步发购买完成消息;
  159. // 否则 App 同步关闭 webview 时 guest 被销毁,executeJavaScript 可能拿不到返回值。
  160. setTimeout(() => {
  161. bridge.notifyPurchaseComplete({
  162. provider: expectedProvider,
  163. timestamp: Date.now()
  164. });
  165. }, 0);
  166. return { ok: true };
  167. })()`,
  168. true,
  169. );
  170. } catch (error) {
  171. return {
  172. ok: false,
  173. reason: error instanceof Error ? error.message : String(error),
  174. };
  175. }
  176. },
  177. webContentsId,
  178. provider,
  179. )) as { ok: boolean; reason?: string; body?: string };
  180. return result.ok;
  181. },
  182. {
  183. timeout: 30000,
  184. timeoutMsg: "触发 Coding Plan webview 购买完成失败",
  185. },
  186. );
  187. } catch (error) {
  188. throw new Error(
  189. [
  190. `触发 Coding Plan webview 购买完成失败: ${result.reason ?? "unknown"}`,
  191. result.url ? `url=${result.url}` : "",
  192. result.readyState ? `readyState=${result.readyState}` : "",
  193. result.title ? `title=${result.title}` : "",
  194. result.body ? `当前内容: ${result.body}` : "",
  195. ]
  196. .filter(Boolean)
  197. .join(","),
  198. { cause: error },
  199. );
  200. }
  201. if (!result.ok) {
  202. throw new Error(`触发 Coding Plan webview 购买完成失败: ${result.reason ?? "unknown"}`);
  203. }
  204. }
  205. export async function waitForCodingPlanUpgradeMockRequest(
  206. predicate: (request: CodingPlanUpgradeMockRequest) => boolean,
  207. timeoutMsg: string,
  208. ) {
  209. let latestRequests: CodingPlanUpgradeMockRequest[] = [];
  210. let latestBaseUrls: string[] = [];
  211. const deadline = Date.now() + 30000;
  212. while (Date.now() < deadline) {
  213. const result = await readCodingPlanUpgradeMockRequests();
  214. latestRequests = result.requests;
  215. latestBaseUrls = result.baseUrls;
  216. if (latestRequests.some(predicate)) {
  217. return;
  218. }
  219. await browser.pause(250);
  220. }
  221. throw new Error(
  222. `${timeoutMsg},mock=${latestBaseUrls.join(" / ")},当前请求: ${latestRequests
  223. .map(formatCodingPlanUpgradeMockRequestForError)
  224. .join(" / ")}`,
  225. );
  226. }
  227. function formatCodingPlanUpgradeMockRequestForError(request: CodingPlanUpgradeMockRequest): string {
  228. const authorization = request.headers.authorization;
  229. const authState =
  230. authorization === undefined
  231. ? "auth=missing"
  232. : authorization.startsWith("Bearer ")
  233. ? "auth=bearer"
  234. : authorization.length > 0
  235. ? "auth=raw"
  236. : "auth=empty";
  237. return `${request.method} ${request.path} (${authState})`;
  238. }
  239. async function readCodingPlanWebviewContentsId(): Promise<number> {
  240. const rendererWebview = (await browser.execute((testIdValue) => {
  241. const isVisible = (element: HTMLElement) => {
  242. const style = window.getComputedStyle(element);
  243. if (style.display === "none" || style.visibility === "hidden") {
  244. return false;
  245. }
  246. const rect = element.getBoundingClientRect();
  247. return rect.width > 0 && rect.height > 0;
  248. };
  249. const webviews = Array.from(
  250. document.querySelectorAll<HTMLElement>(`[data-testid="${testIdValue}"]`),
  251. ) as Array<HTMLElement & { getWebContentsId?: () => number }>;
  252. // 修复原因:升级弹层可能和背景设置页共存,WDIO 默认取第一个会命中隐藏 webview。
  253. const webview = webviews.findLast(isVisible) ?? webviews.at(-1) ?? null;
  254. return {
  255. id: webview?.getWebContentsId?.() ?? 0,
  256. src: webview?.getAttribute("src") ?? "",
  257. };
  258. }, TID_CODING_PLAN_EMBEDDED_WEBVIEW)) as { id: number; src: string };
  259. const webContentsId = (await browser.electron.execute(
  260. (electron, candidateId, expectedSrc) => {
  261. const isCodingPlanUrl = (value: string | undefined) => {
  262. if (!value) return false;
  263. try {
  264. const url = new URL(value);
  265. return url.pathname.includes("coding-plan");
  266. } catch {
  267. return false;
  268. }
  269. };
  270. const candidate = electron.webContents.fromId(candidateId);
  271. if (candidate && !candidate.isDestroyed() && isCodingPlanUrl(candidate.getURL())) {
  272. return candidateId;
  273. }
  274. const matched = electron.webContents
  275. .getAllWebContents()
  276. .find(
  277. (contents) =>
  278. !contents.isDestroyed() &&
  279. (isCodingPlanUrl(contents.getURL()) || contents.getURL() === expectedSrc),
  280. );
  281. return matched?.id ?? candidateId;
  282. },
  283. rendererWebview.id,
  284. rendererWebview.src,
  285. )) as number;
  286. if (!webContentsId) {
  287. throw new Error("没有读取到 Coding Plan webview 的 webContentsId");
  288. }
  289. return webContentsId;
  290. }
  291. export async function readCodingPlanUpgradeMockRequests(): Promise<{
  292. baseUrls: string[];
  293. requests: CodingPlanUpgradeMockRequest[];
  294. }> {
  295. const baseUrls = readCodingPlanUpgradeMockBaseUrlCandidates();
  296. const requestGroups = await Promise.all(
  297. baseUrls.map(async (baseUrl) => {
  298. try {
  299. const response = await fetch(`${baseUrl}/__e2e/coding-plan/requests`);
  300. const payload = (await response.json()) as {
  301. requests?: CodingPlanUpgradeMockRequest[];
  302. };
  303. return Array.isArray(payload.requests) ? payload.requests : [];
  304. } catch {
  305. return [];
  306. }
  307. }),
  308. );
  309. return {
  310. baseUrls,
  311. requests: requestGroups.flat(),
  312. };
  313. }
  314. function readCodingPlanUpgradeMockBaseUrlCandidates(): string[] {
  315. const baseUrls = [
  316. process.env.ZCODE_CODING_PLAN_UPGRADE_MOCK_BASE_URL,
  317. process.env.ZCODE_E2E_CODING_PLAN_MOCK_URL,
  318. process.env.BIGMODEL_TEST_API_BASE_URL,
  319. process.env.BIGMODEL_API_BASE_URL,
  320. process.env.ZAI_BUSINESS_BASE_URL,
  321. process.env.ZCODE_ENDPOINT_ORIGIN,
  322. ].flatMap((item) => {
  323. const value = item?.trim();
  324. return value ? [value] : [];
  325. });
  326. const uniqueBaseUrls = Array.from(new Set(baseUrls));
  327. if (uniqueBaseUrls.length === 0) {
  328. throw new Error("Coding Plan upgrade mock baseUrl 未配置");
  329. }
  330. return uniqueBaseUrls;
  331. }
  332. function readCodingPlanUpgradeMockControlBaseUrl(): string {
  333. const baseUrl = process.env.ZCODE_CODING_PLAN_UPGRADE_MOCK_BASE_URL?.trim();
  334. if (!baseUrl) {
  335. throw new Error("Coding Plan upgrade mock control baseUrl 未配置");
  336. }
  337. return baseUrl;
  338. }
  339. async function markCodingPlanUpgradeMockPurchaseComplete(baseUrl: string) {
  340. const response = await fetch(`${baseUrl}/__e2e/coding-plan/purchase-complete`, {
  341. method: "POST",
  342. });
  343. if (!response.ok) {
  344. throw new Error(`Coding Plan upgrade mock 标记购买完成失败: ${baseUrl}`);
  345. }
  346. }