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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  4. import {
  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/test-ids";
  11. import {
  12. clearAppData,
  13. DEFAULT_WORKSPACE,
  14. clickTestIdByDom,
  15. getE2EAppDataPaths,
  16. quitElectronAppGracefully,
  17. waitForWorkspaceApp,
  18. } from "#e2e/helpers/desktop-app";
  19. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  20. import type { EntitlementPresentation } from "#e2e/fixtures/entitlement-presentation";
  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. // 账号 Provider 已使用短期项目 Token;旧长期 Key 不会再进入订阅请求。
  192. const tokens = subscriptions.map((request) =>
  193. request.headers.authorization?.replace(/^Bearer\s+/i, "").split("."),
  194. );
  195. expect(
  196. tokens.some((parts) => {
  197. if (parts?.length !== 3) return false;
  198. const claims = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8"));
  199. return claims.token_use === "project_access" && claims.api_key === "e2e-key";
  200. }),
  201. ).toBe(true);
  202. });
  203. for (const team of ["expired", "unassigned", "failure"] as const) {
  204. it(`CTP-16: 团队 ${team} 不误判为未登录`, async function () {
  205. this.timeout(120000);
  206. await prepare({ ...empty, team }, "team");
  207. await textVisible(
  208. team === "expired"
  209. ? "Team plan expired"
  210. : team === "unassigned"
  211. ? "Team plan not assigned"
  212. : "Fetch failed",
  213. );
  214. // 权益查询失败/检查中都不能把托管套餐渲染成可手动配置的模型区,
  215. // 只有重试后确认 purchased 才恢复模型列表。
  216. await models(false);
  217. await textVisible("Connect to BigModel", false);
  218. await textVisible("The selected connection is unavailable", false);
  219. const detail = (await requests()).filter((r) => r.path.endsWith("querySubscribeDetail"));
  220. expect(detail.length).toBeGreaterThan(0);
  221. expect(
  222. detail.some(
  223. (r) =>
  224. r.headers.authorization?.includes("e2e-bigmodel-oauth-token") &&
  225. r.headers["bigmodel-organization"] === "org-team-a" &&
  226. r.headers["bigmodel-project"] === "proj-team-a",
  227. ),
  228. ).toBe(true);
  229. if (team === "failure") {
  230. await scenario({ ...empty, team: "active" });
  231. await $("button=Retry").click();
  232. await models(true);
  233. await textVisible("Fetch failed", false);
  234. await textVisible("The selected connection is unavailable", false);
  235. }
  236. });
  237. }
  238. it("CTP-17: HTTP Date 判定过期,不展示旧余额与模型", async function () {
  239. this.timeout(120000);
  240. await prepare({ ...empty, start: "expired" }, "start");
  241. await textVisible("Start Plan expired");
  242. await textVisible("Today's balance", false);
  243. await textVisible("E2E_EXPIRED_BALANCE", false);
  244. await models(false);
  245. await banners(true);
  246. });
  247. it("CTP-18: 同时存在过期和有效 Start,仅显示有效计划", async function () {
  248. this.timeout(120000);
  249. await prepare({ ...empty, start: "mixed" }, "start");
  250. await textVisible("ZCode V3 Start Plan");
  251. await textVisible("Today's balance");
  252. await textVisible("E2E_EXPIRED_PLAN", false);
  253. await textVisible("E2E_EXPIRED_BALANCE", false);
  254. await models(true);
  255. await textVisible("Upgrade");
  256. await textVisible("150%");
  257. });
  258. it("CTP-20: Start 待生效只展示套餐卡,不展示模型列表", async function () {
  259. this.timeout(120000);
  260. // 待生效时账号权益 pending/entitled=false,但余额快照仍带套餐详情,
  261. // 不能因为 status=purchased 就渲染“没有配置模型、可添加模型”的配置区。
  262. await prepare({ ...empty, start: "pending" }, "start");
  263. await textVisible("ZCode V3 Start Plan");
  264. await textVisible("Pending");
  265. await textVisible("Today's balance", false);
  266. await models(false);
  267. });
  268. for (const paid of ["personal", "team"] as const) {
  269. it(`CTP-19: 有效 ${paid} 权益隐藏 Start 购买及升级入口`, async function () {
  270. this.timeout(120000);
  271. await prepare({ ...empty, start: "active", [paid]: "active" }, paid);
  272. // Start 是独立导航页;打开详情不改写 BigModel 已选的个人/团队连接身份。
  273. // 先确认付费连接可用,再切换详情,不能把未选定团队伪装成已确认的有效权益。
  274. await models(true);
  275. await clickTestIdByDom(
  276. testId(
  277. TID_MODEL_PROVIDER_NAV_ITEM,
  278. `coding-plan:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  279. ),
  280. );
  281. await textVisible("ZCode V3 Start Plan");
  282. await models(true);
  283. await banners(false);
  284. await textVisible("Upgrade", false);
  285. await textVisible("150%", false);
  286. await prepare({ ...empty, start: "expired", [paid]: "active" }, paid);
  287. await models(true);
  288. await clickTestIdByDom(
  289. testId(
  290. TID_MODEL_PROVIDER_NAV_ITEM,
  291. `coding-plan:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  292. ),
  293. );
  294. await textVisible("Start Plan expired");
  295. await models(false);
  296. await banners(false);
  297. });
  298. }
  299. });