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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { BUILTIN_MODEL_PROVIDER_IDS, type ProviderFamilyConnectionSelection } from "@zcode/shared";
  4. import {
  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_BACK_BUTTON,
  14. TID_SETTINGS_SECTION_NAV,
  15. TID_TASK_SETTINGS_BUTTON,
  16. TID_CHAT_MODEL_SELECT_TRIGGER,
  17. TID_V4_MODEL_CONFIG,
  18. TID_V4_COMPOSER_INPUT,
  19. testId,
  20. } from "@zcode/shared/test-ids";
  21. import {
  22. DEFAULT_WORKSPACE,
  23. clearAppData,
  24. getE2EAppDataPaths,
  25. quitElectronAppGracefully,
  26. readModelProviders,
  27. waitForDefaultWorkspaceReady,
  28. waitForWorkspaceApp,
  29. } from "./helpers/desktop-app.js";
  30. import { waitForProviderConfigPolling } from "./helpers/provider-config-polling.js";
  31. import { selectRegistryProviderModelById, UPSTREAM_MODEL } from "./helpers/upstream-provider.js";
  32. import { seedPersistedModelSelection } from "./helpers/model-provider-restart.js";
  33. import { sel } from "./helpers/selectors.js";
  34. import { skipOccupationOnboardingIfPresent } from "./helpers/occupation-onboarding.js";
  35. // 修复原因:WDIO 为每个 run 注入隔离 HOME,但 os.homedir() 在 Node 进程中不会
  36. // 随环境变量动态变化。沿用 homedir() 会把场景设置和 provider seed 写到开发机的
  37. // ~/.zcode,Electron 读取的却是本轮隔离 HOME;同时新版 Personal Config 文件名是
  38. // provider_config.json,不是旧的 config.json。统一复用 desktop-app 的路径合同,确保
  39. // 测试写入和应用读取的是同一份 fixture。
  40. const E2E_APP_DATA_PATHS = getE2EAppDataPaths();
  41. const E2E_STORAGE_ROOT = E2E_APP_DATA_PATHS.storageRoot;
  42. const SETTINGS_FILE = join(E2E_APP_DATA_PATHS.appDataDir, "setting.json");
  43. const CREDENTIALS_FILE = E2E_APP_DATA_PATHS.credentialsFile;
  44. const TEAM_PLAN_KEY = "team:bigmodel:product-team-a:org-team-a:proj-team-a";
  45. const PERSONAL_PLAN_KEY = "account:bigmodel-individual-coding-plan";
  46. const PERSONAL_PLAN_CONNECTION_KEY = `coding-plan:${PERSONAL_PLAN_KEY}`;
  47. const BIGMODEL_ACCOUNT_NAV_KEY = `preset:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`;
  48. // 与本轮 Builtin catalog 一致;旧 GLM-5.2 已不在 Account Provider 的可选模型中。
  49. const BIGMODEL_E2E_MODEL = "GLM-5.3";
  50. type CodingPlanScenario = "personalOnly" | "teamOnly" | "both";
  51. type CodingPlanFaultMode =
  52. | "none"
  53. | "optionalActivity"
  54. | "quotaBusinessFailure"
  55. | "quotaFailure"
  56. | "startBalance"
  57. | "startBalanceFailure"
  58. | "unavailableTeam"
  59. | "expiredTeam"
  60. | "twoTeams";
  61. type CodingPlanResetScenario =
  62. | "none"
  63. | "emptyThenGrant"
  64. | "existingMultiple"
  65. | "fiveHourUse"
  66. | "multiFiveHourUse"
  67. | "multiFiveHourUseLagging"
  68. | "urgentOpportunity";
  69. describe("Team Plan 设置与使用统计 E2E", () => {
  70. after(async () => {
  71. await browser.electron.restoreAllMocks();
  72. await clearAppData();
  73. });
  74. it("CTP-13: Start balance 限流显示重试,恢复后展示套餐", async function () {
  75. this.timeout(120000);
  76. const evidenceDir =
  77. process.env.ZCODE_E2E_ARTIFACT_DIR || join(process.cwd(), ".e2e-artifacts", "coding-plan");
  78. await mkdir(evidenceDir, { recursive: true });
  79. await prepareScenario(
  80. "personalOnly",
  81. BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan,
  82. "startBalanceFailure",
  83. );
  84. await openModelProviderSettings();
  85. await clickVisibleTestIdByDom(
  86. testId(
  87. TID_MODEL_PROVIDER_NAV_ITEM,
  88. `coding-plan:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan}`,
  89. ),
  90. {
  91. timeout: 10000,
  92. timeoutMsg: "BigModel 入口缺失",
  93. },
  94. );
  95. await assertBodyTextIncludesAny(["Retry", "重试"]);
  96. await assertBodyTextIncludesAny(["Fetch failed", "获取失败"]);
  97. await browser.saveScreenshot(join(evidenceDir, "coding-plan-start-failure.png"));
  98. await assertBodyTextExcludes([
  99. "Could not verify Coding Plan entitlement. Connect again and retry.",
  100. "暂时无法确认 Coding Plan 权益,请重新连接后再试。",
  101. ]);
  102. await setMockScenario("personalOnly", "startBalance");
  103. // 失败结果也有明确的一秒复用窗口;在窗口结束后验证用户重试恢复。
  104. await browser.pause(1000);
  105. await clickVisibleButtonByText(["Retry", "重试"]);
  106. await assertBodyTextIncludes(["GLM-5-Turbo"]);
  107. await browser.waitUntil(
  108. async () =>
  109. !(await browser.execute(() => document.body.innerText)).match(/Fetch failed|获取失败/),
  110. { timeout: 15000, timeoutMsg: "重试后失败状态未恢复" },
  111. );
  112. await browser.saveScreenshot(join(evidenceDir, "coding-plan-start-recovered.png"));
  113. });
  114. it("CTP-01: 登录后不进入设置页也应获取 Team Plan pricing", async function () {
  115. this.timeout(90000);
  116. await prepareScenario("both", TEAM_PLAN_KEY);
  117. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  118. await waitForMockRequest(
  119. (request) => request.path.endsWith("/subscription/enterprise/v2/pricing"),
  120. "未在不进入设置页时请求企业套餐 pricing",
  121. );
  122. await expect($(sel(TID_SETTINGS_PAGE))).not.toBeDisplayed();
  123. });
  124. it("CTP-02: 设置页连接方式应展示个人 Coding Plan 和 Team Plan", async function () {
  125. this.timeout(120000);
  126. await prepareScenario("both", PERSONAL_PLAN_KEY);
  127. await openModelProviderSettings();
  128. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  129. timeout: 30000,
  130. timeoutMsg: "BigModel 供应商导航项没有出现",
  131. });
  132. await assertConnectionModeOptionsInclude([
  133. {
  134. key: PERSONAL_PLAN_CONNECTION_KEY,
  135. labels: ["Individual Plan", "个人套餐"],
  136. },
  137. { key: TEAM_PLAN_KEY, labels: ["Team Org"] },
  138. ]);
  139. await selectConnectionModeOptionByTestId(
  140. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, TEAM_PLAN_KEY),
  141. "Team Org",
  142. );
  143. await browser.waitUntil(
  144. async () => {
  145. const settings = await readSettings();
  146. const selection = settings.providerFamilyConnectionSelections?.bigmodel;
  147. return (
  148. selection?.kind === "team-coding-plan" &&
  149. selection.productId === "product-team-a" &&
  150. selection.organizationId === "org-team-a" &&
  151. selection.projectId === "proj-team-a"
  152. );
  153. },
  154. {
  155. timeout: 15000,
  156. timeoutMsg: "选择 Team Plan 后没有写入结构化 BigModel connection selection",
  157. },
  158. );
  159. });
  160. for (const empty of [false, true]) {
  161. it(`CTP-${empty ? 26 : 25}: 未登录${empty ? "无 Provider 直接打开设置" : "API 正常选择且无团队登录错误"}`, async function () {
  162. this.timeout(240000);
  163. await prepareScenario("both", PERSONAL_PLAN_KEY, "none", "none", "en-US", true);
  164. for (const width of [1100, 390]) {
  165. for (const theme of ["zai-light", "zai-dark"] as const) {
  166. const disabledProviders = await browser.execute(async (remove) => {
  167. const element = document.querySelector('[data-testid="v4-model-config"]')!;
  168. let fiber = (element as any)[
  169. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  170. ];
  171. let service: any;
  172. while (fiber && !service) {
  173. service =
  174. fiber.memoizedProps?.value?.providerSettingsService ??
  175. fiber.memoizedProps?.services?.providerSettingsService;
  176. fiber = fiber.return;
  177. }
  178. if (!service) throw new Error("ProviderSettingsService not found");
  179. const disabledProviders: { providerId: string; config: Record<string, unknown> }[] = [];
  180. if (remove) {
  181. const view = await service.getView();
  182. for (const provider of view.providers) {
  183. if (provider.effectiveConfig.access?.type !== "zhipu-account" && provider.enabled) {
  184. await service.savePersonalProviderOverlay(
  185. provider.providerId,
  186. provider.personalConfig ?? {},
  187. { enabled: false },
  188. );
  189. // 保存接口替换整个 Overlay,空对象会抹掉自定义 API 配置。
  190. disabledProviders.push({
  191. providerId: provider.providerId,
  192. config: provider.personalConfig ?? {},
  193. });
  194. }
  195. }
  196. }
  197. await service.refresh("e2e-logged-out-composer");
  198. return disabledProviders;
  199. }, empty);
  200. await setRendererViewport(width, 850);
  201. await setSettingsTheme(theme);
  202. if (empty) {
  203. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  204. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  205. expect(
  206. await browser.execute(
  207. () => document.querySelector("[data-composer-model-list]") === null,
  208. ),
  209. ).toBe(true);
  210. await clickVisibleTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15000 });
  211. // 空配置仅属于本次布局;恢复夹具,避免下一次启动被空配置引导接管。
  212. await browser.execute(async (providers) => {
  213. const element = document.querySelector('[data-testid="v4-model-config"]')!;
  214. let fiber = (element as any)[
  215. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  216. ];
  217. let service: any;
  218. while (fiber && !service) {
  219. service =
  220. fiber.memoizedProps?.value?.providerSettingsService ??
  221. fiber.memoizedProps?.services?.providerSettingsService;
  222. fiber = fiber.return;
  223. }
  224. if (!service) throw new Error("ProviderSettingsService not found");
  225. for (const provider of providers)
  226. await service.savePersonalProviderOverlay(provider.providerId, provider.config, {
  227. enabled: true,
  228. });
  229. }, disabledProviders);
  230. } else {
  231. await selectRegistryProviderModelById(UPSTREAM_MODEL, {
  232. providerId: process.env.E2E_PROVIDER_ID,
  233. });
  234. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  235. expect(
  236. await browser.execute(
  237. () =>
  238. document.querySelector("[data-composer-model-list]")?.textContent?.length ?? 0,
  239. ),
  240. ).toBeGreaterThan(0);
  241. expect(
  242. await browser.execute(() =>
  243. document.body.textContent?.includes("coding_plan_oauth_required"),
  244. ),
  245. ).toBe(false);
  246. await browser.keys("Escape");
  247. }
  248. }
  249. }
  250. await clearRendererViewport();
  251. });
  252. }
  253. it("CTP-30: 个人团队切换列表无横向溢出,保留纵向滚动", async function () {
  254. this.timeout(240000);
  255. try {
  256. for (const width of [1100, 390])
  257. for (const theme of ["zai-light", "zai-dark"] as const) {
  258. await prepareScenario("both", PERSONAL_PLAN_KEY);
  259. await setRendererViewport(width, 850);
  260. await setSettingsTheme(theme);
  261. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  262. await browser.execute(() => {
  263. const samples: { client: number; scroll: number }[] = [];
  264. const record = () => {
  265. for (const list of document.querySelectorAll<HTMLElement>(
  266. "[data-composer-provider-list]",
  267. ))
  268. if (list.getBoundingClientRect().width > 0)
  269. samples.push({ client: list.clientWidth, scroll: list.scrollWidth });
  270. };
  271. const observer = new MutationObserver(record);
  272. observer.observe(document.body, { subtree: true, childList: true, attributes: true });
  273. Object.assign(window, {
  274. __providerWidthProbe: { samples, stop: () => observer.disconnect() },
  275. });
  276. });
  277. for (const [label, providerId] of [
  278. ["BigModel Team Org", BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan],
  279. ["BigModel Individual", BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan],
  280. ]) {
  281. await $('[data-testid="composer-provider-trigger"]').waitForClickable({
  282. timeout: 15000,
  283. });
  284. await $('[data-testid="composer-provider-trigger"]').click();
  285. const row = $('[aria-label="' + label + '"]');
  286. await row.waitForDisplayed({ timeout: 15000 });
  287. // 原因:负边距分隔线超出滚动列表 4px;实际布局尺寸才证明没有横向溢出。
  288. const geometry = await browser.execute(() => {
  289. const list = document.querySelector<HTMLElement>("[data-composer-provider-list]")!;
  290. const before = { client: list.clientWidth, scroll: list.scrollWidth };
  291. const style = list.getAttribute("style");
  292. // 当前目录可能只有两项;固定 96px 不产生溢出,无法验证纵向滚动。
  293. const rows = list.querySelectorAll<HTMLElement>('[role="menuitemradio"]');
  294. if (rows.length < 2) throw new Error("滚动夹具至少需要两个 Provider");
  295. list.style.maxHeight = `${rows[0]!.getBoundingClientRect().height}px`;
  296. const vertical = list.scrollHeight > list.clientHeight;
  297. list.scrollTop = 10;
  298. const scrolled = list.scrollTop > 0;
  299. list.scrollTop = 0;
  300. if (style === null) list.removeAttribute("style");
  301. else list.setAttribute("style", style);
  302. return { ...before, vertical, scrolled };
  303. });
  304. expect(geometry.scroll).toBeLessThanOrEqual(geometry.client);
  305. expect(geometry.vertical && geometry.scrolled).toBe(true);
  306. await row.click();
  307. await browser.waitUntil(
  308. async () =>
  309. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) === providerId,
  310. { timeout: 15000 },
  311. );
  312. }
  313. const samples = await browser.execute(() => {
  314. const probe = (window as any).__providerWidthProbe;
  315. probe.stop();
  316. return probe.samples as { client: number; scroll: number }[];
  317. });
  318. await writeFile(
  319. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `provider-width-${width}-${theme}.json`),
  320. JSON.stringify(samples, null, 2),
  321. );
  322. expect(samples.length).toBeGreaterThan(0);
  323. expect(samples.every((sample) => sample.scroll <= sample.client)).toBe(true);
  324. await browser.keys("Escape");
  325. }
  326. } finally {
  327. await browser.execute(() => (window as any).__providerWidthProbe?.stop());
  328. await clearRendererViewport();
  329. }
  330. });
  331. it("CTP-27: 登录加载团队后登出,不保留旧组织目录", async function () {
  332. this.timeout(240000);
  333. try {
  334. for (const width of [1100, 390])
  335. for (const theme of ["zai-light", "zai-dark"] as const) {
  336. await prepareScenario("both", PERSONAL_PLAN_KEY);
  337. await setRendererViewport(width, 850);
  338. await setSettingsTheme(theme);
  339. await selectRegistryProviderModelById(UPSTREAM_MODEL, {
  340. providerId: process.env.E2E_PROVIDER_ID,
  341. });
  342. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  343. await $('[data-testid="composer-provider-trigger"]').click();
  344. await $('[aria-label="BigModel Team Org"]').waitForClickable({ timeout: 15000 });
  345. await $('[aria-label="BigModel Team Org"]').click();
  346. await browser.waitUntil(
  347. async () =>
  348. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) ===
  349. BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  350. { timeout: 15000 },
  351. );
  352. await browser.keys("Escape");
  353. const usageTrigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  354. await usageTrigger.waitForDisplayed({ timeout: 15000 });
  355. await usageTrigger.moveTo();
  356. await browser.waitUntil(
  357. async () =>
  358. (await readComposerTeamUsageSource())?.startsWith("team:bigmodel:") === true,
  359. { timeout: 15000, timeoutMsg: "团队用量来源未加载" },
  360. );
  361. await browser.keys("Escape");
  362. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  363. await $('[data-testid="composer-provider-trigger"]').click();
  364. await $('[aria-label="BigModel Team Org"]').waitForDisplayed({ timeout: 15000 });
  365. // 保持同一 Renderer 挂载:重启会抹掉内存缓存,不能验证登出清理边界。
  366. await installConnectionBoundaryProbe("logout");
  367. await browser.waitUntil(
  368. async () => !(await $('[aria-label="BigModel Team Org"]').isExisting()),
  369. { timeout: 15000, timeoutMsg: "登出后仍显示上一账号组织" },
  370. );
  371. await browser.keys("Escape");
  372. await browser.waitUntil(async () => (await readComposerTeamUsageSource()) === null, {
  373. timeout: 5000,
  374. timeoutMsg: "Provider 刷新前旧团队用量仍可见",
  375. });
  376. await browser.execute(async () => {
  377. await (window as any).__logoutBoundaryRelease();
  378. });
  379. await selectRegistryProviderModelById(UPSTREAM_MODEL, {
  380. providerId: process.env.E2E_PROVIDER_ID,
  381. });
  382. await browser.saveScreenshot(
  383. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "logout-" + width + "-" + theme + ".png"),
  384. );
  385. }
  386. } finally {
  387. const diagnostic = await browser.execute(() => (window as any).__logoutBoundaryAuth?.());
  388. await writeFile(
  389. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "logout-boundary.json"),
  390. JSON.stringify({ auth: diagnostic, source: await readComposerTeamUsageSource() }),
  391. );
  392. await browser.execute(async () => {
  393. await (window as any).__logoutBoundaryRelease?.();
  394. });
  395. await clearRendererViewport();
  396. }
  397. });
  398. for (const mode of ["cas", "mismatch", "refresh-failure"] as const) {
  399. it(
  400. "CTP-" +
  401. (mode === "cas" ? "28" : mode === "mismatch" ? "29" : "31") +
  402. ": " +
  403. mode +
  404. " 冲突解除锁并允许重试",
  405. async function () {
  406. this.timeout(120000);
  407. await prepareScenario(
  408. "both",
  409. mode === "refresh-failure" ? TEAM_PLAN_KEY : PERSONAL_PLAN_KEY,
  410. mode === "refresh-failure" ? "twoTeams" : "none",
  411. );
  412. const targetRow =
  413. mode === "refresh-failure"
  414. ? '[aria-label="BigModel Active Team"]'
  415. : '[aria-label="BigModel Team Org"]';
  416. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  417. await $('[data-testid="composer-provider-trigger"]').click();
  418. await $(targetRow).waitForClickable({ timeout: 15000 });
  419. await installConnectionBoundaryProbe(mode);
  420. try {
  421. // 端口替换触发真实目录重读;等待它结束,再从正常菜单发起被测命令。
  422. await browser.keys("Escape");
  423. await browser.keys("Escape");
  424. // SessionPane 是 memo owner;草稿编辑让它重新读取注入后的服务端口,不发送模型请求。
  425. await $(sel(TID_V4_COMPOSER_INPUT)).click();
  426. await browser.keys("E2E_CONNECTION_BOUNDARY");
  427. if (mode === "refresh-failure") {
  428. // 注入端口后的草稿重渲染会恢复默认 Provider;先用真实菜单建立 Team 起点,
  429. // 否则实际测成 API → Team 的首次读取失败,不是同 Provider 的展示刷新失败。
  430. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  431. await $('[data-testid="composer-provider-trigger"]').click();
  432. await $('[aria-label="BigModel Team Org"]').waitForClickable({ timeout: 15000 });
  433. await $('[aria-label="BigModel Team Org"]').click();
  434. await browser.waitUntil(
  435. async () =>
  436. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) ===
  437. BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  438. { timeout: 15000, timeoutMsg: "起点未进入团队 Provider" },
  439. );
  440. // 本例要求旧 ready 已显示;仅 providerId 就绪时,能力仍可能在首次水合中。
  441. // 先等真实模型能力,避免把启动水合失败误当成“稳定连接的展示重读失败”。
  442. await browser.waitUntil(
  443. async () =>
  444. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought-levels"))
  445. ?.split(",")
  446. .includes("max") === true,
  447. { timeout: 15000, timeoutMsg: "起点团队模型能力尚未水合" },
  448. );
  449. await browser.keys("Escape");
  450. await browser.keys("Escape");
  451. }
  452. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  453. await $('[data-testid="composer-provider-trigger"]').waitForClickable({ timeout: 15000 });
  454. await $('[data-testid="composer-provider-trigger"]').click();
  455. await $(targetRow).waitForClickable({ timeout: 15000 });
  456. await browser.execute(() => (window as any).__connectionBoundaryProbe.arm());
  457. await $(targetRow).click();
  458. if (mode === "mismatch") {
  459. await browser.waitUntil(
  460. async () =>
  461. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) ===
  462. "e2e-upstream",
  463. { timeout: 15000, timeoutMsg: "展示 owner 未投影冲突选择" },
  464. );
  465. // 展示冲突会更换当前 Provider,根菜单可能因此重挂载;重开正常入口检查错误。
  466. await browser.keys("Escape");
  467. await browser.keys("Escape");
  468. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  469. }
  470. await $('[role="alert"]').waitForDisplayed({ timeout: 15000 });
  471. expect(await $('[data-testid="composer-provider-loading"]').isExisting()).toBe(false);
  472. const trace = await browser.execute(
  473. () => (window as any).__connectionBoundaryProbe.trace,
  474. );
  475. expect(trace.length).toBeGreaterThan(0);
  476. await writeFile(
  477. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "connection-" + mode + ".json"),
  478. JSON.stringify(trace, null, 2),
  479. );
  480. if (mode === "cas")
  481. expect((await readSettings()).providerFamilyConnectionSelections?.zai).toEqual({
  482. kind: "individual-coding-plan",
  483. });
  484. } finally {
  485. const diagnostics = await browser.execute(() => {
  486. const probe = (window as any).__connectionBoundaryProbe;
  487. const element = document.querySelector(
  488. '[data-testid="v4-model-config"]',
  489. ) as HTMLElement;
  490. return {
  491. trace: probe.trace,
  492. config: element?.dataset,
  493. alerts: Array.from(document.querySelectorAll('[role="alert"]')).map(
  494. (e) => e.textContent,
  495. ),
  496. };
  497. });
  498. await writeFile(
  499. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "boundary-" + mode + ".json"),
  500. JSON.stringify(diagnostics, null, 2),
  501. );
  502. await browser.execute((mode) => {
  503. const probe = (window as any).__connectionBoundaryProbe;
  504. if (mode === "refresh-failure") probe.recover();
  505. else probe.restore();
  506. }, mode);
  507. }
  508. await browser.keys("Escape");
  509. await browser.keys("Escape");
  510. if (mode !== "refresh-failure") {
  511. await $(sel(TID_V4_COMPOSER_INPUT)).click();
  512. await browser.keys("E2E_CONNECTION_RETRY");
  513. }
  514. await clickVisibleTestIdByDom(TID_CHAT_MODEL_SELECT_TRIGGER, { timeout: 15000 });
  515. const trigger = $('[data-testid="composer-provider-trigger"]');
  516. await trigger.waitForClickable({ timeout: 15000 });
  517. await trigger.click();
  518. await $(targetRow).waitForClickable({ timeout: 15000 });
  519. await $(targetRow).click();
  520. await browser.waitUntil(
  521. async () =>
  522. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) ===
  523. BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  524. { timeout: 15000 },
  525. );
  526. if (mode === "refresh-failure") {
  527. await browser.waitUntil(
  528. async () =>
  529. browser.execute(() =>
  530. (window as any).__connectionBoundaryProbe.trace.some(
  531. (entry: any) => entry.phase === "obsolete-started",
  532. ),
  533. ),
  534. { timeout: 15000 },
  535. );
  536. await browser.execute(() => (window as any).__connectionBoundaryProbe.supersede());
  537. await browser.waitUntil(
  538. async () =>
  539. browser.execute(() =>
  540. (window as any).__connectionBoundaryProbe.trace.some(
  541. (entry: any) => entry.phase === "presentation-recovered",
  542. ),
  543. ),
  544. { timeout: 15000 },
  545. );
  546. await browser.execute(() => (window as any).__connectionBoundaryProbe.rejectObsolete());
  547. }
  548. if (mode === "refresh-failure")
  549. await browser.waitUntil(
  550. async () =>
  551. browser.execute(() =>
  552. (window as any).__connectionBoundaryProbe.trace.some(
  553. (entry: any) => entry.phase === "presentation-recovered",
  554. ),
  555. ),
  556. { timeout: 15000, timeoutMsg: "同连接重试没有请求展示重读" },
  557. );
  558. await browser.waitUntil(
  559. async () => !(await $('[data-testid="composer-provider-loading"]').isExisting()),
  560. { timeout: 15000 },
  561. );
  562. expect(await $('[role="alert"]').isExisting()).toBe(false);
  563. await browser.keys("Escape");
  564. if (mode === "refresh-failure") {
  565. const trace = await browser.execute(
  566. () => (window as any).__connectionBoundaryProbe.trace,
  567. );
  568. const recoveredAt = trace.findIndex((entry: any) => entry.phase === "fault-recovered");
  569. expect(
  570. trace.slice(recoveredAt + 1).some((entry: any) => entry.phase === "target-event"),
  571. ).toBe(false);
  572. // 冷启动目录刷新次数不是合同;恢复必须读取本次已同步的 revision,而非写死 2。
  573. const synchronized = trace.findLast(
  574. (entry: any) => entry.phase === "target-synchronized",
  575. );
  576. expect(synchronized).toBeDefined();
  577. expect(
  578. trace.some(
  579. (entry: any) =>
  580. entry.phase === "presentation-recovered" &&
  581. entry.revision === synchronized.revision,
  582. ),
  583. ).toBe(true);
  584. await writeFile(
  585. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "connection-retry-no-event.json"),
  586. JSON.stringify(trace, null, 2),
  587. );
  588. await browser.execute(() => (window as any).__connectionBoundaryProbe.restore());
  589. }
  590. },
  591. );
  592. }
  593. it("CTP-24: Composer 仅隐藏过期团队,其他有效团队可切换", async function () {
  594. this.timeout(240000);
  595. // 共用 Provider 的 availability 只描述当前团队;每个布局都从过期团队启动,验证真实切换。
  596. try {
  597. for (const width of [1100, 390]) {
  598. for (const theme of ["zai-light", "zai-dark"] as const) {
  599. await prepareScenario("both", TEAM_PLAN_KEY, "expiredTeam", "none", "en-US");
  600. const states = await browser.execute(async () => {
  601. const element = document.querySelector('[data-testid="v4-model-config"]')!;
  602. let fiber = (element as any)[
  603. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  604. ];
  605. let service: any;
  606. while (fiber && !service) {
  607. service =
  608. fiber.memoizedProps?.value?.providerSettingsService ??
  609. fiber.memoizedProps?.services?.providerSettingsService;
  610. fiber = fiber.return;
  611. }
  612. if (!service) throw new Error("ProviderSettingsService not found");
  613. const view = await service.refresh("e2e-expired-team");
  614. return view.providers.map((provider: any) => ({
  615. id: provider.providerId,
  616. state: provider.accountState?.availability,
  617. }));
  618. });
  619. expect(
  620. states.find(
  621. (provider: { id: string; state?: string }) =>
  622. provider.id === BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  623. )?.state,
  624. ).toBe("unavailable");
  625. await setRendererViewport(width, 850);
  626. await setSettingsTheme(theme);
  627. const trigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  628. await trigger.waitForClickable({ timeout: 30000 });
  629. await trigger.click();
  630. const connection = $('[data-testid="composer-provider-trigger"]');
  631. await connection.waitForDisplayed({ timeout: 15000 });
  632. await connection.click();
  633. await $("[data-composer-provider-list]").waitForDisplayed({ timeout: 10000 });
  634. expect(await $('[aria-label="BigModel Team Org"]').isExisting()).toBe(false);
  635. const activeTeam = $('[aria-label="BigModel Active Team"]');
  636. await activeTeam.waitForClickable({ timeout: 15000 }).catch(async (cause) => {
  637. const menu = await browser.execute(() => {
  638. const element = document.querySelector('[data-testid="v4-model-config"]')!;
  639. let fiber = (element as any)[
  640. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  641. ];
  642. while (fiber && !fiber.memoizedProps?.composerOptions) fiber = fiber.return;
  643. return {
  644. text: document.querySelector("[data-composer-provider-list]")?.textContent,
  645. groups: fiber?.memoizedProps?.composerOptions?.providerMenu?.groups?.map(
  646. (g: any) => ({ key: g.key, badge: g.labelBadge }),
  647. ),
  648. };
  649. });
  650. throw new Error(`有效团队缺失:${JSON.stringify(menu)}`, { cause });
  651. });
  652. await activeTeam.click();
  653. await browser.waitUntil(
  654. async () => {
  655. const selection = (await readSettings()).providerFamilyConnectionSelections?.bigmodel;
  656. return (
  657. selection?.kind === "team-coding-plan" &&
  658. selection.organizationId === "org-team-b" &&
  659. selection.projectId === "proj-team-b"
  660. );
  661. },
  662. { timeout: 15000, timeoutMsg: "有效团队完整身份未写入" },
  663. );
  664. await browser.waitUntil(
  665. async () =>
  666. (await connection.getText()).includes("Active Team") &&
  667. (await connection.getAttribute("aria-busy")) !== "true",
  668. { timeout: 30000, timeoutMsg: "有效团队切换未完成" },
  669. );
  670. await browser.keys("Escape");
  671. await browser.keys("Escape");
  672. }
  673. }
  674. } finally {
  675. await clearRendererViewport();
  676. }
  677. });
  678. it("CTP-20: Composer 供应商列表直接展示团队,切换更新实际身份", async function () {
  679. this.timeout(120000);
  680. await prepareScenario("both", PERSONAL_PLAN_KEY, "unavailableTeam");
  681. // 独立回放不能依赖前序用例留下的草稿;连接设置不等于 Composer 选模意图。
  682. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  683. includePlainModelFallback: false,
  684. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  685. });
  686. const trigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  687. await trigger.waitForClickable({ timeout: 30000 });
  688. await trigger.click();
  689. const connection = $('[data-testid="composer-provider-trigger"]');
  690. await connection.waitForDisplayed({ timeout: 15000 });
  691. expect(await $('[data-testid="composer-provider-trigger"]').getText()).toContain("BigModel");
  692. expect(await $('[data-testid="composer-connection-trigger"]').isExisting()).toBe(false);
  693. const slider = $('[data-testid="composer-thought-slider"]');
  694. await slider.waitForDisplayed({ timeout: 10000 });
  695. await slider.click();
  696. await browser.keys("Home");
  697. await browser.keys("ArrowRight");
  698. await browser.waitUntil(
  699. async () => Boolean(await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought")),
  700. { timeout: 10000 },
  701. );
  702. const chosenThought = await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought");
  703. await browser.execute(() => {
  704. const samples: unknown[] = [];
  705. const record = () => {
  706. const config = document.querySelector('[data-testid="v4-model-config"]');
  707. const slider = document.querySelector('[data-testid="composer-thought-slider"]');
  708. samples.push({
  709. at: performance.now(),
  710. provider: config?.getAttribute("data-provider"),
  711. thought: config?.getAttribute("data-thought"),
  712. levels: config?.getAttribute("data-thought-levels"),
  713. effort: slider?.getAttribute("aria-valuetext"),
  714. title: document.querySelector('[data-testid="composer-provider-trigger"]')?.textContent,
  715. loading: Boolean(document.querySelector('[data-testid="composer-provider-loading"]')),
  716. busy: document
  717. .querySelector('[data-testid="composer-provider-trigger"]')
  718. ?.getAttribute("aria-busy"),
  719. });
  720. };
  721. const observer = new MutationObserver(record);
  722. observer.observe(document.body, { subtree: true, childList: true, attributes: true });
  723. Object.assign(window, {
  724. __composerSwitchProbe: { samples, stop: () => observer.disconnect() },
  725. });
  726. record();
  727. });
  728. await connection.click();
  729. const team = $('[aria-label="BigModel Team Org"]');
  730. await team.waitForDisplayed({ timeout: 10000 });
  731. expect(await $('[aria-label="BigModel Unavailable Team"]').isExisting()).toBe(false);
  732. await browser.saveScreenshot(
  733. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "composer-connections-before.png"),
  734. );
  735. await team.click();
  736. await browser.waitUntil(
  737. async () =>
  738. (await readSettings()).providerFamilyConnectionSelections?.bigmodel?.kind ===
  739. "team-coding-plan",
  740. { timeout: 15000 },
  741. );
  742. await browser.waitUntil(
  743. async () =>
  744. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) ===
  745. BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  746. { timeout: 15000 },
  747. );
  748. expect(await trigger.getAttribute("aria-expanded")).toBe("true");
  749. await connection.waitForClickable({ timeout: 15000 });
  750. const samples = await browser.execute(() => {
  751. const probe = (
  752. window as unknown as { __composerSwitchProbe: { samples: unknown[]; stop: () => void } }
  753. ).__composerSwitchProbe;
  754. probe.stop();
  755. return probe.samples;
  756. });
  757. await writeFile(
  758. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "composer-switch-state.json"),
  759. JSON.stringify(samples, null, 2),
  760. );
  761. expect(samples.some((sample) => (sample as { loading?: boolean }).loading)).toBe(true);
  762. expect(
  763. samples
  764. .filter((sample) => (sample as { loading?: boolean }).loading)
  765. .every((sample) => (sample as { busy?: string }).busy === "true"),
  766. ).toBe(true);
  767. expect(await $('[data-testid="composer-provider-loading"]').isExisting()).toBe(false);
  768. // 修复回归:只看最终值会漏掉重选模型触发的中间清空/控件收缩,检查整段 DOM 时序。
  769. expect(
  770. samples.every((sample) => {
  771. const state = sample as { thought?: string; effort?: string; levels?: string };
  772. return state.thought === chosenThought && Boolean(state.effort) && Boolean(state.levels);
  773. }),
  774. ).toBe(true);
  775. expect(await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought")).toBe(chosenThought);
  776. await connection.click();
  777. const selectedTeam = $('[aria-label="BigModel Team Org"]');
  778. await selectedTeam.waitForDisplayed({ timeout: 10000 });
  779. expect(await selectedTeam.getAttribute("aria-checked")).toBe("true");
  780. expect(await connection.getText()).toContain("Team Org");
  781. expect((await readSettings()).providerFamilyConnectionSelections?.bigmodel).toEqual({
  782. kind: "team-coding-plan",
  783. productId: "product-team-a",
  784. organizationId: "org-team-a",
  785. projectId: "proj-team-a",
  786. });
  787. await browser.saveScreenshot(
  788. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "composer-connections-team.png"),
  789. );
  790. const personal = $(
  791. `[data-model-provider-key="registry-provider:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan}"]`,
  792. );
  793. await personal.click();
  794. await browser.waitUntil(
  795. async () =>
  796. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) ===
  797. BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  798. { timeout: 15000 },
  799. );
  800. await connection.waitForClickable({ timeout: 15000 });
  801. expect(await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought")).toBe(chosenThought);
  802. expect((await readSettings()).providerFamilyConnectionSelections?.bigmodel?.kind).toBe(
  803. "individual-coding-plan",
  804. );
  805. await browser.keys("Escape");
  806. });
  807. for (const locale of ["zh-CN", "en-US"] as const) {
  808. it(`CTP-23: 团队激活时补充个人入口使用当前语言 ${locale}`, async function () {
  809. this.timeout(120000);
  810. await prepareScenario("both", TEAM_PLAN_KEY, "none", "none", locale);
  811. const trigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  812. await trigger.waitForClickable({ timeout: 30000 });
  813. await trigger.click();
  814. const connection = $('[data-testid="composer-provider-trigger"]');
  815. await connection.click();
  816. const personalLabel = locale === "zh-CN" ? "个人" : "Individual";
  817. await $(`[aria-label="BigModel ${personalLabel}"]`).waitForDisplayed({ timeout: 10000 });
  818. expect(await $('[aria-label="BigModel Team Org"]').isDisplayed()).toBe(true);
  819. if (locale === "zh-CN")
  820. expect(await $('[aria-label="BigModel Individual"]').isExisting()).toBe(false);
  821. await browser.keys("Escape");
  822. await browser.keys("Escape");
  823. });
  824. }
  825. for (const direction of ["personal-to-team", "team-to-personal"] as const) {
  826. it(`CTP-22: 经过普通 API 切换账号连接后思考完整 ${direction}`, async function () {
  827. this.timeout(120000);
  828. const toTeam = direction === "personal-to-team";
  829. await prepareScenario("both", toTeam ? PERSONAL_PLAN_KEY : TEAM_PLAN_KEY);
  830. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  831. includePlainModelFallback: false,
  832. providerId: toTeam
  833. ? BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan
  834. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan,
  835. });
  836. const trigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  837. await trigger.waitForClickable({ timeout: 30000 });
  838. await trigger.click();
  839. const connection = $('[data-testid="composer-provider-trigger"]');
  840. await browser.execute(() => {
  841. let wasLoading = false;
  842. const read = () =>
  843. JSON.stringify({
  844. models: document.querySelector("[data-composer-model-list]")?.textContent,
  845. effort: document
  846. .querySelector('[data-testid="composer-thought-slider"]')
  847. ?.getAttribute("aria-valuetext"),
  848. });
  849. let previous = read();
  850. const probe = {
  851. count: 0,
  852. samples: [] as { loading: boolean; display: string; previous: string }[],
  853. stop: () => {},
  854. };
  855. const observer = new MutationObserver(() => {
  856. const loading = Boolean(
  857. document.querySelector('[data-testid="composer-provider-loading"]'),
  858. );
  859. if (loading && !wasLoading) probe.count++;
  860. const display = read();
  861. probe.samples.push({ loading, display, previous });
  862. if (!loading) previous = display;
  863. wasLoading = loading;
  864. });
  865. observer.observe(document.body, { subtree: true, childList: true, attributes: true });
  866. probe.stop = () => observer.disconnect();
  867. Object.assign(window, { __connectionLoadingProbe: probe });
  868. });
  869. await connection.click();
  870. // 使用 runner 注入的 Provider 身份,不依赖已移除的旧预设名称。
  871. await $(
  872. `[data-composer-provider-list] [data-model-provider-key="registry-provider:${process.env.E2E_PROVIDER_ID}"]`,
  873. ).click();
  874. await browser.waitUntil(
  875. async () =>
  876. !(await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider"))?.startsWith(
  877. "account:",
  878. ),
  879. );
  880. await connection.waitForClickable({ timeout: 15000 });
  881. expect(await browser.execute(() => (window as any).__connectionLoadingProbe.count)).toBe(1);
  882. await connection.click();
  883. await $(
  884. toTeam
  885. ? '[aria-label="BigModel Team Org"]'
  886. : `[data-model-provider-key="registry-provider:${BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan}"]`,
  887. ).click();
  888. await connection.waitForClickable({ timeout: 15000 });
  889. await browser.waitUntil(
  890. async () =>
  891. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-provider")) ===
  892. (toTeam
  893. ? BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan
  894. : BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan),
  895. { timeout: 15000 },
  896. );
  897. expect(await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought")).not.toBe("");
  898. expect(
  899. await $('[data-testid="composer-thought-slider"]').getAttribute("aria-valuetext"),
  900. ).not.toContain("—");
  901. const probe = await browser.execute(() => {
  902. const probe = (window as any).__connectionLoadingProbe;
  903. probe.stop();
  904. return { count: probe.count, samples: probe.samples };
  905. });
  906. await writeFile(
  907. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `connection-loading-${direction}.json`),
  908. JSON.stringify(probe, null, 2),
  909. );
  910. expect(probe.count).toBe(2);
  911. expect(await $('[role="alert"]').isExisting()).toBe(false);
  912. expect(
  913. probe.samples
  914. .filter((sample: any) => sample.loading)
  915. .every((sample: any) => sample.display === sample.previous),
  916. ).toBe(true);
  917. await browser.keys("Escape");
  918. });
  919. }
  920. it("CTP-21: 调思考后解析未返回时选模型不能留下空档位", async function () {
  921. this.timeout(120000);
  922. await prepareScenario("both", PERSONAL_PLAN_KEY);
  923. const trigger = $(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  924. await trigger.waitForClickable({ timeout: 30000 });
  925. await trigger.click();
  926. await $('[data-testid="composer-thought-slider"]').waitForDisplayed();
  927. // 挂起真实 Renderer -> Host 的下一次选择读取,确定性覆盖用户连续操作窗口。
  928. await browser.execute(() => {
  929. const element = document.querySelector('[data-testid="v4-model-config"]')!;
  930. let fiber = (element as any)[
  931. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  932. ];
  933. let service: any;
  934. while (fiber && !service) {
  935. service =
  936. fiber.memoizedProps?.value?.modelSelectionService ??
  937. fiber.memoizedProps?.services?.modelSelectionService;
  938. fiber = fiber.return;
  939. }
  940. if (!service) throw new Error("ModelSelectionService not found");
  941. const original = service.getView.bind(service);
  942. let release!: () => void;
  943. const pending = new Promise<void>((resolve) => {
  944. release = resolve;
  945. });
  946. service.getView = async (...args: any[]) => {
  947. await pending;
  948. return original(...args);
  949. };
  950. Object.assign(window, {
  951. __releaseSelectionRead: () => {
  952. service.getView = original;
  953. release();
  954. },
  955. });
  956. });
  957. try {
  958. const slider = $('[data-testid="composer-thought-slider"]');
  959. await slider.click();
  960. await browser.keys("Home");
  961. expect(await $('[data-testid="composer-provider-loading"]').isExisting()).toBe(false);
  962. await writeFile(
  963. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "reasoning-read-menu.json"),
  964. JSON.stringify(
  965. await browser.execute(() => ({
  966. config: (document.querySelector('[data-testid="v4-model-config"]') as HTMLElement)
  967. ?.dataset,
  968. menu: Array.from(document.querySelectorAll('[role="menu"]')).map((e) => e.textContent),
  969. })),
  970. null,
  971. 2,
  972. ),
  973. );
  974. const flash = (await $$('[data-composer-model-list] [role="menuitemradio"]'))[1]!;
  975. await flash.click();
  976. await browser.waitUntil(
  977. async () =>
  978. (await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-model")) === "GLM-5.3-Flash",
  979. );
  980. expect(await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought")).not.toBe("");
  981. } finally {
  982. await browser.execute(() => (window as any).__releaseSelectionRead());
  983. }
  984. await $('[data-testid="composer-thought-slider"]').waitForDisplayed();
  985. expect(await $(sel(TID_V4_MODEL_CONFIG)).getAttribute("data-thought")).not.toBe("");
  986. await browser.keys("Escape");
  987. });
  988. for (const locale of ["zh-CN", "en-US"] as const) {
  989. it(`CTP-02B: 侧栏头像菜单应显示当前已确认的 Team Plan 标签(${locale})`, async function () {
  990. this.timeout(120000);
  991. await prepareScenario("teamOnly", TEAM_PLAN_KEY, "none", "none", locale);
  992. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  993. const profileTrigger = $(sel(TID_LOGIN_TRIGGER));
  994. await profileTrigger.waitForDisplayed({
  995. timeout: 30000,
  996. timeoutMsg: "侧栏头像入口没有出现",
  997. });
  998. // 英文 UI 的套餐标签为 Team;只断言徽标本身,避免用户名包含团队文字时误通过。
  999. const teamLabel = locale === "zh-CN" ? "团队" : "Team";
  1000. // 套餐标签已移入头像菜单;不再从头像按钮的旧布局查找。
  1001. await profileTrigger.click();
  1002. const badge = $('[data-testid="profile-menu-plan"]').$(`span[title="${teamLabel}"]`);
  1003. await badge.waitForDisplayed({ timeout: 30000 });
  1004. await expect(badge).toHaveText(teamLabel);
  1005. await browser.keys("Escape");
  1006. });
  1007. }
  1008. it("CTP-03: 用户头像菜单应进入 Team Plan 使用统计并请求团队额度", async function () {
  1009. this.timeout(120000);
  1010. await prepareScenario("teamOnly", TEAM_PLAN_KEY);
  1011. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1012. await openSidebarUsageStats();
  1013. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  1014. await clickUsageCodingPlanTab(TEAM_PLAN_KEY);
  1015. await assertBodyTextIncludes(["Team Org", "90%"]);
  1016. await waitForMockRequest(
  1017. (request) =>
  1018. request.path.endsWith("/api/monitor/usage/quota/limit") &&
  1019. request.query.type === "2" &&
  1020. request.headers["bigmodel-organization"] === "org-team-a" &&
  1021. request.headers["bigmodel-project"] === "proj-team-a",
  1022. "头像菜单未按 Team Plan 请求 quota/limit?type=2",
  1023. );
  1024. });
  1025. it("CTP-04: 使用统计编程套餐应显示 Team Plan 额度、模型用量和工具用量", async function () {
  1026. this.timeout(120000);
  1027. await prepareScenario("teamOnly", TEAM_PLAN_KEY);
  1028. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1029. await assertBodyTextIncludes(["Team Org", "90%", "glm-credit-e2e"]);
  1030. await assertBodyTextIncludesAny(["Models", "模型"]);
  1031. await clickVisibleButtonByText(["Tools", "工具"]);
  1032. await assertBodyTextIncludes(["E2E Search MCP"]);
  1033. await waitForMockRequest(
  1034. (request) =>
  1035. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1036. request.query.usageType === "MODEL" &&
  1037. request.headers["bigmodel-organization"] === "org-team-a" &&
  1038. request.headers["bigmodel-project"] === "proj-team-a",
  1039. "使用统计未按 Team Plan 请求 MODEL credit detail",
  1040. );
  1041. await waitForMockRequest(
  1042. (request) =>
  1043. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1044. request.query.usageType === "MCP" &&
  1045. request.headers["bigmodel-organization"] === "org-team-a" &&
  1046. request.headers["bigmodel-project"] === "proj-team-a",
  1047. "使用统计未按 Team Plan 请求 MCP credit detail",
  1048. );
  1049. });
  1050. it("CTP-04B: 个人套餐应展示 credit activity、明细与性能数据", async function () {
  1051. this.timeout(120000);
  1052. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  1053. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1054. await assertBodyTextIncludes(["glm-credit-e2e"]);
  1055. await assertBodyTextIncludesAny(["Credits total", "积分总数"]);
  1056. await clickVisibleButtonByText(["Tools", "工具"]);
  1057. await assertBodyTextIncludes(["E2E Search MCP"]);
  1058. await waitForMockRequest(
  1059. (request) =>
  1060. request.path.endsWith("/api/monitor/credit-usage/activity") &&
  1061. request.query.type === "1" &&
  1062. !request.headers["bigmodel-organization"] &&
  1063. !request.headers["bigmodel-project"],
  1064. "个人套餐没有请求隔离的 credit activity",
  1065. );
  1066. await waitForMockRequest(
  1067. (request) =>
  1068. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1069. request.query.usageType === "MODEL",
  1070. "个人套餐没有请求 MODEL credit detail",
  1071. );
  1072. await waitForMockRequest(
  1073. (request) => request.path.endsWith("/api/monitor/usage/model-performance-day"),
  1074. "个人套餐没有请求 model performance",
  1075. );
  1076. });
  1077. for (const locale of ["zh-CN", "en-US"] as const) {
  1078. it(`CTP-05: 切换连接后可分别查看个人与团队用量来源(${locale})`, async function () {
  1079. this.timeout(180000);
  1080. await prepareScenario("both", TEAM_PLAN_KEY, "none", "none", locale);
  1081. await openModelProviderSettings();
  1082. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  1083. timeout: 30000,
  1084. timeoutMsg: "BigModel 供应商导航项没有出现",
  1085. });
  1086. await selectConnectionModeOptionByTestId(
  1087. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, PERSONAL_PLAN_CONNECTION_KEY),
  1088. "个人 Coding Plan",
  1089. );
  1090. await waitForBigModelConnectionSelection("individual-coding-plan");
  1091. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1092. await assertBodyTextIncludes(["70%", "glm-credit-e2e"]);
  1093. // 使用统计的个人页签是 Individual Plan,不是设置页左侧的 Coding Plan。
  1094. const personalTab = $(sel(testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${PERSONAL_PLAN_KEY}`)));
  1095. await expect(personalTab).toHaveText(locale === "zh-CN" ? "个人套餐" : "Individual Plan");
  1096. await expect(personalTab).toHaveAttribute("aria-pressed", "true");
  1097. // 使用统计按账号展示全部来源;团队 tab 的名称不代表个人面板泄漏团队额度。
  1098. const teamTab = $(sel(testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${TEAM_PLAN_KEY}`)));
  1099. // 个人额度先返回,团队来源随后异步加入;等待目标来源渲染后再校验未选中状态。
  1100. await teamTab.waitForDisplayed({ timeout: 30_000 });
  1101. await expect(teamTab).toHaveText("Team Org");
  1102. await expect(teamTab).toHaveAttribute("aria-pressed", "false");
  1103. await openModelProviderSettings();
  1104. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  1105. timeout: 30000,
  1106. timeoutMsg: "BigModel 供应商导航项没有出现",
  1107. });
  1108. await selectConnectionModeOptionByTestId(
  1109. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, TEAM_PLAN_KEY),
  1110. "Team Org",
  1111. );
  1112. await waitForBigModelConnectionSelection("team-coding-plan");
  1113. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1114. await assertBodyTextIncludes(["Team Org", "90%", "glm-credit-e2e"]);
  1115. });
  1116. }
  1117. it("CTP-06: 启动恢复 OAuth 时应保留已选择的 Team Plan", async function () {
  1118. this.timeout(120000);
  1119. await prepareScenario("both", TEAM_PLAN_KEY);
  1120. await waitForMockRequest(
  1121. (request) => request.path.endsWith("/subscription/enterprise/v2/pricing"),
  1122. "启动恢复 OAuth 时未请求企业套餐 pricing",
  1123. );
  1124. await browser.waitUntil(
  1125. async () => {
  1126. const selection = (await readSettings()).providerFamilyConnectionSelections?.bigmodel;
  1127. return (
  1128. selection?.kind === "team-coding-plan" &&
  1129. selection.productId === "product-team-a" &&
  1130. selection.organizationId === "org-team-a" &&
  1131. selection.projectId === "proj-team-a"
  1132. );
  1133. },
  1134. {
  1135. timeout: 15000,
  1136. timeoutMsg: "启动恢复 OAuth 后结构化 Team Plan selection 被覆盖",
  1137. },
  1138. );
  1139. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1140. await waitForMockRequest(
  1141. (request) =>
  1142. request.path.endsWith("/api/monitor/usage/quota/limit") &&
  1143. request.query.type === "2" &&
  1144. request.headers["bigmodel-organization"] === "org-team-a" &&
  1145. request.headers["bigmodel-project"] === "proj-team-a",
  1146. "启动恢复 OAuth 后使用统计未继续按 Team Plan 请求 quota/limit?type=2",
  1147. );
  1148. });
  1149. it("CTP-07: 切换 7d/30d 应重新请求不同日期窗口且保持当前来源", async function () {
  1150. this.timeout(120000);
  1151. await prepareScenario("both", TEAM_PLAN_KEY);
  1152. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1153. await clickVisibleButtonByText(["30 days", "近 30 日"]);
  1154. const thirtyDayRequest = await waitForLatestMockRequest(
  1155. (request) =>
  1156. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1157. request.query.usageType === "MODEL" &&
  1158. request.query.type === "3" &&
  1159. requestRangeDays(request) === 29,
  1160. "切换 30d 后没有请求新的日期窗口",
  1161. );
  1162. expect(thirtyDayRequest.headers["bigmodel-organization"]).toBe("org-team-a");
  1163. expect(thirtyDayRequest.headers["bigmodel-project"]).toBe("proj-team-a");
  1164. expect(
  1165. daysBetweenMonitorTimes(
  1166. requireQueryValue(thirtyDayRequest, "startTime"),
  1167. requireQueryValue(thirtyDayRequest, "endTime"),
  1168. ),
  1169. ).toBe(29);
  1170. await clickVisibleButtonByText(["7 days", "近 7 日"]);
  1171. await waitForMockRequest(
  1172. (request) =>
  1173. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1174. request.query.usageType === "MODEL" &&
  1175. request.query.type === "3" &&
  1176. requestRangeDays(request) === 6,
  1177. "切回 7d 后没有恢复对应日期窗口",
  1178. );
  1179. });
  1180. it("CTP-08: 窄窗口下 Usage tabs、range 与热力图仍可操作", async function () {
  1181. this.timeout(120000);
  1182. await setRendererViewport(430, 760);
  1183. try {
  1184. // 本 Case 只验证窄窗口交互,不额外绑定“个人 + Team 同时存在时启动恢复
  1185. // 自动选择哪个套餐”的产品规则;使用单一个人权益保持夹具职责清晰。
  1186. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  1187. await setSettingsTheme("zai-dark");
  1188. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1189. await clickVisibleButtonByText(["30 days", "近 30 日"]);
  1190. await assertBodyTextIncludes(["glm-credit-e2e"]);
  1191. await assertBodyTextIncludesAny(["Token activity", "Token 活动"]);
  1192. } finally {
  1193. await setSettingsTheme("zai-light");
  1194. await clearRendererViewport();
  1195. }
  1196. });
  1197. it("CTP-09: activity 可选接口失败不拖垮 quota,刷新后恢复", async function () {
  1198. this.timeout(120000);
  1199. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "optionalActivity");
  1200. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1201. await assertBodyTextIncludes(["70%", "glm-credit-e2e"]);
  1202. await assertBodyTextExcludes(["350.7K", "35.1万", "35.1 万"]);
  1203. await setMockScenario("personalOnly", "none");
  1204. await clickVisibleButtonByText(["Refresh", "刷新"]);
  1205. await assertBodyTextIncludesAny(["350.7K", "35.1万", "35.1 万"]);
  1206. await waitForMockRequest(
  1207. (request) => request.path.endsWith("/api/monitor/credit-usage/activity"),
  1208. "activity 恢复后刷新没有重新请求",
  1209. );
  1210. });
  1211. it("CTP-10: Context hover 应按 access freshness 展示同一额度快照", async function () {
  1212. this.timeout(120000);
  1213. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  1214. await selectBigModelCodingPlanRuntime("individual-coding-plan");
  1215. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  1216. await trigger.waitForDisplayed({
  1217. timeout: 15000,
  1218. timeoutMsg: "Context usage trigger 没有出现",
  1219. });
  1220. await trigger.moveTo();
  1221. await assertBodyTextIncludes(["70%"]);
  1222. await assertBodyTextIncludesAny(["5 hours", "5 小时"]);
  1223. await waitForMockRequest(
  1224. (request) =>
  1225. request.path.endsWith("/api/monitor/usage/quota/limit") && request.query.type !== "2",
  1226. "Context access 没有读取个人套餐 quota",
  1227. );
  1228. });
  1229. for (const [scenario, planKey, width] of [
  1230. ["personalOnly", PERSONAL_PLAN_KEY, 1200],
  1231. ["teamOnly", TEAM_PLAN_KEY, 1200],
  1232. ["personalOnly", PERSONAL_PLAN_KEY, 390],
  1233. ["teamOnly", TEAM_PLAN_KEY, 390],
  1234. ] as const) {
  1235. it(`CTP-11: ${scenario} ${width}px quota 失败保留套餐入口,重新进入来源后恢复`, async function () {
  1236. this.timeout(120000);
  1237. await prepareScenario(scenario, planKey, "quotaBusinessFailure");
  1238. await openUsageSection();
  1239. await setRendererViewport(width, 900);
  1240. // 订阅查询保持成功,quota 业务失败不能撤销权益,确认 tab 不消失;
  1241. // 详情加载再切传输失败,覆盖 fatal 文案与后续恢复。
  1242. await setMockScenario(scenario, "quotaFailure");
  1243. await clickUsageCodingPlanTab(planKey);
  1244. await assertBodyTextIncludesAny([
  1245. "Unable to load usage stats",
  1246. "无法读取用量统计。请稍后重试,或检查网络和供应商配置。",
  1247. ]);
  1248. await assertBodyTextExcludes(["350.7K", "35.1万", "35.1 万", "glm-credit-e2e"]);
  1249. await setMockScenario(scenario, "none");
  1250. await clickVisibleTestIdByDom(testId(TID_SETTINGS_USAGE_TAB, "app"), {
  1251. timeout: 10000,
  1252. timeoutMsg: "致命失败恢复时无法切换到 App Usage",
  1253. });
  1254. await clickUsageCodingPlanTab(planKey);
  1255. await assertBodyTextIncludes([scenario === "teamOnly" ? "90%" : "70%", "glm-credit-e2e"]);
  1256. await assertBodyTextIncludesAny(["350.7K", "35.1万", "35.1 万"]);
  1257. });
  1258. }
  1259. it("QR-E2E-01: 空状态应调用 opportunity 并以强制 status 结果展示机会", async function () {
  1260. this.timeout(120000);
  1261. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "emptyThenGrant");
  1262. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1263. await waitForMockRequest(
  1264. (request) => request.path.endsWith("/api/v1/coding-plan/reset/opportunity"),
  1265. "空 reset 状态没有触发 opportunity",
  1266. );
  1267. await waitForResetOpportunityCount(1);
  1268. const resetPaths = (await readMockRequests())
  1269. .map((request) => request.path)
  1270. .filter((path) => path.includes("/api/v1/coding-plan/reset/"));
  1271. const opportunityIndex = resetPaths.findIndex((path) => path.endsWith("/opportunity"));
  1272. expect(opportunityIndex).toBeGreaterThan(0);
  1273. expect(resetPaths.slice(opportunityIndex + 1).some((path) => path.endsWith("/status"))).toBe(
  1274. true,
  1275. );
  1276. // QR-E2E-05:单机会徽标同样可点击并打开重置弹框(单机会不展示次数药丸,仅交互升级为按钮)。
  1277. await clickResetOpportunityBadge();
  1278. await assertBodyTextIncludesAny(["可重置额度", "Resettable quota"]);
  1279. await assertBodyTextIncludesAny(["5 小时额度重置", "5-hour quota reset"]);
  1280. });
  1281. it("QR-E2E-02: 已有多类型机会时仍调用 opportunity,Dialog 只展示 status 权威数量", async function () {
  1282. this.timeout(120000);
  1283. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  1284. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1285. await waitForMockRequest(
  1286. (request) => request.path.endsWith("/api/v1/coding-plan/reset/opportunity"),
  1287. "已有 reset 机会时没有继续触发 scope opportunity",
  1288. );
  1289. await waitForResetOpportunityCount(3);
  1290. await clickResetOpportunityBadge();
  1291. await assertBodyTextIncludesAny(["可重置额度", "Resettable quota"]);
  1292. await assertBodyTextIncludesAny(["5 小时额度重置", "5-hour quota reset"]);
  1293. await assertBodyTextIncludesAny(["周额度重置", "Weekly quota reset"]);
  1294. // 次数不再汇总到标题;FIVE_HOUR 持有 2 张机会,改由该行的次数药丸展示。
  1295. await assertBodyTextIncludesAny(["2 次", "×2"]);
  1296. });
  1297. it("QR-E2E-09: Composer 应常驻展示首次机会提醒并在 hover 后收起", async function () {
  1298. this.timeout(120000);
  1299. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  1300. await reloadRendererWithBigModelCodingPlanSelection();
  1301. await waitForContextResetReminder("initial", ["3 次重置额度", "3 reset available"]);
  1302. await assertContextReminderHiddenInSettings("initial");
  1303. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  1304. await trigger.moveTo();
  1305. await browser.waitUntil(async () => !(await isContextResetReminderVisible("initial")), {
  1306. timeout: 10000,
  1307. timeoutMsg: "打开 Context 后首次 reset opportunity 提醒仍未收起",
  1308. });
  1309. });
  1310. it("QR-E2E-10: 最早机会进入最后三分钟时应常驻展示临期提醒", async function () {
  1311. this.timeout(120000);
  1312. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "urgentOpportunity");
  1313. await reloadRendererWithBigModelCodingPlanSelection();
  1314. await waitForContextResetReminder("urgent", ["重置额度过期", "Reset expires in"]);
  1315. await assertContextReminderHiddenInSettings("urgent");
  1316. const alarmAnimation = await browser.execute(() => {
  1317. const icon = document.querySelector<HTMLElement>(
  1318. '[data-context-reset-reminder="urgent"] .animate-zcode-alarm-ring',
  1319. );
  1320. return icon ? window.getComputedStyle(icon).animationName : null;
  1321. });
  1322. expect(alarmAnimation).toBe("zcode-alarm-ring");
  1323. });
  1324. it("QR-E2E-04: Composer Dialog 打开期间应保持 HoverCard 生命周期", async function () {
  1325. this.timeout(120000);
  1326. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  1327. await selectBigModelCodingPlanRuntime("individual-coding-plan");
  1328. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  1329. await trigger.waitForDisplayed({
  1330. timeout: 15000,
  1331. timeoutMsg: "Context usage trigger 没有出现",
  1332. });
  1333. await trigger.moveTo();
  1334. await waitForResetOpportunityCount(3, '[data-slot="hover-card-content"]');
  1335. await clickResetOpportunityBadge('[data-slot="hover-card-content"]');
  1336. await browser.waitUntil(
  1337. async () => {
  1338. const state = await readQuotaResetOverlayState();
  1339. return state.dialogVisible && state.hoverCardVisible;
  1340. },
  1341. {
  1342. timeout: 10000,
  1343. timeoutMsg: "重置 Dialog 打开后 Composer HoverCard 被提前卸载",
  1344. },
  1345. );
  1346. await browser.keys("Escape");
  1347. await browser.waitUntil(
  1348. async () => {
  1349. const state = await readQuotaResetOverlayState();
  1350. return !state.dialogVisible && !state.hoverCardVisible;
  1351. },
  1352. {
  1353. timeout: 10000,
  1354. timeoutMsg: "关闭重置 Dialog 后 Composer HoverCard 没有一起收起",
  1355. },
  1356. );
  1357. });
  1358. it("QR-E2E-03: FIVE_HOUR use 必须等待 status used_at 后才完成", async function () {
  1359. this.timeout(120000);
  1360. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "fiveHourUse");
  1361. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1362. await waitForResetOpportunityCount(2);
  1363. await clickResetOpportunityBadge();
  1364. const resetButton = await findVisibleButtonByAriaLabels(
  1365. ["重置 5 小时额度", "Reset 5-hour quota"],
  1366. true,
  1367. '[role="dialog"]',
  1368. );
  1369. if (!resetButton) throw new Error("没有找到 FIVE_HOUR reset 按钮");
  1370. await resetButton.click();
  1371. await waitForMockRequest(
  1372. (request) =>
  1373. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  1374. isRecord(request.body) &&
  1375. request.body.reset_type === "FIVE_HOUR",
  1376. "五小时重置没有发送 reset_type=FIVE_HOUR",
  1377. );
  1378. // 双 JWT 契约:Authorization 传 Bearer zcode JWT,X-Bigmodel-Authorization 直传 MaaS JWT。
  1379. const useRequest = (await readMockRequests()).find((request) =>
  1380. request.path.endsWith("/api/v1/coding-plan/reset/use"),
  1381. );
  1382. expect(useRequest?.headers.authorization).toBe("Bearer e2e-zcode-jwt");
  1383. expect(useRequest?.headers["x-bigmodel-authorization"]).toBe("e2e-bigmodel-oauth-token");
  1384. // 时序约束:客户端 use 后的 status 确认重试窗口只有约 2.5 秒,confirm 前的每次检查
  1385. // 必须是单次 execute 往返,不能逐按钮发 WebDriver 命令,否则慢机器上会先触发客户端
  1386. // 失败分支,confirm 之后成功态永远不会出现。
  1387. const processingState = await readDialogResetState();
  1388. if (processingState.resetDisabled !== true || processingState.successVisible) {
  1389. throw new Error(
  1390. `status used_at 未确认前没有保持 processing: ${JSON.stringify(processingState)}`,
  1391. );
  1392. }
  1393. await confirmResetUse();
  1394. await browser.waitUntil(async () => (await readDialogResetState()).successVisible, {
  1395. interval: 100,
  1396. timeout: 10000,
  1397. timeoutMsg: "status used_at 更新后没有显示成功状态",
  1398. });
  1399. await waitForMockRequest(
  1400. (request) => request.path.endsWith("/api/v1/coding-plan/reset/history/read"),
  1401. "确认 reset used_at 后没有上报 history/read",
  1402. );
  1403. });
  1404. it("QR-E2E-14: 同类型多张机会核销一张后,弹框不重开即可展示并核销余下机会", async function () {
  1405. this.timeout(120000);
  1406. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "multiFiveHourUse");
  1407. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1408. await waitForResetOpportunityCount(3);
  1409. await clickResetOpportunityBadge();
  1410. await assertBodyTextIncludesAny(["2 次", "×2"]);
  1411. await clickDialogFiveHourReset("没有找到 FIVE_HOUR reset 按钮");
  1412. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 1, {
  1413. timeout: 10000,
  1414. timeoutMsg: "第一次五小时重置没有发送 /use",
  1415. });
  1416. // 回归点:成功反馈结束后该行留在弹框内,直接展示余下 1 张的真实倒计时并恢复可点击;
  1417. // 旧实现在这里显示「0 分 0 秒后过期」,且再次点击被静默忽略,只能关闭重开弹框。
  1418. await waitForDialogResetState(
  1419. (state) =>
  1420. state.resetDisabled === false &&
  1421. !state.successVisible &&
  1422. state.weekResetVisible &&
  1423. state.resetRowText !== null &&
  1424. !["2 次", "×2", "0 分 0 秒", "0m 0s"].some((text) => state.resetRowText?.includes(text)),
  1425. "核销一张后余下机会没有在弹框内直接恢复为可核销",
  1426. );
  1427. await clickDialogFiveHourReset("核销一张后没有找到余下机会的 FIVE_HOUR reset 按钮");
  1428. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 2, {
  1429. timeout: 10000,
  1430. timeoutMsg: "余下机会的再次点击没有真实发送 /use",
  1431. });
  1432. const idempotencyKeys = (await readFiveHourUseRequests()).map((request) =>
  1433. isRecord(request.body) ? request.body.idempotency_key : undefined,
  1434. );
  1435. expect(new Set(idempotencyKeys).size).toBe(2);
  1436. // 机会耗尽后五小时行收起,周额度行不受影响、也不会被误核销。
  1437. await waitForDialogResetState(
  1438. (state) => state.resetDisabled === null && !state.successVisible && state.weekResetVisible,
  1439. "五小时机会耗尽后该行没有收起",
  1440. );
  1441. expect(
  1442. (await readMockRequests()).some(
  1443. (request) =>
  1444. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  1445. isRecord(request.body) &&
  1446. request.body.reset_type === "WEEK",
  1447. ),
  1448. ).toBe(false);
  1449. });
  1450. it("QR-E2E-15: 完成态再次核销时 status 仍是上一张 used_at,读到新 used_at 才确认成功", async function () {
  1451. this.timeout(120000);
  1452. // mock 让 /use 结果延迟 600ms 才在 /status 可见,窗口内 /status 仍返回上一张的 used_at。
  1453. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "multiFiveHourUseLagging");
  1454. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1455. await waitForResetOpportunityCount(3);
  1456. await clickResetOpportunityBadge();
  1457. await assertBodyTextIncludesAny(["2 次", "×2"]);
  1458. await clickDialogFiveHourReset("没有找到 FIVE_HOUR reset 按钮");
  1459. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 1, {
  1460. timeout: 10000,
  1461. timeoutMsg: "第一次五小时重置没有发送 /use",
  1462. });
  1463. await waitForDialogResetState(
  1464. (state) => state.resetDisabled === false && !state.successVisible && state.weekResetVisible,
  1465. "第一次核销后余下机会没有恢复为可核销",
  1466. );
  1467. await clickDialogFiveHourReset("核销一张后没有找到余下机会的 FIVE_HOUR reset 按钮");
  1468. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 2, {
  1469. timeout: 10000,
  1470. timeoutMsg: "余下机会的再次点击没有真实发送 /use",
  1471. });
  1472. // 回归点:旧实现把滞后快照里上一张的 used_at 当作第二次成功,提前播放成功反馈后该行
  1473. // 回到「余 1 张可点击」,直到下一次 60s 轮询才收起。修复后保持处理中,读到新 used_at 才完成。
  1474. let revertedToClickable = false;
  1475. await waitForDialogResetState((state) => {
  1476. revertedToClickable ||= state.resetDisabled === false;
  1477. return state.resetDisabled === null && !state.successVisible && state.weekResetVisible;
  1478. }, "完成态再次核销后五小时行没有随机会耗尽收起");
  1479. expect(revertedToClickable).toBe(false);
  1480. expect(await readFiveHourUseRequests()).toHaveLength(2);
  1481. });
  1482. });
  1483. async function prepareScenario(
  1484. scenario: CodingPlanScenario,
  1485. bigmodelSelectedKey: string,
  1486. faultMode: CodingPlanFaultMode = "none",
  1487. resetScenario: CodingPlanResetScenario = "none",
  1488. locale?: "zh-CN" | "en-US",
  1489. loggedOut = false,
  1490. ) {
  1491. // 修复原因:同一 spec 会连续切换个人/团队套餐场景。必须在旧 Electron 退出前清理
  1492. // file:// origin 的 entitlement 缓存;退出后再执行 browser.execute 会被异常吞掉,
  1493. // 上一场景的 Team 快照就会污染下一场景。
  1494. await clearUsageEntitlementCache();
  1495. // Bug 根因:旧 Electron/host 仍存活时直接改 setting.json,退出阶段的异步写回
  1496. // 会把下一场景的夹具覆盖成上一场景。先等进程完整退出,再写持久化夹具,最后
  1497. // 让 reloadSession 只负责创建新应用,场景边界才是确定的。
  1498. await quitElectronAppGracefully();
  1499. await setMockScenario(scenario, faultMode);
  1500. await setResetMockScenario(resetScenario);
  1501. await writeCredentials({
  1502. "oauth:active_provider": "bigmodel",
  1503. "oauth:bigmodel:access_token": "e2e-bigmodel-oauth-token",
  1504. "oauth:bigmodel:user_info": JSON.stringify({
  1505. displayName: "BigModel E2E",
  1506. id: "bigmodel-e2e-user",
  1507. username: "bigmodel-e2e-user",
  1508. }),
  1509. zcodejwttoken:
  1510. resetScenario === "none" &&
  1511. !faultMode.startsWith("startBalance") &&
  1512. faultMode !== "expiredTeam"
  1513. ? ""
  1514. : "e2e-zcode-jwt",
  1515. });
  1516. if (loggedOut)
  1517. await writeCredentials({
  1518. "oauth:active_provider": "",
  1519. "oauth:bigmodel:access_token": "",
  1520. "oauth:bigmodel:user_info": "",
  1521. "oauth:zai:access_token": "",
  1522. "oauth:zai:user_info": "",
  1523. zcodejwttoken: "",
  1524. });
  1525. const connectionSelection = parseBigModelConnectionSelection(bigmodelSelectedKey);
  1526. await writeSettings({
  1527. ...(locale ? { locale, localePreference: locale } : {}),
  1528. providerFamilyConnectionSelections: {
  1529. bigmodel: connectionSelection,
  1530. },
  1531. providerFamilyDomain: "bigmodel",
  1532. providerFamilyDomainMigrated: true,
  1533. // Bug 根因:同一 spec 多次 reloadSession 会继承前一场景关闭时写回的 workspace。
  1534. // Team Plan case 的 model-resolution seed 明确写 DEFAULT_WORKSPACE,因此启动入口也
  1535. // 必须固定到同一个 project workspace,不能偶发落入 conversation workspace。
  1536. lastWorkspaceSession: [
  1537. {
  1538. kind: "local",
  1539. workspacePath: DEFAULT_WORKSPACE,
  1540. workspacePurpose: "project",
  1541. },
  1542. ],
  1543. lastActiveTabIndex: 0,
  1544. });
  1545. // 修复原因:Electron E2E 的 file:// renderer 直接 browser.refresh()
  1546. // 偶发落到 chrome-error://chromewebdata,后续等待会每条 case 慢 30s。
  1547. // 场景切换需要让 main/host 重新读取磁盘设置,因此使用 reloadSession 重建应用。
  1548. await browser.reloadSession();
  1549. // Escape 只临时关闭职业引导;重载 Renderer 会再次遮住 Composer。
  1550. // 复用真实 Skip 流程完成隔离账号的引导,保证重载类 case 的前置状态持久化。
  1551. await skipOccupationOnboardingIfPresent();
  1552. await waitForDefaultWorkspaceReady(60000);
  1553. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1554. await closeTransientOverlays();
  1555. await waitForProviderConfigPolling();
  1556. }
  1557. function parseBigModelConnectionSelection(selectedKey: string) {
  1558. if (selectedKey === BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan)
  1559. return { kind: "start-plan" as const };
  1560. const parts = selectedKey.split(":");
  1561. if (parts[0] !== "team") {
  1562. return { kind: "individual-coding-plan" as const };
  1563. }
  1564. const [, family, productId, organizationId, projectId] = parts;
  1565. if (family !== "bigmodel" || !productId || !organizationId || !projectId) {
  1566. throw new Error(`无效 Team Plan key: ${selectedKey}`);
  1567. }
  1568. return {
  1569. kind: "team-coding-plan" as const,
  1570. productId,
  1571. organizationId,
  1572. projectId,
  1573. };
  1574. }
  1575. async function waitForBigModelConnectionSelection(
  1576. kind: "individual-coding-plan" | "team-coding-plan",
  1577. ) {
  1578. await browser.waitUntil(
  1579. async () => (await readSettings()).providerFamilyConnectionSelections?.bigmodel?.kind === kind,
  1580. {
  1581. timeout: 15000,
  1582. timeoutMsg: `BigModel 连接方式没有收敛到 ${kind}`,
  1583. },
  1584. );
  1585. await waitForProviderConfigPolling();
  1586. }
  1587. async function clearUsageEntitlementCache() {
  1588. // 修复原因:本 spec 会在同一 file:// origin 内切换 personalOnly/teamOnly mock。
  1589. // useUsageEntitlement 的短 TTL localStorage 缓存会保留上个场景的 no_plan,
  1590. // 导致下一次打开 Usage 页时 Coding Plan tab 被误判为不存在。
  1591. try {
  1592. await browser.execute(() => {
  1593. const prefix = "zcode:usage-entitlement:";
  1594. for (const key of Object.keys(window.localStorage)) {
  1595. if (key.startsWith(prefix)) {
  1596. window.localStorage.removeItem(key);
  1597. }
  1598. }
  1599. });
  1600. } catch {
  1601. // reloadSession 前后偶发没有可执行 renderer;缓存清理失败不阻塞场景重建。
  1602. }
  1603. }
  1604. async function openModelProviderSettings() {
  1605. await closeTransientOverlays();
  1606. await ensureSettingsPageOpen();
  1607. await clickVisibleTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "modelProvider"), {
  1608. timeout: 10000,
  1609. timeoutMsg: "设置页没有出现模型供应商分区入口",
  1610. });
  1611. }
  1612. async function assertConnectionModeOptionsInclude(
  1613. expectedOptions: Array<{ key: string; labels: string[] }>,
  1614. ) {
  1615. await openConnectionModeSelect();
  1616. try {
  1617. for (const expectedOption of expectedOptions) {
  1618. const optionTestId = testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, expectedOption.key);
  1619. const option = await $(sel(optionTestId));
  1620. await option.waitForDisplayed({
  1621. timeout: 10000,
  1622. timeoutMsg: `没有找到连接方式选项: ${optionTestId}`,
  1623. });
  1624. const optionText = await option.getText();
  1625. expect(expectedOption.labels.some((label) => optionText.includes(label))).toBe(true);
  1626. }
  1627. } finally {
  1628. await browser.keys("Escape");
  1629. }
  1630. }
  1631. async function selectConnectionModeOptionByTestId(optionTestId: string, labelForError: string) {
  1632. await openConnectionModeSelect();
  1633. const option = await $(sel(optionTestId));
  1634. await option.waitForDisplayed({
  1635. timeout: 10000,
  1636. timeoutMsg: `没有找到连接方式选项: ${labelForError}`,
  1637. });
  1638. await option.click();
  1639. }
  1640. async function openConnectionModeSelect() {
  1641. await clickVisibleTestIdByDom(TID_MODEL_PROVIDER_CONNECTION_MODE_TRIGGER, {
  1642. timeout: 10000,
  1643. timeoutMsg: "连接方式选择器没有出现",
  1644. });
  1645. }
  1646. async function openUsageCodingPlanTab(sourceId?: string) {
  1647. await openUsageSection();
  1648. await clickUsageCodingPlanTab(sourceId);
  1649. await assertBodyTextIncludesAny(["剩余额度", "Quota remaining", "Quota Remaining"]);
  1650. }
  1651. async function openUsageSection() {
  1652. await closeTransientOverlays();
  1653. await ensureSettingsPageOpen();
  1654. await clickVisibleTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "usage"), {
  1655. timeout: 10000,
  1656. timeoutMsg: "设置页没有出现使用统计分区入口",
  1657. });
  1658. }
  1659. async function ensureSettingsPageOpen() {
  1660. const settingsPage = $(sel(TID_SETTINGS_PAGE));
  1661. if (!(await settingsPage.isDisplayed().catch(() => false))) {
  1662. // Bug 根因:设置新架构会同时保留响应式导航的隐藏副本,旧 helper 取第一个
  1663. // test-id 时可能点中不可见节点并关闭设置页,导致后续误报 Coding Plan tab 消失。
  1664. await clickVisibleTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  1665. timeout: 10000,
  1666. timeoutMsg: "没有找到设置入口按钮",
  1667. });
  1668. await settingsPage.waitForDisplayed({ timeout: 10000 });
  1669. }
  1670. }
  1671. async function openSidebarUsageStats() {
  1672. await closeTransientOverlays();
  1673. await clickVisibleTestIdByDom(TID_LOGIN_TRIGGER, {
  1674. timeout: 10000,
  1675. timeoutMsg: "没有找到头像菜单入口",
  1676. });
  1677. await clickVisibleTestIdByDom(TID_SIDEBAR_CODING_PLAN_USAGE_BUTTON, {
  1678. timeout: 10000,
  1679. timeoutMsg: "没有找到头像菜单里的使用统计入口",
  1680. });
  1681. }
  1682. async function closeTransientOverlays() {
  1683. await browser.keys("Escape");
  1684. await browser.pause(100);
  1685. }
  1686. async function clickUsageCodingPlanTab(sourceId?: string) {
  1687. // 修复原因:使用统计页从单个 "codingPlan" tab 改为按来源生成
  1688. // "codingPlan:<sourceId>",测试不能再写死旧 test id。
  1689. const staticTabId = testId(TID_SETTINGS_USAGE_TAB, "codingPlan");
  1690. const prefix = `${testId(TID_SETTINGS_USAGE_TAB, "codingPlan:")}`;
  1691. const preferredTabId = sourceId ? testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${sourceId}`) : null;
  1692. let selectedTestId = "";
  1693. try {
  1694. await browser.waitUntil(
  1695. async () => {
  1696. selectedTestId = (await browser.execute(
  1697. (legacyTestId, dynamicPrefix, targetTestId) => {
  1698. const candidates = Array.from(
  1699. document.querySelectorAll<HTMLElement>("[data-testid]"),
  1700. ).filter((element) => {
  1701. const current = element.dataset.testid ?? "";
  1702. return current === legacyTestId || current.startsWith(dynamicPrefix);
  1703. });
  1704. // 修复原因:传入 sourceId 时验证的就是该套餐身份。旧 helper
  1705. // 找不到目标时会静默点击第一个可见 tab,把“个人套餐缺失”伪装成
  1706. // 后续 Team 数据断言失败。指定目标时必须精确命中。
  1707. const ordered = targetTestId
  1708. ? candidates.filter((element) => element.dataset.testid === targetTestId)
  1709. : candidates;
  1710. const visible = ordered.find((element) => {
  1711. const style = window.getComputedStyle(element);
  1712. return !(
  1713. style.display === "none" ||
  1714. style.visibility === "hidden" ||
  1715. Number(style.opacity) === 0 ||
  1716. element.getClientRects().length === 0 ||
  1717. element.closest('[aria-hidden="true"], [hidden]')
  1718. );
  1719. });
  1720. return visible?.dataset.testid ?? "";
  1721. },
  1722. staticTabId,
  1723. prefix,
  1724. preferredTabId,
  1725. )) as string;
  1726. return Boolean(selectedTestId);
  1727. },
  1728. {
  1729. timeout: 30000,
  1730. timeoutMsg: "设置页没有出现使用统计 Coding Plan tab",
  1731. },
  1732. );
  1733. const tab = await $(sel(selectedTestId));
  1734. await tab.click();
  1735. } catch (error) {
  1736. throw new Error(
  1737. `设置页没有出现或无法激活 Coding Plan tab: ${selectedTestId}\n${await collectCodingPlanUsageDiagnostics()}`,
  1738. { cause: error },
  1739. );
  1740. }
  1741. }
  1742. async function setRendererViewport(width: number, height: number) {
  1743. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  1744. deviceScaleFactor: 1,
  1745. height,
  1746. mobile: false,
  1747. width,
  1748. });
  1749. await browser.waitUntil(
  1750. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  1751. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  1752. );
  1753. }
  1754. async function setSettingsTheme(theme: "zai-light" | "zai-dark") {
  1755. const changed = await browser.execute((nextTheme) => {
  1756. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  1757. .__testActions;
  1758. const setTheme = actions?.setTheme;
  1759. if (typeof setTheme !== "function") return false;
  1760. (setTheme as (value: string) => void)(nextTheme);
  1761. return true;
  1762. }, theme);
  1763. expect(changed).toBe(true);
  1764. }
  1765. async function clearRendererViewport() {
  1766. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  1767. }
  1768. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  1769. const sent = await browser.electron.execute(
  1770. async (electron, command, commandParams) => {
  1771. const window = electron.BrowserWindow.getAllWindows().find(
  1772. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  1773. );
  1774. if (!window) return false;
  1775. const devtools = window.webContents.debugger;
  1776. if (!devtools.isAttached()) devtools.attach("1.3");
  1777. await devtools.sendCommand(command, commandParams);
  1778. return true;
  1779. },
  1780. method,
  1781. params,
  1782. );
  1783. expect(sent).toBe(true);
  1784. }
  1785. async function collectCodingPlanUsageDiagnostics() {
  1786. const providers = (await readModelProviders()).map((provider) => ({
  1787. id: provider.id,
  1788. enabled: provider.enabled,
  1789. hasApiKey: provider.apiKey.trim().length > 0,
  1790. systemDisabledReason: provider.systemDisabledReason ?? null,
  1791. }));
  1792. const requests = (await readMockRequests()).map((request) => ({
  1793. path: request.path,
  1794. query: request.query,
  1795. organization: request.headers["bigmodel-organization"] ?? null,
  1796. project: request.headers["bigmodel-project"] ?? null,
  1797. }));
  1798. return `诊断: ${JSON.stringify(
  1799. {
  1800. bodyText: (await getBodyText()).slice(0, 2000),
  1801. providers,
  1802. requests,
  1803. },
  1804. null,
  1805. 2,
  1806. )}`;
  1807. }
  1808. async function clickVisibleTestIdByDom(
  1809. currentTestId: string,
  1810. { timeout = 10000, timeoutMsg = `页面没有可见的 test id: ${currentTestId}` } = {},
  1811. ) {
  1812. // 修复原因:头像菜单内容用了 forceMount,隐藏菜单项也会留在 DOM 里。
  1813. // 这里必须等真正可见的菜单项再触发,否则会点到隐藏节点。
  1814. let latestReason = "not-started";
  1815. await browser.waitUntil(
  1816. async () => {
  1817. const result = (await browser.execute((targetTestId) => {
  1818. function isVisible(element: HTMLElement) {
  1819. const style = window.getComputedStyle(element);
  1820. if (
  1821. style.display === "none" ||
  1822. style.visibility === "hidden" ||
  1823. Number(style.opacity) === 0
  1824. ) {
  1825. return false;
  1826. }
  1827. if (element.getClientRects().length === 0) {
  1828. return false;
  1829. }
  1830. return !element.closest('[aria-hidden="true"], [hidden]');
  1831. }
  1832. function dispatchE2EActivation(element: HTMLElement) {
  1833. element.focus();
  1834. const pointerEventCtor = window.PointerEvent ?? MouseEvent;
  1835. for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
  1836. const event =
  1837. type.startsWith("pointer") && pointerEventCtor === window.PointerEvent
  1838. ? new PointerEvent(type, {
  1839. bubbles: true,
  1840. cancelable: true,
  1841. pointerId: 1,
  1842. pointerType: "mouse",
  1843. isPrimary: true,
  1844. })
  1845. : new MouseEvent(type, {
  1846. bubbles: true,
  1847. cancelable: true,
  1848. view: window,
  1849. });
  1850. element.dispatchEvent(event);
  1851. }
  1852. }
  1853. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  1854. (item) => item.dataset.testid === targetTestId && isVisible(item),
  1855. );
  1856. if (!element) {
  1857. return { clicked: false, reason: "missing-visible" };
  1858. }
  1859. const disabled =
  1860. (element instanceof HTMLButtonElement ||
  1861. element instanceof HTMLInputElement ||
  1862. element instanceof HTMLSelectElement ||
  1863. element instanceof HTMLTextAreaElement) &&
  1864. element.disabled;
  1865. if (disabled) {
  1866. return { clicked: false, reason: "disabled" };
  1867. }
  1868. dispatchE2EActivation(element);
  1869. return { clicked: true };
  1870. }, currentTestId)) as { clicked: boolean; reason?: string };
  1871. latestReason = result.reason ?? "clicked";
  1872. return result.clicked;
  1873. },
  1874. {
  1875. timeout,
  1876. timeoutMsg: `${timeoutMsg}: ${latestReason}`,
  1877. },
  1878. );
  1879. }
  1880. async function selectBigModelCodingPlanRuntime(
  1881. planKind: "individual-coding-plan" | "team-coding-plan" = "individual-coding-plan",
  1882. ) {
  1883. const providerId =
  1884. planKind === "team-coding-plan"
  1885. ? "account:bigmodel-team-coding-plan"
  1886. : "account:bigmodel-individual-coding-plan";
  1887. // Bug 根因:只写 selectedSupplierKey 只更新了供应商导航解析状态,并不会更新
  1888. // Composer 的 Effective Model。Context 用量按真实 Effective Provider 判断套餐类型,
  1889. // 因此测试必须和用户一样完成一次 Provider/Model 选择。
  1890. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  1891. includePlainModelFallback: false,
  1892. providerId,
  1893. providerName: "BigModel Coding Plan",
  1894. });
  1895. }
  1896. async function reloadRendererWithBigModelCodingPlanSelection() {
  1897. // Bug 根因:QR-09/10 验证的是 Renderer 首次挂载时的常驻提醒。通过模型菜单选择会
  1898. // 产生提醒外部 pointerdown,从而按产品规则把刚出现的提醒标记为已读;在退出应用前
  1899. // seed 又会被旧 Renderer 的关闭写回覆盖。直接写正式选择存储并只重载 Renderer,
  1900. // 既使用真实 ModelSelection,又不引入测试专用运行时入口或额外 Host 重启。
  1901. await seedPersistedModelSelection({
  1902. modelId: BIGMODEL_E2E_MODEL,
  1903. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1904. reasoningLevel: "max",
  1905. });
  1906. await browser.execute(() => window.location.reload());
  1907. await waitForDefaultWorkspaceReady(60000);
  1908. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1909. await waitForProviderConfigPolling();
  1910. // Bug 根因:直接写 recent selection 只覆盖了草稿的持久化入口;如果当前
  1911. // ModelSelectionView 尚未包含该 Account Provider,Composer 会按现有契约回退到
  1912. // preferredSelection。先通过真实选择控件完成一次有效选择,再重载一次,验证的才是
  1913. // 用户实际会走的 selection -> opportunity 链路,而不是测试专用的 localStorage 假设。
  1914. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  1915. includePlainModelFallback: false,
  1916. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1917. providerName: "BigModel Coding Plan",
  1918. });
  1919. await browser.execute(() => window.location.reload());
  1920. await waitForDefaultWorkspaceReady(60000);
  1921. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1922. await waitForProviderConfigPolling();
  1923. }
  1924. async function setMockScenario(
  1925. scenario: CodingPlanScenario,
  1926. faultMode: CodingPlanFaultMode = "none",
  1927. ) {
  1928. const baseUrl = getMockBaseUrl();
  1929. const response = await fetch(`${baseUrl}/__e2e/coding-plan/scenario`, {
  1930. method: "POST",
  1931. headers: { "content-type": "application/json" },
  1932. body: JSON.stringify({
  1933. faultMode,
  1934. scenario,
  1935. providerResponsive: faultMode.startsWith("startBalance"),
  1936. }),
  1937. });
  1938. if (!response.ok) {
  1939. throw new Error(`切换 Coding Plan mock scenario 失败: ${response.status}`);
  1940. }
  1941. }
  1942. async function setResetMockScenario(resetScenario: CodingPlanResetScenario) {
  1943. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/reset-scenario`, {
  1944. method: "POST",
  1945. headers: { "content-type": "application/json" },
  1946. body: JSON.stringify({ resetScenario }),
  1947. });
  1948. if (!response.ok) {
  1949. throw new Error(`切换 Coding Plan reset mock scenario 失败: ${response.status}`);
  1950. }
  1951. }
  1952. async function confirmResetUse() {
  1953. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/reset-confirm-use`, {
  1954. method: "POST",
  1955. });
  1956. if (!response.ok) {
  1957. throw new Error(`确认 Coding Plan reset use 失败: ${response.status}`);
  1958. }
  1959. }
  1960. async function waitForResetOpportunityCount(count: number, rootSelector?: string) {
  1961. await browser.waitUntil(
  1962. async () => {
  1963. const labels = (await browser.execute((root: string | undefined) => {
  1964. const scope = root ? document.querySelector(root) : document;
  1965. return Array.from(
  1966. scope?.querySelectorAll<HTMLElement>('[data-reset-opportunity="true"]') ?? [],
  1967. )
  1968. .filter((element) => {
  1969. const style = window.getComputedStyle(element);
  1970. return (
  1971. style.display !== "none" &&
  1972. style.visibility !== "hidden" &&
  1973. element.getClientRects().length > 0
  1974. );
  1975. })
  1976. .map((element) => element.innerText.trim());
  1977. }, rootSelector)) as string[];
  1978. return labels.some((label) => label.includes(String(count)));
  1979. },
  1980. {
  1981. timeout: 10000,
  1982. timeoutMsg: `没有展示 ${count} 次 reset opportunity`,
  1983. },
  1984. );
  1985. }
  1986. async function clickResetOpportunityBadge(rootSelector?: string) {
  1987. const selector = rootSelector
  1988. ? `${rootSelector} [data-reset-opportunity="true"]`
  1989. : '[data-reset-opportunity="true"]';
  1990. for (const badge of await $$(selector)) {
  1991. if (await badge.isDisplayed()) {
  1992. await badge.click();
  1993. return;
  1994. }
  1995. }
  1996. throw new Error("没有找到可点击的 reset opportunity 徽标");
  1997. }
  1998. async function isContextResetReminderVisible(phase: "initial" | "urgent") {
  1999. return browser.execute((currentPhase) => {
  2000. const element = document.querySelector<HTMLElement>(
  2001. `[data-context-reset-reminder="${currentPhase}"]`,
  2002. );
  2003. if (!element) return false;
  2004. const style = window.getComputedStyle(element);
  2005. return (
  2006. style.display !== "none" &&
  2007. style.visibility !== "hidden" &&
  2008. element.getClientRects().length > 0
  2009. );
  2010. }, phase);
  2011. }
  2012. async function waitForContextResetReminder(phase: "initial" | "urgent", expectedTexts: string[]) {
  2013. try {
  2014. await browser.waitUntil(
  2015. async () => {
  2016. if (!(await isContextResetReminderVisible(phase))) return false;
  2017. const text = (await browser.execute((currentPhase) => {
  2018. return (
  2019. document.querySelector<HTMLElement>(`[data-context-reset-reminder="${currentPhase}"]`)
  2020. ?.innerText ?? ""
  2021. );
  2022. }, phase)) as string;
  2023. return expectedTexts.some((expected) => text.includes(expected));
  2024. },
  2025. {
  2026. timeout: 15000,
  2027. timeoutMsg: `没有展示 ${phase} reset opportunity reminder`,
  2028. },
  2029. );
  2030. } catch (error) {
  2031. // Bug 调查:提醒缺失不能只留下一个 waitUntil 超时。机会接口、Context 触发器和
  2032. // 实际 DOM 一并进入失败证据,才能区分“没有数据”和“已有机会但提醒被收起”。
  2033. const reminderDiagnostics = await browser.execute(
  2034. (contextTriggerTestId) => ({
  2035. bodyText: document.body?.innerText?.slice(-2500) ?? "",
  2036. contextTriggerVisible: Array.from(
  2037. document.querySelectorAll<HTMLElement>(`[data-testid="${contextTriggerTestId}"]`),
  2038. ).some((element) => element.getClientRects().length > 0),
  2039. opportunityBadges: Array.from(
  2040. document.querySelectorAll<HTMLElement>('[data-reset-opportunity="true"]'),
  2041. ).map((element) => ({
  2042. text: element.innerText,
  2043. visible: element.getClientRects().length > 0,
  2044. })),
  2045. reminders: Array.from(
  2046. document.querySelectorAll<HTMLElement>("[data-context-reset-reminder]"),
  2047. ).map((element) => ({
  2048. phase: element.dataset.contextResetReminder ?? null,
  2049. text: element.innerText,
  2050. visible: element.getClientRects().length > 0,
  2051. })),
  2052. }),
  2053. TID_CHAT_CONTEXT_USAGE_TRIGGER,
  2054. );
  2055. const resetRequests = (await readMockRequests())
  2056. .filter((request) => request.path.includes("/coding-plan/reset/"))
  2057. .map((request) => ({ method: request.method, path: request.path }));
  2058. throw new Error(
  2059. `没有展示 ${phase} reset opportunity reminder\n诊断: ${JSON.stringify(
  2060. { reminderDiagnostics, resetRequests },
  2061. null,
  2062. 2,
  2063. )}`,
  2064. { cause: error },
  2065. );
  2066. }
  2067. }
  2068. async function readQuotaResetOverlayState() {
  2069. return browser.execute(() => {
  2070. const isVisible = (element: Element | null) => {
  2071. if (!(element instanceof HTMLElement)) return false;
  2072. const style = window.getComputedStyle(element);
  2073. return (
  2074. style.display !== "none" &&
  2075. style.visibility !== "hidden" &&
  2076. element.getClientRects().length > 0
  2077. );
  2078. };
  2079. return {
  2080. dialogVisible: isVisible(document.querySelector('[role="dialog"]')),
  2081. hoverCardVisible: isVisible(document.querySelector('[data-slot="hover-card-content"]')),
  2082. };
  2083. });
  2084. }
  2085. async function findVisibleButtonByAriaLabels(
  2086. labels: string[],
  2087. required = true,
  2088. rootSelector?: string,
  2089. ) {
  2090. const selector = rootSelector ? `${rootSelector} button` : "button";
  2091. for (const button of await $$(selector)) {
  2092. if (!(await button.isDisplayed())) continue;
  2093. const ariaLabel = await button.getAttribute("aria-label");
  2094. if (ariaLabel && labels.includes(ariaLabel)) return button;
  2095. }
  2096. if (required) throw new Error(`找不到按钮: ${labels.join("/")}`);
  2097. return undefined;
  2098. }
  2099. /** 单次 execute 往返读取弹框内 FIVE_HOUR 重置按钮与成功态;QR-E2E-03 的 confirm
  2100. * 窗口只有约 2.5 秒,逐按钮 isDisplayed/getAttribute 的多次 WebDriver 往返会超窗。 */
  2101. async function readFiveHourUseRequests() {
  2102. return (await readMockRequests()).filter(
  2103. (request) =>
  2104. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  2105. isRecord(request.body) &&
  2106. request.body.reset_type === "FIVE_HOUR",
  2107. );
  2108. }
  2109. async function clickDialogFiveHourReset(missingMessage: string) {
  2110. const button = await findVisibleButtonByAriaLabels(
  2111. ["重置 5 小时额度", "Reset 5-hour quota"],
  2112. false,
  2113. '[role="dialog"]',
  2114. );
  2115. if (!button) throw new Error(missingMessage);
  2116. await button.click();
  2117. }
  2118. async function readDialogResetState() {
  2119. return browser.execute(
  2120. (resetLabels: string[], successLabels: string[], weekResetLabels: string[]) => {
  2121. const dialog = document.querySelector('[role="dialog"]');
  2122. const buttons = dialog
  2123. ? Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"))
  2124. : [];
  2125. const findByLabels = (candidates: string[]) =>
  2126. buttons.find((button) => candidates.includes(button.getAttribute("aria-label") ?? "")) ??
  2127. null;
  2128. const resetButton = findByLabels(resetLabels);
  2129. return {
  2130. resetDisabled: resetButton ? resetButton.disabled : null,
  2131. // 重置按钮与类型名、次数药丸、倒计时同处一个行容器,用于断言该行展示内容。
  2132. resetRowText: resetButton?.parentElement?.innerText ?? null,
  2133. successVisible: findByLabels(successLabels) !== null,
  2134. weekResetVisible: findByLabels(weekResetLabels) !== null,
  2135. };
  2136. },
  2137. ["重置 5 小时额度", "Reset 5-hour quota"],
  2138. ["重置成功", "Reset successful"],
  2139. ["重置周额度", "Reset weekly quota"],
  2140. );
  2141. }
  2142. async function waitForDialogResetState(
  2143. predicate: (state: Awaited<ReturnType<typeof readDialogResetState>>) => boolean,
  2144. timeoutMsg: string,
  2145. ) {
  2146. let lastState: Awaited<ReturnType<typeof readDialogResetState>> | null = null;
  2147. try {
  2148. await browser.waitUntil(
  2149. async () => {
  2150. const state = await readDialogResetState();
  2151. lastState = state;
  2152. return predicate(state);
  2153. },
  2154. { interval: 100, timeout: 10000, timeoutMsg },
  2155. );
  2156. } catch (error) {
  2157. throw new Error(`${timeoutMsg}: ${JSON.stringify(lastState)}`, { cause: error });
  2158. }
  2159. }
  2160. async function waitForMockRequest(
  2161. predicate: (request: MockRequest) => boolean,
  2162. timeoutMsg: string,
  2163. ) {
  2164. await browser.waitUntil(async () => (await readMockRequests()).some(predicate), {
  2165. timeout: 10000,
  2166. timeoutMsg,
  2167. });
  2168. }
  2169. async function waitForLatestMockRequest(
  2170. predicate: (request: MockRequest) => boolean,
  2171. timeoutMsg: string,
  2172. ): Promise<MockRequest> {
  2173. let match: MockRequest | undefined;
  2174. await browser.waitUntil(
  2175. async () => {
  2176. match = (await readMockRequests()).findLast(predicate);
  2177. return Boolean(match);
  2178. },
  2179. { timeout: 10000, timeoutMsg },
  2180. );
  2181. if (!match) {
  2182. throw new Error(timeoutMsg);
  2183. }
  2184. return match;
  2185. }
  2186. async function clickVisibleButtonByText(labels: string[]): Promise<void> {
  2187. for (const button of await $$("button")) {
  2188. if ((await button.isDisplayed()) && labels.includes((await button.getText()).trim())) {
  2189. await button.click();
  2190. return;
  2191. }
  2192. }
  2193. throw new Error(`找不到可见按钮: ${labels.join("/")}`);
  2194. }
  2195. function daysBetweenMonitorTimes(startTime: string, endTime: string): number {
  2196. const start = Date.parse(startTime.replace(" ", "T") + "Z");
  2197. const end = Date.parse(endTime.replace(" ", "T") + "Z");
  2198. return Math.floor((end - start) / 86_400_000);
  2199. }
  2200. function requireQueryValue(request: MockRequest, key: string): string {
  2201. const value = request.query[key];
  2202. if (!value) {
  2203. throw new Error(`mock request 缺少 query: ${key}`);
  2204. }
  2205. return value;
  2206. }
  2207. function requestRangeDays(request: MockRequest): number | null {
  2208. const startTime = request.query.startTime;
  2209. const endTime = request.query.endTime;
  2210. return startTime && endTime ? daysBetweenMonitorTimes(startTime, endTime) : null;
  2211. }
  2212. async function readMockRequests(): Promise<MockRequest[]> {
  2213. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/requests`);
  2214. const payload = (await response.json()) as { requests?: MockRequest[] };
  2215. return payload.requests ?? [];
  2216. }
  2217. function getMockBaseUrl() {
  2218. const baseUrl = process.env.ZCODE_E2E_CODING_PLAN_MOCK_URL?.trim();
  2219. if (!baseUrl) {
  2220. throw new Error("ZCODE_E2E_CODING_PLAN_MOCK_URL 未配置");
  2221. }
  2222. return baseUrl;
  2223. }
  2224. async function writeSettings(patch: Record<string, unknown>) {
  2225. await mkdir(join(E2E_STORAGE_ROOT, "v2"), { recursive: true });
  2226. const current = await readSettings();
  2227. await writeFile(SETTINGS_FILE, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  2228. }
  2229. async function writeCredentials(patch: Record<string, unknown>) {
  2230. await mkdir(join(E2E_STORAGE_ROOT, "v2"), { recursive: true });
  2231. const current = await readJsonFile(CREDENTIALS_FILE);
  2232. await writeFile(CREDENTIALS_FILE, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  2233. }
  2234. async function readSettings(): Promise<{
  2235. providerFamilyConnectionSelections?: {
  2236. bigmodel?: ProviderFamilyConnectionSelection;
  2237. zai?: ProviderFamilyConnectionSelection;
  2238. };
  2239. [key: string]: unknown;
  2240. }> {
  2241. try {
  2242. return JSON.parse(await readFile(SETTINGS_FILE, "utf-8")) as Record<string, unknown>;
  2243. } catch {
  2244. return {};
  2245. }
  2246. }
  2247. async function readJsonFile(path: string): Promise<Record<string, unknown>> {
  2248. try {
  2249. return JSON.parse(await readFile(path, "utf-8")) as Record<string, unknown>;
  2250. } catch {
  2251. return {};
  2252. }
  2253. }
  2254. function isRecord(value: unknown): value is Record<string, unknown> {
  2255. return typeof value === "object" && value !== null && !Array.isArray(value);
  2256. }
  2257. async function assertBodyTextIncludes(values: string[]) {
  2258. try {
  2259. await browser.waitUntil(
  2260. async () => {
  2261. const bodyText = await getBodyText();
  2262. return values.every((value) => bodyText.includes(value));
  2263. },
  2264. {
  2265. timeout: 10000,
  2266. timeoutMsg: `页面没有出现全部文本: ${values.join(" / ")}`,
  2267. },
  2268. );
  2269. } catch (error) {
  2270. throw new Error(
  2271. `页面没有出现全部文本: ${values.join(" / ")}\n当前页面文本:\n${(await getBodyText()).slice(0, 2000)}`,
  2272. { cause: error },
  2273. );
  2274. }
  2275. }
  2276. async function assertBodyTextIncludesAny(values: string[]) {
  2277. try {
  2278. await browser.waitUntil(
  2279. async () => {
  2280. const bodyText = await getBodyText();
  2281. return values.some((value) => bodyText.includes(value));
  2282. },
  2283. {
  2284. timeout: 10000,
  2285. timeoutMsg: `页面没有出现任一文本: ${values.join(" / ")}`,
  2286. },
  2287. );
  2288. } catch (error) {
  2289. throw new Error(
  2290. `页面没有出现任一文本: ${values.join(" / ")}\n当前页面文本:\n${(await getBodyText()).slice(0, 2000)}`,
  2291. { cause: error },
  2292. );
  2293. }
  2294. }
  2295. async function assertBodyTextExcludes(values: string[]) {
  2296. const bodyText = await getBodyText();
  2297. for (const value of values) {
  2298. expect(bodyText).not.toContain(value);
  2299. }
  2300. }
  2301. function getBodyText() {
  2302. return browser.execute(() => document.body?.innerText ?? "");
  2303. }
  2304. interface MockRequest {
  2305. body?: unknown;
  2306. headers: Record<string, string | string[] | undefined>;
  2307. method: string;
  2308. path: string;
  2309. query: Record<string, string>;
  2310. }
  2311. type ReminderNavigationWindow = Window & {
  2312. __zcodeTabStoreE2E: {
  2313. getState(): {
  2314. activeTabId: string | null;
  2315. openSettingsTab(): void;
  2316. activateTab(id: string): void;
  2317. };
  2318. };
  2319. };
  2320. async function assertContextReminderHiddenInSettings(phase: "initial" | "urgent") {
  2321. // 通过真实导航 store 切层,避免打开入口的 pointerdown 把提醒预先标已读,掩盖 Portal 泄漏。
  2322. const workspaceTabId = await browser.execute(() => {
  2323. const store = (window as unknown as ReminderNavigationWindow).__zcodeTabStoreE2E;
  2324. const id = store.getState().activeTabId;
  2325. store.getState().openSettingsTab();
  2326. return id;
  2327. });
  2328. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 10000 });
  2329. await browser.waitUntil(async () => !(await isContextResetReminderVisible(phase)), {
  2330. timeout: 5000,
  2331. timeoutMsg: "Composer 提醒穿透到设置页",
  2332. });
  2333. // 设置页点击不能消耗后台工作区的提醒状态。
  2334. await browser.execute(() =>
  2335. document
  2336. .querySelector('[data-testid="settings-page"]')!
  2337. .dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })),
  2338. );
  2339. await browser.execute(
  2340. (id) =>
  2341. (window as unknown as ReminderNavigationWindow).__zcodeTabStoreE2E
  2342. .getState()
  2343. .activateTab(id!),
  2344. workspaceTabId,
  2345. );
  2346. await browser.waitUntil(async () => await isContextResetReminderVisible(phase), {
  2347. timeout: 5000,
  2348. timeoutMsg: "设置页点击误将 Composer 提醒标记为已读",
  2349. });
  2350. }
  2351. // 读取真实展示组件的输入:保留 DOM 和 Host owner,只观察同一挂载树中的用量投影。
  2352. async function readComposerTeamUsageSource(): Promise<string | null> {
  2353. return browser.execute(() => {
  2354. const element = document.querySelector('[data-testid="v4-model-config"]');
  2355. if (!element) return null;
  2356. let fiber = (element as any)[
  2357. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  2358. ];
  2359. while (fiber.return) fiber = fiber.return;
  2360. // DOM 上的 Fiber 可指向 alternate;必须从 React 当前 root 读取已提交展示。
  2361. const pending = [fiber.stateNode.current];
  2362. while (pending.length) {
  2363. const node = pending.pop();
  2364. if (Object.hasOwn(node.memoizedProps ?? {}, "codingPlanUsageRemaining"))
  2365. return node.memoizedProps.codingPlanUsageRemaining?.selectedProviderId ?? null;
  2366. if (node.sibling) pending.push(node.sibling);
  2367. if (node.child) pending.push(node.child);
  2368. }
  2369. return null;
  2370. });
  2371. }
  2372. // 注入请求交错,不伪造设置落盘或替换生产菜单。所有修改在 finally 恢复。
  2373. async function installConnectionBoundaryProbe(
  2374. mode: "logout" | "cas" | "mismatch" | "refresh-failure",
  2375. ) {
  2376. await browser.execute(async (mode) => {
  2377. const element = document.querySelector('[data-testid="v4-model-config"]')!;
  2378. let fiber = (element as any)[
  2379. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  2380. ];
  2381. let services: any;
  2382. let store: any;
  2383. const accessors = new Set<any>();
  2384. while (fiber) {
  2385. const value = fiber.memoizedProps?.value;
  2386. const candidate = value?.settingService ? value : fiber.memoizedProps?.services;
  2387. if (candidate?.settingService) accessors.add(candidate);
  2388. services ??= candidate;
  2389. if (value?.getState && value.getState().setUser) store ??= value;
  2390. fiber = fiber.return;
  2391. }
  2392. if (!services?.settingService) throw new Error("Workspace services not found");
  2393. if (mode === "logout") {
  2394. if (!store) throw new Error("Auth store not found");
  2395. // 原因:刷新后断言会漏掉旧 Provider 与新 user 并存的窗口;先阻塞 refresh 再登出。
  2396. const restorers: (() => void)[] = [];
  2397. let release!: () => void;
  2398. const blocked = new Promise<void>((resolve) => {
  2399. release = resolve;
  2400. });
  2401. for (const accessor of accessors) {
  2402. const original = accessor.providerSettingsService;
  2403. accessor.providerSettingsService = new Proxy(original, {
  2404. get(target, prop) {
  2405. if (prop !== "refresh") return Reflect.get(target, prop);
  2406. return async (...args: any[]) => {
  2407. await blocked;
  2408. return target.refresh(...args);
  2409. };
  2410. },
  2411. });
  2412. restorers.push(() => {
  2413. accessor.providerSettingsService = original;
  2414. });
  2415. }
  2416. const suppressedRestores: unknown[] = [];
  2417. // 测试屏障同时暂停旧凭据的恢复回执,保证断言窗口确实保持 user=null;不改生产鉴权流程。
  2418. const pauseAuthRestore = store.subscribe((state: any) => {
  2419. if (state.user) {
  2420. suppressedRestores.push({ userId: state.user.id, authSessionSeq: state.authSessionSeq });
  2421. state.setUser(null);
  2422. }
  2423. });
  2424. (window as any).__logoutBoundaryRelease = async () => {
  2425. pauseAuthRestore();
  2426. restorers.forEach((restore) => restore());
  2427. release();
  2428. await services.oauthService.logoutAll();
  2429. store.getState().setUser(null);
  2430. await services.providerSettingsService.refresh("e2e-signed-out");
  2431. };
  2432. (window as any).__logoutBoundaryAuth = () => ({
  2433. userId: store.getState().user?.id ?? null,
  2434. authSessionSeq: store.getState().authSessionSeq,
  2435. });
  2436. store.getState().setUser(null);
  2437. return;
  2438. }
  2439. const trace: unknown[] = [];
  2440. let restore = () => {};
  2441. const restorers: (() => void)[] = [];
  2442. let injected = false;
  2443. let armed = false;
  2444. let recovered = false;
  2445. let obsoleteStarted = false;
  2446. let rejectObsolete!: (cause: Error) => void;
  2447. const presentationListeners: ((candidate: any) => void)[] = [];
  2448. let releasePresentation!: () => void;
  2449. const synchronized = new Promise<void>((resolve) => {
  2450. releasePresentation = resolve;
  2451. });
  2452. for (const accessor of accessors) {
  2453. const key = mode === "cas" ? "settingService" : "modelSelectionService";
  2454. const service = accessor[key];
  2455. if (mode === "cas") {
  2456. accessor[key] = new Proxy(service, {
  2457. get(target, prop) {
  2458. if (prop !== "update") return Reflect.get(target, prop);
  2459. return async (patch: any, expected: any) => {
  2460. if (armed && !injected && patch.providerFamilyConnectionSelections) {
  2461. injected = true;
  2462. const before = await service.get();
  2463. await service.update(
  2464. {
  2465. providerFamilyConnectionSelections: {
  2466. ...before.providerFamilyConnectionSelections,
  2467. zai: { kind: "individual-coding-plan" },
  2468. },
  2469. },
  2470. {
  2471. providerFamilyDomain: before.providerFamilyDomain,
  2472. providerFamilyConnectionSelections: before.providerFamilyConnectionSelections,
  2473. providerFamilyDomainUpdatedAt: before.providerFamilyDomainUpdatedAt ?? 0,
  2474. },
  2475. );
  2476. trace.push({ phase: "concurrent-write", expected });
  2477. }
  2478. return service.update(patch, expected);
  2479. };
  2480. },
  2481. });
  2482. } else {
  2483. accessor[key] = new Proxy(service, {
  2484. get(target, prop) {
  2485. if (mode === "refresh-failure" && prop === "onDidChange")
  2486. return (listener: any) => {
  2487. presentationListeners.push(listener);
  2488. let delivered = false;
  2489. return service.onDidChange((candidate: any) => {
  2490. // 每个订阅收到一次目标事件;不能由另一订阅抢先吞掉 Composer 的回执。
  2491. if (armed && delivered) return;
  2492. if (armed) {
  2493. delivered = true;
  2494. trace.push({ phase: "target-event", revision: candidate.revision });
  2495. }
  2496. listener(candidate);
  2497. });
  2498. };
  2499. if (prop !== "getView") return Reflect.get(target, prop);
  2500. return async (input: any) => {
  2501. if (mode === "refresh-failure" && armed && input) {
  2502. trace.push({ phase: "presentation-failed" });
  2503. throw new Error("E2E presentation read failed");
  2504. }
  2505. if (mode === "refresh-failure" && recovered && input && !obsoleteStarted) {
  2506. obsoleteStarted = true;
  2507. trace.push({ phase: "obsolete-started" });
  2508. return new Promise((_resolve, reject) => {
  2509. rejectObsolete = reject;
  2510. });
  2511. }
  2512. const view = await service.getView(input);
  2513. if (mode === "refresh-failure") {
  2514. if (recovered && input)
  2515. trace.push({ phase: "presentation-recovered", revision: view.revision });
  2516. if (armed) trace.push({ phase: "target-synchronized", revision: view.revision });
  2517. return view;
  2518. }
  2519. if (!armed) return view;
  2520. if (!input) {
  2521. trace.push({ phase: "target-synchronized", revision: view.revision });
  2522. releasePresentation();
  2523. return view;
  2524. }
  2525. // 挂起展示读取直到连接同步完成,再读取同一 owner 的最新 revision;
  2526. // 旧 ready 不属于本次回执,不能拿它伪造 ready+mismatch。
  2527. await synchronized;
  2528. const latest = await service.getView(input);
  2529. trace.push({
  2530. phase: "ready-mismatch",
  2531. revision: latest.revision,
  2532. original: latest.effectiveSelection,
  2533. });
  2534. return {
  2535. ...latest,
  2536. // 固定的 Flash 恰好可能是目标首选模型,不能保证冲突;回放另一有效 Provider 的选择。
  2537. effectiveSelection: {
  2538. providerId: "e2e-upstream",
  2539. modelId: "deepseek-v4-flash",
  2540. options: { reasoningLevel: "disabled" },
  2541. },
  2542. };
  2543. };
  2544. },
  2545. });
  2546. }
  2547. restorers.push(() => {
  2548. accessor[key] = service;
  2549. });
  2550. }
  2551. // RPC 方法 getter 不读取赋值;替换 accessor 的端口并重渲染,保持生产 RPC 和设置锁。
  2552. if (!store) throw new Error("Auth store not found");
  2553. store.getState().setUser({ ...store.getState().user });
  2554. restore = () => {
  2555. releasePresentation();
  2556. restorers.forEach((restore) => restore());
  2557. store.getState().setUser({ ...store.getState().user });
  2558. };
  2559. Object.assign(window, {
  2560. __connectionBoundaryProbe: {
  2561. trace,
  2562. restore,
  2563. recover: () => {
  2564. armed = false;
  2565. recovered = true;
  2566. trace.push({ phase: "fault-recovered" });
  2567. },
  2568. supersede: async () => {
  2569. const candidate = await Array.from(accessors)[0].modelSelectionService.getView();
  2570. presentationListeners.forEach((listener) => listener(candidate));
  2571. },
  2572. rejectObsolete: () => {
  2573. trace.push({ phase: "obsolete-failed" });
  2574. rejectObsolete(new Error("E2E obsolete presentation failed"));
  2575. },
  2576. arm: () => {
  2577. armed = true;
  2578. },
  2579. },
  2580. });
  2581. }, mode);
  2582. }