side-pane-tabs-responsive-interactions.test.ts 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. import { join } from "node:path";
  2. import { release } from "node:os";
  3. import {
  4. TID_TERMINAL_TOGGLE,
  5. TID_SIDE_PANE_TOGGLE,
  6. TID_WORKSPACE_HEADER,
  7. TID_WORKSPACE_TITLE,
  8. } from "@zcode/shared/test-ids";
  9. import { clearAppData } from "../helpers/desktop-app.js";
  10. import { prepareV4ConversationE2E } from "../helpers/v4-conversation.js";
  11. const TAB_SELECTOR = "[data-side-pane-tab-id]";
  12. const VIEWPORT_SELECTOR = "[data-side-pane-tabs-viewport]";
  13. const CONTENT_SELECTOR = "[data-side-pane-tabs-content]";
  14. const ADD_TRIGGER_SELECTOR = "[data-side-pane-add-tab-trigger]";
  15. const TOOLTIP_SELECTOR = '[data-slot="tooltip-content"]';
  16. const DRAFT_SUGGESTED_PROMPTS_SLOT_SELECTOR = '[data-v4-draft-suggested-prompts-slot="true"]';
  17. function expectedWorkspacePanelRadiusPx(): number {
  18. if (process.platform === "win32") return 6;
  19. // Darwin 25 起对应 Tahoe,Sequoia 及旧系统的工作区使用更小的内层圆角。
  20. if (process.platform === "darwin") return Number.parseInt(release(), 10) >= 25 ? 12 : 6;
  21. return 12;
  22. }
  23. interface TabStripMetrics {
  24. addInsideViewport: boolean;
  25. clientWidth: number;
  26. scrollWidth: number;
  27. tabWidths: number[];
  28. }
  29. describe("Side Pane Tab responsive interactions", () => {
  30. before(async () => {
  31. await prepareV4ConversationE2E({ skipProvider: true });
  32. });
  33. after(async () => {
  34. await browser.electron.restoreAllMocks();
  35. await clearAppData();
  36. });
  37. it("SPT-E2E-000 renders the shared header skeleton for a new task draft", async () => {
  38. const header = await $(`[data-testid="${TID_WORKSPACE_HEADER}"]`);
  39. await header.waitForDisplayed({ timeout: 10_000 });
  40. expect(await header.getAttribute("data-workspace-header-variant")).toBe("draft");
  41. if (process.platform === "win32" || process.platform === "linux") {
  42. expect(await header.$('[data-testid="desktop-window-controls"]').isExisting()).toBe(true);
  43. }
  44. expect(await header.$(`[data-testid="${TID_TERMINAL_TOGGLE}"]`).getSize("height")).toBe(28);
  45. if (process.platform === "win32" || process.platform === "linux") {
  46. expect(await header.$("button > svg.lucide-chevron-down").isExisting()).toBe(false);
  47. }
  48. expect(await $(`[data-testid="${TID_WORKSPACE_TITLE}"]`).isExisting()).toBe(false);
  49. expect(await readHeaderBorderBottomColor()).toBe("rgba(0, 0, 0, 0)");
  50. expect(
  51. await browser.execute((slotSelector) => {
  52. const slot = document.querySelector<HTMLElement>(slotSelector);
  53. if (!slot) return null;
  54. const style = window.getComputedStyle(slot);
  55. return { height: style.height, position: style.position };
  56. }, DRAFT_SUGGESTED_PROMPTS_SLOT_SELECTOR),
  57. ).toEqual({ height: "32px", position: "static" });
  58. const sidePaneToggle = await $(`[data-testid="${TID_SIDE_PANE_TOGGLE}"]`);
  59. await sidePaneToggle.waitForClickable({ timeout: 10_000 });
  60. const originalWidth = await browser.execute(
  61. () =>
  62. document
  63. .querySelector('[data-workspace-conversation-frame="true"]')
  64. ?.getBoundingClientRect().width ?? 0,
  65. );
  66. let expectedRestoredWidth = originalWidth;
  67. await sidePaneToggle.click();
  68. await browser.waitUntil(
  69. async () => (await readHeaderBorderBottomColor()) === "rgba(0, 0, 0, 0)",
  70. {
  71. timeout: 5_000,
  72. timeoutMsg: "Side Pane 展开后 Draft Header 分割线应保持透明",
  73. },
  74. );
  75. await browser.waitUntil(
  76. async () => {
  77. const metrics = await readIndependentPanelMetrics();
  78. return Boolean(
  79. metrics &&
  80. Math.abs(metrics.gap - 4) < 1 &&
  81. Math.abs(metrics.topDelta) < 1 &&
  82. Math.abs(metrics.bottomDelta) < 1,
  83. );
  84. },
  85. { timeout: 5000, timeoutMsg: "独立面板未形成上下对齐的 4px 间距" },
  86. );
  87. const panels = await readIndependentPanelMetrics();
  88. if (process.platform === "win32" || process.platform === "linux")
  89. expect(
  90. await browser.execute(() => {
  91. const controls = document.querySelector(
  92. '[data-workspace-side-frame] [data-testid="desktop-window-controls"]',
  93. )!;
  94. const frame = controls.closest("[data-workspace-side-frame]")!;
  95. return (
  96. frame.getBoundingClientRect().right -
  97. controls.getBoundingClientRect().right -
  98. parseFloat(getComputedStyle(frame).borderRightWidth)
  99. );
  100. }),
  101. ).toBeCloseTo(8, 0);
  102. if (process.platform === "win32" || process.platform === "linux") {
  103. expect(await header.$('[data-testid="desktop-window-controls"]').isExisting()).toBe(false);
  104. expect(
  105. await $(
  106. '[data-workspace-side-frame] [data-testid="desktop-window-controls"]',
  107. ).isDisplayed(),
  108. ).toBe(true);
  109. expect(
  110. await browser.execute(() => {
  111. const controls = document.querySelector(
  112. '[data-workspace-side-frame] [data-testid="desktop-window-controls"]',
  113. )!;
  114. const toggle = controls.previousElementSibling!;
  115. return controls.getBoundingClientRect().left - toggle.getBoundingClientRect().right;
  116. }),
  117. ).toBeCloseTo(2, 0);
  118. }
  119. if (process.platform === "win32" || process.platform === "linux") {
  120. expect(
  121. await browser.execute(() => {
  122. const logo = document.querySelector('[data-testid="desktop-top-logo-sidebar-toggle"]')!;
  123. return logo.getBoundingClientRect().left;
  124. }),
  125. ).toBe(13);
  126. const logoButton = await $('[data-testid="desktop-top-logo-sidebar-toggle"]');
  127. expect(await logoButton.getSize("width")).toBe(28);
  128. expect(await logoButton.$("[data-desktop-logo-badge]").getSize("width")).toBe(20);
  129. expect(await logoButton.$("[data-desktop-logo-badge] svg").getSize("width")).toBe(13);
  130. expect(await logoButton.$("animate").isExisting()).toBe(false);
  131. await logoButton.moveTo();
  132. await browser.waitUntil(
  133. async () =>
  134. await logoButton
  135. .$("[data-desktop-logo-visual]")
  136. .getCSSProperty("opacity")
  137. .then((value) => Number(value.value) === 0),
  138. );
  139. await logoButton.click();
  140. await logoButton.$("svg.lucide-panel-left-open").waitForExist();
  141. await browser.waitUntil(async () =>
  142. browser.execute(
  143. (inset) =>
  144. Math.abs(
  145. document
  146. .querySelector('[data-workspace-conversation-frame="true"]')!
  147. .getBoundingClientRect().left - inset,
  148. ) < 1,
  149. process.platform === "win32" ? 6 : 4,
  150. ),
  151. );
  152. await logoButton.click();
  153. await logoButton.$("svg.lucide-panel-left-close").waitForExist();
  154. }
  155. if (process.platform === "win32" || process.platform === "linux") {
  156. expect(
  157. await browser.execute(() => {
  158. const left = document
  159. .querySelector('[data-testid="desktop-top-nav-back"]')!
  160. .getBoundingClientRect();
  161. const right = document
  162. .querySelector('[data-testid="workspace-header"]')!
  163. .getBoundingClientRect();
  164. return Math.abs(left.top + left.height / 2 - right.top - right.height / 2);
  165. }),
  166. ).toBeLessThanOrEqual(1);
  167. }
  168. expect(
  169. await browser.execute(() => {
  170. const header = document.querySelector('[data-testid="workspace-header"]')!;
  171. const content = Array.from(header.children).find((element) =>
  172. element.classList.contains("p-2"),
  173. )!;
  174. return getComputedStyle(content).paddingRight;
  175. }),
  176. ).toBe("8px");
  177. if (
  178. process.platform === "win32" ||
  179. process.platform === "linux" ||
  180. process.platform === "darwin"
  181. ) {
  182. const inset = await browser.execute(() => {
  183. const content = document.querySelector("#content")!;
  184. const frame = document.querySelector('[data-workspace-conversation-frame="true"]')!;
  185. const style = getComputedStyle(content);
  186. return {
  187. right: style.paddingRight,
  188. bottom: style.paddingBottom,
  189. top: frame.getBoundingClientRect().top - content.getBoundingClientRect().top,
  190. };
  191. });
  192. const outerInset = process.platform === "win32" ? 6 : 4;
  193. expect(inset).toEqual({
  194. right: `${outerInset}px`,
  195. bottom: `${outerInset}px`,
  196. top: outerInset,
  197. });
  198. expect(
  199. await browser.execute(() => {
  200. const sidebar = document.querySelector<HTMLElement>(
  201. '[data-workspace-sidebar-panel="true"]',
  202. );
  203. const handle = document.querySelector<HTMLElement>('[data-testid="resizable-handle"]');
  204. if (!sidebar || !handle) return null;
  205. const sidebarRect = sidebar.getBoundingClientRect();
  206. const handleRect = handle.getBoundingClientRect();
  207. return handleRect.left + handleRect.width / 2 - sidebarRect.right;
  208. }),
  209. ).toBe(2);
  210. await movePointerAwayFromResizeHandles();
  211. expect(await readResizeHandleStyle('[data-testid="resizable-handle"]')).toEqual({
  212. hasExtendedIndicatorLine: true,
  213. indicatorOpacity: "0",
  214. handleHeight: "full",
  215. handleWidth: 4,
  216. marginLeft: "0px",
  217. marginRight: "0px",
  218. });
  219. const sidebarWidthBeforeDrag = await browser.execute(
  220. () =>
  221. document
  222. .querySelector<HTMLElement>('[data-workspace-sidebar-panel="true"]')!
  223. .getBoundingClientRect().width,
  224. );
  225. await hoverResizeHandle('[data-testid="resizable-handle"]');
  226. await assertResizeHandleVisible('[data-testid="resizable-handle"]');
  227. await dragResizeHandle('[data-testid="resizable-handle"]', 24, 0);
  228. await browser.waitUntil(
  229. async () =>
  230. Math.abs(
  231. (await browser.execute(
  232. () =>
  233. document
  234. .querySelector<HTMLElement>('[data-workspace-sidebar-panel="true"]')!
  235. .getBoundingClientRect().width,
  236. )) - sidebarWidthBeforeDrag,
  237. ) > 10,
  238. { timeout: 5000, timeoutMsg: "Sidebar resize handle 没有改变侧栏宽度" },
  239. );
  240. const sidebarWidthAfterDrag = await browser.execute(
  241. () =>
  242. document
  243. .querySelector<HTMLElement>('[data-workspace-sidebar-panel="true"]')!
  244. .getBoundingClientRect().width,
  245. );
  246. expectedRestoredWidth -= sidebarWidthAfterDrag - sidebarWidthBeforeDrag;
  247. }
  248. expect(await header.$(`[data-testid="${TID_SIDE_PANE_TOGGLE}"]`).isExisting()).toBe(false);
  249. const sidePaneClose = await $(
  250. `[data-workspace-side-frame] [data-testid="${TID_SIDE_PANE_TOGGLE}"]`,
  251. );
  252. await sidePaneClose.waitForClickable({ timeout: 5000 });
  253. expect(panels?.headerInsideConversation).toBe(true);
  254. const expectedPanelRadiusPx = expectedWorkspacePanelRadiusPx();
  255. if (expectedPanelRadiusPx === 6) {
  256. // Side Pane 展开时会话外框使用动态圆角变量,只有右侧 chrome 外框使用圆角 token。
  257. const framesUseRadiusToken = await browser.execute(() => {
  258. const frame = document.querySelector('[data-workspace-side-frame="true"]');
  259. return Boolean(
  260. frame?.classList.contains("rounded-md") || frame?.classList.contains("rounded-l-md"),
  261. );
  262. });
  263. expect(framesUseRadiusToken).toBe(true);
  264. }
  265. expect(panels?.leftRadius).toBe(`${expectedPanelRadiusPx}px`);
  266. expect(panels?.rightRadius).toBe(`${expectedPanelRadiusPx}px`);
  267. await movePointerAwayFromResizeHandles();
  268. expect(
  269. await readResizeHandleStyle('[data-workspace-side-pane-resize-handle="true"]'),
  270. ).toMatchObject({
  271. hasExtendedIndicatorLine: true,
  272. indicatorOpacity: "0",
  273. handleWidth: 4,
  274. });
  275. await hoverResizeHandle('[data-workspace-side-pane-resize-handle="true"]');
  276. await assertResizeHandleVisible('[data-workspace-side-pane-resize-handle="true"]');
  277. if (process.platform === "win32" || process.platform === "linux") {
  278. expect(
  279. await browser.execute(() => {
  280. const style = getComputedStyle(document.querySelector("[data-workspace-side-frame]")!);
  281. return [style.borderTopRightRadius, style.borderBottomRightRadius];
  282. }),
  283. ).toEqual(process.platform === "win32" ? ["6px", "6px"] : ["12px", "12px"]);
  284. }
  285. const drag = await browser.execute(() => {
  286. const frame = document
  287. .querySelector('[data-workspace-conversation-frame="true"]')!
  288. .getBoundingClientRect();
  289. return {
  290. x: Math.round(frame.right + 2),
  291. y: Math.round(frame.top + frame.height / 2),
  292. width: frame.width,
  293. };
  294. });
  295. await dragResizeHandle('[data-workspace-side-pane-resize-handle="true"]', -45, 0);
  296. await browser.waitUntil(
  297. async () => {
  298. const width = await browser.execute(
  299. () =>
  300. document
  301. .querySelector('[data-workspace-conversation-frame="true"]')!
  302. .getBoundingClientRect().width,
  303. );
  304. return Math.abs(width - drag.width) > 10;
  305. },
  306. { timeout: 5000, timeoutMsg: "独立面板间距无法拖动调整宽度" },
  307. );
  308. expect((await readIndependentPanelMetrics())?.gap).toBeCloseTo(4, 0);
  309. const terminalToggle = await $(`[data-testid="${TID_TERMINAL_TOGGLE}"]`);
  310. await terminalToggle.click();
  311. await browser.waitUntil(
  312. async () =>
  313. browser.execute(() => {
  314. const terminal = document.querySelector<HTMLElement>("#terminal");
  315. const frame = document.querySelector('[data-workspace-conversation-frame="true"]');
  316. return Boolean(
  317. terminal &&
  318. frame &&
  319. !frame.contains(terminal) &&
  320. terminal.closest("#conversation-column") === frame.closest("#conversation-column") &&
  321. terminal.getBoundingClientRect().height > 20 &&
  322. Math.abs(
  323. terminal.getBoundingClientRect().top - frame.getBoundingClientRect().bottom - 4,
  324. ) < 1,
  325. );
  326. }),
  327. { timeout: 10000, timeoutMsg: "终端没有以 4px 间距在会话下方独立展开" },
  328. );
  329. await movePointerAwayFromResizeHandles();
  330. expect(
  331. await readResizeHandleStyle('[data-workspace-terminal-resize-handle="true"]'),
  332. ).toMatchObject({
  333. hasExtendedIndicatorLine: true,
  334. indicatorOpacity: "0",
  335. handleHeight: 4,
  336. });
  337. const conversationHeightBeforeDrag = await browser.execute(
  338. () =>
  339. document
  340. .querySelector<HTMLElement>('[data-workspace-conversation-frame="true"]')!
  341. .getBoundingClientRect().height,
  342. );
  343. await hoverResizeHandle('[data-workspace-terminal-resize-handle="true"]');
  344. await assertResizeHandleVisible('[data-workspace-terminal-resize-handle="true"]');
  345. await dragResizeHandle('[data-workspace-terminal-resize-handle="true"]', 0, -24);
  346. await browser.waitUntil(
  347. async () =>
  348. Math.abs(
  349. (await browser.execute(
  350. () =>
  351. document
  352. .querySelector<HTMLElement>('[data-workspace-conversation-frame="true"]')!
  353. .getBoundingClientRect().height,
  354. )) - conversationHeightBeforeDrag,
  355. ) > 10,
  356. { timeout: 5000, timeoutMsg: "Terminal resize handle 没有改变会话高度" },
  357. );
  358. for (const theme of ["zai-light", "zai-dark"]) {
  359. await browser.execute((value) => {
  360. const actions = (
  361. window as typeof window & { __testActions?: { setTheme?: (theme: string) => void } }
  362. ).__testActions;
  363. if (!actions?.setTheme) throw new Error("缺少主题测试入口");
  364. actions.setTheme(value);
  365. }, theme);
  366. await browser.waitUntil(
  367. async () =>
  368. browser.execute(
  369. (value) => document.documentElement.classList.contains(`theme-${value}`),
  370. theme,
  371. ),
  372. { timeout: 5000 },
  373. );
  374. for (const selector of [
  375. '[data-testid="resizable-handle"]',
  376. '[data-workspace-side-pane-resize-handle="true"]',
  377. '[data-workspace-terminal-resize-handle="true"]',
  378. ]) {
  379. expect((await readResizeHandleStyle(selector)).hasExtendedIndicatorLine).toBe(true);
  380. }
  381. const colors = await browser.execute(() => {
  382. const left = document.querySelector('[data-workspace-conversation-frame="true"]')!;
  383. const right = document.querySelector('[data-workspace-side-frame="true"]')!;
  384. const terminal = document.querySelector('[data-workspace-terminal-frame="true"]')!;
  385. return [
  386. getComputedStyle(left).backgroundColor,
  387. getComputedStyle(right).backgroundColor,
  388. getComputedStyle(terminal).backgroundColor,
  389. ];
  390. });
  391. expect(colors[0]).toBe(colors[1]);
  392. expect(colors[0]).toBe(colors[2]);
  393. expect(colors[0]).not.toBe("rgba(0, 0, 0, 0)");
  394. if (process.platform === "win32" || process.platform === "linux") {
  395. expect(await $("[data-desktop-logo-badge] svg").getSize("width")).toBe(13);
  396. }
  397. const terminalTabStyle = await browser.execute(() => {
  398. const tab = document.querySelector('#terminal [role="tab"][data-active]')!;
  399. const content = tab.querySelector("[data-terminal-tab-content]")!;
  400. return {
  401. border: getComputedStyle(tab).borderColor,
  402. mask: getComputedStyle(content).maskImage,
  403. closePosition: getComputedStyle(tab.querySelector("button")!).position,
  404. gap: getComputedStyle(tab.closest('[role="tablist"]')!).columnGap,
  405. };
  406. });
  407. expect(terminalTabStyle.border).toBe("rgba(0, 0, 0, 0)");
  408. expect(terminalTabStyle.mask).not.toBe("none");
  409. expect(terminalTabStyle.closePosition).toBe("static");
  410. expect(terminalTabStyle.gap).toBe("4px");
  411. await browser.saveScreenshot(
  412. join(
  413. process.env.ZCODE_E2E_ARTIFACT_DIR || process.cwd(),
  414. `independent-panels-${theme}.png`,
  415. ),
  416. );
  417. }
  418. await terminalToggle.click();
  419. await sidePaneClose.click();
  420. await browser.waitUntil(
  421. async () => (await readHeaderBorderBottomColor()) === "rgba(0, 0, 0, 0)",
  422. {
  423. timeout: 5_000,
  424. timeoutMsg: "Side Pane 收起后 Draft Header 分割线未恢复透明",
  425. },
  426. );
  427. await browser.waitUntil(
  428. async () => {
  429. const width = await browser.execute(
  430. () =>
  431. document
  432. .querySelector('[data-workspace-conversation-frame="true"]')
  433. ?.getBoundingClientRect().width ?? 0,
  434. );
  435. return Math.abs(width - expectedRestoredWidth) < 2;
  436. },
  437. { timeout: 5000, timeoutMsg: "关闭 Side Pane 后会话宽度未恢复" },
  438. );
  439. const closedFrame = await browser.execute(() => {
  440. const frame = document.querySelector('[data-workspace-conversation-frame="true"]')!;
  441. return {
  442. usesRadiusToken:
  443. frame.classList.contains("rounded-md") || frame.classList.contains("rounded-l-md"),
  444. leftRadius: getComputedStyle(frame).borderTopLeftRadius,
  445. };
  446. });
  447. if (expectedPanelRadiusPx === 6) expect(closedFrame.usesRadiusToken).toBe(true);
  448. expect(closedFrame.leftRadius).toBe(`${expectedPanelRadiusPx}px`);
  449. });
  450. it("SPT-E2E-001 keeps one tab at 156px and the add button beside it", async () => {
  451. if (process.platform === "win32" || process.platform === "linux") {
  452. // 本组用例强制 tab viewport 为 360px;自绘窗控按 CSS 像素预留后,需要足够宽的真实窗口容纳测试夹具。
  453. await browser.electron.execute((electron) => {
  454. electron.BrowserWindow.getAllWindows()[0]!.setSize(2200, 1400);
  455. });
  456. await browser.waitUntil(async () => browser.execute(() => window.innerWidth > 1400));
  457. }
  458. await ensureTerminalTabCount(1);
  459. await setTabsViewportWidth(360);
  460. const metrics = await readTabStripMetrics();
  461. expect(metrics.tabWidths).toHaveLength(1);
  462. expect(metrics.tabWidths[0]).toBeCloseTo(156, 0);
  463. expect(metrics.scrollWidth).toBeLessThanOrEqual(metrics.clientWidth + 1);
  464. expect(metrics.addInsideViewport).toBe(true);
  465. const regions = await browser.execute(() => {
  466. const header = document.querySelector('[data-workspace-side-frame] [role="tablist"]')!;
  467. const region = (element: Element) =>
  468. getComputedStyle(element).getPropertyValue("-webkit-app-region");
  469. return {
  470. header: region(header),
  471. controls: [...header.querySelectorAll("button, [data-side-pane-tab-id]")].map(region),
  472. };
  473. });
  474. expect(regions.header).toBe("drag");
  475. expect(regions.controls.length).toBeGreaterThan(2);
  476. expect(regions.controls.every((region) => region === "no-drag")).toBe(true);
  477. const close = await $(`[data-workspace-side-frame] [data-testid="${TID_SIDE_PANE_TOGGLE}"]`);
  478. expect(
  479. await browser.execute(() => {
  480. const header = document.querySelector('[data-workspace-side-frame] [role="tablist"]')!;
  481. const first = header.querySelector("button")!;
  482. return first.getBoundingClientRect().left - header.getBoundingClientRect().left;
  483. }),
  484. ).toBeCloseTo(8, 0);
  485. await close.waitForClickable({ timeout: 5000 });
  486. await close.click();
  487. const reopen = await $(
  488. `[data-testid="${TID_WORKSPACE_HEADER}"] [data-testid="${TID_SIDE_PANE_TOGGLE}"]`,
  489. );
  490. await reopen.waitForClickable({ timeout: 5000 });
  491. await reopen.click();
  492. await ensureSidePaneExpanded();
  493. await $(TAB_SELECTOR).waitForDisplayed({ timeout: 5000 });
  494. });
  495. it("SPT-E2E-002 shrinks tabs equally above 60px before scrolling", async () => {
  496. await ensureTerminalTabCount(3);
  497. await setTabsViewportWidth(300);
  498. const metrics = await readTabStripMetrics();
  499. expect(metrics.tabWidths).toHaveLength(3);
  500. expect(Math.max(...metrics.tabWidths) - Math.min(...metrics.tabWidths)).toBeLessThanOrEqual(1);
  501. expect(metrics.tabWidths[0]).toBeGreaterThan(60);
  502. expect(metrics.tabWidths[0]).toBeLessThan(156);
  503. expect(metrics.scrollWidth).toBeLessThanOrEqual(metrics.clientWidth + 1);
  504. expect(metrics.addInsideViewport).toBe(true);
  505. });
  506. it("SPT-E2E-003 scrolls only at the 60px floor and fixes add outside", async () => {
  507. await ensureTerminalTabCount(6);
  508. await setTabsViewportWidth(300);
  509. const metrics = await readTabStripMetrics();
  510. expect(metrics.tabWidths).toHaveLength(6);
  511. expect(Math.min(...metrics.tabWidths)).toBeGreaterThanOrEqual(59.5);
  512. expect(metrics.scrollWidth).toBeGreaterThan(metrics.clientWidth + 1);
  513. expect(metrics.addInsideViewport).toBe(false);
  514. });
  515. it("SPT-E2E-004 shows close on active or hovered tabs without activating an inactive tab", async () => {
  516. await ensureTerminalTabCount(2);
  517. await setTabsViewportWidth(360);
  518. await browser.execute(() => (document.activeElement as HTMLElement | null)?.blur());
  519. await $(`[data-testid="${TID_WORKSPACE_HEADER}"]`).moveTo();
  520. const before = await browser.execute((tabSelector) => {
  521. const tabs = Array.from(document.querySelectorAll<HTMLElement>(tabSelector));
  522. return tabs.map((tab) => {
  523. const closeButton = tab.querySelector<HTMLButtonElement>("button");
  524. const style = closeButton ? window.getComputedStyle(closeButton) : null;
  525. return {
  526. id: tab.dataset.sidePaneTabId ?? "",
  527. active: tab.dataset.state === "active",
  528. closeVisible:
  529. Boolean(closeButton) &&
  530. style?.display !== "none" &&
  531. style?.visibility !== "hidden" &&
  532. Number(style?.opacity ?? "0") > 0,
  533. };
  534. });
  535. }, TAB_SELECTOR);
  536. const inactive = before.find((tab) => !tab.active);
  537. const active = before.find((tab) => tab.active);
  538. expect(active?.closeVisible).toBe(true);
  539. expect(inactive?.closeVisible).toBe(false);
  540. expect(inactive?.id).toBeTruthy();
  541. expect(active?.id).toBeTruthy();
  542. const inactiveTab = await $(`${TAB_SELECTOR}[data-side-pane-tab-id="${inactive!.id}"]`);
  543. const readContent = () =>
  544. browser.execute((id) => {
  545. const tab = document.querySelector(`[data-side-pane-tab-id="${id}"]`)!;
  546. const content = tab.querySelector("[data-side-pane-tab-content]")!;
  547. const title = tab.querySelector("[data-side-pane-tab-title]")!;
  548. return {
  549. width: content.getBoundingClientRect().width,
  550. left: title.getBoundingClientRect().left,
  551. mask: getComputedStyle(content).maskImage,
  552. textOverflow: getComputedStyle(title).textOverflow,
  553. };
  554. }, inactive!.id);
  555. const idleContent = await readContent();
  556. await inactiveTab.moveTo();
  557. const hoveredContent = await readContent();
  558. expect(idleContent.textOverflow).toBe("clip");
  559. expect(idleContent.mask).not.toBe("none");
  560. expect(hoveredContent.mask).not.toBe(idleContent.mask);
  561. expect(hoveredContent.width).toBe(idleContent.width);
  562. expect(hoveredContent.left).toBe(idleContent.left);
  563. const closeButton = await inactiveTab.$("button");
  564. await closeButton.waitForDisplayed({ timeout: 5000 });
  565. await closeButton.click();
  566. await browser.waitUntil(
  567. async () =>
  568. browser.execute(
  569. (tabSelector, closedId, activeId) => {
  570. const closed = document.querySelector(
  571. `${tabSelector}[data-side-pane-tab-id="${closedId}"]`,
  572. );
  573. const current = document.querySelector<HTMLElement>(
  574. `${tabSelector}[data-side-pane-tab-id="${activeId}"]`,
  575. );
  576. return !closed && current?.dataset.state === "active";
  577. },
  578. TAB_SELECTOR,
  579. inactive!.id,
  580. active!.id,
  581. ),
  582. { timeout: 5_000, timeoutMsg: "关闭 inactive tab 后 active tab 发生变化" },
  583. );
  584. });
  585. it("SPT-E2E-005 restarts the 1500ms tooltip delay on another tab", async () => {
  586. await ensureTerminalTabCount(2);
  587. await setTabsViewportWidth(360);
  588. const tabs = await $$(TAB_SELECTOR);
  589. const [firstTab, secondTab] = tabs;
  590. if (!firstTab || !secondTab) throw new Error("Expected two Side Pane tabs");
  591. await firstTab.moveTo();
  592. await browser.pause(1_000);
  593. expect(await countDisplayedTooltips()).toBe(0);
  594. await secondTab.moveTo();
  595. await browser.pause(700);
  596. expect(await countDisplayedTooltips()).toBe(0);
  597. await browser.pause(1_000);
  598. // 终端标题可能重复且包含序号;读取 Tooltip 语义节点,避免外层 textContent 包含双份文案。
  599. expect(await countDisplayedTooltips()).toBe(1);
  600. const tooltipTitle = await browser.execute(() =>
  601. document.querySelector('[data-slot="tooltip-content"] [role="tooltip"]')?.textContent?.trim(),
  602. );
  603. expect(tooltipTitle).toBe(await secondTab.$("[data-side-pane-tab-title]").getText());
  604. });
  605. it("SPT-E2E-006 closes an inactive tab with the middle mouse button without activating it", async () => {
  606. await ensureTerminalTabCount(2);
  607. await setTabsViewportWidth(360);
  608. const before = await browser.execute((tabSelector) => {
  609. const tabs = Array.from(document.querySelectorAll<HTMLElement>(tabSelector));
  610. return tabs.map((tab) => ({
  611. id: tab.dataset.sidePaneTabId ?? "",
  612. active: tab.dataset.state === "active",
  613. }));
  614. }, TAB_SELECTOR);
  615. const inactive = before.find((tab) => !tab.active);
  616. const active = before.find((tab) => tab.active);
  617. expect(inactive?.id).toBeTruthy();
  618. expect(active?.id).toBeTruthy();
  619. const dispatchResult = await browser.execute(
  620. (tabSelector, tabId) => {
  621. const tab = document.querySelector<HTMLElement>(
  622. `${tabSelector}[data-side-pane-tab-id="${tabId}"]`,
  623. );
  624. if (!tab) throw new Error(`Missing tab ${tabId}`);
  625. const event = new MouseEvent("auxclick", {
  626. bubbles: true,
  627. cancelable: true,
  628. button: 1,
  629. buttons: 4,
  630. });
  631. const notCanceled = tab.dispatchEvent(event);
  632. return { notCanceled, active: tab.dataset.state === "active" };
  633. },
  634. TAB_SELECTOR,
  635. inactive!.id,
  636. );
  637. expect(dispatchResult.notCanceled).toBe(false);
  638. expect(dispatchResult.active).toBe(false);
  639. await browser.waitUntil(
  640. async () =>
  641. browser.execute(
  642. (tabSelector, closedId, activeId) => {
  643. const closed = document.querySelector(
  644. `${tabSelector}[data-side-pane-tab-id="${closedId}"]`,
  645. );
  646. const current = document.querySelector<HTMLElement>(
  647. `${tabSelector}[data-side-pane-tab-id="${activeId}"]`,
  648. );
  649. return !closed && current?.dataset.state === "active";
  650. },
  651. TAB_SELECTOR,
  652. inactive!.id,
  653. active!.id,
  654. ),
  655. { timeout: 5_000, timeoutMsg: "中键关闭 inactive tab 后 active tab 发生变化" },
  656. );
  657. });
  658. it("SPT-E2E-007 routes custom desktop minimize and close controls", async function () {
  659. if (process.platform !== "win32" && process.platform !== "linux") {
  660. this.skip();
  661. return;
  662. }
  663. if (process.platform === "win32" || process.platform === "linux") {
  664. const maximize = await $('[data-testid="window-control-maximize"]');
  665. const normalBounds = await browser.electron.execute((electron) =>
  666. electron.BrowserWindow.getAllWindows()[0]!.getBounds(),
  667. );
  668. expect(await maximize.getSize("height")).toBe(28);
  669. await maximize.click();
  670. await browser.waitUntil(
  671. async () => (await maximize.getAttribute("data-maximized")) === "true",
  672. );
  673. expect(await maximize.$("svg.lucide-window-restore").isExisting()).toBe(true);
  674. try {
  675. await browser.waitUntil(
  676. async () =>
  677. browser.execute(() => {
  678. const style = getComputedStyle(
  679. document.querySelector("[data-workspace-side-frame]")!,
  680. );
  681. return (
  682. [
  683. style.borderTopLeftRadius,
  684. style.borderTopRightRadius,
  685. style.borderBottomLeftRadius,
  686. style.borderBottomRightRadius,
  687. ].every((value) => value === "5px") &&
  688. [
  689. style.borderTopWidth,
  690. style.borderRightWidth,
  691. style.borderBottomWidth,
  692. style.borderLeftWidth,
  693. ].every((value) => value === "1px")
  694. );
  695. }),
  696. { timeout: 5000, timeoutMsg: "最大化后的 Side Pane 必须保持四角 5px 和完整边框" },
  697. );
  698. } finally {
  699. await maximize.click();
  700. await browser.waitUntil(
  701. async () => (await maximize.getAttribute("data-maximized")) === "false",
  702. );
  703. await browser.waitUntil(async () => {
  704. const bounds = await browser.electron.execute((electron) =>
  705. electron.BrowserWindow.getAllWindows()[0]!.getBounds(),
  706. );
  707. return (
  708. bounds.width === normalBounds.width &&
  709. bounds.height === normalBounds.height &&
  710. Math.abs((await readIndependentPanelMetrics())!.gap - 4) < 1
  711. );
  712. });
  713. }
  714. }
  715. await browser.electron.execute((electron) => {
  716. const win = electron.BrowserWindow.getAllWindows()[0]! as Electron.BrowserWindow & {
  717. testMinimized?: boolean;
  718. };
  719. win.testMinimized = false;
  720. win.once("minimize", () => {
  721. win.testMinimized = true;
  722. });
  723. });
  724. await $('[data-testid="window-control-minimize"]').click();
  725. try {
  726. // WDIO 获取窗口上下文可能重新激活窗口,使用真实 minimize 事件作为成功证据。
  727. await browser.waitUntil(async () =>
  728. browser.electron.execute(
  729. (electron) =>
  730. (
  731. electron.BrowserWindow.getAllWindows()[0]! as Electron.BrowserWindow & {
  732. testMinimized?: boolean;
  733. }
  734. ).testMinimized === true,
  735. ),
  736. );
  737. } finally {
  738. await browser.electron.execute((electron) => {
  739. const win = electron.BrowserWindow.getAllWindows()[0]!;
  740. win.restore();
  741. win.show();
  742. });
  743. }
  744. // 验证真实 close 事件,但阻止测试窗口退出,避免销毁 WDIO 会话。
  745. await browser.electron.execute((electron) => {
  746. const win = electron.BrowserWindow.getAllWindows()[0]! as Electron.BrowserWindow & {
  747. testCloseReceived?: boolean;
  748. };
  749. win.testCloseReceived = false;
  750. win.once("close", (event) => {
  751. event.preventDefault();
  752. win.testCloseReceived = true;
  753. });
  754. });
  755. await $('[data-testid="window-control-close"]').click();
  756. expect(
  757. await browser.electron.execute((electron) => {
  758. const win = electron.BrowserWindow.getAllWindows()[0]! as Electron.BrowserWindow & {
  759. testCloseReceived?: boolean;
  760. };
  761. return win.testCloseReceived;
  762. }),
  763. ).toBe(true);
  764. });
  765. it("SPT-E2E-009 opens a real new tab and replaces it with a tool", async () => {
  766. await ensureSidePaneExpanded();
  767. const active = () => $('[data-side-pane-tab-id][data-state="active"]');
  768. while ((await readTabCount()) > 1) {
  769. const count = await readTabCount();
  770. await (await active()).$("button").click();
  771. await browser.waitUntil(async () => (await readTabCount()) === count - 1);
  772. }
  773. if (!/新标签页|New tab/.test(await (await active()).getText())) {
  774. await (await active()).$("button").click();
  775. await browser.waitUntil(async () => (await readTabCount()) === 0);
  776. await $(
  777. `[data-testid="${TID_WORKSPACE_HEADER}"] [data-testid="${TID_SIDE_PANE_TOGGLE}"]`,
  778. ).waitForDisplayed();
  779. await ensureSidePaneExpanded();
  780. }
  781. expect(await readTabCount()).toBe(1);
  782. await $(ADD_TRIGGER_SELECTOR).waitForDisplayed();
  783. await $('[data-state="active"] [data-side-pane-open-tab-item="terminal"]').click();
  784. await browser.waitUntil(async () => !/新标签页|New tab/.test(await (await active()).getText()));
  785. expect(await readTabCount()).toBe(1);
  786. const toolId = await (await active()).getAttribute("data-side-pane-tab-id");
  787. await $(`[data-testid="${TID_SIDE_PANE_TOGGLE}"]`).click();
  788. await ensureSidePaneExpanded();
  789. expect(await (await active()).getAttribute("data-side-pane-tab-id")).toBe(toolId);
  790. await $(ADD_TRIGGER_SELECTOR).click();
  791. await browser.waitUntil(async () => (await readTabCount()) === 2);
  792. expect(await (await active()).getText()).toMatch(/新标签页|New tab/);
  793. await (await active()).$("button").click();
  794. await browser.waitUntil(async () => (await readTabCount()) === 1);
  795. await (await active()).$("button").click();
  796. await browser.waitUntil(async () => (await readTabCount()) === 0);
  797. await $(
  798. `[data-testid="${TID_WORKSPACE_HEADER}"] [data-testid="${TID_SIDE_PANE_TOGGLE}"]`,
  799. ).waitForDisplayed();
  800. await ensureSidePaneExpanded();
  801. expect(await (await active()).getText()).toMatch(/新标签页|New tab/);
  802. // 走真实菜单命令与 IPC,确认末标签关闭不再被自动补建吞掉。
  803. await browser.electron.execute((electron) => {
  804. const item = electron.Menu.getApplicationMenu()
  805. ?.items.flatMap((menu) => menu.submenu?.items ?? [])
  806. .find((entry) => entry.accelerator === "CmdOrCtrl+W");
  807. if (!item) throw new Error("未找到关闭当前上下文菜单");
  808. const target = electron.BrowserWindow.getAllWindows().find((win) =>
  809. win.webContents.getURL().includes("/renderer/index.html"),
  810. );
  811. if (!target || !item.enabled) throw new Error("关闭菜单或目标窗口不可用");
  812. target.focus();
  813. item.click(item, target, {} as never);
  814. });
  815. await browser.waitUntil(async () => (await readTabCount()) === 0);
  816. await $(
  817. `[data-testid="${TID_WORKSPACE_HEADER}"] [data-testid="${TID_SIDE_PANE_TOGGLE}"]`,
  818. ).waitForDisplayed();
  819. // 不真正关闭测试窗口;再次发出同一可取消事件,必须允许 Root 执行关窗 fallback。
  820. expect(
  821. await browser.execute(() =>
  822. window.dispatchEvent(new Event("zcode:close-active-context-request", { cancelable: true })),
  823. ),
  824. ).toBe(true);
  825. await ensureSidePaneExpanded();
  826. expect(await readTabCount()).toBe(1);
  827. });
  828. it("新标签页支持多开、聚焦、统一宽度和关闭", async () => {
  829. await ensureTerminalTabCount(1);
  830. const ids: string[] = [];
  831. for (let index = 0; index < 2; index += 1) {
  832. await $(ADD_TRIGGER_SELECTOR).click();
  833. await browser.waitUntil(async () => (await readTabCount()) === index + 2);
  834. const active = await $('[data-side-pane-tab-id][data-state="active"]');
  835. const id = await active.getAttribute("data-side-pane-tab-id");
  836. if (!id) throw new Error("新标签页缺少 id");
  837. ids.push(id);
  838. expect(await active.getText()).toMatch(/新标签页|New tab/);
  839. expect(await active.getSize("width")).toBeLessThanOrEqual(156);
  840. }
  841. expect(ids[0]).not.toBe(ids[1]);
  842. const first = await $(`[data-side-pane-tab-id="${ids[0]}"]`);
  843. await first.click();
  844. expect(await first.getAttribute("data-state")).toBe("active");
  845. await $('[data-state="active"] [data-side-pane-open-tab-item="browser"]').waitForDisplayed();
  846. await first.$("button").click();
  847. await browser.waitUntil(async () => (await readTabCount()) === 2);
  848. await $(`[data-side-pane-tab-id="${ids[1]}"] button`).click();
  849. await browser.waitUntil(async () => (await readTabCount()) === 1);
  850. });
  851. });
  852. interface ResizeHandleRect {
  853. x: number;
  854. y: number;
  855. }
  856. async function readResizeHandleRect(selector: string): Promise<ResizeHandleRect> {
  857. return browser.execute((targetSelector) => {
  858. const rect = document.querySelector<HTMLElement>(targetSelector)!.getBoundingClientRect();
  859. return { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2) };
  860. }, selector);
  861. }
  862. async function movePointerAwayFromResizeHandles(): Promise<void> {
  863. await browser.performActions([
  864. {
  865. type: "pointer",
  866. id: "resize-pointer",
  867. parameters: { pointerType: "mouse" },
  868. actions: [{ type: "pointerMove", duration: 0, x: 20, y: 20 }],
  869. },
  870. ]);
  871. await browser.releaseActions();
  872. }
  873. async function hoverResizeHandle(selector: string): Promise<void> {
  874. await $(selector).moveTo();
  875. }
  876. async function dragResizeHandle(selector: string, deltaX: number, deltaY: number): Promise<void> {
  877. const rect = await readResizeHandleRect(selector);
  878. await browser.performActions([
  879. {
  880. type: "pointer",
  881. id: "resize-pointer",
  882. parameters: { pointerType: "mouse" },
  883. actions: [
  884. { type: "pointerMove", duration: 0, x: rect.x, y: rect.y },
  885. { type: "pointerDown", button: 0 },
  886. { type: "pointerMove", duration: 250, x: rect.x + deltaX, y: rect.y + deltaY },
  887. ],
  888. },
  889. ]);
  890. try {
  891. await assertResizeHandleVisible(selector);
  892. } finally {
  893. await browser.performActions([
  894. {
  895. type: "pointer",
  896. id: "resize-pointer",
  897. parameters: { pointerType: "mouse" },
  898. actions: [{ type: "pointerUp", button: 0 }],
  899. },
  900. ]);
  901. await browser.releaseActions();
  902. }
  903. }
  904. async function readResizeHandleStyle(selector: string) {
  905. return browser.execute((targetSelector) => {
  906. const handle = document.querySelector<HTMLElement>(targetSelector)!;
  907. const handleRect = handle.getBoundingClientRect();
  908. const handleStyle = getComputedStyle(handle);
  909. const indicatorStyle = getComputedStyle(handle, "::after");
  910. const reference = document.createElement("div");
  911. // 测试节点不参与 Tailwind 扫描,直接按主题 token 计算期望色,避免缺失 utility 造成误报。
  912. reference.style.backgroundColor = document.documentElement.classList.contains("dark")
  913. ? "var(--color-sky-400)"
  914. : "var(--color-sky-500)";
  915. document.body.append(reference);
  916. const indicatorColor = getComputedStyle(reference).backgroundColor;
  917. reference.remove();
  918. const vertical = handleRect.height > handleRect.width;
  919. const expectedInset = Number.parseFloat(
  920. handleStyle.getPropertyValue(
  921. targetSelector === '[data-testid="resizable-handle"]'
  922. ? "--workspace-resize-handle-inset"
  923. : "--workspace-panel-radius",
  924. ),
  925. );
  926. return {
  927. hasExtendedIndicatorLine:
  928. indicatorStyle.content !== "none" &&
  929. indicatorStyle.maskImage === "none" &&
  930. Math.abs(
  931. Number.parseFloat(vertical ? indicatorStyle.height : indicatorStyle.width) -
  932. ((vertical ? handleRect.height : handleRect.width) - 2 * expectedInset),
  933. ) < 1 &&
  934. indicatorStyle.backgroundColor === indicatorColor,
  935. indicatorOpacity: indicatorStyle.opacity,
  936. handleHeight: vertical ? "full" : handleRect.height,
  937. handleWidth: handleRect.width,
  938. marginLeft: handleStyle.marginLeft,
  939. marginRight: handleStyle.marginRight,
  940. };
  941. }, selector);
  942. }
  943. async function assertResizeHandleVisible(selector: string): Promise<void> {
  944. await browser.waitUntil(
  945. async () => Number((await readResizeHandleStyle(selector)).indicatorOpacity) > 0.99,
  946. { timeout: 1000 },
  947. );
  948. expect((await readResizeHandleStyle(selector)).hasExtendedIndicatorLine).toBe(true);
  949. }
  950. async function readHeaderBorderBottomColor(): Promise<string> {
  951. return browser.execute((headerTestId) => {
  952. const headerElement = document.querySelector<HTMLElement>(`[data-testid="${headerTestId}"]`);
  953. if (!headerElement) {
  954. throw new Error("Workspace Header is not mounted");
  955. }
  956. return window.getComputedStyle(headerElement).borderBottomColor;
  957. }, TID_WORKSPACE_HEADER);
  958. }
  959. async function ensureTerminalTabCount(targetCount: number): Promise<void> {
  960. await ensureSidePaneExpanded();
  961. const initialLauncher = await $(
  962. '[data-state="active"] [data-side-pane-open-tab-item="terminal"]',
  963. );
  964. if (await initialLauncher.isDisplayed()) {
  965. await initialLauncher.click();
  966. await browser.waitUntil(async () => !(await initialLauncher.isDisplayed()));
  967. }
  968. let count = await readTabCount();
  969. while (count > targetCount) {
  970. await browser.execute((tabSelector) => {
  971. const tabs = Array.from(document.querySelectorAll<HTMLElement>(tabSelector));
  972. tabs.at(-1)?.querySelector<HTMLButtonElement>("button")?.click();
  973. }, TAB_SELECTOR);
  974. count -= 1;
  975. await browser.waitUntil(async () => (await readTabCount()) === count, {
  976. timeout: 5_000,
  977. timeoutMsg: `Side Pane Tab 数量未减少到 ${count}`,
  978. });
  979. }
  980. while (count < targetCount) {
  981. if (count === 0) {
  982. const launcher = await $('[data-side-pane-open-tab-item="terminal"]');
  983. await launcher.waitForClickable({ timeout: 10_000 });
  984. await launcher.click();
  985. } else {
  986. const addTrigger = await $(ADD_TRIGGER_SELECTOR);
  987. await addTrigger.waitForClickable({ timeout: 5_000 });
  988. await addTrigger.click();
  989. const launcher = await $('[data-state="active"] [data-side-pane-open-tab-item="terminal"]');
  990. await launcher.waitForClickable({ timeout: 5_000 });
  991. await launcher.click();
  992. }
  993. count += 1;
  994. await browser.waitUntil(async () => (await readTabCount()) === count, {
  995. timeout: 10_000,
  996. timeoutMsg: `Side Pane Tab 数量未增加到 ${count}`,
  997. });
  998. }
  999. }
  1000. async function readTabCount(): Promise<number> {
  1001. return browser.execute(
  1002. (tabSelector) => document.querySelectorAll(tabSelector).length,
  1003. TAB_SELECTOR,
  1004. );
  1005. }
  1006. async function ensureSidePaneExpanded(): Promise<void> {
  1007. // Side Pane 收起后仍保留 DOM,不能把标签栏存在当作已展开;等待实际面板显示后再操作。
  1008. const isExpanded = () =>
  1009. browser.execute(() => {
  1010. const frame = document.querySelector('[data-workspace-side-frame="true"]');
  1011. const panel = frame?.parentElement;
  1012. return Boolean(
  1013. panel &&
  1014. panel.getBoundingClientRect().width > 100 &&
  1015. getComputedStyle(panel).opacity === "1",
  1016. );
  1017. });
  1018. // 展开动画尚未完成时不能再次切换;只有 WorkspaceHeader 中的展开按钮才触发打开。
  1019. const toggle = await $(
  1020. `[data-testid="${TID_WORKSPACE_HEADER}"] [data-testid="${TID_SIDE_PANE_TOGGLE}"]`,
  1021. );
  1022. if (await toggle.isExisting()) {
  1023. await toggle.waitForClickable({ timeout: 10_000 });
  1024. await toggle.click();
  1025. }
  1026. await browser.waitUntil(isExpanded, { timeout: 10_000, timeoutMsg: "Side Pane 未实际展开" });
  1027. }
  1028. async function setTabsViewportWidth(widthPx: number): Promise<void> {
  1029. await browser.execute(
  1030. (viewportSelector, width) => {
  1031. const viewport = document.querySelector<HTMLElement>(viewportSelector);
  1032. if (!viewport) throw new Error("Missing Side Pane tabs viewport");
  1033. viewport.style.flex = `0 0 ${width}px`;
  1034. viewport.style.width = `${width}px`;
  1035. },
  1036. VIEWPORT_SELECTOR,
  1037. widthPx,
  1038. );
  1039. await browser.pause(150);
  1040. }
  1041. async function readTabStripMetrics(): Promise<TabStripMetrics> {
  1042. return browser.execute(
  1043. (tabSelector, viewportSelector, contentSelector, addSelector) => {
  1044. const viewport = document.querySelector<HTMLElement>(viewportSelector);
  1045. const content = document.querySelector<HTMLElement>(contentSelector);
  1046. const addTrigger = document.querySelector<HTMLElement>(addSelector);
  1047. if (!viewport || !content || !addTrigger) {
  1048. throw new Error("Side Pane tab strip metrics target is missing");
  1049. }
  1050. return {
  1051. addInsideViewport: viewport.contains(addTrigger),
  1052. clientWidth: viewport.clientWidth,
  1053. scrollWidth: viewport.scrollWidth,
  1054. tabWidths: Array.from(content.querySelectorAll<HTMLElement>(tabSelector)).map(
  1055. (tab) => tab.getBoundingClientRect().width,
  1056. ),
  1057. };
  1058. },
  1059. TAB_SELECTOR,
  1060. VIEWPORT_SELECTOR,
  1061. CONTENT_SELECTOR,
  1062. ADD_TRIGGER_SELECTOR,
  1063. );
  1064. }
  1065. async function countDisplayedTooltips(): Promise<number> {
  1066. return browser.execute(
  1067. (tooltipSelector) =>
  1068. Array.from(document.querySelectorAll<HTMLElement>(tooltipSelector)).filter(
  1069. (tooltip) => window.getComputedStyle(tooltip).visibility !== "hidden",
  1070. ).length,
  1071. TOOLTIP_SELECTOR,
  1072. );
  1073. }
  1074. async function readIndependentPanelMetrics() {
  1075. return browser.execute(() => {
  1076. const left = document.querySelector<HTMLElement>('[data-workspace-conversation-frame="true"]');
  1077. const right = document.querySelector<HTMLElement>('[data-workspace-side-frame="true"]');
  1078. const header = document.querySelector('[data-testid="workspace-header"]');
  1079. if (!left || !right) return null;
  1080. const a = left.getBoundingClientRect();
  1081. const b = right.getBoundingClientRect();
  1082. return {
  1083. gap: b.left - a.right,
  1084. topDelta: b.top - a.top,
  1085. bottomDelta: b.bottom - a.bottom,
  1086. headerInsideConversation: left.contains(header),
  1087. leftRadius: getComputedStyle(left).borderTopLeftRadius,
  1088. rightRadius: getComputedStyle(right).borderTopLeftRadius,
  1089. };
  1090. });
  1091. }