general-coding-mode.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import { mkdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. TID_LOGIN_TRIGGER,
  5. TID_SETTINGS_BACK_BUTTON,
  6. TID_SETTINGS_PAGE,
  7. TID_SETTINGS_SECTION_NAV,
  8. TID_SIDE_PANE_TOGGLE,
  9. TID_TASK_SETTINGS_BUTTON,
  10. TID_TERMINAL_TOGGLE,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import { clearAppData, clickTestIdByDom } from "#e2e/helpers/desktop-app";
  14. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  15. // MODE-01/02/03:只操作应用 UI 和本地 PTY,不发送模型请求。
  16. describe("办公与编程模式 M1", () => {
  17. let telemetryFetch: Awaited<ReturnType<typeof browser.electron.mock>>;
  18. before(async () => {
  19. await prepareV4ConversationE2E({ skipProvider: true });
  20. await switchMode("coding");
  21. telemetryFetch = await browser.electron.mock("net", "fetch");
  22. await telemetryFetch.mockResolvedValue({ ok: true, status: 204 });
  23. });
  24. after(async () => {
  25. await browser.electron.restoreAllMocks();
  26. await clearAppData();
  27. });
  28. it("MODE-01 设置页与头像菜单共用偏好,刷新后保留", async () => {
  29. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  30. await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).waitForDisplayed();
  31. // 界面模式已迁到常规设置并更名 office,旧 appearance/general 断言无法进入待测交互。
  32. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "general"));
  33. const select = '[role="combobox"][aria-label="界面模式"]';
  34. await $(select).waitForDisplayed();
  35. await $(select).click();
  36. await clickText('[role="option"]', "办公模式");
  37. await waitForMode("office");
  38. await assertSwitches([
  39. { event_region: "app.setting", previous_ui_mode: "code", ui_mode: "work" },
  40. ]);
  41. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  42. await switchMode("coding");
  43. await switchMode("coding"); // 重选同值不产生切换事件。
  44. await browser.refresh();
  45. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).waitForDisplayed({ timeout: 30000 });
  46. await waitForMode("coding");
  47. expect(await $(`[data-testid="${TID_TERMINAL_TOGGLE}"]`).isExisting()).toBe(true);
  48. const switches = [
  49. { event_region: "app.setting", previous_ui_mode: "code", ui_mode: "work" },
  50. { event_region: "app.profile", previous_ui_mode: "work", ui_mode: "code" },
  51. ];
  52. await assertSwitches(switches); // 刷新恢复偏好不补报。
  53. const openModePage = async () => {
  54. await browser.keys([process.platform === "darwin" ? "Meta" : "Control", "Shift", "o"]);
  55. await $('[data-testid="onboarding-page"]').waitForDisplayed();
  56. await clickText('[data-testid="onboarding-page"] button', "下一步");
  57. await clickText('[data-testid="onboarding-page"] button[aria-pressed] span', "办公模式");
  58. };
  59. await openModePage();
  60. await browser.keys("Escape");
  61. await $('[data-testid="onboarding-page"]').waitForExist({ reverse: true });
  62. await waitForMode("coding");
  63. await assertSwitches(switches); // 卡片草稿及关闭不改变实际界面模式。
  64. await openModePage();
  65. await clickText('[data-testid="onboarding-page"] button', "下一步");
  66. await assertSwitches(switches);
  67. // 偏好页的跳过沿用既有语义:仍应用上一页已选择的界面模式。
  68. await clickText('[data-testid="onboarding-page"] button', "跳过");
  69. await $('[data-testid="onboarding-page"]').waitForExist({ reverse: true });
  70. await waitForMode("office");
  71. const appliedSwitches = [
  72. ...switches,
  73. { event_region: "app.onboarding", previous_ui_mode: "code", ui_mode: "work" },
  74. ];
  75. await assertSwitches(appliedSwitches);
  76. const toggleByShortcut = () =>
  77. browser.keys([process.platform === "darwin" ? "Meta" : "Control", "Shift", "u"]);
  78. // 快捷键虽由常驻引导组件处理,但不是这三个 UI 入口,不能误归到 app.onboarding。
  79. await toggleByShortcut();
  80. await waitForMode("coding");
  81. await assertSwitches(appliedSwitches);
  82. await openModePage();
  83. await toggleByShortcut();
  84. await waitForMode("office");
  85. await clickText('[data-testid="onboarding-page"] button', "下一步");
  86. await clickText('[data-testid="onboarding-page"] button', "跳过");
  87. await $('[data-testid="onboarding-page"]').waitForExist({ reverse: true });
  88. await assertSwitches(appliedSwitches); // 快捷键已应用模式,提交同值不补报。
  89. await switchMode("coding");
  90. await assertSwitches([
  91. ...appliedSwitches,
  92. { event_region: "app.profile", previous_ui_mode: "work", ui_mode: "code" },
  93. ]);
  94. });
  95. it("MODE-02/03 隐藏新建入口,保留已打开审查、终端和 PTY", async () => {
  96. await switchMode("office");
  97. await clickTestIdByDom(TID_SIDE_PANE_TOGGLE);
  98. await $('[data-side-pane-open-tab-item="browser"]').waitForDisplayed();
  99. expect(await $('[data-side-pane-open-tab-item="review"]').isExisting()).toBe(false);
  100. expect(await $('[data-side-pane-open-tab-item="terminal"]').isExisting()).toBe(false);
  101. expect(await $(`[data-testid="${TID_TERMINAL_TOGGLE}"]`).isExisting()).toBe(false);
  102. await switchMode("coding");
  103. await $('[data-side-pane-open-tab-item="review"]').click();
  104. await $('[data-side-pane-tab-id="git"]').waitForDisplayed();
  105. await $("[data-side-pane-add-tab-trigger]").click();
  106. await $('[data-state="active"] [data-side-pane-open-tab-item="terminal"]').click();
  107. await $('[data-side-pane-tab-id^="terminal:"]').waitForDisplayed();
  108. await clickTestIdByDom(TID_TERMINAL_TOGGLE);
  109. await browser.waitUntil(async () => (await terminalHeight()) > 50);
  110. const before = await readTabs();
  111. const terminalId = before.find((tab) => tab.id.startsWith("terminal:"))!.id;
  112. await switchMode("office");
  113. expect(await readTabs()).toEqual(before);
  114. expect(await terminalHeight()).toBeGreaterThan(50);
  115. expect(await $(`[data-testid="${TID_TERMINAL_TOGGLE}"]`).isExisting()).toBe(false);
  116. expect(await $('button[aria-label="新建终端"]').isExisting()).toBe(false);
  117. await $("[data-side-pane-add-tab-trigger]").click();
  118. expect(
  119. await $('[data-state="active"] [data-side-pane-open-tab-item="terminal"]').isExisting(),
  120. ).toBe(false);
  121. expect(await visibleTexts('[role="menuitem"]')).not.toContain("审查");
  122. await $(`[data-side-pane-tab-id="${terminalId}"]`).click();
  123. const terminalInput = $("[data-workspace-side-frame] .xterm-helper-textarea");
  124. await terminalInput.waitForExist();
  125. // 冷启动时 textarea 先于 terminal.create 完成出现;等 shell 提示符后再输入,避免命令被丢弃。
  126. await browser.waitUntil(async () =>
  127. browser.execute(() =>
  128. [...document.querySelectorAll("[data-workspace-side-frame] .xterm-rows > div")].some(
  129. (row) => /[%$#>]\s*$/.test(row.textContent ?? ""),
  130. ),
  131. ),
  132. );
  133. // xterm 的输入 textarea 位于负 z-index,不能作为真实点击目标;点击可见终端后校验焦点。
  134. await $("[data-workspace-side-frame] .xterm-screen").click();
  135. await browser.waitUntil(async () => terminalInput.isFocused());
  136. await browser.keys("printf 'MODE_%s\\n' PTY_ALIVE");
  137. await browser.keys("Enter");
  138. try {
  139. await browser.waitUntil(async () =>
  140. browser.execute(() =>
  141. [...document.querySelectorAll("[data-workspace-side-frame] .xterm-rows > div")].some(
  142. (row) => row.textContent?.trim() === "MODE_PTY_ALIVE",
  143. ),
  144. ),
  145. );
  146. } finally {
  147. const artifactDir = join(process.cwd(), ".e2e-artifacts", "general-coding-mode");
  148. await mkdir(artifactDir, { recursive: true });
  149. await browser.saveScreenshot(join(artifactDir, "general-mode-pty.png"));
  150. }
  151. await browser.execute(() =>
  152. document.querySelector<HTMLElement>('[data-side-pane-tab-id="git"]')!.click(),
  153. );
  154. await browser.waitUntil(
  155. async () => (await readTabs()).find((tab) => tab.id === "git")?.active === true,
  156. );
  157. await switchMode("coding");
  158. await switchMode("office");
  159. expect((await readTabs()).find((tab) => tab.id === "git")?.active).toBe(true);
  160. expect((await readTabs()).map((tab) => tab.id)).toContain(terminalId);
  161. await browser.execute((id) => {
  162. const tab = [...document.querySelectorAll<HTMLElement>("[data-side-pane-tab-id]")].find(
  163. (item) => item.dataset.sidePaneTabId === id,
  164. );
  165. tab?.querySelector<HTMLButtonElement>("button")?.click();
  166. }, terminalId);
  167. await browser.waitUntil(async () => !(await readTabs()).some((tab) => tab.id === terminalId));
  168. expect((await readTabs()).find((tab) => tab.id === "git")?.active).toBe(true);
  169. });
  170. async function readSwitches(): Promise<Array<Record<string, string>>> {
  171. await telemetryFetch.update();
  172. return telemetryFetch.mock.calls.flatMap((call) => {
  173. const [url, init] = call as [unknown, { body?: string } | undefined];
  174. if (!String(url).includes("/event/report") || !init?.body) return [];
  175. const event = JSON.parse(init.body);
  176. if (event.element_name !== "ui_mode_switch") return [];
  177. return [
  178. {
  179. ...event.event_extra_detail,
  180. event_region: event.event_region,
  181. event_type: event.event_type,
  182. },
  183. ];
  184. });
  185. }
  186. async function assertSwitches(expected: Array<Record<string, string>>) {
  187. await browser.waitUntil(async () => (await readSwitches()).length >= expected.length, {
  188. timeout: 15000,
  189. timeoutMsg: "ui_mode_switch 未到达最终上报边界",
  190. });
  191. expect(await readSwitches()).toEqual(expected.map((event) => ({ ...event, event_type: "ck" })));
  192. }
  193. });
  194. async function switchMode(mode: "office" | "coding") {
  195. // Radix 的退出动画期间仍有旧菜单层;等待它卸载,避免下一次点击被当作关闭旧层。
  196. await browser.waitUntil(
  197. async () => !(await $('[data-slot="dropdown-menu-content"]').isExisting()),
  198. );
  199. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).waitForDisplayed();
  200. await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).click();
  201. await clickText('[role="menuitem"]', "界面模式");
  202. await clickText('[role="menuitemradio"]', mode === "office" ? "办公模式" : "编程模式");
  203. await browser.keys("Escape");
  204. await waitForMode(mode);
  205. await browser.waitUntil(
  206. async () =>
  207. (await $(`[data-testid="${TID_LOGIN_TRIGGER}"]`).getAttribute("aria-expanded")) === "false",
  208. );
  209. }
  210. async function clickText(selector: string, text: string) {
  211. try {
  212. await browser.waitUntil(
  213. async () =>
  214. browser.execute(
  215. (query, label) => {
  216. const element = [...document.querySelectorAll<HTMLElement>(query)].find(
  217. (item) =>
  218. item.getBoundingClientRect().width > 0 && item.textContent?.trim() === label,
  219. );
  220. if (!element) return false;
  221. element.click();
  222. return true;
  223. },
  224. selector,
  225. text,
  226. ),
  227. { timeout: 10000, timeoutMsg: `未找到 ${text}` },
  228. );
  229. } catch (error) {
  230. const diagnostic = await browser.execute(() => ({
  231. trigger: document.querySelector('[data-testid="login-trigger"]')?.outerHTML,
  232. menus: [...document.querySelectorAll('[role*="menu"]')].map((item) => ({
  233. role: item.getAttribute("role"),
  234. text: item.textContent,
  235. state: item.getAttribute("data-state"),
  236. rect: item.getBoundingClientRect().toJSON(),
  237. })),
  238. bodyPointerEvents: document.body.style.pointerEvents,
  239. }));
  240. throw new Error(`${String(error)}; UI=${JSON.stringify(diagnostic)}`);
  241. }
  242. }
  243. async function waitForMode(mode: string) {
  244. await browser.waitUntil(async () =>
  245. browser.execute((expected) => localStorage.getItem("zcode-interface-mode") === expected, mode),
  246. );
  247. }
  248. async function readTabs() {
  249. return browser.execute(() =>
  250. [...document.querySelectorAll<HTMLElement>("[data-side-pane-tab-id]")].map((tab) => ({
  251. id: tab.dataset.sidePaneTabId!,
  252. active: tab.dataset.state === "active",
  253. })),
  254. );
  255. }
  256. async function terminalHeight() {
  257. return browser.execute(
  258. () =>
  259. document.querySelector("[data-workspace-terminal-frame]")?.getBoundingClientRect().height ??
  260. 0,
  261. );
  262. }
  263. async function visibleTexts(selector: string) {
  264. return browser.execute(
  265. (query) =>
  266. [...document.querySelectorAll<HTMLElement>(query)]
  267. .filter((item) => item.getBoundingClientRect().width > 0)
  268. .map((item) => item.textContent?.trim()),
  269. selector,
  270. );
  271. }