settings-ui-polish.test.ts 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  1. import { mkdir } from "node:fs/promises";
  2. import { ModelConfig, ModelOptionSpecsConfig } from "@zcode/provider";
  3. import { NodePersonalProviderConfigRepository } from "@zcode/provider-node";
  4. import { join } from "node:path";
  5. import { encodeCustomModelValue } from "@zcode/shared";
  6. import {
  7. TID_CHAT_MODEL_SELECT_ITEM,
  8. TID_CHAT_MODEL_SELECT_GROUP,
  9. TID_CHAT_MODEL_SELECT_TRIGGER,
  10. TID_SETTINGS_BACK_BUTTON,
  11. TID_LOGIN_TRIGGER,
  12. TID_MODEL_PROVIDER_ADD_PROVIDER_BUTTON,
  13. TID_MODEL_PROVIDER_ADD_MODEL_BUTTON,
  14. TID_MODEL_PROVIDER_API_KEY_INPUT,
  15. TID_MODEL_PROVIDER_API_FORMAT_TRIGGER,
  16. TID_MODEL_PROVIDER_BASE_URL_INPUT,
  17. TID_MODEL_PROVIDER_MODEL_DELETE_BUTTON,
  18. TID_MODEL_PROVIDER_NAV_ITEM,
  19. TID_MODEL_PROVIDER_TEMPLATE_BACK_BUTTON,
  20. TID_MODEL_PROVIDER_TEMPLATE_ITEM,
  21. TID_MODEL_PROVIDER_TEMPLATE_PICKER,
  22. TID_SETTINGS_PAGE,
  23. TID_TASK_SETTINGS_BUTTON,
  24. testId,
  25. } from "@zcode/shared/test-ids";
  26. import {
  27. DEFAULT_WORKSPACE,
  28. getE2EAppDataPaths,
  29. clearAppData,
  30. clickTestIdByDom,
  31. clickTestIdByWebDriver,
  32. readModelProvider,
  33. waitForWorkspaceApp,
  34. } from "#e2e/helpers/desktop-app";
  35. import { restartIntoWorkspace, seedReplayProvider } from "#e2e/helpers/model-provider-restart";
  36. import { sel } from "#e2e/helpers/selectors";
  37. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  38. import {
  39. assertNoRemoteModelProviderSyncAction,
  40. openModelProviderSettings,
  41. } from "#e2e/helpers/settings-model-provider-boundary";
  42. const EMPTY_MODELS_PROVIDER_ID = "e2e-empty-models-provider";
  43. const REORDER_MODELS_PROVIDER_ID = "e2e-reorder-models-provider";
  44. const REORDER_MODEL_IDS = ["e2e-reorder-first", "e2e-reorder-second"] as const;
  45. const REASONING_EDITOR_PROVIDER_ID = "e2e-reasoning-editor-provider";
  46. const REASONING_EDITOR_MODEL_ID = "gateway/team/glm-5.3-20260907";
  47. const DELETE_PROVIDER_ID = "e2e-delete-provider";
  48. describe("设置页 UI polish E2E", () => {
  49. after(async () => {
  50. await browser.electron.restoreAllMocks();
  51. await clearAppData();
  52. });
  53. beforeEach(async () => {
  54. // 上一个用例可能停在设置页,先真实关闭遮挡层再操作侧栏项目。
  55. const back = $(sel(TID_SETTINGS_BACK_BUTTON));
  56. if (await back.isDisplayed()) await back.click();
  57. await prepareV4ConversationE2E({ skipProvider: true });
  58. // prepare 已保证默认项目草稿;窄屏检查会收起侧栏,不能再无条件 hover 新建。
  59. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  60. });
  61. it("UP-00: Windows 设置页使用问号帮助入口且移除 caption 下箭头", async function () {
  62. if (process.platform !== "win32") {
  63. this.skip();
  64. return;
  65. }
  66. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 15000 });
  67. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  68. const panel = await $('[data-settings-panel-frame="true"]');
  69. expect(((await panel.getAttribute("class")) ?? "").split(/\s+/)).toContain("rounded-md");
  70. expect(await panel.getCSSProperty("border-top-left-radius")).toMatchObject({ value: "6px" });
  71. expect(
  72. await $('[data-testid="settings-page"] svg.lucide-circle-question-mark').isDisplayed(),
  73. ).toBe(true);
  74. expect(
  75. await $(
  76. '[data-testid="settings-page"] button[aria-label="titleBar.windowMenu"]',
  77. ).isExisting(),
  78. ).toBe(false);
  79. expect(
  80. await $(
  81. '[data-testid="settings-page"] [data-testid="desktop-window-controls"]',
  82. ).isDisplayed(),
  83. ).toBe(true);
  84. expect(
  85. await browser.execute(() => {
  86. const panel = document.querySelector<HTMLElement>('[data-settings-panel-frame="true"]');
  87. return panel ? getComputedStyle(panel).borderTopRightRadius : null;
  88. }),
  89. ).toBe("6px");
  90. expect(
  91. await browser.execute(() => {
  92. const logo = document.querySelector<HTMLElement>(
  93. '[data-testid="settings-page"] [data-testid="settings-logo"]',
  94. );
  95. if (!logo) return null;
  96. const rect = logo.getBoundingClientRect();
  97. return { left: rect.left, top: rect.top };
  98. }),
  99. ).toEqual({ left: 17, top: 19 });
  100. const settingsLogo = await $('[data-testid="settings-logo"]');
  101. expect(await settingsLogo.$("[data-desktop-logo-badge]").getSize("width")).toBe(20);
  102. expect(await settingsLogo.$("svg").getSize("width")).toBe(13);
  103. expect(await settingsLogo.$("animate").isExisting()).toBe(false);
  104. for (const theme of ["light", "dark"]) {
  105. await setPresentation({ locale: "zh-CN", theme });
  106. expect(await settingsLogo.$("svg").getSize("width")).toBe(13);
  107. const screenshotDir = join(process.cwd(), ".e2e-artifacts", "desktop-logo");
  108. await mkdir(screenshotDir, { recursive: true });
  109. await browser.saveScreenshot(join(screenshotDir, `settings-${theme}.png`));
  110. }
  111. expect(
  112. await browser.execute(() => {
  113. const help = document
  114. .querySelector('[data-testid="settings-page"] svg.lucide-circle-question-mark')
  115. ?.closest<HTMLElement>("button");
  116. const close = document.querySelector<HTMLElement>(
  117. '[data-testid="settings-page"] [data-testid="window-control-close"]',
  118. );
  119. if (!help || !close) return null;
  120. const helpRect = help.getBoundingClientRect();
  121. const closeRect = close.getBoundingClientRect();
  122. return {
  123. helpTop: helpRect.top,
  124. closeTop: closeRect.top,
  125. closeRightInset: window.innerWidth - closeRect.right,
  126. };
  127. }),
  128. ).toEqual({ helpTop: 17, closeTop: 17, closeRightInset: 15 });
  129. expect(
  130. await browser.execute(() => {
  131. const content = document.querySelector('[data-settings-content-frame="true"]')!;
  132. const panel = document.querySelector('[data-settings-panel-frame="true"]')!;
  133. const style = getComputedStyle(content);
  134. return {
  135. right: style.paddingRight,
  136. bottom: style.paddingBottom,
  137. top: panel.getBoundingClientRect().top - content.getBoundingClientRect().top,
  138. };
  139. }),
  140. ).toEqual({ right: "6px", bottom: "6px", top: 6 });
  141. });
  142. it("UP-01: 头像菜单按 language、theme、zoom 顺序展示偏好入口", async function () {
  143. this.timeout(60000);
  144. await clickVisibleTestId(TID_LOGIN_TRIGGER, {
  145. timeout: 15000,
  146. timeoutMsg: "侧边栏头像菜单入口没有出现",
  147. });
  148. await browser.waitUntil(async () => (await readVisibleProfileMenuItems()).length >= 3, {
  149. timeout: 15000,
  150. timeoutMsg: "头像菜单的偏好入口没有完整展开",
  151. });
  152. const menuSnapshot = await readVisibleProfileMenuItems();
  153. if (process.platform === "darwin") {
  154. // macOS 根框架使用 background-alt;比较语义 utility 的运行时主题色,避免绑定具体色值格式。
  155. const backgrounds = await browser.execute(() => {
  156. const frame = document.querySelector<HTMLElement>(
  157. "div.h-dvh.flex.flex-col.overflow-hidden.border-border.text-foreground",
  158. );
  159. if (!frame) throw new Error("DesktopWindowFrame 不存在");
  160. const reference = document.createElement("div");
  161. reference.className = "bg-background-alt";
  162. document.body.append(reference);
  163. const result = [
  164. getComputedStyle(frame).backgroundColor,
  165. getComputedStyle(reference).backgroundColor,
  166. ];
  167. reference.remove();
  168. return result;
  169. });
  170. expect(backgrounds[0]).toBe(backgrounds[1]);
  171. }
  172. if (process.platform === "linux") {
  173. const shellChrome = await browser.execute(() => {
  174. const frame = document.querySelector<HTMLElement>('[data-desktop-window-frame="true"]');
  175. if (!frame) throw new Error("DesktopWindowFrame 不存在");
  176. const style = getComputedStyle(frame);
  177. return { radius: style.borderTopLeftRadius, clipPath: style.clipPath };
  178. });
  179. expect(shellChrome).toEqual({ radius: "16px", clipPath: "inset(0px round 16px)" });
  180. }
  181. // 圆角规范:独立菜单外壳 lg,选项 md;读取计算样式以覆盖实际 CSS 和业务覆盖。
  182. const radii = await browser.execute(() => {
  183. const menu = Array.from(
  184. document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-content"]'),
  185. ).find((element) => element.getBoundingClientRect().width > 0);
  186. if (!menu) throw new Error("头像菜单浮层没有出现");
  187. return {
  188. shell: getComputedStyle(menu).borderTopLeftRadius,
  189. items: Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitem"]')).map(
  190. (item) => getComputedStyle(item).borderTopLeftRadius,
  191. ),
  192. };
  193. });
  194. expect(radii.shell).toBe("8px");
  195. expect(radii.items.length).toBeGreaterThanOrEqual(3);
  196. expect(radii.items.every((radius) => radius === "6px")).toBe(true);
  197. const languageIndex = menuSnapshot.findIndex((text) => /界面语言|Language/.test(text));
  198. const themeIndex = menuSnapshot.findIndex((text) => /界面主题|App theme/.test(text));
  199. const zoomIndex = menuSnapshot.findIndex((text) => /界面缩放|Interface zoom/.test(text));
  200. if (languageIndex < 0 || themeIndex < 0 || zoomIndex < 0) {
  201. throw new Error(`头像菜单偏好入口不完整:${JSON.stringify(menuSnapshot)}`);
  202. }
  203. expect(themeIndex).toBeGreaterThan(languageIndex);
  204. expect(zoomIndex).toBeGreaterThan(themeIndex);
  205. // 本例遗留的模态菜单会屏蔽下一例真实滚轮;DOM click 不受遮挡,曾掩盖该污染。
  206. await browser.keys("Escape");
  207. await browser.waitUntil(
  208. async () =>
  209. (await readVisibleProfileMenuItems()).length === 0 &&
  210. (await browser.execute(() => getComputedStyle(document.body).pointerEvents)) !== "none",
  211. { timeout: 10000, timeoutMsg: "头像菜单未关闭或指针屏障尚未释放" },
  212. );
  213. });
  214. it("UP-02: 设置页桌面 Sidebar 宽度为 268px 且与内容直接相接", async () => {
  215. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 15000 });
  216. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  217. expect(
  218. await browser.execute(() => {
  219. const page = document.querySelector<HTMLElement>('[data-testid="settings-page"]');
  220. const sidebar = page?.querySelector<HTMLElement>(":scope > aside");
  221. const content = page?.querySelector<HTMLElement>('[data-settings-content-frame="true"]');
  222. if (!page || !sidebar || !content) return null;
  223. const pageRect = page.getBoundingClientRect();
  224. const sidebarRect = sidebar.getBoundingClientRect();
  225. const contentRect = content.getBoundingClientRect();
  226. return {
  227. sidebarWidth: sidebarRect.width,
  228. contentOffset: contentRect.left - pageRect.left,
  229. gap: contentRect.left - sidebarRect.right,
  230. };
  231. }),
  232. ).toEqual({ sidebarWidth: 268, contentOffset: 268, gap: 0 });
  233. });
  234. async function readVisibleProfileMenuItems() {
  235. return browser.execute(() => {
  236. const visibleItems = Array.from(
  237. document.querySelectorAll<HTMLElement>('[role="menuitem"]'),
  238. ).filter((element) => {
  239. const rect = element.getBoundingClientRect();
  240. return rect.width > 0 && rect.height > 0;
  241. });
  242. return visibleItems.map((element) => element.innerText.trim());
  243. });
  244. }
  245. it("MP-UI-01: 点击新增供应商后原子创建并直接进入普通详情卡", async function () {
  246. this.timeout(60000);
  247. await openModelProviderSettings();
  248. expect(
  249. await browser.execute((addProviderTestId) => {
  250. const addButton = document.querySelector<HTMLButtonElement>(
  251. `[data-testid="${addProviderTestId}"]`,
  252. );
  253. const actions = addButton?.parentElement;
  254. const refreshButton = Array.from(
  255. actions?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  256. ).find((button) => button !== addButton);
  257. return {
  258. addVariant: addButton?.dataset.variant,
  259. addSize: addButton?.dataset.size,
  260. gap: actions ? getComputedStyle(actions).gap : null,
  261. refreshBeforeAdd: Boolean(
  262. refreshButton &&
  263. addButton &&
  264. refreshButton.compareDocumentPosition(addButton) & Node.DOCUMENT_POSITION_FOLLOWING,
  265. ),
  266. refreshVariant: refreshButton?.dataset.variant,
  267. refreshSize: refreshButton?.dataset.size,
  268. };
  269. }, TID_MODEL_PROVIDER_ADD_PROVIDER_BUTTON),
  270. ).toEqual({
  271. addVariant: "default",
  272. addSize: "default",
  273. gap: "8px",
  274. refreshBeforeAdd: true,
  275. refreshVariant: "outline",
  276. refreshSize: "icon-md",
  277. });
  278. const selectedProviderTestId = await browser.execute(() => {
  279. const selected = document.querySelector<HTMLElement>(
  280. '[data-testid^="model-provider-nav-item-"][aria-selected="true"]',
  281. );
  282. return selected?.dataset.testid ?? null;
  283. });
  284. if (!selectedProviderTestId) throw new Error("进入设置页后没有选中的 Provider");
  285. await clickTestIdByDom(TID_MODEL_PROVIDER_ADD_PROVIDER_BUTTON, {
  286. timeout: 30000,
  287. timeoutMsg: "添加模型供应商入口没有出现",
  288. });
  289. await $(sel(TID_MODEL_PROVIDER_TEMPLATE_PICKER)).waitForDisplayed({
  290. timeout: 15000,
  291. timeoutMsg: "添加供应商后没有进入 Template 选择页",
  292. });
  293. const templateLayout = await browser.execute((templateItemPrefix) => {
  294. const picker = document.querySelector<HTMLElement>(
  295. '[data-testid="model-provider-template-picker"]',
  296. );
  297. const cards = Array.from(
  298. picker?.querySelectorAll<HTMLElement>(`[data-testid^="${templateItemPrefix}"]`) ?? [],
  299. );
  300. return {
  301. cardHeights: cards.map((card) => Math.round(card.getBoundingClientRect().height)),
  302. columns: picker
  303. ? getComputedStyle(picker.querySelector<HTMLElement>(".grid")!)
  304. .gridTemplateColumns.split(" ")
  305. .filter(Boolean).length
  306. : 0,
  307. hasChevron: cards.every((card) => Boolean(card.querySelector(".lucide-chevron-right"))),
  308. };
  309. }, `${TID_MODEL_PROVIDER_TEMPLATE_ITEM}-`);
  310. expect(templateLayout.cardHeights.every((height) => height >= 64)).toBe(true);
  311. expect(templateLayout.columns).toBe(2);
  312. expect(templateLayout.hasChevron).toBe(true);
  313. expect(
  314. await browser.execute(() =>
  315. Array.from(
  316. document.querySelectorAll(
  317. '[data-provider-template-group="zhipu"] [data-testid^="model-provider-template-item-"]',
  318. ),
  319. ).map((node) => node.getAttribute("data-testid")),
  320. ),
  321. ).toEqual([
  322. "model-provider-template-item-bigmodel-api",
  323. "model-provider-template-item-zai-api",
  324. "model-provider-template-item-bigmodel-standard-api",
  325. "model-provider-template-item-zai-standard-api",
  326. ]);
  327. await clickTestIdByDom(TID_MODEL_PROVIDER_TEMPLATE_BACK_BUTTON);
  328. await browser.waitUntil(
  329. async () =>
  330. !(await $(sel(TID_MODEL_PROVIDER_TEMPLATE_PICKER)).isDisplayed()) &&
  331. (await $(sel(selectedProviderTestId)).getAttribute("aria-selected")) === "true",
  332. {
  333. timeout: 15000,
  334. timeoutMsg: "从 Template 选择页返回后没有恢复原 Provider 详情",
  335. },
  336. );
  337. await clickTestIdByDom(TID_MODEL_PROVIDER_ADD_PROVIDER_BUTTON);
  338. await clickTestIdByDom(testId(TID_MODEL_PROVIDER_TEMPLATE_ITEM, "deepseek"), {
  339. timeout: 15000,
  340. timeoutMsg: "Upstream Built-in Template 入口没有出现",
  341. });
  342. await $(sel("model-provider-actions-button")).waitForDisplayed({
  343. timeout: 15000,
  344. timeoutMsg: "Built-in Template 创建后没有进入供应商详情",
  345. });
  346. await browser.waitUntil(
  347. async () =>
  348. (await $(sel(TID_MODEL_PROVIDER_BASE_URL_INPUT)).getValue()) ===
  349. "https://api.deepseek.com/anthropic",
  350. {
  351. timeout: 30000,
  352. timeoutMsg: "Template Endpoint 没有进入新 Provider 的 Effective Config",
  353. },
  354. );
  355. expect(await $(sel(TID_MODEL_PROVIDER_API_FORMAT_TRIGGER)).getText()).toMatch(
  356. /Anthropic Messages/iu,
  357. );
  358. // Todo113 第二轮官方默认目录已去掉旧 Flash 别名,旧规则兼容另由配置测试覆盖。
  359. expect(await readModelOrder()).toEqual(["deepseek-flash", "deepseek-v4-pro"]);
  360. expect(
  361. await browser.execute((addModelTestId) => {
  362. const addModelButton = document.querySelector<HTMLButtonElement>(
  363. `[data-testid="${addModelTestId}"]`,
  364. );
  365. return {
  366. parentMarginBottom: addModelButton?.parentElement
  367. ? getComputedStyle(addModelButton.parentElement).marginBottom
  368. : null,
  369. size: addModelButton?.dataset.size,
  370. variant: addModelButton?.dataset.variant,
  371. };
  372. }, TID_MODEL_PROVIDER_ADD_MODEL_BUTTON),
  373. ).toEqual({ parentMarginBottom: "4px", size: "default", variant: "secondary" });
  374. expect(
  375. await browser.execute(() => {
  376. const detail = document.querySelector('[data-model-provider-detail-scroll="true"]');
  377. return Array.from(detail?.querySelectorAll<HTMLImageElement>("img") ?? []).some((image) => {
  378. const rect = image.getBoundingClientRect();
  379. return rect.width > 0 && rect.height > 0;
  380. });
  381. }),
  382. ).toBe(true);
  383. await clickTestIdByDom(TID_MODEL_PROVIDER_ADD_PROVIDER_BUTTON);
  384. await clickTestIdByDom(testId(TID_MODEL_PROVIDER_TEMPLATE_ITEM, "custom"), {
  385. timeout: 15000,
  386. timeoutMsg: "自定义供应商 Template 入口没有出现",
  387. });
  388. await $(sel("model-provider-actions-button")).waitForDisplayed({
  389. timeout: 15000,
  390. timeoutMsg: "原子创建后没有进入普通供应商详情卡",
  391. });
  392. await $(sel(TID_MODEL_PROVIDER_BASE_URL_INPUT)).waitForDisplayed();
  393. await $(sel(TID_MODEL_PROVIDER_API_KEY_INPUT)).waitForDisplayed();
  394. await $(sel(TID_MODEL_PROVIDER_ADD_MODEL_BUTTON)).waitForDisplayed();
  395. expect(
  396. await browser.execute(
  397. () => document.querySelector('[data-testid="add-provider-footer"]') === null,
  398. ),
  399. ).toBe(true);
  400. // 先验证创建链路,独立滚动故障不能遮蔽模板/自定义 Provider 的实际结果。
  401. await assertModelProviderPageScroll();
  402. });
  403. it("MP-UI-05: 模型配置页不显示远程配置同步入口", async function () {
  404. this.timeout(60000);
  405. await openModelProviderSettings();
  406. await assertNoRemoteModelProviderSyncAction();
  407. });
  408. it("MP-UI-02: 模型供应商删光模型后仍显示空状态和添加模型入口", async function () {
  409. this.timeout(120000);
  410. await restartIntoWorkspace({
  411. // Bug 根因:运行中的 Host 会在退出阶段回写 provider 文件;先 seed 再重启时,
  412. // 正式 E2E 的退出写回可能覆盖 fixture。必须在进程退出屏障后写入持久态。
  413. afterElectronProcessExit: async () => {
  414. await seedReplayProvider({
  415. apiKey: "e2e-bigmodel-empty-models-token",
  416. id: EMPTY_MODELS_PROVIDER_ID,
  417. models: ["glm-empty-models-e2e"],
  418. name: "Empty Models E2E",
  419. });
  420. },
  421. });
  422. await openModelProviderSettings();
  423. await clickTestIdByDom(
  424. testId(TID_MODEL_PROVIDER_NAV_ITEM, `custom:${EMPTY_MODELS_PROVIDER_ID}`),
  425. {
  426. timeout: 30000,
  427. timeoutMsg: "空模型测试供应商入口没有出现",
  428. },
  429. );
  430. await clickTestIdByDom(testId(TID_MODEL_PROVIDER_MODEL_DELETE_BUTTON, "0"), {
  431. timeout: 15000,
  432. timeoutMsg: "最后一个模型的删除按钮没有出现",
  433. });
  434. const emptyState = await waitForEmptyModelState();
  435. expect(emptyState).toEqual(
  436. expect.objectContaining({
  437. hasDashedBorder: true,
  438. hasInfoIcon: true,
  439. isLeftAligned: true,
  440. isStandardHeight: true,
  441. }),
  442. );
  443. expect(emptyState.text).toMatch(
  444. /当前没有配置模型,添加模型后可在聊天中使用。|No models are configured\. Add a model to use it in chat\./,
  445. );
  446. await $(sel(TID_MODEL_PROVIDER_ADD_MODEL_BUTTON)).waitForDisplayed({
  447. timeout: 15000,
  448. timeoutMsg: "空模型状态没有保留添加模型入口",
  449. });
  450. });
  451. it("MP-UI-03: 模型拖拽保存期间保持乐观顺序且列表边框不重叠", async function () {
  452. this.timeout(120000);
  453. await restartIntoWorkspace({
  454. afterElectronProcessExit: async () => {
  455. await seedReplayProvider({
  456. apiKey: "e2e-reorder-models-token",
  457. id: REORDER_MODELS_PROVIDER_ID,
  458. models: REORDER_MODEL_IDS,
  459. name: "Reorder Models E2E",
  460. });
  461. },
  462. });
  463. await openModelProviderSettings();
  464. await clickTestIdByDom(
  465. testId(TID_MODEL_PROVIDER_NAV_ITEM, `custom:${REORDER_MODELS_PROVIDER_ID}`),
  466. {
  467. timeout: 30000,
  468. timeoutMsg: "调序测试供应商入口没有出现",
  469. },
  470. );
  471. await waitForModelOrder(REORDER_MODEL_IDS);
  472. await beginModelOrderTrace();
  473. await beginModelDragStyleTrace(REORDER_MODEL_IDS[0]);
  474. await dragModel(REORDER_MODEL_IDS[0], REORDER_MODEL_IDS[1]);
  475. const expectedOrder = [REORDER_MODEL_IDS[1], REORDER_MODEL_IDS[0]] as const;
  476. await waitForModelOrder(expectedOrder);
  477. await browser.pause(800);
  478. const trace = await finishModelOrderTrace();
  479. const firstExpectedIndex = trace.findIndex(
  480. (order) => order.join("/") === expectedOrder.join("/"),
  481. );
  482. expect(firstExpectedIndex).toBeGreaterThanOrEqual(0);
  483. expect(
  484. trace
  485. .slice(firstExpectedIndex)
  486. .some((order) => order.join("/") === REORDER_MODEL_IDS.join("/")),
  487. ).toBe(false);
  488. expect(await finishModelDragStyleTrace()).toContainEqual({
  489. hasTransparentBottomBorder: true,
  490. hasVisibleBottomDivider: false,
  491. });
  492. const borderSnapshot = await readModelListBorderSnapshot();
  493. expect(borderSnapshot).toEqual({
  494. containerHasDivide: false,
  495. firstHasBottomBorder: true,
  496. lastHasBottomBorder: false,
  497. modelContentPaddingInline: "12px",
  498. });
  499. });
  500. it("MP-UI-04: 删除供应商后导航与 Personal Config 同时移除", async function () {
  501. this.timeout(120000);
  502. await restartIntoWorkspace({
  503. afterElectronProcessExit: async () => {
  504. await seedReplayProvider({
  505. id: DELETE_PROVIDER_ID,
  506. models: ["e2e-delete-provider-model"],
  507. name: "Delete Provider E2E",
  508. });
  509. },
  510. });
  511. await openModelProviderSettings();
  512. const navTestId = testId(TID_MODEL_PROVIDER_NAV_ITEM, `custom:${DELETE_PROVIDER_ID}`);
  513. await clickTestIdByDom(navTestId, {
  514. timeout: 30000,
  515. timeoutMsg: "删除测试供应商入口没有出现",
  516. });
  517. // Todo115 删除操作已移入菜单,不再查找标题栏的独立垃圾桶。
  518. await clickTestIdByWebDriver("model-provider-actions-button");
  519. const deleteItem = $('[role="menuitem"]:has(svg.lucide-trash-2)');
  520. await deleteItem.waitForDisplayed({ timeout: 15000 });
  521. await deleteItem.click();
  522. await browser.waitUntil(
  523. async () =>
  524. browser.execute(() =>
  525. Array.from(document.querySelectorAll<HTMLButtonElement>("button")).some((button) => {
  526. const rect = button.getBoundingClientRect();
  527. return (
  528. rect.width > 0 &&
  529. rect.height > 0 &&
  530. /确认删除|Delete provider/.test(button.innerText.trim())
  531. );
  532. }),
  533. ),
  534. {
  535. timeout: 15000,
  536. timeoutMsg: "删除供应商确认按钮没有出现",
  537. },
  538. );
  539. await browser.execute(() => {
  540. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  541. (candidate) => {
  542. const rect = candidate.getBoundingClientRect();
  543. return (
  544. rect.width > 0 &&
  545. rect.height > 0 &&
  546. /确认删除|Delete provider/.test(candidate.innerText.trim())
  547. );
  548. },
  549. );
  550. button?.click();
  551. });
  552. await browser.waitUntil(
  553. async () =>
  554. browser.execute(
  555. (targetTestId) => !document.querySelector(`[data-testid="${targetTestId}"]`),
  556. navTestId,
  557. ),
  558. {
  559. timeout: 30000,
  560. timeoutMsg: "删除后供应商仍残留在设置页导航",
  561. },
  562. );
  563. expect(await readModelProvider(DELETE_PROVIDER_ID)).toBeNull();
  564. });
  565. it("MP-UI-06: 推理档位与 Mapping 使用紧凑编辑器并保存 Personal 覆盖", async function () {
  566. this.timeout(120000);
  567. await restartIntoWorkspace({
  568. afterElectronProcessExit: async () => {
  569. await seedReplayProvider({
  570. id: REASONING_EDITOR_PROVIDER_ID,
  571. models: [REASONING_EDITOR_MODEL_ID],
  572. name: "Reasoning Editor E2E",
  573. });
  574. // 本例验证推荐配置的继承编辑;通用 replay 的 disabled 精确覆盖会遮住推荐档位。
  575. const repository = new NodePersonalProviderConfigRepository({
  576. filePath: getE2EAppDataPaths().configFile,
  577. pollingIntervalMs: false,
  578. });
  579. try {
  580. await repository.update((current) => {
  581. const model = current.models.getExactRule(
  582. REASONING_EDITOR_PROVIDER_ID,
  583. REASONING_EDITOR_MODEL_ID,
  584. )!.config;
  585. return {
  586. ...current,
  587. models: current.models.setExact(
  588. REASONING_EDITOR_PROVIDER_ID,
  589. REASONING_EDITOR_MODEL_ID,
  590. new ModelConfig({
  591. ...model,
  592. optionSpecs: new ModelOptionSpecsConfig({
  593. ...model.optionSpecs,
  594. reasoningLevel: undefined,
  595. }),
  596. }),
  597. ),
  598. };
  599. });
  600. } finally {
  601. repository.dispose();
  602. }
  603. },
  604. });
  605. await openModelProviderSettings();
  606. await clickTestIdByDom(
  607. testId(TID_MODEL_PROVIDER_NAV_ITEM, `custom:${REASONING_EDITOR_PROVIDER_ID}`),
  608. {
  609. timeout: 30000,
  610. timeoutMsg: "推理档位测试供应商入口没有出现",
  611. },
  612. );
  613. await openModelMetadataDialog(REASONING_EDITOR_MODEL_ID);
  614. // Todo141 将输入能力和推理配置移到默认收起的高级区;先验证折叠,再由真实点击展开。
  615. const advanced = $('[data-model-advanced-trigger="true"]');
  616. await expect(advanced).toHaveAttribute("aria-expanded", "false");
  617. expect(await $('[data-model-max-output="true"] input').isDisplayed()).toBe(true);
  618. expect(await $('[data-model-reasoning-level-editor="true"]').isDisplayed()).toBe(false);
  619. await advanced.click();
  620. await expect(advanced).toHaveAttribute("aria-expanded", "true");
  621. expect(
  622. await browser.execute(() =>
  623. Array.from(document.querySelectorAll<HTMLElement>("[data-model-settings-group]")).map(
  624. (element) => element.dataset.modelSettingsGroup,
  625. ),
  626. ),
  627. ).toEqual(["basic", "tokens", "tokens", "modalities", "capabilities", "reasoning"]);
  628. expect(
  629. await browser.execute(
  630. () => document.querySelectorAll("[data-model-settings-group] > h3").length,
  631. ),
  632. ).toBe(0);
  633. expect(
  634. await browser.execute(() => {
  635. // Todo125 分组标题包含独立帮助按钮,不能再冒充单字段 label。
  636. const inputLabel = document.querySelector<HTMLElement>(
  637. '[data-model-help="inputModalities"]',
  638. )?.parentElement;
  639. const capabilitiesLabel = document.querySelector<HTMLElement>(
  640. '[data-model-capabilities-label="true"]',
  641. );
  642. return {
  643. capabilitiesLabel: capabilitiesLabel?.textContent?.trim(),
  644. labelSpacingMatches:
  645. Boolean(inputLabel && capabilitiesLabel) &&
  646. getComputedStyle(inputLabel!).marginBottom ===
  647. getComputedStyle(capabilitiesLabel!).marginBottom,
  648. };
  649. }),
  650. ).toMatchObject({
  651. capabilitiesLabel: expect.stringMatching(/^(Model capabilities|模型能力)$/),
  652. labelSpacingMatches: true,
  653. });
  654. expect(
  655. await browser.execute(() => ({
  656. hasIdentityRow: Boolean(document.querySelector('[data-model-identity-row="true"]')),
  657. hasEnabledRow: Boolean(document.querySelector('[data-model-enabled-row="true"]')),
  658. hasLegacyIdentityEnabledLayout: Boolean(
  659. document.querySelector('[data-model-identity-enabled-layout="true"]'),
  660. ),
  661. })),
  662. ).toEqual({
  663. hasIdentityRow: true,
  664. hasEnabledRow: false,
  665. hasLegacyIdentityEnabledLayout: false,
  666. });
  667. expect(
  668. await browser.execute(() => {
  669. const options = Array.from(
  670. document.querySelectorAll<HTMLElement>('[data-model-capability-option="true"]'),
  671. );
  672. return {
  673. count: options.length,
  674. iconCount: document.querySelectorAll('[data-model-capability-icon="true"]').length,
  675. structuredOutputUsesLayers: Boolean(options[0]?.querySelector("svg.lucide-layers")),
  676. checkboxCount: options.reduce(
  677. (count, option) =>
  678. count + option.querySelectorAll('[data-model-option-checkbox="true"]').length,
  679. 0,
  680. ),
  681. roles: options.map((option) => option.getAttribute("role")),
  682. states: options.map((option) => option.getAttribute("aria-checked")),
  683. personalOverrides: options.map((option) => option.dataset.personalOverride),
  684. };
  685. }),
  686. ).toEqual({
  687. count: 3,
  688. iconCount: 0,
  689. structuredOutputUsesLayers: false,
  690. checkboxCount: 3,
  691. roles: ["checkbox", "checkbox", "checkbox"],
  692. states: ["false", "false", "false"],
  693. personalOverrides: ["true", "true", "true"],
  694. });
  695. expect(
  696. await browser.execute(() => {
  697. const footer = document.querySelector<HTMLElement>('[data-model-settings-footer="true"]');
  698. const buttons = Array.from(footer?.querySelectorAll<HTMLButtonElement>("button") ?? []);
  699. const saveButton = buttons.find((button) => /^(Save|保存)$/u.test(button.innerText.trim()));
  700. const cancelButton = buttons.find((button) =>
  701. /^(Cancel|取消)$/u.test(button.innerText.trim()),
  702. );
  703. return {
  704. cancelSize: cancelButton?.dataset.size,
  705. cancelVariant: cancelButton?.dataset.variant,
  706. saveBeforeCancel: Boolean(
  707. saveButton &&
  708. cancelButton &&
  709. saveButton.compareDocumentPosition(cancelButton) & Node.DOCUMENT_POSITION_FOLLOWING,
  710. ),
  711. saveSize: saveButton?.dataset.size,
  712. saveVariant: saveButton?.dataset.variant,
  713. };
  714. }),
  715. ).toEqual({
  716. cancelSize: "lg",
  717. cancelVariant: "ghost",
  718. saveBeforeCancel: false,
  719. saveSize: "lg",
  720. saveVariant: "default",
  721. });
  722. expect(
  723. await browser.execute(() => ({
  724. advancedGroupExists: Boolean(document.querySelector('[data-model-advanced="true"]')),
  725. advancedTriggerExists: Boolean(
  726. document.querySelector('[data-model-advanced-trigger="true"]'),
  727. ),
  728. reasoningHasLevelsAndMapping: Boolean(
  729. document.querySelector(
  730. '[data-model-settings-group="reasoning"] [data-model-reasoning-level-editor="true"]',
  731. ) &&
  732. document.querySelector(
  733. '[data-model-settings-group="reasoning"] [data-model-reasoning-level-map-editor="true"]',
  734. ),
  735. ),
  736. })),
  737. ).toEqual({
  738. advancedGroupExists: true,
  739. advancedTriggerExists: true,
  740. reasoningHasLevelsAndMapping: true,
  741. });
  742. expect(await $('[data-model-reasoning-level-editor="true"]').isDisplayed()).toBe(true);
  743. expect(await $('[data-model-input-modality="text"]').getAttribute("aria-pressed")).toBe("true");
  744. expect(await $('[data-model-input-modality="image"]').getAttribute("aria-pressed")).toBe(
  745. "false",
  746. );
  747. expect(
  748. await browser.execute(
  749. () => document.querySelectorAll('[data-model-modality-lock="true"]').length,
  750. ),
  751. ).toBe(1);
  752. await setRendererViewport(390, 844);
  753. try {
  754. for (const presentation of [
  755. { locale: "zh-CN", theme: "dark" },
  756. { locale: "en-US", theme: "light" },
  757. ]) {
  758. await setPresentation(presentation);
  759. await verifyModelEditorFocusFeedback();
  760. const geometry = await browser.execute(() => {
  761. const dialog = document.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;
  762. const heading = dialog.querySelector<HTMLElement>('[data-slot="dialog-header"]')!;
  763. const scroller = dialog.querySelector<HTMLElement>("[data-model-settings-scroll]")!;
  764. const bounds = dialog.getBoundingClientRect();
  765. return {
  766. titleVisible: heading.getBoundingClientRect().top >= bounds.top,
  767. scrollTop: dialog.scrollTop,
  768. clientHeight: dialog.clientHeight,
  769. scrollHeight: dialog.scrollHeight,
  770. gridRows: getComputedStyle(dialog).gridTemplateRows,
  771. scrollerClient: scroller.clientHeight,
  772. scrollerScroll: scroller.scrollHeight,
  773. };
  774. });
  775. expect(geometry).toMatchObject({ titleVisible: true, scrollTop: 0 });
  776. const screenshotDir = join(process.cwd(), ".e2e-artifacts", "todo90-92");
  777. await mkdir(screenshotDir, { recursive: true });
  778. await browser.saveScreenshot(
  779. join(screenshotDir, `model-editor-${presentation.theme}-390.png`),
  780. );
  781. expect(
  782. await browser.execute(() => {
  783. const footer = document.querySelector<HTMLElement>(
  784. '[data-model-settings-footer="true"]',
  785. );
  786. const groups = Array.from(
  787. document.querySelectorAll<HTMLElement>("[data-model-settings-group]"),
  788. );
  789. const fit = (element: HTMLElement) => {
  790. const rect = element.getBoundingClientRect();
  791. return rect.width > 0 && rect.left >= 0 && rect.right <= window.innerWidth;
  792. };
  793. return Boolean(footer && fit(footer) && groups.length === 6 && groups.every(fit));
  794. }),
  795. ).toBe(true);
  796. }
  797. expect(
  798. await browser.execute(() => {
  799. const dialog = document.querySelector<HTMLElement>('[data-slot="dialog-content"]');
  800. const scroller = document.querySelector<HTMLElement>(
  801. '[data-model-settings-scroll="true"]',
  802. );
  803. const firstGroup = document.querySelector<HTMLElement>("[data-model-settings-group]");
  804. if (!dialog || !scroller || !firstGroup) return null;
  805. const dialogRect = dialog.getBoundingClientRect();
  806. const scrollerRect = scroller.getBoundingClientRect();
  807. const groupRect = firstGroup.getBoundingClientRect();
  808. // 系统滚动条可能占 15px。用 client 右沿检查应用留白,避免把滚动条算成 padding。
  809. const clientRight = scrollerRect.left + scroller.clientLeft + scroller.clientWidth;
  810. return {
  811. scrollbarOuterInset: Math.round(dialogRect.right - scrollerRect.right),
  812. scrollbarGutter: Math.round(clientRight - groupRect.right),
  813. };
  814. }),
  815. ).toEqual({
  816. scrollbarOuterInset: 5,
  817. scrollbarGutter: 16,
  818. });
  819. expect(
  820. await browser.execute(() => {
  821. const groups = Array.from(
  822. document.querySelectorAll<HTMLElement>("[data-model-settings-group]"),
  823. );
  824. const booleanOptions = Array.from(
  825. document.querySelectorAll<HTMLElement>('[data-model-boolean-option="true"]'),
  826. );
  827. const modalityOptions = Array.from(
  828. document.querySelectorAll<HTMLElement>(
  829. "[data-model-input-modality], [data-model-output-modality]",
  830. ),
  831. );
  832. const identityRow = document.querySelector<HTMLElement>(
  833. '[data-model-identity-row="true"]',
  834. );
  835. const enabledRow = document.querySelector<HTMLElement>('[data-model-enabled-row="true"]');
  836. const fitsViewport = (element: HTMLElement) => {
  837. const rect = element.getBoundingClientRect();
  838. return rect.left >= 0 && rect.right <= window.innerWidth;
  839. };
  840. return (
  841. window.innerWidth === 390 &&
  842. groups.every(fitsViewport) &&
  843. booleanOptions.every(fitsViewport) &&
  844. modalityOptions.every(fitsViewport) &&
  845. Boolean(identityRow && !enabledRow) &&
  846. fitsViewport(identityRow!) &&
  847. !enabledRow
  848. );
  849. }),
  850. ).toBe(true);
  851. } finally {
  852. await clearRendererViewport();
  853. await setPresentation({ locale: "zh-CN", theme: "dark" });
  854. }
  855. await browser.waitUntil(
  856. async () => (await readReasoningLevelValues()).join("/") === "low/high/max",
  857. {
  858. timeout: 15000,
  859. timeoutMsg: "模型配置没有展示有序推理档位标签",
  860. },
  861. );
  862. const reasoningLevelTypographyBeforeEdit = await browser.execute(() => {
  863. const editor = document.querySelector<HTMLElement>(
  864. '[data-model-reasoning-level-editor="true"]',
  865. );
  866. const chip = editor?.querySelector<HTMLButtonElement>("div > button:first-of-type");
  867. const addButton = editor?.querySelector<HTMLButtonElement>(
  868. '[data-model-reasoning-level-add="true"]',
  869. );
  870. if (!chip || !addButton) return null;
  871. const chipStyle = getComputedStyle(chip);
  872. const chipHeight = chip.parentElement?.getBoundingClientRect().height ?? 0;
  873. return {
  874. addButtonHeight: Math.round(addButton.getBoundingClientRect().height),
  875. addButtonWidth: Math.round(addButton.getBoundingClientRect().width),
  876. addButtonVariant: addButton.dataset.variant,
  877. chipFontFamily: chipStyle.fontFamily,
  878. chipFontSize: chipStyle.fontSize,
  879. chipHeight: Math.round(chipHeight),
  880. };
  881. });
  882. expect(reasoningLevelTypographyBeforeEdit).not.toBeNull();
  883. const firstReasoningLevel = $(
  884. '[data-model-reasoning-level-editor="true"] > div > button:first-of-type',
  885. );
  886. await firstReasoningLevel.click();
  887. const reasoningLevelInput = $('input[data-model-reasoning-level-input="true"]');
  888. await reasoningLevelInput.waitForDisplayed({
  889. timeout: 10000,
  890. timeoutMsg: "点击推理档位后没有进入编辑态",
  891. });
  892. const reasoningLevelTypographyAfterEdit = await browser.execute(() => {
  893. const editor = document.querySelector<HTMLElement>(
  894. '[data-model-reasoning-level-editor="true"]',
  895. );
  896. const input = editor?.querySelector<HTMLInputElement>(
  897. 'input[data-model-reasoning-level-input="true"]',
  898. );
  899. if (!input) return null;
  900. const inputStyle = getComputedStyle(input);
  901. return {
  902. inputFontFamily: inputStyle.fontFamily,
  903. inputFontSize: inputStyle.fontSize,
  904. inputHeight: Math.round(input.getBoundingClientRect().height),
  905. };
  906. });
  907. expect(reasoningLevelTypographyAfterEdit).not.toBeNull();
  908. expect(reasoningLevelTypographyBeforeEdit?.addButtonVariant).toBe("outline");
  909. expect(reasoningLevelTypographyBeforeEdit?.addButtonHeight).toBe(
  910. reasoningLevelTypographyBeforeEdit?.chipHeight,
  911. );
  912. expect(reasoningLevelTypographyBeforeEdit?.addButtonWidth).toBe(
  913. reasoningLevelTypographyBeforeEdit?.chipHeight,
  914. );
  915. expect(reasoningLevelTypographyAfterEdit?.inputHeight).toBe(
  916. reasoningLevelTypographyBeforeEdit?.chipHeight,
  917. );
  918. expect(reasoningLevelTypographyAfterEdit?.inputFontSize).toBe(
  919. reasoningLevelTypographyBeforeEdit?.chipFontSize,
  920. );
  921. expect(reasoningLevelTypographyAfterEdit?.inputFontFamily).toBe(
  922. reasoningLevelTypographyBeforeEdit?.chipFontFamily,
  923. );
  924. await browser.execute(() => {
  925. document
  926. .querySelector<HTMLInputElement>('input[data-model-reasoning-level-input="true"]')
  927. ?.blur();
  928. });
  929. await browser.waitUntil(async () => !(await reasoningLevelInput.isExisting()), {
  930. timeout: 10000,
  931. timeoutMsg: "推理档位输入框失焦后没有退出编辑态",
  932. });
  933. expect(
  934. await browser.execute(
  935. () =>
  936. document.querySelector('[data-model-reasoning-level-editor="true"] textarea') === null,
  937. ),
  938. ).toBe(true);
  939. const reasoningMapEditor = $('[data-model-reasoning-level-map-editor="true"] textarea');
  940. await reasoningMapEditor.waitForDisplayed({
  941. timeout: 15000,
  942. timeoutMsg: "推理参数 Mapping JSON 编辑框没有出现",
  943. });
  944. // 继承配置只作为 placeholder 展示;空 value 表示尚未写入 Personal Overlay。
  945. expect(await reasoningMapEditor.getValue()).toBe("");
  946. expect((await reasoningMapEditor.getAttribute("placeholder"))?.trim()).not.toBe("");
  947. const personalReasoningMapInput = '{"reasoning_effort": reasoningLevel}';
  948. // Todo98 保留用户 Map 原文,不再压成单行或删除表达式中的空格。
  949. await reasoningMapEditor.setValue(personalReasoningMapInput);
  950. await browser.execute(() => {
  951. const first = document.querySelector<HTMLButtonElement>(
  952. '[data-model-reasoning-level-editor="true"] > div > button:first-of-type',
  953. );
  954. first?.dispatchEvent(
  955. new KeyboardEvent("keydown", { altKey: true, bubbles: true, key: "ArrowRight" }),
  956. );
  957. });
  958. await browser.waitUntil(
  959. async () => (await readReasoningLevelValues()).join("/") === "high/low/max",
  960. {
  961. timeout: 10000,
  962. timeoutMsg: "键盘调整推理档位顺序没有立即反映到草稿",
  963. },
  964. );
  965. expect(
  966. await browser.execute(() => {
  967. const chips = [
  968. ...document.querySelectorAll<HTMLElement>('[data-model-reasoning-chip="true"]'),
  969. ];
  970. const map = document.querySelector<HTMLElement>(
  971. '[data-model-reasoning-level-map-editor="true"] textarea',
  972. );
  973. const group = document.querySelector<HTMLElement>(
  974. '[data-model-settings-group="reasoning"]',
  975. );
  976. const capability = document.querySelector<HTMLElement>(
  977. '[data-model-settings-group="capabilities"] [role="checkbox"]',
  978. );
  979. return {
  980. chips: chips.map((chip) => chip.dataset.personalOverride),
  981. map: map?.dataset.personalOverride,
  982. outerHighlighted: group?.className.includes("border-primary") ?? false,
  983. capabilityCheckboxes: capability?.querySelectorAll("[data-model-option-checkbox]").length,
  984. };
  985. }),
  986. ).toEqual({
  987. chips: ["true", "true", "true"],
  988. map: "true",
  989. outerHighlighted: false,
  990. capabilityCheckboxes: 1,
  991. });
  992. await clickVisibleButton(/保存|Save/);
  993. // 修复原因:Dialog 有关闭动画。若立即用 DOM click 重开,会穿透尚未卸载的遮罩层,
  994. // wait 条件又会误把旧 Dialog 当成新 Dialog,随后只能持续读到空档位。
  995. await browser.waitUntil(
  996. async () =>
  997. browser.execute(
  998. () => document.querySelector('[data-model-reasoning-level-editor="true"]') === null,
  999. ),
  1000. { timeout: 15000, timeoutMsg: "模型配置保存后弹窗没有关闭" },
  1001. );
  1002. await browser.waitUntil(
  1003. async () =>
  1004. browser.execute(() =>
  1005. Boolean(document.querySelector('[data-provider-detail-feedback-state="success"]')),
  1006. ),
  1007. { timeout: 15000, timeoutMsg: "模型配置保存后没有展示成功反馈" },
  1008. );
  1009. await assertLongProviderFeedbackVisible();
  1010. expect(
  1011. await browser.execute(() => {
  1012. const feedback = document.querySelector<HTMLElement>(
  1013. '[data-provider-detail-feedback-state="success"]',
  1014. );
  1015. const viewport = document.querySelector<HTMLElement>(
  1016. '[data-testid="provider-detail-feedback-viewport"]',
  1017. );
  1018. const icon = feedback?.querySelector<HTMLElement>("svg");
  1019. if (!feedback || !viewport || !icon) return null;
  1020. return {
  1021. matchesLoadingWidth:
  1022. Math.abs(
  1023. feedback.getBoundingClientRect().width - viewport.getBoundingClientRect().width,
  1024. ) <= 1,
  1025. usesXlRadius: feedback.classList.contains("rounded-xl"),
  1026. iconUsesSuccess: icon.classList.contains("text-success"),
  1027. neutralSurface:
  1028. feedback.classList.contains("border-border") &&
  1029. feedback.classList.contains("bg-popover/95") &&
  1030. feedback.classList.contains("text-foreground"),
  1031. };
  1032. }),
  1033. ).toEqual({
  1034. matchesLoadingWidth: true,
  1035. usesXlRadius: true,
  1036. iconUsesSuccess: true,
  1037. neutralSurface: true,
  1038. });
  1039. await openModelMetadataDialog(REASONING_EDITOR_MODEL_ID, true);
  1040. await browser.waitUntil(
  1041. async () => (await readReasoningLevelValues()).join("/") === "high/low/max",
  1042. {
  1043. timeout: 30000,
  1044. timeoutMsg: "推理档位顺序保存后没有保持",
  1045. },
  1046. );
  1047. expect(await $('[data-model-reasoning-level-map-editor="true"] textarea').getValue()).toBe(
  1048. personalReasoningMapInput,
  1049. );
  1050. const followSwitch = '[data-model-recommended-config="true"] [role="switch"]';
  1051. expect(await $(followSwitch).getAttribute("aria-checked")).toBe("true");
  1052. await $(followSwitch).click();
  1053. expect(await $(followSwitch).getAttribute("aria-checked")).toBe("false");
  1054. await closeAndReopenModelEditor("cancel");
  1055. expect(await $(followSwitch).getAttribute("aria-checked")).toBe("true");
  1056. expect(await $('[data-model-reasoning-level-map-editor="true"] textarea').getValue()).toBe(
  1057. personalReasoningMapInput,
  1058. );
  1059. await $(followSwitch).click();
  1060. await closeAndReopenModelEditor("save");
  1061. expect(await $(followSwitch).getAttribute("aria-checked")).toBe("false");
  1062. expect(await $('[data-model-reasoning-level-map-editor="true"] textarea').getValue()).toBe(
  1063. personalReasoningMapInput,
  1064. );
  1065. await $(followSwitch).click();
  1066. expect(await $('[data-model-reasoning-level-map-editor="true"] textarea').getValue()).toBe("");
  1067. const editedAfterReset = '{"output_config":{"effort":reasoningLevel}}';
  1068. await $('[data-model-reasoning-level-map-editor="true"] textarea').setValue(editedAfterReset);
  1069. await closeAndReopenModelEditor("save");
  1070. expect(await $(followSwitch).getAttribute("aria-checked")).toBe("true");
  1071. expect(await $('[data-model-reasoning-level-map-editor="true"] textarea').getValue()).toBe(
  1072. editedAfterReset,
  1073. );
  1074. // 能力由真实表单保存,随后验证两个消费入口;不直接改 DOM 或注入徽标。
  1075. // 切回推荐配置会恢复当前 Built-in 能力;按真实状态开启视觉,不能无条件反转成关闭。
  1076. const imageInput = $('[data-model-input-modality="image"]');
  1077. if ((await imageInput.getAttribute("aria-pressed")) !== "true") await imageInput.click();
  1078. await expect(imageInput).toHaveAttribute("aria-pressed", "true");
  1079. await clickVisibleButton(/保存|Save/);
  1080. await $('[data-model-settings-scroll="true"]').waitForExist({ reverse: true });
  1081. for (const presentation of [
  1082. { locale: "zh-CN", theme: "dark" },
  1083. { locale: "en-US", theme: "light" },
  1084. ]) {
  1085. await setPresentation(presentation);
  1086. const badge = $(
  1087. `[data-model-provider-model-id="${REASONING_EDITOR_MODEL_ID}"] [data-model-input-capability="vision"]`,
  1088. );
  1089. await badge.waitForDisplayed();
  1090. expect(await badge.getText()).toMatch(/视觉|Vision/);
  1091. }
  1092. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  1093. await clickTestIdByWebDriver(TID_CHAT_MODEL_SELECT_TRIGGER);
  1094. // 合并模型菜单先打开 Provider 分组,再进入具体模型列表。
  1095. await $('[data-testid="composer-provider-trigger"]').click();
  1096. await $(
  1097. sel(testId(TID_CHAT_MODEL_SELECT_GROUP, `registry-provider:${REASONING_EDITOR_PROVIDER_ID}`)),
  1098. ).click();
  1099. const modelItem = $(
  1100. sel(
  1101. testId(
  1102. TID_CHAT_MODEL_SELECT_ITEM,
  1103. encodeCustomModelValue(REASONING_EDITOR_PROVIDER_ID, REASONING_EDITOR_MODEL_ID),
  1104. ),
  1105. ),
  1106. );
  1107. try {
  1108. await modelItem.waitForDisplayed();
  1109. } catch (error) {
  1110. const menu = await browser.execute(() =>
  1111. Array.from(
  1112. document.querySelectorAll<HTMLElement>(
  1113. '[role="menu"], [role="listbox"], [data-testid^="chat-model-select"]',
  1114. ),
  1115. ).map((element) => ({ id: element.dataset.testid, text: element.innerText })),
  1116. );
  1117. throw new Error(`视觉模型候选未显示:${JSON.stringify(menu)}`, { cause: error });
  1118. }
  1119. expect(await modelItem.$('[data-model-input-capability="vision"]').isDisplayed()).toBe(true);
  1120. });
  1121. });
  1122. async function verifyModelEditorFocusFeedback(): Promise<void> {
  1123. if (!(await browser.execute(() => matchMedia("(hover: hover)").matches))) {
  1124. throw new Error("MP-UI-06 需要支持悬停的桌面指针,当前 renderer 未启用 hover 媒体查询");
  1125. }
  1126. const selector = '[data-model-settings-group="capabilities"] [role="checkbox"]';
  1127. const button = $(selector);
  1128. await button.scrollIntoView();
  1129. const outside = $('[data-model-settings-footer="true"] button');
  1130. await outside.moveTo();
  1131. await browser.execute((target) => document.querySelector<HTMLElement>(target)?.blur(), selector);
  1132. const readStyle = () =>
  1133. browser.executeAsync(
  1134. (target, done: (style: { background: string; border: string }) => void) => {
  1135. const element = document.querySelector<HTMLElement>(target)!;
  1136. // Bug 原因:Hover 中途的 alpha=0.047 被当成最终颜色,随后与焦点最终的
  1137. // alpha=0.05 比较必然超时。只等待此控件的动画完成,不修改产品样式或固定 sleep。
  1138. void Promise.allSettled(
  1139. element.getAnimations().map((animation) => animation.finished),
  1140. ).then(() => {
  1141. const css = getComputedStyle(element);
  1142. done({ background: css.backgroundColor, border: css.borderColor });
  1143. });
  1144. },
  1145. selector,
  1146. );
  1147. const normal = await readStyle();
  1148. await button.moveTo();
  1149. await browser.waitUntil(async () => (await readStyle()).background !== normal.background, {
  1150. timeoutMsg: "模型能力按钮悬停后没有显示背景反馈",
  1151. });
  1152. const hovered = await readStyle();
  1153. await outside.moveTo();
  1154. await browser.keys("Tab");
  1155. await browser.execute((target) => document.querySelector<HTMLElement>(target)?.focus(), selector);
  1156. await browser.waitUntil(async () => (await readStyle()).background === hovered.background);
  1157. expect((await readStyle()).border).toBe(normal.border);
  1158. // 鼠标已经移走,键盘焦点仍有同一底色;不能用取消 ring 让 Tab 焦点消失。
  1159. expect(
  1160. await browser.execute(
  1161. (target) => document.querySelector(target) === document.activeElement,
  1162. selector,
  1163. ),
  1164. ).toBe(true);
  1165. await outside.moveTo();
  1166. await browser.execute((target) => document.querySelector<HTMLElement>(target)?.blur(), selector);
  1167. await browser.waitUntil(async () => (await readStyle()).background === normal.background);
  1168. }
  1169. async function setPresentation(input: { locale: string; theme: string }): Promise<void> {
  1170. const error = await browser.executeAsync((next, done: (error?: string) => void) => {
  1171. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  1172. .__testActions;
  1173. if (typeof actions?.setLocale !== "function" || typeof actions?.setTheme !== "function")
  1174. return done("missing presentation test actions");
  1175. (actions.setLocale as (value: string) => void)(next.locale);
  1176. (actions.setTheme as (value: string) => void)(next.theme);
  1177. requestAnimationFrame(() => requestAnimationFrame(() => done()));
  1178. }, input);
  1179. if (error) throw new Error(error);
  1180. }
  1181. async function readModelOrder(): Promise<string[]> {
  1182. return browser.execute(() =>
  1183. Array.from(document.querySelectorAll<HTMLElement>("[data-model-provider-model-id]")).map(
  1184. (element) => element.dataset.modelProviderModelId ?? "",
  1185. ),
  1186. );
  1187. }
  1188. async function openModelMetadataDialog(modelId: string, expandAdvanced = false) {
  1189. const clicked = await browser.execute((targetModelId) => {
  1190. const row = document.querySelector<HTMLElement>(
  1191. `[data-model-provider-model-id="${CSS.escape(targetModelId)}"]`,
  1192. );
  1193. const button = Array.from(row?.querySelectorAll<HTMLButtonElement>("button") ?? []).find(
  1194. (candidate) => candidate.querySelector("svg.lucide-pencil") !== null,
  1195. );
  1196. button?.click();
  1197. return Boolean(button);
  1198. }, modelId);
  1199. if (!clicked) throw new Error(`模型编辑按钮不存在:${modelId}`);
  1200. await browser.waitUntil(
  1201. async () =>
  1202. browser.execute(
  1203. () => document.querySelector('[data-model-reasoning-level-editor="true"]') !== null,
  1204. ),
  1205. { timeout: 15000, timeoutMsg: "模型配置弹窗没有出现" },
  1206. );
  1207. if (expandAdvanced) await $('[data-model-advanced-trigger="true"]').click();
  1208. }
  1209. async function readReasoningLevelValues(): Promise<string[]> {
  1210. return browser.execute(() =>
  1211. Array.from(
  1212. document.querySelectorAll<HTMLButtonElement>(
  1213. '[data-model-reasoning-level-editor="true"] > div > button:first-of-type',
  1214. ),
  1215. ).map((button) => button.innerText.trim()),
  1216. );
  1217. }
  1218. async function closeAndReopenModelEditor(action: "save" | "cancel") {
  1219. await clickVisibleButton(action === "save" ? /^(保存|Save)$/u : /^(取消|Cancel)$/u);
  1220. await browser.waitUntil(
  1221. async () => !(await $('[data-model-reasoning-level-editor="true"]').isExisting()),
  1222. { timeout: 15000, timeoutMsg: "模型编辑弹窗没有关闭" },
  1223. );
  1224. await openModelMetadataDialog(REASONING_EDITOR_MODEL_ID, true);
  1225. }
  1226. async function clickVisibleButton(label: RegExp) {
  1227. const clicked = await browser.execute(
  1228. (source, flags) => {
  1229. const matcher = new RegExp(source, flags);
  1230. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  1231. (candidate) => {
  1232. const rect = candidate.getBoundingClientRect();
  1233. return rect.width > 0 && rect.height > 0 && matcher.test(candidate.innerText.trim());
  1234. },
  1235. );
  1236. button?.click();
  1237. return Boolean(button);
  1238. },
  1239. label.source,
  1240. label.flags,
  1241. );
  1242. if (!clicked) throw new Error(`没有找到按钮:${label}`);
  1243. }
  1244. async function waitForModelOrder(expected: readonly string[]) {
  1245. await browser.waitUntil(async () => (await readModelOrder()).join("/") === expected.join("/"), {
  1246. timeout: 30000,
  1247. timeoutMsg: `模型顺序没有收敛到 ${expected.join("/")}`,
  1248. });
  1249. }
  1250. async function beginModelOrderTrace() {
  1251. await browser.execute(() => {
  1252. const windowWithTrace = window as Window & {
  1253. __e2eModelOrderTrace?: string[][];
  1254. __e2eModelOrderObserver?: MutationObserver;
  1255. };
  1256. const readOrder = () =>
  1257. Array.from(document.querySelectorAll<HTMLElement>("[data-model-provider-model-id]")).map(
  1258. (element) => element.dataset.modelProviderModelId ?? "",
  1259. );
  1260. const record = () => {
  1261. const trace = (windowWithTrace.__e2eModelOrderTrace ??= []);
  1262. const order = readOrder();
  1263. if (trace.at(-1)?.join("/") !== order.join("/")) trace.push(order);
  1264. };
  1265. windowWithTrace.__e2eModelOrderTrace = [];
  1266. windowWithTrace.__e2eModelOrderObserver?.disconnect();
  1267. windowWithTrace.__e2eModelOrderObserver = new MutationObserver(record);
  1268. windowWithTrace.__e2eModelOrderObserver.observe(document.body, {
  1269. childList: true,
  1270. subtree: true,
  1271. });
  1272. record();
  1273. });
  1274. }
  1275. async function finishModelOrderTrace(): Promise<string[][]> {
  1276. return browser.execute(() => {
  1277. const windowWithTrace = window as Window & {
  1278. __e2eModelOrderTrace?: string[][];
  1279. __e2eModelOrderObserver?: MutationObserver;
  1280. };
  1281. windowWithTrace.__e2eModelOrderObserver?.disconnect();
  1282. return windowWithTrace.__e2eModelOrderTrace ?? [];
  1283. });
  1284. }
  1285. async function beginModelDragStyleTrace(modelId: string) {
  1286. await browser.execute((targetModelId) => {
  1287. const windowWithTrace = window as Window & {
  1288. __e2eModelDragStyleTrace?: Array<{
  1289. hasTransparentBottomBorder: boolean;
  1290. hasVisibleBottomDivider: boolean;
  1291. }>;
  1292. __e2eModelDragStyleObserver?: MutationObserver;
  1293. };
  1294. const row = document.querySelector<HTMLElement>(
  1295. `[data-model-provider-model-id="${CSS.escape(targetModelId)}"]`,
  1296. );
  1297. windowWithTrace.__e2eModelDragStyleTrace = [];
  1298. windowWithTrace.__e2eModelDragStyleObserver?.disconnect();
  1299. if (!row) return;
  1300. windowWithTrace.__e2eModelDragStyleObserver = new MutationObserver(() => {
  1301. if (!row.classList.contains("z-10")) return;
  1302. windowWithTrace.__e2eModelDragStyleTrace?.push({
  1303. hasTransparentBottomBorder: row.classList.contains("border-transparent"),
  1304. hasVisibleBottomDivider: row.classList.contains("border-input-border"),
  1305. });
  1306. });
  1307. windowWithTrace.__e2eModelDragStyleObserver.observe(row, {
  1308. attributes: true,
  1309. attributeFilter: ["class"],
  1310. });
  1311. }, modelId);
  1312. }
  1313. async function finishModelDragStyleTrace() {
  1314. return browser.execute(() => {
  1315. const windowWithTrace = window as Window & {
  1316. __e2eModelDragStyleTrace?: Array<{
  1317. hasTransparentBottomBorder: boolean;
  1318. hasVisibleBottomDivider: boolean;
  1319. }>;
  1320. __e2eModelDragStyleObserver?: MutationObserver;
  1321. };
  1322. windowWithTrace.__e2eModelDragStyleObserver?.disconnect();
  1323. return windowWithTrace.__e2eModelDragStyleTrace ?? [];
  1324. });
  1325. }
  1326. async function dragModel(sourceModelId: string, targetModelId: string) {
  1327. const positions = await browser.execute(
  1328. (sourceId, targetId) => {
  1329. const source = document.querySelector<HTMLElement>(
  1330. `[data-model-provider-model-id="${CSS.escape(sourceId)}"]`,
  1331. );
  1332. const target = document.querySelector<HTMLElement>(
  1333. `[data-model-provider-model-id="${CSS.escape(targetId)}"]`,
  1334. );
  1335. if (!source || !target) return null;
  1336. const sourceRect = source.getBoundingClientRect();
  1337. const targetRect = target.getBoundingClientRect();
  1338. return {
  1339. startX: Math.round(sourceRect.left + sourceRect.width / 2),
  1340. startY: Math.round(sourceRect.top + sourceRect.height / 2),
  1341. endX: Math.round(targetRect.left + targetRect.width / 2),
  1342. endY: Math.round(targetRect.bottom - 4),
  1343. };
  1344. },
  1345. sourceModelId,
  1346. targetModelId,
  1347. );
  1348. if (!positions) throw new Error("模型拖拽元素不存在");
  1349. await browser.performActions([
  1350. {
  1351. id: "model-reorder-pointer",
  1352. type: "pointer",
  1353. parameters: { pointerType: "mouse" },
  1354. actions: [
  1355. { type: "pointerMove", duration: 0, x: positions.startX, y: positions.startY },
  1356. { type: "pointerDown", button: 0 },
  1357. { type: "pause", duration: 80 },
  1358. {
  1359. type: "pointerMove",
  1360. duration: 120,
  1361. x: positions.startX,
  1362. y: positions.startY + 10,
  1363. },
  1364. {
  1365. type: "pointerMove",
  1366. duration: 260,
  1367. x: positions.endX,
  1368. y: positions.endY,
  1369. },
  1370. { type: "pointerUp", button: 0 },
  1371. ],
  1372. },
  1373. ]);
  1374. await browser.releaseActions();
  1375. }
  1376. async function readModelListBorderSnapshot() {
  1377. return browser.execute(() => {
  1378. const rows = Array.from(
  1379. document.querySelectorAll<HTMLElement>("[data-model-provider-model-id]"),
  1380. );
  1381. const container = rows[0]?.parentElement;
  1382. return {
  1383. containerHasDivide: container?.className.includes("divide-y") ?? false,
  1384. firstHasBottomBorder: rows[0]?.classList.contains("border-b") ?? false,
  1385. lastHasBottomBorder: rows.at(-1)?.classList.contains("border-b") ?? false,
  1386. modelContentPaddingInline: rows[0]?.firstElementChild
  1387. ? getComputedStyle(rows[0].firstElementChild).paddingInlineStart
  1388. : null,
  1389. };
  1390. });
  1391. }
  1392. async function clickVisibleTestId(
  1393. currentTestId: string,
  1394. options: {
  1395. timeout?: number;
  1396. timeoutMsg?: string;
  1397. } = {},
  1398. ) {
  1399. const timeout = options.timeout ?? 10000;
  1400. await browser.waitUntil(
  1401. async () => {
  1402. return browser.execute((targetTestId) => {
  1403. const target = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  1404. (candidate) => {
  1405. const rect = candidate.getBoundingClientRect();
  1406. return candidate.dataset.testid === targetTestId && rect.width > 0 && rect.height > 0;
  1407. },
  1408. );
  1409. if (!target) return false;
  1410. target.focus();
  1411. for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
  1412. target.dispatchEvent(
  1413. new MouseEvent(type, {
  1414. bubbles: true,
  1415. cancelable: true,
  1416. view: window,
  1417. }),
  1418. );
  1419. }
  1420. return true;
  1421. }, currentTestId);
  1422. },
  1423. { timeout, timeoutMsg: options.timeoutMsg },
  1424. );
  1425. }
  1426. async function waitForEmptyModelState() {
  1427. await browser.waitUntil(async () => (await readEmptyModelStateSnapshot()) !== null, {
  1428. timeout: 30000,
  1429. timeoutMsg: "模型供应商空模型提示没有出现",
  1430. });
  1431. const snapshot = await readEmptyModelStateSnapshot();
  1432. if (!snapshot) {
  1433. throw new Error("Coding Plan 空模型提示等待成功后又消失");
  1434. }
  1435. return snapshot;
  1436. }
  1437. async function readEmptyModelStateSnapshot() {
  1438. return browser.execute(() => {
  1439. // 修复原因:祖先容器的 innerText 也包含空状态文案,必须锁定虚线提示自身,
  1440. // 否则几何/样式断言会误读整个设置页容器。
  1441. const candidate = Array.from(document.querySelectorAll<HTMLElement>("div")).find(
  1442. (element) =>
  1443. element.classList.contains("border-dashed") &&
  1444. /当前没有配置模型|No models are configured/.test(element.innerText.trim()),
  1445. );
  1446. if (!candidate) {
  1447. return null;
  1448. }
  1449. return {
  1450. hasDashedBorder: candidate.classList.contains("border-dashed"),
  1451. hasInfoIcon: candidate.querySelector("svg.lucide-info") !== null,
  1452. isLeftAligned:
  1453. candidate.classList.contains("justify-start") && candidate.classList.contains("text-left"),
  1454. isStandardHeight: candidate.classList.contains("h-12"),
  1455. text: candidate.innerText.trim(),
  1456. } satisfies EmptyModelStateSnapshot;
  1457. });
  1458. }
  1459. interface EmptyModelStateSnapshot {
  1460. hasDashedBorder: boolean;
  1461. hasInfoIcon: boolean;
  1462. isLeftAligned: boolean;
  1463. isStandardHeight: boolean;
  1464. text: string;
  1465. }
  1466. async function setRendererViewport(width: number, height: number) {
  1467. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  1468. deviceScaleFactor: 1,
  1469. height,
  1470. mobile: false,
  1471. width,
  1472. });
  1473. await browser.waitUntil(
  1474. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  1475. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  1476. );
  1477. }
  1478. async function clearRendererViewport() {
  1479. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  1480. }
  1481. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  1482. const sent = await browser.electron.execute(
  1483. async (electron, command, commandParams) => {
  1484. const window = electron.BrowserWindow.getAllWindows().find(
  1485. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  1486. );
  1487. if (!window) return false;
  1488. const devtools = window.webContents.debugger;
  1489. if (!devtools.isAttached()) devtools.attach("1.3");
  1490. await devtools.sendCommand(command, commandParams);
  1491. return true;
  1492. },
  1493. method,
  1494. params,
  1495. );
  1496. expect(sent).toBe(true);
  1497. }
  1498. async function assertModelProviderPageScroll() {
  1499. try {
  1500. for (const width of [1280, 600]) {
  1501. await setRendererViewport(width, 800);
  1502. for (const side of ["navigation", "detail"]) {
  1503. const geometry = await browser.execute((side) => {
  1504. const panel = document.querySelector<HTMLElement>(
  1505. '[data-model-provider-split-panel="true"]',
  1506. )!;
  1507. const nav = panel.querySelector<HTMLElement>(
  1508. '[data-model-provider-navigation-scroll="true"]',
  1509. )!;
  1510. const detail = panel.querySelector<HTMLElement>(
  1511. '[data-model-provider-detail-scroll="true"]',
  1512. )!;
  1513. const main = panel.closest("main")!;
  1514. const probe = document.createElement("div");
  1515. probe.dataset.modelLayoutProbe = "true";
  1516. probe.style.height = "1200px";
  1517. probe.setAttribute("aria-hidden", "true");
  1518. (side === "navigation" ? nav : detail).append(probe);
  1519. main.scrollTop = panel.offsetTop;
  1520. nav.scrollTop = 100;
  1521. detail.scrollTop = 100;
  1522. const rect = panel.getBoundingClientRect();
  1523. const target = (side === "navigation" ? nav : detail).getBoundingClientRect();
  1524. return {
  1525. height: rect.height,
  1526. navHeight: nav.getBoundingClientRect().height,
  1527. detailHeight: detail.getBoundingClientRect().height,
  1528. navScroll: nav.scrollTop,
  1529. detailScroll: detail.scrollTop,
  1530. minHeight: getComputedStyle(panel).minHeight,
  1531. mainScroll: main.scrollTop,
  1532. x: Math.round(target.left + Math.min(target.width / 2, 30)),
  1533. y: Math.round(Math.max(rect.top, main.getBoundingClientRect().top) + 100),
  1534. };
  1535. }, side);
  1536. expect(geometry.minHeight).toBe("576px");
  1537. expect(geometry.height).toBeGreaterThan(1200);
  1538. expect(Math.abs(geometry.navHeight - geometry.detailHeight)).toBeLessThan(1);
  1539. expect(geometry.navScroll).toBe(0);
  1540. expect(geometry.detailScroll).toBe(0);
  1541. await browser.performActions([
  1542. {
  1543. type: "wheel",
  1544. id: "model-page-wheel",
  1545. actions: [
  1546. {
  1547. type: "scroll",
  1548. duration: 200,
  1549. x: geometry.x,
  1550. y: geometry.y,
  1551. deltaX: 0,
  1552. deltaY: 160,
  1553. },
  1554. ],
  1555. },
  1556. ]);
  1557. try {
  1558. await browser.waitUntil(
  1559. async () =>
  1560. browser.execute((before) => {
  1561. const panel = document.querySelector('[data-model-provider-split-panel="true"]')!;
  1562. return panel.closest("main")!.scrollTop > before + 20;
  1563. }, geometry.mainScroll),
  1564. { timeout: 3000, timeoutMsg: "Outer settings page did not scroll" },
  1565. );
  1566. } catch (error) {
  1567. const actual = await browser.execute(({ x, y }) => {
  1568. const panel = document.querySelector('[data-model-provider-split-panel="true"]')!;
  1569. const main = panel.closest("main")!;
  1570. const hit = document.elementFromPoint(x, y);
  1571. return {
  1572. scrollTop: main.scrollTop,
  1573. scrollHeight: main.scrollHeight,
  1574. clientHeight: main.clientHeight,
  1575. probePresent: Boolean(panel.querySelector("[data-model-layout-probe]")),
  1576. hit: hit?.tagName,
  1577. hitClass: hit?.className,
  1578. hitInsideMain: Boolean(hit && main.contains(hit)),
  1579. };
  1580. }, geometry);
  1581. throw new Error(
  1582. `Outer settings page did not scroll: ${JSON.stringify({ width, side, geometry, actual })}`,
  1583. { cause: error },
  1584. );
  1585. }
  1586. await browser.execute(() => {
  1587. document.querySelector("[data-model-layout-probe]")?.remove();
  1588. document
  1589. .querySelector('[data-model-provider-split-panel="true"]')!
  1590. .closest("main")!.scrollTop = 0;
  1591. });
  1592. }
  1593. }
  1594. } finally {
  1595. await browser.releaseActions();
  1596. await browser.execute(() =>
  1597. document.querySelectorAll("[data-model-layout-probe]").forEach((e) => e.remove()),
  1598. );
  1599. await clearRendererViewport();
  1600. }
  1601. }
  1602. async function assertLongProviderFeedbackVisible() {
  1603. try {
  1604. for (const [width, height] of [
  1605. [1280, 600],
  1606. [600, 500],
  1607. ]) {
  1608. await setRendererViewport(width!, height!);
  1609. for (const side of ["navigation", "detail"]) {
  1610. const results = await browser.execute((side) => {
  1611. const panel = document.querySelector<HTMLElement>(
  1612. '[data-model-provider-split-panel="true"]',
  1613. )!;
  1614. const main = panel.closest("main")!;
  1615. const detail = panel.querySelector<HTMLElement>(
  1616. '[data-model-provider-detail-scroll="true"]',
  1617. )!;
  1618. const target = panel.querySelector<HTMLElement>(
  1619. `[data-model-provider-${side}-scroll="true"]`,
  1620. )!;
  1621. const probe = document.createElement("div");
  1622. probe.dataset.feedbackLayoutProbe = "true";
  1623. probe.style.height = "1200px";
  1624. target.prepend(probe);
  1625. const feedback = panel.querySelector<HTMLElement>(
  1626. '[data-provider-detail-feedback-state="success"]',
  1627. )!;
  1628. const fullHeight = main.scrollHeight;
  1629. const results = [0, (main.scrollHeight - main.clientHeight) / 2, main.scrollHeight].map(
  1630. (offset) => {
  1631. main.scrollTop = offset;
  1632. const rect = feedback.getBoundingClientRect();
  1633. const viewport = main.getBoundingClientRect();
  1634. const column = detail.getBoundingClientRect();
  1635. return {
  1636. visible:
  1637. rect.height > 0 && rect.top >= viewport.top && rect.bottom <= viewport.bottom,
  1638. insideColumn: rect.left >= column.left && rect.right <= column.right,
  1639. stableHeight: main.scrollHeight === fullHeight,
  1640. };
  1641. },
  1642. );
  1643. probe.remove();
  1644. main.scrollTop = 0;
  1645. return results;
  1646. }, side);
  1647. for (const result of results)
  1648. expect(result).toEqual({ visible: true, insideColumn: true, stableHeight: true });
  1649. }
  1650. }
  1651. } finally {
  1652. await browser.execute(() =>
  1653. document.querySelectorAll("[data-feedback-layout-probe]").forEach((probe) => probe.remove()),
  1654. );
  1655. await clearRendererViewport();
  1656. }
  1657. }