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

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