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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  3. import { TID_LOGIN_TRIGGER } from "@zcode/shared/test-ids";
  4. import {
  5. clearAppData,
  6. getE2EAppDataPaths,
  7. DEFAULT_WORKSPACE,
  8. readModelProvider,
  9. seedCredentials,
  10. seedSettings,
  11. waitForWorkspaceApp,
  12. } from "#e2e/helpers/desktop-app";
  13. import {
  14. openBigModelCodingPlanPersonalUpgradePanel,
  15. openZaiCodingPlanPersonalUpgradePanel,
  16. } from "#e2e/helpers/coding-plan-upgrade";
  17. import {
  18. readCodingPlanWebviewLocalStorage,
  19. readCodingPlanUpgradeMockRequests,
  20. triggerCodingPlanWebviewPurchaseComplete,
  21. waitForCodingPlanUpgradeMockRequest,
  22. waitForCodingPlanWebviewClosed,
  23. waitForCodingPlanWebviewDisplayed,
  24. } from "#e2e/helpers/coding-plan-upgrade-webview";
  25. describe("BigModel Coding Plan 官网 webview 支付完成 E2E", () => {
  26. afterEach(async () => {
  27. await browser.electron.restoreAllMocks();
  28. await clearAppData();
  29. });
  30. it("CPUW-01: webview 通知 App 关闭升级弹窗并刷新当前 provider", async function () {
  31. this.timeout(120000);
  32. const setInventoryMode = async (mode: "hold" | "fail" | "ready") => {
  33. const base =
  34. process.env.ZCODE_CODING_PLAN_UPGRADE_MOCK_BASE_URL ??
  35. process.env.BIGMODEL_TEST_API_BASE_URL;
  36. if (!base) throw new Error("Missing mock URL");
  37. const response = await fetch(`${base}/__e2e/coding-plan/inventory-mode`, {
  38. method: "POST",
  39. headers: { "content-type": "application/json" },
  40. body: JSON.stringify({ mode }),
  41. });
  42. expect(response.ok).toBe(true);
  43. };
  44. await setInventoryMode("hold");
  45. await browser.refresh();
  46. const telemetryFetch = await browser.electron.mock("net", "fetch");
  47. await telemetryFetch.mockResolvedValue({ ok: true, status: 204 });
  48. await openBigModelCodingPlanPersonalUpgradePanel(async () => {
  49. const entry = () => $('[data-testid="sidebar-coding-plan-upgrade-button"]');
  50. await browser.waitUntil(async () => (await entry().getAttribute("data-disabled")) !== null, {
  51. timeout: 10000,
  52. });
  53. // 测试窗口沿用当前语言;英文专用断言会把正确的中文 loading/error 误判为业务失败。
  54. expect(await entry().getText()).toMatch(/Loading plans|正在查询套餐/);
  55. expect(await $('[data-testid="coding-plan-embedded-webview"]').isExisting()).toBe(false);
  56. await setInventoryMode("fail");
  57. await browser.waitUntil(
  58. async () => {
  59. if (!(await entry().isExisting()))
  60. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  61. return /Retry|重试/.test(await entry().getText());
  62. },
  63. {
  64. timeout: 15000,
  65. },
  66. );
  67. await telemetryFetch.update();
  68. expect(
  69. telemetryFetch.mock.calls.filter(([, init]) =>
  70. String((init as { body?: string })?.body).includes("coding_plan_upgrade_ck"),
  71. ),
  72. ).toHaveLength(0);
  73. await setInventoryMode("ready");
  74. await entry().click();
  75. expect(await $('[data-testid="coding-plan-embedded-webview"]').isExisting()).toBe(false);
  76. await browser.waitUntil(
  77. async () => {
  78. if (!(await entry().isExisting()))
  79. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  80. const label = await entry().getText();
  81. return !/Retry|重试|Loading plans|正在查询套餐/.test(label);
  82. },
  83. { timeout: 15000 },
  84. );
  85. await telemetryFetch.update();
  86. expect(
  87. telemetryFetch.mock.calls.filter(([, init]) =>
  88. String((init as { body?: string })?.body).includes("coding_plan_upgrade_ck"),
  89. ),
  90. ).toHaveLength(0);
  91. });
  92. await waitForCodingPlanWebviewDisplayed();
  93. const readEntryEvents = async () => {
  94. await telemetryFetch.update();
  95. return telemetryFetch.mock.calls.flatMap(([url, init]) => {
  96. if (!String(url).includes("/event/report")) return [];
  97. const body = (init as { body?: string } | undefined)?.body;
  98. if (!body) return [];
  99. const event = JSON.parse(body) as {
  100. element_name: string;
  101. event_extra_detail: Record<string, string>;
  102. };
  103. return event.element_name === "coding_plan_upgrade_ck" ? [event] : [];
  104. });
  105. };
  106. await browser.waitUntil(async () => (await readEntryEvents()).length === 1, {
  107. timeout: 10000,
  108. timeoutMsg: "购买入口没有通过 App net.fetch 上报一次",
  109. });
  110. const [entry] = await readEntryEvents();
  111. if (!entry) throw new Error("App 入口事件不存在");
  112. expect(entry.event_extra_detail.purchase_funnel_id).toBeTruthy();
  113. expect(entry.event_extra_detail.entry_plan_list).toBe(
  114. "coding_plan__personal_pro,start_plan__zcode_v3_start_plan",
  115. );
  116. await browser.waitUntil(
  117. async () => {
  118. const storage = await readCodingPlanWebviewLocalStorage([
  119. "zcode:coding-plan:report-context",
  120. ]);
  121. const context = JSON.parse(storage["zcode:coding-plan:report-context"] || "{}");
  122. return (
  123. context.purchase_funnel_id === entry.event_extra_detail.purchase_funnel_id &&
  124. context.purchase_entry_reporter === "app" &&
  125. (context.entry_plan_list ?? "") === entry.event_extra_detail.entry_plan_list
  126. );
  127. },
  128. { timeout: 10000, timeoutMsg: "App 上报字段与 WebView 注入上下文不一致" },
  129. );
  130. await browser.electron.execute((electron) => {
  131. const guest = electron.webContents
  132. .getAllWebContents()
  133. .find(
  134. (contents) =>
  135. contents.getType() === "webview" && contents.getURL().includes("coding-plan"),
  136. );
  137. if (!guest) throw new Error("购买 WebView 不存在");
  138. return new Promise<void>((resolve) => {
  139. guest.once("did-finish-load", () => resolve());
  140. guest.reload();
  141. });
  142. });
  143. await browser.waitUntil(
  144. async () => {
  145. const storage = await readCodingPlanWebviewLocalStorage([
  146. "zcode:coding-plan:report-context",
  147. ]);
  148. const context = JSON.parse(storage["zcode:coding-plan:report-context"] || "{}");
  149. return (
  150. context.purchase_entry_reporter === "app" &&
  151. context.purchase_funnel_id === entry.event_extra_detail.purchase_funnel_id
  152. );
  153. },
  154. { timeout: 10000 },
  155. );
  156. expect(await readEntryEvents()).toHaveLength(1);
  157. // 账号已迁到 Key ID 换 PAT;Copy Secret 已删除,有效 PAT 在购买刷新时允许复用。
  158. await waitForCodingPlanUpgradeMockRequest(
  159. (request) =>
  160. request.method === "POST" &&
  161. request.path ===
  162. "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys/bigmodel-personal-api-key/access_tokens" &&
  163. request.headers.authorization === "Bearer e2e-bigmodel-oauth-token",
  164. "账号初始化没有签发 BigModel PAT",
  165. );
  166. await completePurchaseAndWaitForRefresh("bigmodel");
  167. expect(
  168. (await readCodingPlanUpgradeMockRequests()).requests.some((request) =>
  169. request.path.includes("/copy/"),
  170. ),
  171. ).toBe(false);
  172. // PAT 由账号 owner 管理,不落盘到 Personal Provider Config。
  173. expect(
  174. (await readModelProvider(BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan))?.apiKey ??
  175. "",
  176. ).toBe("");
  177. });
  178. it("CPUW-CN: 国内关联账号购买只交接主 JWT,不泄漏上游及关联 token", async function () {
  179. this.timeout(120000);
  180. await seedCredentials("zai-webview-oauth-token");
  181. const { credentialsFile } = getE2EAppDataPaths();
  182. const saved = JSON.parse(await readFile(credentialsFile, "utf8"));
  183. for (const key of Object.keys(saved)) if (key.startsWith("oauth:")) delete saved[key];
  184. Object.assign(saved, {
  185. "oauth:active_provider": "zai_cn",
  186. "oauth:session_revision": "e2e-embedded-cn",
  187. "oauth:zai_cn:access_token": "e2e-cn-upstream-oauth",
  188. "oauth:zai_cn:user_info": JSON.stringify({ user_id: "e2e-cn-user", name: "CN" }),
  189. "oauth:linked_bigmodel": JSON.stringify({
  190. userId: "e2e-cn-user",
  191. customerId: "e2e-user",
  192. accessToken: "e2e-linked-bigmodel-jwt",
  193. }),
  194. zcodejwttoken: "e2e-cn-zcode-jwt",
  195. });
  196. await writeFile(credentialsFile, JSON.stringify(saved), "utf8");
  197. await seedSettings({
  198. providerFamilyDomain: "bigmodel",
  199. providerFamilyDomainMigrated: true,
  200. providerFamilyConnectionSelections: { bigmodel: { kind: "individual-coding-plan" } },
  201. lastWorkspaceSession: [
  202. { kind: "local", workspacePath: DEFAULT_WORKSPACE, workspacePurpose: "project" },
  203. ],
  204. lastActiveTabIndex: 0,
  205. });
  206. await browser.reloadSession();
  207. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  208. await openBigModelCodingPlanPersonalUpgradePanel();
  209. await waitForCodingPlanWebviewDisplayed();
  210. await browser.waitUntil(
  211. async () =>
  212. (await readCodingPlanWebviewLocalStorage(["oauth:active_provider"]))[
  213. "oauth:active_provider"
  214. ] === "zai_cn",
  215. { timeout: 10000 },
  216. );
  217. const storage = await readCodingPlanWebviewLocalStorage([
  218. "zcodejwttoken",
  219. "oauth:zai_cn:access_token",
  220. "oauth:bigmodel:access_token",
  221. "oauth:zai:access_token",
  222. ]);
  223. expect(storage).toEqual({
  224. zcodejwttoken: "e2e-cn-zcode-jwt",
  225. "oauth:zai_cn:access_token": null,
  226. "oauth:bigmodel:access_token": null,
  227. "oauth:zai:access_token": null,
  228. });
  229. // 模拟旧无 revision 的会话在异步读取期间被另一进程升级,旧 JWT 不能注入。
  230. await browser.execute(async (triggerId) => {
  231. const element = document.querySelector(`[data-testid="${triggerId}"]`)!;
  232. let fiber = (element as any)[
  233. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  234. ];
  235. while (fiber) {
  236. const value = fiber.memoizedProps?.value;
  237. const services = value?.oauthService ? value : fiber.memoizedProps?.services;
  238. if (services?.oauthService) {
  239. await services.credentialService.delete("oauth:session_revision");
  240. const original = services.oauthService;
  241. const state: any = ((window as any).__embeddedSessionProbe = {
  242. services,
  243. original,
  244. captured: false,
  245. checked: false,
  246. release: null,
  247. });
  248. services.oauthService = new Proxy(original, {
  249. get(target, key) {
  250. if (key === "getWebsiteSession")
  251. return async () => {
  252. const snapshot = await original.getWebsiteSession();
  253. if (state.captured) return snapshot;
  254. state.captured = true;
  255. state.oldRevision = snapshot.sessionRevision;
  256. await new Promise((resolve) => {
  257. state.release = resolve;
  258. });
  259. return snapshot;
  260. };
  261. if (key === "getAccountAvailability")
  262. return async () => {
  263. const result = await original.getAccountAvailability();
  264. state.checked = true;
  265. return result;
  266. };
  267. return Reflect.get(target, key);
  268. },
  269. });
  270. (window as any).__testActions.setTheme(
  271. document.documentElement.classList.contains("dark") ? "zai-light" : "zai-dark",
  272. );
  273. return;
  274. }
  275. fiber = fiber.return;
  276. }
  277. throw new Error("Missing OAuth accessor");
  278. }, TID_LOGIN_TRIGGER);
  279. try {
  280. await browser.waitUntil(
  281. () => browser.execute(() => (window as any).__embeddedSessionProbe.captured),
  282. { timeout: 10000 },
  283. );
  284. expect(
  285. await browser.execute(() => (window as any).__embeddedSessionProbe.oldRevision),
  286. ).toBeNull();
  287. await browser.execute(async () => {
  288. const state = (window as any).__embeddedSessionProbe;
  289. await state.services.credentialService.save(
  290. "oauth:session_revision",
  291. "e2e-upgraded-revision",
  292. );
  293. await state.services.credentialService.save("zcodejwttoken", "e2e-new-zcode-jwt");
  294. state.release();
  295. });
  296. await browser.waitUntil(
  297. () => browser.execute(() => (window as any).__embeddedSessionProbe.checked),
  298. { timeout: 10000 },
  299. );
  300. await browser.executeAsync((done) =>
  301. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  302. );
  303. expect((await readCodingPlanWebviewLocalStorage(["zcodejwttoken"])).zcodejwttoken).not.toBe(
  304. "e2e-cn-zcode-jwt",
  305. );
  306. expect(await $('[data-testid="coding-plan-upgrade-surface"]').getText()).toMatch(
  307. /Couldn't sign you into the plan page|无法登录到套餐页/,
  308. );
  309. } finally {
  310. await browser.execute(() => {
  311. const state = (window as any).__embeddedSessionProbe;
  312. state.release?.();
  313. state.services.oauthService = state.original;
  314. delete (window as any).__embeddedSessionProbe;
  315. });
  316. }
  317. await triggerCodingPlanWebviewPurchaseComplete("bigmodel");
  318. await waitForCodingPlanWebviewClosed();
  319. });
  320. it("CPUW-03: Z.ai webview 通知 App 关闭升级弹窗并刷新当前 provider 与 Team Plan products", async function () {
  321. this.timeout(120000);
  322. await prepareZaiCodingPlanUpgradeState();
  323. await openZaiCodingPlanPersonalUpgradePanel();
  324. await waitForCodingPlanWebviewDisplayed();
  325. await waitForZaiWebviewCredentialsInjected();
  326. await completePurchaseAndWaitForRefresh("zai");
  327. // PAT 由账号 owner 管理,不落盘到 Personal Provider Config。
  328. expect(
  329. (await readModelProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan))?.apiKey ?? "",
  330. ).toBe("");
  331. });
  332. });
  333. async function completePurchaseAndWaitForRefresh(provider: "bigmodel" | "zai") {
  334. // 旧断言会命中启动请求;冻结边界后只读购买完成后的新增请求。
  335. const before = (await readCodingPlanUpgradeMockRequests()).requests;
  336. // 订阅接口使用已签发的 PAT,企业目录仍使用 OAuth,不能把两种凭据混作同一个断言。
  337. const subscriptionAuthorization = before.findLast(
  338. (request) => request.path === "/api/biz/subscription/list",
  339. )?.headers.authorization;
  340. expect(Boolean(subscriptionAuthorization)).toBe(true);
  341. await triggerCodingPlanWebviewPurchaseComplete(provider);
  342. await waitForCodingPlanWebviewClosed();
  343. const expectedToken =
  344. provider === "bigmodel" ? "e2e-bigmodel-oauth-token" : "zai-webview-oauth-token";
  345. await browser.waitUntil(
  346. async () => {
  347. const requests = (await readCodingPlanUpgradeMockRequests()).requests.slice(before.length);
  348. return ["/api/biz/subscription/list", "/api/biz/subscription/enterprise/v2/pricing"].every(
  349. (path) =>
  350. requests.some(
  351. (request) =>
  352. request.path === path &&
  353. request.headers.authorization ===
  354. (path.endsWith("/subscription/list") ? subscriptionAuthorization : expectedToken),
  355. ),
  356. );
  357. },
  358. { timeout: 30000, timeoutMsg: `${provider} 购买完成后未按当前账号刷新订阅与企业套餐` },
  359. );
  360. }
  361. async function prepareZaiCodingPlanUpgradeState() {
  362. await clearAppData();
  363. await seedCredentials("zai-webview-oauth-token");
  364. await seedSettings({
  365. providerFamilyConnectionSelections: {
  366. zai: { kind: "individual-coding-plan" },
  367. bigmodel: { kind: "individual-coding-plan" },
  368. },
  369. providerFamilyDomain: "zai",
  370. providerFamilyDomainMigrated: true,
  371. lastWorkspaceSession: [
  372. {
  373. kind: "local",
  374. workspacePath: DEFAULT_WORKSPACE,
  375. workspacePurpose: "project",
  376. },
  377. ],
  378. lastActiveTabIndex: 0,
  379. });
  380. await browser.reloadSession();
  381. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  382. }
  383. async function waitForZaiWebviewCredentialsInjected() {
  384. let latestStorage: Record<string, string | null> = {};
  385. await browser.waitUntil(
  386. async () => {
  387. latestStorage = await readCodingPlanWebviewLocalStorage([
  388. "oauth:zai:access_token",
  389. "zcodejwttoken",
  390. "oauth:bigmodel:access_token",
  391. ]);
  392. return (
  393. latestStorage["oauth:zai:access_token"] === "zai-webview-oauth-token" &&
  394. latestStorage.zcodejwttoken === "zai-webview-oauth-token" &&
  395. latestStorage["oauth:bigmodel:access_token"] === null
  396. );
  397. },
  398. {
  399. timeout: 30000,
  400. timeoutMsg: `Z.ai credentials 没有注入到 Coding Plan webview localStorage: ${JSON.stringify(latestStorage)}`,
  401. },
  402. );
  403. }