coding-plan-team-usage.test.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. BUILTIN_MODEL_PROVIDER_IDS,
  5. TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM,
  6. TID_MODEL_PROVIDER_CONNECTION_MODE_TRIGGER,
  7. TID_MODEL_PROVIDER_NAV_ITEM,
  8. TID_LOGIN_TRIGGER,
  9. TID_CHAT_CONTEXT_USAGE_TRIGGER,
  10. TID_SETTINGS_USAGE_TAB,
  11. TID_SIDEBAR_CODING_PLAN_USAGE_BUTTON,
  12. TID_SETTINGS_PAGE,
  13. TID_SETTINGS_SECTION_NAV,
  14. TID_TASK_SETTINGS_BUTTON,
  15. testId,
  16. type ProviderFamilyConnectionSelection,
  17. } from "@zcode/shared";
  18. import {
  19. DEFAULT_WORKSPACE,
  20. clearAppData,
  21. getE2EAppDataPaths,
  22. quitElectronAppGracefully,
  23. readModelProviders,
  24. waitForDefaultWorkspaceReady,
  25. waitForWorkspaceApp,
  26. } from "./helpers/desktop-app.js";
  27. import { waitForProviderConfigPolling } from "./helpers/provider-config-polling.js";
  28. import { selectRegistryProviderModelById } from "./helpers/upstream-provider.js";
  29. import { seedPersistedModelSelection } from "./helpers/model-provider-restart.js";
  30. import { sel } from "./helpers/selectors.js";
  31. import { skipOccupationOnboardingIfPresent } from "./helpers/occupation-onboarding.js";
  32. // 修复原因:WDIO 为每个 run 注入隔离 HOME,但 os.homedir() 在 Node 进程中不会
  33. // 随环境变量动态变化。沿用 homedir() 会把场景设置和 provider seed 写到开发机的
  34. // ~/.zcode,Electron 读取的却是本轮隔离 HOME;同时新版 Personal Config 文件名是
  35. // provider_config.json,不是旧的 config.json。统一复用 desktop-app 的路径合同,确保
  36. // 测试写入和应用读取的是同一份 fixture。
  37. const E2E_APP_DATA_PATHS = getE2EAppDataPaths();
  38. const E2E_STORAGE_ROOT = E2E_APP_DATA_PATHS.storageRoot;
  39. const SETTINGS_FILE = join(E2E_APP_DATA_PATHS.appDataDir, "setting.json");
  40. const CREDENTIALS_FILE = E2E_APP_DATA_PATHS.credentialsFile;
  41. const TEAM_PLAN_KEY = "team:bigmodel:product-team-a:org-team-a:proj-team-a";
  42. const PERSONAL_PLAN_KEY = "account:bigmodel-individual-coding-plan";
  43. const PERSONAL_PLAN_CONNECTION_KEY = `coding-plan:${PERSONAL_PLAN_KEY}`;
  44. const BIGMODEL_ACCOUNT_NAV_KEY = `preset:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`;
  45. // 与本轮 Builtin catalog 一致;旧 GLM-5.2 已不在 Account Provider 的可选模型中。
  46. const BIGMODEL_E2E_MODEL = "GLM-5.3";
  47. type CodingPlanScenario = "personalOnly" | "teamOnly" | "both";
  48. type CodingPlanFaultMode =
  49. | "none"
  50. | "optionalActivity"
  51. | "quotaBusinessFailure"
  52. | "quotaFailure"
  53. | "startBalance"
  54. | "startBalanceFailure";
  55. type CodingPlanResetScenario =
  56. | "none"
  57. | "emptyThenGrant"
  58. | "existingMultiple"
  59. | "fiveHourUse"
  60. | "multiFiveHourUse"
  61. | "multiFiveHourUseLagging"
  62. | "urgentOpportunity";
  63. describe("Team Plan 设置与使用统计 E2E", () => {
  64. after(async () => {
  65. await browser.electron.restoreAllMocks();
  66. await clearAppData();
  67. });
  68. it("CTP-13: Start balance 限流显示重试,恢复后展示套餐", async function () {
  69. this.timeout(120000);
  70. const evidenceDir =
  71. process.env.ZCODE_E2E_ARTIFACT_DIR || join(process.cwd(), ".e2e-artifacts", "coding-plan");
  72. await mkdir(evidenceDir, { recursive: true });
  73. await prepareScenario(
  74. "personalOnly",
  75. BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  76. "startBalanceFailure",
  77. );
  78. await openModelProviderSettings();
  79. await clickVisibleTestIdByDom(
  80. testId(
  81. TID_MODEL_PROVIDER_NAV_ITEM,
  82. `coding-plan:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  83. ),
  84. {
  85. timeout: 10000,
  86. timeoutMsg: "BigModel 入口缺失",
  87. },
  88. );
  89. await assertBodyTextIncludesAny(["Retry", "重试"]);
  90. await assertBodyTextIncludesAny(["Fetch failed", "获取失败"]);
  91. await browser.saveScreenshot(join(evidenceDir, "coding-plan-start-failure.png"));
  92. await assertBodyTextExcludes([
  93. "Could not verify Coding Plan entitlement. Connect again and retry.",
  94. "暂时无法确认 Coding Plan 权益,请重新连接后再试。",
  95. ]);
  96. await setMockScenario("personalOnly", "startBalance");
  97. // 失败结果也有明确的一秒复用窗口;在窗口结束后验证用户重试恢复。
  98. await browser.pause(1000);
  99. await clickVisibleButtonByText(["Retry", "重试"]);
  100. await assertBodyTextIncludes(["GLM-5-Turbo"]);
  101. await browser.waitUntil(
  102. async () =>
  103. !(await browser.execute(() => document.body.innerText)).match(/Fetch failed|获取失败/),
  104. { timeout: 15000, timeoutMsg: "重试后失败状态未恢复" },
  105. );
  106. await browser.saveScreenshot(join(evidenceDir, "coding-plan-start-recovered.png"));
  107. });
  108. it("CTP-01: 登录后不进入设置页也应获取 Team Plan pricing", async function () {
  109. this.timeout(90000);
  110. await prepareScenario("both", TEAM_PLAN_KEY);
  111. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  112. await waitForMockRequest(
  113. (request) => request.path.endsWith("/subscription/enterprise/v2/pricing"),
  114. "未在不进入设置页时请求企业套餐 pricing",
  115. );
  116. await expect($(sel(TID_SETTINGS_PAGE))).not.toBeDisplayed();
  117. });
  118. it("CTP-02: 设置页连接方式应展示个人 Coding Plan 和 Team Plan", async function () {
  119. this.timeout(120000);
  120. await prepareScenario("both", PERSONAL_PLAN_KEY);
  121. await openModelProviderSettings();
  122. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  123. timeout: 30000,
  124. timeoutMsg: "BigModel 供应商导航项没有出现",
  125. });
  126. await assertConnectionModeOptionsInclude([
  127. {
  128. key: PERSONAL_PLAN_CONNECTION_KEY,
  129. labels: ["Individual Plan", "个人套餐"],
  130. },
  131. { key: TEAM_PLAN_KEY, labels: ["Team Org"] },
  132. ]);
  133. await selectConnectionModeOptionByTestId(
  134. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, TEAM_PLAN_KEY),
  135. "Team Org",
  136. );
  137. await browser.waitUntil(
  138. async () => {
  139. const settings = await readSettings();
  140. const selection = settings.providerFamilyConnectionSelections?.bigmodel;
  141. return (
  142. selection?.kind === "team-coding-plan" &&
  143. selection.productId === "product-team-a" &&
  144. selection.organizationId === "org-team-a" &&
  145. selection.projectId === "proj-team-a"
  146. );
  147. },
  148. {
  149. timeout: 15000,
  150. timeoutMsg: "选择 Team Plan 后没有写入结构化 BigModel connection selection",
  151. },
  152. );
  153. });
  154. for (const locale of ["zh-CN", "en-US"] as const) {
  155. it(`CTP-02B: 侧栏头像旁应显示当前已确认的 Team Plan 标签(${locale})`, async function () {
  156. this.timeout(120000);
  157. await prepareScenario("teamOnly", TEAM_PLAN_KEY, "none", "none", locale);
  158. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  159. const profileTrigger = $(sel(TID_LOGIN_TRIGGER));
  160. await profileTrigger.waitForDisplayed({
  161. timeout: 30000,
  162. timeoutMsg: "侧栏头像入口没有出现",
  163. });
  164. // 英文 UI 的套餐标签为 Team;只断言徽标本身,避免用户名包含团队文字时误通过。
  165. const teamLabel = locale === "zh-CN" ? "团队" : "Team";
  166. const badge = profileTrigger.$(`span[title="${teamLabel}"]`);
  167. await badge.waitForDisplayed({ timeout: 30000 });
  168. await expect(badge).toHaveText(teamLabel);
  169. });
  170. }
  171. it("CTP-03: 用户头像菜单应进入 Team Plan 使用统计并请求团队额度", async function () {
  172. this.timeout(120000);
  173. await prepareScenario("teamOnly", TEAM_PLAN_KEY);
  174. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  175. await openSidebarUsageStats();
  176. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  177. await clickUsageCodingPlanTab(TEAM_PLAN_KEY);
  178. await assertBodyTextIncludes(["Team Org", "90%"]);
  179. await waitForMockRequest(
  180. (request) =>
  181. request.path.endsWith("/api/monitor/usage/quota/limit") &&
  182. request.query.type === "2" &&
  183. request.headers["bigmodel-organization"] === "org-team-a" &&
  184. request.headers["bigmodel-project"] === "proj-team-a",
  185. "头像菜单未按 Team Plan 请求 quota/limit?type=2",
  186. );
  187. });
  188. it("CTP-04: 使用统计编程套餐应显示 Team Plan 额度、模型用量和工具用量", async function () {
  189. this.timeout(120000);
  190. await prepareScenario("teamOnly", TEAM_PLAN_KEY);
  191. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  192. await assertBodyTextIncludes(["Team Org", "90%", "glm-credit-e2e"]);
  193. await assertBodyTextIncludesAny(["Models", "模型"]);
  194. await clickVisibleButtonByText(["Tools", "工具"]);
  195. await assertBodyTextIncludes(["E2E Search MCP"]);
  196. await waitForMockRequest(
  197. (request) =>
  198. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  199. request.query.usageType === "MODEL" &&
  200. request.headers["bigmodel-organization"] === "org-team-a" &&
  201. request.headers["bigmodel-project"] === "proj-team-a",
  202. "使用统计未按 Team Plan 请求 MODEL credit detail",
  203. );
  204. await waitForMockRequest(
  205. (request) =>
  206. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  207. request.query.usageType === "MCP" &&
  208. request.headers["bigmodel-organization"] === "org-team-a" &&
  209. request.headers["bigmodel-project"] === "proj-team-a",
  210. "使用统计未按 Team Plan 请求 MCP credit detail",
  211. );
  212. });
  213. it("CTP-04B: 个人套餐应展示 credit activity、明细与性能数据", async function () {
  214. this.timeout(120000);
  215. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  216. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  217. await assertBodyTextIncludes(["glm-credit-e2e"]);
  218. await assertBodyTextIncludesAny(["Credits total", "积分总数"]);
  219. await clickVisibleButtonByText(["Tools", "工具"]);
  220. await assertBodyTextIncludes(["E2E Search MCP"]);
  221. await waitForMockRequest(
  222. (request) =>
  223. request.path.endsWith("/api/monitor/credit-usage/activity") &&
  224. request.query.type === "1" &&
  225. !request.headers["bigmodel-organization"] &&
  226. !request.headers["bigmodel-project"],
  227. "个人套餐没有请求隔离的 credit activity",
  228. );
  229. await waitForMockRequest(
  230. (request) =>
  231. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  232. request.query.usageType === "MODEL",
  233. "个人套餐没有请求 MODEL credit detail",
  234. );
  235. await waitForMockRequest(
  236. (request) => request.path.endsWith("/api/monitor/usage/model-performance-day"),
  237. "个人套餐没有请求 model performance",
  238. );
  239. });
  240. for (const locale of ["zh-CN", "en-US"] as const) {
  241. it(`CTP-05: 个人/团队套餐组合应跟随当前连接方式展示(${locale})`, async function () {
  242. this.timeout(180000);
  243. await prepareScenario("both", TEAM_PLAN_KEY, "none", "none", locale);
  244. await openModelProviderSettings();
  245. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  246. timeout: 30000,
  247. timeoutMsg: "BigModel 供应商导航项没有出现",
  248. });
  249. await selectConnectionModeOptionByTestId(
  250. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, PERSONAL_PLAN_CONNECTION_KEY),
  251. "个人 Coding Plan",
  252. );
  253. await waitForBigModelConnectionSelection("individual-coding-plan");
  254. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  255. await assertBodyTextIncludes(["70%", "glm-credit-e2e"]);
  256. // 使用统计的个人页签是 Individual Plan,不是设置页左侧的 Coding Plan。
  257. const personalTab = $(sel(testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${PERSONAL_PLAN_KEY}`)));
  258. await expect(personalTab).toHaveText(locale === "zh-CN" ? "个人套餐" : "Individual Plan");
  259. await expect(personalTab).toHaveAttribute("aria-pressed", "true");
  260. await assertBodyTextExcludes(["Team Org"]);
  261. await openModelProviderSettings();
  262. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  263. timeout: 30000,
  264. timeoutMsg: "BigModel 供应商导航项没有出现",
  265. });
  266. await selectConnectionModeOptionByTestId(
  267. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, TEAM_PLAN_KEY),
  268. "Team Org",
  269. );
  270. await waitForBigModelConnectionSelection("team-coding-plan");
  271. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  272. await assertBodyTextIncludes(["Team Org", "90%", "glm-credit-e2e"]);
  273. });
  274. }
  275. it("CTP-06: 启动恢复 OAuth 时应保留已选择的 Team Plan", async function () {
  276. this.timeout(120000);
  277. await prepareScenario("both", TEAM_PLAN_KEY);
  278. await waitForMockRequest(
  279. (request) => request.path.endsWith("/subscription/enterprise/v2/pricing"),
  280. "启动恢复 OAuth 时未请求企业套餐 pricing",
  281. );
  282. await browser.waitUntil(
  283. async () => {
  284. const selection = (await readSettings()).providerFamilyConnectionSelections?.bigmodel;
  285. return (
  286. selection?.kind === "team-coding-plan" &&
  287. selection.productId === "product-team-a" &&
  288. selection.organizationId === "org-team-a" &&
  289. selection.projectId === "proj-team-a"
  290. );
  291. },
  292. {
  293. timeout: 15000,
  294. timeoutMsg: "启动恢复 OAuth 后结构化 Team Plan selection 被覆盖",
  295. },
  296. );
  297. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  298. await waitForMockRequest(
  299. (request) =>
  300. request.path.endsWith("/api/monitor/usage/quota/limit") &&
  301. request.query.type === "2" &&
  302. request.headers["bigmodel-organization"] === "org-team-a" &&
  303. request.headers["bigmodel-project"] === "proj-team-a",
  304. "启动恢复 OAuth 后使用统计未继续按 Team Plan 请求 quota/limit?type=2",
  305. );
  306. });
  307. it("CTP-07: 切换 7d/30d 应重新请求不同日期窗口且保持当前来源", async function () {
  308. this.timeout(120000);
  309. await prepareScenario("both", TEAM_PLAN_KEY);
  310. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  311. await clickVisibleButtonByText(["30 days", "近 30 日"]);
  312. const thirtyDayRequest = await waitForLatestMockRequest(
  313. (request) =>
  314. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  315. request.query.usageType === "MODEL" &&
  316. request.query.type === "3" &&
  317. requestRangeDays(request) === 29,
  318. "切换 30d 后没有请求新的日期窗口",
  319. );
  320. expect(thirtyDayRequest.headers["bigmodel-organization"]).toBe("org-team-a");
  321. expect(thirtyDayRequest.headers["bigmodel-project"]).toBe("proj-team-a");
  322. expect(
  323. daysBetweenMonitorTimes(
  324. requireQueryValue(thirtyDayRequest, "startTime"),
  325. requireQueryValue(thirtyDayRequest, "endTime"),
  326. ),
  327. ).toBe(29);
  328. await clickVisibleButtonByText(["7 days", "近 7 日"]);
  329. await waitForMockRequest(
  330. (request) =>
  331. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  332. request.query.usageType === "MODEL" &&
  333. request.query.type === "3" &&
  334. requestRangeDays(request) === 6,
  335. "切回 7d 后没有恢复对应日期窗口",
  336. );
  337. });
  338. it("CTP-08: 窄窗口下 Usage tabs、range 与热力图仍可操作", async function () {
  339. this.timeout(120000);
  340. await setRendererViewport(430, 760);
  341. try {
  342. // 本 Case 只验证窄窗口交互,不额外绑定“个人 + Team 同时存在时启动恢复
  343. // 自动选择哪个套餐”的产品规则;使用单一个人权益保持夹具职责清晰。
  344. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  345. await setSettingsTheme("zai-dark");
  346. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  347. await clickVisibleButtonByText(["30 days", "近 30 日"]);
  348. await assertBodyTextIncludes(["glm-credit-e2e"]);
  349. await assertBodyTextIncludesAny(["Token activity", "Token 活动"]);
  350. } finally {
  351. await setSettingsTheme("zai-light");
  352. await clearRendererViewport();
  353. }
  354. });
  355. it("CTP-09: activity 可选接口失败不拖垮 quota,刷新后恢复", async function () {
  356. this.timeout(120000);
  357. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "optionalActivity");
  358. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  359. await assertBodyTextIncludes(["70%", "glm-credit-e2e"]);
  360. await assertBodyTextExcludes(["350.7K", "35.1万", "35.1 万"]);
  361. await setMockScenario("personalOnly", "none");
  362. await clickVisibleButtonByText(["Refresh", "刷新"]);
  363. await assertBodyTextIncludesAny(["350.7K", "35.1万", "35.1 万"]);
  364. await waitForMockRequest(
  365. (request) => request.path.endsWith("/api/monitor/credit-usage/activity"),
  366. "activity 恢复后刷新没有重新请求",
  367. );
  368. });
  369. it("CTP-10: Context hover 应按 access freshness 展示同一额度快照", async function () {
  370. this.timeout(120000);
  371. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  372. await selectBigModelCodingPlanRuntime("individual-coding-plan");
  373. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  374. await trigger.waitForDisplayed({
  375. timeout: 15000,
  376. timeoutMsg: "Context usage trigger 没有出现",
  377. });
  378. await trigger.moveTo();
  379. await assertBodyTextIncludes(["70%"]);
  380. await assertBodyTextIncludesAny(["5 hours", "5 小时"]);
  381. await waitForMockRequest(
  382. (request) =>
  383. request.path.endsWith("/api/monitor/usage/quota/limit") && request.query.type !== "2",
  384. "Context access 没有读取个人套餐 quota",
  385. );
  386. });
  387. for (const [scenario, planKey, width] of [
  388. ["personalOnly", PERSONAL_PLAN_KEY, 1200],
  389. ["teamOnly", TEAM_PLAN_KEY, 1200],
  390. ["personalOnly", PERSONAL_PLAN_KEY, 390],
  391. ["teamOnly", TEAM_PLAN_KEY, 390],
  392. ] as const) {
  393. it(`CTP-11: ${scenario} ${width}px quota 失败保留套餐入口,重新进入来源后恢复`, async function () {
  394. this.timeout(120000);
  395. await prepareScenario(scenario, planKey, "quotaBusinessFailure");
  396. await openUsageSection();
  397. await setRendererViewport(width, 900);
  398. // 订阅查询保持成功,quota 业务失败不能撤销权益,确认 tab 不消失;
  399. // 详情加载再切传输失败,覆盖 fatal 文案与后续恢复。
  400. await setMockScenario(scenario, "quotaFailure");
  401. await clickUsageCodingPlanTab(planKey);
  402. await assertBodyTextIncludesAny([
  403. "Unable to load usage stats",
  404. "无法读取用量统计。请稍后重试,或检查网络和供应商配置。",
  405. ]);
  406. await assertBodyTextExcludes(["350.7K", "35.1万", "35.1 万", "glm-credit-e2e"]);
  407. await setMockScenario(scenario, "none");
  408. await clickVisibleTestIdByDom(testId(TID_SETTINGS_USAGE_TAB, "app"), {
  409. timeout: 10000,
  410. timeoutMsg: "致命失败恢复时无法切换到 App Usage",
  411. });
  412. await clickUsageCodingPlanTab(planKey);
  413. await assertBodyTextIncludes([scenario === "teamOnly" ? "90%" : "70%", "glm-credit-e2e"]);
  414. await assertBodyTextIncludesAny(["350.7K", "35.1万", "35.1 万"]);
  415. });
  416. }
  417. it("QR-E2E-01: 空状态应调用 opportunity 并以强制 status 结果展示机会", async function () {
  418. this.timeout(120000);
  419. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "emptyThenGrant");
  420. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  421. await waitForMockRequest(
  422. (request) => request.path.endsWith("/api/v1/coding-plan/reset/opportunity"),
  423. "空 reset 状态没有触发 opportunity",
  424. );
  425. await waitForResetOpportunityCount(1);
  426. const resetPaths = (await readMockRequests())
  427. .map((request) => request.path)
  428. .filter((path) => path.includes("/api/v1/coding-plan/reset/"));
  429. const opportunityIndex = resetPaths.findIndex((path) => path.endsWith("/opportunity"));
  430. expect(opportunityIndex).toBeGreaterThan(0);
  431. expect(resetPaths.slice(opportunityIndex + 1).some((path) => path.endsWith("/status"))).toBe(
  432. true,
  433. );
  434. // QR-E2E-05:单机会徽标同样可点击并打开重置弹框(单机会不展示次数药丸,仅交互升级为按钮)。
  435. await clickResetOpportunityBadge();
  436. await assertBodyTextIncludesAny(["可重置额度", "Resettable quota"]);
  437. await assertBodyTextIncludesAny(["5 小时额度重置", "5-hour quota reset"]);
  438. });
  439. it("QR-E2E-02: 已有多类型机会时仍调用 opportunity,Dialog 只展示 status 权威数量", async function () {
  440. this.timeout(120000);
  441. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  442. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  443. await waitForMockRequest(
  444. (request) => request.path.endsWith("/api/v1/coding-plan/reset/opportunity"),
  445. "已有 reset 机会时没有继续触发 scope opportunity",
  446. );
  447. await waitForResetOpportunityCount(3);
  448. await clickResetOpportunityBadge();
  449. await assertBodyTextIncludesAny(["可重置额度", "Resettable quota"]);
  450. await assertBodyTextIncludesAny(["5 小时额度重置", "5-hour quota reset"]);
  451. await assertBodyTextIncludesAny(["周额度重置", "Weekly quota reset"]);
  452. // 次数不再汇总到标题;FIVE_HOUR 持有 2 张机会,改由该行的次数药丸展示。
  453. await assertBodyTextIncludesAny(["2 次", "×2"]);
  454. });
  455. it("QR-E2E-09: Composer 应常驻展示首次机会提醒并在 hover 后收起", async function () {
  456. this.timeout(120000);
  457. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  458. await reloadRendererWithBigModelCodingPlanSelection();
  459. await waitForContextResetReminder("initial", ["3 次重置额度", "3 reset available"]);
  460. await assertContextReminderHiddenInSettings("initial");
  461. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  462. await trigger.moveTo();
  463. await browser.waitUntil(async () => !(await isContextResetReminderVisible("initial")), {
  464. timeout: 10000,
  465. timeoutMsg: "打开 Context 后首次 reset opportunity 提醒仍未收起",
  466. });
  467. });
  468. it("QR-E2E-10: 最早机会进入最后三分钟时应常驻展示临期提醒", async function () {
  469. this.timeout(120000);
  470. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "urgentOpportunity");
  471. await reloadRendererWithBigModelCodingPlanSelection();
  472. await waitForContextResetReminder("urgent", ["重置额度过期", "Reset expires in"]);
  473. await assertContextReminderHiddenInSettings("urgent");
  474. const alarmAnimation = await browser.execute(() => {
  475. const icon = document.querySelector<HTMLElement>(
  476. '[data-context-reset-reminder="urgent"] .animate-zcode-alarm-ring',
  477. );
  478. return icon ? window.getComputedStyle(icon).animationName : null;
  479. });
  480. expect(alarmAnimation).toBe("zcode-alarm-ring");
  481. });
  482. it("QR-E2E-04: Composer Dialog 打开期间应保持 HoverCard 生命周期", async function () {
  483. this.timeout(120000);
  484. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  485. await selectBigModelCodingPlanRuntime("individual-coding-plan");
  486. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  487. await trigger.waitForDisplayed({
  488. timeout: 15000,
  489. timeoutMsg: "Context usage trigger 没有出现",
  490. });
  491. await trigger.moveTo();
  492. await waitForResetOpportunityCount(3, '[data-slot="hover-card-content"]');
  493. await clickResetOpportunityBadge('[data-slot="hover-card-content"]');
  494. await browser.waitUntil(
  495. async () => {
  496. const state = await readQuotaResetOverlayState();
  497. return state.dialogVisible && state.hoverCardVisible;
  498. },
  499. {
  500. timeout: 10000,
  501. timeoutMsg: "重置 Dialog 打开后 Composer HoverCard 被提前卸载",
  502. },
  503. );
  504. await browser.keys("Escape");
  505. await browser.waitUntil(
  506. async () => {
  507. const state = await readQuotaResetOverlayState();
  508. return !state.dialogVisible && !state.hoverCardVisible;
  509. },
  510. {
  511. timeout: 10000,
  512. timeoutMsg: "关闭重置 Dialog 后 Composer HoverCard 没有一起收起",
  513. },
  514. );
  515. });
  516. it("QR-E2E-03: FIVE_HOUR use 必须等待 status used_at 后才完成", async function () {
  517. this.timeout(120000);
  518. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "fiveHourUse");
  519. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  520. await waitForResetOpportunityCount(2);
  521. await clickResetOpportunityBadge();
  522. const resetButton = await findVisibleButtonByAriaLabels(
  523. ["重置 5 小时额度", "Reset 5-hour quota"],
  524. true,
  525. '[role="dialog"]',
  526. );
  527. if (!resetButton) throw new Error("没有找到 FIVE_HOUR reset 按钮");
  528. await resetButton.click();
  529. await waitForMockRequest(
  530. (request) =>
  531. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  532. isRecord(request.body) &&
  533. request.body.reset_type === "FIVE_HOUR",
  534. "五小时重置没有发送 reset_type=FIVE_HOUR",
  535. );
  536. // 双 JWT 契约:Authorization 传 Bearer zcode JWT,X-Bigmodel-Authorization 直传 MaaS JWT。
  537. const useRequest = (await readMockRequests()).find((request) =>
  538. request.path.endsWith("/api/v1/coding-plan/reset/use"),
  539. );
  540. expect(useRequest?.headers.authorization).toBe("Bearer e2e-zcode-jwt");
  541. expect(useRequest?.headers["x-bigmodel-authorization"]).toBe("e2e-bigmodel-oauth-token");
  542. // 时序约束:客户端 use 后的 status 确认重试窗口只有约 2.5 秒,confirm 前的每次检查
  543. // 必须是单次 execute 往返,不能逐按钮发 WebDriver 命令,否则慢机器上会先触发客户端
  544. // 失败分支,confirm 之后成功态永远不会出现。
  545. const processingState = await readDialogResetState();
  546. if (processingState.resetDisabled !== true || processingState.successVisible) {
  547. throw new Error(
  548. `status used_at 未确认前没有保持 processing: ${JSON.stringify(processingState)}`,
  549. );
  550. }
  551. await confirmResetUse();
  552. await browser.waitUntil(async () => (await readDialogResetState()).successVisible, {
  553. interval: 100,
  554. timeout: 10000,
  555. timeoutMsg: "status used_at 更新后没有显示成功状态",
  556. });
  557. await waitForMockRequest(
  558. (request) => request.path.endsWith("/api/v1/coding-plan/reset/history/read"),
  559. "确认 reset used_at 后没有上报 history/read",
  560. );
  561. });
  562. it("QR-E2E-14: 同类型多张机会核销一张后,弹框不重开即可展示并核销余下机会", async function () {
  563. this.timeout(120000);
  564. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "multiFiveHourUse");
  565. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  566. await waitForResetOpportunityCount(3);
  567. await clickResetOpportunityBadge();
  568. await assertBodyTextIncludesAny(["2 次", "×2"]);
  569. await clickDialogFiveHourReset("没有找到 FIVE_HOUR reset 按钮");
  570. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 1, {
  571. timeout: 10000,
  572. timeoutMsg: "第一次五小时重置没有发送 /use",
  573. });
  574. // 回归点:成功反馈结束后该行留在弹框内,直接展示余下 1 张的真实倒计时并恢复可点击;
  575. // 旧实现在这里显示「0 分 0 秒后过期」,且再次点击被静默忽略,只能关闭重开弹框。
  576. await waitForDialogResetState(
  577. (state) =>
  578. state.resetDisabled === false &&
  579. !state.successVisible &&
  580. state.weekResetVisible &&
  581. state.resetRowText !== null &&
  582. !["2 次", "×2", "0 分 0 秒", "0m 0s"].some((text) => state.resetRowText?.includes(text)),
  583. "核销一张后余下机会没有在弹框内直接恢复为可核销",
  584. );
  585. await clickDialogFiveHourReset("核销一张后没有找到余下机会的 FIVE_HOUR reset 按钮");
  586. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 2, {
  587. timeout: 10000,
  588. timeoutMsg: "余下机会的再次点击没有真实发送 /use",
  589. });
  590. const idempotencyKeys = (await readFiveHourUseRequests()).map((request) =>
  591. isRecord(request.body) ? request.body.idempotency_key : undefined,
  592. );
  593. expect(new Set(idempotencyKeys).size).toBe(2);
  594. // 机会耗尽后五小时行收起,周额度行不受影响、也不会被误核销。
  595. await waitForDialogResetState(
  596. (state) => state.resetDisabled === null && !state.successVisible && state.weekResetVisible,
  597. "五小时机会耗尽后该行没有收起",
  598. );
  599. expect(
  600. (await readMockRequests()).some(
  601. (request) =>
  602. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  603. isRecord(request.body) &&
  604. request.body.reset_type === "WEEK",
  605. ),
  606. ).toBe(false);
  607. });
  608. it("QR-E2E-15: 完成态再次核销时 status 仍是上一张 used_at,读到新 used_at 才确认成功", async function () {
  609. this.timeout(120000);
  610. // mock 让 /use 结果延迟 600ms 才在 /status 可见,窗口内 /status 仍返回上一张的 used_at。
  611. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "multiFiveHourUseLagging");
  612. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  613. await waitForResetOpportunityCount(3);
  614. await clickResetOpportunityBadge();
  615. await assertBodyTextIncludesAny(["2 次", "×2"]);
  616. await clickDialogFiveHourReset("没有找到 FIVE_HOUR reset 按钮");
  617. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 1, {
  618. timeout: 10000,
  619. timeoutMsg: "第一次五小时重置没有发送 /use",
  620. });
  621. await waitForDialogResetState(
  622. (state) => state.resetDisabled === false && !state.successVisible && state.weekResetVisible,
  623. "第一次核销后余下机会没有恢复为可核销",
  624. );
  625. await clickDialogFiveHourReset("核销一张后没有找到余下机会的 FIVE_HOUR reset 按钮");
  626. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 2, {
  627. timeout: 10000,
  628. timeoutMsg: "余下机会的再次点击没有真实发送 /use",
  629. });
  630. // 回归点:旧实现把滞后快照里上一张的 used_at 当作第二次成功,提前播放成功反馈后该行
  631. // 回到「余 1 张可点击」,直到下一次 60s 轮询才收起。修复后保持处理中,读到新 used_at 才完成。
  632. let revertedToClickable = false;
  633. await waitForDialogResetState((state) => {
  634. revertedToClickable ||= state.resetDisabled === false;
  635. return state.resetDisabled === null && !state.successVisible && state.weekResetVisible;
  636. }, "完成态再次核销后五小时行没有随机会耗尽收起");
  637. expect(revertedToClickable).toBe(false);
  638. expect(await readFiveHourUseRequests()).toHaveLength(2);
  639. });
  640. });
  641. async function prepareScenario(
  642. scenario: CodingPlanScenario,
  643. bigmodelSelectedKey: string,
  644. faultMode: CodingPlanFaultMode = "none",
  645. resetScenario: CodingPlanResetScenario = "none",
  646. locale?: "zh-CN" | "en-US",
  647. ) {
  648. // 修复原因:同一 spec 会连续切换个人/团队套餐场景。必须在旧 Electron 退出前清理
  649. // file:// origin 的 entitlement 缓存;退出后再执行 browser.execute 会被异常吞掉,
  650. // 上一场景的 Team 快照就会污染下一场景。
  651. await clearUsageEntitlementCache();
  652. // Bug 根因:旧 Electron/host 仍存活时直接改 setting.json,退出阶段的异步写回
  653. // 会把下一场景的夹具覆盖成上一场景。先等进程完整退出,再写持久化夹具,最后
  654. // 让 reloadSession 只负责创建新应用,场景边界才是确定的。
  655. await quitElectronAppGracefully();
  656. await setMockScenario(scenario, faultMode);
  657. await setResetMockScenario(resetScenario);
  658. await writeCredentials({
  659. "oauth:active_provider": "bigmodel",
  660. "oauth:bigmodel:access_token": "e2e-bigmodel-oauth-token",
  661. "oauth:bigmodel:user_info": JSON.stringify({
  662. displayName: "BigModel E2E",
  663. id: "bigmodel-e2e-user",
  664. username: "bigmodel-e2e-user",
  665. }),
  666. zcodejwttoken:
  667. resetScenario === "none" && !faultMode.startsWith("startBalance") ? "" : "e2e-zcode-jwt",
  668. });
  669. const connectionSelection = parseBigModelConnectionSelection(bigmodelSelectedKey);
  670. await writeSettings({
  671. ...(locale ? { locale, localePreference: locale } : {}),
  672. providerFamilyConnectionSelections: {
  673. bigmodel: connectionSelection,
  674. },
  675. providerFamilyDomain: "bigmodel",
  676. providerFamilyDomainMigrated: true,
  677. // Bug 根因:同一 spec 多次 reloadSession 会继承前一场景关闭时写回的 workspace。
  678. // Team Plan case 的 model-resolution seed 明确写 DEFAULT_WORKSPACE,因此启动入口也
  679. // 必须固定到同一个 project workspace,不能偶发落入 conversation workspace。
  680. lastWorkspaceSession: [
  681. {
  682. kind: "local",
  683. workspacePath: DEFAULT_WORKSPACE,
  684. workspacePurpose: "project",
  685. },
  686. ],
  687. lastActiveTabIndex: 0,
  688. });
  689. // 修复原因:Electron E2E 的 file:// renderer 直接 browser.refresh()
  690. // 偶发落到 chrome-error://chromewebdata,后续等待会每条 case 慢 30s。
  691. // 场景切换需要让 main/host 重新读取磁盘设置,因此使用 reloadSession 重建应用。
  692. await browser.reloadSession();
  693. // Escape 只临时关闭职业引导;重载 Renderer 会再次遮住 Composer。
  694. // 复用真实 Skip 流程完成隔离账号的引导,保证重载类 case 的前置状态持久化。
  695. await skipOccupationOnboardingIfPresent();
  696. await waitForDefaultWorkspaceReady(60000);
  697. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  698. await closeTransientOverlays();
  699. await waitForProviderConfigPolling();
  700. }
  701. function parseBigModelConnectionSelection(selectedKey: string) {
  702. if (selectedKey === BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan)
  703. return { kind: "start-plan" as const };
  704. const parts = selectedKey.split(":");
  705. if (parts[0] !== "team") {
  706. return { kind: "individual-coding-plan" as const };
  707. }
  708. const [, family, productId, organizationId, projectId] = parts;
  709. if (family !== "bigmodel" || !productId || !organizationId || !projectId) {
  710. throw new Error(`无效 Team Plan key: ${selectedKey}`);
  711. }
  712. return {
  713. kind: "team-coding-plan" as const,
  714. productId,
  715. organizationId,
  716. projectId,
  717. };
  718. }
  719. async function waitForBigModelConnectionSelection(
  720. kind: "individual-coding-plan" | "team-coding-plan",
  721. ) {
  722. await browser.waitUntil(
  723. async () => (await readSettings()).providerFamilyConnectionSelections?.bigmodel?.kind === kind,
  724. {
  725. timeout: 15000,
  726. timeoutMsg: `BigModel 连接方式没有收敛到 ${kind}`,
  727. },
  728. );
  729. await waitForProviderConfigPolling();
  730. }
  731. async function clearUsageEntitlementCache() {
  732. // 修复原因:本 spec 会在同一 file:// origin 内切换 personalOnly/teamOnly mock。
  733. // useUsageEntitlement 的短 TTL localStorage 缓存会保留上个场景的 no_plan,
  734. // 导致下一次打开 Usage 页时 Coding Plan tab 被误判为不存在。
  735. try {
  736. await browser.execute(() => {
  737. const prefix = "zcode:usage-entitlement:";
  738. for (const key of Object.keys(window.localStorage)) {
  739. if (key.startsWith(prefix)) {
  740. window.localStorage.removeItem(key);
  741. }
  742. }
  743. });
  744. } catch {
  745. // reloadSession 前后偶发没有可执行 renderer;缓存清理失败不阻塞场景重建。
  746. }
  747. }
  748. async function openModelProviderSettings() {
  749. await closeTransientOverlays();
  750. await ensureSettingsPageOpen();
  751. await clickVisibleTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "modelProvider"), {
  752. timeout: 10000,
  753. timeoutMsg: "设置页没有出现模型供应商分区入口",
  754. });
  755. }
  756. async function assertConnectionModeOptionsInclude(
  757. expectedOptions: Array<{ key: string; labels: string[] }>,
  758. ) {
  759. await openConnectionModeSelect();
  760. try {
  761. for (const expectedOption of expectedOptions) {
  762. const optionTestId = testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, expectedOption.key);
  763. const option = await $(sel(optionTestId));
  764. await option.waitForDisplayed({
  765. timeout: 10000,
  766. timeoutMsg: `没有找到连接方式选项: ${optionTestId}`,
  767. });
  768. const optionText = await option.getText();
  769. expect(expectedOption.labels.some((label) => optionText.includes(label))).toBe(true);
  770. }
  771. } finally {
  772. await browser.keys("Escape");
  773. }
  774. }
  775. async function selectConnectionModeOptionByTestId(optionTestId: string, labelForError: string) {
  776. await openConnectionModeSelect();
  777. const option = await $(sel(optionTestId));
  778. await option.waitForDisplayed({
  779. timeout: 10000,
  780. timeoutMsg: `没有找到连接方式选项: ${labelForError}`,
  781. });
  782. await option.click();
  783. }
  784. async function openConnectionModeSelect() {
  785. await clickVisibleTestIdByDom(TID_MODEL_PROVIDER_CONNECTION_MODE_TRIGGER, {
  786. timeout: 10000,
  787. timeoutMsg: "连接方式选择器没有出现",
  788. });
  789. }
  790. async function openUsageCodingPlanTab(sourceId?: string) {
  791. await openUsageSection();
  792. await clickUsageCodingPlanTab(sourceId);
  793. await assertBodyTextIncludesAny(["剩余额度", "Quota remaining", "Quota Remaining"]);
  794. }
  795. async function openUsageSection() {
  796. await closeTransientOverlays();
  797. await ensureSettingsPageOpen();
  798. await clickVisibleTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "usage"), {
  799. timeout: 10000,
  800. timeoutMsg: "设置页没有出现使用统计分区入口",
  801. });
  802. }
  803. async function ensureSettingsPageOpen() {
  804. const settingsPage = $(sel(TID_SETTINGS_PAGE));
  805. if (!(await settingsPage.isDisplayed().catch(() => false))) {
  806. // Bug 根因:设置新架构会同时保留响应式导航的隐藏副本,旧 helper 取第一个
  807. // test-id 时可能点中不可见节点并关闭设置页,导致后续误报 Coding Plan tab 消失。
  808. await clickVisibleTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  809. timeout: 10000,
  810. timeoutMsg: "没有找到设置入口按钮",
  811. });
  812. await settingsPage.waitForDisplayed({ timeout: 10000 });
  813. }
  814. }
  815. async function openSidebarUsageStats() {
  816. await closeTransientOverlays();
  817. await clickVisibleTestIdByDom(TID_LOGIN_TRIGGER, {
  818. timeout: 10000,
  819. timeoutMsg: "没有找到头像菜单入口",
  820. });
  821. await clickVisibleTestIdByDom(TID_SIDEBAR_CODING_PLAN_USAGE_BUTTON, {
  822. timeout: 10000,
  823. timeoutMsg: "没有找到头像菜单里的使用统计入口",
  824. });
  825. }
  826. async function closeTransientOverlays() {
  827. await browser.keys("Escape");
  828. await browser.pause(100);
  829. }
  830. async function clickUsageCodingPlanTab(sourceId?: string) {
  831. // 修复原因:使用统计页从单个 "codingPlan" tab 改为按来源生成
  832. // "codingPlan:<sourceId>",测试不能再写死旧 test id。
  833. const staticTabId = testId(TID_SETTINGS_USAGE_TAB, "codingPlan");
  834. const prefix = `${testId(TID_SETTINGS_USAGE_TAB, "codingPlan:")}`;
  835. const preferredTabId = sourceId ? testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${sourceId}`) : null;
  836. let selectedTestId = "";
  837. try {
  838. await browser.waitUntil(
  839. async () => {
  840. selectedTestId = (await browser.execute(
  841. (legacyTestId, dynamicPrefix, targetTestId) => {
  842. const candidates = Array.from(
  843. document.querySelectorAll<HTMLElement>("[data-testid]"),
  844. ).filter((element) => {
  845. const current = element.dataset.testid ?? "";
  846. return current === legacyTestId || current.startsWith(dynamicPrefix);
  847. });
  848. // 修复原因:传入 sourceId 时验证的就是该套餐身份。旧 helper
  849. // 找不到目标时会静默点击第一个可见 tab,把“个人套餐缺失”伪装成
  850. // 后续 Team 数据断言失败。指定目标时必须精确命中。
  851. const ordered = targetTestId
  852. ? candidates.filter((element) => element.dataset.testid === targetTestId)
  853. : candidates;
  854. const visible = ordered.find((element) => {
  855. const style = window.getComputedStyle(element);
  856. return !(
  857. style.display === "none" ||
  858. style.visibility === "hidden" ||
  859. Number(style.opacity) === 0 ||
  860. element.getClientRects().length === 0 ||
  861. element.closest('[aria-hidden="true"], [hidden]')
  862. );
  863. });
  864. return visible?.dataset.testid ?? "";
  865. },
  866. staticTabId,
  867. prefix,
  868. preferredTabId,
  869. )) as string;
  870. return Boolean(selectedTestId);
  871. },
  872. {
  873. timeout: 30000,
  874. timeoutMsg: "设置页没有出现使用统计 Coding Plan tab",
  875. },
  876. );
  877. const tab = await $(sel(selectedTestId));
  878. await tab.click();
  879. } catch (error) {
  880. throw new Error(
  881. `设置页没有出现或无法激活 Coding Plan tab: ${selectedTestId}\n${await collectCodingPlanUsageDiagnostics()}`,
  882. { cause: error },
  883. );
  884. }
  885. }
  886. async function setRendererViewport(width: number, height: number) {
  887. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  888. deviceScaleFactor: 1,
  889. height,
  890. mobile: false,
  891. width,
  892. });
  893. await browser.waitUntil(
  894. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  895. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  896. );
  897. }
  898. async function setSettingsTheme(theme: "zai-light" | "zai-dark") {
  899. const changed = await browser.execute((nextTheme) => {
  900. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  901. .__testActions;
  902. const setTheme = actions?.setTheme;
  903. if (typeof setTheme !== "function") return false;
  904. (setTheme as (value: string) => void)(nextTheme);
  905. return true;
  906. }, theme);
  907. expect(changed).toBe(true);
  908. }
  909. async function clearRendererViewport() {
  910. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  911. }
  912. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  913. const sent = await browser.electron.execute(
  914. async (electron, command, commandParams) => {
  915. const window = electron.BrowserWindow.getAllWindows().find(
  916. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  917. );
  918. if (!window) return false;
  919. const devtools = window.webContents.debugger;
  920. if (!devtools.isAttached()) devtools.attach("1.3");
  921. await devtools.sendCommand(command, commandParams);
  922. return true;
  923. },
  924. method,
  925. params,
  926. );
  927. expect(sent).toBe(true);
  928. }
  929. async function collectCodingPlanUsageDiagnostics() {
  930. const providers = (await readModelProviders()).map((provider) => ({
  931. id: provider.id,
  932. enabled: provider.enabled,
  933. hasApiKey: provider.apiKey.trim().length > 0,
  934. systemDisabledReason: provider.systemDisabledReason ?? null,
  935. }));
  936. const requests = (await readMockRequests()).map((request) => ({
  937. path: request.path,
  938. query: request.query,
  939. organization: request.headers["bigmodel-organization"] ?? null,
  940. project: request.headers["bigmodel-project"] ?? null,
  941. }));
  942. return `诊断: ${JSON.stringify(
  943. {
  944. bodyText: (await getBodyText()).slice(0, 2000),
  945. providers,
  946. requests,
  947. },
  948. null,
  949. 2,
  950. )}`;
  951. }
  952. async function clickVisibleTestIdByDom(
  953. currentTestId: string,
  954. { timeout = 10000, timeoutMsg = `页面没有可见的 test id: ${currentTestId}` } = {},
  955. ) {
  956. // 修复原因:头像菜单内容用了 forceMount,隐藏菜单项也会留在 DOM 里。
  957. // 这里必须等真正可见的菜单项再触发,否则会点到隐藏节点。
  958. let latestReason = "not-started";
  959. await browser.waitUntil(
  960. async () => {
  961. const result = (await browser.execute((targetTestId) => {
  962. function isVisible(element: HTMLElement) {
  963. const style = window.getComputedStyle(element);
  964. if (
  965. style.display === "none" ||
  966. style.visibility === "hidden" ||
  967. Number(style.opacity) === 0
  968. ) {
  969. return false;
  970. }
  971. if (element.getClientRects().length === 0) {
  972. return false;
  973. }
  974. return !element.closest('[aria-hidden="true"], [hidden]');
  975. }
  976. function dispatchE2EActivation(element: HTMLElement) {
  977. element.focus();
  978. const pointerEventCtor = window.PointerEvent ?? MouseEvent;
  979. for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
  980. const event =
  981. type.startsWith("pointer") && pointerEventCtor === window.PointerEvent
  982. ? new PointerEvent(type, {
  983. bubbles: true,
  984. cancelable: true,
  985. pointerId: 1,
  986. pointerType: "mouse",
  987. isPrimary: true,
  988. })
  989. : new MouseEvent(type, {
  990. bubbles: true,
  991. cancelable: true,
  992. view: window,
  993. });
  994. element.dispatchEvent(event);
  995. }
  996. }
  997. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  998. (item) => item.dataset.testid === targetTestId && isVisible(item),
  999. );
  1000. if (!element) {
  1001. return { clicked: false, reason: "missing-visible" };
  1002. }
  1003. const disabled =
  1004. (element instanceof HTMLButtonElement ||
  1005. element instanceof HTMLInputElement ||
  1006. element instanceof HTMLSelectElement ||
  1007. element instanceof HTMLTextAreaElement) &&
  1008. element.disabled;
  1009. if (disabled) {
  1010. return { clicked: false, reason: "disabled" };
  1011. }
  1012. dispatchE2EActivation(element);
  1013. return { clicked: true };
  1014. }, currentTestId)) as { clicked: boolean; reason?: string };
  1015. latestReason = result.reason ?? "clicked";
  1016. return result.clicked;
  1017. },
  1018. {
  1019. timeout,
  1020. timeoutMsg: `${timeoutMsg}: ${latestReason}`,
  1021. },
  1022. );
  1023. }
  1024. async function selectBigModelCodingPlanRuntime(
  1025. planKind: "individual-coding-plan" | "team-coding-plan" = "individual-coding-plan",
  1026. ) {
  1027. const providerId =
  1028. planKind === "team-coding-plan"
  1029. ? "account:bigmodel-team-coding-plan"
  1030. : "account:bigmodel-individual-coding-plan";
  1031. // Bug 根因:只写 selectedSupplierKey 只更新了供应商导航解析状态,并不会更新
  1032. // Composer 的 Effective Model。Context 用量按真实 Effective Provider 判断套餐类型,
  1033. // 因此测试必须和用户一样完成一次 Provider/Model 选择。
  1034. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  1035. includePlainModelFallback: false,
  1036. providerId,
  1037. providerName: "BigModel Coding Plan",
  1038. });
  1039. }
  1040. async function reloadRendererWithBigModelCodingPlanSelection() {
  1041. // Bug 根因:QR-09/10 验证的是 Renderer 首次挂载时的常驻提醒。通过模型菜单选择会
  1042. // 产生提醒外部 pointerdown,从而按产品规则把刚出现的提醒标记为已读;在退出应用前
  1043. // seed 又会被旧 Renderer 的关闭写回覆盖。直接写正式选择存储并只重载 Renderer,
  1044. // 既使用真实 ModelSelection,又不引入测试专用运行时入口或额外 Host 重启。
  1045. await seedPersistedModelSelection({
  1046. modelId: BIGMODEL_E2E_MODEL,
  1047. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1048. reasoningLevel: "max",
  1049. });
  1050. await browser.execute(() => window.location.reload());
  1051. await waitForDefaultWorkspaceReady(60000);
  1052. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1053. await waitForProviderConfigPolling();
  1054. // Bug 根因:直接写 recent selection 只覆盖了草稿的持久化入口;如果当前
  1055. // ModelSelectionView 尚未包含该 Account Provider,Composer 会按现有契约回退到
  1056. // preferredSelection。先通过真实选择控件完成一次有效选择,再重载一次,验证的才是
  1057. // 用户实际会走的 selection -> opportunity 链路,而不是测试专用的 localStorage 假设。
  1058. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  1059. includePlainModelFallback: false,
  1060. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1061. providerName: "BigModel Coding Plan",
  1062. });
  1063. await browser.execute(() => window.location.reload());
  1064. await waitForDefaultWorkspaceReady(60000);
  1065. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1066. await waitForProviderConfigPolling();
  1067. }
  1068. async function setMockScenario(
  1069. scenario: CodingPlanScenario,
  1070. faultMode: CodingPlanFaultMode = "none",
  1071. ) {
  1072. const baseUrl = getMockBaseUrl();
  1073. const response = await fetch(`${baseUrl}/__e2e/coding-plan/scenario`, {
  1074. method: "POST",
  1075. headers: { "content-type": "application/json" },
  1076. body: JSON.stringify({
  1077. faultMode,
  1078. scenario,
  1079. providerResponsive: faultMode.startsWith("startBalance"),
  1080. }),
  1081. });
  1082. if (!response.ok) {
  1083. throw new Error(`切换 Coding Plan mock scenario 失败: ${response.status}`);
  1084. }
  1085. }
  1086. async function setResetMockScenario(resetScenario: CodingPlanResetScenario) {
  1087. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/reset-scenario`, {
  1088. method: "POST",
  1089. headers: { "content-type": "application/json" },
  1090. body: JSON.stringify({ resetScenario }),
  1091. });
  1092. if (!response.ok) {
  1093. throw new Error(`切换 Coding Plan reset mock scenario 失败: ${response.status}`);
  1094. }
  1095. }
  1096. async function confirmResetUse() {
  1097. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/reset-confirm-use`, {
  1098. method: "POST",
  1099. });
  1100. if (!response.ok) {
  1101. throw new Error(`确认 Coding Plan reset use 失败: ${response.status}`);
  1102. }
  1103. }
  1104. async function waitForResetOpportunityCount(count: number, rootSelector?: string) {
  1105. await browser.waitUntil(
  1106. async () => {
  1107. const labels = (await browser.execute((root: string | undefined) => {
  1108. const scope = root ? document.querySelector(root) : document;
  1109. return Array.from(
  1110. scope?.querySelectorAll<HTMLElement>('[data-reset-opportunity="true"]') ?? [],
  1111. )
  1112. .filter((element) => {
  1113. const style = window.getComputedStyle(element);
  1114. return (
  1115. style.display !== "none" &&
  1116. style.visibility !== "hidden" &&
  1117. element.getClientRects().length > 0
  1118. );
  1119. })
  1120. .map((element) => element.innerText.trim());
  1121. }, rootSelector)) as string[];
  1122. return labels.some((label) => label.includes(String(count)));
  1123. },
  1124. {
  1125. timeout: 10000,
  1126. timeoutMsg: `没有展示 ${count} 次 reset opportunity`,
  1127. },
  1128. );
  1129. }
  1130. async function clickResetOpportunityBadge(rootSelector?: string) {
  1131. const selector = rootSelector
  1132. ? `${rootSelector} [data-reset-opportunity="true"]`
  1133. : '[data-reset-opportunity="true"]';
  1134. for (const badge of await $$(selector)) {
  1135. if (await badge.isDisplayed()) {
  1136. await badge.click();
  1137. return;
  1138. }
  1139. }
  1140. throw new Error("没有找到可点击的 reset opportunity 徽标");
  1141. }
  1142. async function isContextResetReminderVisible(phase: "initial" | "urgent") {
  1143. return browser.execute((currentPhase) => {
  1144. const element = document.querySelector<HTMLElement>(
  1145. `[data-context-reset-reminder="${currentPhase}"]`,
  1146. );
  1147. if (!element) return false;
  1148. const style = window.getComputedStyle(element);
  1149. return (
  1150. style.display !== "none" &&
  1151. style.visibility !== "hidden" &&
  1152. element.getClientRects().length > 0
  1153. );
  1154. }, phase);
  1155. }
  1156. async function waitForContextResetReminder(phase: "initial" | "urgent", expectedTexts: string[]) {
  1157. try {
  1158. await browser.waitUntil(
  1159. async () => {
  1160. if (!(await isContextResetReminderVisible(phase))) return false;
  1161. const text = (await browser.execute((currentPhase) => {
  1162. return (
  1163. document.querySelector<HTMLElement>(`[data-context-reset-reminder="${currentPhase}"]`)
  1164. ?.innerText ?? ""
  1165. );
  1166. }, phase)) as string;
  1167. return expectedTexts.some((expected) => text.includes(expected));
  1168. },
  1169. {
  1170. timeout: 15000,
  1171. timeoutMsg: `没有展示 ${phase} reset opportunity reminder`,
  1172. },
  1173. );
  1174. } catch (error) {
  1175. // Bug 调查:提醒缺失不能只留下一个 waitUntil 超时。机会接口、Context 触发器和
  1176. // 实际 DOM 一并进入失败证据,才能区分“没有数据”和“已有机会但提醒被收起”。
  1177. const reminderDiagnostics = await browser.execute(
  1178. (contextTriggerTestId) => ({
  1179. bodyText: document.body?.innerText?.slice(-2500) ?? "",
  1180. contextTriggerVisible: Array.from(
  1181. document.querySelectorAll<HTMLElement>(`[data-testid="${contextTriggerTestId}"]`),
  1182. ).some((element) => element.getClientRects().length > 0),
  1183. opportunityBadges: Array.from(
  1184. document.querySelectorAll<HTMLElement>('[data-reset-opportunity="true"]'),
  1185. ).map((element) => ({
  1186. text: element.innerText,
  1187. visible: element.getClientRects().length > 0,
  1188. })),
  1189. reminders: Array.from(
  1190. document.querySelectorAll<HTMLElement>("[data-context-reset-reminder]"),
  1191. ).map((element) => ({
  1192. phase: element.dataset.contextResetReminder ?? null,
  1193. text: element.innerText,
  1194. visible: element.getClientRects().length > 0,
  1195. })),
  1196. }),
  1197. TID_CHAT_CONTEXT_USAGE_TRIGGER,
  1198. );
  1199. const resetRequests = (await readMockRequests())
  1200. .filter((request) => request.path.includes("/coding-plan/reset/"))
  1201. .map((request) => ({ method: request.method, path: request.path }));
  1202. throw new Error(
  1203. `没有展示 ${phase} reset opportunity reminder\n诊断: ${JSON.stringify(
  1204. { reminderDiagnostics, resetRequests },
  1205. null,
  1206. 2,
  1207. )}`,
  1208. { cause: error },
  1209. );
  1210. }
  1211. }
  1212. async function readQuotaResetOverlayState() {
  1213. return browser.execute(() => {
  1214. const isVisible = (element: Element | null) => {
  1215. if (!(element instanceof HTMLElement)) return false;
  1216. const style = window.getComputedStyle(element);
  1217. return (
  1218. style.display !== "none" &&
  1219. style.visibility !== "hidden" &&
  1220. element.getClientRects().length > 0
  1221. );
  1222. };
  1223. return {
  1224. dialogVisible: isVisible(document.querySelector('[role="dialog"]')),
  1225. hoverCardVisible: isVisible(document.querySelector('[data-slot="hover-card-content"]')),
  1226. };
  1227. });
  1228. }
  1229. async function findVisibleButtonByAriaLabels(
  1230. labels: string[],
  1231. required = true,
  1232. rootSelector?: string,
  1233. ) {
  1234. const selector = rootSelector ? `${rootSelector} button` : "button";
  1235. for (const button of await $$(selector)) {
  1236. if (!(await button.isDisplayed())) continue;
  1237. const ariaLabel = await button.getAttribute("aria-label");
  1238. if (ariaLabel && labels.includes(ariaLabel)) return button;
  1239. }
  1240. if (required) throw new Error(`找不到按钮: ${labels.join("/")}`);
  1241. return undefined;
  1242. }
  1243. /** 单次 execute 往返读取弹框内 FIVE_HOUR 重置按钮与成功态;QR-E2E-03 的 confirm
  1244. * 窗口只有约 2.5 秒,逐按钮 isDisplayed/getAttribute 的多次 WebDriver 往返会超窗。 */
  1245. async function readFiveHourUseRequests() {
  1246. return (await readMockRequests()).filter(
  1247. (request) =>
  1248. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  1249. isRecord(request.body) &&
  1250. request.body.reset_type === "FIVE_HOUR",
  1251. );
  1252. }
  1253. async function clickDialogFiveHourReset(missingMessage: string) {
  1254. const button = await findVisibleButtonByAriaLabels(
  1255. ["重置 5 小时额度", "Reset 5-hour quota"],
  1256. false,
  1257. '[role="dialog"]',
  1258. );
  1259. if (!button) throw new Error(missingMessage);
  1260. await button.click();
  1261. }
  1262. async function readDialogResetState() {
  1263. return browser.execute(
  1264. (resetLabels: string[], successLabels: string[], weekResetLabels: string[]) => {
  1265. const dialog = document.querySelector('[role="dialog"]');
  1266. const buttons = dialog
  1267. ? Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"))
  1268. : [];
  1269. const findByLabels = (candidates: string[]) =>
  1270. buttons.find((button) => candidates.includes(button.getAttribute("aria-label") ?? "")) ??
  1271. null;
  1272. const resetButton = findByLabels(resetLabels);
  1273. return {
  1274. resetDisabled: resetButton ? resetButton.disabled : null,
  1275. // 重置按钮与类型名、次数药丸、倒计时同处一个行容器,用于断言该行展示内容。
  1276. resetRowText: resetButton?.parentElement?.innerText ?? null,
  1277. successVisible: findByLabels(successLabels) !== null,
  1278. weekResetVisible: findByLabels(weekResetLabels) !== null,
  1279. };
  1280. },
  1281. ["重置 5 小时额度", "Reset 5-hour quota"],
  1282. ["重置成功", "Reset successful"],
  1283. ["重置周额度", "Reset weekly quota"],
  1284. );
  1285. }
  1286. async function waitForDialogResetState(
  1287. predicate: (state: Awaited<ReturnType<typeof readDialogResetState>>) => boolean,
  1288. timeoutMsg: string,
  1289. ) {
  1290. let lastState: Awaited<ReturnType<typeof readDialogResetState>> | null = null;
  1291. try {
  1292. await browser.waitUntil(
  1293. async () => {
  1294. const state = await readDialogResetState();
  1295. lastState = state;
  1296. return predicate(state);
  1297. },
  1298. { interval: 100, timeout: 10000, timeoutMsg },
  1299. );
  1300. } catch (error) {
  1301. throw new Error(`${timeoutMsg}: ${JSON.stringify(lastState)}`, { cause: error });
  1302. }
  1303. }
  1304. async function waitForMockRequest(
  1305. predicate: (request: MockRequest) => boolean,
  1306. timeoutMsg: string,
  1307. ) {
  1308. await browser.waitUntil(async () => (await readMockRequests()).some(predicate), {
  1309. timeout: 10000,
  1310. timeoutMsg,
  1311. });
  1312. }
  1313. async function waitForLatestMockRequest(
  1314. predicate: (request: MockRequest) => boolean,
  1315. timeoutMsg: string,
  1316. ): Promise<MockRequest> {
  1317. let match: MockRequest | undefined;
  1318. await browser.waitUntil(
  1319. async () => {
  1320. match = (await readMockRequests()).findLast(predicate);
  1321. return Boolean(match);
  1322. },
  1323. { timeout: 10000, timeoutMsg },
  1324. );
  1325. if (!match) {
  1326. throw new Error(timeoutMsg);
  1327. }
  1328. return match;
  1329. }
  1330. async function clickVisibleButtonByText(labels: string[]): Promise<void> {
  1331. for (const button of await $$("button")) {
  1332. if ((await button.isDisplayed()) && labels.includes((await button.getText()).trim())) {
  1333. await button.click();
  1334. return;
  1335. }
  1336. }
  1337. throw new Error(`找不到可见按钮: ${labels.join("/")}`);
  1338. }
  1339. function daysBetweenMonitorTimes(startTime: string, endTime: string): number {
  1340. const start = Date.parse(startTime.replace(" ", "T") + "Z");
  1341. const end = Date.parse(endTime.replace(" ", "T") + "Z");
  1342. return Math.floor((end - start) / 86_400_000);
  1343. }
  1344. function requireQueryValue(request: MockRequest, key: string): string {
  1345. const value = request.query[key];
  1346. if (!value) {
  1347. throw new Error(`mock request 缺少 query: ${key}`);
  1348. }
  1349. return value;
  1350. }
  1351. function requestRangeDays(request: MockRequest): number | null {
  1352. const startTime = request.query.startTime;
  1353. const endTime = request.query.endTime;
  1354. return startTime && endTime ? daysBetweenMonitorTimes(startTime, endTime) : null;
  1355. }
  1356. async function readMockRequests(): Promise<MockRequest[]> {
  1357. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/requests`);
  1358. const payload = (await response.json()) as { requests?: MockRequest[] };
  1359. return payload.requests ?? [];
  1360. }
  1361. function getMockBaseUrl() {
  1362. const baseUrl = process.env.ZCODE_E2E_CODING_PLAN_MOCK_URL?.trim();
  1363. if (!baseUrl) {
  1364. throw new Error("ZCODE_E2E_CODING_PLAN_MOCK_URL 未配置");
  1365. }
  1366. return baseUrl;
  1367. }
  1368. async function writeSettings(patch: Record<string, unknown>) {
  1369. await mkdir(join(E2E_STORAGE_ROOT, "v2"), { recursive: true });
  1370. const current = await readSettings();
  1371. await writeFile(SETTINGS_FILE, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  1372. }
  1373. async function writeCredentials(patch: Record<string, unknown>) {
  1374. await mkdir(join(E2E_STORAGE_ROOT, "v2"), { recursive: true });
  1375. const current = await readJsonFile(CREDENTIALS_FILE);
  1376. await writeFile(CREDENTIALS_FILE, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  1377. }
  1378. async function readSettings(): Promise<{
  1379. providerFamilyConnectionSelections?: {
  1380. bigmodel?: ProviderFamilyConnectionSelection;
  1381. };
  1382. [key: string]: unknown;
  1383. }> {
  1384. try {
  1385. return JSON.parse(await readFile(SETTINGS_FILE, "utf-8")) as Record<string, unknown>;
  1386. } catch {
  1387. return {};
  1388. }
  1389. }
  1390. async function readJsonFile(path: string): Promise<Record<string, unknown>> {
  1391. try {
  1392. return JSON.parse(await readFile(path, "utf-8")) as Record<string, unknown>;
  1393. } catch {
  1394. return {};
  1395. }
  1396. }
  1397. function isRecord(value: unknown): value is Record<string, unknown> {
  1398. return typeof value === "object" && value !== null && !Array.isArray(value);
  1399. }
  1400. async function assertBodyTextIncludes(values: string[]) {
  1401. try {
  1402. await browser.waitUntil(
  1403. async () => {
  1404. const bodyText = await getBodyText();
  1405. return values.every((value) => bodyText.includes(value));
  1406. },
  1407. {
  1408. timeout: 10000,
  1409. timeoutMsg: `页面没有出现全部文本: ${values.join(" / ")}`,
  1410. },
  1411. );
  1412. } catch (error) {
  1413. throw new Error(
  1414. `页面没有出现全部文本: ${values.join(" / ")}\n当前页面文本:\n${(await getBodyText()).slice(0, 2000)}`,
  1415. { cause: error },
  1416. );
  1417. }
  1418. }
  1419. async function assertBodyTextIncludesAny(values: string[]) {
  1420. try {
  1421. await browser.waitUntil(
  1422. async () => {
  1423. const bodyText = await getBodyText();
  1424. return values.some((value) => bodyText.includes(value));
  1425. },
  1426. {
  1427. timeout: 10000,
  1428. timeoutMsg: `页面没有出现任一文本: ${values.join(" / ")}`,
  1429. },
  1430. );
  1431. } catch (error) {
  1432. throw new Error(
  1433. `页面没有出现任一文本: ${values.join(" / ")}\n当前页面文本:\n${(await getBodyText()).slice(0, 2000)}`,
  1434. { cause: error },
  1435. );
  1436. }
  1437. }
  1438. async function assertBodyTextExcludes(values: string[]) {
  1439. const bodyText = await getBodyText();
  1440. for (const value of values) {
  1441. expect(bodyText).not.toContain(value);
  1442. }
  1443. }
  1444. function getBodyText() {
  1445. return browser.execute(() => document.body?.innerText ?? "");
  1446. }
  1447. interface MockRequest {
  1448. body?: unknown;
  1449. headers: Record<string, string | string[] | undefined>;
  1450. method: string;
  1451. path: string;
  1452. query: Record<string, string>;
  1453. }
  1454. type ReminderNavigationWindow = Window & {
  1455. __zcodeTabStoreE2E: {
  1456. getState(): {
  1457. activeTabId: string | null;
  1458. openSettingsTab(): void;
  1459. activateTab(id: string): void;
  1460. };
  1461. };
  1462. };
  1463. async function assertContextReminderHiddenInSettings(phase: "initial" | "urgent") {
  1464. // 通过真实导航 store 切层,避免打开入口的 pointerdown 把提醒预先标已读,掩盖 Portal 泄漏。
  1465. const workspaceTabId = await browser.execute(() => {
  1466. const store = (window as unknown as ReminderNavigationWindow).__zcodeTabStoreE2E;
  1467. const id = store.getState().activeTabId;
  1468. store.getState().openSettingsTab();
  1469. return id;
  1470. });
  1471. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 10000 });
  1472. await browser.waitUntil(async () => !(await isContextResetReminderVisible(phase)), {
  1473. timeout: 5000,
  1474. timeoutMsg: "Composer 提醒穿透到设置页",
  1475. });
  1476. // 设置页点击不能消耗后台工作区的提醒状态。
  1477. await browser.execute(() =>
  1478. document
  1479. .querySelector('[data-testid="settings-page"]')!
  1480. .dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })),
  1481. );
  1482. await browser.execute(
  1483. (id) =>
  1484. (window as unknown as ReminderNavigationWindow).__zcodeTabStoreE2E
  1485. .getState()
  1486. .activateTab(id!),
  1487. workspaceTabId,
  1488. );
  1489. await browser.waitUntil(async () => await isContextResetReminderVisible(phase), {
  1490. timeout: 5000,
  1491. timeoutMsg: "设置页点击误将 Composer 提醒标记为已读",
  1492. });
  1493. }