settings-ui-polish.test.ts 69 KB

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