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

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