composer-voice-input.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. import { readFile, readdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. TID_V4_COMPOSER_INPUT,
  5. TID_V4_COMPOSER_SEND,
  6. TID_V4_COMPOSER_VOICE_INPUT,
  7. TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE,
  8. TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS,
  9. TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE,
  10. TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH,
  11. TID_V4_COMPOSER_VOICE_WAVEFORM,
  12. } from "@zcode/shared/test-ids";
  13. import { readSettings, seedSettings, waitForDefaultWorkspaceReady } from "#e2e/helpers/desktop-app";
  14. import {
  15. startAsrFrameDroppingProxy,
  16. type AsrMockScenario,
  17. type AsrMockSession,
  18. } from "#e2e/helpers/asr-mock-server";
  19. import { reloadElectronSessionSafely } from "#e2e/helpers/e2e-electron-reload";
  20. import {
  21. clickV4Send,
  22. getV4Messages,
  23. getV4PaneSnapshot,
  24. pasteV4ComposerFileAttachment,
  25. waitForV4RowAttachments,
  26. selectV4TaskById,
  27. setV4ComposerText,
  28. startNewV4Draft,
  29. waitForV4Pane,
  30. } from "#e2e/helpers/v4-conversation";
  31. import { getToastMessages, waitForToastContaining } from "#e2e/helpers/conversation-session-toast";
  32. // 规格:docs/chat/composer-voice-input.md。麦克风由 wdio appArgs 的 Chromium 假设备提供(持续正弦音)。
  33. type LexicalInputE2EElement = HTMLElement & {
  34. __zcodeLexicalInputE2E?: {
  35. getText: () => string;
  36. focus: () => void;
  37. setText: (text: string) => void;
  38. };
  39. };
  40. const PREFIX = "前缀";
  41. const byId = (id: string) => $(`[data-testid="${id}"]`);
  42. // 替身由 wdio beforeSession 在 Electron 启动前启动(prepareVoiceInputFixture)。
  43. function mockOrigin(): string {
  44. const value = process.env.ZCODE_E2E_ASR_MOCK_URL;
  45. if (!value) throw new Error("缺少语音输入 ASR 替身");
  46. return value;
  47. }
  48. async function resetMock(scenario: AsrMockScenario) {
  49. await fetch(`${mockOrigin()}/__e2e/asr/reset`, {
  50. method: "POST",
  51. body: JSON.stringify(scenario),
  52. });
  53. }
  54. async function mockState(): Promise<{
  55. ticketRequests: Array<{ authorization?: string; body: string }>;
  56. sessions: AsrMockSession[];
  57. }> {
  58. return (await (await fetch(`${mockOrigin()}/__e2e/asr/state`)).json()) as never;
  59. }
  60. async function voiceState(): Promise<string | null> {
  61. const button = await byId(TID_V4_COMPOSER_VOICE_INPUT);
  62. return (await button.isExisting()) ? button.getAttribute("data-voice-state") : null;
  63. }
  64. async function waitForVoiceState(state: string, timeoutMsg: string) {
  65. await browser.waitUntil(async () => (await voiceState()) === state, {
  66. timeout: 15_000,
  67. timeoutMsg: `${timeoutMsg}; latest=${await voiceState()}`,
  68. });
  69. }
  70. async function editorText(): Promise<string> {
  71. return browser.execute((id) => {
  72. const root = document.querySelector<LexicalInputE2EElement>(`[data-testid="${id}"]`);
  73. return root?.__zcodeLexicalInputE2E?.getText() ?? "";
  74. }, TID_V4_COMPOSER_INPUT);
  75. }
  76. /** 每个用例从固定草稿开始,光标在末尾,输入框保持焦点。 */
  77. async function resetEditor() {
  78. await browser.execute(
  79. (id, text) => {
  80. const bridge = document.querySelector<LexicalInputE2EElement>(
  81. `[data-testid="${id}"]`,
  82. )?.__zcodeLexicalInputE2E;
  83. bridge?.setText(text);
  84. bridge?.focus();
  85. },
  86. TID_V4_COMPOSER_INPUT,
  87. PREFIX,
  88. );
  89. await browser.waitUntil(async () => (await editorText()) === PREFIX, {
  90. timeout: 5_000,
  91. timeoutMsg: "没有重置输入框",
  92. });
  93. }
  94. async function waitForEditorText(expected: string, timeoutMsg: string) {
  95. await browser.waitUntil(async () => (await editorText()) === expected, {
  96. timeout: 10_000,
  97. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(await editorText())}`,
  98. });
  99. }
  100. async function runtimeLogText(): Promise<string> {
  101. const logs = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR);
  102. if (!logs) throw new Error("缺少 worker 运行时日志目录");
  103. const names = (await readdir(logs)).filter((name) => name.endsWith(".log")).sort();
  104. return (await Promise.all(names.map((name) => readFile(join(logs, name), "utf8")))).join("\n");
  105. }
  106. /** 渲染层记录的最后一次采集总字节数(含 flush 出的尾块),来自运行时日志。 */
  107. async function lastCapturedBytes(): Promise<number | null> {
  108. const text = await runtimeLogText();
  109. const matches = [...text.matchAll(/\[voice-input\] capture stopped .*?"bytes":(\d+)/gu)];
  110. return matches.length > 0 ? Number(matches.at(-1)![1]) : null;
  111. }
  112. /** 时间线里已发送的用户消息文本。 */
  113. async function sentUserMessages(): Promise<string[]> {
  114. return (await getV4Messages("user")).map((message) => message.text);
  115. }
  116. async function releaseHeldCompletions() {
  117. await fetch(`${mockOrigin()}/__e2e/asr/release`, { method: "POST" });
  118. }
  119. /** 在新草稿里发送一条消息,得到一个真实会话并返回其 id。 */
  120. async function createSession(seed: string): Promise<string> {
  121. await startNewV4Draft();
  122. await setV4ComposerText(seed);
  123. await clickV4Send();
  124. await waitForV4Pane(
  125. (snapshot) => Boolean(snapshot.sessionId) && snapshot.sessionId !== "draft",
  126. `发送 ${seed} 后没有生成会话`,
  127. 30_000,
  128. );
  129. return (await getV4PaneSnapshot()).sessionId!;
  130. }
  131. async function mockMicrophonePermission(status: "granted" | "denied") {
  132. const mock = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
  133. await mock.mockReturnValue(status);
  134. }
  135. /** 系统权限被拒时点击麦克风,等待引导浮层出现 */
  136. async function openPermissionGuide() {
  137. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  138. await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).waitForDisplayed({
  139. timeout: 5_000,
  140. timeoutMsg: "权限被拒后没有显示引导浮层",
  141. });
  142. }
  143. async function startRecording() {
  144. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  145. await waitForVoiceState("recording", "点击麦克风后没有进入录音状态");
  146. }
  147. describe("Composer 语音输入", () => {
  148. let originalSettings: Awaited<ReturnType<typeof readSettings>>;
  149. before(async () => {
  150. await waitForDefaultWorkspaceReady(30_000);
  151. originalSettings = await readSettings();
  152. await seedSettings({ locale: "zh-CN", localePreference: "zh-CN" });
  153. await browser.refresh();
  154. await waitForDefaultWorkspaceReady(30_000);
  155. });
  156. beforeEach(async () => {
  157. await resetMock({ kind: "normal", partial: "模拟临时", final: "你好世界" });
  158. await mockMicrophonePermission("granted");
  159. await byId(TID_V4_COMPOSER_VOICE_INPUT).waitForDisplayed({
  160. timeout: 15_000,
  161. timeoutMsg: "已登录桌面端没有显示语音输入按钮",
  162. });
  163. await resetEditor();
  164. });
  165. afterEach(async () => {
  166. await browser.keys("Escape");
  167. await browser.electron.restoreAllMocks();
  168. });
  169. after(async () => {
  170. await seedSettings(originalSettings);
  171. });
  172. it("VI-01: 识别结果直接写入光标处,结束后由最终文本替换且不自动发送", async () => {
  173. await startRecording();
  174. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入光标处");
  175. // 录音中显示音量点阵;假设备持续输出正弦音,点阵应出现有音量的点。
  176. const waveform = await byId(TID_V4_COMPOSER_VOICE_WAVEFORM);
  177. await waveform.waitForDisplayed({ timeout: 5_000, timeoutMsg: "录音中没有显示音量点阵" });
  178. await browser.waitUntil(
  179. async () => Number(await waveform.getAttribute("data-voice-active-dots")) > 0,
  180. { timeout: 5_000, timeoutMsg: "音量点阵没有随麦克风输入变化" },
  181. );
  182. const visual = await browser.execute(
  183. (buttonId, waveformId) => {
  184. const button = document.querySelector<HTMLElement>(`[data-testid="${buttonId}"]`)!;
  185. const wave = document.querySelector<HTMLElement>(`[data-testid="${waveformId}"]`)!;
  186. // 共享 Button 基础类本身带 aria-invalid:border-destructive,不能按类名判断;比较实际渲染颜色。
  187. const colorOf = (className: string) => {
  188. const probe = document.createElement("span");
  189. probe.className = className;
  190. document.body.append(probe);
  191. const color = getComputedStyle(probe).backgroundColor;
  192. probe.remove();
  193. return color;
  194. };
  195. const iconBlue = colorOf("bg-voice-input-wave");
  196. const accent = colorOf("bg-voice-input-surface");
  197. return {
  198. expandTransition: getComputedStyle(wave.parentElement!.parentElement!).transitionProperty,
  199. destructiveColors: [colorOf("bg-destructive"), colorOf("bg-destructive-surface")],
  200. buttonBackground: getComputedStyle(button).backgroundColor,
  201. stopColor: getComputedStyle(button.querySelector("span")!).backgroundColor,
  202. iconBlue,
  203. accent,
  204. pillBackground: getComputedStyle(button.parentElement!).backgroundColor,
  205. barColor: getComputedStyle(wave.firstElementChild!).backgroundColor,
  206. waveWidth: wave.getBoundingClientRect().width,
  207. buttonWidth: button.getBoundingClientRect().width,
  208. };
  209. },
  210. TID_V4_COMPOSER_VOICE_INPUT,
  211. TID_V4_COMPOSER_VOICE_WAVEFORM,
  212. );
  213. // 停止按钮是 ghost(点击后鼠标仍在按钮上,可能是 hover 底色),不使用 destructive 色;
  214. // 点阵不超过按钮宽度的 3 倍。
  215. expect(visual.destructiveColors).not.toContain(visual.buttonBackground);
  216. // 胶囊底色与波形、停止方块使用 DESIGN.md 的 sky 色系语音输入 token。
  217. expect(visual.stopColor).toBe(visual.iconBlue);
  218. expect(visual.barColor).toBe(visual.iconBlue);
  219. expect(visual.pillBackground).toBe(visual.accent);
  220. expect(visual.waveWidth).toBeLessThanOrEqual(visual.buttonWidth * 3);
  221. // 胶囊展开带宽度过渡,而不是直接出现。
  222. expect(visual.expandTransition).toContain("grid-template-columns");
  223. // 采集超过 300ms 才不会被判为说话时间太短。
  224. await browser.pause(1_000);
  225. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  226. await waitForVoiceState("idle", "识别完成后没有回到空闲");
  227. // 最终文本替换临时结果,而不是追加;输入框仍有内容说明没有自动发送。
  228. await waitForEditorText(`${PREFIX}你好世界`, "最终文本没有替换临时结果");
  229. expect(await byId(TID_V4_COMPOSER_VOICE_WAVEFORM).isExisting()).toBe(false);
  230. const state = await mockState();
  231. expect(state.ticketRequests).toHaveLength(1);
  232. expect(state.ticketRequests[0]!.authorization).toMatch(/^Bearer \S+/u);
  233. expect(JSON.parse(state.ticketRequests[0]!.body)).toEqual({ mode: "realtime" });
  234. const session = state.sessions[0]!;
  235. expect(session.start).toMatchObject({
  236. type: "start",
  237. audio: { encoding: "pcm_s16le", sample_rate: 16000, channels: 1 },
  238. language: "zh-CN",
  239. });
  240. // 假设备持续输出音频;至少 1 秒 16kHz PCM16。
  241. expect(session.audioBytes).toBeGreaterThan(16_000);
  242. expect(session.audioBytes % 2).toBe(0);
  243. expect(session.controls).toEqual(["finish"]);
  244. // 尾块回归:停止时 flush 出的不足 100ms 音频也要发出,且全部在 finish 之前到达服务端。
  245. let capturedBytes: number | null = null;
  246. await browser.waitUntil(
  247. async () => {
  248. capturedBytes = await lastCapturedBytes();
  249. return capturedBytes !== null;
  250. },
  251. { timeout: 5_000, timeoutMsg: "运行时日志里没有采集统计" },
  252. );
  253. expect(session.audioBytesAtFinish).toBe(capturedBytes);
  254. expect(session.audioAfterFinish).toBe(0);
  255. });
  256. it("VI-02: 录音中按 Escape 取消并删除语音文字", async () => {
  257. await startRecording();
  258. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  259. await browser.keys("Escape");
  260. await waitForVoiceState("idle", "Escape 后没有回到空闲");
  261. await browser.waitUntil(async () => (await mockState()).sessions[0]?.closed === true, {
  262. timeout: 5_000,
  263. timeoutMsg: "取消后服务端连接没有关闭",
  264. });
  265. expect((await mockState()).sessions[0]!.controls).toEqual(["cancel"]);
  266. expect(await editorText()).toBe(PREFIX);
  267. });
  268. it("VI-06: 录音中用户开始输入时与点击停止一致,最终文本替换语音文字且保留用户输入", async () => {
  269. await startRecording();
  270. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  271. // 采集超过 300ms 才不会被判为说话时间太短。
  272. await browser.pause(1_000);
  273. await browser.keys("abc");
  274. await waitForVoiceState("idle", "用户输入后语音输入没有结束");
  275. // 走 finish 而不是 cancel:拿到服务端最终文本替换临时结果,用户在其后输入的字符保留。
  276. expect((await mockState()).sessions[0]!.controls).toEqual(["finish"]);
  277. await waitForEditorText(`${PREFIX}你好世界abc`, "最终文本没有替换临时结果或用户输入丢失");
  278. });
  279. it("VI-07: 录音中点击发送时先等最终文本,再发送最终文本", async () => {
  280. await startRecording();
  281. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  282. await browser.pause(1_000);
  283. await (await byId(TID_V4_COMPOSER_SEND)).click();
  284. let sent: string[] = [];
  285. await browser.waitUntil(
  286. async () => {
  287. sent = await sentUserMessages();
  288. return sent.some((text) => text.includes(`${PREFIX}你好世界`));
  289. },
  290. {
  291. timeout: 15_000,
  292. timeoutMsg: `发送的消息不是语音识别的最终文本; sent=${JSON.stringify(sent)}`,
  293. },
  294. );
  295. expect((await mockState()).sessions[0]!.controls).toEqual(["finish"]);
  296. expect(sent.some((text) => text.includes("模拟临时"))).toBe(false);
  297. });
  298. it("VI-08: 等待识别结果期间切换会话,中止本次发送,不串会话", async () => {
  299. const sessionA = await createSession("VI08-A");
  300. const sessionB = await createSession("VI08-B");
  301. // B 有独立草稿:切回 B 时会恢复它。
  302. await setV4ComposerText("B草稿");
  303. await selectV4TaskById(sessionA);
  304. const userMessagesA = await sentUserMessages();
  305. await resetMock({
  306. kind: "normal",
  307. partial: "模拟临时",
  308. final: "切换后不应出现",
  309. holdFinal: true,
  310. });
  311. await resetEditor();
  312. await startRecording();
  313. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  314. await browser.pause(1_000);
  315. await (await byId(TID_V4_COMPOSER_SEND)).click();
  316. // 服务端已收到 finish,但最终结果被扣住:发送正在等待识别。
  317. await browser.waitUntil(
  318. async () => (await mockState()).sessions[0]?.controls.includes("finish") === true,
  319. { timeout: 5_000, timeoutMsg: "点击发送后没有发出 finish" },
  320. );
  321. await selectV4TaskById(sessionB);
  322. await releaseHeldCompletions();
  323. await browser.pause(1_500);
  324. // 旧提交恢复后识别出目标已变化并中止(不靠后续守卫碰巧拦下)。
  325. expect(await runtimeLogText()).toContain("[voice-input] submit aborted");
  326. // B:草稿仍在,没有收到 A 的内容,也没有被发送清空。
  327. expect(await editorText()).toBe("B草稿");
  328. expect(await sentUserMessages()).toEqual(
  329. expect.not.arrayContaining([expect.stringContaining("B草稿")]),
  330. );
  331. await selectV4TaskById(sessionA);
  332. // A:切走后没有发生提交;临时语音文字留在 A 的草稿里。先等时间线加载完。
  333. await browser.waitUntil(async () => (await sentUserMessages()).length > 0, {
  334. timeout: 15_000,
  335. timeoutMsg: "切回 A 后时间线没有加载",
  336. });
  337. expect(await sentUserMessages()).toEqual(userMessagesA);
  338. await waitForEditorText(`${PREFIX}模拟临时`, "A 的草稿没有保留临时语音文字");
  339. });
  340. it("VI-09: 首个识别结果前用户已开始输入,最终文本插在录音开始处且不移动光标", async () => {
  341. await resetMock({ kind: "normal", partial: "", final: "你好世界" });
  342. await startRecording();
  343. await browser.pause(1_000);
  344. await browser.keys("abc");
  345. await waitForVoiceState("idle", "用户输入后语音输入没有结束");
  346. await waitForEditorText(`${PREFIX}你好世界abc`, "最终文本没有插在录音开始处");
  347. // 光标仍在用户输入的 abc 之后:继续输入的字符紧跟 abc。
  348. await browser.keys("d");
  349. await waitForEditorText(`${PREFIX}你好世界abcd`, "最终文本写入后光标被移动");
  350. });
  351. it("VI-10: 首个识别结果前用户在录音开始点之前输入,开始点失效,最终文本追加到末尾", async () => {
  352. await resetMock({ kind: "normal", partial: "", final: "你好世界" });
  353. await startRecording();
  354. await browser.pause(1_000);
  355. // 光标移到行首再输入:录音开始点(「前缀」之后)前面的内容变了,旧 offset 不能再用。
  356. // 用 DOM 选区把光标移到行首:macOS 下 WebDriver 发出的 Cmd+← 不会移动 contenteditable 光标。
  357. await browser.execute((id) => {
  358. const root = document.querySelector<HTMLElement>(`[data-testid="${id}"]`)!;
  359. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  360. const first = walker.nextNode();
  361. if (first) window.getSelection()?.collapse(first, 0);
  362. }, TID_V4_COMPOSER_INPUT);
  363. await browser.pause(100);
  364. await browser.keys("ab");
  365. await waitForVoiceState("idle", "用户输入后语音输入没有结束");
  366. // 不拆开「前缀」,按 spec 追加到末尾;光标仍在用户输入的 ab 之后。
  367. await waitForEditorText(`ab${PREFIX}你好世界`, "开始点失效时最终文本没有追加到末尾");
  368. await browser.keys("c");
  369. await waitForEditorText(`abc${PREFIX}你好世界`, "最终文本写入后光标被移动");
  370. });
  371. it("VI-11: 等待识别期间新增附件,随消息发出并在发送后从输入框清除", async () => {
  372. // 从新草稿开始:之前用例的会话可能仍有进行中的回合,语音消息会进入队列而不出现在时间线上。
  373. await startNewV4Draft();
  374. await resetMock({ kind: "normal", partial: "模拟临时", final: "你好世界", holdFinal: true });
  375. await resetEditor();
  376. await startRecording();
  377. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  378. await browser.pause(1_000);
  379. await (await byId(TID_V4_COMPOSER_SEND)).click();
  380. await browser.waitUntil(
  381. async () => (await mockState()).sessions[0]?.controls.includes("finish") === true,
  382. { timeout: 5_000, timeoutMsg: "点击发送后没有发出 finish" },
  383. );
  384. // 发送正在等待识别:此时新增一个附件,并等它上传就绪。
  385. await pasteV4ComposerFileAttachment("vi11-added.png");
  386. await $("[data-composer-attachment-remove]").waitForExist({
  387. timeout: 15_000,
  388. timeoutMsg: "附件没有出现在输入框",
  389. });
  390. await browser.waitUntil(
  391. async () =>
  392. browser.execute(
  393. () =>
  394. document.querySelector(
  395. '[data-composer-file-attachments-row="true"] [aria-busy="true"]',
  396. ) === null,
  397. ),
  398. { timeout: 15_000, timeoutMsg: "附件没有上传就绪" },
  399. );
  400. await releaseHeldCompletions();
  401. let sent: { id: string | null; text: string } | undefined;
  402. await browser.waitUntil(
  403. async () => {
  404. sent = (await getV4Messages("user")).find((message) =>
  405. message.text.includes(`${PREFIX}你好世界`),
  406. );
  407. return sent !== undefined;
  408. },
  409. { timeout: 15_000, timeoutMsg: "没有发出语音最终文本" },
  410. );
  411. // 附件属于本次发送:消息带上它,发送后输入框里不再残留。
  412. expect(await waitForV4RowAttachments(15_000, ["vi11-added.png"])).toContain("vi11-added.png");
  413. await browser.waitUntil(
  414. async () => !(await $("[data-composer-attachment-remove]").isExisting()),
  415. { timeout: 5_000, timeoutMsg: "发送后附件仍残留在输入框里" },
  416. );
  417. });
  418. it("VI-12: 用户在语音文字后追加输入再按 Escape,只删除语音文字,保留用户输入", async () => {
  419. await resetMock({ kind: "normal", partial: "模拟临时", final: "迟到结果", holdFinal: true });
  420. await startRecording();
  421. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  422. await browser.pause(1_000);
  423. // 光标在语音文字末尾:追加的字符进入同一个文本节点,录音进入识别中。
  424. await browser.keys("abc");
  425. await waitForEditorText(`${PREFIX}模拟临时abc`, "用户输入没有写入");
  426. await waitForVoiceState("finishing", "用户输入后没有进入识别中");
  427. await browser.keys("Escape");
  428. await waitForVoiceState("idle", "Escape 后没有回到空闲");
  429. await waitForEditorText(`${PREFIX}abc`, "Escape 后语音文字没有删除,或用户输入丢失");
  430. await browser.waitUntil(
  431. async () => (await mockState()).sessions[0]?.controls.includes("cancel") === true,
  432. { timeout: 5_000, timeoutMsg: "Escape 后服务端没有收到 cancel" },
  433. );
  434. // 迟到的最终结果不能再写回输入框。
  435. await releaseHeldCompletions();
  436. await browser.pause(1_000);
  437. expect(await editorText()).toBe(`${PREFIX}abc`);
  438. // 光标仍在 abc 之后。
  439. await browser.keys("d");
  440. await waitForEditorText(`${PREFIX}abcd`, "删除语音文字后光标位置不对");
  441. });
  442. it("VI-03: 服务端繁忙时提示稍后再试", async () => {
  443. await resetMock({ kind: "ticket-error", status: 429, errorCode: "rate_limited" });
  444. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  445. await waitForToastContaining("语音识别繁忙,请稍后再试", "限流后没有提示");
  446. await waitForVoiceState("idle", "限流后没有回到空闲");
  447. expect((await mockState()).sessions).toHaveLength(0);
  448. });
  449. it("VI-04: 服务端返回空文本时提示没有识别到内容", async () => {
  450. await resetMock({ kind: "empty-final" });
  451. await startRecording();
  452. await browser.pause(1_000);
  453. const before = await editorText();
  454. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  455. await waitForToastContaining("没有识别到内容", "空结果后没有提示");
  456. expect(await editorText()).toBe(before);
  457. });
  458. it("VI-05: 系统拒绝麦克风权限时显示引导浮层,按钮打开系统麦克风设置", async function () {
  459. if (process.platform === "linux") this.skip();
  460. await browser.electron.restoreAllMocks();
  461. await mockMicrophonePermission("denied");
  462. const openExternal = await browser.electron.mock("shell", "openExternal");
  463. await openExternal.mockResolvedValue(undefined);
  464. await openPermissionGuide();
  465. // 系统权限被拒时不申请 ticket,也不再用 toast 提示。
  466. expect((await mockState()).ticketRequests).toHaveLength(0);
  467. expect((await getToastMessages()).some((message) => message.includes("没有麦克风权限"))).toBe(
  468. false,
  469. );
  470. // 浮层打开不移动焦点:焦点仍在输入框(beforeEach 已聚焦输入框)。
  471. expect(
  472. await browser.execute(
  473. (id) =>
  474. document.querySelector(`[data-testid="${id}"]`)?.contains(document.activeElement) ??
  475. false,
  476. TID_V4_COMPOSER_INPUT,
  477. ),
  478. ).toBe(true);
  479. // 「重新授权」只在 macOS 提供。
  480. expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE).isExisting()).toBe(
  481. process.platform === "darwin",
  482. );
  483. await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS)).click();
  484. const expectedUrl =
  485. process.platform === "darwin"
  486. ? "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"
  487. : "ms-settings:privacy-microphone";
  488. await browser.waitUntil(
  489. async () => {
  490. try {
  491. await expect(openExternal).toHaveBeenCalledWith(expectedUrl);
  492. return true;
  493. } catch {
  494. return false;
  495. }
  496. },
  497. { timeout: 5_000, timeoutMsg: `没有打开 ${expectedUrl}` },
  498. );
  499. // 打开设置后浮层保留,用户返回后还能继续操作。
  500. expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).isDisplayed()).toBe(true);
  501. });
  502. // 打包版会真实执行 tccutil 重置本机 ZCode 的麦克风记录,只在开发版 Electron 上跑(开发版跳过 tccutil)。
  503. describe("macOS 重新授权", () => {
  504. before(function () {
  505. if (process.platform !== "darwin" || process.env.ZCODE_E2E_PACKAGED_APP_PATH?.trim()) {
  506. this.skip();
  507. }
  508. });
  509. it("VI-15: 重置后状态变为未询问,系统弹框允许后关闭浮层并提示已开启", async () => {
  510. await browser.electron.restoreAllMocks();
  511. const status = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
  512. await status.mockReturnValue("denied");
  513. await openPermissionGuide();
  514. // 模拟 tccutil 重置成功:之后读到未询问,系统弹框里用户点「允许」。
  515. await status.mockReturnValue("not-determined");
  516. const ask = await browser.electron.mock("systemPreferences", "askForMediaAccess");
  517. await ask.mockResolvedValue(true);
  518. await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE)).click();
  519. await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).waitForExist({
  520. reverse: true,
  521. timeout: 5_000,
  522. timeoutMsg: "重新授权成功后浮层没有关闭",
  523. });
  524. await waitForToastContaining("已开启麦克风权限", "重新授权成功后没有提示");
  525. await expect(ask).toHaveBeenCalledWith("microphone");
  526. // 不自动开始录音。
  527. expect(await voiceState()).toBe("idle");
  528. expect((await mockState()).ticketRequests).toHaveLength(0);
  529. });
  530. it("VI-16: 重置后当前进程仍读到 denied,浮层改为需要重启", async () => {
  531. await browser.electron.restoreAllMocks();
  532. await mockMicrophonePermission("denied");
  533. const ask = await browser.electron.mock("systemPreferences", "askForMediaAccess");
  534. await ask.mockResolvedValue(false);
  535. await openPermissionGuide();
  536. await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE)).click();
  537. await browser.waitUntil(
  538. async () =>
  539. (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).getAttribute(
  540. "data-voice-permission-phase",
  541. )) === "restart-required",
  542. { timeout: 5_000, timeoutMsg: "重置后仍是 denied 时没有提示需要重启" },
  543. );
  544. expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH).isDisplayed()).toBe(true);
  545. // 状态没有变成未询问时不调用系统弹框。
  546. await expect(ask).not.toHaveBeenCalled();
  547. });
  548. });
  549. it("VI-17: 浮层打开时窗口重新获得焦点,权限已开启则关闭浮层", async function () {
  550. if (process.platform === "linux") this.skip();
  551. await browser.electron.restoreAllMocks();
  552. const status = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
  553. await status.mockReturnValue("denied");
  554. await openPermissionGuide();
  555. // 用户在系统设置里打开开关后回到 ZCode。
  556. await status.mockReturnValue("granted");
  557. // 浮层的 focus 监听在 React effect 中挂上,比浮层出现晚一帧;重复发送 focus,直到浮层关闭。
  558. await browser.waitUntil(
  559. async () => {
  560. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  561. return !(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).isExisting());
  562. },
  563. { timeout: 5_000, interval: 300, timeoutMsg: "权限开启后回到窗口,浮层没有关闭" },
  564. );
  565. await waitForToastContaining("已开启麦克风权限", "权限开启后没有提示");
  566. expect(await voiceState()).toBe("idle");
  567. });
  568. // Host 网络 transport 只在启动时读取代理设置,所以这组用例要重启应用;放在最后,结束时恢复原代理设置。
  569. describe("经 HTTP 代理", () => {
  570. let proxy: Awaited<ReturnType<typeof startAsrFrameDroppingProxy>>;
  571. let originalNetwork: { httpProxy?: string; httpProxyNoProxy?: string };
  572. const restartWithNetwork = async (network: {
  573. httpProxy?: string;
  574. httpProxyNoProxy?: string;
  575. }) => {
  576. await reloadElectronSessionSafely(browser, {
  577. afterElectronProcessExit: async () => {
  578. await seedSettings(network);
  579. },
  580. });
  581. // 重启后恢复上次会话,活动工作区不一定是默认工作区;这组用例只需要 Composer 与语音按钮。
  582. await byId(TID_V4_COMPOSER_VOICE_INPUT).waitForDisplayed({
  583. timeout: 30_000,
  584. timeoutMsg: "重启后没有显示语音输入按钮",
  585. });
  586. };
  587. /** 本次点击之后新增的 Host 失败日志(按出现顺序) */
  588. const failureLogsSince = async (before: number) =>
  589. [...(await runtimeLogText()).matchAll(/voice input failed (\{.*\})/gu)]
  590. .slice(before)
  591. .map((match) => JSON.parse(match[1]!) as Record<string, unknown>);
  592. before(async () => {
  593. proxy = await startAsrFrameDroppingProxy();
  594. // capture 模式会预设代理(No Proxy 含 127.0.0.1),结束时按原值恢复。
  595. const { httpProxy, httpProxyNoProxy } = await readSettings();
  596. originalNetwork = { httpProxy, httpProxyNoProxy };
  597. // httpProxyNoProxy 不能写空字符串(schema 要求非空,否则整份设置回退默认值),用 undefined 删除。
  598. await restartWithNetwork({ httpProxy: proxy.url, httpProxyNoProxy: undefined });
  599. });
  600. after(async () => {
  601. await restartWithNetwork(originalNetwork);
  602. await proxy.close();
  603. });
  604. it("VI-13: 代理在握手后丢弃 WS 数据帧,提示代理问题并记录握手结果", async () => {
  605. const before = (await failureLogsSince(0)).length;
  606. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  607. await waitForToastContaining(
  608. "无法通过 HTTP 代理连接语音识别服务",
  609. "代理断开后没有提示代理问题",
  610. );
  611. await waitForVoiceState("idle", "代理断开后没有回到空闲");
  612. // ticket 经代理成功;WS 握手经代理完成,start 被代理丢弃,服务端没有收到。
  613. expect(proxy.upgradedSockets).toBe(1);
  614. const state = await mockState();
  615. expect(state.ticketRequests).toHaveLength(1);
  616. expect(state.sessions).toHaveLength(1);
  617. expect(state.sessions[0]?.start).toBeUndefined();
  618. expect(await runtimeLogText()).toMatch(/voice input socket open .*"viaProxy":true/u);
  619. // 同一行可能出现在多个日志文件里,取本次点击后最新一条。
  620. expect((await failureLogsSince(before)).at(-1)).toMatchObject({
  621. code: "proxy",
  622. stage: "socket",
  623. opened: true,
  624. viaProxy: true,
  625. closeCode: 1006,
  626. wasClean: false,
  627. });
  628. });
  629. it("VI-14: 服务端在握手阶段拒绝时提示通用失败,不归为代理问题", async () => {
  630. await resetMock({ kind: "ws-reject", status: 403 });
  631. const upgradedBefore = proxy.upgradedSockets;
  632. const before = (await failureLogsSince(0)).length;
  633. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  634. await waitForToastContaining("语音识别失败,请重试", "握手被拒后没有提示通用失败");
  635. await waitForVoiceState("idle", "握手被拒后没有回到空闲");
  636. // 握手没有成功:代理只转发了 403,没有进入丢帧,服务端也没有建立会话。
  637. expect(proxy.upgradedSockets).toBe(upgradedBefore);
  638. expect((await mockState()).sessions).toHaveLength(0);
  639. // 上一个用例的代理 toast 可能仍在,分类以 Host 日志为准。
  640. await browser.waitUntil(async () => (await failureLogsSince(before)).length > 0, {
  641. timeout: 5_000,
  642. timeoutMsg: "握手被拒后 Host 没有记录失败",
  643. });
  644. expect((await failureLogsSince(before)).at(-1)).toMatchObject({
  645. code: "failed",
  646. stage: "handshake",
  647. opened: false,
  648. viaProxy: true,
  649. });
  650. });
  651. });
  652. });