composer-voice-input.test.ts 27 KB

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