coding-plan-upgrade-webview-refresh-provider.test.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import { BUILTIN_MODEL_PROVIDER_IDS, TID_LOGIN_TRIGGER } from "@zcode/shared";
  2. import {
  3. clearAppData,
  4. DEFAULT_WORKSPACE,
  5. readModelProvider,
  6. seedCredentials,
  7. seedSettings,
  8. waitForWorkspaceApp,
  9. } from "./helpers/desktop-app.js";
  10. import {
  11. openBigModelCodingPlanPersonalUpgradePanel,
  12. openZaiCodingPlanPersonalUpgradePanel,
  13. } from "./helpers/coding-plan-upgrade.js";
  14. import {
  15. readCodingPlanWebviewLocalStorage,
  16. triggerCodingPlanWebviewPurchaseComplete,
  17. waitForCodingPlanUpgradeMockRequest,
  18. waitForCodingPlanWebviewClosed,
  19. waitForCodingPlanWebviewDisplayed,
  20. } from "./helpers/coding-plan-upgrade-webview.js";
  21. describe("BigModel Coding Plan 官网 webview 支付完成 E2E", () => {
  22. afterEach(async () => {
  23. await browser.electron.restoreAllMocks();
  24. await clearAppData();
  25. });
  26. it("CPUW-01: webview 通知 App 关闭升级弹窗并刷新当前 provider", async function () {
  27. this.timeout(120000);
  28. const setInventoryMode = async (mode: "hold" | "fail" | "ready") => {
  29. const base =
  30. process.env.ZCODE_CODING_PLAN_UPGRADE_MOCK_BASE_URL ??
  31. process.env.BIGMODEL_TEST_API_BASE_URL;
  32. if (!base) throw new Error("Missing mock URL");
  33. const response = await fetch(`${base}/__e2e/coding-plan/inventory-mode`, {
  34. method: "POST",
  35. headers: { "content-type": "application/json" },
  36. body: JSON.stringify({ mode }),
  37. });
  38. expect(response.ok).toBe(true);
  39. };
  40. await setInventoryMode("hold");
  41. await browser.refresh();
  42. const telemetryFetch = await browser.electron.mock("net", "fetch");
  43. await telemetryFetch.mockResolvedValue({ ok: true, status: 204 });
  44. await openBigModelCodingPlanPersonalUpgradePanel(async () => {
  45. const entry = () => $('[data-testid="sidebar-coding-plan-upgrade-button"]');
  46. await browser.waitUntil(async () => (await entry().getAttribute("data-disabled")) !== null, {
  47. timeout: 10000,
  48. });
  49. // 测试窗口沿用当前语言;英文专用断言会把正确的中文 loading/error 误判为业务失败。
  50. expect(await entry().getText()).toMatch(/Loading plans|正在查询套餐/);
  51. expect(await $('[data-testid="coding-plan-embedded-webview"]').isExisting()).toBe(false);
  52. await setInventoryMode("fail");
  53. await browser.waitUntil(
  54. async () => {
  55. if (!(await entry().isExisting()))
  56. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  57. return /Retry|重试/.test(await entry().getText());
  58. },
  59. {
  60. timeout: 15000,
  61. },
  62. );
  63. await telemetryFetch.update();
  64. expect(
  65. telemetryFetch.mock.calls.filter(([, init]) =>
  66. String((init as { body?: string })?.body).includes("coding_plan_upgrade_ck"),
  67. ),
  68. ).toHaveLength(0);
  69. await setInventoryMode("ready");
  70. await entry().click();
  71. expect(await $('[data-testid="coding-plan-embedded-webview"]').isExisting()).toBe(false);
  72. await browser.waitUntil(
  73. async () => {
  74. if (!(await entry().isExisting()))
  75. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  76. const label = await entry().getText();
  77. return !/Retry|重试|Loading plans|正在查询套餐/.test(label);
  78. },
  79. { timeout: 15000 },
  80. );
  81. await telemetryFetch.update();
  82. expect(
  83. telemetryFetch.mock.calls.filter(([, init]) =>
  84. String((init as { body?: string })?.body).includes("coding_plan_upgrade_ck"),
  85. ),
  86. ).toHaveLength(0);
  87. });
  88. await waitForCodingPlanWebviewDisplayed();
  89. const readEntryEvents = async () => {
  90. await telemetryFetch.update();
  91. return telemetryFetch.mock.calls.flatMap(([url, init]) => {
  92. if (!String(url).includes("/event/report")) return [];
  93. const body = (init as { body?: string } | undefined)?.body;
  94. if (!body) return [];
  95. const event = JSON.parse(body) as {
  96. element_name: string;
  97. event_extra_detail: Record<string, string>;
  98. };
  99. return event.element_name === "coding_plan_upgrade_ck" ? [event] : [];
  100. });
  101. };
  102. await browser.waitUntil(async () => (await readEntryEvents()).length === 1, {
  103. timeout: 10000,
  104. timeoutMsg: "购买入口没有通过 App net.fetch 上报一次",
  105. });
  106. const [entry] = await readEntryEvents();
  107. if (!entry) throw new Error("App 入口事件不存在");
  108. expect(entry.event_extra_detail.purchase_funnel_id).toBeTruthy();
  109. expect(entry.event_extra_detail.entry_plan_list).toBe(
  110. "coding_plan__personal_pro,start_plan__zcode_v3_start_plan",
  111. );
  112. await browser.waitUntil(
  113. async () => {
  114. const storage = await readCodingPlanWebviewLocalStorage([
  115. "zcode:coding-plan:report-context",
  116. ]);
  117. const context = JSON.parse(storage["zcode:coding-plan:report-context"] || "{}");
  118. return (
  119. context.purchase_funnel_id === entry.event_extra_detail.purchase_funnel_id &&
  120. context.purchase_entry_reporter === "app" &&
  121. (context.entry_plan_list ?? "") === entry.event_extra_detail.entry_plan_list
  122. );
  123. },
  124. { timeout: 10000, timeoutMsg: "App 上报字段与 WebView 注入上下文不一致" },
  125. );
  126. await browser.electron.execute((electron) => {
  127. const guest = electron.webContents
  128. .getAllWebContents()
  129. .find(
  130. (contents) =>
  131. contents.getType() === "webview" && contents.getURL().includes("coding-plan"),
  132. );
  133. if (!guest) throw new Error("购买 WebView 不存在");
  134. return new Promise<void>((resolve) => {
  135. guest.once("did-finish-load", () => resolve());
  136. guest.reload();
  137. });
  138. });
  139. await browser.waitUntil(
  140. async () => {
  141. const storage = await readCodingPlanWebviewLocalStorage([
  142. "zcode:coding-plan:report-context",
  143. ]);
  144. const context = JSON.parse(storage["zcode:coding-plan:report-context"] || "{}");
  145. return (
  146. context.purchase_entry_reporter === "app" &&
  147. context.purchase_funnel_id === entry.event_extra_detail.purchase_funnel_id
  148. );
  149. },
  150. { timeout: 10000 },
  151. );
  152. expect(await readEntryEvents()).toHaveLength(1);
  153. await triggerCodingPlanWebviewPurchaseComplete("bigmodel");
  154. await waitForCodingPlanWebviewClosed();
  155. await waitForCodingPlanUpgradeMockRequest(
  156. (request) => request.path.endsWith("/api/biz/customer/getCustomerInfo"),
  157. "购买完成后没有刷新 customerInfo",
  158. );
  159. await waitForCodingPlanUpgradeMockRequest(
  160. (request) =>
  161. request.path.includes("/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys") &&
  162. !request.path.includes("/copy/"),
  163. "购买完成后没有读取或创建 BigModel API key",
  164. );
  165. await waitForCodingPlanUpgradeMockRequest(
  166. (request) =>
  167. request.path.endsWith(
  168. "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys/copy/bigmodel-webview-refreshed-key",
  169. ),
  170. "购买完成后没有复制 BigModel API key secret",
  171. );
  172. await waitForCodingPlanUpgradeMockRequest(
  173. (request) => request.path.endsWith("/api/biz/subscription/list"),
  174. "购买完成后没有校验 subscription/list",
  175. );
  176. // Account 凭据属于 Credential Store,不恢复旧 Provider Store 的 apiKey 持久化断言。
  177. expect(
  178. (await readModelProvider(BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan))?.apiKey ??
  179. "",
  180. ).toBe("");
  181. });
  182. it("CPUW-03: Z.ai webview 通知 App 关闭升级弹窗并刷新当前 provider 与 Team Plan products", async function () {
  183. this.timeout(120000);
  184. await prepareZaiCodingPlanUpgradeState();
  185. await openZaiCodingPlanPersonalUpgradePanel();
  186. await waitForCodingPlanWebviewDisplayed();
  187. await waitForZaiWebviewCredentialsInjected();
  188. await triggerCodingPlanWebviewPurchaseComplete("zai");
  189. await waitForCodingPlanWebviewClosed();
  190. await waitForCodingPlanUpgradeMockRequest(
  191. (request) =>
  192. request.path.endsWith("/api/biz/customer/getCustomerInfo") &&
  193. request.headers.authorization === "Bearer zai-webview-oauth-token",
  194. "购买完成后没有按 Z.ai token 刷新 customerInfo",
  195. );
  196. await waitForCodingPlanUpgradeMockRequest(
  197. (request) =>
  198. request.path.endsWith("/api/biz/subscription/enterprise/v2/pricing") &&
  199. request.headers.authorization === "zai-webview-oauth-token",
  200. "购买完成后没有刷新 Z.ai enterprise pricing",
  201. );
  202. // Account 凭据属于 Credential Store,不恢复旧 Provider Store 的 apiKey 持久化断言。
  203. expect(
  204. (await readModelProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan))?.apiKey ?? "",
  205. ).toBe("");
  206. });
  207. });
  208. async function prepareZaiCodingPlanUpgradeState() {
  209. await clearAppData();
  210. await seedCredentials("zai-webview-oauth-token");
  211. await seedSettings({
  212. providerFamilyConnectionSelections: {
  213. zai: { kind: "individual-coding-plan" },
  214. bigmodel: { kind: "individual-coding-plan" },
  215. },
  216. providerFamilyDomain: "zai",
  217. providerFamilyDomainMigrated: true,
  218. lastWorkspaceSession: [
  219. {
  220. kind: "local",
  221. workspacePath: DEFAULT_WORKSPACE,
  222. workspacePurpose: "project",
  223. },
  224. ],
  225. lastActiveTabIndex: 0,
  226. });
  227. await browser.reloadSession();
  228. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  229. }
  230. async function waitForZaiWebviewCredentialsInjected() {
  231. let latestStorage: Record<string, string | null> = {};
  232. await browser.waitUntil(
  233. async () => {
  234. latestStorage = await readCodingPlanWebviewLocalStorage([
  235. "oauth:zai:access_token",
  236. "zcodejwttoken",
  237. "oauth:bigmodel:access_token",
  238. ]);
  239. return (
  240. latestStorage["oauth:zai:access_token"] === "zai-webview-oauth-token" &&
  241. latestStorage.zcodejwttoken === "zai-webview-oauth-token" &&
  242. latestStorage["oauth:bigmodel:access_token"] === null
  243. );
  244. },
  245. {
  246. timeout: 30000,
  247. timeoutMsg: `Z.ai credentials 没有注入到 Coding Plan webview localStorage: ${JSON.stringify(latestStorage)}`,
  248. },
  249. );
  250. }