shortcut-settings-realkeys.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. TID_SETTINGS_BACK_BUTTON,
  5. TID_SETTINGS_PAGE,
  6. TID_SETTINGS_SECTION_NAV,
  7. TID_SIDEBAR,
  8. TID_TASK_SETTINGS_BUTTON,
  9. TID_V4_COMPOSER_INPUT,
  10. TID_V4_SESSION_PANE,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. DEFAULT_WORKSPACE,
  15. clearAppData,
  16. clickTestIdByDom,
  17. getE2EAppDataPaths,
  18. quitElectronAppGracefully,
  19. waitForDefaultWorkspaceReady,
  20. waitForWorkspaceApp,
  21. } from "#e2e/helpers/desktop-app";
  22. import { sel } from "#e2e/helpers/selectors";
  23. interface ShortcutSettingsShape {
  24. shortcutBindings?: Record<string, string[]>;
  25. }
  26. /**
  27. * 快捷键设置真实按键 E2E:browser.keys() 走 CDP 真实输入管线(与合成 KeyboardEvent 不同,
  28. * 含修饰键按下顺序、按键释放等真实序列),覆盖用户报告的三个场景:
  29. * 1. 纯 Shift 组合(无 Ctrl/Cmd/Alt)能否录制并生效(SC-04);
  30. * 2. 录制冲突后不按 Escape,直接按第二组组合是否可用(SC-05);
  31. * 3. 录制态收到 IME 组合噪声事件时按 event.code 反查物理键录制(SC-06,合成事件模拟)。
  32. */
  33. describe("快捷键设置真实按键 E2E", () => {
  34. before(async () => {
  35. // 干净基线:清掉上一轮可能残留的 shortcutBindings 覆盖(SC-05/SC-08 依赖默认绑定制造冲突)
  36. await quitElectronAppGracefully();
  37. await writeSettings({
  38. lastWorkspaceSession: [
  39. { kind: "local", workspacePath: DEFAULT_WORKSPACE, workspacePurpose: "project" },
  40. ],
  41. lastActiveTabIndex: 0,
  42. shortcutBindings: {},
  43. });
  44. await browser.reloadSession();
  45. await waitForDefaultWorkspaceReady(30_000);
  46. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30_000);
  47. });
  48. after(async () => {
  49. await browser.electron.restoreAllMocks();
  50. await clearAppData();
  51. });
  52. it("SC-04: 真实按键录制纯 Shift 组合(Shift+F)并生效", async function () {
  53. this.timeout(120_000);
  54. await openShortcutSettings();
  55. await clickTestIdByDom("settings-shortcut-bind-toggleSidebar-0", {
  56. timeout: 15_000,
  57. timeoutMsg: "快捷键列表没有出现 toggleSidebar 行",
  58. });
  59. await realKeys(["Shift", "F"]);
  60. await browser.waitUntil(
  61. async () => {
  62. const settings = await readSettings();
  63. return settings.shortcutBindings?.toggleSidebar?.[0] === "Shift+f";
  64. },
  65. { timeout: 15_000, timeoutMsg: "纯 Shift 组合没有写入 setting.json(录制失败或被拒绝)" },
  66. );
  67. // 主界面真实按键:Shift+F 应切换侧栏
  68. await backToWorkspace();
  69. await realKeys(["Shift", "F"]);
  70. await $(sel(TID_SIDEBAR)).waitForDisplayed({ reverse: true, timeout: 10_000 });
  71. await realKeys(["Shift", "F"]);
  72. await $(sel(TID_SIDEBAR)).waitForDisplayed({ timeout: 10_000 });
  73. });
  74. it("SC-05: 真实按键冲突后不按 Escape,直接输入第二组组合", async function () {
  75. this.timeout(120_000);
  76. await openShortcutSettings();
  77. await clickTestIdByDom("settings-shortcut-bind-findInTask-0", {
  78. timeout: 15_000,
  79. timeoutMsg: "快捷键列表没有出现 findInTask 行",
  80. });
  81. // 第一组:Ctrl+J 被 toggleTerminal 默认占用 → 标红提示
  82. await realKeys(["Control", "j"]);
  83. await $(sel("settings-shortcut-error-findInTask")).waitForDisplayed({ timeout: 10_000 });
  84. // 第二组:不按 Escape 直接输入 Ctrl+E → 应直接录制成功并退出录制态
  85. await realKeys(["Control", "e"]);
  86. await browser.waitUntil(
  87. async () => {
  88. const settings = await readSettings();
  89. return settings.shortcutBindings?.findInTask?.[0] === "CmdOrCtrl+e";
  90. },
  91. {
  92. timeout: 15_000,
  93. timeoutMsg: "冲突后直接输入第二组组合没有写入 setting.json(录制态没有续上)",
  94. },
  95. );
  96. await $(sel("settings-shortcut-error-findInTask")).waitForDisplayed({
  97. reverse: true,
  98. timeout: 5_000,
  99. });
  100. });
  101. it("SC-06: 录制态收到 IME 组合事件(isComposing)仍按 event.code 录制", async function () {
  102. this.timeout(90_000);
  103. await openShortcutSettings();
  104. await clickTestIdByDom("settings-shortcut-bind-toggleSidePane-0", {
  105. timeout: 15_000,
  106. timeoutMsg: "快捷键列表没有出现 toggleSidePane 行",
  107. });
  108. // 中文 IME 焦点落在可编辑元素时,Shift+G 会被吞成组合输入,事件只剩 isComposing 标记;
  109. // 录制是显式意图,内核应按 event.code 反查物理键录出 Shift+g
  110. await dispatchKey("Process", "KeyG", { shiftKey: true, isComposing: true });
  111. await browser.waitUntil(
  112. async () => {
  113. const settings = await readSettings();
  114. return settings.shortcutBindings?.toggleSidePane?.[0] === "Shift+g";
  115. },
  116. { timeout: 15_000, timeoutMsg: "IME 组合事件没有按 event.code 录制为 Shift+g" },
  117. );
  118. });
  119. it("SC-07: 纯 Shift+可打印键在可编辑目标内不触发命令、不吞字符(CR-02)", async function () {
  120. this.timeout(120_000);
  121. await openShortcutSettings();
  122. await clickTestIdByDom("settings-shortcut-bind-toggleSidePane-0", {
  123. timeout: 15_000,
  124. timeoutMsg: "快捷键列表没有出现 toggleSidePane 行",
  125. });
  126. await realKeys(["Shift", "G"]);
  127. await browser.waitUntil(
  128. async () => {
  129. const settings = await readSettings();
  130. return settings.shortcutBindings?.toggleSidePane?.[0] === "Shift+g";
  131. },
  132. { timeout: 15_000, timeoutMsg: "纯 Shift 组合没有写入 setting.json" },
  133. );
  134. await backToWorkspace();
  135. // 焦点进聊天输入框(contenteditable):按 Shift+G 应输入大写 G,
  136. // 且不得触发 toggleSidePane(侧面板保持收起)——否则用户打不出大写字母
  137. await clickTestIdByDom(TID_V4_COMPOSER_INPUT, {
  138. timeout: 15_000,
  139. timeoutMsg: "没有找到聊天输入框",
  140. });
  141. await realKeys(["Shift", "G"]);
  142. await browser.waitUntil(
  143. async () => {
  144. const text = await $(sel(TID_V4_COMPOSER_INPUT)).getText();
  145. return text.includes("G");
  146. },
  147. { timeout: 10_000, timeoutMsg: "可编辑目标内 Shift+G 的字符被快捷键吞掉" },
  148. );
  149. expect(await $(sel(TID_V4_SESSION_PANE)).isDisplayed()).toBe(false);
  150. });
  151. it("SC-08: 抢绑 menu 通道默认键后原 accelerator 摘除,按键只触发新 owner(CR-03)", async function () {
  152. this.timeout(120_000);
  153. await openShortcutSettings();
  154. await clickTestIdByDom("settings-shortcut-bind-findInTask-0", {
  155. timeout: 15_000,
  156. timeoutMsg: "快捷键列表没有出现 findInTask 行",
  157. });
  158. // Ctrl+N 被 newTask(menu 通道)默认占用 → 标红 + 「仍要绑定」抢绑
  159. await realKeys(["Control", "n"]);
  160. await $(sel("settings-shortcut-error-findInTask")).waitForDisplayed({ timeout: 10_000 });
  161. await clickTestIdByDom("settings-shortcut-steal-findInTask");
  162. await browser.waitUntil(
  163. async () => {
  164. const settings = await readSettings();
  165. return (
  166. settings.shortcutBindings?.findInTask?.[0] === "CmdOrCtrl+n" &&
  167. settings.shortcutBindings?.newTask?.length === 0
  168. );
  169. },
  170. {
  171. timeout: 15_000,
  172. timeoutMsg: "抢绑后 findInTask 未绑上 CmdOrCtrl+n 或 newTask 未清成显式空数组",
  173. },
  174. );
  175. await backToWorkspace();
  176. const countWorkspaceItems = async () =>
  177. await browser.execute(
  178. () => document.querySelectorAll('[data-testid^="workspace-item-"]').length,
  179. );
  180. const before = await countWorkspaceItems();
  181. // 修复前:main 侧 ?? fallback 让 newTask 默认 accelerator 复活,Ctrl+N 同时触发
  182. // 菜单 newTask(新建任务)与 renderer findInTask(查找弹窗);修复后只触发后者
  183. await realKeys(["Control", "n"]);
  184. await browser.waitUntil(async () => await $('[role="dialog"]').isExisting(), {
  185. timeout: 10_000,
  186. timeoutMsg: "Ctrl+N 没有触发 findInTask 查找弹窗",
  187. });
  188. await browser.keys(["Escape"]);
  189. expect(await countWorkspaceItems()).toBe(before);
  190. });
  191. it("SC-09: composer 作用域改绑——裸 Enter 换行不发送,CmdOrCtrl+Enter 发送(spec §12)", async function () {
  192. this.timeout(180_000);
  193. // 设置页把 composerSend 录制为 CmdOrCtrl+Enter(真实按键走录制器)
  194. await openShortcutSettings();
  195. await clickTestIdByDom("settings-shortcut-bind-composerSend-0", {
  196. timeout: 15_000,
  197. timeoutMsg: "快捷键列表没有出现 composerSend 行",
  198. });
  199. await realKeys(["Control", "Enter"]);
  200. await browser.waitUntil(
  201. async () => {
  202. const settings = await readSettings();
  203. return settings.shortcutBindings?.composerSend?.[0] === "CmdOrCtrl+Enter";
  204. },
  205. { timeout: 15_000, timeoutMsg: "composerSend 没有录制为 CmdOrCtrl+Enter" },
  206. );
  207. // 落盘 ≠ renderer 生效表已刷新:SettingsChanged 广播有亚秒级异步窗口,
  208. // 立即回主界面按键会踩进旧键位窗口误发送(曾致本用例偶发失败);显式等窗口过去。
  209. await new Promise((resolve) => setTimeout(resolve, 2_000));
  210. await backToWorkspace();
  211. await clickTestIdByDom(TID_V4_COMPOSER_INPUT, {
  212. timeout: 15_000,
  213. timeoutMsg: "没有找到聊天输入框",
  214. });
  215. // Bugfix: clickTestIdByDom 是 JS element.click(),对 contenteditable 不转移焦点;
  216. // 焦点不在 composer 时 keys 输入会落空(本用例曾因此误判"裸 Enter 吞草稿")。显式聚焦。
  217. await browser.execute((inputTestId) => {
  218. (document.querySelector(`[data-testid="${inputTestId}"]`) as HTMLElement | null)?.focus();
  219. }, TID_V4_COMPOSER_INPUT);
  220. await browser.keys("sc9");
  221. // 裸 Enter:composerSend 已改绑走 → 回退换行,不发送(草稿保留)
  222. await realKeys(["Enter"]);
  223. await browser.waitUntil(
  224. async () => {
  225. const text = await $(sel(TID_V4_COMPOSER_INPUT)).getText();
  226. return text.includes("sc9");
  227. },
  228. { timeout: 10_000, timeoutMsg: "改绑后裸 Enter 误触发送或吞掉了草稿" },
  229. );
  230. // CmdOrCtrl+Enter:命中改绑后的发送 → 草稿清空
  231. await realKeys(["Control", "Enter"]);
  232. await browser.waitUntil(
  233. async () => {
  234. const draft = await $(sel(TID_V4_COMPOSER_INPUT)).getText();
  235. return !draft.includes("sc9");
  236. },
  237. { timeout: 15_000, timeoutMsg: "CmdOrCtrl+Enter 没有触发发送(草稿未清空)" },
  238. );
  239. });
  240. it("SC-10: 全部恢复默认有二次确认——取消保留覆盖,确认清空(spec §12.4)", async function () {
  241. this.timeout(120_000);
  242. await openShortcutSettings();
  243. // 前序用例留下的覆盖仍在,按钮可用;点击后弹全局确认弹窗(ConfirmDialogHost)
  244. await clickTestIdByDom("settings-shortcut-reset-all", {
  245. timeout: 15_000,
  246. timeoutMsg: "没有找到「全部恢复默认」按钮",
  247. });
  248. await $(sel("confirm-dialog-confirm")).waitForDisplayed({ timeout: 10_000 });
  249. // 取消(Esc):覆盖保留
  250. await browser.keys(["Escape"]);
  251. await $(sel("confirm-dialog-confirm")).waitForDisplayed({ reverse: true, timeout: 10_000 });
  252. const settingsAfterCancel = await readSettings();
  253. expect(Object.keys(settingsAfterCancel.shortcutBindings ?? {}).length).toBeGreaterThan(0);
  254. // 再点并确认:shortcutBindings 清空,全部命令回到默认绑定
  255. await clickTestIdByDom("settings-shortcut-reset-all", {
  256. timeout: 15_000,
  257. timeoutMsg: "确认弹窗关闭后没找到「全部恢复默认」按钮",
  258. });
  259. await clickTestIdByDom("confirm-dialog-confirm", {
  260. timeout: 10_000,
  261. timeoutMsg: "没有出现恢复默认确认弹窗",
  262. });
  263. await browser.waitUntil(
  264. async () => {
  265. const settings = await readSettings();
  266. return Object.keys(settings.shortcutBindings ?? {}).length === 0;
  267. },
  268. { timeout: 15_000, timeoutMsg: "确认后 shortcutBindings 没有被清空" },
  269. );
  270. });
  271. it("SC-11: 工具条三键转正为可配置命令——列表可见、改绑落盘(spec §12.6)", async function () {
  272. this.timeout(120_000);
  273. await openShortcutSettings();
  274. // 三条工具条命令出现在列表(数据驱动,含「全局」作用域标注)
  275. for (const commandId of ["openModelMenu", "cycleSessionMode", "cycleThoughtLevel"]) {
  276. await clickTestIdByDom(`settings-shortcut-bind-${commandId}-0`, {
  277. timeout: 15_000,
  278. timeoutMsg: `快捷键列表没有出现 ${commandId} 行`,
  279. });
  280. // 进入录制态后 Escape 取消,保持循环继续
  281. await realKeys(["Escape"]);
  282. }
  283. // 把 openModelMenu 改绑为 Ctrl+Shift+Y:win 上录制器平台归一产出 "CmdOrCtrl+Shift+y"
  284. // (注意不能选 Ctrl+Y——归一后撞黑名单的 redo "CmdOrCtrl+y" 会被拒)
  285. await clickTestIdByDom("settings-shortcut-bind-openModelMenu-0", {
  286. timeout: 15_000,
  287. timeoutMsg: "没有找到 openModelMenu 绑定入口",
  288. });
  289. await realKeys(["Control", "Shift", "y"]);
  290. await browser.waitUntil(
  291. async () => {
  292. const settings = await readSettings();
  293. return settings.shortcutBindings?.openModelMenu?.[0] === "CmdOrCtrl+Shift+y";
  294. },
  295. { timeout: 15_000, timeoutMsg: "openModelMenu 没有录制为 CmdOrCtrl+Shift+y" },
  296. );
  297. });
  298. });
  299. /** 平台主修饰键感知的真实按键(macOS 用 Command)。 */
  300. async function realKeys(keys: string[]) {
  301. const isMac = await browser.execute(() => /Mac|iPhone|iPad/.test(navigator.userAgent));
  302. const mapped = keys.map((key) => (key === "Control" && isMac ? "Command" : key));
  303. await browser.keys(mapped as never);
  304. }
  305. /** 合成 keydown 直发 window(SC-06 模拟 IME 噪声事件形态)。 */
  306. async function dispatchKey(
  307. key: string,
  308. code: string,
  309. modifiers: { shiftKey?: boolean; isComposing?: boolean },
  310. ) {
  311. await browser.execute(
  312. (eventKey, eventCode, shiftKey, isComposing) => {
  313. window.dispatchEvent(
  314. new KeyboardEvent("keydown", {
  315. key: eventKey,
  316. code: eventCode,
  317. shiftKey,
  318. isComposing,
  319. bubbles: true,
  320. cancelable: true,
  321. }),
  322. );
  323. },
  324. key,
  325. code,
  326. modifiers.shiftKey ?? false,
  327. modifiers.isComposing ?? false,
  328. );
  329. }
  330. async function openShortcutSettings() {
  331. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  332. timeout: 15_000,
  333. timeoutMsg: "没有找到设置入口按钮",
  334. });
  335. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15_000 });
  336. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "shortcuts"), {
  337. timeout: 15_000,
  338. timeoutMsg: "设置页没有出现快捷键分区入口",
  339. });
  340. }
  341. async function backToWorkspace() {
  342. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  343. timeout: 15_000,
  344. timeoutMsg: "设置页没有出现返回按钮",
  345. });
  346. }
  347. async function writeSettings(patch: Record<string, unknown>) {
  348. const settingsFile = join(getE2EAppDataPaths().appDataDir, "setting.json");
  349. await mkdir(join(getE2EAppDataPaths().appDataDir), { recursive: true });
  350. const current = await readSettings();
  351. await writeFile(settingsFile, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  352. }
  353. async function readSettings(): Promise<ShortcutSettingsShape> {
  354. try {
  355. return JSON.parse(
  356. await readFile(join(getE2EAppDataPaths().appDataDir, "setting.json"), "utf-8"),
  357. ) as ShortcutSettingsShape;
  358. } catch {
  359. return {};
  360. }
  361. }