composer-voice-input.test.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. import { readFile, readdir } 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_TASK_SETTINGS_BUTTON,
  8. TID_V4_COMPOSER_INPUT,
  9. TID_V4_COMPOSER_SEND,
  10. TID_V4_COMPOSER_VOICE_INPUT,
  11. TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE,
  12. TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS,
  13. TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE,
  14. TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH,
  15. TID_V4_COMPOSER_VOICE_WAVEFORM,
  16. testId,
  17. } from "@zcode/shared/test-ids";
  18. import {
  19. clickTestIdByDom,
  20. readSettings,
  21. seedSettings,
  22. waitForDefaultWorkspaceReady,
  23. } from "#e2e/helpers/desktop-app";
  24. import {
  25. startAsrFrameDroppingProxy,
  26. type AsrMockScenario,
  27. type AsrMockSession,
  28. } from "#e2e/helpers/asr-mock-server";
  29. import { reloadElectronSessionSafely } from "#e2e/helpers/e2e-electron-reload";
  30. import {
  31. clickV4Send,
  32. denyV4PermissionWithFeedback,
  33. hasV4PermissionDialog,
  34. getV4Messages,
  35. getV4PaneSnapshot,
  36. pasteV4ComposerFileAttachment,
  37. waitForV4RowAttachments,
  38. selectV4TaskById,
  39. sendV4Prompt,
  40. setV4ComposerText,
  41. startNewV4Draft,
  42. switchV4Mode,
  43. waitForV4Pane,
  44. waitForV4PermissionDialogInComposerDock,
  45. waitForV4TimelineContaining,
  46. } from "#e2e/helpers/v4-conversation";
  47. import { getToastMessages, waitForToastContaining } from "#e2e/helpers/conversation-session-toast";
  48. // 规格:docs/chat/composer-voice-input.md。麦克风由 wdio appArgs 的 Chromium 假设备提供(持续正弦音)。
  49. type LexicalInputE2EElement = HTMLElement & {
  50. __zcodeLexicalInputE2E?: {
  51. getText: () => string;
  52. focus: () => void;
  53. setText: (text: string) => void;
  54. };
  55. };
  56. const PREFIX = "前缀";
  57. const byId = (id: string) => $(`[data-testid="${id}"]`);
  58. // 替身由 wdio beforeSession 在 Electron 启动前启动(prepareVoiceInputFixture)。
  59. function mockOrigin(): string {
  60. const value = process.env.ZCODE_E2E_ASR_MOCK_URL;
  61. if (!value) throw new Error("缺少语音输入 ASR 替身");
  62. return value;
  63. }
  64. async function resetMock(scenario: AsrMockScenario) {
  65. await fetch(`${mockOrigin()}/__e2e/asr/reset`, {
  66. method: "POST",
  67. body: JSON.stringify(scenario),
  68. });
  69. }
  70. async function mockState(): Promise<{
  71. ticketRequests: Array<{ authorization?: string; body: string }>;
  72. sessions: AsrMockSession[];
  73. }> {
  74. return (await (await fetch(`${mockOrigin()}/__e2e/asr/state`)).json()) as never;
  75. }
  76. async function voiceState(): Promise<string | null> {
  77. const button = await byId(TID_V4_COMPOSER_VOICE_INPUT);
  78. return (await button.isExisting()) ? button.getAttribute("data-voice-state") : null;
  79. }
  80. async function waitForVoiceState(state: string, timeoutMsg: string) {
  81. await browser.waitUntil(async () => (await voiceState()) === state, {
  82. timeout: 15_000,
  83. timeoutMsg: `${timeoutMsg}; latest=${await voiceState()}`,
  84. });
  85. }
  86. async function editorText(): Promise<string> {
  87. return browser.execute((id) => {
  88. const root = document.querySelector<LexicalInputE2EElement>(`[data-testid="${id}"]`);
  89. return root?.__zcodeLexicalInputE2E?.getText() ?? "";
  90. }, TID_V4_COMPOSER_INPUT);
  91. }
  92. /** 每个用例从固定草稿开始,光标在末尾,输入框保持焦点。 */
  93. async function resetEditor() {
  94. await browser.execute(
  95. (id, text) => {
  96. const bridge = document.querySelector<LexicalInputE2EElement>(
  97. `[data-testid="${id}"]`,
  98. )?.__zcodeLexicalInputE2E;
  99. bridge?.setText(text);
  100. bridge?.focus();
  101. },
  102. TID_V4_COMPOSER_INPUT,
  103. PREFIX,
  104. );
  105. await browser.waitUntil(async () => (await editorText()) === PREFIX, {
  106. timeout: 5_000,
  107. timeoutMsg: "没有重置输入框",
  108. });
  109. }
  110. async function waitForEditorText(expected: string, timeoutMsg: string) {
  111. await browser.waitUntil(async () => (await editorText()) === expected, {
  112. timeout: 10_000,
  113. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(await editorText())}`,
  114. });
  115. }
  116. async function runtimeLogText(): Promise<string> {
  117. const logs = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR);
  118. if (!logs) throw new Error("缺少 worker 运行时日志目录");
  119. const names = (await readdir(logs)).filter((name) => name.endsWith(".log")).sort();
  120. return (await Promise.all(names.map((name) => readFile(join(logs, name), "utf8")))).join("\n");
  121. }
  122. /** 渲染层记录的最后一次采集总字节数(含 flush 出的尾块),来自运行时日志。 */
  123. async function lastCapturedBytes(): Promise<number | null> {
  124. const text = await runtimeLogText();
  125. const matches = [...text.matchAll(/\[voice-input\] capture stopped .*?"bytes":(\d+)/gu)];
  126. return matches.length > 0 ? Number(matches.at(-1)![1]) : null;
  127. }
  128. /** 时间线里已发送的用户消息文本。 */
  129. async function sentUserMessages(): Promise<string[]> {
  130. return (await getV4Messages("user")).map((message) => message.text);
  131. }
  132. async function releaseHeldCompletions() {
  133. await fetch(`${mockOrigin()}/__e2e/asr/release`, { method: "POST" });
  134. }
  135. /** 在新草稿里发送一条消息,得到一个真实会话并返回其 id。 */
  136. async function createSession(seed: string): Promise<string> {
  137. await startNewV4Draft();
  138. await setV4ComposerText(seed);
  139. await clickV4Send();
  140. await waitForV4Pane(
  141. (snapshot) => Boolean(snapshot.sessionId) && snapshot.sessionId !== "draft",
  142. `发送 ${seed} 后没有生成会话`,
  143. 30_000,
  144. );
  145. return (await getV4PaneSnapshot()).sessionId!;
  146. }
  147. async function mockMicrophonePermission(status: "granted" | "denied") {
  148. const mock = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
  149. await mock.mockReturnValue(status);
  150. }
  151. /** 系统权限被拒时点击麦克风,等待引导浮层出现 */
  152. async function openPermissionGuide() {
  153. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  154. await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).waitForDisplayed({
  155. timeout: 5_000,
  156. timeoutMsg: "权限被拒后没有显示引导浮层",
  157. });
  158. }
  159. async function startRecording() {
  160. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  161. await waitForVoiceState("recording", "点击麦克风后没有进入录音状态");
  162. }
  163. /** 语音输入快捷键默认值:平台主修饰键 + Shift + D。browser.keys 走 CDP 真实输入管线。 */
  164. async function pressVoiceShortcut() {
  165. const isMac = await browser.execute(() => /Mac|iPhone|iPad/.test(navigator.userAgent));
  166. await browser.keys([isMac ? "Command" : "Control", "Shift", "d"]);
  167. }
  168. /** 平台主修饰键 + 单键(macOS 用 Command)。 */
  169. async function pressPrimaryKey(key: string) {
  170. const isMac = await browser.execute(() => /Mac|iPhone|iPad/.test(navigator.userAgent));
  171. await browser.keys([isMac ? "Command" : "Control", key]);
  172. }
  173. // 任务内查找是 aria-modal="false" 的行内查找条,输入框是其中唯一的 input。
  174. async function isFindInputFocused(): Promise<boolean> {
  175. return browser.execute(() => {
  176. const active = document.activeElement;
  177. return active instanceof HTMLInputElement && Boolean(active.closest('[role="dialog"]'));
  178. });
  179. }
  180. async function waitForFindInputFocused() {
  181. await browser.waitUntil(isFindInputFocused, {
  182. timeout: 5_000,
  183. timeoutMsg: "任务内查找没有打开或查找框没有获得焦点",
  184. });
  185. }
  186. async function findInputValue(): Promise<string | null> {
  187. return browser.execute(
  188. () => document.querySelector<HTMLInputElement>('[role="dialog"] input')?.value ?? null,
  189. );
  190. }
  191. async function waitForVoiceButtonAfterRefresh() {
  192. await byId(TID_V4_COMPOSER_VOICE_INPUT).waitForDisplayed({
  193. timeout: 30_000,
  194. timeoutMsg: "刷新后没有显示语音输入按钮",
  195. });
  196. }
  197. async function isFocusInComposerInput(): Promise<boolean> {
  198. return browser.execute((id) => {
  199. const root = document.querySelector(`[data-testid="${id}"]`);
  200. return Boolean(root && document.activeElement && root.contains(document.activeElement));
  201. }, TID_V4_COMPOSER_INPUT);
  202. }
  203. describe("Composer 语音输入", () => {
  204. let originalSettings: Awaited<ReturnType<typeof readSettings>>;
  205. before(async () => {
  206. await waitForDefaultWorkspaceReady(30_000);
  207. originalSettings = await readSettings();
  208. await seedSettings({ locale: "zh-CN", localePreference: "zh-CN" });
  209. await browser.refresh();
  210. await waitForDefaultWorkspaceReady(30_000);
  211. });
  212. beforeEach(async () => {
  213. await resetMock({ kind: "normal", partial: "模拟临时", final: "你好世界" });
  214. await mockMicrophonePermission("granted");
  215. await byId(TID_V4_COMPOSER_VOICE_INPUT).waitForDisplayed({
  216. timeout: 15_000,
  217. timeoutMsg: "已登录桌面端没有显示语音输入按钮",
  218. });
  219. await resetEditor();
  220. });
  221. afterEach(async () => {
  222. await browser.keys("Escape");
  223. await browser.electron.restoreAllMocks();
  224. });
  225. after(async () => {
  226. await seedSettings(originalSettings);
  227. });
  228. it("VI-01: 识别结果直接写入光标处,结束后由最终文本替换且不自动发送", async () => {
  229. await startRecording();
  230. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入光标处");
  231. // 录音中显示音量点阵;假设备持续输出正弦音,点阵应出现有音量的点。
  232. const waveform = await byId(TID_V4_COMPOSER_VOICE_WAVEFORM);
  233. await waveform.waitForDisplayed({ timeout: 5_000, timeoutMsg: "录音中没有显示音量点阵" });
  234. await browser.waitUntil(
  235. async () => Number(await waveform.getAttribute("data-voice-active-dots")) > 0,
  236. { timeout: 5_000, timeoutMsg: "音量点阵没有随麦克风输入变化" },
  237. );
  238. const visual = await browser.execute(
  239. (buttonId, waveformId) => {
  240. const button = document.querySelector<HTMLElement>(`[data-testid="${buttonId}"]`)!;
  241. const wave = document.querySelector<HTMLElement>(`[data-testid="${waveformId}"]`)!;
  242. // 共享 Button 基础类本身带 aria-invalid:border-destructive,不能按类名判断;比较实际渲染颜色。
  243. const colorOf = (className: string) => {
  244. const probe = document.createElement("span");
  245. probe.className = className;
  246. document.body.append(probe);
  247. const color = getComputedStyle(probe).backgroundColor;
  248. probe.remove();
  249. return color;
  250. };
  251. const iconBlue = colorOf("bg-voice-input-wave");
  252. const accent = colorOf("bg-voice-input-surface");
  253. return {
  254. expandTransition: getComputedStyle(wave.parentElement!.parentElement!).transitionProperty,
  255. destructiveColors: [colorOf("bg-destructive"), colorOf("bg-destructive-surface")],
  256. buttonBackground: getComputedStyle(button).backgroundColor,
  257. stopColor: getComputedStyle(button.querySelector("span")!).backgroundColor,
  258. iconBlue,
  259. accent,
  260. pillBackground: getComputedStyle(button.parentElement!).backgroundColor,
  261. barColor: getComputedStyle(wave.firstElementChild!).backgroundColor,
  262. waveWidth: wave.getBoundingClientRect().width,
  263. buttonWidth: button.getBoundingClientRect().width,
  264. };
  265. },
  266. TID_V4_COMPOSER_VOICE_INPUT,
  267. TID_V4_COMPOSER_VOICE_WAVEFORM,
  268. );
  269. // 停止按钮是 ghost(点击后鼠标仍在按钮上,可能是 hover 底色),不使用 destructive 色;
  270. // 点阵不超过按钮宽度的 3 倍。
  271. expect(visual.destructiveColors).not.toContain(visual.buttonBackground);
  272. // 胶囊底色与波形、停止方块使用 DESIGN.md 的 sky 色系语音输入 token。
  273. expect(visual.stopColor).toBe(visual.iconBlue);
  274. expect(visual.barColor).toBe(visual.iconBlue);
  275. expect(visual.pillBackground).toBe(visual.accent);
  276. expect(visual.waveWidth).toBeLessThanOrEqual(visual.buttonWidth * 3);
  277. // 胶囊展开带宽度过渡,而不是直接出现。
  278. expect(visual.expandTransition).toContain("grid-template-columns");
  279. // 采集超过 300ms 才不会被判为说话时间太短。
  280. await browser.pause(1_000);
  281. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  282. await waitForVoiceState("idle", "识别完成后没有回到空闲");
  283. // 最终文本替换临时结果,而不是追加;输入框仍有内容说明没有自动发送。
  284. await waitForEditorText(`${PREFIX}你好世界`, "最终文本没有替换临时结果");
  285. expect(await byId(TID_V4_COMPOSER_VOICE_WAVEFORM).isExisting()).toBe(false);
  286. const state = await mockState();
  287. expect(state.ticketRequests).toHaveLength(1);
  288. expect(state.ticketRequests[0]!.authorization).toMatch(/^Bearer \S+/u);
  289. expect(JSON.parse(state.ticketRequests[0]!.body)).toEqual({ mode: "realtime" });
  290. const session = state.sessions[0]!;
  291. expect(session.start).toMatchObject({
  292. type: "start",
  293. audio: { encoding: "pcm_s16le", sample_rate: 16000, channels: 1 },
  294. language: "zh-CN",
  295. });
  296. // 假设备持续输出音频;至少 1 秒 16kHz PCM16。
  297. expect(session.audioBytes).toBeGreaterThan(16_000);
  298. expect(session.audioBytes % 2).toBe(0);
  299. expect(session.controls).toEqual(["finish"]);
  300. // 尾块回归:停止时 flush 出的不足 100ms 音频也要发出,且全部在 finish 之前到达服务端。
  301. let capturedBytes: number | null = null;
  302. await browser.waitUntil(
  303. async () => {
  304. capturedBytes = await lastCapturedBytes();
  305. return capturedBytes !== null;
  306. },
  307. { timeout: 5_000, timeoutMsg: "运行时日志里没有采集统计" },
  308. );
  309. expect(session.audioBytesAtFinish).toBe(capturedBytes);
  310. expect(session.audioAfterFinish).toBe(0);
  311. });
  312. it("VI-02: 录音中按 Escape 取消并删除语音文字", async () => {
  313. await startRecording();
  314. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  315. await browser.keys("Escape");
  316. await waitForVoiceState("idle", "Escape 后没有回到空闲");
  317. await browser.waitUntil(async () => (await mockState()).sessions[0]?.closed === true, {
  318. timeout: 5_000,
  319. timeoutMsg: "取消后服务端连接没有关闭",
  320. });
  321. expect((await mockState()).sessions[0]!.controls).toEqual(["cancel"]);
  322. expect(await editorText()).toBe(PREFIX);
  323. });
  324. it("VI-06: 录音中用户开始输入时与点击停止一致,最终文本替换语音文字且保留用户输入", async () => {
  325. await startRecording();
  326. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  327. // 采集超过 300ms 才不会被判为说话时间太短。
  328. await browser.pause(1_000);
  329. await browser.keys("abc");
  330. await waitForVoiceState("idle", "用户输入后语音输入没有结束");
  331. // 走 finish 而不是 cancel:拿到服务端最终文本替换临时结果,用户在其后输入的字符保留。
  332. expect((await mockState()).sessions[0]!.controls).toEqual(["finish"]);
  333. await waitForEditorText(`${PREFIX}你好世界abc`, "最终文本没有替换临时结果或用户输入丢失");
  334. });
  335. it("VI-07: 录音中点击发送时先等最终文本,再发送最终文本", async () => {
  336. await startRecording();
  337. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  338. await browser.pause(1_000);
  339. await (await byId(TID_V4_COMPOSER_SEND)).click();
  340. let sent: string[] = [];
  341. await browser.waitUntil(
  342. async () => {
  343. sent = await sentUserMessages();
  344. return sent.some((text) => text.includes(`${PREFIX}你好世界`));
  345. },
  346. {
  347. timeout: 15_000,
  348. timeoutMsg: `发送的消息不是语音识别的最终文本; sent=${JSON.stringify(sent)}`,
  349. },
  350. );
  351. expect((await mockState()).sessions[0]!.controls).toEqual(["finish"]);
  352. expect(sent.some((text) => text.includes("模拟临时"))).toBe(false);
  353. });
  354. it("VI-08: 等待识别结果期间切换会话,中止本次发送,不串会话", async () => {
  355. const sessionA = await createSession("VI08-A");
  356. const sessionB = await createSession("VI08-B");
  357. // B 有独立草稿:切回 B 时会恢复它。
  358. await setV4ComposerText("B草稿");
  359. await selectV4TaskById(sessionA);
  360. const userMessagesA = await sentUserMessages();
  361. await resetMock({
  362. kind: "normal",
  363. partial: "模拟临时",
  364. final: "切换后不应出现",
  365. holdFinal: true,
  366. });
  367. await resetEditor();
  368. await startRecording();
  369. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  370. await browser.pause(1_000);
  371. await (await byId(TID_V4_COMPOSER_SEND)).click();
  372. // 服务端已收到 finish,但最终结果被扣住:发送正在等待识别。
  373. await browser.waitUntil(
  374. async () => (await mockState()).sessions[0]?.controls.includes("finish") === true,
  375. { timeout: 5_000, timeoutMsg: "点击发送后没有发出 finish" },
  376. );
  377. await selectV4TaskById(sessionB);
  378. await releaseHeldCompletions();
  379. await browser.pause(1_500);
  380. // 旧提交恢复后识别出目标已变化并中止(不靠后续守卫碰巧拦下)。
  381. expect(await runtimeLogText()).toContain("[voice-input] submit aborted");
  382. // B:草稿仍在,没有收到 A 的内容,也没有被发送清空。
  383. expect(await editorText()).toBe("B草稿");
  384. expect(await sentUserMessages()).toEqual(
  385. expect.not.arrayContaining([expect.stringContaining("B草稿")]),
  386. );
  387. await selectV4TaskById(sessionA);
  388. // A:切走后没有发生提交;临时语音文字留在 A 的草稿里。先等时间线加载完。
  389. await browser.waitUntil(async () => (await sentUserMessages()).length > 0, {
  390. timeout: 15_000,
  391. timeoutMsg: "切回 A 后时间线没有加载",
  392. });
  393. expect(await sentUserMessages()).toEqual(userMessagesA);
  394. await waitForEditorText(`${PREFIX}模拟临时`, "A 的草稿没有保留临时语音文字");
  395. });
  396. it("VI-09: 首个识别结果前用户已开始输入,最终文本插在录音开始处且不移动光标", async () => {
  397. await resetMock({ kind: "normal", partial: "", final: "你好世界" });
  398. await startRecording();
  399. await browser.pause(1_000);
  400. await browser.keys("abc");
  401. await waitForVoiceState("idle", "用户输入后语音输入没有结束");
  402. await waitForEditorText(`${PREFIX}你好世界abc`, "最终文本没有插在录音开始处");
  403. // 光标仍在用户输入的 abc 之后:继续输入的字符紧跟 abc。
  404. await browser.keys("d");
  405. await waitForEditorText(`${PREFIX}你好世界abcd`, "最终文本写入后光标被移动");
  406. });
  407. it("VI-10: 首个识别结果前用户在录音开始点之前输入,开始点失效,最终文本追加到末尾", async () => {
  408. await resetMock({ kind: "normal", partial: "", final: "你好世界" });
  409. await startRecording();
  410. await browser.pause(1_000);
  411. // 光标移到行首再输入:录音开始点(「前缀」之后)前面的内容变了,旧 offset 不能再用。
  412. // 用 DOM 选区把光标移到行首:macOS 下 WebDriver 发出的 Cmd+← 不会移动 contenteditable 光标。
  413. await browser.execute((id) => {
  414. const root = document.querySelector<HTMLElement>(`[data-testid="${id}"]`)!;
  415. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  416. const first = walker.nextNode();
  417. if (first) window.getSelection()?.collapse(first, 0);
  418. }, TID_V4_COMPOSER_INPUT);
  419. await browser.pause(100);
  420. await browser.keys("ab");
  421. await waitForVoiceState("idle", "用户输入后语音输入没有结束");
  422. // 不拆开「前缀」,按 spec 追加到末尾;光标仍在用户输入的 ab 之后。
  423. await waitForEditorText(`ab${PREFIX}你好世界`, "开始点失效时最终文本没有追加到末尾");
  424. await browser.keys("c");
  425. await waitForEditorText(`abc${PREFIX}你好世界`, "最终文本写入后光标被移动");
  426. });
  427. it("VI-11: 等待识别期间新增附件,随消息发出并在发送后从输入框清除", async () => {
  428. // 从新草稿开始:之前用例的会话可能仍有进行中的回合,语音消息会进入队列而不出现在时间线上。
  429. await startNewV4Draft();
  430. await resetMock({ kind: "normal", partial: "模拟临时", final: "你好世界", holdFinal: true });
  431. await resetEditor();
  432. await startRecording();
  433. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  434. await browser.pause(1_000);
  435. await (await byId(TID_V4_COMPOSER_SEND)).click();
  436. await browser.waitUntil(
  437. async () => (await mockState()).sessions[0]?.controls.includes("finish") === true,
  438. { timeout: 5_000, timeoutMsg: "点击发送后没有发出 finish" },
  439. );
  440. // 发送正在等待识别:此时新增一个附件,并等它上传就绪。
  441. await pasteV4ComposerFileAttachment("vi11-added.png");
  442. await $("[data-composer-attachment-remove]").waitForExist({
  443. timeout: 15_000,
  444. timeoutMsg: "附件没有出现在输入框",
  445. });
  446. await browser.waitUntil(
  447. async () =>
  448. browser.execute(
  449. () =>
  450. document.querySelector(
  451. '[data-composer-file-attachments-row="true"] [aria-busy="true"]',
  452. ) === null,
  453. ),
  454. { timeout: 15_000, timeoutMsg: "附件没有上传就绪" },
  455. );
  456. await releaseHeldCompletions();
  457. let sent: { id: string | null; text: string } | undefined;
  458. await browser.waitUntil(
  459. async () => {
  460. sent = (await getV4Messages("user")).find((message) =>
  461. message.text.includes(`${PREFIX}你好世界`),
  462. );
  463. return sent !== undefined;
  464. },
  465. { timeout: 15_000, timeoutMsg: "没有发出语音最终文本" },
  466. );
  467. // 附件属于本次发送:消息带上它,发送后输入框里不再残留。
  468. expect(await waitForV4RowAttachments(15_000, ["vi11-added.png"])).toContain("vi11-added.png");
  469. await browser.waitUntil(
  470. async () => !(await $("[data-composer-attachment-remove]").isExisting()),
  471. { timeout: 5_000, timeoutMsg: "发送后附件仍残留在输入框里" },
  472. );
  473. });
  474. it("VI-12: 用户在语音文字后追加输入再按 Escape,只删除语音文字,保留用户输入", async () => {
  475. await resetMock({ kind: "normal", partial: "模拟临时", final: "迟到结果", holdFinal: true });
  476. await startRecording();
  477. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  478. await browser.pause(1_000);
  479. // 光标在语音文字末尾:追加的字符进入同一个文本节点,录音进入识别中。
  480. await browser.keys("abc");
  481. await waitForEditorText(`${PREFIX}模拟临时abc`, "用户输入没有写入");
  482. await waitForVoiceState("finishing", "用户输入后没有进入识别中");
  483. await browser.keys("Escape");
  484. await waitForVoiceState("idle", "Escape 后没有回到空闲");
  485. await waitForEditorText(`${PREFIX}abc`, "Escape 后语音文字没有删除,或用户输入丢失");
  486. await browser.waitUntil(
  487. async () => (await mockState()).sessions[0]?.controls.includes("cancel") === true,
  488. { timeout: 5_000, timeoutMsg: "Escape 后服务端没有收到 cancel" },
  489. );
  490. // 迟到的最终结果不能再写回输入框。
  491. await releaseHeldCompletions();
  492. await browser.pause(1_000);
  493. expect(await editorText()).toBe(`${PREFIX}abc`);
  494. // 光标仍在 abc 之后。
  495. await browser.keys("d");
  496. await waitForEditorText(`${PREFIX}abcd`, "删除语音文字后光标位置不对");
  497. });
  498. it("VI-03: 服务端繁忙时提示稍后再试", async () => {
  499. await resetMock({ kind: "ticket-error", status: 429, errorCode: "rate_limited" });
  500. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  501. await waitForToastContaining("语音识别繁忙,请稍后再试", "限流后没有提示");
  502. await waitForVoiceState("idle", "限流后没有回到空闲");
  503. expect((await mockState()).sessions).toHaveLength(0);
  504. });
  505. it("VI-04: 服务端返回空文本时提示没有识别到内容", async () => {
  506. await resetMock({ kind: "empty-final" });
  507. await startRecording();
  508. await browser.pause(1_000);
  509. const before = await editorText();
  510. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  511. await waitForToastContaining("没有识别到内容", "空结果后没有提示");
  512. expect(await editorText()).toBe(before);
  513. });
  514. it("VI-05: 系统拒绝麦克风权限时显示引导浮层,按钮打开系统麦克风设置", async function () {
  515. if (process.platform === "linux") this.skip();
  516. await browser.electron.restoreAllMocks();
  517. await mockMicrophonePermission("denied");
  518. const openExternal = await browser.electron.mock("shell", "openExternal");
  519. await openExternal.mockResolvedValue(undefined);
  520. await openPermissionGuide();
  521. // 系统权限被拒时不申请 ticket,也不再用 toast 提示。
  522. expect((await mockState()).ticketRequests).toHaveLength(0);
  523. expect((await getToastMessages()).some((message) => message.includes("没有麦克风权限"))).toBe(
  524. false,
  525. );
  526. // 浮层打开不移动焦点:焦点仍在输入框(beforeEach 已聚焦输入框)。
  527. expect(
  528. await browser.execute(
  529. (id) =>
  530. document.querySelector(`[data-testid="${id}"]`)?.contains(document.activeElement) ??
  531. false,
  532. TID_V4_COMPOSER_INPUT,
  533. ),
  534. ).toBe(true);
  535. // 「重新授权」只在 macOS 提供。
  536. expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE).isExisting()).toBe(
  537. process.platform === "darwin",
  538. );
  539. await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_OPEN_SETTINGS)).click();
  540. const expectedUrl =
  541. process.platform === "darwin"
  542. ? "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"
  543. : "ms-settings:privacy-microphone";
  544. await browser.waitUntil(
  545. async () => {
  546. try {
  547. await expect(openExternal).toHaveBeenCalledWith(expectedUrl);
  548. return true;
  549. } catch {
  550. return false;
  551. }
  552. },
  553. { timeout: 5_000, timeoutMsg: `没有打开 ${expectedUrl}` },
  554. );
  555. // 打开设置后浮层保留,用户返回后还能继续操作。
  556. expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).isDisplayed()).toBe(true);
  557. });
  558. // 打包版会真实执行 tccutil 重置本机 ZCode 的麦克风记录,只在开发版 Electron 上跑(开发版跳过 tccutil)。
  559. describe("macOS 重新授权", () => {
  560. before(function () {
  561. if (process.platform !== "darwin" || process.env.ZCODE_E2E_PACKAGED_APP_PATH?.trim()) {
  562. this.skip();
  563. }
  564. });
  565. it("VI-15: 重置后状态变为未询问,系统弹框允许后关闭浮层并提示已开启", async () => {
  566. await browser.electron.restoreAllMocks();
  567. const status = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
  568. await status.mockReturnValue("denied");
  569. await openPermissionGuide();
  570. // 模拟 tccutil 重置成功:之后读到未询问,系统弹框里用户点「允许」。
  571. await status.mockReturnValue("not-determined");
  572. const ask = await browser.electron.mock("systemPreferences", "askForMediaAccess");
  573. await ask.mockResolvedValue(true);
  574. await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE)).click();
  575. await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).waitForExist({
  576. reverse: true,
  577. timeout: 5_000,
  578. timeoutMsg: "重新授权成功后浮层没有关闭",
  579. });
  580. await waitForToastContaining("已开启麦克风权限", "重新授权成功后没有提示");
  581. await expect(ask).toHaveBeenCalledWith("microphone");
  582. // 不自动开始录音。
  583. expect(await voiceState()).toBe("idle");
  584. expect((await mockState()).ticketRequests).toHaveLength(0);
  585. });
  586. it("VI-16: 重置后当前进程仍读到 denied,浮层改为需要重启", async () => {
  587. await browser.electron.restoreAllMocks();
  588. await mockMicrophonePermission("denied");
  589. const ask = await browser.electron.mock("systemPreferences", "askForMediaAccess");
  590. await ask.mockResolvedValue(false);
  591. await openPermissionGuide();
  592. await (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_REAUTHORIZE)).click();
  593. await browser.waitUntil(
  594. async () =>
  595. (await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).getAttribute(
  596. "data-voice-permission-phase",
  597. )) === "restart-required",
  598. { timeout: 5_000, timeoutMsg: "重置后仍是 denied 时没有提示需要重启" },
  599. );
  600. expect(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_RELAUNCH).isDisplayed()).toBe(true);
  601. // 状态没有变成未询问时不调用系统弹框。
  602. await expect(ask).not.toHaveBeenCalled();
  603. });
  604. });
  605. it("VI-17: 浮层打开时窗口重新获得焦点,权限已开启则关闭浮层", async function () {
  606. if (process.platform === "linux") this.skip();
  607. await browser.electron.restoreAllMocks();
  608. const status = await browser.electron.mock("systemPreferences", "getMediaAccessStatus");
  609. await status.mockReturnValue("denied");
  610. await openPermissionGuide();
  611. // 用户在系统设置里打开开关后回到 ZCode。
  612. await status.mockReturnValue("granted");
  613. // 浮层的 focus 监听在 React effect 中挂上,比浮层出现晚一帧;重复发送 focus,直到浮层关闭。
  614. await browser.waitUntil(
  615. async () => {
  616. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  617. return !(await byId(TID_V4_COMPOSER_VOICE_PERMISSION_GUIDE).isExisting());
  618. },
  619. { timeout: 5_000, interval: 300, timeoutMsg: "权限开启后回到窗口,浮层没有关闭" },
  620. );
  621. await waitForToastContaining("已开启麦克风权限", "权限开启后没有提示");
  622. expect(await voiceState()).toBe("idle");
  623. });
  624. it("VI-18: 焦点在输入框外时按快捷键,焦点移入输入框并开始录音,再按一次结束", async () => {
  625. // 焦点离开输入框:事件目标是 body,不在任何对话区域内,由主区焦点 pane 的 Composer 处理。
  626. await browser.execute(() => (document.activeElement as HTMLElement | null)?.blur());
  627. expect(await isFocusInComposerInput()).toBe(false);
  628. await pressVoiceShortcut();
  629. await waitForVoiceState("recording", "按快捷键后没有进入录音状态");
  630. expect(await isFocusInComposerInput()).toBe(true);
  631. // 光标恢复到编辑器上次的选区(末尾),识别结果写在原有文字之后。
  632. await waitForEditorText(`${PREFIX}模拟临时`, "快捷键开始录音后识别结果没有写入");
  633. // 采集超过 300ms 才不会被判为说话时间太短。
  634. await browser.pause(1_000);
  635. await pressVoiceShortcut();
  636. await waitForVoiceState("idle", "再按快捷键后识别没有结束");
  637. await waitForEditorText(`${PREFIX}你好世界`, "快捷键结束录音后最终文本没有替换临时结果");
  638. expect((await mockState()).sessions[0]!.controls).toEqual(["finish"]);
  639. });
  640. it("VI-19: 快捷键已被用户显式绑给其他命令时,语音输入让位且设置页显示未分配", async () => {
  641. // 设置文件只在启动或刷新时读取。前面用例建过会话,刷新后恢复的可能是其他工作区里的会话,
  642. // 所以不等默认工作区,只等 Composer 的麦克风按钮出现。
  643. await seedSettings({ shortcutBindings: { findInTask: ["CmdOrCtrl+Shift+d"] } });
  644. await browser.refresh();
  645. try {
  646. await waitForVoiceButtonAfterRefresh();
  647. await resetEditor();
  648. await pressVoiceShortcut();
  649. // 按键只触发用户绑定的任务内查找。
  650. await browser.waitUntil(
  651. async () =>
  652. browser.execute(() =>
  653. [...document.querySelectorAll('[role="dialog"] h2')].some(
  654. (title) => title.textContent === "在任务中查找",
  655. ),
  656. ),
  657. { timeout: 5_000, timeoutMsg: "按键没有打开任务内查找" },
  658. );
  659. // 等待足够长:如果语音输入也响应了按键,这时已经申请过 ticket。
  660. await browser.pause(1_000);
  661. expect(await voiceState()).toBe("idle");
  662. expect((await mockState()).ticketRequests).toHaveLength(0);
  663. await browser.keys("Escape");
  664. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  665. timeout: 15_000,
  666. timeoutMsg: "没有找到设置入口按钮",
  667. });
  668. await byId(TID_SETTINGS_PAGE).waitForDisplayed({ timeout: 15_000 });
  669. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "shortcuts"), {
  670. timeout: 15_000,
  671. timeoutMsg: "设置页没有出现快捷键分区入口",
  672. });
  673. const unassigned = await byId("settings-shortcut-bind-toggleVoiceInput-unassigned");
  674. await unassigned.waitForDisplayed({
  675. timeout: 10_000,
  676. timeoutMsg: "设置页语音输入快捷键没有显示未分配",
  677. });
  678. expect((await unassigned.getText()).trim()).toBe("未分配");
  679. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  680. timeout: 15_000,
  681. timeoutMsg: "设置页没有出现返回按钮",
  682. });
  683. } finally {
  684. await seedSettings({ shortcutBindings: originalSettings.shortcutBindings ?? {} });
  685. await browser.refresh();
  686. await waitForVoiceButtonAfterRefresh();
  687. }
  688. });
  689. it("VI-20: 改绑为纯 Shift 字符时,在可编辑元素内正常输入,在非编辑区域才开始录音", async () => {
  690. await seedSettings({ shortcutBindings: { toggleVoiceInput: ["Shift+d"] } });
  691. await browser.refresh();
  692. try {
  693. await waitForVoiceButtonAfterRefresh();
  694. await resetEditor();
  695. // 刷新后测试桥的 focus() 不一定能拿到 DOM 焦点(实测焦点仍在 body),
  696. // 按键会落到非编辑区域。用真实点击把焦点放进输入框,并在按键前确认。
  697. await (await byId(TID_V4_COMPOSER_INPUT)).click();
  698. await browser.waitUntil(isFocusInComposerInput, {
  699. timeout: 5_000,
  700. timeoutMsg: "点击后焦点没有进入 Composer 输入框",
  701. });
  702. // Composer 内输入大写 D:字符写入,语音不开始。
  703. await browser.keys(["Shift", "d"]);
  704. await browser.waitUntil(async () => (await editorText()).includes("D"), {
  705. timeout: 5_000,
  706. timeoutMsg: `Composer 内的大写 D 被快捷键吞掉; latest=${JSON.stringify(await editorText())}`,
  707. });
  708. expect(await voiceState()).toBe("idle");
  709. // 查找框内输入大写 D:同样正常输入。
  710. await pressPrimaryKey("f");
  711. await waitForFindInputFocused();
  712. await browser.keys(["Shift", "d"]);
  713. await browser.waitUntil(async () => (await findInputValue()) === "D", {
  714. timeout: 5_000,
  715. timeoutMsg: `查找框内的大写 D 被快捷键吞掉; latest=${await findInputValue()}`,
  716. });
  717. // 等待足够长:如果语音输入响应了按键,这时已经申请过 ticket。
  718. await browser.pause(1_000);
  719. expect(await voiceState()).toBe("idle");
  720. expect((await mockState()).ticketRequests).toHaveLength(0);
  721. await browser.keys("Escape");
  722. // 非编辑区域按键:照常开始录音。
  723. await browser.execute(() => (document.activeElement as HTMLElement | null)?.blur());
  724. await browser.keys(["Shift", "d"]);
  725. await waitForVoiceState("recording", "非编辑区域按 Shift+D 没有开始录音");
  726. await browser.keys("Escape");
  727. await waitForVoiceState("idle", "Escape 后没有回到空闲");
  728. } finally {
  729. await seedSettings({ shortcutBindings: originalSettings.shortcutBindings ?? {} });
  730. await browser.refresh();
  731. await waitForVoiceButtonAfterRefresh();
  732. }
  733. });
  734. it("VI-21: 识别中按快捷键与按钮一致不响应,不拦截按键也不移动焦点", async () => {
  735. await resetMock({ kind: "normal", partial: "模拟临时", final: "你好世界", holdFinal: true });
  736. await startRecording();
  737. await waitForEditorText(`${PREFIX}模拟临时`, "录音中识别结果没有写入");
  738. // 采集超过 300ms 才不会被判为说话时间太短。
  739. await browser.pause(1_000);
  740. await pressVoiceShortcut();
  741. // 服务端扣住最终结果,状态停在识别中。
  742. await waitForVoiceState("finishing", "按快捷键结束录音后没有进入识别中");
  743. // 焦点移到查找框,再按一次快捷键。
  744. await pressPrimaryKey("f");
  745. await waitForFindInputFocused();
  746. await pressVoiceShortcut();
  747. await browser.pause(500);
  748. expect(await isFindInputFocused()).toBe(true);
  749. expect(await voiceState()).toBe("finishing");
  750. expect((await mockState()).sessions[0]!.controls).toEqual(["finish"]);
  751. await releaseHeldCompletions();
  752. await waitForVoiceState("idle", "放行最终结果后没有回到空闲");
  753. await waitForEditorText(`${PREFIX}你好世界`, "最终文本没有替换临时结果");
  754. });
  755. it("VI-22: 审批卡片出现时取消录音并保留文字,卡片显示期间快捷键不开始录音", async () => {
  756. // fixture(fixtures/upstream/ui-shell/composer-voice-input.json)延迟 4 秒返回需要审批的 Bash 调用,
  757. // guarded 模式下递归删除必定弹出审批卡片;录音在这 4 秒内开始。
  758. await startNewV4Draft();
  759. await switchV4Mode("guarded");
  760. await sendV4Prompt("E2E_VOICE_BLOCKED Execute the fixture command once.");
  761. // 草稿转正会换 sessionId,而切换会话本身就会取消录音;先等转正完成、按钮可用,
  762. // 确保下面观察到的取消来自审批卡片。
  763. await waitForV4Pane(
  764. (snapshot) => Boolean(snapshot.sessionId) && snapshot.sessionId !== "draft",
  765. "VI-22 发送后没有生成会话",
  766. 30_000,
  767. );
  768. await browser.waitUntil(
  769. async () =>
  770. (await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).getAttribute("disabled")) === null,
  771. { timeout: 10_000, timeoutMsg: "会话连接后麦克风按钮没有变为可用" },
  772. );
  773. await startRecording();
  774. await waitForEditorText("模拟临时", "录音中识别结果没有写入");
  775. // 审批卡片替换并隐藏 Composer:录音取消,服务端收到 cancel,按钮禁用。
  776. await waitForV4PermissionDialogInComposerDock();
  777. try {
  778. await waitForVoiceState("idle", "审批卡片出现后录音没有取消");
  779. await browser.waitUntil(async () => (await mockState()).sessions[0]?.closed === true, {
  780. timeout: 5_000,
  781. timeoutMsg: "取消后服务端连接没有关闭",
  782. });
  783. expect((await mockState()).sessions[0]!.controls).toEqual(["cancel"]);
  784. expect(
  785. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).getAttribute("disabled"),
  786. ).not.toBeNull();
  787. // 卡片显示期间按快捷键:不开始录音,也不申请新的 ticket。
  788. await pressVoiceShortcut();
  789. await browser.pause(1_000);
  790. expect(await voiceState()).toBe("idle");
  791. expect((await mockState()).ticketRequests).toHaveLength(1);
  792. } finally {
  793. // 断言失败时也要结束审批,否则卡片一直隐藏 Composer,后续用例找不到麦克风按钮。
  794. if (await hasV4PermissionDialog()) {
  795. await denyV4PermissionWithFeedback("VI-22: do not execute.");
  796. }
  797. }
  798. // 拒绝后回合结束,Composer 恢复显示,临时文字仍在草稿里。
  799. await waitForV4TimelineContaining("E2E_VOICE_BLOCKED_DONE");
  800. await byId(TID_V4_COMPOSER_INPUT).waitForDisplayed({
  801. timeout: 10_000,
  802. timeoutMsg: "拒绝审批后 Composer 没有恢复显示",
  803. });
  804. expect(await editorText()).toBe("模拟临时");
  805. });
  806. // Host 网络 transport 只在启动时读取代理设置,所以这组用例要重启应用;放在最后,结束时恢复原代理设置。
  807. describe("经 HTTP 代理", () => {
  808. let proxy: Awaited<ReturnType<typeof startAsrFrameDroppingProxy>>;
  809. let originalNetwork: { httpProxy?: string; httpProxyNoProxy?: string };
  810. const restartWithNetwork = async (network: {
  811. httpProxy?: string;
  812. httpProxyNoProxy?: string;
  813. }) => {
  814. await reloadElectronSessionSafely(browser, {
  815. afterElectronProcessExit: async () => {
  816. await seedSettings(network);
  817. },
  818. });
  819. // 重启后恢复上次会话,活动工作区不一定是默认工作区;这组用例只需要 Composer 与语音按钮。
  820. await byId(TID_V4_COMPOSER_VOICE_INPUT).waitForDisplayed({
  821. timeout: 30_000,
  822. timeoutMsg: "重启后没有显示语音输入按钮",
  823. });
  824. };
  825. /** 本次点击之后新增的 Host 失败日志(按出现顺序) */
  826. const failureLogsSince = async (before: number) =>
  827. [...(await runtimeLogText()).matchAll(/voice input failed (\{.*\})/gu)]
  828. .slice(before)
  829. .map((match) => JSON.parse(match[1]!) as Record<string, unknown>);
  830. before(async () => {
  831. proxy = await startAsrFrameDroppingProxy();
  832. // capture 模式会预设代理(No Proxy 含 127.0.0.1),结束时按原值恢复。
  833. const { httpProxy, httpProxyNoProxy } = await readSettings();
  834. originalNetwork = { httpProxy, httpProxyNoProxy };
  835. // httpProxyNoProxy 不能写空字符串(schema 要求非空,否则整份设置回退默认值),用 undefined 删除。
  836. await restartWithNetwork({ httpProxy: proxy.url, httpProxyNoProxy: undefined });
  837. });
  838. after(async () => {
  839. await restartWithNetwork(originalNetwork);
  840. await proxy.close();
  841. });
  842. it("VI-13: 代理在握手后丢弃 WS 数据帧,提示代理问题并记录握手结果", async () => {
  843. const before = (await failureLogsSince(0)).length;
  844. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  845. await waitForToastContaining(
  846. "无法通过 HTTP 代理连接语音识别服务",
  847. "代理断开后没有提示代理问题",
  848. );
  849. await waitForVoiceState("idle", "代理断开后没有回到空闲");
  850. // ticket 经代理成功;WS 握手经代理完成,start 被代理丢弃,服务端没有收到。
  851. expect(proxy.upgradedSockets).toBe(1);
  852. const state = await mockState();
  853. expect(state.ticketRequests).toHaveLength(1);
  854. expect(state.sessions).toHaveLength(1);
  855. expect(state.sessions[0]?.start).toBeUndefined();
  856. expect(await runtimeLogText()).toMatch(/voice input socket open .*"viaProxy":true/u);
  857. // 同一行可能出现在多个日志文件里,取本次点击后最新一条。
  858. expect((await failureLogsSince(before)).at(-1)).toMatchObject({
  859. code: "proxy",
  860. stage: "socket",
  861. opened: true,
  862. viaProxy: true,
  863. closeCode: 1006,
  864. wasClean: false,
  865. });
  866. });
  867. it("VI-14: 服务端在握手阶段拒绝时提示通用失败,不归为代理问题", async () => {
  868. await resetMock({ kind: "ws-reject", status: 403 });
  869. const upgradedBefore = proxy.upgradedSockets;
  870. const before = (await failureLogsSince(0)).length;
  871. await (await byId(TID_V4_COMPOSER_VOICE_INPUT)).click();
  872. await waitForToastContaining("语音识别失败,请重试", "握手被拒后没有提示通用失败");
  873. await waitForVoiceState("idle", "握手被拒后没有回到空闲");
  874. // 握手没有成功:代理只转发了 403,没有进入丢帧,服务端也没有建立会话。
  875. expect(proxy.upgradedSockets).toBe(upgradedBefore);
  876. expect((await mockState()).sessions).toHaveLength(0);
  877. // 上一个用例的代理 toast 可能仍在,分类以 Host 日志为准。
  878. await browser.waitUntil(async () => (await failureLogsSince(before)).length > 0, {
  879. timeout: 5_000,
  880. timeoutMsg: "握手被拒后 Host 没有记录失败",
  881. });
  882. expect((await failureLogsSince(before)).at(-1)).toMatchObject({
  883. code: "failed",
  884. stage: "handshake",
  885. opened: false,
  886. viaProxy: true,
  887. });
  888. });
  889. });
  890. });