feat(web): mic moves into the send pill and Stop ends dictation #28844
Openmaria-rckswants to merge 63 commits into
maria/redesign/4-settings-setup fromrefs/pull/28844/headopened View on GitHubmaria-rcks added labelsDO NOT MERGE
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/desktop/src/preview/PickPreload.ts lines 1600 to 1604OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1367,0 +1584,21 @@1584+ return;1585+ }1586+ if (1587+ voiceAvailable &&1588+ editor.style.display !== "none" &&1589+ resolveKeybindingCommand(event, voice.keybindings, navigator.platform, {1590+ previewFocus: true,1591+ previewOpen: true,1592+ isDesktop: true,1593+ isWeb: false,1594+ editableFocus: true,1595+ }) === "composer.dictation"1596+ ) {1597+ event.preventDefault();1598+ event.stopImmediatePropagation();1599+ voiceKeyCode = event.code || event.key;1600+ if (!event.repeat && !voiceBusy) {1601+ voiceBusy = true;1602+ comment.readOnly = true;1603+ submit.disabled = true;1604+ }apps/server/src/speech/native.ts lines 265 to 297OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+ },105+ );106+ return await new Promise<{ id: string; name: string }[]>((resolve, reject) => {107+ child.on("message", (devices: unknown) => {108+ if (109+ Array.isArray(devices) &&110+ devices.every(111+ (device: unknown) =>112+ typeof device === "object" &&113+ device !== null &&114+ "id" in device &&115+ typeof device.id === "string" &&116+ "name" in device &&117+ typeof device.name === "string",118+ )119+ )120+ resolve(devices);121+ });122+ child.once("error", reject);123+ child.once("exit", (code) => reject(new Error(`Speech device discovery exited (${code}).`)));124+ });apps/server/src/speech/SpeechService.lifecycle.test.ts lines 483 to 493OutdatedResolvedby maria-rcks@@ -0,0 +473,21 @@473+ Effect.gen(function* () {474+ native.reset.mockRejectedValueOnce(new Error("reset failed"));475+ const speech = yield* SpeechService.SpeechService;476+ yield* speech.startStream().pipe(Effect.scoped);477+ expect(native.dispose).toHaveBeenCalledOnce();478+ yield* speech.startStream().pipe(Effect.scoped);479+ expect(loadNative).toHaveBeenCalledTimes(2);480+ }).pipe(Effect.provide(layer)),481+);482+483+it.live("stops an unresponsive stream reset and releases the busy slot", () =>484+ Effect.gen(function* () {485+ native.reset.mockImplementationOnce(() => new Promise(() => {}));486+ const speech = yield* SpeechService.SpeechService;487+ yield* speech.startStream().pipe(Effect.scoped);488+ expect(native.dispose).toHaveBeenCalledOnce();489+ expect(yield* speech.status).toMatchObject({ state: "ready" });490+ yield* speech.startStream().pipe(Effect.scoped);491+ expect(loadNative).toHaveBeenCalledTimes(2);492+ }).pipe(Effect.provide(layer)),493+);apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx lines 122 to 126OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ null,107+ createElement("h3", null, title),108+ createElement("p", null, description),109+ control,110+ children,111+ ),112+}));113+import { VoiceSettingsPanel } from "./VoiceSettingsPanel";114+115+const button = (name: string) => page.getByRole("button", { name, exact: true });116+const modelDescriptions = (container: HTMLElement) =>117+ [...container.querySelectorAll("p")]118+ .map((paragraph) => paragraph.textContent ?? "")119+ .filter((text) => text.endsWith(" description"));120+const languageOptions = () =>121+ [...document.querySelectorAll('[data-slot="combobox-item"]')].map((option) => option.textContent);122+async function renderPanel() {123+ const screen = await render(createElement(VoiceSettingsPanel));124+ await userEvent.click(page.getByRole("button", { name: /Transcription models/ }));125+ return screen;126+}apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx lines 122 to 143OutdatedResolvedby maria-rcks@@ -0,0 +123,21 @@123+ setup();124+ using _timers = fakeTimers();125+ mocks.microphoneFailure = false;126+ mocks.busy = true;127+ const probe = createProbe();128+ await using _screen = await render(probe.view());129+ let starting!: Promise<void>;130+ await act(async () => {131+ starting = probe.voice.start();132+ for (let i = 0; i < 10; i++) await Promise.resolve();133+ });134+ expect(probe.voice.state.phase).toBe("preparing");135+ expect(mocks.microphoneRequests).toBe(0);136+ mocks.busy = false;137+ await act(async () => {138+ await vi.advanceTimersByTimeAsync(250);139+ await starting;140+ });141+ expect(probe.voice.state.phase).toBe("recording");142+ expect(mocks.microphoneRequests).toBe(1);143+});apps/web/src/speech/useEnvironmentSpeechInput.ts line 379OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +164,21 @@164+ prepared,165+ getProjectName: () => {166+ const name = latestInputRef.current.projectName;167+ return name && name.length <= 200 ? name : undefined;168+ },169+ getMicrophoneId: () => microphoneIdRef.current,170+ onLevel: setLevel,171+ onDurationLimit: () => void controller.stop(),172+ onText: (text) => {173+ if (!disposed) setPreview(text);174+ },175+ onError: (message) => {176+ if (!disposed) void controller.interruptRecording(message);177+ },178+ });179+ controller = new VoiceInputController<true>({180+ recorder: platform.recorder,181+ getTranscriber: () => platform.transcriber,182+ requestPermission: async () => ({ granted: true, canAskAgain: true }),183+ configureRecording: async () => undefined,184+ releaseRecording: async () => platform.cancelRecording(),packages/contracts/src/settings.ts line 1667OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1577,3 +1655,13 @@15771655 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),15781656 continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),15791657 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),1658+ speechModelId: Schema.optionalKey(Schema.String),1659+ speechAcceleration: Schema.optionalKey(SpeechAcceleration),1660+ speechModelUnloadTimeout: Schema.optionalKey(SpeechModelUnloadTimeout),1661+ speechLanguage: Schema.optionalKey(SpeechLanguage),1662+ speechTranslateToEnglish: Schema.optionalKey(Schema.Boolean),1663+ speechCustomWords: Schema.optionalKey(SpeechCustomWords),1664+ speechRemoveFillerWords: Schema.optionalKey(Schema.Boolean),1665+ speechPostProcessingEnabled: Schema.optionalKey(Schema.Boolean),1666+ speechCorrectionWord: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(50))),1667+ speechPostProcessingModelSelection: Schema.optionalKey(ModelSelectionPatch),
- apps/server/src/serverSettings.ts lines 495 to 498OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -482,11 +483,16 @@482483 isDriverAllowed: DriverAllowed = anyDriver,483484 ): ServerSettings {484485 const selection = settings.textGenerationModelSelection;485- return isModelSelectionProviderEnabled(settings, selection) &&486+ const resolved =487+ isModelSelectionProviderEnabled(settings, selection) &&486488 selectionSupportsTextGeneration(settings, selection) &&487489 isDriverAllowed(488490 settings.providerInstances[selection.instanceId]?.driver ??489491 ProviderDriverKind.make(selection.instanceId),490492 )491- ? settings492- : fallbackTextGenerationProvider(settings, isDriverAllowed);493+ ? settings494+ : fallbackTextGenerationProvider(settings, isDriverAllowed);495+ const speechPostProcessingModelSelection = resolveSpeechPostProcessingModelSelection(resolved);496+ return speechPostProcessingModelSelection === resolved.speechPostProcessingModelSelection497+ ? resolved498+ : { ...resolved, speechPostProcessingModelSelection };
- apps/web/src/components/chat/ChatComposer.tsx line 1909OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1886 +1889,21 @@188618891890+ const speechInput = useEnvironmentSpeechInput({1891+ environmentId,1892+ projectName: props.projectName,1893+ ownerKey: JSON.stringify([composerDraftTarget, activePendingProgress?.activeQuestion?.id]),1894+ draftText: prompt,1895+ readDraft: () => {1896+ const snapshot = readComposerSnapshot();1897+ return {1898+ text: snapshot.value,1899+ selection: { start: snapshot.expandedCursor, end: snapshot.expandedCursor },1900+ };1901+ },1902+ commitDraft: (text, selection) => {1903+ const snapshot = readComposerSnapshot();1904+ const applied = applyPromptReplacement(0, snapshot.value.length, text, {1905+ expectedText: snapshot.value,1906+ focusEditorAfterReplace: false,1907+ });1908+ if (!applied) return;1909+ const cursor = collapseExpandedComposerCursor(text, selection.start);
- apps/web/src/components/settings/VoiceSettingsPanel.tsx lines 485 to 498OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +478,21 @@478+ setFailedDownloads((current) => {479+ const modelIds = new Set(current?.prepared === prepared ? current.modelIds : []);480+ if (failed) modelIds.add(modelId);481+ else modelIds.delete(modelId);482+ return { prepared, modelIds };483+ });484+ };485+ const runModelOperation = (modelId: string, run: () => Promise<unknown>, kind?: "download") => {486+ if (kind === "download") {487+ markDownloadFailed(modelId, false);488+ setCancelledDownload(null);489+ }490+ setOperation(modelId);491+ void run()492+ .then(refreshModels)493+ .catch((error) => {494+ if (kind === "download") markDownloadFailed(modelId, true);495+ else reportModelError(error);496+ })497+ .finally(() => setOperation(null));498+ };
juliusmarminge added labelsbugfix
juliusmarminge added labelspr:needs-julius
- apps/server/src/speech/customWords.ts line 140OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +120,21 @@120+ /[\r\n]/.test(text.slice(token.end, slice[offset + 1]!.start)),121+ )122+ )123+ continue;124+ const match = bestMatch(matchKey(slice.map(({ value }) => value).join("")), keys);125+ if (126+ match &&127+ (!best || match.score < best.score || (match.score === best.score && count < best.count))128+ )129+ best = { count, ...match };130+ }131+ if (!best) {132+ index += 1;133+ continue;134+ }135+ const consumed = tokens.slice(index, index + best.count);136+ output.push(text.slice(cursor, consumed[0]!.start));137+ output.push(138+ punctuation(consumed[0]!.value).prefix +139+ preserveCase(consumed[0]!.value, best.word) +140+ punctuation(consumed.at(-1)!.value).suffix,@@ -2257,6 +2257,7 @@22572257 const publishComposerOverlayHeight = (height: number) => {22582258 const nextHeight = Math.ceil(height);22592259 if (nextHeight <= 0) return;2260- if (composerTimelineInsetRef.current !== nextHeight) {2261- composerTimelineInsetRef.current = nextHeight;2262- setComposerTimelineInset(nextHeight);2260+ const speechTray = composerOverlayElement?.querySelector<HTMLElement>(2261+ '[data-chat-composer-speech="true"]',2262+ );2263+ const timelineInset = Math.ceil(height - (speechTray?.getBoundingClientRect().height ?? 0));apps/web/src/components/chat/ChatComposer.tsx line 1904OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1889,3 +1892,13 @@18891892 };18901893 const readComposerSnapshotStable = useStableCallback(readComposerSnapshot);189118941895+ const speechInput = useEnvironmentSpeechInput({1896+ environmentId,1897+ projectName: props.projectName,1898+ ownerKey: JSON.stringify([composerDraftTarget, activePendingProgress?.activeQuestion?.id]),1899+ draftText: prompt,1900+ readDraft: () => {1901+ const snapshot = readComposerSnapshot();1902+ return {1903+ text: snapshot.value,1904+ selection: { start: snapshot.expandedCursor, end: snapshot.expandedCursor },apps/server/src/speech/http.ts lines 160 to 160OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +140,21 @@140+ return yield* speech.updateCustomWords(args.payload.words).pipe(141+ Effect.catchTags({142+ SpeechInvalidAudioError: () => failEnvironmentInvalidRequest("invalid_audio"),143+ SpeechUnsupportedPlatformError: () =>144+ failEnvironmentInvalidRequest("speech_unavailable"),145+ SpeechBusyError: () => failEnvironmentInvalidRequest("speech_busy"),146+ SpeechDownloadCancelledError: () => failEnvironmentInvalidRequest("speech_busy"),147+ SpeechModelNotFoundError: () => failEnvironmentInvalidRequest("invalid_command"),148+ SpeechOperationError: (error) => failEnvironmentInternal("internal_error", error),149+ }),150+ );151+ }),152+ )153+ .handle(154+ "updateFillerWordRemoval",155+ Effect.fn("environment.voice.updateFillerWordRemoval")(function* (args) {156+ yield* annotateEnvironmentRequest(args.endpoint.name);157+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);158+ return yield* speech159+ .updateFillerWordRemoval(args.payload.enabled)160+ .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error)));apps/web/src/components/preview/PreviewAnnotationSpeech.tsx line 50OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +30,21 @@30+ const keys = useRef<DictationKeyHandlers | null>(null);31+ const speech = useEnvironmentSpeechInput({32+ environmentId,33+ ownerKey: JSON.stringify([environmentId, tabId, config.sessionId]),34+ draftText: text,35+ readDraft: () => ({36+ text: draft.current.text,37+ selection: { start: draft.current.cursor, end: draft.current.cursor },38+ }),39+ commitDraft: (next, selection) => {40+ draft.current = { text: next, cursor: selection.start };41+ setText(next);42+ void publish({ text: next, cursor: selection.start });43+ },44+ });45+ const current = useRef(speech);46+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Publish committed speech actions before desktop annotation events read them.47+ useEffect(() => {48+ current.current = speech;49+ });50+ const subscribeKeys = (handlers: DictationKeyHandlers) => {packages/shared/src/serverSettings.ts lines 170 to 172OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -135,0 +152,21 @@152+ return (153+ provider?.enabled === true &&154+ provider.installed &&155+ isProviderAvailable(provider) &&156+ provider.supportsTextGeneration !== false157+ );158+ };159+ let selection: ModelSelection | null = settings.speechPostProcessingModelSelection;160+ if (!canUse(selection)) {161+ selection = null;162+ for (const [driver, defaults] of Object.entries(DEFAULT_SPEECH_POST_PROCESSING_MODELS)) {163+ if (!defaults) continue;164+ const instanceIds = [165+ ProviderInstanceId.make(driver),166+ ...Object.entries(settings.providerInstances)167+ .filter(([id, instance]) => instance.driver === driver && id !== driver)168+ .map(([id]) => ProviderInstanceId.make(id)),169+ ];170+ const instanceId = instanceIds.find((id) =>171+ canUse({ instanceId: id, model: defaults.model }),172+ );@@ -453,3 +456,14 @@453456 "usage quota rate limit reset recover continue reported reset time cancel scheduled continuation",454457 ],455458 },459+ {460+ id: "dictation-shortcut-mode",461+ title: "Dictation shortcut mode",462+ to: "/settings/voice",463+ searchTerms: ["speech voice keyboard hotkey hold toggle auto"],464+ },465+ {466+ id: "transcription-environment",467+ title: "Transcription environment",468+ to: "/settings/voice",469+ desktopOnly: true,
- apps/web/src/components/chat/ComposerPrimaryActions.tsx line 351OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -339,3 +348,4 @@339348340349 const submit = (341350 <ComposerSendPill>351+ {leadingAction}
- apps/web/src/components/chat/ComposerSpeechButton.tsx lines 147 to 147OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +127,21 @@127+ ? "Skip post-processing"128+ : isBusy129+ ? "Transcribing"130+ : "Start voice input";131+ const showShortcut = (phase === "idle" || phase === "error" || isRecording) && !openSettings;132+ const isPill = (props.appearance ?? "pill") === "pill";133+ const onClick = () => {134+ if (openSettings) {135+ props.onCancel();136+ void navigate({ to: "/settings/voice" });137+ } else if (isRecording) {138+ props.onStop();139+ } else if (phase === "preparing") {140+ props.onCancel();141+ } else if (phase === "post-processing") {142+ props.onSkipPostProcessing();143+ } else if (!isBusy) {144+ props.onStart();145+ }146+ };147+ const disabled = (props.disabled && phase === "idle") || phase === "transcribing";apps/web/src/speech/useEnvironmentSpeechInput.ts line 461OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +291,21 @@291+ setSetupModel(292+ result.models.find((model) => model.id === currentStatus.modelId) ?? null,293+ );294+ })295+ .catch(() => undefined)296+ .finally(() => {297+ refreshing = false;298+ });299+ }, 350);300+ return () => {301+ disposed = true;302+ window.clearInterval(timer);303+ };304+ }, [currentStatus, prepared, setupDownloading, setupOpen]);305+306+ const previousOwnerRef = useRef(input.ownerKey);307+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Cancel the external recording and queued start when the editor owner changes.308+ useEffect(() => {309+ if (previousOwnerRef.current === input.ownerKey) return;310+ previousOwnerRef.current = input.ownerKey;311+ startRequestRef.current += 1;@@ -1364,4 +1534,12 @@1364153413651535 const onCancel = (): void => teardown(false);13661536 const onCaptured = (): void => teardown(false);1537+ const onVoiceKeyUp = (event: KeyboardEvent) => {1538+ if ((event.code || event.key) !== voiceKeyCode) return;1539+ voiceKeyCode = null;1540+ event.preventDefault();1541+ event.stopImmediatePropagation();1542+ sendVoice("key", event);1543+ };13671544 const onKeyDown = (event: KeyboardEvent): void => {1545+ if (voice && !event.isComposing && event.keyCode !== 229) {
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
maria-rcks changed the title
- apps/web/src/components/chat/ComposerSpeechButton.tsx lines 131 to 131OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -128,10 +128,4 @@128128 {isRecording ? (129129 <RecordingStatus level={props.level} recordingLimitSeconds={props.recordingLimitSeconds} />130130 ) : (131- <span132- className={cn(133- "min-w-0 flex-1 truncate text-right text-sm text-secondary-label",134- isError && "text-destructive",135- )}136- >137- {presentation.status}131+ <span className="min-w-0 flex-1 text-right">
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -3770,20 +3824 @@3770- state={speechInput.state}3771- progress={null}3772- finishShortcutLabel={dictationShortcutLabel}3773- cancelShortcutLabel="Esc"3774- level={speechInput.level}3775- disabled={dictationDisabled}3776- onStart={() => void speechInput.start()}3777- onStop={() => void speechInput.stop()}3778- onCancel={() => speechInput.cancel()}3779- onSkipPostProcessing={() => speechInput.skipPostProcessing()}3780- />3781- <ComposerSpeechButton3782- state={speechInput.state}3783- progress={null}3784- shortcutLabel={dictationShortcutLabel}3785- disabled={dictationDisabled}3786- onStart={() => void speechInput.start()}3787- onCancel={() => speechInput.cancel()}3788- />3789- </>3824+ {speechInput.available && speechInput.state.phase === "error" ? (
- @@ -173,5 +181,9 @@173181 const isSendDisabled = !canOperateThread || sendDisabledReason !== null;174182175183 // The stop square sits in the same pill as send, so the pill never changes shape.184+ // While dictating it ends the recording; a running turn's stop returns after.185+ const stopsDictation = onStopDictation !== undefined && !pendingAction;186+ const stopLabel = stopsDictation ? "Stop voice input" : generationStopLabel;176187 const renderStopGenerationButton = (insidePendingAction: boolean) => (177188 <ComposerSendPill key="interrupt" className={cn(insidePendingAction && "sm:h-7")}>189+ {insidePendingAction ? null : renderSpeechAction?.(true)}
Sign in to join this conversation.





Macroscope has since reviewed this pull request. An earlier review was skipped by a cost limit; a review has now completed, so that notice no longer applies.