From 373180a71db2d263777135a3c9beae8a000ba28d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 08:03:17 +0000 Subject: [PATCH 1/2] feat(ui-react): tap the composer mic to dictate, hold it to open Start The composer's resting mic is now the kit's MicButton in the Composer micControl slot (#3727). A tap, Enter or Space dictates through the existing path. A press fills the ring from elapsed time; at 0.6 s (V1) a light haptic fires and the existing Start disclosure opens, or the S4 notice where live conversation is not available (V4). An earlier release is a tap, and leaving the mic cancels the hold. Shift+Enter and the "Talk live..." action open Start from a keyboard or screen reader. A hold starts a timer and a frame loop only: no microphone, provider or history work. The offline "Record on this device" mic has no hold (M1). Dictating, a recording in progress, an undecided mic, and a host with neither dictation nor live conversation keep the kit's own mic. The attach menu's "Live conversation" row and its naming are removed, with their tests; the D37 note records the move. A new rail-* browser test presses the real mic with mouse and touch input and instruments getUserMedia and the network to prove a hold, or a cancelled one, captures nothing. Refs #3693 Co-Authored-By: Claude Opus 5.5 --- .changeset/composer-mic-gesture.md | 7 + docs/decisions/design-kit/navigation.md | 10 + packages/ui-kit/vitest.config.ts | 2 +- .../src/components/chat/composer-mic.tsx | 153 ++++++++++ .../src/components/chat/composer-view.tsx | 20 +- .../ui-react/src/components/chat/composer.tsx | 42 ++- .../tests/browser/attach-tooltip.pointer.tsx | 25 +- .../tests/browser/auth-expiry.offline.tsx | 4 +- .../tests/browser/composer-mic.pointer.tsx | 268 ++++++++++++++++++ .../browser/conversation-controls.offline.tsx | 38 +-- .../browser/dictation-gemini.offline.tsx | 2 +- .../browser/dictation-notice.pointer.tsx | 2 +- .../dictation-provider-end.offline.tsx | 2 +- .../tests/browser/local-capture.offline.tsx | 2 +- .../tests/render/render-smoke.test.tsx | 21 +- 15 files changed, 533 insertions(+), 65 deletions(-) create mode 100644 .changeset/composer-mic-gesture.md create mode 100644 packages/ui-react/src/components/chat/composer-mic.tsx create mode 100644 packages/ui-react/tests/browser/composer-mic.pointer.tsx diff --git a/.changeset/composer-mic-gesture.md b/.changeset/composer-mic-gesture.md new file mode 100644 index 0000000000..edc4b3929d --- /dev/null +++ b/.changeset/composer-mic-gesture.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-react": minor +--- + +The composer has one mic for both voice modes (#3693). Tap it to dictate, as before. Hold it for 0.6 s and the ring fills, then the live-conversation Start sheet opens, with a light haptic where the device supports one. Releasing earlier is a tap, and moving off the mic cancels the hold. Nothing is captured during a hold: no microphone, voice-service connection or history read starts until you pick dictation or press Start. On a keyboard, Enter or Space on the mic dictates and Shift+Enter opens Start; screen readers get a "Talk live…" action. Where live conversation isn't set up, the ring still fills and a notice explains instead. + +The attach menu no longer has a "Live conversation" row, and the paperclip's name is back to "Attach — photo, camera, files". The offline "Record on this device" mic has no hold. diff --git a/docs/decisions/design-kit/navigation.md b/docs/decisions/design-kit/navigation.md index 450faa1f5c..e176562838 100644 --- a/docs/decisions/design-kit/navigation.md +++ b/docs/decisions/design-kit/navigation.md @@ -54,6 +54,16 @@ The fifth drop answered the eleven questions the maintainer forwarded > composer detail (capture is a menu behind attach); it adds no separate > entry, no persistent desktop label and no touch long-press, and the kit > and the menu keep their ownership. + + > **2026-11-09 — Live entry moved to the mic by #3693 (epic #3690, ruling + > V1; composition signed off on #3727).** Live conversation is no longer a + > row in the attach menu, and the attach trigger's name no longer lists it: + > it is "Attach — photo, camera, files" again ("Attach — files" with the + > desktop Files menu). The composer's one mic is the kit's `MicButton` in + > the `micControl` slot: a tap dictates, and a 0.6 s hold opens Start + > (Shift+Enter on the mic, or its "Talk live…" action, for keyboards and + > screen readers). This supersedes the #3045 note above for live + > conversation only; the trigger's tooltip and its rules are unchanged. 5. **No snooze on a blocking approval**; "Always allow" has no key. 6. **Focus after the last decision in a list goes to the `EmptyState` heading that replaces the section, with the `InlineToast` receipt above it**; the diff --git a/packages/ui-kit/vitest.config.ts b/packages/ui-kit/vitest.config.ts index d23e179e11..8c14b3cae7 100644 --- a/packages/ui-kit/vitest.config.ts +++ b/packages/ui-kit/vitest.config.ts @@ -99,7 +99,7 @@ const railProject = (mode: "fine" | "coarse" | "mixed") => ({ // pointer; they need the consumer stylesheet. Button's hover text // contrast (#974) and the palette's reason rows (#1106) are measured // under all three pointers as well. - include: ["tests/visual/native-buttons.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx", "tests/visual/status-indicator-targets.visual.tsx", "../ui-react/tests/browser/desktop-navigation.pointer.tsx", "../ui-react/tests/browser/keyboard-hints.pointer.tsx", "../ui-react/tests/browser/phone-navigation.pointer.tsx", "../ui-react/tests/browser/destination-press.pointer.tsx", "../ui-react/tests/browser/working-sessions.pointer.tsx", "../ui-react/tests/browser/session-drafts.pointer.tsx", "../ui-react/tests/browser/navigation-reach.*.pointer.tsx", "../ui-react/tests/browser/hit-reach.*.pointer.tsx", "../ui-react/tests/browser/recordings-tray.offline.tsx", "../ui-react/tests/browser/dictation-notice.pointer.tsx", "../ui-react/tests/browser/attach-tooltip.pointer.tsx", "../ui-react/tests/browser/overlay-stacking.pointer.tsx", "../ui-react/tests/browser/session-profile.pointer.tsx", "../ui-react/tests/browser/turn-budget.pointer.tsx"], + include: ["tests/visual/native-buttons.visual.tsx", "tests/visual/side-rail-targets.visual.tsx", "tests/visual/button-hover-contrast.visual.tsx", "tests/visual/overlay-targets.visual.tsx", "tests/visual/session-strip.visual.tsx", "tests/visual/pending-follow-ups.visual.tsx", "tests/visual/palette-reasons.visual.tsx", "tests/visual/status-indicator-targets.visual.tsx", "../ui-react/tests/browser/desktop-navigation.pointer.tsx", "../ui-react/tests/browser/keyboard-hints.pointer.tsx", "../ui-react/tests/browser/phone-navigation.pointer.tsx", "../ui-react/tests/browser/destination-press.pointer.tsx", "../ui-react/tests/browser/working-sessions.pointer.tsx", "../ui-react/tests/browser/session-drafts.pointer.tsx", "../ui-react/tests/browser/navigation-reach.*.pointer.tsx", "../ui-react/tests/browser/hit-reach.*.pointer.tsx", "../ui-react/tests/browser/recordings-tray.offline.tsx", "../ui-react/tests/browser/dictation-notice.pointer.tsx", "../ui-react/tests/browser/attach-tooltip.pointer.tsx", "../ui-react/tests/browser/composer-mic.pointer.tsx", "../ui-react/tests/browser/overlay-stacking.pointer.tsx", "../ui-react/tests/browser/session-profile.pointer.tsx", "../ui-react/tests/browser/turn-budget.pointer.tsx"], provide: { railPointer: mode, keyboardHintsLive: false }, browser: { enabled: true, diff --git a/packages/ui-react/src/components/chat/composer-mic.tsx b/packages/ui-react/src/components/chat/composer-mic.tsx new file mode 100644 index 0000000000..84d92606ce --- /dev/null +++ b/packages/ui-react/src/components/chat/composer-mic.tsx @@ -0,0 +1,153 @@ +import { useEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from "react"; +import { MicButton, type MicPhase } from "@schlessera/brain-ui-kit"; + +/** V1 (#3690): a hold this long opens Start; an earlier release is a tap. */ +const HOLD_MS = 600; + +/** How long a stray click after a hold or a cancelled hold is swallowed. */ +const SWALLOW_MS = 1000; + +interface ComposerMicProps { + /** The accessible name: "Dictate", "Dictate · ", "Record on this device". */ + name?: string; + /** A tap, Enter or Space. */ + onTap?: () => void; + /** + * A completed hold, Shift+Enter or "Talk live…". Absent: the mic has no + * hold (M1, #3727), so a long press is a tap and no hint is drawn. + */ + onTalkLive?: () => void; +} + +/** + * The composer's one mic (#3693): tap to dictate, hold to talk live. + * + * The kit's `MicButton` is presentational; this owns the hold. A press + * fills the ring from elapsed time, and at 0.6 s the hold completes: a light + * haptic where the device has one, then `onTalkLive`. Releasing earlier is a + * tap, so the button's own click dictates. Leaving the mic, or a cancelled + * pointer, ends the hold with nothing done. + * + * Nothing is captured during a hold: the press starts a timer and an + * animation frame loop, and nothing else. No microphone, provider or history + * work starts until the user picks dictation or presses Start. + */ +export function ComposerMic(p: ComposerMicProps) { + const [phase, setPhase] = useState("idle"); + const [progress, setProgress] = useState(0); + const timer = useRef | null>(null); + const frame = useRef(null); + const holding = useRef(false); + const swallow = useRef<(() => void) | null>(null); + const latest = useRef(p); + latest.current = p; + + function stopTimers() { + if (timer.current !== null) clearTimeout(timer.current); + if (frame.current !== null) cancelAnimationFrame(frame.current); + timer.current = null; + frame.current = null; + } + + /** + * After a hold completes or is cancelled, the release can still produce a + * click (on the mic, or on whatever replaced it). That click is not a tap. + * The next press of any kind ends the guard, so a later tap is never lost. + */ + function swallowNextClick() { + swallow.current?.(); + const click = (event: MouseEvent) => { event.preventDefault(); event.stopPropagation(); end(); }; + const end = () => { + window.removeEventListener("click", click, true); + window.removeEventListener("pointerdown", end, true); + window.removeEventListener("keydown", end, true); + clearTimeout(expiry); + if (swallow.current === end) swallow.current = null; + }; + const expiry = setTimeout(end, SWALLOW_MS); + window.addEventListener("click", click, true); + window.addEventListener("pointerdown", end, true); + window.addEventListener("keydown", end, true); + swallow.current = end; + } + + // A completed hold usually unmounts the composer (Start replaces it). The + // click guard outlives it on purpose, and ends on its own. + useEffect(() => stopTimers, []); + + function reset() { + stopTimers(); + holding.current = false; + setPhase("idle"); + setProgress(0); + } + + function onPointerDown(event: PointerEvent) { + if (!latest.current.onTalkLive || event.button !== 0 || holding.current) return; + // A touch is captured implicitly, to whatever it landed on: the button, + // or the icon inside it. Release it so leaving the mic is seen, and + // cancels the hold. + const landed = event.target instanceof Element ? event.target : event.currentTarget; + if (landed.hasPointerCapture?.(event.pointerId)) landed.releasePointerCapture(event.pointerId); + // A touch's compatibility mousedown arrives after the finger lifts, and + // would pull focus back from what the hold opened. The click that makes + // a tap is not one of those events, and still arrives. + if (event.pointerType === "touch") event.preventDefault(); + holding.current = true; + const started = performance.now(); + setPhase("pressed"); + setProgress(0); + const tick = () => { + const fill = Math.min(1, (performance.now() - started) / HOLD_MS); + setPhase("holding"); + setProgress(fill); + frame.current = fill < 1 ? requestAnimationFrame(tick) : null; + }; + frame.current = requestAnimationFrame(tick); + timer.current = setTimeout(() => { + stopTimers(); + holding.current = false; + setPhase("complete"); + setProgress(1); + swallowNextClick(); + try { navigator.vibrate?.(10); } catch { /* No haptic on this device. */ } + latest.current.onTalkLive?.(); + }, HOLD_MS); + } + + function onPointerUp() { + // Released before the hold completed: the click that follows is the tap. + if (holding.current) reset(); + else if (phase === "complete") reset(); + } + + function cancel() { + if (!holding.current) return; + reset(); + swallowNextClick(); + } + + function onKeyDown(event: KeyboardEvent) { + if (event.key === "Enter" && event.shiftKey && latest.current.onTalkLive) { + // Shift+Enter opens Start; Enter and Space stay the button's click. + event.preventDefault(); + latest.current.onTalkLive(); + } + } + + return ( + + ); +} diff --git a/packages/ui-react/src/components/chat/composer-view.tsx b/packages/ui-react/src/components/chat/composer-view.tsx index ef0e913b34..2b7a6de019 100644 --- a/packages/ui-react/src/components/chat/composer-view.tsx +++ b/packages/ui-react/src/components/chat/composer-view.tsx @@ -54,7 +54,6 @@ interface ComposerProvider { export interface ComposerViewProps { /** Capture panel, kept inside the existing bounded composer frame. */ dictation?: ReactNode; - onConversation?: () => void; /** * Why the mic cannot record, in place of the capture panel: a refused * microphone, or a browser that cannot record on the device (#1012). @@ -71,6 +70,11 @@ export interface ComposerViewProps { micUnavailable?: string; /** Off: no mic is drawn, because there is no capture to offer. */ mic?: boolean; + /** + * The composer's hold-to-talk mic (#3693), drawn in the kit's mic slot. + * When set, `mic`, `onMic`, `micLabel`, `micTip` and `micUnavailable` do not apply. + */ + micControl?: ReactNode; value: string; state: ComposerState; /** Overrides the state's own placeholder (a connection reason, the host's copy). */ @@ -180,20 +184,17 @@ export function ComposerView(p: ComposerViewProps) { const pointer = useMediaQuery("(min-width: 900px)"); const files = p.onPickFiles ? p.files : undefined; const fileCount = (files?.queued.length ?? 0) + (files?.stored.length ?? 0); - // The trigger's name lists what its menu offers, in menu order (#3045): - // live conversation is reached through the paperclip, so the paperclip says - // so whenever the row is there. The kit paints the same string as the - // pointer tooltip; a phone's sheet names the actions in its subtitle. + // The trigger's name lists what its menu offers, in menu order (#3045). + // Live conversation is no longer in it: the mic's hold opens it (#3693). // Desktop with composer files: one unrestricted Files action (desktop // menu A, #3155); phones keep Photo library and Camera beside it. const desktopFiles = pointer && !!p.onPickFiles; - const attachLabel = p.onConversation ? `Attach — live conversation, ${desktopFiles ? "files" : "photo, camera, files"}` : desktopFiles ? "Attach — files" : undefined; + const attachLabel = desktopFiles ? "Attach — files" : undefined; const attachSubtitle = p.onPickFiles - ? `${p.onConversation ? "Live conversation, photo" : "Photo"}, camera, files or paste.` - : `${p.onConversation ? "Live conversation, photo" : "Photo"}, camera, ${p.onPickTracks ? "track files, " : ""}or paste.`; + ? "Photo, camera, files or paste." + : `Photo, camera, ${p.onPickTracks ? "track files, " : ""}or paste.`; const attachMenu = (
- {p.onConversation && } {!desktopFiles && } {!desktopFiles && } {p.onPickFiles @@ -303,6 +304,7 @@ export function ComposerView(p: ComposerViewProps) { micLabel={p.micLabel} micTip={p.micTip} micUnavailable={p.micUnavailable} + micControl={p.micControl} />
); diff --git a/packages/ui-react/src/components/chat/composer.tsx b/packages/ui-react/src/components/chat/composer.tsx index 0eb5854990..9f5e80703f 100644 --- a/packages/ui-react/src/components/chat/composer.tsx +++ b/packages/ui-react/src/components/chat/composer.tsx @@ -1,7 +1,7 @@ import { useStore } from "zustand"; import { ConversationUnassigned } from "../voice/conversation-unassigned.js"; import { ConversationStrip } from "../voice/conversation-strip.js"; -import { InlineToast } from "@schlessera/brain-ui-kit"; +import { InlineToast, VoiceNotice } from "@schlessera/brain-ui-kit"; import { useBrainUiRoot, useRootStore } from "../../root-context.js"; import { useState, useRef, useEffect, useLayoutEffect, useImperativeHandle, useReducer, type Ref } from "react"; import { resolveThinkingLevel } from "@schlessera/brain-ui-sdk/internal/client"; @@ -18,6 +18,7 @@ import { import { ShareIntake } from "./share-card.js"; import { CommandPalette, exactCommand, matchCommands } from "./command-palette.js"; import { ComposerView } from "./composer-view.js"; +import { ComposerMic } from "./composer-mic.js"; import { RecordingsTray } from "../voice/recordings-tray.js"; import { LocalRecordingSheet } from "../voice/local-recording-sheet.js"; import { DictationSheet } from "../voice/dictation-sheet.js"; @@ -338,6 +339,14 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void const dictationUnavailable = micMode === "dictate" && voiceMode !== "dictate" && discovery?.providers.length === 0 ? "Dictation isn\u0027t set up on this host." : undefined; + const micLabel = micMode !== "local" ? voiceMode === "dictate" ? undefined : dictateLabel : localPhase === "idle" || localPhase === "opening" ? "Record on this device" : "Stop and save"; + // The hold-to-talk mic at rest (#3693, drawn as signed off on #3727): it + // dictates, or records on the device with no hold (M1). Dictating, a + // recording in progress and a mic still deciding keep the kit's own mic. + // With neither dictation nor live conversation here, the kit's disabled + // mic still says why, since a hold would have nothing to offer. + const restingMic = (micMode === "dictate" && voiceMode !== "dictate" && !(dictationUnavailable && !conversation.available)) + || (micMode === "local" && (localPhase === "idle" || localPhase === "opening")); const [dismissedLocalNotice, setDismissedLocalNotice] = useState(null); const captureNotice = micMode === "unsupported" ? "This browser can't save recordings on the device. You can type a note and send it when you're back online." @@ -779,6 +788,29 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void } } + // The mic's hold (#3693): Start when live conversation is offered here, + // otherwise the S4 notice (V4). A hold itself captures nothing. + const [liveNotice, setLiveNotice] = useState(false); + function handleTalkLive() { + setAttachMenuOpen(false); + setProviderMenuOpen(false); + const voice = root.stores.voice.getState(); + if (voice.mode !== "idle" || voice.local !== "idle") return; + if (root.connection.conversation.state.getState().available) { setLiveNotice(false); root.connection.conversation.enter(); } + else setLiveNotice(true); + } + function dismissLiveNotice() { + setLiveNotice(false); + focusMic(); + } + // The notice answers one hold; it goes once the mic does something else. + useEffect(() => { if (voiceMode !== "idle" || conversation.active) setLiveNotice(false); }, [voiceMode, conversation.active]); + useEffect(() => { + if (!liveNotice) return; + const ok = [...frameRef.current?.querySelectorAll("[data-live-notice] button") ?? []].find(b => b.textContent === "OK"); + ok?.focus({ preventScroll: true }); + }, [liveNotice]); + function handleVoiceSend() { if (!draftText() || isStreaming || wsStatus !== "connected") { // If we cannot send right now, fall back to editing @@ -892,8 +924,10 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void {filesOn && } { setAttachMenuOpen(false); root.connection.conversation.enter(); } : undefined} - dictation={<> : undefined} + dictation={<>{liveNotice &&
+ +
} dictation.cancel()} onConfirm={dictation.confirm} onOpenSettings={() => { dictation.cancel(); root.stores.ui.getState().openSettings("voice"); }} /> {root.localCapture?.durable && }} @@ -902,7 +936,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void captureNotice={captureNotice !== dismissedLocalNotice ? captureNotice : undefined} onDismissCaptureNotice={() => dismissNotice("local")} mic={micMode !== "unsupported"} - micLabel={micMode !== "local" ? voiceMode === "dictate" ? undefined : dictateLabel : localPhase === "idle" || localPhase === "opening" ? "Record on this device" : "Stop and save"} + micLabel={micLabel} micTip={micMode === "dictate" && voiceMode !== "dictate" && dictateLabel !== undefined} micUnavailable={dictationUnavailable} value={input} diff --git a/packages/ui-react/tests/browser/attach-tooltip.pointer.tsx b/packages/ui-react/tests/browser/attach-tooltip.pointer.tsx index 398f753827..7385eebac1 100644 --- a/packages/ui-react/tests/browser/attach-tooltip.pointer.tsx +++ b/packages/ui-react/tests/browser/attach-tooltip.pointer.tsx @@ -7,8 +7,9 @@ * A hovering primary pointer gets the tooltip on hover and on keyboard focus * (the `ui-react-layout` scene in `conversation-controls.offline.tsx` times it). * A touch-only device never renders it — not on focus, not after a tap — and - * reads the name in the attach sheet instead. The live row still leads to the - * first-entry disclosure and nothing opens a provider or a microphone. + * reads the name in the attach sheet instead. Live conversation is no longer + * in the menu or its name: the mic's hold opens it (#3693, + * `composer-mic.pointer.tsx`). */ import { afterAll, beforeAll, expect, inject, test, type TestContext } from "vitest"; import { commands, page, userEvent } from "vitest/browser"; @@ -26,7 +27,7 @@ declare module "vitest" { } const SESSION = "odysseus-ithaca"; -const LIVE_ATTACH = "Attach — live conversation, photo, camera, files"; +const ATTACH = "Attach — photo, camera, files"; const PROFILE = conversationProfileSchema.parse({ providerId: "gpt-live", capabilities: { nonblockingWork: "supported", manualEndpoint: "supported", finalTranscript: "unproven", remoteOutputCancelAck: "unproven", exactPermissionSpeech: "unproven", echoIsolatedInput: "unproven", outputWordAlignment: "unproven" }, @@ -68,10 +69,10 @@ for (const theme of ["light", "dark"] as const) for (const [width, height] of [[ if (mode === "coarse") expect(touch, "touch premise").toBe(true); expect(matchMedia("(prefers-reduced-motion: reduce)").matches, "reduced motion premise").toBe(true); const s = await scene(ctx, width, height, theme); - const trigger = page.getByRole("button", { name: LIVE_ATTACH, exact: true }).element() as HTMLElement; + const trigger = page.getByRole("button", { name: ATTACH, exact: true }).element() as HTMLElement; const tip = trigger.querySelector("[data-composer-tip]")!; const shown = () => getComputedStyle(tip).display !== "none" && getComputedStyle(tip).visibility === "visible"; - expect(tip.textContent).toBe(LIVE_ATTACH); + expect(tip.textContent).toBe(ATTACH); // Keyboard focus: at once with a hovering pointer, never on touch. s.host.querySelector("textarea[data-composer]")!.focus(); @@ -95,15 +96,11 @@ for (const theme of ["light", "dark"] as const) for (const [width, height] of [[ } if (width < 900) { await expect.poll(() => document.querySelector('[data-overlay-site="attach"]')).not.toBe(null); - expect(document.querySelector('[data-overlay-site="attach"]')!.textContent, "the sheet names live conversation").toContain("Live conversation, photo, camera, track files, or paste."); + expect(document.querySelector('[data-overlay-site="attach"]')!.textContent, "the sheet names the menu's actions").toContain("Photo, camera, track files, or paste."); } else await expect.element(page.getByRole("menu", { name: "Attach" })).toBeInTheDocument(); - const row = page.getByRole("button", { name: /^Live conversation/ }).element() as HTMLElement; - if (touch) expect(row.getBoundingClientRect().height, "the live row is a 44px target").toBeGreaterThanOrEqual(44); + expect(document.body.textContent, "live conversation is the mic's hold, not a menu row").not.toContain("Live conversation"); await page.screenshot({ element: s.host, path: `../../.vitest-attachments/attach-tooltip/${mode}-${theme}-${width}-menu.png` }); - if (touch) { const r = row.getBoundingClientRect(); await commands.rankTap({ x: r.x + r.width / 2, y: r.y + r.height / 2 }); } - else await userEvent.click(row); - await expect.poll(() => s.client.state.getState().disclosureOpen).toBe(true); - expect(s.client.state.getState().micOn).toBe(false); - expect(s.network.socket()!.frames("conversation_start"), "ENTRY_DISCLOSES_WITHOUT_OPENING_PROVIDER").toHaveLength(0); - expect(s.network.socket()!.frames("conversation_audio")).toHaveLength(0); + await userEvent.keyboard("{Escape}"); + await expect.poll(() => document.querySelector('[data-overlay-site="attach"],[role="menu"]')).toBe(null); + expect(s.client.state.getState().disclosureOpen).toBe(false); }); diff --git a/packages/ui-react/tests/browser/auth-expiry.offline.tsx b/packages/ui-react/tests/browser/auth-expiry.offline.tsx index c584b6f0be..cafddf5f7a 100644 --- a/packages/ui-react/tests/browser/auth-expiry.offline.tsx +++ b/packages/ui-react/tests/browser/auth-expiry.offline.tsx @@ -90,7 +90,7 @@ async function mount(ctx: TestContext, providerId: "deepgram" | "webspeech", loc return { ui, host, net, snapshot }; } -const dictate = (s: Scene) => s.host.querySelector('[data-composer] [role="button"][aria-label^="Dictate"]'); +const dictate = (s: Scene) => s.host.querySelector('[data-composer] :is(button,[role="button"])[aria-label^="Dictate"]'); /** Taps Dictate and waits for the provider's client to be listening. */ async function startDictating(s: Scene) { @@ -140,7 +140,7 @@ test("transport drop keeps local capture and protected views mounted; auth expir s.net.drop(); await expect.poll(()=>s.ui.stores.connection.getState().wsStatus).toBe("disconnected"); await settle(); - const local=()=>s.host.querySelector('[data-composer] [role="button"][aria-label="Record on this device"]'); + const local=()=>s.host.querySelector('[data-composer] :is(button,[role="button"])[aria-label="Record on this device"]'); await expect.poll(local).not.toBeNull(); await userEvent.click(local()!); await expect.poll(()=>s.ui.stores.voice.getState().local).toBe("recording"); expect(mic.streams.length).toBeGreaterThan(0); diff --git a/packages/ui-react/tests/browser/composer-mic.pointer.tsx b/packages/ui-react/tests/browser/composer-mic.pointer.tsx new file mode 100644 index 0000000000..6e11b99c46 --- /dev/null +++ b/packages/ui-react/tests/browser/composer-mic.pointer.tsx @@ -0,0 +1,268 @@ +/// +/** + * The composer's one mic (#3693): tap to dictate, hold for 0.6 s to open + * Start, in Chromium launched as a fine, coarse or mixed device (the `rail-*` + * projects). Each scene presses the real mic with native input: a mouse under + * a fine pointer, a touch under a coarse one, and both under a mixed one. + * + * Nothing is captured during a hold. The real browser APIs are instrumented: + * `MediaDevices.prototype.getUserMedia`, and #1016's fault network for + * `fetch`, XHR, beacons, every WebSocket and every frame sent, so a hold, or + * a hold that was cancelled, is proven to have opened no microphone, no + * provider connection and no history read. Each instrument is restored with + * its complete property descriptor when the test ends. + */ +import { afterAll, beforeAll, expect, inject, onTestFinished, test, type TestContext } from "vitest"; +import { commands, page, userEvent } from "vitest/browser"; +import { createRoot } from "react-dom/client"; +import { flushSync } from "react-dom"; +import type { VoiceSessionResponse } from "@schlessera/brain-ui-sdk/client"; +import { conversationProfileSchema, serverHelloSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { createBrainUiRoot } from "../../src/root.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { AppShell } from "../../src/components/layout/app-shell.js"; +import { ChatPage } from "../../src/components/chat/chat-page.js"; +import { installFaultNetwork } from "./offline/fault-network.js"; +import { primeDictation } from "../fixtures/dictation-discovery.js"; + +declare module "vitest" { + interface ProvidedContext { railPointer: "fine" | "coarse" | "mixed"; } +} + +const SESSION = "odysseus-ithaca"; +const SPEECH = "wss://speech.invalid/v1/listen"; +const PROFILE = conversationProfileSchema.parse({ + providerId: "gpt-live", + capabilities: { nonblockingWork: "supported", manualEndpoint: "supported", finalTranscript: "unproven", remoteOutputCancelAck: "unproven", exactPermissionSpeech: "unproven", echoIsolatedInput: "unproven", outputWordAlignment: "unproven" }, + disclosure: { voiceService: "Odysseus voice fixture", destinations: ["Audio and transcripts: fictional fixture. Retention: unknown."] }, +}); +const HELLO = serverHelloSchema.parse({ type: "server_hello", protocolRev: 5, principalKey: "odysseus-principal", capabilities: { liveConversation: true, conversationPause: true, toolResolution: true, chatRequestAck: true }, conversationProfile: PROFILE }); +const SPEECH_SESSION: VoiceSessionResponse = { providerId: "deepgram", url: SPEECH, token: "odysseus-grant", expiresAt: Date.now() + 60 * 60_000, capabilities: { streaming: true, interimResults: true, keyterms: false, endpointing: false } }; +const S4 = "Live conversation isn’t set up here"; + +let styles: HTMLStyleElement; +beforeAll(async () => { styles = document.createElement("style"); styles.textContent = await commands.formConsumerStyles(); document.head.append(styles); }); +afterAll(() => styles.remove()); + +const wait = (ms: number) => new Promise(done => setTimeout(done, ms)); + +/** Replaces one property for the test and puts its complete descriptor back afterwards. */ +function instrument(ctx: TestContext, target: T, key: PropertyKey, value: unknown) { + const own = Object.getOwnPropertyDescriptor(target, key); + Object.defineProperty(target, key, { configurable: true, writable: true, value }); + ctx.onTestFinished(() => { if (own) Object.defineProperty(target, key, own); else delete (target as Record)[key]; }); +} + +async function scene(ctx: TestContext, width: number) { + const viewport = { width: innerWidth, height: innerHeight }; + const outer = await commands.formViewport(width, 720); + await page.viewport(width, 720); + const network = installFaultNetwork({ + routes: url => url.pathname.endsWith("/sessions") ? Response.json({ sessions: [] }) + : url.pathname.endsWith("/voice/session") ? Response.json(SPEECH_SESSION) + : url.pathname.endsWith("/voice/overrides") ? Response.json({ overrides: [] }) : undefined, + onOpen(socket) { + if (socket.url.startsWith(SPEECH)) return; + socket.deliver(HELLO); socket.deliver({ type: "session_info", sessionId: SESSION, isNew: false }); socket.deliver({ type: "session_history", sessionId: SESSION, messages: [] }); socket.deliver({ type: "status", sessionId: SESSION, status: "idle" }); + }, + }); + // After the fault network, so its own restore runs last. + const microphone: string[] = []; + const realGetUserMedia = MediaDevices.prototype.getUserMedia; + instrument(ctx, MediaDevices.prototype, "getUserMedia", function spiedGetUserMedia(this: MediaDevices, constraints?: MediaStreamConstraints) { + microphone.push(JSON.stringify(constraints ?? {})); + return realGetUserMedia.call(this, constraints); + }); + const haptics: unknown[] = []; + instrument(ctx, navigator, "vibrate", (pattern: VibratePattern) => { haptics.push(pattern); return true; }); + + const ui = createBrainUiRoot({ storage: null, request: network.request }); + primeDictation(ui, "deepgram"); + ui.stores.chat.getState().setActiveSession(SESSION); + const host = document.createElement("div"); + host.style.cssText = `position:fixed;inset:0;width:${width}px;height:720px`; + document.body.append(host); + const renderer = createRoot(host); + flushSync(() => renderer.render()); + const release = ui.connection.connect(); + ctx.onTestFinished(async () => { flushSync(() => renderer.unmount()); release(); ui.dispose(); network.restore(); host.remove(); await page.viewport(viewport.width, viewport.height); await commands.formViewport(outer.width - 100, outer.height - 120); }); + await expect.poll(() => ui.stores.connection.getState().wsStatus).toBe("connected"); + await expect.poll(() => ui.connection.conversation.state.getState().available).toBe(true); + const mic = () => host.querySelector('[data-composer-mic] button.bk-voice-mic'); + await expect.poll(mic, { message: "the composer draws the hold-to-talk mic" }).not.toBe(null); + expect(mic()!.getAttribute("aria-label")).toBe("Dictate · Deepgram"); + // A first press would focus the window, and focus refreshes the shell's + // storage evidence. Focus it now, so the window below holds only the gesture. + await userEvent.click(host.querySelector("textarea[data-composer]")!); + expect(document.hasFocus(), "the window has focus before the gesture").toBe(true); + // Let start-up reads settle, so the window below holds only the gesture. + // The shell's storage indicator reads its guidance once the session is + // active; it is the last start-up read, and it is not the mic's. + await expect.poll(() => network.requests.some(r => new URL(r.url).pathname.endsWith("/storage/guidance")), { timeout: 5_000 }).toBe(true); + let settled = -1; + await expect.poll(async () => { const now = network.requests.length + network.frames.length; const quiet = now === settled; settled = now; await wait(300); return quiet; }, { timeout: 5_000 }).toBe(true); + /** Everything a hold must not start: a microphone, a request, a socket, a frame. */ + const traffic = () => ({ + microphone: [...microphone], + requests: network.requests.map(r => `${r.via} ${r.method} ${new URL(r.url).pathname}`), + sockets: network.sockets.map(socket => socket.url), + frames: network.frames.map(frame => typeof frame.data === "string" ? String(JSON.parse(frame.data).type) : `binary ${frame.bytes}`), + }); + return { ui, host, network, mic, traffic, microphone, haptics, client: ui.connection.conversation }; +} + +type Kind = "mouse" | "touch"; + +function centre(el: Element) { + const box = el.getBoundingClientRect(); + return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; +} +/** A press that a failed assertion leaves down is lifted when its test ends. */ +function press(kind: Kind, at: { x: number; y: number }) { + onTestFinished(() => commands.sheetInput(kind, [{ type: "up", ...at, t: 0 }])); + return commands.sheetInput(kind, [{ type: "down", ...at, t: 0 }]); +} +const move = (kind: Kind, at: { x: number; y: number }, t: number) => commands.sheetInput(kind, [{ type: "move", ...at, t }]); +const lift = (kind: Kind, at: { x: number; y: number }, t: number) => commands.sheetInput(kind, [{ type: "up", ...at, t }]); + +const MODE = inject("railPointer"); +/** A mouse under a fine pointer, a touch under a coarse one, both under a mixed one. */ +const KINDS: Kind[] = MODE === "coarse" ? ["touch"] : MODE === "fine" ? ["mouse"] : ["mouse", "touch"]; + +function premise() { + const mode = MODE; + if (mode === "coarse") expect(matchMedia("(pointer: coarse)").matches, "coarse premise").toBe(true); + if (mode === "fine") expect(matchMedia("(any-pointer: coarse)").matches, "fine premise").toBe(false); +} + +for (const kind of KINDS) for (const width of [320, 1280] as const) test(`a completed hold opens Start and captures nothing on the way ${kind} ${width}`, async ctx => { + premise(); + { + const s = await scene(ctx, width); + const at = centre(s.mic()!); + const before = s.traffic(); + await press(kind, at); + // Mid-hold: the ring fills and the hint explains, and nothing has started. + await expect.poll(() => s.mic()!.dataset.phase, { message: `${kind}: the ring fills` }).toBe("holding"); + await expect.poll(() => s.host.querySelector(".bk-voice-hint")?.textContent).toBe("Keep holding to talk live"); + await wait(250); + expect(Number(s.mic()!.querySelector(".bk-voice-ring")?.getAttribute("data-progress")), `${kind}: progress follows elapsed time`).toBeGreaterThan(0); + expect(s.client.state.getState().disclosureOpen, `${kind}: 0.6 s has not passed`).toBe(false); + expect(s.traffic(), `${kind}: HOLD_CAPTURES_NOTHING`).toEqual(before); + // Still held: at 0.6 s Start opens, with a light haptic. + await expect.poll(() => s.client.state.getState().disclosureOpen, { message: `${kind}: the hold opens Start` }).toBe(true); + expect(s.haptics, `${kind}: one light haptic`).toEqual([10]); + await lift(kind, at, 900); + await wait(100); + // The release is not a tap: Start stays, and no dictation began. + expect(s.client.state.getState().disclosureOpen, `${kind}: the release does not dismiss Start`).toBe(true); + expect(s.ui.stores.voice.getState().mode).toBe("conversation"); + expect(s.microphone, `${kind}: Start is not Start pressed`).toEqual([]); + expect(s.traffic().frames.filter(type => type !== "conversation_enter"), `${kind}: no provider bytes before Start`).toEqual(before.frames); + expect(s.network.socket()!.frames("conversation_start")).toHaveLength(0); + await userEvent.click(page.getByRole("button", { name: "Cancel", exact: true })); + expect(s.client.state.getState().active).toBe(false); + } +}); + +for (const kind of KINDS) for (const width of [320, 1280] as const) test(`an early release dictates, and never opens Start ${kind} ${width}`, async ctx => { + premise(); + { + const s = await scene(ctx, width); + const at = centre(s.mic()!); + await press(kind, at); + await wait(250); + await lift(kind, at, 250); + await expect.poll(() => s.ui.stores.voice.getState().mode, { message: `${kind}: the tap dictates` }).toBe("dictate"); + await wait(600); + expect(s.client.state.getState().disclosureOpen, `${kind}: EARLY_RELEASE_NEVER_OPENS_START`).toBe(false); + expect(s.client.state.getState().active).toBe(false); + expect(s.haptics).toEqual([]); + // The dictation path is the one that opens the microphone. + await expect.poll(() => s.microphone.length, { message: `${kind}: dictation opens the microphone`, timeout: 5_000 }).toBeGreaterThan(0); + } +}); + +for (const kind of KINDS) for (const width of [320, 1280] as const) test(`leaving the mic cancels the hold, and nothing is captured after it ${kind} ${width}`, async ctx => { + premise(); + { + const s = await scene(ctx, width); + const at = centre(s.mic()!); + const before = s.traffic(); + await press(kind, at); + await expect.poll(() => s.mic()!.dataset.phase).toBe("holding"); + const away = { x: at.x - 120, y: at.y - 160 }; + await move(kind, away, 150); + await expect.poll(() => s.mic()?.dataset.phase ?? "no mic: the hold completed", { message: `${kind}: leaving cancels` }).toBe("idle"); + expect(s.host.querySelector(".bk-voice-hint"), `${kind}: the hint goes with the hold`).toBe(null); + await wait(700); + // Back over the mic and released there: still not a tap, and not a hold. + await move(kind, at, 850); + await lift(kind, at, 900); + await wait(300); + expect(s.client.state.getState().disclosureOpen, `${kind}: a cancelled hold never opens Start`).toBe(false); + expect(s.ui.stores.voice.getState().mode, `${kind}: a cancelled hold does not dictate`).toBe("idle"); + expect(s.haptics).toEqual([]); + expect(s.traffic(), `${kind}: CANCELLED_HOLD_CAPTURES_NOTHING`).toEqual(before); + // The next tap is still a tap. + await press(kind, at); + await lift(kind, at, 100); + await expect.poll(() => s.ui.stores.voice.getState().mode, { message: `${kind}: the next tap dictates` }).toBe("dictate"); + } +}); + +for (const kind of KINDS) for (const width of [320, 1280] as const) test(`without live conversation the ring fills, then S4 explains ${kind} ${width}`, async ctx => { + premise(); + { + const s = await scene(ctx, width); + flushSync(() => s.client.state.setState({ available: false })); + const at = centre(s.mic()!); + const before = s.traffic(); + await press(kind, at); + await expect.poll(() => s.mic()!.dataset.phase, { message: `${kind}: the ring still fills (V4)` }).toBe("holding"); + await expect.poll(() => s.host.textContent, { message: `${kind}: S4 replaces Start` }).toContain(S4); + expect(s.haptics).toEqual([10]); + await lift(kind, at, 800); + await wait(150); + expect(s.client.state.getState().active, `${kind}: Start does not open`).toBe(false); + expect(s.ui.stores.voice.getState().mode, `${kind}: the release is not a tap`).toBe("idle"); + expect(s.traffic(), `${kind}: S4 captures nothing`).toEqual(before); + const ok = page.getByRole("button", { name: "OK", exact: true }); + expect(document.activeElement, `${kind}: the notice takes focus`).toBe(ok.element()); + await userEvent.keyboard("{Enter}"); + await expect.poll(() => s.host.textContent).not.toContain(S4); + await expect.poll(() => document.activeElement, { message: `${kind}: OK hands focus back to the mic` }).toBe(s.mic()); + } +}); + +test("the keyboard and a screen reader reach both modes", async ctx => { + premise(); + const s = await scene(ctx, 1280); + s.mic()!.focus(); + await userEvent.keyboard("{Shift>}{Enter}{/Shift}"); + await expect.poll(() => s.client.state.getState().disclosureOpen, { message: "Shift+Enter opens Start" }).toBe(true); + expect(s.ui.stores.voice.getState().mode, "Shift+Enter does not dictate").toBe("conversation"); + await userEvent.click(page.getByRole("button", { name: "Cancel", exact: true })); + await expect.poll(s.mic).not.toBe(null); + + // "Talk live…": the screen reader's way, focusable and named. + const talkLive = page.getByRole("button", { name: "Talk live…", exact: true }).element() as HTMLElement; + talkLive.focus(); + expect(document.activeElement).toBe(talkLive); + await userEvent.keyboard("{Enter}"); + await expect.poll(() => s.client.state.getState().disclosureOpen, { message: "Talk live… opens Start" }).toBe(true); + await userEvent.click(page.getByRole("button", { name: "Cancel", exact: true })); + await expect.poll(s.mic).not.toBe(null); + expect(s.microphone, "neither path opened the microphone").toEqual([]); + + for (const key of ["{Enter}", " "]) { + s.mic()!.focus(); + await userEvent.keyboard(key); + await expect.poll(() => s.ui.stores.voice.getState().mode, { message: `${key} dictates` }).toBe("dictate"); + expect(s.client.state.getState().disclosureOpen).toBe(false); + await expect.poll(() => s.ui.stores.voice.getState().connecting, { timeout: 5_000 }).toBe(false); + await userEvent.keyboard("{Escape}"); + await expect.poll(() => s.ui.stores.voice.getState().mode).toBe("idle"); + await expect.poll(s.mic).not.toBe(null); + } +}); diff --git a/packages/ui-react/tests/browser/conversation-controls.offline.tsx b/packages/ui-react/tests/browser/conversation-controls.offline.tsx index 5e6501ba45..3cf793af08 100644 --- a/packages/ui-react/tests/browser/conversation-controls.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-controls.offline.tsx @@ -15,7 +15,9 @@ const SESSION = "odysseus-ithaca"; const PROFILE: ServerConversationOpened = { type: "conversation_opened", conversationId: "ithaca-voice", epoch: 1, sessionId: SESSION, providerId: "gpt-live", capabilities: { nonblockingWork: "supported", manualEndpoint: "supported", finalTranscript: "unproven", remoteOutputCancelAck: "unproven", exactPermissionSpeech: "unproven", echoIsolatedInput: "unproven", outputWordAlignment: "unproven" }, disclosure: { voiceService: "Odysseus voice fixture", destinations: ["Audio and transcripts: fictional fixture. Retention: unknown."] }, limits: { ...CONVERSATION_LIMITS }, resync: { work: 0, outputs: 0 } }; const DISCLOSED_PROFILE = conversationProfileSchema.parse({providerId:PROFILE.providerId,capabilities:PROFILE.capabilities,disclosure:PROFILE.disclosure}); const HELLO = serverHelloSchema.parse({type:"server_hello",protocolRev:5,principalKey:"odysseus-principal",capabilities:{liveConversation:true,conversationPause:true,toolResolution:true},conversationProfile:DISCLOSED_PROFILE}); -const LIVE_ATTACH = "Attach — live conversation, photo, camera, files"; +const ATTACH = "Attach — photo, camera, files"; +/** The composer's one mic (#3693): Shift+Enter on it opens Start, as a completed hold does. */ +const mic = () => document.querySelector('[data-composer-mic] button[aria-label^="Dictate"]')!; let styles: HTMLStyleElement; beforeAll(async () => { styles = document.createElement("style"); styles.textContent = await commands.formConsumerStyles(); document.head.append(styles); }); afterAll(() => styles.remove()); @@ -125,9 +127,11 @@ for (const theme of ["light", "dark"] as const) for (const [width, height, scale for (const theme of ["light", "dark"] as const) test(`entry and connecting disclosure ${theme}`, async ctx => { const s = await scene(ctx, 1280, 720, theme); - await userEvent.click(page.getByRole("button", { name: LIVE_ATTACH, exact: true })); + await expect.poll(() => s.client.state.getState().available).toBe(true); + await expect.poll(() => document.querySelector('[data-composer-mic] button[aria-label^="Dictate"]')).not.toBe(null); + mic().focus(); await s.capture("entry"); - await userEvent.click(page.getByRole("button", { name: /Live conversation/ })); + await userEvent.keyboard("{Shift>}{Enter}{/Shift}"); await expect.poll(() => s.client.state.getState().disclosureOpen).toBe(true); await s.capture("connecting-disclosure"); expect(s.client.state.getState().micOn).toBe(false); @@ -151,8 +155,9 @@ for (const theme of ["light", "dark"] as const) test(`entry and connecting discl expect(s.client.state.getState().active).toBe(false); }); -// #3045: the paperclip names live conversation, and a pointer can read that -// name as a tooltip; a touch screen reads it in the attach sheet instead. +// #3045: the paperclip names its menu, and a pointer can read that name as a +// tooltip; a touch screen reads it in the attach sheet instead. Live +// conversation is not in the menu: the mic's hold opens it (#3693). for (const theme of ["light", "dark"] as const) for (const [width, height] of [[1280, 720], [320, 568]] as const) test(`entry is named from the paperclip ${theme} ${width}x${height}`, async ctx => { const s = await scene(ctx, width, height, theme); const trigger = () => page.getByRole("button", { name: /^Attach — / }).element() as HTMLElement; @@ -163,8 +168,8 @@ for (const theme of ["light", "dark"] as const) for (const [width, height] of [[ await expect.poll(() => s.client.state.getState().available).toBe(true); // Available: one string is the accessible name and the painted tooltip. - await expect.element(page.getByRole("button", { name: LIVE_ATTACH, exact: true })).toBeInTheDocument(); - expect(tip().textContent).toBe(LIVE_ATTACH); + await expect.element(page.getByRole("button", { name: ATTACH, exact: true })).toBeInTheDocument(); + expect(tip().textContent).toBe(ATTACH); expect(tip().getAttribute("aria-hidden")).toBe("true"); expect(shown(), "no tooltip at rest").toBe(false); @@ -190,8 +195,7 @@ for (const theme of ["light", "dark"] as const) for (const [width, height] of [[ else { // A phone's sheet names the option in its subtitle; its row is a full target. await expect.poll(() => document.querySelector('[data-overlay-site="attach"]')).not.toBe(null); - expect(document.querySelector('[data-overlay-site="attach"]')!.textContent).toContain("Live conversation, photo, camera, track files, or paste."); - expect((page.getByRole("button", { name: /^Live conversation/ }).element() as HTMLElement).getBoundingClientRect().height).toBeGreaterThanOrEqual(44); + expect(document.querySelector('[data-overlay-site="attach"]')!.textContent).toContain("Photo, camera, track files, or paste."); await s.capture("attach-sheet"); } expect(shown(), "an opened menu hides the tooltip").toBe(false); @@ -220,21 +224,17 @@ for (const theme of ["light", "dark"] as const) for (const [width, height] of [[ expect(shown(), "Escape dismisses a hover tooltip without moving the pointer").toBe(false); await userEvent.unhover(trigger()); - // Not available: the name and the menu leave live conversation out. - flushSync(() => s.client.state.setState({ available: false })); - await expect.element(page.getByRole("button", { name: "Attach — photo, camera, files", exact: true })).toBeInTheDocument(); - expect(tip().textContent).toBe("Attach — photo, camera, files"); + // Neither the name nor the menu offers live conversation, available or not. await userEvent.click(trigger()); expect(document.body.textContent).not.toContain("Live conversation"); - await s.capture("attach-inactive-menu"); + await s.capture("attach-menu"); await userEvent.keyboard("{Escape}"); await expect.poll(() => document.querySelector('[data-overlay-site="attach"],[role="menu"]')).toBe(null); - flushSync(() => s.client.state.setState({ available: true })); - await expect.element(page.getByRole("button", { name: LIVE_ATTACH, exact: true })).toBeInTheDocument(); - await userEvent.click(trigger()); - await userEvent.click(page.getByRole("button", { name: /^Live conversation/ })); - // The entry still leads to the first-entry disclosure; nothing opens a provider or a microphone. + // The mic's "Talk live…" action still leads to the first-entry disclosure; + // nothing opens a provider or a microphone. + (page.getByRole("button", { name: "Talk live…", exact: true }).element() as HTMLElement).focus(); + await userEvent.keyboard("{Enter}"); await expect.poll(() => s.client.state.getState().disclosureOpen).toBe(true); expect(s.client.state.getState().micOn).toBe(false); expect(s.network.socket()!.frames("conversation_start"), "ENTRY_DISCLOSES_WITHOUT_OPENING_PROVIDER").toHaveLength(0); diff --git a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx index 417e8a2d5a..4443bddbfe 100644 --- a/packages/ui-react/tests/browser/dictation-gemini.offline.tsx +++ b/packages/ui-react/tests/browser/dictation-gemini.offline.tsx @@ -127,7 +127,7 @@ function hardware(ctx: TestContext, rate: number) { return { contexts, streams, worklet }; } -const dictate = (s: Scene) => s.host.querySelector('[data-composer] [role="button"][aria-label^="Dictate"]'); +const dictate = (s: Scene) => s.host.querySelector('[data-composer] :is(button,[role="button"])[aria-label^="Dictate"]'); async function startDictating(s: Scene): Promise { await expect.poll(() => dictate(s), { message: "the composer has a mic" }).not.toBe(null); diff --git a/packages/ui-react/tests/browser/dictation-notice.pointer.tsx b/packages/ui-react/tests/browser/dictation-notice.pointer.tsx index 2025c68de4..9a12512b51 100644 --- a/packages/ui-react/tests/browser/dictation-notice.pointer.tsx +++ b/packages/ui-react/tests/browser/dictation-notice.pointer.tsx @@ -88,7 +88,7 @@ async function mount(ctx: TestContext, providerId: "deepgram" | "webspeech", sta return { ui, host, net }; } -const dictate = (s: Scene) => s.host.querySelector('[data-composer] [role="button"][aria-label^="Dictate"]'); +const dictate = (s: Scene) => s.host.querySelector('[data-composer] :is(button,[role="button"])[aria-label^="Dictate"]'); /** Taps Dictate and waits for the provider's client to be listening. */ async function startDictating(s: Scene) { diff --git a/packages/ui-react/tests/browser/dictation-provider-end.offline.tsx b/packages/ui-react/tests/browser/dictation-provider-end.offline.tsx index 4f33581c43..968abf9a76 100644 --- a/packages/ui-react/tests/browser/dictation-provider-end.offline.tsx +++ b/packages/ui-react/tests/browser/dictation-provider-end.offline.tsx @@ -83,7 +83,7 @@ async function mount(ctx: TestContext, providerId: "deepgram" | "webspeech"): Pr return { ui, host, net }; } -const dictate = (s: Scene) => s.host.querySelector('[data-composer] [role="button"][aria-label^="Dictate"]'); +const dictate = (s: Scene) => s.host.querySelector('[data-composer] :is(button,[role="button"])[aria-label^="Dictate"]'); /** Taps Dictate and waits for the provider's client to be listening. */ async function startDictating(s: Scene) { diff --git a/packages/ui-react/tests/browser/local-capture.offline.tsx b/packages/ui-react/tests/browser/local-capture.offline.tsx index f6ec41e97b..840630c831 100644 --- a/packages/ui-react/tests/browser/local-capture.offline.tsx +++ b/packages/ui-react/tests/browser/local-capture.offline.tsx @@ -184,7 +184,7 @@ async function mount(ctx: TestContext, opts: { online?: boolean; gum?: MediaDevi return s; } -const mic = (s: Scene) => s.host.querySelector('[data-composer] [role="button"][aria-label="Record on this device"], [data-composer] [role="button"][aria-label="Stop and save"], [data-composer] [role="button"][aria-label^="Dictate"], [data-composer] [role="button"][aria-label="Stop dictation"]'); +const mic = (s: Scene) => s.host.querySelector('[data-composer] :is(button,[role="button"])[aria-label="Record on this device"], [data-composer] :is(button,[role="button"])[aria-label="Stop and save"], [data-composer] :is(button,[role="button"])[aria-label^="Dictate"], [data-composer] :is(button,[role="button"])[aria-label="Stop dictation"]'); const field = (s: Scene) => s.host.querySelector("[data-composer] textarea")!; const notice = (s: Scene) => s.host.querySelector("[data-capture-notice]"); const phase = (s: Scene) => s.ui.stores.voice.getState().local; diff --git a/packages/ui-react/tests/render/render-smoke.test.tsx b/packages/ui-react/tests/render/render-smoke.test.tsx index 3c66193ad4..1a76251d7c 100644 --- a/packages/ui-react/tests/render/render-smoke.test.tsx +++ b/packages/ui-react/tests/render/render-smoke.test.tsx @@ -5821,24 +5821,21 @@ describe("ComposerView", () => { streaming.unmount(); }); - test("the paperclip names live conversation whenever its menu offers it (#3045)", () => { + test("the paperclip names its menu, and live conversation is the mic's hold, not a row (#3045, #3693)", () => { const h = handlers(); - const live = "Attach — live conversation, photo, camera, files"; - const view = render( {})} onPickTracks={mock(() => {})} {...h} />); - const trigger = view.getByRole("button", { name: live }); + const name = "Attach — photo, camera, files"; + const view = render( {})} micControl={