coding-plan-entitlement-presentation.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. BUILTIN_MODEL_PROVIDER_IDS,
  5. TID_MODEL_PROVIDER_ADD_MODEL_BUTTON,
  6. TID_MODEL_PROVIDER_NAV_ITEM,
  7. TID_SETTINGS_SECTION_NAV,
  8. TID_TASK_SETTINGS_BUTTON,
  9. testId,
  10. } from "@zcode/shared";
  11. import {
  12. clearAppData,
  13. DEFAULT_WORKSPACE,
  14. clickTestIdByDom,
  15. getE2EAppDataPaths,
  16. quitElectronAppGracefully,
  17. waitForWorkspaceApp,
  18. } from "../helpers/desktop-app.js";
  19. import { skipOccupationOnboardingIfPresent } from "../helpers/occupation-onboarding.js";
  20. import type { EntitlementPresentation } from "../fixtures/entitlement-presentation.js";
  21. const paths = getE2EAppDataPaths();
  22. const base = () => {
  23. const value = process.env.ZCODE_CODING_PLAN_TEAM_MOCK_BASE_URL;
  24. if (!value) throw new Error("missing business mock");
  25. return value;
  26. };
  27. const empty: EntitlementPresentation = {
  28. personal: "none",
  29. team: "none",
  30. start: "none",
  31. };
  32. async function scenario(presentation: EntitlementPresentation) {
  33. const response = await fetch(`${base()}/__e2e/coding-plan/scenario`, {
  34. method: "POST",
  35. headers: { "content-type": "application/json" },
  36. body: JSON.stringify({ scenario: "both", presentation }),
  37. });
  38. if (!response.ok) throw new Error(`scenario failed: ${response.status}`);
  39. }
  40. async function prepare(
  41. state: EntitlementPresentation,
  42. selection: "personal" | "team" | "start",
  43. connected = true,
  44. ) {
  45. await browser.execute(() => {
  46. for (const key of Object.keys(localStorage)) {
  47. if (key.startsWith("zcode:usage-entitlement:")) localStorage.removeItem(key);
  48. }
  49. });
  50. await quitElectronAppGracefully();
  51. await scenario(state);
  52. await writeFile(
  53. paths.credentialsFile,
  54. JSON.stringify({
  55. "oauth:active_provider": connected ? "bigmodel" : "",
  56. "oauth:bigmodel:access_token": connected ? "e2e-bigmodel-oauth-token" : "",
  57. "oauth:bigmodel:user_info": connected
  58. ? JSON.stringify({
  59. id: "bigmodel-e2e-user",
  60. displayName: "BigModel E2E",
  61. username: "bigmodel-e2e-user",
  62. })
  63. : "",
  64. zcodejwttoken: connected ? "e2e-zcode-jwt" : "",
  65. }),
  66. );
  67. const file = join(paths.appDataDir, "setting.json");
  68. const settings = JSON.parse(await readFile(file, "utf8"));
  69. await writeFile(
  70. file,
  71. JSON.stringify({
  72. ...settings,
  73. locale: "en-US",
  74. localePreference: "en-US",
  75. providerFamilyDomain: "bigmodel",
  76. providerFamilyDomainMigrated: true,
  77. providerFamilyConnectionSelections: {
  78. bigmodel:
  79. selection === "team"
  80. ? {
  81. kind: "team-coding-plan",
  82. // 模拟保存的商品与当前订阅不同,但团队组织/项目未变的启动恢复。
  83. productId: "product-team-previous",
  84. organizationId: "org-team-a",
  85. projectId: "proj-team-a",
  86. }
  87. : {
  88. kind: selection === "start" ? "start-plan" : "individual-coding-plan",
  89. },
  90. },
  91. lastWorkspaceSession: [
  92. {
  93. kind: "local",
  94. workspacePath: DEFAULT_WORKSPACE,
  95. workspacePurpose: "project",
  96. },
  97. ],
  98. lastActiveTabIndex: 0,
  99. }),
  100. );
  101. await browser.reloadSession();
  102. await skipOccupationOnboardingIfPresent();
  103. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  104. await browser.keys("Escape");
  105. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  106. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "modelProvider"));
  107. const key = `${selection === "start" ? "coding-plan" : "preset"}:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`;
  108. await clickTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, key));
  109. }
  110. async function textVisible(text: string, present = true) {
  111. await browser.waitUntil(
  112. async () =>
  113. browser.execute(
  114. (expected, wanted) => {
  115. const nodes = Array.from(document.querySelectorAll("body *"));
  116. const found = nodes.some(
  117. (node) =>
  118. Array.from(node.childNodes)
  119. .filter((child) => child.nodeType === Node.TEXT_NODE)
  120. .map((child) => child.textContent)
  121. .join(" ")
  122. .includes(expected) && node.getBoundingClientRect().width > 0,
  123. );
  124. return Boolean(found) === wanted;
  125. },
  126. text,
  127. present,
  128. ),
  129. { timeout: 20000, timeoutMsg: `${present ? "缺少" : "不应显示"}: ${text}` },
  130. );
  131. }
  132. async function models(present: boolean) {
  133. await browser.waitUntil(
  134. async () =>
  135. browser.execute(
  136. (wanted, id) => {
  137. const button = document.querySelector(`[data-testid="${id}"]`);
  138. return Boolean(button && button.getBoundingClientRect().width > 0) === wanted;
  139. },
  140. present,
  141. TID_MODEL_PROVIDER_ADD_MODEL_BUTTON,
  142. ),
  143. { timeout: 20000, timeoutMsg: `模型列表显隐错误: ${present}` },
  144. );
  145. await textVisible("Model list", present);
  146. }
  147. async function banners(present: boolean) {
  148. // 描述只属于购买横幅,避免和连接方式菜单里的同名选项混淆。
  149. await textVisible("dedicated Coding Plan quota", present);
  150. await textVisible("centralized billing", present);
  151. await textVisible("E2E_TRIAL_PROMO", false);
  152. }
  153. async function requests() {
  154. return (await (await fetch(`${base()}/__e2e/coding-plan/requests`)).json()).requests as Array<{
  155. path: string;
  156. headers: Record<string, string>;
  157. }>;
  158. }
  159. describe("套餐权益展示与购买入口", () => {
  160. afterEach(async function () {
  161. if (this.currentTest?.state === "failed") {
  162. console.log("[entitlement-presentation] visible page:", await $("body").getText());
  163. if (process.env.ZCODE_E2E_ARTIFACT_DIR)
  164. await browser.saveScreenshot(
  165. join(
  166. process.env.ZCODE_E2E_ARTIFACT_DIR,
  167. `${this.currentTest.title.replace(/[^a-zA-Z0-9-]/g, "_")}.png`,
  168. ),
  169. );
  170. }
  171. });
  172. after(async () => {
  173. await clearAppData();
  174. });
  175. it("CTP-14: 未连接只显示个人和团队购买入口", async function () {
  176. this.timeout(120000);
  177. await prepare(empty, "personal", false);
  178. await textVisible("Not connected");
  179. await textVisible("Connect to BigModel");
  180. await models(false);
  181. await banners(true);
  182. });
  183. it("CTP-15: 历史团队订阅不隐藏无权益账号的团队 banner", async function () {
  184. this.timeout(120000);
  185. await prepare({ ...empty, team: "expired" }, "personal");
  186. await textVisible("Not subscribed, enabled after subscription");
  187. await models(false);
  188. await banners(true);
  189. const subscriptions = (await requests()).filter((r) => r.path === "/api/biz/subscription/list");
  190. expect(subscriptions.length).toBeGreaterThan(0);
  191. expect(subscriptions.some((r) => r.headers.authorization?.includes("personal-secret"))).toBe(
  192. true,
  193. );
  194. });
  195. for (const team of ["expired", "unassigned", "failure"] as const) {
  196. it(`CTP-16: 团队 ${team} 不误判为未登录`, async function () {
  197. this.timeout(120000);
  198. await prepare({ ...empty, team }, "team");
  199. await textVisible(
  200. team === "expired"
  201. ? "Team plan expired"
  202. : team === "unassigned"
  203. ? "Team plan not assigned"
  204. : "Fetch failed",
  205. );
  206. if (team !== "failure") await models(false);
  207. await textVisible("Connect to BigModel", false);
  208. await textVisible("The selected connection is unavailable", false);
  209. const detail = (await requests()).filter((r) => r.path.endsWith("querySubscribeDetail"));
  210. expect(detail.length).toBeGreaterThan(0);
  211. expect(
  212. detail.some(
  213. (r) =>
  214. r.headers.authorization?.includes("e2e-bigmodel-oauth-token") &&
  215. r.headers["bigmodel-organization"] === "org-team-a" &&
  216. r.headers["bigmodel-project"] === "proj-team-a",
  217. ),
  218. ).toBe(true);
  219. if (team === "failure") {
  220. await scenario({ ...empty, team: "active" });
  221. await $("button=Retry").click();
  222. await models(true);
  223. await textVisible("Fetch failed", false);
  224. await textVisible("The selected connection is unavailable", false);
  225. }
  226. });
  227. }
  228. it("CTP-17: HTTP Date 判定过期,不展示旧余额与模型", async function () {
  229. this.timeout(120000);
  230. await prepare({ ...empty, start: "expired" }, "start");
  231. await textVisible("Start Plan expired");
  232. await textVisible("Today's balance", false);
  233. await textVisible("E2E_EXPIRED_BALANCE", false);
  234. await models(false);
  235. await banners(true);
  236. });
  237. it("CTP-18: 同时存在过期和有效 Start,仅显示有效计划", async function () {
  238. this.timeout(120000);
  239. await prepare({ ...empty, start: "mixed" }, "start");
  240. await textVisible("ZCode V3 Start Plan");
  241. await textVisible("Today's balance");
  242. await textVisible("E2E_EXPIRED_PLAN", false);
  243. await textVisible("E2E_EXPIRED_BALANCE", false);
  244. await models(true);
  245. await textVisible("Upgrade");
  246. await textVisible("150%");
  247. });
  248. for (const paid of ["personal", "team"] as const) {
  249. it(`CTP-19: 有效 ${paid} 权益隐藏 Start 购买及升级入口`, async function () {
  250. this.timeout(120000);
  251. await prepare({ ...empty, start: "active", [paid]: "active" }, paid);
  252. // Start 是独立导航页;打开详情不改写 BigModel 已选的个人/团队连接身份。
  253. // 先确认付费连接可用,再切换详情,不能把未选定团队伪装成已确认的有效权益。
  254. await models(true);
  255. await clickTestIdByDom(
  256. testId(
  257. TID_MODEL_PROVIDER_NAV_ITEM,
  258. `coding-plan:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  259. ),
  260. );
  261. await textVisible("ZCode V3 Start Plan");
  262. await models(true);
  263. await banners(false);
  264. await textVisible("Upgrade", false);
  265. await textVisible("150%", false);
  266. await prepare({ ...empty, start: "expired", [paid]: "active" }, paid);
  267. await models(true);
  268. await clickTestIdByDom(
  269. testId(
  270. TID_MODEL_PROVIDER_NAV_ITEM,
  271. `coding-plan:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  272. ),
  273. );
  274. await textVisible("Start Plan expired");
  275. await models(false);
  276. await banners(false);
  277. });
  278. }
  279. });