coding-plan-upgrade-mock-server.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. import { requestSecurityClientConfig } from "./request-security-edition/index.js";
  2. /* eslint-disable max-lines -- E2E fixture server 需要集中维护 ZCode client config 与 BigModel 购买接口响应 */
  3. import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
  4. import { once } from "node:events";
  5. import { readFile } from "node:fs/promises";
  6. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  7. import { createMarketingTouchFixture } from "./marketing-touch-fixture.js";
  8. import { rewardsWebsiteFixture } from "./rewards-website-fixture.js";
  9. export type CodingPlanUpgradeMockScenario =
  10. | "manual-claim-experience"
  11. | "personal-sold-out"
  12. | "personal-system-busy"
  13. | "webview-refresh-provider";
  14. export interface CodingPlanUpgradeMockRequest {
  15. method: string;
  16. path: string;
  17. query: Record<string, string>;
  18. headers: Record<string, string>;
  19. keyCreation?: { name?: unknown; usageScene?: unknown };
  20. }
  21. export interface CodingPlanUpgradeMockServer {
  22. baseUrl: string;
  23. scenario: CodingPlanUpgradeMockScenario;
  24. stop(): Promise<void>;
  25. }
  26. interface CodingPlanUpgradeMockState {
  27. webviewMode: "hold" | "fail" | "ready";
  28. webviewWaiters: Array<() => void>;
  29. customerInfoHeld: boolean;
  30. customerInfoWaiters: Array<() => void>;
  31. inventoryMode: "hold" | "fail" | "ready";
  32. inventoryWaiters: Array<() => void>;
  33. clientConfigPayload: CodingPlanClientConfigFixture;
  34. manualClaimBucketReady: boolean;
  35. manualClaimCompleted: boolean;
  36. manualClaimShouldFail: boolean;
  37. startPlanExpired: boolean;
  38. purchaseCompleted: boolean;
  39. scenario: CodingPlanUpgradeMockScenario;
  40. }
  41. const DEFAULT_FULL_E2E_SPEC_GLOB = "./test/e2e/**/*.test.ts";
  42. export function resolveCodingPlanUpgradeMockScenario(
  43. specs: readonly string[],
  44. ): CodingPlanUpgradeMockScenario | null {
  45. if (specs.some((spec) => spec.includes("marketing-touch-"))) {
  46. return "manual-claim-experience";
  47. }
  48. if (specs.some((spec) => spec.includes("coding-plan-upgrade-personal-system-busy"))) {
  49. return "personal-system-busy";
  50. }
  51. if (specs.some((spec) => spec.includes("coding-plan-upgrade-personal-sold-out"))) {
  52. return "personal-sold-out";
  53. }
  54. if (
  55. specs.some(
  56. (spec) =>
  57. spec.includes("coding-plan-upgrade-webview-refresh-provider") ||
  58. spec.includes("account-key-usage-scene"),
  59. )
  60. ) {
  61. return "webview-refresh-provider";
  62. }
  63. return null;
  64. }
  65. export function shouldPrepareCodingPlanUpgradeMockForBuild(specs: readonly string[]): boolean {
  66. return (
  67. resolveCodingPlanUpgradeMockScenario(specs) !== null ||
  68. specs.some((spec) => spec.replace(/\\/gu, "/") === DEFAULT_FULL_E2E_SPEC_GLOB)
  69. );
  70. }
  71. export async function resetCodingPlanUpgradeMockServer(
  72. baseUrl: string,
  73. scenario: CodingPlanUpgradeMockScenario,
  74. ): Promise<void> {
  75. const response = await fetch(`${baseUrl}/__e2e/coding-plan/reset`, {
  76. body: JSON.stringify({ scenario }),
  77. headers: { "content-type": "application/json" },
  78. method: "POST",
  79. });
  80. if (!response.ok) {
  81. throw new Error(
  82. `Coding Plan E2E mock reset failed: ${response.status} ${await response.text()}`,
  83. );
  84. }
  85. }
  86. export async function startCodingPlanUpgradeMockServer(
  87. scenario: CodingPlanUpgradeMockScenario,
  88. options: { marketingTouch?: boolean } = {},
  89. ): Promise<CodingPlanUpgradeMockServer> {
  90. // 修复原因:pnpm filter 会把 E2E cwd 切到 packages/desktop,不能用 cwd 定位仓库级 fixture。
  91. const clientConfigFixtureUrl = new URL(
  92. "../fixtures/coding-plan-client-configs.json",
  93. import.meta.url,
  94. );
  95. const baseClientConfigPayload = JSON.parse(
  96. await readFile(clientConfigFixtureUrl, "utf8"),
  97. ) as CodingPlanClientConfigFixture;
  98. const requests: CodingPlanUpgradeMockRequest[] = [];
  99. const state = createCodingPlanUpgradeMockState(baseClientConfigPayload, scenario);
  100. // 同套餐场景也供旧测试复用,不能隐式注入需要 release 的营销领取暂停。
  101. const marketing = options.marketingTouch ? await createMarketingTouchFixture() : null;
  102. const server = createServer((request, response) => {
  103. void (async () => {
  104. if (
  105. marketing &&
  106. /^\/(cn|en)\/rewards$/.test(new URL(request.url ?? "/", "http://localhost").pathname)
  107. ) {
  108. response.writeHead(200, {
  109. "Content-Type": "text/html; charset=utf-8",
  110. "Cache-Control": "no-store",
  111. });
  112. response.end(rewardsWebsiteFixture);
  113. return;
  114. }
  115. if (await marketing?.handle(request, response)) return;
  116. await handleRequest(baseClientConfigPayload, state, requests, request, response);
  117. })().catch((error) => {
  118. if (!response.headersSent) {
  119. sendJson(response, { code: 500, msg: formatErrorMessage(error) }, 500);
  120. return;
  121. }
  122. response.destroy(error instanceof Error ? error : new Error(String(error)));
  123. });
  124. });
  125. server.listen(0, "127.0.0.1");
  126. await once(server, "listening");
  127. const address = server.address();
  128. if (!address || typeof address === "string") {
  129. throw new Error("Coding Plan E2E mock server did not bind to a TCP port");
  130. }
  131. return {
  132. baseUrl: `http://127.0.0.1:${address.port}`,
  133. get scenario() {
  134. return state.scenario;
  135. },
  136. stop: async () => {
  137. marketing?.stop();
  138. state.webviewWaiters.splice(0).forEach((release) => release());
  139. state.customerInfoWaiters.splice(0).forEach((release) => release());
  140. state.inventoryWaiters.splice(0).forEach((release) => release());
  141. server.close();
  142. await once(server, "close");
  143. },
  144. };
  145. }
  146. async function handleRequest(
  147. baseClientConfigPayload: CodingPlanClientConfigFixture,
  148. state: CodingPlanUpgradeMockState,
  149. requests: CodingPlanUpgradeMockRequest[],
  150. request: IncomingMessage,
  151. response: ServerResponse,
  152. ) {
  153. const url = new URL(request.url ?? "/", "http://127.0.0.1");
  154. if (url.pathname === "/__e2e/coding-plan/webview-state") {
  155. sendJson(response, { pending: state.webviewWaiters.length });
  156. return;
  157. }
  158. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/webview-mode") {
  159. const { mode } = await readJsonBody<{ mode: "hold" | "fail" | "ready" }>(request);
  160. state.webviewMode = mode;
  161. state.webviewWaiters.splice(0).forEach((release) => release());
  162. sendJson(response, { ok: true });
  163. return;
  164. }
  165. if (request.method === "GET" && url.pathname === "/__e2e/coding-plan/requests") {
  166. sendJson(response, { requests });
  167. return;
  168. }
  169. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/customer-info-hold") {
  170. const { held } = await readJsonBody<{ held: boolean }>(request);
  171. state.customerInfoHeld = held;
  172. if (!held) state.customerInfoWaiters.splice(0).forEach((release) => release());
  173. sendJson(response, { ok: true });
  174. return;
  175. }
  176. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/inventory-mode") {
  177. const { mode } = await readJsonBody<{ mode: "hold" | "fail" | "ready" }>(request);
  178. state.inventoryMode = mode;
  179. state.inventoryWaiters.splice(0).forEach((release) => release());
  180. sendJson(response, { ok: true });
  181. return;
  182. }
  183. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/reset") {
  184. const payload = await readJsonBody<{ scenario?: unknown }>(request);
  185. if (!isCodingPlanUpgradeMockScenario(payload.scenario)) {
  186. sendJson(response, { code: 400, msg: "Invalid Coding Plan E2E scenario" }, 400);
  187. return;
  188. }
  189. // Bug 根因:全量 suite 的 webview origin 在 build 前固定,但各 worker 的业务场景
  190. // 不同;复用 origin 时必须把 scenario、购买状态和 request ledger 一起重置。
  191. state.webviewWaiters.splice(0).forEach((release) => release());
  192. Object.assign(
  193. state,
  194. createCodingPlanUpgradeMockState(baseClientConfigPayload, payload.scenario),
  195. );
  196. requests.splice(0, requests.length);
  197. sendJson(response, { ok: true, scenario: state.scenario });
  198. return;
  199. }
  200. if (
  201. request.method === "POST" &&
  202. url.pathname === "/__e2e/coding-plan/manual-claim-failure" &&
  203. state.scenario === "manual-claim-experience"
  204. ) {
  205. state.manualClaimShouldFail = true;
  206. sendJson(response, { ok: true });
  207. return;
  208. }
  209. if (
  210. request.method === "POST" &&
  211. url.pathname === "/__e2e/coding-plan/manual-claim-bucket-ready" &&
  212. state.scenario === "manual-claim-experience"
  213. ) {
  214. state.manualClaimBucketReady = true;
  215. sendJson(response, { ok: true });
  216. return;
  217. }
  218. if (
  219. request.method === "POST" &&
  220. url.pathname === "/__e2e/coding-plan/manual-claim-next-window" &&
  221. state.scenario === "manual-claim-experience"
  222. ) {
  223. // Bug 原因:下一时段只重置 completed 会让失败用例的一次性开关泄漏到后续成功用例。
  224. state.manualClaimCompleted = false;
  225. state.manualClaimShouldFail = false;
  226. sendJson(response, { ok: true });
  227. return;
  228. }
  229. const recordedRequest = recordRequest(requests, request, url);
  230. if (
  231. request.method === "POST" &&
  232. url.pathname === "/__e2e/coding-plan/start-expired" &&
  233. state.scenario === "manual-claim-experience"
  234. ) {
  235. state.startPlanExpired = true;
  236. sendJson(response, { ok: true });
  237. return;
  238. }
  239. if (
  240. request.method === "GET" &&
  241. url.pathname === "/api/v1/zcode-plan/billing/preview" &&
  242. state.scenario === "manual-claim-experience"
  243. ) {
  244. sendJson(response, {
  245. code: 0,
  246. msg: "ok",
  247. data: {
  248. server_time: Math.floor(Date.now() / 1_000),
  249. plans: state.manualClaimCompleted
  250. ? []
  251. : [
  252. {
  253. plan_id: "weekend-plan-e2e",
  254. name: "ZCode Weekend Build",
  255. description: "Deterministic manual claim fixture",
  256. priority: 100,
  257. entitlements: [
  258. {
  259. entitlement_id: "weekend-glm-flash",
  260. show_name: "GLM-5.3-Flash",
  261. meter: "model_usage",
  262. unit_type: "token",
  263. capabilities: ["model:glm-5.3-flash"],
  264. grant_units: 10_000_000_000,
  265. period: "one_time",
  266. priority: 10,
  267. },
  268. ],
  269. },
  270. ],
  271. },
  272. });
  273. return;
  274. }
  275. if (
  276. request.method === "POST" &&
  277. url.pathname === "/api/v1/zcode-plan/billing/claim" &&
  278. state.scenario === "manual-claim-experience"
  279. ) {
  280. if (state.manualClaimShouldFail) {
  281. state.manualClaimShouldFail = false;
  282. state.manualClaimCompleted = true;
  283. sendJson(response, { code: 1003, data: null, msg: "already claimed" });
  284. return;
  285. }
  286. state.manualClaimCompleted = true;
  287. const nowSeconds = Math.floor(Date.now() / 1_000);
  288. sendJson(response, {
  289. code: 0,
  290. msg: "ok",
  291. data: {
  292. server_time: nowSeconds,
  293. plan: {
  294. user_plan_id: "user-weekend-plan-e2e",
  295. plan_id: "weekend-plan-e2e",
  296. status: "active",
  297. starts_at: nowSeconds,
  298. ends_at: nowSeconds + 86_400,
  299. entitlements: [
  300. {
  301. entitlement_id: "weekend-glm-flash",
  302. show_name: "GLM-5.3-Flash",
  303. effective_at: nowSeconds + 3_600,
  304. },
  305. ],
  306. },
  307. },
  308. });
  309. return;
  310. }
  311. if (request.method === "GET" && url.pathname === "/coding-plan") {
  312. if (state.webviewMode === "hold")
  313. await new Promise<void>((resolve) => state.webviewWaiters.push(resolve));
  314. if (state.webviewMode === "fail") {
  315. response.destroy();
  316. return;
  317. }
  318. sendHtml(response, buildCodingPlanWebviewFixtureHtml(state.scenario));
  319. return;
  320. }
  321. if (request.method === "POST" && url.pathname === "/__e2e/coding-plan/purchase-complete") {
  322. state.purchaseCompleted = true;
  323. sendJson(response, { ok: true });
  324. return;
  325. }
  326. if (request.method === "GET" && url.pathname === "/api/v2/releases/latest") {
  327. sendJson(response, {
  328. code: 0,
  329. data: { config_version: "coding-plan-upgrade-e2e" },
  330. config_version: "coding-plan-upgrade-e2e",
  331. });
  332. return;
  333. }
  334. if (request.method === "GET" && url.pathname === "/api/v1/client/configs") {
  335. sendJson(response, state.clientConfigPayload);
  336. return;
  337. }
  338. if (
  339. request.method === "GET" &&
  340. url.pathname === "/api/v1/zcode-plan/billing/balance" &&
  341. (state.scenario === "manual-claim-experience" || state.scenario === "webview-refresh-provider")
  342. ) {
  343. // Bug 原因:领取 fixture 只 mock 了旧 quota 接口;当前 Start 可用性以
  344. // billing/balance 为准,缺失时刷新会把刚写入的 Start selectedKey 收敛回 Individual。
  345. sendJson(
  346. response,
  347. state.startPlanExpired
  348. ? {
  349. code: 0,
  350. msg: "ok",
  351. data: {
  352. server_time: Math.floor(Date.now() / 1000),
  353. plans: [],
  354. balances: [],
  355. },
  356. }
  357. : buildManualClaimStartPlanBalance(
  358. state.manualClaimCompleted,
  359. state.manualClaimBucketReady,
  360. ),
  361. );
  362. return;
  363. }
  364. if (request.method === "POST" && url.pathname === "/api/biz/pay/batch-preview") {
  365. if (state.scenario === "personal-system-busy") {
  366. // 修复原因:系统繁忙是接口整体失败语义,不能伪造成商品售罄。
  367. // 服务层会把 WAF/HTML 类不可展示响应收敛成 coding_plan_system_busy,再交给 UI 本地化。
  368. sendJson(response, {
  369. code: 503,
  370. msg: "<html>request has been blocked</html>",
  371. data: null,
  372. });
  373. return;
  374. }
  375. const personalProducts =
  376. state.clientConfigPayload.data.configs.codingPlanStaticProducts[
  377. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan
  378. ] ?? [];
  379. sendJson(response, {
  380. code: 200,
  381. data: {
  382. isAuthenticated: true,
  383. isSubscribed: false,
  384. productList: personalProducts.map((product) => ({
  385. ...product,
  386. canPurchase: false,
  387. soldOut: true,
  388. })),
  389. },
  390. });
  391. return;
  392. }
  393. if (request.method === "GET" && url.pathname === "/api/monitor/usage/quota/limit") {
  394. if (state.scenario === "webview-refresh-provider") {
  395. sendJson(response, { code: 200, data: { level: "pro", limits: [] } });
  396. return;
  397. }
  398. if (state.scenario === "manual-claim-experience") {
  399. const nowSeconds = Math.floor(Date.now() / 1_000);
  400. sendJson(response, {
  401. code: 0,
  402. msg: "ok",
  403. data: {
  404. plans: [
  405. {
  406. plan_id: "weekend-plan-e2e",
  407. name: "ZCode Weekend Build",
  408. status: "active",
  409. starts_at: nowSeconds,
  410. ends_at: nowSeconds + 86_400,
  411. entitlements: [{ meter: "model_usage", period: "one_time" }],
  412. },
  413. ],
  414. balances: [
  415. {
  416. plan_id: "weekend-plan-e2e",
  417. entitlement_id: "weekend-glm-flash",
  418. show_name: "GLM-5.3-Flash",
  419. capabilities: ["model:glm-5.3-flash"],
  420. total_units: 10_000_000_000,
  421. used_units: 0,
  422. remaining_units: 10_000_000_000,
  423. available_units: 10_000_000_000,
  424. expires_at: nowSeconds + 86_400,
  425. },
  426. ],
  427. },
  428. });
  429. return;
  430. }
  431. // 修复原因:sidebar 升级入口通过 entitlement 判断账号是已连接但未开通套餐;
  432. // mock 必须用 HTTP 200 承载业务 no_plan,否则 readApiJson 会提前抛错,
  433. // 购买面板会被当成不可用账号并跳过 batch-preview。
  434. sendJson(response, {
  435. code: 404,
  436. msg: "当前用户不存在coding plan",
  437. data: null,
  438. });
  439. return;
  440. }
  441. if (request.method === "GET" && url.pathname === "/api/biz/subscription/list") {
  442. sendJson(response, {
  443. code: 200,
  444. data:
  445. state.scenario === "webview-refresh-provider" ||
  446. (state.scenario === "manual-claim-experience" && state.manualClaimCompleted)
  447. ? [
  448. {
  449. productId: "glm-coding-pro-e2e",
  450. productName: "GLM Coding Pro",
  451. status: "VALID",
  452. inCurrentPeriod: true,
  453. },
  454. ]
  455. : [],
  456. });
  457. return;
  458. }
  459. if (request.method === "GET" && url.pathname === "/api/biz/customer/getCustomerInfo") {
  460. // 将单卡 provider 同步停在网络边界,验证全局查询已完成后的 Subscribe 加载反馈。
  461. if (state.customerInfoHeld) {
  462. await new Promise<void>((resolve) => state.customerInfoWaiters.push(resolve));
  463. }
  464. sendJson(response, {
  465. code: 200,
  466. data:
  467. state.purchaseCompleted ||
  468. // 当前账号服务通过组织/项目取得凭据;库存场景购买前已经拥有个人套餐,不能只伪造订阅列表。
  469. state.scenario === "webview-refresh-provider" ||
  470. (state.scenario === "manual-claim-experience" && state.manualClaimCompleted)
  471. ? {
  472. organizations: [
  473. {
  474. organizationId: "org-e2e",
  475. projects: [{ projectId: "proj-e2e", projectType: 0 }],
  476. },
  477. ],
  478. }
  479. : { organizations: [] },
  480. });
  481. return;
  482. }
  483. if (
  484. (request.method === "GET" || request.method === "POST") &&
  485. url.pathname === "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys"
  486. ) {
  487. if (request.method === "POST" && recordedRequest) {
  488. // 仅记录创建用途与名称,不把可能含凭据的任意请求体写入 E2E ledger。
  489. const { name, usageScene } = await readJsonBody<{
  490. name?: unknown;
  491. usageScene?: unknown;
  492. }>(request);
  493. recordedRequest.keyCreation = { name, usageScene };
  494. }
  495. sendJson(response, {
  496. code: 200,
  497. data: !state.purchaseCompleted
  498. ? request.method === "GET"
  499. ? [{ name: "zcode", apiKey: "bigmodel-personal-api-key" }]
  500. : { name: "zcode", apiKey: "bigmodel-personal-api-key" }
  501. : request.method === "GET"
  502. ? [{ name: "zcode", apiKey: "bigmodel-webview-refreshed-key" }]
  503. : { name: "zcode", apiKey: "bigmodel-webview-refreshed-key" },
  504. });
  505. return;
  506. }
  507. if (
  508. request.method === "POST" &&
  509. /^\/api\/biz\/v1\/organization\/org-e2e\/projects\/proj-e2e\/api_keys\/[^/]+\/access_tokens$/.test(
  510. url.pathname,
  511. )
  512. ) {
  513. const body = await readJsonBody<{ clientType?: string }>(request);
  514. if (body.clientType !== "zcode" || !request.headers.authorization?.startsWith("Bearer ")) {
  515. sendJson(response, { code: 400, msg: "invalid_token_request" });
  516. return;
  517. }
  518. const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
  519. const token = `${encode({ alg: "HS256", typ: "JWT", sign_type: "SIGN" })}.${encode({ token_use: "project_access", api_key: "e2e-key", exp: Math.floor(Date.now() / 1000) + 600 })}.e2e-signature`;
  520. sendJson(response, {
  521. code: 200,
  522. data: {
  523. enable: true,
  524. accessToken: token,
  525. tokenType: "Bearer",
  526. expiresIn: 600,
  527. expiresAt: Math.floor(Date.now() / 1000) + 600,
  528. },
  529. });
  530. return;
  531. }
  532. if (
  533. request.method === "GET" &&
  534. (url.pathname ===
  535. "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys/copy/bigmodel-webview-refreshed-key" ||
  536. url.pathname ===
  537. "/api/biz/v1/organization/org-e2e/projects/proj-e2e/api_keys/copy/bigmodel-personal-api-key")
  538. ) {
  539. sendJson(response, {
  540. code: 200,
  541. // Bug 原因:Z.ai 的 resolver 需要 copy secret,但 BigModel 的 apiKey 本身已是
  542. // 完整凭据。fixture 若无条件返回 Z.ai secret,会把 BigModel key 错拼成 key.secret。
  543. data: {
  544. secretKey:
  545. request.headers.authorization === "Bearer zai-webview-oauth-token"
  546. ? "zai-webview-refreshed-secret"
  547. : "",
  548. },
  549. });
  550. return;
  551. }
  552. if (
  553. request.method === "GET" &&
  554. (url.pathname === "/api/biz/subscription/enterprise/v2/pricing" ||
  555. url.pathname === "/api/biz/campaign/partner/enterprise/pricing")
  556. ) {
  557. if (url.pathname === "/api/biz/subscription/enterprise/v2/pricing") {
  558. if (state.inventoryMode === "hold")
  559. await new Promise<void>((resolve) => state.inventoryWaiters.push(resolve));
  560. if (state.inventoryMode === "fail") {
  561. sendJson(response, { code: 503, msg: "inventory unavailable" }, 503);
  562. return;
  563. }
  564. }
  565. sendJson(response, { code: 200, data: { productList: [] } });
  566. return;
  567. }
  568. sendJson(
  569. response,
  570. {
  571. code: 404,
  572. msg: `Unhandled E2E mock path: ${request.method} ${url.pathname}`,
  573. },
  574. 404,
  575. );
  576. }
  577. function createCodingPlanUpgradeMockState(
  578. basePayload: CodingPlanClientConfigFixture,
  579. scenario: CodingPlanUpgradeMockScenario,
  580. ): CodingPlanUpgradeMockState {
  581. const clientConfigPayload = structuredClone(basePayload);
  582. enrichClientConfigPayloadForUpgradeE2E(clientConfigPayload, scenario);
  583. return {
  584. clientConfigPayload,
  585. manualClaimBucketReady: false,
  586. manualClaimCompleted: false,
  587. manualClaimShouldFail: false,
  588. startPlanExpired: false,
  589. customerInfoHeld: false,
  590. customerInfoWaiters: [],
  591. inventoryMode: "ready",
  592. webviewMode: "ready",
  593. webviewWaiters: [],
  594. inventoryWaiters: [],
  595. purchaseCompleted: false,
  596. scenario,
  597. };
  598. }
  599. function buildManualClaimStartPlanBalance(claimed: boolean, newBucketReady: boolean) {
  600. const nowSeconds = Math.floor(Date.now() / 1_000);
  601. const oldPlanId = "zcode-v3-start-plan";
  602. const newPlanId = "weekend-plan-e2e";
  603. const oldPlan = {
  604. ends_at: nowSeconds + 4 * 86_400,
  605. entitlements: [
  606. {
  607. effective_at: 0,
  608. entitlement_id: "start-glm-turbo-e2e",
  609. show_name: "GLM-5-Turbo",
  610. },
  611. ],
  612. name: "ZCode V3 Start Plan",
  613. plan_id: oldPlanId,
  614. starts_at: nowSeconds - 86_400,
  615. status: "active",
  616. };
  617. const oldBalance = {
  618. available_units: 1_000_000_000,
  619. capabilities: ["model:glm-5-turbo"],
  620. entitlement_id: "start-glm-turbo-e2e",
  621. expires_at: nowSeconds + 4 * 86_400,
  622. plan_id: oldPlanId,
  623. remaining_units: 500_000_000,
  624. show_name: "GLM-5-Turbo",
  625. total_units: 1_000_000_000,
  626. used_units: 500_000_000,
  627. };
  628. const newPlan = {
  629. ends_at: nowSeconds + 86_400,
  630. entitlements: [
  631. {
  632. // 已到达排期时间但额度桶尚未生成,驱动设置页显示「刷新权益」。
  633. effective_at: nowSeconds - 60,
  634. entitlement_id: "weekend-glm-flash",
  635. show_name: "GLM-5.3-Flash",
  636. },
  637. ],
  638. name: "ZCode Weekend Build",
  639. plan_id: newPlanId,
  640. starts_at: nowSeconds - 60,
  641. status: "active",
  642. };
  643. const newBalance = {
  644. available_units: 10_000_000_000,
  645. capabilities: ["model:glm-5.3-flash"],
  646. entitlement_id: "weekend-glm-flash",
  647. expires_at: nowSeconds + 86_400,
  648. plan_id: newPlanId,
  649. remaining_units: 10_000_000_000,
  650. show_name: "GLM-5.3-Flash",
  651. total_units: 10_000_000_000,
  652. used_units: 0,
  653. };
  654. return {
  655. code: 0,
  656. data: {
  657. server_time: nowSeconds,
  658. balances: [oldBalance, ...(claimed && newBucketReady ? [newBalance] : [])],
  659. plans: [oldPlan, ...(claimed ? [newPlan] : [])],
  660. },
  661. msg: "ok",
  662. success: true,
  663. };
  664. }
  665. function isCodingPlanUpgradeMockScenario(value: unknown): value is CodingPlanUpgradeMockScenario {
  666. return (
  667. value === "manual-claim-experience" ||
  668. value === "personal-sold-out" ||
  669. value === "personal-system-busy" ||
  670. value === "webview-refresh-provider"
  671. );
  672. }
  673. async function readJsonBody<T>(request: IncomingMessage): Promise<T> {
  674. const chunks: Buffer[] = [];
  675. for await (const chunk of request) {
  676. chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  677. }
  678. const raw = Buffer.concat(chunks).toString("utf8").trim();
  679. return (raw ? JSON.parse(raw) : {}) as T;
  680. }
  681. function formatErrorMessage(error: unknown) {
  682. return error instanceof Error ? error.message : String(error);
  683. }
  684. interface CodingPlanClientConfigFixture {
  685. data: {
  686. builtinProviders?: Array<{
  687. id?: string;
  688. name?: string;
  689. schema?: string;
  690. baseUrl?: string;
  691. models?: string[];
  692. }>;
  693. builtinModels?: Array<{
  694. modelId: string;
  695. name?: string;
  696. contextWindow?: number;
  697. maxCompletionTokens?: number;
  698. priority?: number;
  699. }>;
  700. configs: {
  701. codingPlanStaticProducts: Partial<
  702. Record<
  703. string,
  704. Array<{
  705. productId: string;
  706. productName: string;
  707. priceUnit: "month" | "quarter" | "year";
  708. payAmount?: number;
  709. }>
  710. >
  711. >;
  712. };
  713. };
  714. }
  715. function enrichClientConfigPayloadForUpgradeE2E(
  716. payload: CodingPlanClientConfigFixture,
  717. scenario: CodingPlanUpgradeMockScenario,
  718. ) {
  719. if (scenario === "manual-claim-experience") {
  720. // Bug 原因:领取 fixture 需要同时下发 Individual 与 Start;且 BigModel OAuth
  721. // resolver 会从同 family 的远端列表选择首个 Anthropic provider,Individual 必须排在前面,
  722. // 否则会把 Start 模型错误复用到 Individual,无法覆盖真实切换链路。
  723. payload.data.builtinProviders = [
  724. {
  725. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  726. name: "BigModel - Coding Plan",
  727. schema: "anthropic",
  728. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  729. models: ["GLM-5.3-Flash"],
  730. },
  731. {
  732. id: BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  733. name: "BigModel - Start Plan",
  734. schema: "anthropic",
  735. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  736. models: ["GLM-5.3-Flash", "GLM-5-Turbo"],
  737. },
  738. ];
  739. payload.data.builtinModels = [
  740. {
  741. modelId: "GLM-5-Turbo",
  742. name: "GLM-5-Turbo",
  743. contextWindow: 1_048_576,
  744. maxCompletionTokens: 131_072,
  745. priority: 101,
  746. },
  747. {
  748. modelId: "GLM-5.3-Flash",
  749. name: "GLM-5.3-Flash",
  750. contextWindow: 1_048_576,
  751. maxCompletionTokens: 131_072,
  752. priority: 100,
  753. },
  754. ];
  755. Object.assign(payload.data.configs, requestSecurityClientConfig());
  756. return;
  757. }
  758. if (scenario !== "webview-refresh-provider") {
  759. return;
  760. }
  761. payload.data.builtinProviders = [
  762. {
  763. id: "bigmodel",
  764. name: "BigModel - Coding Plan",
  765. schema: "anthropic",
  766. baseUrl: "https://open.bigmodel.cn/api/anthropic",
  767. models: ["glm-5.1-highspeed"],
  768. },
  769. {
  770. id: "zai",
  771. name: "Z.ai - Coding Plan",
  772. schema: "anthropic",
  773. baseUrl: "https://api.z.ai/api/anthropic",
  774. models: ["glm-5.1-highspeed"],
  775. },
  776. ];
  777. }
  778. function buildCodingPlanWebviewFixtureHtml(scenario: CodingPlanUpgradeMockScenario): string {
  779. const label =
  780. scenario === "personal-system-busy"
  781. ? "System busy"
  782. : scenario === "personal-sold-out"
  783. ? "Sold out"
  784. : "Complete purchase";
  785. return `<!doctype html>
  786. <html>
  787. <head>
  788. <meta charset="utf-8" />
  789. <title>Coding Plan E2E</title>
  790. </head>
  791. <body>
  792. <main data-testid="coding-plan-webview-fixture">
  793. <h1>Coding Plan E2E</h1>
  794. <button id="complete" type="button">${label}</button>
  795. </main>
  796. <script>
  797. document.getElementById("complete").addEventListener("click", async () => {
  798. await fetch("/__e2e/coding-plan/purchase-complete", {
  799. method: "POST",
  800. keepalive: true
  801. });
  802. window.zcodeBridge.notifyPurchaseComplete({
  803. provider: "bigmodel",
  804. timestamp: Date.now()
  805. });
  806. });
  807. </script>
  808. </body>
  809. </html>`;
  810. }
  811. function recordRequest(
  812. requests: CodingPlanUpgradeMockRequest[],
  813. request: IncomingMessage,
  814. url: URL,
  815. ) {
  816. if (url.pathname === "/__e2e/coding-plan/requests") {
  817. return;
  818. }
  819. const recorded: CodingPlanUpgradeMockRequest = {
  820. method: request.method ?? "GET",
  821. path: url.pathname,
  822. query: Object.fromEntries(url.searchParams.entries()),
  823. headers: Object.fromEntries(
  824. Object.entries(request.headers).flatMap(([key, value]) => {
  825. if (Array.isArray(value)) return [[key, value.join(",")]];
  826. return typeof value === "string" ? [[key, value]] : [];
  827. }),
  828. ),
  829. };
  830. requests.push(recorded);
  831. return recorded;
  832. }
  833. function sendHtml(response: ServerResponse, html: string) {
  834. response.writeHead(200, {
  835. "content-type": "text/html; charset=utf-8",
  836. "cache-control": "no-store",
  837. });
  838. response.end(html);
  839. }
  840. function sendJson(response: ServerResponse, payload: unknown, statusCode = 200) {
  841. response.writeHead(statusCode, {
  842. "content-type": "application/json; charset=utf-8",
  843. "cache-control": "no-store",
  844. });
  845. response.end(JSON.stringify(payload));
  846. }