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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717
  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. // 侧栏提示已移到延迟 Tooltip,不再保留原生 title;限定套餐容器读取可见文字。
  1003. const badge = $('[data-testid="profile-menu-plan"]');
  1004. await badge.waitForDisplayed({ timeout: 30000 });
  1005. await expect(badge).toHaveText(teamLabel);
  1006. await browser.keys("Escape");
  1007. });
  1008. }
  1009. it("CTP-03: 用户头像菜单应进入 Team Plan 使用统计并请求团队额度", async function () {
  1010. this.timeout(120000);
  1011. await prepareScenario("teamOnly", TEAM_PLAN_KEY);
  1012. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1013. await openSidebarUsageStats();
  1014. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  1015. await clickUsageCodingPlanTab(TEAM_PLAN_KEY);
  1016. await assertBodyTextIncludes(["Team Org", "90%"]);
  1017. await waitForMockRequest(
  1018. (request) =>
  1019. request.path.endsWith("/api/monitor/usage/quota/limit") &&
  1020. request.query.type === "2" &&
  1021. request.headers["bigmodel-organization"] === "org-team-a" &&
  1022. request.headers["bigmodel-project"] === "proj-team-a",
  1023. "头像菜单未按 Team Plan 请求 quota/limit?type=2",
  1024. );
  1025. });
  1026. it("CTP-04: 使用统计编程套餐应显示 Team Plan 额度、模型用量和工具用量", async function () {
  1027. this.timeout(120000);
  1028. await prepareScenario("teamOnly", TEAM_PLAN_KEY);
  1029. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1030. await assertBodyTextIncludes(["Team Org", "90%", "glm-credit-e2e"]);
  1031. await assertBodyTextIncludesAny(["Models", "模型"]);
  1032. await clickVisibleButtonByText(["Tools", "工具"]);
  1033. await assertBodyTextIncludes(["E2E Search MCP"]);
  1034. await waitForMockRequest(
  1035. (request) =>
  1036. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1037. request.query.usageType === "MODEL" &&
  1038. request.headers["bigmodel-organization"] === "org-team-a" &&
  1039. request.headers["bigmodel-project"] === "proj-team-a",
  1040. "使用统计未按 Team Plan 请求 MODEL credit detail",
  1041. );
  1042. await waitForMockRequest(
  1043. (request) =>
  1044. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1045. request.query.usageType === "MCP" &&
  1046. request.headers["bigmodel-organization"] === "org-team-a" &&
  1047. request.headers["bigmodel-project"] === "proj-team-a",
  1048. "使用统计未按 Team Plan 请求 MCP credit detail",
  1049. );
  1050. });
  1051. it("CTP-04B: 个人套餐应展示 credit activity、明细与性能数据", async function () {
  1052. this.timeout(120000);
  1053. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  1054. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1055. await assertBodyTextIncludes(["glm-credit-e2e"]);
  1056. await assertBodyTextIncludesAny(["Credits total", "积分总数"]);
  1057. await clickVisibleButtonByText(["Tools", "工具"]);
  1058. await assertBodyTextIncludes(["E2E Search MCP"]);
  1059. await waitForMockRequest(
  1060. (request) =>
  1061. request.path.endsWith("/api/monitor/credit-usage/activity") &&
  1062. request.query.type === "1" &&
  1063. !request.headers["bigmodel-organization"] &&
  1064. !request.headers["bigmodel-project"],
  1065. "个人套餐没有请求隔离的 credit activity",
  1066. );
  1067. await waitForMockRequest(
  1068. (request) =>
  1069. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1070. request.query.usageType === "MODEL",
  1071. "个人套餐没有请求 MODEL credit detail",
  1072. );
  1073. await waitForMockRequest(
  1074. (request) => request.path.endsWith("/api/monitor/usage/model-performance-day"),
  1075. "个人套餐没有请求 model performance",
  1076. );
  1077. });
  1078. for (const locale of ["zh-CN", "en-US"] as const) {
  1079. it(`CTP-05: 切换连接后可分别查看个人与团队用量来源(${locale})`, async function () {
  1080. this.timeout(180000);
  1081. await prepareScenario("both", TEAM_PLAN_KEY, "none", "none", locale);
  1082. await openModelProviderSettings();
  1083. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  1084. timeout: 30000,
  1085. timeoutMsg: "BigModel 供应商导航项没有出现",
  1086. });
  1087. await selectConnectionModeOptionByTestId(
  1088. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, PERSONAL_PLAN_CONNECTION_KEY),
  1089. "个人 Coding Plan",
  1090. );
  1091. await waitForBigModelConnectionSelection("individual-coding-plan");
  1092. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1093. await assertBodyTextIncludes(["70%", "glm-credit-e2e"]);
  1094. // 使用统计的个人页签是 Individual Plan,不是设置页左侧的 Coding Plan。
  1095. const personalTab = $(sel(testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${PERSONAL_PLAN_KEY}`)));
  1096. await expect(personalTab).toHaveText(locale === "zh-CN" ? "个人套餐" : "Individual Plan");
  1097. await expect(personalTab).toHaveAttribute("aria-pressed", "true");
  1098. // 使用统计按账号展示全部来源;团队 tab 的名称不代表个人面板泄漏团队额度。
  1099. const teamTab = $(sel(testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${TEAM_PLAN_KEY}`)));
  1100. // 个人额度先返回,团队来源随后异步加入;等待目标来源渲染后再校验未选中状态。
  1101. await teamTab.waitForDisplayed({ timeout: 30_000 });
  1102. await expect(teamTab).toHaveText("Team Org");
  1103. await expect(teamTab).toHaveAttribute("aria-pressed", "false");
  1104. await openModelProviderSettings();
  1105. await clickVisibleTestIdByDom(testId(TID_MODEL_PROVIDER_NAV_ITEM, BIGMODEL_ACCOUNT_NAV_KEY), {
  1106. timeout: 30000,
  1107. timeoutMsg: "BigModel 供应商导航项没有出现",
  1108. });
  1109. await selectConnectionModeOptionByTestId(
  1110. testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, TEAM_PLAN_KEY),
  1111. "Team Org",
  1112. );
  1113. await waitForBigModelConnectionSelection("team-coding-plan");
  1114. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1115. await assertBodyTextIncludes(["Team Org", "90%", "glm-credit-e2e"]);
  1116. });
  1117. }
  1118. it("CTP-06: 启动恢复 OAuth 时应保留已选择的 Team Plan", async function () {
  1119. this.timeout(120000);
  1120. await prepareScenario("both", TEAM_PLAN_KEY);
  1121. await waitForMockRequest(
  1122. (request) => request.path.endsWith("/subscription/enterprise/v2/pricing"),
  1123. "启动恢复 OAuth 时未请求企业套餐 pricing",
  1124. );
  1125. await browser.waitUntil(
  1126. async () => {
  1127. const selection = (await readSettings()).providerFamilyConnectionSelections?.bigmodel;
  1128. return (
  1129. selection?.kind === "team-coding-plan" &&
  1130. selection.productId === "product-team-a" &&
  1131. selection.organizationId === "org-team-a" &&
  1132. selection.projectId === "proj-team-a"
  1133. );
  1134. },
  1135. {
  1136. timeout: 15000,
  1137. timeoutMsg: "启动恢复 OAuth 后结构化 Team Plan selection 被覆盖",
  1138. },
  1139. );
  1140. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1141. await waitForMockRequest(
  1142. (request) =>
  1143. request.path.endsWith("/api/monitor/usage/quota/limit") &&
  1144. request.query.type === "2" &&
  1145. request.headers["bigmodel-organization"] === "org-team-a" &&
  1146. request.headers["bigmodel-project"] === "proj-team-a",
  1147. "启动恢复 OAuth 后使用统计未继续按 Team Plan 请求 quota/limit?type=2",
  1148. );
  1149. });
  1150. it("CTP-07: 切换 7d/30d 应重新请求不同日期窗口且保持当前来源", async function () {
  1151. this.timeout(120000);
  1152. await prepareScenario("both", TEAM_PLAN_KEY);
  1153. await openUsageCodingPlanTab(TEAM_PLAN_KEY);
  1154. await clickVisibleButtonByText(["30 days", "近 30 日"]);
  1155. const thirtyDayRequest = await waitForLatestMockRequest(
  1156. (request) =>
  1157. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1158. request.query.usageType === "MODEL" &&
  1159. request.query.type === "3" &&
  1160. requestRangeDays(request) === 29,
  1161. "切换 30d 后没有请求新的日期窗口",
  1162. );
  1163. expect(thirtyDayRequest.headers["bigmodel-organization"]).toBe("org-team-a");
  1164. expect(thirtyDayRequest.headers["bigmodel-project"]).toBe("proj-team-a");
  1165. expect(
  1166. daysBetweenMonitorTimes(
  1167. requireQueryValue(thirtyDayRequest, "startTime"),
  1168. requireQueryValue(thirtyDayRequest, "endTime"),
  1169. ),
  1170. ).toBe(29);
  1171. await clickVisibleButtonByText(["7 days", "近 7 日"]);
  1172. await waitForMockRequest(
  1173. (request) =>
  1174. request.path.endsWith("/api/monitor/credit-usage/usage-detail") &&
  1175. request.query.usageType === "MODEL" &&
  1176. request.query.type === "3" &&
  1177. requestRangeDays(request) === 6,
  1178. "切回 7d 后没有恢复对应日期窗口",
  1179. );
  1180. });
  1181. it("CTP-08: 窄窗口下 Usage tabs、range 与热力图仍可操作", async function () {
  1182. this.timeout(120000);
  1183. await setRendererViewport(430, 760);
  1184. try {
  1185. // 本 Case 只验证窄窗口交互,不额外绑定“个人 + Team 同时存在时启动恢复
  1186. // 自动选择哪个套餐”的产品规则;使用单一个人权益保持夹具职责清晰。
  1187. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  1188. await setSettingsTheme("zai-dark");
  1189. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1190. await clickVisibleButtonByText(["30 days", "近 30 日"]);
  1191. await assertBodyTextIncludes(["glm-credit-e2e"]);
  1192. await assertBodyTextIncludesAny(["Token activity", "Token 活动"]);
  1193. } finally {
  1194. await setSettingsTheme("zai-light");
  1195. await clearRendererViewport();
  1196. }
  1197. });
  1198. it("CTP-09: activity 可选接口失败不拖垮 quota,刷新后恢复", async function () {
  1199. this.timeout(120000);
  1200. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "optionalActivity");
  1201. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1202. await assertBodyTextIncludes(["70%", "glm-credit-e2e"]);
  1203. await assertBodyTextExcludes(["350.7K", "35.1万", "35.1 万"]);
  1204. await setMockScenario("personalOnly", "none");
  1205. await clickVisibleButtonByText(["Refresh", "刷新"]);
  1206. await assertBodyTextIncludesAny(["350.7K", "35.1万", "35.1 万"]);
  1207. await waitForMockRequest(
  1208. (request) => request.path.endsWith("/api/monitor/credit-usage/activity"),
  1209. "activity 恢复后刷新没有重新请求",
  1210. );
  1211. });
  1212. it("CTP-10: Context hover 应按 access freshness 展示同一额度快照", async function () {
  1213. this.timeout(120000);
  1214. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY);
  1215. await selectBigModelCodingPlanRuntime("individual-coding-plan");
  1216. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  1217. await trigger.waitForDisplayed({
  1218. timeout: 15000,
  1219. timeoutMsg: "Context usage trigger 没有出现",
  1220. });
  1221. await trigger.moveTo();
  1222. await assertBodyTextIncludes(["70%"]);
  1223. await assertBodyTextIncludesAny(["5 hours", "5 小时"]);
  1224. await waitForMockRequest(
  1225. (request) =>
  1226. request.path.endsWith("/api/monitor/usage/quota/limit") && request.query.type !== "2",
  1227. "Context access 没有读取个人套餐 quota",
  1228. );
  1229. });
  1230. for (const [scenario, planKey, width] of [
  1231. ["personalOnly", PERSONAL_PLAN_KEY, 1200],
  1232. ["teamOnly", TEAM_PLAN_KEY, 1200],
  1233. ["personalOnly", PERSONAL_PLAN_KEY, 390],
  1234. ["teamOnly", TEAM_PLAN_KEY, 390],
  1235. ] as const) {
  1236. it(`CTP-11: ${scenario} ${width}px quota 失败保留套餐入口,重新进入来源后恢复`, async function () {
  1237. this.timeout(120000);
  1238. await prepareScenario(scenario, planKey, "quotaBusinessFailure");
  1239. await openUsageSection();
  1240. await setRendererViewport(width, 900);
  1241. // 订阅查询保持成功,quota 业务失败不能撤销权益,确认 tab 不消失;
  1242. // 详情加载再切传输失败,覆盖 fatal 文案与后续恢复。
  1243. await setMockScenario(scenario, "quotaFailure");
  1244. await clickUsageCodingPlanTab(planKey);
  1245. await assertBodyTextIncludesAny([
  1246. "Unable to load usage stats",
  1247. "无法读取用量统计。请稍后重试,或检查网络和供应商配置。",
  1248. ]);
  1249. await assertBodyTextExcludes(["350.7K", "35.1万", "35.1 万", "glm-credit-e2e"]);
  1250. await setMockScenario(scenario, "none");
  1251. await clickVisibleTestIdByDom(testId(TID_SETTINGS_USAGE_TAB, "app"), {
  1252. timeout: 10000,
  1253. timeoutMsg: "致命失败恢复时无法切换到 App Usage",
  1254. });
  1255. await clickUsageCodingPlanTab(planKey);
  1256. await assertBodyTextIncludes([scenario === "teamOnly" ? "90%" : "70%", "glm-credit-e2e"]);
  1257. await assertBodyTextIncludesAny(["350.7K", "35.1万", "35.1 万"]);
  1258. });
  1259. }
  1260. it("QR-E2E-01: 空状态应调用 opportunity 并以强制 status 结果展示机会", async function () {
  1261. this.timeout(120000);
  1262. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "emptyThenGrant");
  1263. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1264. await waitForMockRequest(
  1265. (request) => request.path.endsWith("/api/v1/coding-plan/reset/opportunity"),
  1266. "空 reset 状态没有触发 opportunity",
  1267. );
  1268. await waitForResetOpportunityCount(1);
  1269. const resetPaths = (await readMockRequests())
  1270. .map((request) => request.path)
  1271. .filter((path) => path.includes("/api/v1/coding-plan/reset/"));
  1272. const opportunityIndex = resetPaths.findIndex((path) => path.endsWith("/opportunity"));
  1273. expect(opportunityIndex).toBeGreaterThan(0);
  1274. expect(resetPaths.slice(opportunityIndex + 1).some((path) => path.endsWith("/status"))).toBe(
  1275. true,
  1276. );
  1277. // QR-E2E-05:单机会徽标同样可点击并打开重置弹框(单机会不展示次数药丸,仅交互升级为按钮)。
  1278. await clickResetOpportunityBadge();
  1279. await assertBodyTextIncludesAny(["可重置额度", "Resettable quota"]);
  1280. await assertBodyTextIncludesAny(["5 小时额度重置", "5-hour quota reset"]);
  1281. });
  1282. it("QR-E2E-02: 已有多类型机会时仍调用 opportunity,Dialog 只展示 status 权威数量", async function () {
  1283. this.timeout(120000);
  1284. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  1285. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1286. await waitForMockRequest(
  1287. (request) => request.path.endsWith("/api/v1/coding-plan/reset/opportunity"),
  1288. "已有 reset 机会时没有继续触发 scope opportunity",
  1289. );
  1290. await waitForResetOpportunityCount(3);
  1291. await clickResetOpportunityBadge();
  1292. await assertBodyTextIncludesAny(["可重置额度", "Resettable quota"]);
  1293. await assertBodyTextIncludesAny(["5 小时额度重置", "5-hour quota reset"]);
  1294. await assertBodyTextIncludesAny(["周额度重置", "Weekly quota reset"]);
  1295. // 次数不再汇总到标题;FIVE_HOUR 持有 2 张机会,改由该行的次数药丸展示。
  1296. await assertBodyTextIncludesAny(["2 次", "×2"]);
  1297. });
  1298. it("QR-E2E-09: Composer 应常驻展示首次机会提醒并在 hover 后收起", async function () {
  1299. this.timeout(120000);
  1300. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  1301. await reloadRendererWithBigModelCodingPlanSelection();
  1302. await waitForContextResetReminder("initial", ["3 次重置额度", "3 reset available"]);
  1303. await assertContextReminderHiddenInSettings("initial");
  1304. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  1305. await trigger.moveTo();
  1306. await browser.waitUntil(async () => !(await isContextResetReminderVisible("initial")), {
  1307. timeout: 10000,
  1308. timeoutMsg: "打开 Context 后首次 reset opportunity 提醒仍未收起",
  1309. });
  1310. });
  1311. it("QR-E2E-10: 最早机会进入最后三分钟时应常驻展示临期提醒", async function () {
  1312. this.timeout(120000);
  1313. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "urgentOpportunity");
  1314. await reloadRendererWithBigModelCodingPlanSelection();
  1315. await waitForContextResetReminder("urgent", ["重置额度过期", "Reset expires in"]);
  1316. await assertContextReminderHiddenInSettings("urgent");
  1317. const alarmAnimation = await browser.execute(() => {
  1318. const icon = document.querySelector<HTMLElement>(
  1319. '[data-context-reset-reminder="urgent"] .animate-zcode-alarm-ring',
  1320. );
  1321. return icon ? window.getComputedStyle(icon).animationName : null;
  1322. });
  1323. expect(alarmAnimation).toBe("zcode-alarm-ring");
  1324. });
  1325. it("QR-E2E-04: Composer Dialog 打开期间应保持 HoverCard 生命周期", async function () {
  1326. this.timeout(120000);
  1327. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "existingMultiple");
  1328. await selectBigModelCodingPlanRuntime("individual-coding-plan");
  1329. const trigger = await $(sel(TID_CHAT_CONTEXT_USAGE_TRIGGER));
  1330. await trigger.waitForDisplayed({
  1331. timeout: 15000,
  1332. timeoutMsg: "Context usage trigger 没有出现",
  1333. });
  1334. await trigger.moveTo();
  1335. await waitForResetOpportunityCount(3, '[data-slot="hover-card-content"]');
  1336. await clickResetOpportunityBadge('[data-slot="hover-card-content"]');
  1337. await browser.waitUntil(
  1338. async () => {
  1339. const state = await readQuotaResetOverlayState();
  1340. return state.dialogVisible && state.hoverCardVisible;
  1341. },
  1342. {
  1343. timeout: 10000,
  1344. timeoutMsg: "重置 Dialog 打开后 Composer HoverCard 被提前卸载",
  1345. },
  1346. );
  1347. await browser.keys("Escape");
  1348. await browser.waitUntil(
  1349. async () => {
  1350. const state = await readQuotaResetOverlayState();
  1351. return !state.dialogVisible && !state.hoverCardVisible;
  1352. },
  1353. {
  1354. timeout: 10000,
  1355. timeoutMsg: "关闭重置 Dialog 后 Composer HoverCard 没有一起收起",
  1356. },
  1357. );
  1358. });
  1359. it("QR-E2E-03: FIVE_HOUR use 必须等待 status used_at 后才完成", async function () {
  1360. this.timeout(120000);
  1361. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "fiveHourUse");
  1362. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1363. await waitForResetOpportunityCount(2);
  1364. await clickResetOpportunityBadge();
  1365. const resetButton = await findVisibleButtonByAriaLabels(
  1366. ["重置 5 小时额度", "Reset 5-hour quota"],
  1367. true,
  1368. '[role="dialog"]',
  1369. );
  1370. if (!resetButton) throw new Error("没有找到 FIVE_HOUR reset 按钮");
  1371. await resetButton.click();
  1372. await waitForMockRequest(
  1373. (request) =>
  1374. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  1375. isRecord(request.body) &&
  1376. request.body.reset_type === "FIVE_HOUR",
  1377. "五小时重置没有发送 reset_type=FIVE_HOUR",
  1378. );
  1379. // 双 JWT 契约:Authorization 传 Bearer zcode JWT,X-Bigmodel-Authorization 直传 MaaS JWT。
  1380. const useRequest = (await readMockRequests()).find((request) =>
  1381. request.path.endsWith("/api/v1/coding-plan/reset/use"),
  1382. );
  1383. expect(useRequest?.headers.authorization).toBe("Bearer e2e-zcode-jwt");
  1384. expect(useRequest?.headers["x-bigmodel-authorization"]).toBe("e2e-bigmodel-oauth-token");
  1385. // 时序约束:客户端 use 后的 status 确认重试窗口只有约 2.5 秒,confirm 前的每次检查
  1386. // 必须是单次 execute 往返,不能逐按钮发 WebDriver 命令,否则慢机器上会先触发客户端
  1387. // 失败分支,confirm 之后成功态永远不会出现。
  1388. const processingState = await readDialogResetState();
  1389. if (processingState.resetDisabled !== true || processingState.successVisible) {
  1390. throw new Error(
  1391. `status used_at 未确认前没有保持 processing: ${JSON.stringify(processingState)}`,
  1392. );
  1393. }
  1394. await confirmResetUse();
  1395. await browser.waitUntil(async () => (await readDialogResetState()).successVisible, {
  1396. interval: 100,
  1397. timeout: 10000,
  1398. timeoutMsg: "status used_at 更新后没有显示成功状态",
  1399. });
  1400. await waitForMockRequest(
  1401. (request) => request.path.endsWith("/api/v1/coding-plan/reset/history/read"),
  1402. "确认 reset used_at 后没有上报 history/read",
  1403. );
  1404. });
  1405. it("QR-E2E-14: 同类型多张机会核销一张后,弹框不重开即可展示并核销余下机会", async function () {
  1406. this.timeout(120000);
  1407. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "multiFiveHourUse");
  1408. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1409. await waitForResetOpportunityCount(3);
  1410. await clickResetOpportunityBadge();
  1411. await assertBodyTextIncludesAny(["2 次", "×2"]);
  1412. await clickDialogFiveHourReset("没有找到 FIVE_HOUR reset 按钮");
  1413. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 1, {
  1414. timeout: 10000,
  1415. timeoutMsg: "第一次五小时重置没有发送 /use",
  1416. });
  1417. // 回归点:成功反馈结束后该行留在弹框内,直接展示余下 1 张的真实倒计时并恢复可点击;
  1418. // 旧实现在这里显示「0 分 0 秒后过期」,且再次点击被静默忽略,只能关闭重开弹框。
  1419. await waitForDialogResetState(
  1420. (state) =>
  1421. state.resetDisabled === false &&
  1422. !state.successVisible &&
  1423. state.weekResetVisible &&
  1424. state.resetRowText !== null &&
  1425. !["2 次", "×2", "0 分 0 秒", "0m 0s"].some((text) => state.resetRowText?.includes(text)),
  1426. "核销一张后余下机会没有在弹框内直接恢复为可核销",
  1427. );
  1428. await clickDialogFiveHourReset("核销一张后没有找到余下机会的 FIVE_HOUR reset 按钮");
  1429. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 2, {
  1430. timeout: 10000,
  1431. timeoutMsg: "余下机会的再次点击没有真实发送 /use",
  1432. });
  1433. const idempotencyKeys = (await readFiveHourUseRequests()).map((request) =>
  1434. isRecord(request.body) ? request.body.idempotency_key : undefined,
  1435. );
  1436. expect(new Set(idempotencyKeys).size).toBe(2);
  1437. // 机会耗尽后五小时行收起,周额度行不受影响、也不会被误核销。
  1438. await waitForDialogResetState(
  1439. (state) => state.resetDisabled === null && !state.successVisible && state.weekResetVisible,
  1440. "五小时机会耗尽后该行没有收起",
  1441. );
  1442. expect(
  1443. (await readMockRequests()).some(
  1444. (request) =>
  1445. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  1446. isRecord(request.body) &&
  1447. request.body.reset_type === "WEEK",
  1448. ),
  1449. ).toBe(false);
  1450. });
  1451. it("QR-E2E-15: 完成态再次核销时 status 仍是上一张 used_at,读到新 used_at 才确认成功", async function () {
  1452. this.timeout(120000);
  1453. // mock 让 /use 结果延迟 600ms 才在 /status 可见,窗口内 /status 仍返回上一张的 used_at。
  1454. await prepareScenario("personalOnly", PERSONAL_PLAN_KEY, "none", "multiFiveHourUseLagging");
  1455. await openUsageCodingPlanTab(PERSONAL_PLAN_KEY);
  1456. await waitForResetOpportunityCount(3);
  1457. await clickResetOpportunityBadge();
  1458. await assertBodyTextIncludesAny(["2 次", "×2"]);
  1459. await clickDialogFiveHourReset("没有找到 FIVE_HOUR reset 按钮");
  1460. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 1, {
  1461. timeout: 10000,
  1462. timeoutMsg: "第一次五小时重置没有发送 /use",
  1463. });
  1464. await waitForDialogResetState(
  1465. (state) => state.resetDisabled === false && !state.successVisible && state.weekResetVisible,
  1466. "第一次核销后余下机会没有恢复为可核销",
  1467. );
  1468. await clickDialogFiveHourReset("核销一张后没有找到余下机会的 FIVE_HOUR reset 按钮");
  1469. await browser.waitUntil(async () => (await readFiveHourUseRequests()).length === 2, {
  1470. timeout: 10000,
  1471. timeoutMsg: "余下机会的再次点击没有真实发送 /use",
  1472. });
  1473. // 回归点:旧实现把滞后快照里上一张的 used_at 当作第二次成功,提前播放成功反馈后该行
  1474. // 回到「余 1 张可点击」,直到下一次 60s 轮询才收起。修复后保持处理中,读到新 used_at 才完成。
  1475. let revertedToClickable = false;
  1476. await waitForDialogResetState((state) => {
  1477. revertedToClickable ||= state.resetDisabled === false;
  1478. return state.resetDisabled === null && !state.successVisible && state.weekResetVisible;
  1479. }, "完成态再次核销后五小时行没有随机会耗尽收起");
  1480. expect(revertedToClickable).toBe(false);
  1481. expect(await readFiveHourUseRequests()).toHaveLength(2);
  1482. });
  1483. });
  1484. async function prepareScenario(
  1485. scenario: CodingPlanScenario,
  1486. bigmodelSelectedKey: string,
  1487. faultMode: CodingPlanFaultMode = "none",
  1488. resetScenario: CodingPlanResetScenario = "none",
  1489. locale?: "zh-CN" | "en-US",
  1490. loggedOut = false,
  1491. ) {
  1492. // 修复原因:同一 spec 会连续切换个人/团队套餐场景。必须在旧 Electron 退出前清理
  1493. // file:// origin 的 entitlement 缓存;退出后再执行 browser.execute 会被异常吞掉,
  1494. // 上一场景的 Team 快照就会污染下一场景。
  1495. await clearUsageEntitlementCache();
  1496. // Bug 根因:旧 Electron/host 仍存活时直接改 setting.json,退出阶段的异步写回
  1497. // 会把下一场景的夹具覆盖成上一场景。先等进程完整退出,再写持久化夹具,最后
  1498. // 让 reloadSession 只负责创建新应用,场景边界才是确定的。
  1499. await quitElectronAppGracefully();
  1500. await setMockScenario(scenario, faultMode);
  1501. await setResetMockScenario(resetScenario);
  1502. await writeCredentials({
  1503. "oauth:active_provider": "bigmodel",
  1504. "oauth:bigmodel:access_token": "e2e-bigmodel-oauth-token",
  1505. "oauth:bigmodel:user_info": JSON.stringify({
  1506. displayName: "BigModel E2E",
  1507. id: "bigmodel-e2e-user",
  1508. username: "bigmodel-e2e-user",
  1509. }),
  1510. zcodejwttoken:
  1511. resetScenario === "none" &&
  1512. !faultMode.startsWith("startBalance") &&
  1513. faultMode !== "expiredTeam"
  1514. ? ""
  1515. : "e2e-zcode-jwt",
  1516. });
  1517. if (loggedOut)
  1518. await writeCredentials({
  1519. "oauth:active_provider": "",
  1520. "oauth:bigmodel:access_token": "",
  1521. "oauth:bigmodel:user_info": "",
  1522. "oauth:zai:access_token": "",
  1523. "oauth:zai:user_info": "",
  1524. zcodejwttoken: "",
  1525. });
  1526. const connectionSelection = parseBigModelConnectionSelection(bigmodelSelectedKey);
  1527. await writeSettings({
  1528. ...(locale ? { locale, localePreference: locale } : {}),
  1529. providerFamilyConnectionSelections: {
  1530. bigmodel: connectionSelection,
  1531. },
  1532. providerFamilyDomain: "bigmodel",
  1533. providerFamilyDomainMigrated: true,
  1534. // Bug 根因:同一 spec 多次 reloadSession 会继承前一场景关闭时写回的 workspace。
  1535. // Team Plan case 的 model-resolution seed 明确写 DEFAULT_WORKSPACE,因此启动入口也
  1536. // 必须固定到同一个 project workspace,不能偶发落入 conversation workspace。
  1537. lastWorkspaceSession: [
  1538. {
  1539. kind: "local",
  1540. workspacePath: DEFAULT_WORKSPACE,
  1541. workspacePurpose: "project",
  1542. },
  1543. ],
  1544. lastActiveTabIndex: 0,
  1545. });
  1546. // 修复原因:Electron E2E 的 file:// renderer 直接 browser.refresh()
  1547. // 偶发落到 chrome-error://chromewebdata,后续等待会每条 case 慢 30s。
  1548. // 场景切换需要让 main/host 重新读取磁盘设置,因此使用 reloadSession 重建应用。
  1549. await browser.reloadSession();
  1550. // Escape 只临时关闭职业引导;重载 Renderer 会再次遮住 Composer。
  1551. // 复用真实 Skip 流程完成隔离账号的引导,保证重载类 case 的前置状态持久化。
  1552. await skipOccupationOnboardingIfPresent();
  1553. await waitForDefaultWorkspaceReady(60000);
  1554. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1555. await closeTransientOverlays();
  1556. await waitForProviderConfigPolling();
  1557. }
  1558. function parseBigModelConnectionSelection(selectedKey: string) {
  1559. if (selectedKey === BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan)
  1560. return { kind: "start-plan" as const };
  1561. const parts = selectedKey.split(":");
  1562. if (parts[0] !== "team") {
  1563. return { kind: "individual-coding-plan" as const };
  1564. }
  1565. const [, family, productId, organizationId, projectId] = parts;
  1566. if (family !== "bigmodel" || !productId || !organizationId || !projectId) {
  1567. throw new Error(`无效 Team Plan key: ${selectedKey}`);
  1568. }
  1569. return {
  1570. kind: "team-coding-plan" as const,
  1571. productId,
  1572. organizationId,
  1573. projectId,
  1574. };
  1575. }
  1576. async function waitForBigModelConnectionSelection(
  1577. kind: "individual-coding-plan" | "team-coding-plan",
  1578. ) {
  1579. await browser.waitUntil(
  1580. async () => (await readSettings()).providerFamilyConnectionSelections?.bigmodel?.kind === kind,
  1581. {
  1582. timeout: 15000,
  1583. timeoutMsg: `BigModel 连接方式没有收敛到 ${kind}`,
  1584. },
  1585. );
  1586. await waitForProviderConfigPolling();
  1587. }
  1588. async function clearUsageEntitlementCache() {
  1589. // 修复原因:本 spec 会在同一 file:// origin 内切换 personalOnly/teamOnly mock。
  1590. // useUsageEntitlement 的短 TTL localStorage 缓存会保留上个场景的 no_plan,
  1591. // 导致下一次打开 Usage 页时 Coding Plan tab 被误判为不存在。
  1592. try {
  1593. await browser.execute(() => {
  1594. const prefix = "zcode:usage-entitlement:";
  1595. for (const key of Object.keys(window.localStorage)) {
  1596. if (key.startsWith(prefix)) {
  1597. window.localStorage.removeItem(key);
  1598. }
  1599. }
  1600. });
  1601. } catch {
  1602. // reloadSession 前后偶发没有可执行 renderer;缓存清理失败不阻塞场景重建。
  1603. }
  1604. }
  1605. async function openModelProviderSettings() {
  1606. await closeTransientOverlays();
  1607. await ensureSettingsPageOpen();
  1608. await clickVisibleTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "modelProvider"), {
  1609. timeout: 10000,
  1610. timeoutMsg: "设置页没有出现模型供应商分区入口",
  1611. });
  1612. }
  1613. async function assertConnectionModeOptionsInclude(
  1614. expectedOptions: Array<{ key: string; labels: string[] }>,
  1615. ) {
  1616. await openConnectionModeSelect();
  1617. try {
  1618. for (const expectedOption of expectedOptions) {
  1619. const optionTestId = testId(TID_MODEL_PROVIDER_CONNECTION_MODE_ITEM, expectedOption.key);
  1620. const option = await $(sel(optionTestId));
  1621. await option.waitForDisplayed({
  1622. timeout: 10000,
  1623. timeoutMsg: `没有找到连接方式选项: ${optionTestId}`,
  1624. });
  1625. const optionText = await option.getText();
  1626. expect(expectedOption.labels.some((label) => optionText.includes(label))).toBe(true);
  1627. }
  1628. } finally {
  1629. await browser.keys("Escape");
  1630. }
  1631. }
  1632. async function selectConnectionModeOptionByTestId(optionTestId: string, labelForError: string) {
  1633. await openConnectionModeSelect();
  1634. const option = await $(sel(optionTestId));
  1635. await option.waitForDisplayed({
  1636. timeout: 10000,
  1637. timeoutMsg: `没有找到连接方式选项: ${labelForError}`,
  1638. });
  1639. await option.click();
  1640. }
  1641. async function openConnectionModeSelect() {
  1642. await clickVisibleTestIdByDom(TID_MODEL_PROVIDER_CONNECTION_MODE_TRIGGER, {
  1643. timeout: 10000,
  1644. timeoutMsg: "连接方式选择器没有出现",
  1645. });
  1646. }
  1647. async function openUsageCodingPlanTab(sourceId?: string) {
  1648. await openUsageSection();
  1649. await clickUsageCodingPlanTab(sourceId);
  1650. await assertBodyTextIncludesAny(["剩余额度", "Quota remaining", "Quota Remaining"]);
  1651. }
  1652. async function openUsageSection() {
  1653. await closeTransientOverlays();
  1654. await ensureSettingsPageOpen();
  1655. await clickVisibleTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "usage"), {
  1656. timeout: 10000,
  1657. timeoutMsg: "设置页没有出现使用统计分区入口",
  1658. });
  1659. }
  1660. async function ensureSettingsPageOpen() {
  1661. const settingsPage = $(sel(TID_SETTINGS_PAGE));
  1662. if (!(await settingsPage.isDisplayed().catch(() => false))) {
  1663. // Bug 根因:设置新架构会同时保留响应式导航的隐藏副本,旧 helper 取第一个
  1664. // test-id 时可能点中不可见节点并关闭设置页,导致后续误报 Coding Plan tab 消失。
  1665. await clickVisibleTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  1666. timeout: 10000,
  1667. timeoutMsg: "没有找到设置入口按钮",
  1668. });
  1669. await settingsPage.waitForDisplayed({ timeout: 10000 });
  1670. }
  1671. }
  1672. async function openSidebarUsageStats() {
  1673. await closeTransientOverlays();
  1674. await clickVisibleTestIdByDom(TID_LOGIN_TRIGGER, {
  1675. timeout: 10000,
  1676. timeoutMsg: "没有找到头像菜单入口",
  1677. });
  1678. await clickVisibleTestIdByDom(TID_SIDEBAR_CODING_PLAN_USAGE_BUTTON, {
  1679. timeout: 10000,
  1680. timeoutMsg: "没有找到头像菜单里的使用统计入口",
  1681. });
  1682. }
  1683. async function closeTransientOverlays() {
  1684. await browser.keys("Escape");
  1685. await browser.pause(100);
  1686. }
  1687. async function clickUsageCodingPlanTab(sourceId?: string) {
  1688. // 修复原因:使用统计页从单个 "codingPlan" tab 改为按来源生成
  1689. // "codingPlan:<sourceId>",测试不能再写死旧 test id。
  1690. const staticTabId = testId(TID_SETTINGS_USAGE_TAB, "codingPlan");
  1691. const prefix = `${testId(TID_SETTINGS_USAGE_TAB, "codingPlan:")}`;
  1692. const preferredTabId = sourceId ? testId(TID_SETTINGS_USAGE_TAB, `codingPlan:${sourceId}`) : null;
  1693. let selectedTestId = "";
  1694. try {
  1695. await browser.waitUntil(
  1696. async () => {
  1697. selectedTestId = (await browser.execute(
  1698. (legacyTestId, dynamicPrefix, targetTestId) => {
  1699. const candidates = Array.from(
  1700. document.querySelectorAll<HTMLElement>("[data-testid]"),
  1701. ).filter((element) => {
  1702. const current = element.dataset.testid ?? "";
  1703. return current === legacyTestId || current.startsWith(dynamicPrefix);
  1704. });
  1705. // 修复原因:传入 sourceId 时验证的就是该套餐身份。旧 helper
  1706. // 找不到目标时会静默点击第一个可见 tab,把“个人套餐缺失”伪装成
  1707. // 后续 Team 数据断言失败。指定目标时必须精确命中。
  1708. const ordered = targetTestId
  1709. ? candidates.filter((element) => element.dataset.testid === targetTestId)
  1710. : candidates;
  1711. const visible = ordered.find((element) => {
  1712. const style = window.getComputedStyle(element);
  1713. return !(
  1714. style.display === "none" ||
  1715. style.visibility === "hidden" ||
  1716. Number(style.opacity) === 0 ||
  1717. element.getClientRects().length === 0 ||
  1718. element.closest('[aria-hidden="true"], [hidden]')
  1719. );
  1720. });
  1721. return visible?.dataset.testid ?? "";
  1722. },
  1723. staticTabId,
  1724. prefix,
  1725. preferredTabId,
  1726. )) as string;
  1727. return Boolean(selectedTestId);
  1728. },
  1729. {
  1730. timeout: 30000,
  1731. timeoutMsg: "设置页没有出现使用统计 Coding Plan tab",
  1732. },
  1733. );
  1734. const tab = await $(sel(selectedTestId));
  1735. await tab.click();
  1736. } catch (error) {
  1737. throw new Error(
  1738. `设置页没有出现或无法激活 Coding Plan tab: ${selectedTestId}\n${await collectCodingPlanUsageDiagnostics()}`,
  1739. { cause: error },
  1740. );
  1741. }
  1742. }
  1743. async function setRendererViewport(width: number, height: number) {
  1744. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  1745. deviceScaleFactor: 1,
  1746. height,
  1747. mobile: false,
  1748. width,
  1749. });
  1750. await browser.waitUntil(
  1751. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  1752. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  1753. );
  1754. }
  1755. async function setSettingsTheme(theme: "zai-light" | "zai-dark") {
  1756. const changed = await browser.execute((nextTheme) => {
  1757. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  1758. .__testActions;
  1759. const setTheme = actions?.setTheme;
  1760. if (typeof setTheme !== "function") return false;
  1761. (setTheme as (value: string) => void)(nextTheme);
  1762. return true;
  1763. }, theme);
  1764. expect(changed).toBe(true);
  1765. }
  1766. async function clearRendererViewport() {
  1767. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  1768. }
  1769. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  1770. const sent = await browser.electron.execute(
  1771. async (electron, command, commandParams) => {
  1772. const window = electron.BrowserWindow.getAllWindows().find(
  1773. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  1774. );
  1775. if (!window) return false;
  1776. const devtools = window.webContents.debugger;
  1777. if (!devtools.isAttached()) devtools.attach("1.3");
  1778. await devtools.sendCommand(command, commandParams);
  1779. return true;
  1780. },
  1781. method,
  1782. params,
  1783. );
  1784. expect(sent).toBe(true);
  1785. }
  1786. async function collectCodingPlanUsageDiagnostics() {
  1787. const providers = (await readModelProviders()).map((provider) => ({
  1788. id: provider.id,
  1789. enabled: provider.enabled,
  1790. hasApiKey: provider.apiKey.trim().length > 0,
  1791. systemDisabledReason: provider.systemDisabledReason ?? null,
  1792. }));
  1793. const requests = (await readMockRequests()).map((request) => ({
  1794. path: request.path,
  1795. query: request.query,
  1796. organization: request.headers["bigmodel-organization"] ?? null,
  1797. project: request.headers["bigmodel-project"] ?? null,
  1798. }));
  1799. return `诊断: ${JSON.stringify(
  1800. {
  1801. bodyText: (await getBodyText()).slice(0, 2000),
  1802. providers,
  1803. requests,
  1804. },
  1805. null,
  1806. 2,
  1807. )}`;
  1808. }
  1809. async function clickVisibleTestIdByDom(
  1810. currentTestId: string,
  1811. { timeout = 10000, timeoutMsg = `页面没有可见的 test id: ${currentTestId}` } = {},
  1812. ) {
  1813. // 修复原因:头像菜单内容用了 forceMount,隐藏菜单项也会留在 DOM 里。
  1814. // 这里必须等真正可见的菜单项再触发,否则会点到隐藏节点。
  1815. let latestReason = "not-started";
  1816. await browser.waitUntil(
  1817. async () => {
  1818. const result = (await browser.execute((targetTestId) => {
  1819. function isVisible(element: HTMLElement) {
  1820. const style = window.getComputedStyle(element);
  1821. if (
  1822. style.display === "none" ||
  1823. style.visibility === "hidden" ||
  1824. Number(style.opacity) === 0
  1825. ) {
  1826. return false;
  1827. }
  1828. if (element.getClientRects().length === 0) {
  1829. return false;
  1830. }
  1831. return !element.closest('[aria-hidden="true"], [hidden]');
  1832. }
  1833. function dispatchE2EActivation(element: HTMLElement) {
  1834. element.focus();
  1835. const pointerEventCtor = window.PointerEvent ?? MouseEvent;
  1836. for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
  1837. const event =
  1838. type.startsWith("pointer") && pointerEventCtor === window.PointerEvent
  1839. ? new PointerEvent(type, {
  1840. bubbles: true,
  1841. cancelable: true,
  1842. pointerId: 1,
  1843. pointerType: "mouse",
  1844. isPrimary: true,
  1845. })
  1846. : new MouseEvent(type, {
  1847. bubbles: true,
  1848. cancelable: true,
  1849. view: window,
  1850. });
  1851. element.dispatchEvent(event);
  1852. }
  1853. }
  1854. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  1855. (item) => item.dataset.testid === targetTestId && isVisible(item),
  1856. );
  1857. if (!element) {
  1858. return { clicked: false, reason: "missing-visible" };
  1859. }
  1860. const disabled =
  1861. (element instanceof HTMLButtonElement ||
  1862. element instanceof HTMLInputElement ||
  1863. element instanceof HTMLSelectElement ||
  1864. element instanceof HTMLTextAreaElement) &&
  1865. element.disabled;
  1866. if (disabled) {
  1867. return { clicked: false, reason: "disabled" };
  1868. }
  1869. dispatchE2EActivation(element);
  1870. return { clicked: true };
  1871. }, currentTestId)) as { clicked: boolean; reason?: string };
  1872. latestReason = result.reason ?? "clicked";
  1873. return result.clicked;
  1874. },
  1875. {
  1876. timeout,
  1877. timeoutMsg: `${timeoutMsg}: ${latestReason}`,
  1878. },
  1879. );
  1880. }
  1881. async function selectBigModelCodingPlanRuntime(
  1882. planKind: "individual-coding-plan" | "team-coding-plan" = "individual-coding-plan",
  1883. ) {
  1884. const providerId =
  1885. planKind === "team-coding-plan"
  1886. ? "account:bigmodel-team-coding-plan"
  1887. : "account:bigmodel-individual-coding-plan";
  1888. // Bug 根因:只写 selectedSupplierKey 只更新了供应商导航解析状态,并不会更新
  1889. // Composer 的 Effective Model。Context 用量按真实 Effective Provider 判断套餐类型,
  1890. // 因此测试必须和用户一样完成一次 Provider/Model 选择。
  1891. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  1892. includePlainModelFallback: false,
  1893. providerId,
  1894. providerName: "BigModel Coding Plan",
  1895. });
  1896. }
  1897. async function reloadRendererWithBigModelCodingPlanSelection() {
  1898. // Bug 根因:QR-09/10 验证的是 Renderer 首次挂载时的常驻提醒。通过模型菜单选择会
  1899. // 产生提醒外部 pointerdown,从而按产品规则把刚出现的提醒标记为已读;在退出应用前
  1900. // seed 又会被旧 Renderer 的关闭写回覆盖。直接写正式选择存储并只重载 Renderer,
  1901. // 既使用真实 ModelSelection,又不引入测试专用运行时入口或额外 Host 重启。
  1902. await seedPersistedModelSelection({
  1903. modelId: BIGMODEL_E2E_MODEL,
  1904. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1905. reasoningLevel: "max",
  1906. });
  1907. await browser.execute(() => window.location.reload());
  1908. await waitForDefaultWorkspaceReady(60000);
  1909. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1910. await waitForProviderConfigPolling();
  1911. // Bug 根因:直接写 recent selection 只覆盖了草稿的持久化入口;如果当前
  1912. // ModelSelectionView 尚未包含该 Account Provider,Composer 会按现有契约回退到
  1913. // preferredSelection。先通过真实选择控件完成一次有效选择,再重载一次,验证的才是
  1914. // 用户实际会走的 selection -> opportunity 链路,而不是测试专用的 localStorage 假设。
  1915. await selectRegistryProviderModelById(BIGMODEL_E2E_MODEL, {
  1916. includePlainModelFallback: false,
  1917. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  1918. providerName: "BigModel Coding Plan",
  1919. });
  1920. await browser.execute(() => window.location.reload());
  1921. await waitForDefaultWorkspaceReady(60000);
  1922. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  1923. await waitForProviderConfigPolling();
  1924. }
  1925. async function setMockScenario(
  1926. scenario: CodingPlanScenario,
  1927. faultMode: CodingPlanFaultMode = "none",
  1928. ) {
  1929. const baseUrl = getMockBaseUrl();
  1930. const response = await fetch(`${baseUrl}/__e2e/coding-plan/scenario`, {
  1931. method: "POST",
  1932. headers: { "content-type": "application/json" },
  1933. body: JSON.stringify({
  1934. faultMode,
  1935. scenario,
  1936. providerResponsive: faultMode.startsWith("startBalance"),
  1937. }),
  1938. });
  1939. if (!response.ok) {
  1940. throw new Error(`切换 Coding Plan mock scenario 失败: ${response.status}`);
  1941. }
  1942. }
  1943. async function setResetMockScenario(resetScenario: CodingPlanResetScenario) {
  1944. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/reset-scenario`, {
  1945. method: "POST",
  1946. headers: { "content-type": "application/json" },
  1947. body: JSON.stringify({ resetScenario }),
  1948. });
  1949. if (!response.ok) {
  1950. throw new Error(`切换 Coding Plan reset mock scenario 失败: ${response.status}`);
  1951. }
  1952. }
  1953. async function confirmResetUse() {
  1954. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/reset-confirm-use`, {
  1955. method: "POST",
  1956. });
  1957. if (!response.ok) {
  1958. throw new Error(`确认 Coding Plan reset use 失败: ${response.status}`);
  1959. }
  1960. }
  1961. async function waitForResetOpportunityCount(count: number, rootSelector?: string) {
  1962. await browser.waitUntil(
  1963. async () => {
  1964. const labels = (await browser.execute((root: string | undefined) => {
  1965. const scope = root ? document.querySelector(root) : document;
  1966. return Array.from(
  1967. scope?.querySelectorAll<HTMLElement>('[data-reset-opportunity="true"]') ?? [],
  1968. )
  1969. .filter((element) => {
  1970. const style = window.getComputedStyle(element);
  1971. return (
  1972. style.display !== "none" &&
  1973. style.visibility !== "hidden" &&
  1974. element.getClientRects().length > 0
  1975. );
  1976. })
  1977. .map((element) => element.innerText.trim());
  1978. }, rootSelector)) as string[];
  1979. return labels.some((label) => label.includes(String(count)));
  1980. },
  1981. {
  1982. timeout: 10000,
  1983. timeoutMsg: `没有展示 ${count} 次 reset opportunity`,
  1984. },
  1985. );
  1986. }
  1987. async function clickResetOpportunityBadge(rootSelector?: string) {
  1988. const selector = rootSelector
  1989. ? `${rootSelector} [data-reset-opportunity="true"]`
  1990. : '[data-reset-opportunity="true"]';
  1991. for (const badge of await $$(selector)) {
  1992. if (await badge.isDisplayed()) {
  1993. await badge.click();
  1994. return;
  1995. }
  1996. }
  1997. throw new Error("没有找到可点击的 reset opportunity 徽标");
  1998. }
  1999. async function isContextResetReminderVisible(phase: "initial" | "urgent") {
  2000. return browser.execute((currentPhase) => {
  2001. const element = document.querySelector<HTMLElement>(
  2002. `[data-context-reset-reminder="${currentPhase}"]`,
  2003. );
  2004. if (!element) return false;
  2005. const style = window.getComputedStyle(element);
  2006. return (
  2007. style.display !== "none" &&
  2008. style.visibility !== "hidden" &&
  2009. element.getClientRects().length > 0
  2010. );
  2011. }, phase);
  2012. }
  2013. async function waitForContextResetReminder(phase: "initial" | "urgent", expectedTexts: string[]) {
  2014. try {
  2015. await browser.waitUntil(
  2016. async () => {
  2017. if (!(await isContextResetReminderVisible(phase))) return false;
  2018. const text = (await browser.execute((currentPhase) => {
  2019. return (
  2020. document.querySelector<HTMLElement>(`[data-context-reset-reminder="${currentPhase}"]`)
  2021. ?.innerText ?? ""
  2022. );
  2023. }, phase)) as string;
  2024. return expectedTexts.some((expected) => text.includes(expected));
  2025. },
  2026. {
  2027. timeout: 15000,
  2028. timeoutMsg: `没有展示 ${phase} reset opportunity reminder`,
  2029. },
  2030. );
  2031. } catch (error) {
  2032. // Bug 调查:提醒缺失不能只留下一个 waitUntil 超时。机会接口、Context 触发器和
  2033. // 实际 DOM 一并进入失败证据,才能区分“没有数据”和“已有机会但提醒被收起”。
  2034. const reminderDiagnostics = await browser.execute(
  2035. (contextTriggerTestId) => ({
  2036. bodyText: document.body?.innerText?.slice(-2500) ?? "",
  2037. contextTriggerVisible: Array.from(
  2038. document.querySelectorAll<HTMLElement>(`[data-testid="${contextTriggerTestId}"]`),
  2039. ).some((element) => element.getClientRects().length > 0),
  2040. opportunityBadges: Array.from(
  2041. document.querySelectorAll<HTMLElement>('[data-reset-opportunity="true"]'),
  2042. ).map((element) => ({
  2043. text: element.innerText,
  2044. visible: element.getClientRects().length > 0,
  2045. })),
  2046. reminders: Array.from(
  2047. document.querySelectorAll<HTMLElement>("[data-context-reset-reminder]"),
  2048. ).map((element) => ({
  2049. phase: element.dataset.contextResetReminder ?? null,
  2050. text: element.innerText,
  2051. visible: element.getClientRects().length > 0,
  2052. })),
  2053. }),
  2054. TID_CHAT_CONTEXT_USAGE_TRIGGER,
  2055. );
  2056. const resetRequests = (await readMockRequests())
  2057. .filter((request) => request.path.includes("/coding-plan/reset/"))
  2058. .map((request) => ({ method: request.method, path: request.path }));
  2059. throw new Error(
  2060. `没有展示 ${phase} reset opportunity reminder\n诊断: ${JSON.stringify(
  2061. { reminderDiagnostics, resetRequests },
  2062. null,
  2063. 2,
  2064. )}`,
  2065. { cause: error },
  2066. );
  2067. }
  2068. }
  2069. async function readQuotaResetOverlayState() {
  2070. return browser.execute(() => {
  2071. const isVisible = (element: Element | null) => {
  2072. if (!(element instanceof HTMLElement)) return false;
  2073. const style = window.getComputedStyle(element);
  2074. return (
  2075. style.display !== "none" &&
  2076. style.visibility !== "hidden" &&
  2077. element.getClientRects().length > 0
  2078. );
  2079. };
  2080. return {
  2081. dialogVisible: isVisible(document.querySelector('[role="dialog"]')),
  2082. hoverCardVisible: isVisible(document.querySelector('[data-slot="hover-card-content"]')),
  2083. };
  2084. });
  2085. }
  2086. async function findVisibleButtonByAriaLabels(
  2087. labels: string[],
  2088. required = true,
  2089. rootSelector?: string,
  2090. ) {
  2091. const selector = rootSelector ? `${rootSelector} button` : "button";
  2092. for (const button of await $$(selector)) {
  2093. if (!(await button.isDisplayed())) continue;
  2094. const ariaLabel = await button.getAttribute("aria-label");
  2095. if (ariaLabel && labels.includes(ariaLabel)) return button;
  2096. }
  2097. if (required) throw new Error(`找不到按钮: ${labels.join("/")}`);
  2098. return undefined;
  2099. }
  2100. /** 单次 execute 往返读取弹框内 FIVE_HOUR 重置按钮与成功态;QR-E2E-03 的 confirm
  2101. * 窗口只有约 2.5 秒,逐按钮 isDisplayed/getAttribute 的多次 WebDriver 往返会超窗。 */
  2102. async function readFiveHourUseRequests() {
  2103. return (await readMockRequests()).filter(
  2104. (request) =>
  2105. request.path.endsWith("/api/v1/coding-plan/reset/use") &&
  2106. isRecord(request.body) &&
  2107. request.body.reset_type === "FIVE_HOUR",
  2108. );
  2109. }
  2110. async function clickDialogFiveHourReset(missingMessage: string) {
  2111. const button = await findVisibleButtonByAriaLabels(
  2112. ["重置 5 小时额度", "Reset 5-hour quota"],
  2113. false,
  2114. '[role="dialog"]',
  2115. );
  2116. if (!button) throw new Error(missingMessage);
  2117. await button.click();
  2118. }
  2119. async function readDialogResetState() {
  2120. return browser.execute(
  2121. (resetLabels: string[], successLabels: string[], weekResetLabels: string[]) => {
  2122. const dialog = document.querySelector('[role="dialog"]');
  2123. const buttons = dialog
  2124. ? Array.from(dialog.querySelectorAll<HTMLButtonElement>("button"))
  2125. : [];
  2126. const findByLabels = (candidates: string[]) =>
  2127. buttons.find((button) => candidates.includes(button.getAttribute("aria-label") ?? "")) ??
  2128. null;
  2129. const resetButton = findByLabels(resetLabels);
  2130. return {
  2131. resetDisabled: resetButton ? resetButton.disabled : null,
  2132. // 重置按钮与类型名、次数药丸、倒计时同处一个行容器,用于断言该行展示内容。
  2133. resetRowText: resetButton?.parentElement?.innerText ?? null,
  2134. successVisible: findByLabels(successLabels) !== null,
  2135. weekResetVisible: findByLabels(weekResetLabels) !== null,
  2136. };
  2137. },
  2138. ["重置 5 小时额度", "Reset 5-hour quota"],
  2139. ["重置成功", "Reset successful"],
  2140. ["重置周额度", "Reset weekly quota"],
  2141. );
  2142. }
  2143. async function waitForDialogResetState(
  2144. predicate: (state: Awaited<ReturnType<typeof readDialogResetState>>) => boolean,
  2145. timeoutMsg: string,
  2146. ) {
  2147. let lastState: Awaited<ReturnType<typeof readDialogResetState>> | null = null;
  2148. try {
  2149. await browser.waitUntil(
  2150. async () => {
  2151. const state = await readDialogResetState();
  2152. lastState = state;
  2153. return predicate(state);
  2154. },
  2155. { interval: 100, timeout: 10000, timeoutMsg },
  2156. );
  2157. } catch (error) {
  2158. throw new Error(`${timeoutMsg}: ${JSON.stringify(lastState)}`, { cause: error });
  2159. }
  2160. }
  2161. async function waitForMockRequest(
  2162. predicate: (request: MockRequest) => boolean,
  2163. timeoutMsg: string,
  2164. ) {
  2165. await browser.waitUntil(async () => (await readMockRequests()).some(predicate), {
  2166. timeout: 10000,
  2167. timeoutMsg,
  2168. });
  2169. }
  2170. async function waitForLatestMockRequest(
  2171. predicate: (request: MockRequest) => boolean,
  2172. timeoutMsg: string,
  2173. ): Promise<MockRequest> {
  2174. let match: MockRequest | undefined;
  2175. await browser.waitUntil(
  2176. async () => {
  2177. match = (await readMockRequests()).findLast(predicate);
  2178. return Boolean(match);
  2179. },
  2180. { timeout: 10000, timeoutMsg },
  2181. );
  2182. if (!match) {
  2183. throw new Error(timeoutMsg);
  2184. }
  2185. return match;
  2186. }
  2187. async function clickVisibleButtonByText(labels: string[]): Promise<void> {
  2188. for (const button of await $$("button")) {
  2189. if ((await button.isDisplayed()) && labels.includes((await button.getText()).trim())) {
  2190. await button.click();
  2191. return;
  2192. }
  2193. }
  2194. throw new Error(`找不到可见按钮: ${labels.join("/")}`);
  2195. }
  2196. function daysBetweenMonitorTimes(startTime: string, endTime: string): number {
  2197. const start = Date.parse(startTime.replace(" ", "T") + "Z");
  2198. const end = Date.parse(endTime.replace(" ", "T") + "Z");
  2199. return Math.floor((end - start) / 86_400_000);
  2200. }
  2201. function requireQueryValue(request: MockRequest, key: string): string {
  2202. const value = request.query[key];
  2203. if (!value) {
  2204. throw new Error(`mock request 缺少 query: ${key}`);
  2205. }
  2206. return value;
  2207. }
  2208. function requestRangeDays(request: MockRequest): number | null {
  2209. const startTime = request.query.startTime;
  2210. const endTime = request.query.endTime;
  2211. return startTime && endTime ? daysBetweenMonitorTimes(startTime, endTime) : null;
  2212. }
  2213. async function readMockRequests(): Promise<MockRequest[]> {
  2214. const response = await fetch(`${getMockBaseUrl()}/__e2e/coding-plan/requests`);
  2215. const payload = (await response.json()) as { requests?: MockRequest[] };
  2216. return payload.requests ?? [];
  2217. }
  2218. function getMockBaseUrl() {
  2219. const baseUrl = process.env.ZCODE_E2E_CODING_PLAN_MOCK_URL?.trim();
  2220. if (!baseUrl) {
  2221. throw new Error("ZCODE_E2E_CODING_PLAN_MOCK_URL 未配置");
  2222. }
  2223. return baseUrl;
  2224. }
  2225. async function writeSettings(patch: Record<string, unknown>) {
  2226. await mkdir(join(E2E_STORAGE_ROOT, "v2"), { recursive: true });
  2227. const current = await readSettings();
  2228. await writeFile(SETTINGS_FILE, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  2229. }
  2230. async function writeCredentials(patch: Record<string, unknown>) {
  2231. await mkdir(join(E2E_STORAGE_ROOT, "v2"), { recursive: true });
  2232. const current = await readJsonFile(CREDENTIALS_FILE);
  2233. await writeFile(CREDENTIALS_FILE, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  2234. }
  2235. async function readSettings(): Promise<{
  2236. providerFamilyConnectionSelections?: {
  2237. bigmodel?: ProviderFamilyConnectionSelection;
  2238. zai?: ProviderFamilyConnectionSelection;
  2239. };
  2240. [key: string]: unknown;
  2241. }> {
  2242. try {
  2243. return JSON.parse(await readFile(SETTINGS_FILE, "utf-8")) as Record<string, unknown>;
  2244. } catch {
  2245. return {};
  2246. }
  2247. }
  2248. async function readJsonFile(path: string): Promise<Record<string, unknown>> {
  2249. try {
  2250. return JSON.parse(await readFile(path, "utf-8")) as Record<string, unknown>;
  2251. } catch {
  2252. return {};
  2253. }
  2254. }
  2255. function isRecord(value: unknown): value is Record<string, unknown> {
  2256. return typeof value === "object" && value !== null && !Array.isArray(value);
  2257. }
  2258. async function assertBodyTextIncludes(values: string[]) {
  2259. try {
  2260. await browser.waitUntil(
  2261. async () => {
  2262. const bodyText = await getBodyText();
  2263. return values.every((value) => bodyText.includes(value));
  2264. },
  2265. {
  2266. timeout: 10000,
  2267. timeoutMsg: `页面没有出现全部文本: ${values.join(" / ")}`,
  2268. },
  2269. );
  2270. } catch (error) {
  2271. throw new Error(
  2272. `页面没有出现全部文本: ${values.join(" / ")}\n当前页面文本:\n${(await getBodyText()).slice(0, 2000)}`,
  2273. { cause: error },
  2274. );
  2275. }
  2276. }
  2277. async function assertBodyTextIncludesAny(values: string[]) {
  2278. try {
  2279. await browser.waitUntil(
  2280. async () => {
  2281. const bodyText = await getBodyText();
  2282. return values.some((value) => bodyText.includes(value));
  2283. },
  2284. {
  2285. timeout: 10000,
  2286. timeoutMsg: `页面没有出现任一文本: ${values.join(" / ")}`,
  2287. },
  2288. );
  2289. } catch (error) {
  2290. throw new Error(
  2291. `页面没有出现任一文本: ${values.join(" / ")}\n当前页面文本:\n${(await getBodyText()).slice(0, 2000)}`,
  2292. { cause: error },
  2293. );
  2294. }
  2295. }
  2296. async function assertBodyTextExcludes(values: string[]) {
  2297. const bodyText = await getBodyText();
  2298. for (const value of values) {
  2299. expect(bodyText).not.toContain(value);
  2300. }
  2301. }
  2302. function getBodyText() {
  2303. return browser.execute(() => document.body?.innerText ?? "");
  2304. }
  2305. interface MockRequest {
  2306. body?: unknown;
  2307. headers: Record<string, string | string[] | undefined>;
  2308. method: string;
  2309. path: string;
  2310. query: Record<string, string>;
  2311. }
  2312. type ReminderNavigationWindow = Window & {
  2313. __zcodeTabStoreE2E: {
  2314. getState(): {
  2315. activeTabId: string | null;
  2316. openSettingsTab(): void;
  2317. activateTab(id: string): void;
  2318. };
  2319. };
  2320. };
  2321. async function assertContextReminderHiddenInSettings(phase: "initial" | "urgent") {
  2322. // 通过真实导航 store 切层,避免打开入口的 pointerdown 把提醒预先标已读,掩盖 Portal 泄漏。
  2323. const workspaceTabId = await browser.execute(() => {
  2324. const store = (window as unknown as ReminderNavigationWindow).__zcodeTabStoreE2E;
  2325. const id = store.getState().activeTabId;
  2326. store.getState().openSettingsTab();
  2327. return id;
  2328. });
  2329. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 10000 });
  2330. await browser.waitUntil(async () => !(await isContextResetReminderVisible(phase)), {
  2331. timeout: 5000,
  2332. timeoutMsg: "Composer 提醒穿透到设置页",
  2333. });
  2334. // 设置页点击不能消耗后台工作区的提醒状态。
  2335. await browser.execute(() =>
  2336. document
  2337. .querySelector('[data-testid="settings-page"]')!
  2338. .dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })),
  2339. );
  2340. await browser.execute(
  2341. (id) =>
  2342. (window as unknown as ReminderNavigationWindow).__zcodeTabStoreE2E
  2343. .getState()
  2344. .activateTab(id!),
  2345. workspaceTabId,
  2346. );
  2347. await browser.waitUntil(async () => await isContextResetReminderVisible(phase), {
  2348. timeout: 5000,
  2349. timeoutMsg: "设置页点击误将 Composer 提醒标记为已读",
  2350. });
  2351. }
  2352. // 读取真实展示组件的输入:保留 DOM 和 Host owner,只观察同一挂载树中的用量投影。
  2353. async function readComposerTeamUsageSource(): Promise<string | null> {
  2354. return browser.execute(() => {
  2355. const element = document.querySelector('[data-testid="v4-model-config"]');
  2356. if (!element) return null;
  2357. let fiber = (element as any)[
  2358. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  2359. ];
  2360. while (fiber.return) fiber = fiber.return;
  2361. // DOM 上的 Fiber 可指向 alternate;必须从 React 当前 root 读取已提交展示。
  2362. const pending = [fiber.stateNode.current];
  2363. while (pending.length) {
  2364. const node = pending.pop();
  2365. if (Object.hasOwn(node.memoizedProps ?? {}, "codingPlanUsageRemaining"))
  2366. return node.memoizedProps.codingPlanUsageRemaining?.selectedProviderId ?? null;
  2367. if (node.sibling) pending.push(node.sibling);
  2368. if (node.child) pending.push(node.child);
  2369. }
  2370. return null;
  2371. });
  2372. }
  2373. // 注入请求交错,不伪造设置落盘或替换生产菜单。所有修改在 finally 恢复。
  2374. async function installConnectionBoundaryProbe(
  2375. mode: "logout" | "cas" | "mismatch" | "refresh-failure",
  2376. ) {
  2377. await browser.execute(async (mode) => {
  2378. const element = document.querySelector('[data-testid="v4-model-config"]')!;
  2379. let fiber = (element as any)[
  2380. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  2381. ];
  2382. let services: any;
  2383. let store: any;
  2384. const accessors = new Set<any>();
  2385. while (fiber) {
  2386. const value = fiber.memoizedProps?.value;
  2387. const candidate = value?.settingService ? value : fiber.memoizedProps?.services;
  2388. if (candidate?.settingService) accessors.add(candidate);
  2389. services ??= candidate;
  2390. if (value?.getState && value.getState().setUser) store ??= value;
  2391. fiber = fiber.return;
  2392. }
  2393. if (!services?.settingService) throw new Error("Workspace services not found");
  2394. if (mode === "logout") {
  2395. if (!store) throw new Error("Auth store not found");
  2396. // 原因:刷新后断言会漏掉旧 Provider 与新 user 并存的窗口;先阻塞 refresh 再登出。
  2397. const restorers: (() => void)[] = [];
  2398. let release!: () => void;
  2399. const blocked = new Promise<void>((resolve) => {
  2400. release = resolve;
  2401. });
  2402. for (const accessor of accessors) {
  2403. const original = accessor.providerSettingsService;
  2404. accessor.providerSettingsService = new Proxy(original, {
  2405. get(target, prop) {
  2406. if (prop !== "refresh") return Reflect.get(target, prop);
  2407. return async (...args: any[]) => {
  2408. await blocked;
  2409. return target.refresh(...args);
  2410. };
  2411. },
  2412. });
  2413. restorers.push(() => {
  2414. accessor.providerSettingsService = original;
  2415. });
  2416. }
  2417. const suppressedRestores: unknown[] = [];
  2418. // 测试屏障同时暂停旧凭据的恢复回执,保证断言窗口确实保持 user=null;不改生产鉴权流程。
  2419. const pauseAuthRestore = store.subscribe((state: any) => {
  2420. if (state.user) {
  2421. suppressedRestores.push({ userId: state.user.id, authSessionSeq: state.authSessionSeq });
  2422. state.setUser(null);
  2423. }
  2424. });
  2425. (window as any).__logoutBoundaryRelease = async () => {
  2426. pauseAuthRestore();
  2427. restorers.forEach((restore) => restore());
  2428. release();
  2429. await services.oauthService.logoutAll();
  2430. store.getState().setUser(null);
  2431. await services.providerSettingsService.refresh("e2e-signed-out");
  2432. };
  2433. (window as any).__logoutBoundaryAuth = () => ({
  2434. userId: store.getState().user?.id ?? null,
  2435. authSessionSeq: store.getState().authSessionSeq,
  2436. });
  2437. store.getState().setUser(null);
  2438. return;
  2439. }
  2440. const trace: unknown[] = [];
  2441. let restore = () => {};
  2442. const restorers: (() => void)[] = [];
  2443. let injected = false;
  2444. let armed = false;
  2445. let recovered = false;
  2446. let obsoleteStarted = false;
  2447. let rejectObsolete!: (cause: Error) => void;
  2448. const presentationListeners: ((candidate: any) => void)[] = [];
  2449. let releasePresentation!: () => void;
  2450. const synchronized = new Promise<void>((resolve) => {
  2451. releasePresentation = resolve;
  2452. });
  2453. for (const accessor of accessors) {
  2454. const key = mode === "cas" ? "settingService" : "modelSelectionService";
  2455. const service = accessor[key];
  2456. if (mode === "cas") {
  2457. accessor[key] = new Proxy(service, {
  2458. get(target, prop) {
  2459. if (prop !== "update") return Reflect.get(target, prop);
  2460. return async (patch: any, expected: any) => {
  2461. if (armed && !injected && patch.providerFamilyConnectionSelections) {
  2462. injected = true;
  2463. const before = await service.get();
  2464. await service.update(
  2465. {
  2466. providerFamilyConnectionSelections: {
  2467. ...before.providerFamilyConnectionSelections,
  2468. zai: { kind: "individual-coding-plan" },
  2469. },
  2470. },
  2471. {
  2472. providerFamilyDomain: before.providerFamilyDomain,
  2473. providerFamilyConnectionSelections: before.providerFamilyConnectionSelections,
  2474. providerFamilyDomainUpdatedAt: before.providerFamilyDomainUpdatedAt ?? 0,
  2475. },
  2476. );
  2477. trace.push({ phase: "concurrent-write", expected });
  2478. }
  2479. return service.update(patch, expected);
  2480. };
  2481. },
  2482. });
  2483. } else {
  2484. accessor[key] = new Proxy(service, {
  2485. get(target, prop) {
  2486. if (mode === "refresh-failure" && prop === "onDidChange")
  2487. return (listener: any) => {
  2488. presentationListeners.push(listener);
  2489. let delivered = false;
  2490. return service.onDidChange((candidate: any) => {
  2491. // 每个订阅收到一次目标事件;不能由另一订阅抢先吞掉 Composer 的回执。
  2492. if (armed && delivered) return;
  2493. if (armed) {
  2494. delivered = true;
  2495. trace.push({ phase: "target-event", revision: candidate.revision });
  2496. }
  2497. listener(candidate);
  2498. });
  2499. };
  2500. if (prop !== "getView") return Reflect.get(target, prop);
  2501. return async (input: any) => {
  2502. if (mode === "refresh-failure" && armed && input) {
  2503. trace.push({ phase: "presentation-failed" });
  2504. throw new Error("E2E presentation read failed");
  2505. }
  2506. if (mode === "refresh-failure" && recovered && input && !obsoleteStarted) {
  2507. obsoleteStarted = true;
  2508. trace.push({ phase: "obsolete-started" });
  2509. return new Promise((_resolve, reject) => {
  2510. rejectObsolete = reject;
  2511. });
  2512. }
  2513. const view = await service.getView(input);
  2514. if (mode === "refresh-failure") {
  2515. if (recovered && input)
  2516. trace.push({ phase: "presentation-recovered", revision: view.revision });
  2517. if (armed) trace.push({ phase: "target-synchronized", revision: view.revision });
  2518. return view;
  2519. }
  2520. if (!armed) return view;
  2521. if (!input) {
  2522. trace.push({ phase: "target-synchronized", revision: view.revision });
  2523. releasePresentation();
  2524. return view;
  2525. }
  2526. // 挂起展示读取直到连接同步完成,再读取同一 owner 的最新 revision;
  2527. // 旧 ready 不属于本次回执,不能拿它伪造 ready+mismatch。
  2528. await synchronized;
  2529. const latest = await service.getView(input);
  2530. trace.push({
  2531. phase: "ready-mismatch",
  2532. revision: latest.revision,
  2533. original: latest.effectiveSelection,
  2534. });
  2535. return {
  2536. ...latest,
  2537. // 固定的 Flash 恰好可能是目标首选模型,不能保证冲突;回放另一有效 Provider 的选择。
  2538. effectiveSelection: {
  2539. providerId: "e2e-upstream",
  2540. modelId: "deepseek-v4-flash",
  2541. options: { reasoningLevel: "disabled" },
  2542. },
  2543. };
  2544. };
  2545. },
  2546. });
  2547. }
  2548. restorers.push(() => {
  2549. accessor[key] = service;
  2550. });
  2551. }
  2552. // RPC 方法 getter 不读取赋值;替换 accessor 的端口并重渲染,保持生产 RPC 和设置锁。
  2553. if (!store) throw new Error("Auth store not found");
  2554. store.getState().setUser({ ...store.getState().user });
  2555. restore = () => {
  2556. releasePresentation();
  2557. restorers.forEach((restore) => restore());
  2558. store.getState().setUser({ ...store.getState().user });
  2559. };
  2560. Object.assign(window, {
  2561. __connectionBoundaryProbe: {
  2562. trace,
  2563. restore,
  2564. recover: () => {
  2565. armed = false;
  2566. recovered = true;
  2567. trace.push({ phase: "fault-recovered" });
  2568. },
  2569. supersede: async () => {
  2570. const candidate = await Array.from(accessors)[0].modelSelectionService.getView();
  2571. presentationListeners.forEach((listener) => listener(candidate));
  2572. },
  2573. rejectObsolete: () => {
  2574. trace.push({ phase: "obsolete-failed" });
  2575. rejectObsolete(new Error("E2E obsolete presentation failed"));
  2576. },
  2577. arm: () => {
  2578. armed = true;
  2579. },
  2580. },
  2581. });
  2582. }, mode);
  2583. }