Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: pick dictation's engine beside the mic

leepokaiab05eaf59a45
diff --git a/apps/desktop/src/renderer/components/RecordingPill.tsx b/apps/desktop/src/renderer/components/RecordingPill.tsx
index 1d13c267..993b2296 100644
--- a/apps/desktop/src/renderer/components/RecordingPill.tsx
+++ b/apps/desktop/src/renderer/components/RecordingPill.tsx
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react'
+import { Spinner } from './Controls'
import { Icon } from './Icon'
import { LevelDots, type LevelSample } from './LevelDots'
+import { HStack } from './Stack'
import { Text } from './Text'
import './recording-pill.css'
@@ -17,23 +19,33 @@ function useElapsed(startedAt: number) {
/**
* Dictation in progress, in place of the mic: stop, the time since it started, and dots that
- * follow the microphone's level. `color` null is the text color.
+ * follow the microphone's level; `transcribing` once a recording waits for its transcript.
+ * `color` null is the text color.
*/
-export function RecordingPill({ startedAt, sample, onStop, color = null, className = '' }: {
+export function RecordingPill({ startedAt, sample, onStop, transcribing = false, color = null, className = '' }: {
startedAt: number
sample: () => LevelSample
onStop: () => void
+ transcribing?: boolean
color?: string | null
className?: string
}) {
const elapsed = useElapsed(startedAt)
+ if (transcribing) {
+ return (
+ <HStack as="span" gap={6} className={`recording-pill transcribing ${className}`}>
+ <Spinner size={12} />
+ <Text tone="secondary">Transcribing…</Text>
+ </HStack>
+ )
+ }
return (
- <span className={`recording-pill ${className}`}>
+ <HStack as="span" gap={6} className={`recording-pill ${className}`}>
<button type="button" className="recording-stop" aria-label="Stop dictating" title="Stop dictating" onClick={onStop}>
<Icon name="stop.fill" size={11} scaled={false} />
</button>
<Text tabular tone="text">{elapsed}</Text>
<LevelDots sample={sample} color={color} width={32} height={12} label="Listening" />
- </span>
+ </HStack>
)
}
diff --git a/apps/desktop/src/renderer/components/recording-pill.css b/apps/desktop/src/renderer/components/recording-pill.css
index 037e0c85..82e48a33 100644
--- a/apps/desktop/src/renderer/components/recording-pill.css
+++ b/apps/desktop/src/renderer/components/recording-pill.css
@@ -1,9 +1,6 @@
/* Dictation in progress: a quiet pill with stop, the time and the level dots. */
.recording-pill {
flex: none;
- display: inline-flex;
- align-items: center;
- gap: 6px;
height: 28px;
box-sizing: border-box;
padding: 0 10px 0 4px;
@@ -12,6 +9,9 @@
font-size: var(--text-body);
animation: fade-in var(--fade) both;
}
+.recording-pill.transcribing {
+ padding-left: 10px;
+}
.recording-stop {
width: 22px;
height: 22px;
diff --git a/apps/desktop/src/renderer/views/call/CallView.tsx b/apps/desktop/src/renderer/views/call/CallView.tsx
index c83ae6b5..2106bb23 100644
--- a/apps/desktop/src/renderer/views/call/CallView.tsx
+++ b/apps/desktop/src/renderer/views/call/CallView.tsx
@@ -11,6 +11,8 @@ import { avatarColor } from '../../lib/theme'
import { analytics } from '../../store/analytics'
import { useStore } from '../../store/context'
import { VoiceChatSettingsView } from '../settings/VoiceChatSettingsView'
+import { voiceStatus } from '../settings/voice-settings'
+import { stopDictation } from '../thread/dictation'
import { CallOperator } from './call-operator'
/**
@@ -22,7 +24,7 @@ import { CloudSpeechEngine } from './CloudSpeechEngine'
import { GeminiLiveEngine } from './GeminiLiveEngine'
import { OnDeviceEngine } from './OnDeviceEngine'
import { OpenAIRealtimeEngine } from './OpenAIRealtimeEngine'
-import { countVoiceUsage, fromBase64, onDeviceAvailable, onDeviceUnavailableReason, providerName, toBase64, VoiceEngine, VoiceSettings, type VoiceProvider, type VoiceStatus } from './voice'
+import { countVoiceUsage, fromBase64, onDeviceAvailable, onDeviceUnavailableReason, providerName, transcribeOnHost, VoiceEngine, VoiceSettings, type VoiceProvider } from './voice'
import { watchVoiceCall } from './voice-call'
import './call.css'
@@ -71,6 +73,8 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
/** Starts the engine: a realtime provider on the key kept by the computer, or on-device speech. */
const begin = (provider: VoiceProvider | null) => {
if (closed.current) return
+ // Every engine takes the microphone (and the speech helper) from any dictation in progress.
+ stopDictation()
if (!provider && !onDeviceAvailable()) return void fallbackFromDevice()
const op = new CallOperator(store, botId)
const send = (text: string) => store.send(text, botId)
@@ -81,8 +85,7 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
const voice = VoiceSettings.voice(provider)
next = new CloudSpeechEngine(provider, {
// ponytail: kit turns Simplified Chinese transcripts into Traditional (ICU Hans-Hant); Chromium has no such transform.
- transcribe: async (audio) =>
- (await (await store.ready()).call<{ text: string }>('voiceTranscribe', { provider, model: transcribe, audio: toBase64(audio) }, 60_000)).text,
+ transcribe: async (audio) => transcribeOnHost(await store.ready(), provider, transcribe, audio),
speak: async (text) => {
const clip = await (await store.ready()).call<{ audio: string; format: string }>('voiceSpeak', { provider, model: speechModel, voice, text }, 90_000)
return { audio: fromBase64(clip.audio), format: clip.format }
@@ -122,9 +125,7 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {
const rememberStatus = async () => {
try {
- const status = await (await store.ready()).call<VoiceStatus>('voiceStatus')
- VoiceSettings.remember(status)
- return status
+ return await voiceStatus(await store.ready())
} catch {
return null
}
diff --git a/apps/desktop/src/renderer/views/call/OnDeviceEngine.ts b/apps/desktop/src/renderer/views/call/OnDeviceEngine.ts
index 20bba939..b7e5c34c 100644
--- a/apps/desktop/src/renderer/views/call/OnDeviceEngine.ts
+++ b/apps/desktop/src/renderer/views/call/OnDeviceEngine.ts
@@ -1,5 +1,4 @@
import type { SpeechEvent } from '@shared/ipc'
-import { stopDictation } from '../thread/dictation'
import { onDeviceUnavailableReason, spokenText, VoiceEngine, VoiceSettings } from './voice'
/**
@@ -55,8 +54,6 @@ export class OnDeviceEngine extends VoiceEngine {
async start() {
if (!window.codync.speech.available) return this.fail(onDeviceUnavailableReason())
- // The call takes the recognizer from any dictation in progress.
- stopDictation()
speechSynthesis.getVoices()
this.offEvents = window.codync.speech.onEvent((e) => this.event(e))
this.listen()
diff --git a/apps/desktop/src/renderer/views/call/voice.ts b/apps/desktop/src/renderer/views/call/voice.ts
index fcb0b3ce..be3014c1 100644
--- a/apps/desktop/src/renderer/views/call/voice.ts
+++ b/apps/desktop/src/renderer/views/call/voice.ts
@@ -1,15 +1,16 @@
+import type { HostClient } from '../../client/host-client'
import { Observable } from '../../lib/observable'
import {
addVoiceUsage,
chosenModel,
chosenVoice,
+ dictationEngine,
engine,
isVoiceProvider,
language,
mode,
pause,
rate,
- rememberStatus,
voiceInfo,
type VoiceProvider,
} from '../settings/voice-settings'
@@ -36,12 +37,16 @@ export const VoiceSettings = {
const value = engine.get()
return isVoiceProvider(value) ? value : null
},
+ /** The provider picked for dictation; null for on-device. */
+ dictationProvider: (): VoiceProvider | null => {
+ const value = dictationEngine.get()
+ return isVoiceProvider(value) ? value : null
+ },
model: (p: VoiceProvider) => chosenModel(p, 'realtime'),
transcribeModel: (p: VoiceProvider) => chosenModel(p, 'transcribe'),
speechModel: (p: VoiceProvider) => chosenModel(p, 'speech'),
voice: chosenVoice,
isSpeechMode: (p: VoiceProvider) => mode(p).get() === 'speech',
- remember: rememberStatus,
/** A pause this long (seconds) ends what you're saying and sends it. */
pause: () => (pause.get() > 0 ? pause.get() : 1.5),
/** AVSpeechUtterance's rate (0…1, 0.5 normal), as the Mac stores it. */
@@ -187,6 +192,11 @@ export function wav(chunks: Int16Array[]): Uint8Array {
return out
}
+/** Speech to text for one recording (a 16 kHz WAV) on the host, which holds the provider's key. */
+export async function transcribeOnHost(client: HostClient, provider: VoiceProvider, model: string, audio: Uint8Array) {
+ return (await client.call<{ text: string }>('voiceTranscribe', { provider, model, audio: toBase64(audio) }, 60_000)).text
+}
+
export function toBase64(bytes: Uint8Array) {
let s = ''
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
diff --git a/apps/desktop/src/renderer/views/island/island-model.ts b/apps/desktop/src/renderer/views/island/island-model.ts
index ef45d1d1..ba1aa059 100644
--- a/apps/desktop/src/renderer/views/island/island-model.ts
+++ b/apps/desktop/src/renderer/views/island/island-model.ts
@@ -6,6 +6,7 @@ import { VOICE_SHORTCUT_KEYS, type VoiceKey, type VoiceShortcut } from '@shared/
import { Observable } from '../../lib/observable'
import { pref } from '../../lib/prefs'
import { Dictation } from '../thread/dictation'
+import { dictationPlatform } from '../thread/dictation-platform'
/** The bare notch peeks at once and opens after a rest; the compact island opens sooner. */
const OPEN_FROM_PEEK_MS = 650
@@ -31,7 +32,7 @@ export class IslandModel extends Observable {
/** The message field's text. */
draft = ''
/** Talking into the message field (the field's mic, or the voice input shortcut). */
- readonly dictation = new Dictation((text) => this.update(() => (this.draft = text)))
+ readonly dictation = new Dictation((change) => this.update(() => (this.draft = change(this.draft))), dictationPlatform())
/** The voice input shortcut, as Settings → General has it. */
shortcut: VoiceShortcut = 'off'
/** The shape grew on its last change: open with a spring, close without one. */
@@ -126,6 +127,8 @@ export class IslandModel extends Observable {
/** The header's tabs. Bots puts the approvals on screen off until another arrives. */
setTab(tab: IslandTab) {
+ // Leaving the message field hides the recording pill: stop there, keeping the words.
+ if (this.tab === 'message' && tab !== 'message' && this.dictation.busy) this.dictation.finish()
this.update(() => {
if (tab === 'bots') for (const p of this.summary.permissions) this.deferred.add(p.entryId)
if (tab === 'message' && !this.messageRef) this.messageRef = this.focus?.ref ?? null
diff --git a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
index 99a69ffb..4fd0a0aa 100644
--- a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
+++ b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx
@@ -25,6 +25,9 @@ export function VoiceChatSettingsView({ showsHeader = true }: { showsHeader?: bo
const [language, setLanguage] = usePref(voice.language)
const languages = useMemo(() => voice.languageOptions(window.codync.speech.locales()), [])
const provider = voice.isVoiceProvider(engine) ? engine : null
+ const [dictationEngine] = usePref(voice.dictationEngine)
+ /** Dictation on another provider than calls still needs that provider's key and speech-to-text model. */
+ const dictationProvider = voice.isVoiceProvider(dictationEngine) && dictationEngine !== provider ? dictationEngine : null
const [mode, setMode] = usePref(voice.mode(provider ?? 'openai'))
const footer = provider
? `Your own ${voice.voiceInfo[provider].name} key, billed by ${voice.voiceInfo[provider].name}. Applies from the next call.`
@@ -68,6 +71,7 @@ export function VoiceChatSettingsView({ showsHeader = true }: { showsHeader?: bo
]}
</CardSection>
{provider ? <ProviderVoiceSettings key={provider} provider={provider} /> : null}
+ {dictationProvider ? <ProviderVoiceSettings key={`dictation-${dictationProvider}`} provider={dictationProvider} dictationOnly /> : null}
</CardForm>
</div>
</SheetPage>
@@ -86,11 +90,12 @@ function PauseRow() {
)
}
-/** One provider: the key the computer keeps, models, voice and this month's minutes. */
-function ProviderVoiceSettings({ provider }: { provider: VoiceProvider }) {
+/** One provider: the key the computer keeps, models, voice and this month's minutes. `dictationOnly` keeps the key and speech-to-text model. */
+function ProviderVoiceSettings({ provider, dictationOnly = false }: { provider: VoiceProvider; dictationOnly?: boolean }) {
const store = useStore()
const info = voice.voiceInfo[provider]
const [mode] = usePref(voice.mode(provider))
+ const [dictationEngine] = usePref(voice.dictationEngine)
/** null while the computer hasn't answered yet. */
const [saved, setSaved] = useState<boolean | null>(null)
const [replacing, setReplacing] = useState(false)
@@ -104,6 +109,8 @@ function ProviderVoiceSettings({ provider }: { provider: VoiceProvider }) {
const [models, setModels] = useState<VoiceModels>(() => voice.modelsCache(provider).get() ?? { models: [], transcribe: [], speech: [] })
const busyRef = useRef(false)
const speechMode = mode === 'speech'
+ /** Speech mode and dictation with this provider both use its speech-to-text model. */
+ const transcribes = dictationOnly || speechMode || dictationEngine === provider
const hasKey = saved === true
const notConnected = { ok: false, text: `Not connected to ${store.hostName}.` }
@@ -133,9 +140,7 @@ function ProviderVoiceSettings({ provider }: { provider: VoiceProvider }) {
}
let configured: boolean
try {
- const status = await voice.voiceStatus(client)
- voice.rememberStatus(status)
- configured = voice.configured(status, provider)
+ configured = voice.configured(await voice.voiceStatus(client), provider)
} catch (e) {
if (cancelled) return
setSaved(false)
@@ -168,13 +173,17 @@ function ProviderVoiceSettings({ provider }: { provider: VoiceProvider }) {
})
}
- /** A pasted key is checked with the provider by the computer before it's kept. With a key saved, Test starts a call credential with the chosen model and voice. */
+ /**
+ * A pasted key is checked with the provider by the computer before it's kept. With a key saved, Test starts a call
+ * credential with the chosen model and voice; for dictation only, it lists the key's models.
+ */
const test = () => {
const typed = key.trim()
if (!typed && !hasKey) return
run(async (client) => {
if (!typed || (!replacing && hasKey)) {
- if (speechMode) await voice.voiceSpeak(client, provider, speechModel, chosenVoice, 'OK')
+ if (dictationOnly) await voice.voiceModels(client, provider)
+ else if (speechMode) await voice.voiceSpeak(client, provider, speechModel, chosenVoice, 'OK')
else await voice.voiceSession(client, provider, model, chosenVoice)
setResult({ ok: true, text: 'Key works' })
} else {
@@ -200,6 +209,9 @@ function ProviderVoiceSettings({ provider }: { provider: VoiceProvider }) {
}
const dimmed = hasKey ? 'settings-dimmable' : 'settings-dimmable dimmed'
+ let footer: string | null = null
+ if (!hasKey) footer = `Add a key to choose from ${info.name}'s models.`
+ else if (dictationOnly) footer = 'For dictation in the message box.'
const keyArea = (
<VStack key="key" gap={8}>
{hasKey && !replacing ? (
@@ -268,30 +280,34 @@ function ProviderVoiceSettings({ provider }: { provider: VoiceProvider }) {
)
return (
- <CardSection title={info.name} footer={hasKey ? null : `Add a key to choose from ${info.name}'s models.`}>
+ <CardSection title={info.name} footer={footer}>
{[
keyArea,
- ...(speechMode
- ? [
- <div key="stt" className={dimmed}><ValueRow label="Speech to text">{picker(transcribeModel, models.transcribe, pick('transcribe', setTranscribeModel))}</ValueRow></div>,
- <div key="tts" className={dimmed}><ValueRow label="Text to speech">{picker(speechModel, models.speech, pick('speech', setSpeechModel))}</ValueRow></div>,
- ]
- : [<div key="model" className={dimmed}><ValueRow label="Model">{picker(model, models.models, pick('realtime', setModel))}</ValueRow></div>]),
- <div key="voice" className={dimmed}>
- <ValueRow label="Voice">
- <ChoicePicker
- selection={chosenVoice}
- options={info.voices.map((v) => ({ id: v, label: v }))}
- onChange={(v) => {
- setChosenVoice(v)
- voice.saveVoice(provider, v)
- }}
- />
- </ValueRow>
- </div>,
- <div key="minutes" className={dimmed}>
- <ValueRow label="This month">≈ {voice.voiceMinutes(provider)} min</ValueRow>
- </div>,
+ ...(transcribes
+ ? [<div key="stt" className={dimmed}><ValueRow label="Speech to text">{picker(transcribeModel, models.transcribe, pick('transcribe', setTranscribeModel))}</ValueRow></div>]
+ : []),
+ ...(dictationOnly
+ ? []
+ : [
+ speechMode
+ ? <div key="tts" className={dimmed}><ValueRow label="Text to speech">{picker(speechModel, models.speech, pick('speech', setSpeechModel))}</ValueRow></div>
+ : <div key="model" className={dimmed}><ValueRow label="Model">{picker(model, models.models, pick('realtime', setModel))}</ValueRow></div>,
+ <div key="voice" className={dimmed}>
+ <ValueRow label="Voice">
+ <ChoicePicker
+ selection={chosenVoice}
+ options={info.voices.map((v) => ({ id: v, label: v }))}
+ onChange={(v) => {
+ setChosenVoice(v)
+ voice.saveVoice(provider, v)
+ }}
+ />
+ </ValueRow>
+ </div>,
+ <div key="minutes" className={dimmed}>
+ <ValueRow label="This month">≈ {voice.voiceMinutes(provider)} min</ValueRow>
+ </div>,
+ ]),
]}
</CardSection>
)
diff --git a/apps/desktop/src/renderer/views/settings/voice-settings.ts b/apps/desktop/src/renderer/views/settings/voice-settings.ts
index 5bf5faed..ad9a57bd 100644
--- a/apps/desktop/src/renderer/views/settings/voice-settings.ts
+++ b/apps/desktop/src/renderer/views/settings/voice-settings.ts
@@ -55,6 +55,8 @@ export const configured = (s: VoiceStatus, p: VoiceProvider) => s.providers.some
/** `device` (on-device speech) or a provider. */
export const engine = pref('callEngine', 'device')
+/** The same choice for dictation into the message box, picked beside its mic. */
+export const dictationEngine = pref('dictationEngine', 'device')
/** On-device reading speed (AVSpeechUtterance's scale: 0.5 is normal). */
export const DEFAULT_RATE = 0.5
export const rate = pref('callRate', DEFAULT_RATE)
@@ -104,10 +106,6 @@ export function rememberDefaults(p: VoiceProvider, d: VoiceDefaults | null | und
if (d) defaultsPref(p).set(d)
}
-export function rememberStatus(s: VoiceStatus) {
- for (const entry of s.providers) rememberDefaults(entry.provider, entry.defaults)
-}
-
export type ModelKind = keyof VoiceDefaults
export const chosenModel = (p: VoiceProvider, kind: ModelKind) => modelPrefs[kind](p).get() ?? voiceDefaults(p)[kind]
@@ -137,7 +135,12 @@ export const voiceMinutes = (p: VoiceProvider, at = new Date()) => Math.floor((k
// Host calls
-export const voiceStatus = (c: HostClient) => c.call<VoiceStatus>('voiceStatus')
+/** Which providers the computer has keys for; the newest models it reports become the defaults. */
+export async function voiceStatus(c: HostClient) {
+ const status = await c.call<VoiceStatus>('voiceStatus')
+ for (const entry of status.providers) rememberDefaults(entry.provider, entry.defaults)
+ return status
+}
/** Checks the key with the provider before the computer keeps it; an empty key removes it. */
export const setVoiceKey = (c: HostClient, p: VoiceProvider, key: string) => c.call<VoiceStatus>('setVoiceKey', { provider: p, key }, 30_000)
diff --git a/apps/desktop/src/renderer/views/thread/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsx
index d560d72d..6f1fd1f0 100644
--- a/apps/desktop/src/renderer/views/thread/Composer.tsx
+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx
@@ -16,7 +16,8 @@ import { composerEnter } from './composer-keyboard'
import { CommandMenu, useCommandMenu } from './CommandMenu'
import { ComposerAttachment } from './ComposerAttachment'
import { QuoteRow } from './ChatRows'
-import { useDictation } from './dictation'
+import { useDictation } from './dictation-platform'
+import { DictationEngineMenu } from './DictationEngineMenu'
import { builtInCommand, slashCommands, slashQuery, type SlashCommand } from './slash-commands'
import { useVoiceShortcut } from './voice-shortcut-keys'
@@ -52,7 +53,7 @@ function DestinationComposer({ botId, reply, cancelReply, onCall, onInterrupt }:
const draft = useSyncExternalStore(drafts.subscribe, () => drafts.get(botId))
const setDraft = (text: string) => drafts.set(botId, text)
const [files, setFiles] = useState<OutgoingFile[]>([])
- const dictation = useDictation(setDraft)
+ const dictation = useDictation((change) => drafts.set(botId, change(drafts.get(botId))))
const field = useRef<HTMLTextAreaElement>(null)
const measure = useRef<HTMLDivElement>(null)
const composing = useRef(false)
@@ -171,9 +172,6 @@ function DestinationComposer({ botId, reply, cancelReply, onCall, onInterrupt }:
field.current?.focus()
}
useVoiceShortcut(dictation, draft, submit, () => field.current?.focus())
- useEffect(() => {
- if (dictation.error) store.setError(dictation.error)
- }, [dictation.error, store])
const trailing: Trailing = onInterrupt && !draft && !files.length ? 'interrupt' : working && !draft && !files.length ? 'stop' : onCall && !draft && !files.length ? 'call' : 'send'
const [symbol, label] = ({
@@ -279,12 +277,21 @@ function DestinationComposer({ botId, reply, cancelReply, onCall, onInterrupt }:
}}
/>
</div>
- {dictation.listening ? (
- <RecordingPill startedAt={dictation.startedAt} sample={() => dictation} onStop={() => dictation.finish()} className="composer-recording" />
+ {dictation.listening || dictation.transcribing ? (
+ <RecordingPill
+ startedAt={dictation.startedAt}
+ sample={() => dictation}
+ onStop={() => dictation.finish()}
+ transcribing={dictation.transcribing}
+ className="composer-recording"
+ />
) : dictation.available ? (
- <button className="press composer-mic" aria-label="Dictate" title="Dictate" onClick={() => dictation.start(draft)}>
- <Icon name="mic" size={13} weight="medium" />
- </button>
+ <HStack as="span" gap={0} className="composer-mic-group">
+ <button className="press composer-mic" aria-label="Dictate" title="Dictate" onClick={() => dictation.start(draft)}>
+ <Icon name="mic" size={13} weight="medium" />
+ </button>
+ <DictationEngineMenu />
+ </HStack>
) : null}
<button
className={trailing === 'interrupt' ? 'press composer-send interrupt' : 'press composer-send'}
diff --git a/apps/desktop/src/renderer/views/thread/DictationEngineMenu.tsx b/apps/desktop/src/renderer/views/thread/DictationEngineMenu.tsx
new file mode 100644
index 00000000..8819c4ed
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/DictationEngineMenu.tsx
@@ -0,0 +1,20 @@
+import { DropdownMenu } from '../../components/Controls'
+import { Icon } from '../../components/Icon'
+import { usePref } from '../../lib/prefs'
+import { dictationEngine, VOICE_PROVIDERS, voiceInfo } from '../settings/voice-settings'
+
+const ENGINES = [{ id: 'device', title: 'On device' }, ...VOICE_PROVIDERS.map((p) => ({ id: p, title: voiceInfo[p].name }))]
+
+/** Beside the mic, in its capsule: which speech dictation uses, on-device or a provider on the user's own key. */
+export function DictationEngineMenu() {
+ const [engine, setEngine] = usePref(dictationEngine)
+ return (
+ <DropdownMenu
+ className="press composer-engine"
+ title="Dictation engine"
+ items={() => ENGINES.map((e) => ({ title: e.title, selected: e.id === engine, action: () => setEngine(e.id) }))}
+ >
+ <Icon name="chevron.up" size={10} weight="semibold" />
+ </DropdownMenu>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/thread/composer.css b/apps/desktop/src/renderer/views/thread/composer.css
index 89fd3be1..2a8b2191 100644
--- a/apps/desktop/src/renderer/views/thread/composer.css
+++ b/apps/desktop/src/renderer/views/thread/composer.css
@@ -157,21 +157,39 @@
}
.composer-symbol.active { opacity: 1; transform: scale(1) rotate(0); }
/* Dictation, beside send / call (Grok Bot's): a light circle; a recording pill while it listens. */
+/* The mic and its engine menu share one light capsule. */
+.composer-mic-group {
+ flex: none;
+ height: 25px;
+ border-radius: var(--radius-pill);
+ background: color-mix(in srgb, var(--text) 7%, var(--composer-fill));
+ margin-bottom: var(--first-line-inset);
+}
.composer-mic {
width: 25px;
height: 25px;
- border-radius: 50%;
display: grid;
place-items: center;
flex: none;
color: var(--secondary);
- background: color-mix(in srgb, var(--text) 7%, var(--composer-fill));
- margin-bottom: var(--first-line-inset);
- transition: background-color var(--morph), color var(--morph), transform var(--press);
+ transition: color var(--morph), transform var(--press);
}
.composer-mic:hover {
color: var(--text);
}
+.composer-engine {
+ width: 18px;
+ height: 25px;
+ display: grid;
+ place-items: center;
+ flex: none;
+ padding-right: 4px;
+ color: var(--secondary);
+ transition: color var(--hover);
+}
+.composer-engine:hover {
+ color: var(--text);
+}
/* Centered on the first line, like the mic it replaces. */
.composer-recording {
height: 25px;
diff --git a/apps/desktop/src/renderer/views/thread/dictation-pieces.test.ts b/apps/desktop/src/renderer/views/thread/dictation-pieces.test.ts
new file mode 100644
index 00000000..3c429156
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/dictation-pieces.test.ts
@@ -0,0 +1,53 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { inOrder, joinDictated, MIN_SAMPLES, PIECE_SAMPLES, pieces } from './dictation-pieces.ts'
+
+const recording = (samples: number, chunk = 4096) => {
+ const chunks: Int16Array[] = []
+ for (let at = 0; at < samples; at += chunk) chunks.push(Int16Array.from({ length: Math.min(chunk, samples - at) }, (_, i) => (at + i) % 30000))
+ return chunks
+}
+const lengths = (samples: number) => pieces(recording(samples)).map((p) => p.length)
+
+test('a recording is cut into 20 s pieces that keep every sample in order', () => {
+ assert.deepEqual(lengths(PIECE_SAMPLES * 0.5), [PIECE_SAMPLES * 0.5])
+ assert.deepEqual(lengths(PIECE_SAMPLES * 2), [PIECE_SAMPLES, PIECE_SAMPLES])
+ assert.deepEqual(lengths(PIECE_SAMPLES * 2 + MIN_SAMPLES), [PIECE_SAMPLES, PIECE_SAMPLES, MIN_SAMPLES])
+ const joined = pieces(recording(PIECE_SAMPLES * 2 + 123)).flatMap((p) => [...p])
+ assert.deepEqual(joined, recording(PIECE_SAMPLES * 2 + 123).flatMap((c) => [...c]))
+})
+
+test('a tail under half a second stays with the piece before', () => {
+ assert.deepEqual(lengths(PIECE_SAMPLES + MIN_SAMPLES - 1), [PIECE_SAMPLES + MIN_SAMPLES - 1])
+ assert.deepEqual(lengths(PIECE_SAMPLES * 2 + 1), [PIECE_SAMPLES, PIECE_SAMPLES + 1])
+})
+
+test('transcripts come back in order with a few requests at a time', async () => {
+ let running = 0
+ let most = 0
+ const out = await inOrder([5, 1, 4, 2, 3, 0], async (n) => {
+ most = Math.max(most, ++running)
+ await new Promise((done) => setTimeout(done, n))
+ running--
+ return `piece ${n}`
+ })
+ assert.deepEqual(out, ['piece 5', 'piece 1', 'piece 4', 'piece 2', 'piece 3', 'piece 0'])
+ assert.equal(most, 3)
+})
+
+test('the first failed piece stops the rest', async () => {
+ const started: number[] = []
+ await assert.rejects(inOrder([0, 1, 2, 3, 4, 5, 6], async (n) => {
+ started.push(n)
+ if (n === 0) throw new Error('429')
+ await new Promise((done) => setTimeout(done, 5))
+ }), /429/)
+ assert.deepEqual(started, [0, 1, 2])
+})
+
+test('dictated words go after the box with one space', () => {
+ assert.equal(joinDictated('', 'hello'), 'hello')
+ assert.equal(joinDictated('Fix the bug', 'in the parser'), 'Fix the bug in the parser')
+ assert.equal(joinDictated('Fix the bug\n', 'now'), 'Fix the bug\nnow')
+ assert.equal(joinDictated('Fix the bug', ''), 'Fix the bug')
+})
diff --git a/apps/desktop/src/renderer/views/thread/dictation-pieces.ts b/apps/desktop/src/renderer/views/thread/dictation-pieces.ts
new file mode 100644
index 00000000..1a360369
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/dictation-pieces.ts
@@ -0,0 +1,50 @@
+/** Under half a second is a click of the mic, not speech (and speech-to-text models invent words for silence). */
+export const MIN_SAMPLES = 16000 / 2
+/** One transcription request: 20 s of 16 kHz audio, well under the host's 2 MB request body once base64-encoded. */
+export const PIECE_SAMPLES = 16000 * 20
+/** Transcription requests running at once, under the providers' burst limits. */
+export const IN_FLIGHT = 3
+
+/** `said` after what's already in the box, with one space between. */
+export function joinDictated(before: string, said: string) {
+ if (!before.trim()) return said
+ if (!said) return before
+ return /\s$/.test(before) ? before + said : `${before} ${said}`
+}
+
+/** A recording cut into requests of `size` samples; a tail under `MIN_SAMPLES` stays with the piece before. */
+export function pieces(chunks: Int16Array[], size = PIECE_SAMPLES): Int16Array[] {
+ const all = new Int16Array(chunks.reduce((n, c) => n + c.length, 0))
+ let at = 0
+ for (const c of chunks) {
+ all.set(c, at)
+ at += c.length
+ }
+ const out: Int16Array[] = []
+ for (let start = 0; start < all.length; start += size) {
+ const end = all.length - (start + size) < MIN_SAMPLES ? all.length : start + size
+ out.push(all.subarray(start, end))
+ if (end === all.length) break
+ }
+ return out
+}
+
+/** `run` over `items`, at most `limit` at once, results in the items' order; the first failure stops the rest. */
+export async function inOrder<T, R>(items: T[], run: (item: T) => Promise<R>, limit = IN_FLIGHT): Promise<R[]> {
+ const out: R[] = []
+ let next = 0
+ let failed = false
+ const worker = async () => {
+ while (!failed && next < items.length) {
+ const i = next++
+ try {
+ out[i] = await run(items[i]!)
+ } catch (e) {
+ failed = true
+ throw e
+ }
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
+ return out
+}
diff --git a/apps/desktop/src/renderer/views/thread/dictation-platform.ts b/apps/desktop/src/renderer/views/thread/dictation-platform.ts
new file mode 100644
index 00000000..1c0e4609
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/dictation-platform.ts
@@ -0,0 +1,46 @@
+import { useEffect, useRef, useState } from 'react'
+import type { HostClient } from '../../client/host-client'
+import { useModel } from '../../lib/observable'
+import { useStoreRef } from '../../store/context'
+import { countVoiceUsage, micPCM16k, onDeviceUnavailableReason, providerName, transcribeOnHost, VoiceSettings, wav } from '../call/voice'
+import { configured, voiceStatus } from '../settings/voice-settings'
+import { Dictation, type DictationPlatform } from './dictation'
+
+/**
+ * Dictation's real surroundings: the speech helper and the microphone, and with `host` a provider
+ * on the user's key through it; `report` shows its errors (the island has neither).
+ */
+export function dictationPlatform(host: (() => Promise<HostClient>) | null = null, report: (message: string) => void = () => {}): DictationPlatform {
+ const client = async () => {
+ if (!host) throw new Error('Dictating with a provider needs the chat window.')
+ return host()
+ }
+ return {
+ speech: window.codync.speech.available ? window.codync.speech : null,
+ noSpeech: onDeviceUnavailableReason(),
+ host: host !== null,
+ language: () => VoiceSettings.language() || null,
+ provider: VoiceSettings.dictationProvider,
+ async checkKey(provider) {
+ if (!configured(await voiceStatus(await client()), provider)) {
+ throw new Error(`Add your ${providerName(provider)} key in Voice chat settings to dictate with it.`)
+ }
+ },
+ microphone: micPCM16k,
+ transcribe: async (provider, piece) => transcribeOnHost(await client(), provider, VoiceSettings.transcribeModel(provider), wav([piece])),
+ count: countVoiceUsage,
+ report,
+ }
+}
+
+/** A composer's dictation; it stops when the composer goes away (another chat), and its errors show in the window. */
+export function useDictation(editDraft: (change: (box: string) => string) => void) {
+ const store = useStoreRef()
+ const edit = useRef(editDraft)
+ edit.current = editDraft
+ const [dictation] = useState(
+ () => new Dictation((change) => edit.current(change), dictationPlatform(() => store.ready(), (message) => store.setError(message))),
+ )
+ useEffect(() => () => dictation.cancel(), [dictation])
+ return useModel(dictation)
+}
diff --git a/apps/desktop/src/renderer/views/thread/dictation.test.ts b/apps/desktop/src/renderer/views/thread/dictation.test.ts
new file mode 100644
index 00000000..7914bb32
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/dictation.test.ts
@@ -0,0 +1,169 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import type { SpeechEvent } from '../../../shared/ipc.ts'
+import { Dictation, type DictationPlatform } from './dictation.ts'
+import { MIN_SAMPLES, PIECE_SAMPLES } from './dictation-pieces.ts'
+
+/** A stub platform: a speech helper driven by `say`, a microphone fed by `hear`, transcripts on demand. */
+function setup(over: Partial<DictationPlatform> = {}) {
+ let listener: ((e: SpeechEvent) => void) | null = null
+ let feed: ((pcm: Int16Array, level: number) => void) | null = null
+ const log: string[] = []
+ const pending: { piece: Int16Array; answer: (text: string) => void; fail: (e: Error) => void }[] = []
+ const platform: DictationPlatform = {
+ speech: {
+ start: () => void log.push('speech.start'),
+ stop: () => void log.push('speech.stop'),
+ onEvent: (l) => {
+ listener = l
+ return () => void (listener = null)
+ },
+ },
+ noSpeech: 'No speech here.',
+ host: true,
+ language: () => null,
+ provider: () => null,
+ checkKey: async () => {},
+ microphone: async (out) => {
+ feed = out
+ log.push('mic.open')
+ return () => void log.push('mic.close')
+ },
+ transcribe: (_, piece) => new Promise((answer, fail) => pending.push({ piece, answer, fail })),
+ count: (seconds) => void log.push(`count ${seconds}`),
+ report: (message) => void log.push(`report ${message}`),
+ ...over,
+ }
+ let box = 'Fix the bug'
+ const dictation = new Dictation((change) => (box = change(box)), platform)
+ return {
+ dictation,
+ log,
+ pending,
+ box: () => box,
+ type: (text: string) => void (box += text),
+ say: (e: SpeechEvent) => listener?.(e),
+ hear: (samples: number) => feed?.(new Int16Array(samples), 0.5),
+ }
+}
+
+const settle = () => new Promise((done) => setTimeout(done, 0))
+
+test('on-device words go after the draft, and finish waits for the last of them', () => {
+ const s = setup()
+ s.dictation.start(s.box())
+ s.say({ type: 'partial', text: 'in the' })
+ assert.equal(s.box(), 'Fix the bug in the')
+ s.say({ type: 'final', text: 'in the parser' })
+ let sent = false
+ s.dictation.finish(() => (sent = true))
+ assert.equal(sent, false)
+ s.say({ type: 'final', text: 'today' })
+ s.say({ type: 'stopped' })
+ assert.equal(s.box(), 'Fix the bug in the parser today')
+ assert.equal(sent, true)
+ assert.equal(s.dictation.busy, false)
+})
+
+test('cancel drops words still on their way', () => {
+ const s = setup()
+ s.dictation.start(s.box())
+ s.dictation.cancel()
+ s.say({ type: 'final', text: 'late' })
+ assert.equal(s.box(), 'Fix the bug')
+ assert.deepEqual(s.log, ['speech.start', 'speech.stop'])
+})
+
+test('a speech error ends it and reports it; a send already asked for goes with the words so far', () => {
+ const s = setup()
+ s.dictation.start(s.box())
+ s.say({ type: 'final', text: 'in the parser' })
+ let sent = false
+ s.dictation.finish(() => (sent = true))
+ s.say({ type: 'error', message: 'Speech recognition is off.' })
+ assert.equal(s.dictation.error, 'Speech recognition is off.')
+ assert.ok(s.log.includes('report Speech recognition is off.'))
+ assert.equal(s.dictation.busy, false)
+ assert.equal(sent, true)
+ assert.equal(s.box(), 'Fix the bug in the parser')
+})
+
+test('without on-device speech or a provider, the mic says what to pick', () => {
+ const s = setup({ speech: null })
+ s.dictation.start(s.box())
+ assert.equal(s.dictation.error, 'No speech here. Pick OpenAI or Gemini beside the mic.')
+ assert.equal(s.dictation.listening, false)
+})
+
+test('a provider without a key never opens the microphone', async () => {
+ const s = setup({ provider: () => 'openai', checkKey: async () => Promise.reject(new Error('Add your OpenAI key.')) })
+ s.dictation.start(s.box())
+ await settle()
+ assert.equal(s.dictation.error, 'Add your OpenAI key.')
+ assert.ok(!s.log.includes('mic.open'))
+ assert.equal(s.dictation.busy, false)
+})
+
+test("a provider's transcript lands after what's in the box by then, in order, then done runs", async () => {
+ const s = setup({ provider: () => 'gemini' })
+ s.dictation.start(s.box())
+ await settle()
+ s.hear(PIECE_SAMPLES)
+ s.hear(PIECE_SAMPLES / 2)
+ s.type(' in the parser')
+ let sent = false
+ s.dictation.finish(() => (sent = true))
+ assert.ok(s.log.includes('mic.close'))
+ assert.equal(s.dictation.transcribing, true)
+ await settle()
+ assert.equal(s.pending.length, 2)
+ s.pending[1]!.answer('second')
+ s.pending[0]!.answer('first')
+ await settle()
+ assert.equal(s.box(), 'Fix the bug in the parser first second')
+ assert.ok(s.log.includes(`count ${(PIECE_SAMPLES * 1.5) / 16000}`))
+ assert.equal(sent, true)
+ assert.equal(s.dictation.transcribing, false)
+})
+
+test('cancel while transcribing drops the transcript', async () => {
+ const s = setup({ provider: () => 'openai' })
+ s.dictation.start(s.box())
+ await settle()
+ s.hear(MIN_SAMPLES * 2)
+ s.dictation.finish()
+ await settle()
+ s.dictation.cancel()
+ s.pending[0]!.answer('too late')
+ await settle()
+ assert.equal(s.box(), 'Fix the bug')
+ assert.equal(s.dictation.busy, false)
+})
+
+test('a recording under half a second is dropped without a request', async () => {
+ const s = setup({ provider: () => 'openai' })
+ s.dictation.start(s.box())
+ await settle()
+ s.hear(MIN_SAMPLES - 1)
+ let sent = false
+ s.dictation.finish(() => (sent = true))
+ await settle()
+ assert.equal(s.pending.length, 0)
+ assert.equal(sent, true)
+ assert.equal(s.box(), 'Fix the bug')
+})
+
+test('a failed transcription reports it and sends nothing', async () => {
+ const s = setup({ provider: () => 'openai' })
+ s.dictation.start(s.box())
+ await settle()
+ s.hear(MIN_SAMPLES * 2)
+ let sent = false
+ s.dictation.finish(() => (sent = true))
+ await settle()
+ s.pending[0]!.fail(new Error('Host error 500'))
+ await settle()
+ assert.equal(s.dictation.error, 'Host error 500')
+ assert.equal(sent, false)
+ assert.equal(s.dictation.busy, false)
+})
diff --git a/apps/desktop/src/renderer/views/thread/dictation.ts b/apps/desktop/src/renderer/views/thread/dictation.ts
index 77461cb6..9c93ea1e 100644
--- a/apps/desktop/src/renderer/views/thread/dictation.ts
+++ b/apps/desktop/src/renderer/views/thread/dictation.ts
@@ -1,8 +1,8 @@
-import { useEffect, useRef, useState } from 'react'
-import type { SpeechEvent } from '@shared/ipc'
-import { VoiceKeyRouter, type VoiceKey } from '@shared/voice-shortcut'
-import { Observable, useModel } from '../../lib/observable'
-import { VoiceSettings } from '../call/voice'
+import type { CodyncBridge, SpeechEvent } from '../../../shared/ipc.ts'
+import { VoiceKeyRouter, type VoiceKey } from '../../../shared/voice-shortcut.ts'
+import { Observable } from '../../lib/observable.ts'
+import type { VoiceProvider } from '../settings/voice-settings.ts'
+import { inOrder, joinDictated, MIN_SAMPLES, pieces } from './dictation-pieces.ts'
/** The running dictation: one recognizer at a time, and a call stops dictation first. */
let active: Dictation | null = null
@@ -11,21 +11,50 @@ export function stopDictation() {
active?.cancel()
}
-/** `said` after what's already in the box, with one space between. */
-export function joinDictated(before: string, said: string) {
- if (!before.trim()) return said
- if (!said) return before
- return /\s$/.test(before) ? before + said : `${before} ${said}`
+/** What dictation reaches outside itself: `dictation-platform.ts` wires the real ones, tests stub them. */
+export interface DictationPlatform {
+ /** The on-device speech helper (macOS), or null without one. */
+ speech: Pick<CodyncBridge['speech'], 'start' | 'stop' | 'onEvent'> | null
+ /** Why there's no on-device speech here, said when it's picked anyway. */
+ noSpeech: string
+ /** This window reaches a host, so it can dictate with a provider on the user's key. */
+ host: boolean
+ /** The on-device recognizer's language; null is the computer's. */
+ language(): string | null
+ /** The provider picked beside the mic; null is on-device. */
+ provider(): VoiceProvider | null
+ /** Rejects, saying what to do, unless the host holds `provider`'s key. */
+ checkKey(provider: VoiceProvider): Promise<void>
+ /** Opens the microphone as 16 kHz PCM; resolves to what closes it. */
+ microphone(out: (pcm: Int16Array, level: number) => void): Promise<() => void>
+ /** One piece of a recording, as the provider's text. */
+ transcribe(provider: VoiceProvider, piece: Int16Array): Promise<string>
+ /** Seconds sent to `provider`, for this month's usage. */
+ count(seconds: number, provider: VoiceProvider): void
+ /** Shows an error, every time (even the same one again). */
+ report(message: string): void
}
+/** Recording for a provider: what the microphone heard so far, and how to stop it. */
+interface Recording {
+ provider: VoiceProvider
+ pcm: Int16Array[]
+ stopMic: (() => void) | null
+}
+
+const messageOf = (e: unknown) => (e instanceof Error ? e.message : String(e))
+
/**
- * Dictation with on-device speech (the speech helper; macOS). Words reach `write` as they're
- * recognized, after what was already typed. The helper doesn't stop on a pause: it ends on
- * `finish()` once the last words are in, on `cancel()`, on an error, or when another window takes it.
+ * Dictation into a message box. With on-device speech (the speech helper; macOS), words reach
+ * `edit` as they're recognized, after what was already typed; the helper doesn't stop on a pause:
+ * it ends on `finish()` once the last words are in, on `cancel()`, on an error, or when another
+ * window takes it. With a provider picked beside the mic, it records, and `finish()` has the host
+ * transcribe the whole recording with the user's key, then puts it after what's in the box by then.
*/
export class Dictation extends Observable {
- readonly available = window.codync.speech.available
listening = false
+ /** Recorded for a provider, waiting for its transcript. */
+ transcribing = false
/** When it started listening (ms since the epoch). */
startedAt = 0
/** The microphone's level while listening, 0…1. Read it each frame: it doesn't re-render. */
@@ -35,18 +64,31 @@ export class Dictation extends Observable {
/** The box up to the words still being recognized. */
private before = ''
private off: (() => void) | null = null
+ private recording: Recording | null = null
private done: (() => void) | null = null
+ /** Bumped by each start, finish and cancel: a microphone or transcript arriving late for an earlier one is dropped. */
+ private generation = 0
/** Started by the voice input shortcut's double tap: its next tap sends what's in the field. */
private byShortcut = false
private readonly keys = new VoiceKeyRouter()
+ /** Changes the box's text. */
+ private readonly edit: (change: (box: string) => string) => void
+ private readonly platform: DictationPlatform
- constructor(private write: (text: string) => void) {
+ constructor(edit: (change: (box: string) => string) => void, platform: DictationPlatform) {
super()
+ this.edit = edit
+ this.platform = platform
+ }
+
+ /** On-device speech here, or a host to transcribe with a provider. */
+ get available() {
+ return this.platform.speech !== null || this.platform.host
}
/** Listening, or stopped and waiting for the last words. */
get busy() {
- return this.off !== null
+ return this.off !== null || this.recording !== null || this.transcribing
}
start(draft: string, byShortcut = false) {
@@ -55,30 +97,42 @@ export class Dictation extends Observable {
this.byShortcut = byShortcut
this.error = null
this.before = draft
- this.off = window.codync.speech.onEvent((e) => this.event(e))
- window.codync.speech.start(VoiceSettings.language() || null)
+ const { speech } = this.platform
+ const provider = this.platform.host ? this.platform.provider() : null
+ if (provider) {
+ this.recording = { provider, pcm: [], stopMic: null }
+ void this.record(this.recording, ++this.generation)
+ } else if (speech) {
+ this.off = speech.onEvent((e) => this.event(e))
+ speech.start(this.platform.language())
+ } else {
+ return this.fail(`${this.platform.noSpeech} Pick OpenAI or Gemini beside the mic.`)
+ }
this.startedAt = Date.now()
this.listening = true
this.changed()
}
- /** Stops listening; `done` runs once the recognizer has delivered its last words. */
+ /** Stops listening; `done` runs once the last words are in the box (recognized, or transcribed for a provider). */
finish(done?: () => void) {
this.byShortcut = false
+ if (this.recording) return void this.transcribe(this.recording, done)
if (!this.off) return done?.()
this.done = done ?? null
this.listening = false
this.level = 0
this.changed()
- window.codync.speech.stop()
+ this.platform.speech?.stop()
}
/** Stops listening now and drops words still on their way. */
cancel() {
this.byShortcut = false
this.error = null
- if (!this.off) return
- window.codync.speech.stop()
+ if (!this.busy) return
+ this.generation++
+ if (this.off) this.platform.speech?.stop()
+ this.done = null
this.end()
}
@@ -94,21 +148,81 @@ export class Dictation extends Observable {
private event(e: SpeechEvent) {
if (e.type === 'level') this.level = e.value
- if (e.type === 'partial' || e.type === 'final') this.write(joinDictated(this.before, e.text))
+ if (e.type === 'partial' || e.type === 'final') this.edit(() => joinDictated(this.before, e.text))
if (e.type === 'final') this.before = joinDictated(this.before, e.text)
if (e.type === 'error') {
// Nothing to send, and the helper (which may still hold the microphone) goes too.
this.byShortcut = false
this.error = e.message
- window.codync.speech.stop()
+ this.platform.report(e.message)
+ this.platform.speech?.stop()
}
if (e.type === 'stopped' || e.type === 'error') this.end()?.()
}
+ /** Opens the microphone once the host has the provider's key, so nothing said is lost to a missing one. */
+ private async record(recording: Recording, generation: number) {
+ try {
+ await this.platform.checkKey(recording.provider)
+ if (generation !== this.generation) return
+ const stop = await this.platform.microphone((pcm, level) => {
+ recording.pcm.push(pcm)
+ this.level = level
+ })
+ if (generation !== this.generation) return stop()
+ recording.stopMic = stop
+ } catch (e) {
+ if (generation === this.generation) this.fail(messageOf(e))
+ }
+ }
+
+ /**
+ * Stops recording and puts the provider's transcript of all of it after what's in the box now
+ * (typing goes on while it records); `done` runs once it's there.
+ */
+ private async transcribe(recording: Recording, done?: () => void) {
+ const generation = ++this.generation
+ recording.stopMic?.()
+ this.recording = null
+ this.done = done ?? null
+ this.listening = false
+ this.level = 0
+ const samples = recording.pcm.reduce((n, c) => n + c.length, 0)
+ if (samples < MIN_SAMPLES) return void this.end()?.()
+ this.transcribing = true
+ this.changed()
+ try {
+ const { provider } = recording
+ // Once cancelled, the pieces not sent yet stay unsent (each is billed on the user's key).
+ const texts = await inOrder(pieces(recording.pcm), (piece) =>
+ generation === this.generation ? this.platform.transcribe(provider, piece) : Promise.reject(new Error('Cancelled')),
+ )
+ this.platform.count(samples / 16000, provider)
+ if (generation !== this.generation) return
+ const said = texts.map((t) => t.trim()).filter(Boolean).reduce(joinDictated, '')
+ this.edit((box) => joinDictated(box, said))
+ this.end()?.()
+ } catch (e) {
+ if (generation === this.generation) this.fail(messageOf(e))
+ }
+ }
+
+ /** Ends with `message` and nothing to send. */
+ private fail(message: string) {
+ this.byShortcut = false
+ this.error = message
+ this.platform.report(message)
+ this.done = null
+ this.end()
+ }
+
/** Returns what was waiting for the last words. */
private end() {
this.off?.()
this.off = null
+ this.recording?.stopMic?.()
+ this.recording = null
+ this.transcribing = false
this.listening = false
this.level = 0
if (active === this) active = null
@@ -118,12 +232,3 @@ export class Dictation extends Observable {
return done
}
}
-
-/** A composer's dictation; it stops when the composer goes away (another chat). */
-export function useDictation(setDraft: (text: string) => void) {
- const write = useRef(setDraft)
- write.current = setDraft
- const [dictation] = useState(() => new Dictation((text) => write.current(text)))
- useEffect(() => () => dictation.cancel(), [dictation])
- return useModel(dictation)
-}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift b/apps/ios/Kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift
index 45a6fdac..f7b6d2b9 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift
@@ -7,6 +7,7 @@ import SwiftUI
/// from the computer's row in settings; the computer is the `BotStore` in the environment.
public struct VoiceChatSettingsView: View {
@AppStorage(VoiceSettings.engineKey) private var engine = "device"
+ @AppStorage(VoiceSettings.dictationEngineKey) private var dictationEngine = "device"
@AppStorage(OnDeviceEngine.rateKey) private var rate = Double(AVSpeechUtteranceDefaultSpeechRate)
@AppStorage(OnDeviceEngine.languageKey) private var language = ""
@State private var languages = OnDeviceEngine.languageOptions
@@ -40,12 +41,20 @@ public struct VoiceChatSettingsView: View {
if let provider = VoiceProvider(rawValue: engine) {
ProviderVoiceSettings(provider: provider).id(provider)
}
+ if let provider = dictationProvider {
+ ProviderVoiceSettings(provider: provider, dictationOnly: true).id("dictation-\(provider.rawValue)")
+ }
}
}
.background(Palette.background)
.tracked(.screenViewed(.voiceSettings))
}
+ /// Dictation on another provider than calls still needs that provider's key and speech-to-text model.
+ private var dictationProvider: VoiceProvider? {
+ dictationEngine == engine ? nil : VoiceProvider(rawValue: dictationEngine)
+ }
+
private var engineFooter: String {
guard let provider = VoiceProvider(rawValue: engine) else {
return "Apple speech, on this device. Applies from the next call."
@@ -84,11 +93,14 @@ private struct PauseRow: View {
}
/// One provider: mode, the key the computer keeps, models, voice and this month's minutes.
+/// `dictationOnly` keeps the key and speech-to-text model.
private struct ProviderVoiceSettings: View {
let provider: VoiceProvider
+ let dictationOnly: Bool
@Environment(BotStore.self) private var store
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@AppStorage private var mode: String
+ @AppStorage(VoiceSettings.dictationEngineKey) private var dictationEngine = "device"
/// nil while the computer hasn't answered yet.
@State private var saved: Bool?
@State private var replacing = false
@@ -101,16 +113,19 @@ private struct ProviderVoiceSettings: View {
@State private var speechModel = ""
@State private var models = VoiceModels(models: [], transcribe: [], speech: [])
- init(provider: VoiceProvider) {
+ init(provider: VoiceProvider, dictationOnly: Bool = false) {
self.provider = provider
+ self.dictationOnly = dictationOnly
_mode = AppStorage(wrappedValue: "realtime", VoiceSettings.modeKey(provider))
}
private var speechMode: Bool { mode == "speech" }
+ /// Speech mode and dictation with this provider both use its speech-to-text model.
+ private var transcribes: Bool { dictationOnly || speechMode || dictationEngine == provider.rawValue }
private var hasKey: Bool { saved == true }
var body: some View {
- CardSection(provider.name, footer: hasKey ? nil : "Add a key to choose from \(provider.name)'s models.") {
+ CardSection(provider.name, footer: footer) {
VStack(alignment: .leading, spacing: 8) {
if hasKey && !replacing {
savedKeyRow
@@ -127,14 +142,18 @@ private struct ProviderVoiceSettings: View {
}
}
Group {
- if speechMode {
+ if transcribes {
ValueRow("Speech to text") { picker($transcribeModel, models.transcribe) }
- ValueRow("Text to speech") { picker($speechModel, models.speech) }
- } else {
- ValueRow("Model") { picker($model, models.models) }
}
- ValueRow("Voice") { ChoicePicker(selection: $voice, options: provider.voices.map { ($0, $0) }) }
- ValueRow("This month", value: "≈ \(VoiceUsage.minutes(for: provider)) min")
+ if !dictationOnly {
+ if speechMode {
+ ValueRow("Text to speech") { picker($speechModel, models.speech) }
+ } else {
+ ValueRow("Model") { picker($model, models.models) }
+ }
+ ValueRow("Voice") { ChoicePicker(selection: $voice, options: provider.voices.map { ($0, $0) }) }
+ ValueRow("This month", value: "≈ \(VoiceUsage.minutes(for: provider)) min")
+ }
}
.disabled(!hasKey)
.opacity(hasKey ? 1 : 0.55)
@@ -154,6 +173,11 @@ private struct ProviderVoiceSettings: View {
}
}
+ private var footer: String? {
+ guard hasKey else { return "Add a key to choose from \(provider.name)'s models." }
+ return dictationOnly ? "For dictation in the message box." : nil
+ }
+
/// The key is on the computer: say so, and offer test / replace / remove.
private var savedKeyRow: some View {
HStack(spacing: 10) {
@@ -269,13 +293,16 @@ private struct ProviderVoiceSettings: View {
}
/// A pasted key is checked with the provider by the computer before it's kept. With a key
- /// saved, Test starts a call credential with the chosen model and voice.
+ /// saved, Test starts a call credential with the chosen model and voice; for dictation only, it
+ /// lists the key's models.
private func test() {
let typed = key.trimmingCharacters(in: .whitespacesAndNewlines)
guard !typed.isEmpty || hasKey else { return }
run { client in
if typed.isEmpty || !replacing && hasKey {
- if speechMode {
+ if dictationOnly {
+ _ = try await client.voiceModels(provider)
+ } else if speechMode {
_ = try await client.voiceSpeak(provider, model: speechModel, voice: voice, text: "OK")
} else {
_ = try await client.voiceSession(provider, model: model, voice: voice)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/VoiceEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/VoiceEngine.swift
index 112e5951..aefc1c1a 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Call/VoiceEngine.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Call/VoiceEngine.swift
@@ -60,6 +60,13 @@ enum VoiceSettings {
UserDefaults.standard.string(forKey: engineKey).flatMap(VoiceProvider.init(rawValue:))
}
+ /// The same choice for dictation into the message box, picked beside its mic.
+ static let dictationEngineKey = "dictationEngine"
+
+ static var dictationProvider: VoiceProvider? {
+ UserDefaults.standard.string(forKey: dictationEngineKey).flatMap(VoiceProvider.init(rawValue:))
+ }
+
static func modelKey(_ provider: VoiceProvider) -> String { "callModel.\(provider.rawValue)" }
/// The provider's model list as last fetched with the user's key.
static func modelsKey(_ provider: VoiceProvider) -> String { "callModels.\(provider.rawValue)" }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
index 36ad80f4..4275a2a9 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
@@ -26,8 +26,6 @@ struct Composer: View {
@State private var photoItems: [PhotosPickerItem] = []
@FocusState private var focused: Bool
@State private var dictation = Dictation()
- /// The box when dictation started; the words heard go after it.
- @State private var dictatedAfter = ""
/// One line of the field's text, following Dynamic Type: the send button centers on the last line.
@ScaledMetric(relativeTo: .body) private var lineHeight: CGFloat = 22
@@ -207,31 +205,39 @@ struct Composer: View {
.animation(Motion.reduced(Motion.morph, reduceMotion), value: canSend)
}
- /// Dictation, beside send / call (Grok Bot's): a light circle; while it listens, the recording pill.
+ /// Dictation, beside send / call (Grok Bot's): a light circle with its engine menu; while it
+ /// listens or transcribes, the recording pill.
private var micButton: some View {
Group {
- if dictation.listening {
+ if dictation.listening || dictation.transcribing {
RecordingPill(dictation: dictation, height: buttonSize)
.transition(.opacity.combined(with: .scale(scale: 0.9, anchor: .trailing)))
} else {
- Button {
- dictatedAfter = draft
- Task { await dictation.start { said in draft = Dictation.join(dictatedAfter, said) } }
- } label: {
- Image(systemName: "mic")
- .font(.system(size: 15, weight: .medium))
- .foregroundStyle(Palette.secondary)
- .frame(width: buttonSize, height: buttonSize)
- .background(Palette.bubbleAgent, in: Circle())
- .contentShape(Circle())
+ HStack(spacing: 0) {
+ Button {
+ Task {
+ await dictation.start(after: draft, model: model) { change in draft = change(draft) }
+ }
+ } label: {
+ Image(systemName: "mic")
+ .font(.system(size: 15, weight: .medium))
+ .foregroundStyle(Palette.secondary)
+ .frame(width: buttonSize, height: buttonSize)
+ .contentShape(Circle())
+ }
+ .buttonStyle(PressScale())
+ .accessibilityLabel("Dictate")
+ .help("Dictate")
+ DictationEngineMenu(height: buttonSize)
}
- .buttonStyle(PressScale())
- .accessibilityLabel("Dictate")
- .help("Dictate")
+ // The mic and its engine menu share one light capsule.
+ .background(Palette.bubbleAgent, in: Capsule())
.transition(.opacity)
}
}
- .animation(Motion.reduced(Motion.morph, reduceMotion), value: dictation.listening)
+ .animation(Motion.reduced(Motion.morph, reduceMotion), value: dictation.listening || dictation.transcribing)
+ .codyncDialog("Couldn't dictate", isPresented: Binding(get: { dictation.failure != nil }, set: { if !$0 { dictation.failure = nil } }),
+ message: dictation.failure, cancel: "OK") { [] }
}
private var box: some View {
@@ -378,6 +384,8 @@ struct Composer: View {
}
private func submit() {
+ // Words still on their way would land in the emptied box.
+ dictation.stop()
if files.isEmpty, let command = SlashCommands.builtIn(for: bot, members: members, draft: draft) { return run(command) }
guard canSend else { return }
withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swift
index aa4e64a3..de64dbd9 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swift
@@ -1,24 +1,47 @@
import AVFoundation
+import CodyncKit
import Speech
import SwiftUI
-/// Dictation into the message box with on-device speech: the words appear as they're recognized,
-/// after what was already typed; the recording pill's stop, or the recognizer finishing on a pause,
-/// stops it. It uses the call's language setting.
+/// Dictation into the message box. With on-device speech the words appear as they're recognized,
+/// after what was already typed, and the recording pill's stop, or the recognizer finishing on a
+/// pause, stops it; it uses the call's language setting. With a provider picked beside the mic, it
+/// records, and the pill's stop has the computer transcribe all of it with the user's key; the
+/// transcript goes after what's in the box by then.
@MainActor @Observable
final class Dictation {
private(set) var listening = false
+ /// Recorded for a provider, waiting for its transcript.
+ private(set) var transcribing = false
/// When it started listening, for the recording pill's time.
private(set) var startedAt = Date.now
/// The microphone's level while listening, 0…1.
private(set) var level: Float = 0
+ /// Why the last dictation ended early (no key, no network), until the next.
+ var failure: String?
@ObservationIgnored private let engine = AVAudioEngine()
@ObservationIgnored private var request: SFSpeechAudioBufferRecognitionRequest?
@ObservationIgnored private var task: SFSpeechRecognitionTask?
- @ObservationIgnored private var heard: ((String) -> Void)?
- /// Bumped per start and stop, so a late result from an earlier recognition is dropped.
+ /// Recording for a provider: what the microphone heard (16 kHz mono PCM16), and whose computer transcribes it.
+ @ObservationIgnored private var recording: (provider: VoiceProvider, model: BotStore, pcm: Data)?
+ /// Changes the box's text: on-device words replace what follows `before`; a transcript goes after the box as it is then.
+ @ObservationIgnored private var edit: (((String) -> String) -> Void)?
+ /// The box when dictation started.
+ @ObservationIgnored private var before = ""
+ /// A recording's transcription; `stop()` cancels it so no more pieces go out on the user's key.
+ @ObservationIgnored private var transcription: Task<Void, Never>?
+ /// Bumped per start and stop, so a start still waiting (key check, permission) or a late
+ /// result from an earlier recognition is dropped.
@ObservationIgnored private var generation = 0
+ /// A transcription request has to fit one channel message once base64-encoded: 20 s of audio
+ /// (20.5 s with a short tail still fits).
+ static let pieceBytes = 16000 * 2 * 20
+ /// Under half a second is a tap of the mic, not speech (and speech-to-text models invent words for silence).
+ static let minBytes = 16000 * 2 / 2
+ /// Transcription requests in flight at once, under the channel's and the providers' limits.
+ private static let inFlight = 3
+
/// `said` after what's already in the box, with one space between.
static func join(_ before: String, _ said: String) -> String {
if before.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return said }
@@ -26,63 +49,171 @@ final class Dictation {
return before.last?.isWhitespace == true ? before + said : before + " " + said
}
- func start(heard: @escaping (String) -> Void) async {
- guard !listening, await AVAudioApplication.requestRecordPermission(), await Self.authorized() else { return }
- let recognizer = UserDefaults.standard.string(forKey: OnDeviceEngine.languageKey)
- .flatMap { $0.isEmpty ? nil : SFSpeechRecognizer(locale: Locale(identifier: $0)) } ?? SFSpeechRecognizer()
- guard let recognizer, recognizer.isAvailable else { return }
- do {
- let audio = AVAudioSession.sharedInstance()
- // The call's session: a recording tap on a `.record` session fails on some routes.
- try audio.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothHFP, .duckOthers])
- try audio.setActive(true)
- } catch {
- return
- }
- guard let format = try? MicTap.format(of: engine.inputNode) else {
- try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
- return
- }
+ /// Starts with the engine picked beside the mic, after `draft`; a provider goes through `model`'s
+ /// computer. A `stop()` (another chat, a call, a send) or another tap while it waits wins.
+ func start(after draft: String, model: BotStore, edit: @escaping ((String) -> String) -> Void) async {
+ guard !listening, !transcribing else { return }
+ failure = nil
generation += 1
- self.heard = heard
- let request = SFSpeechAudioBufferRecognitionRequest()
- request.shouldReportPartialResults = true
- request.addsPunctuation = true
- if recognizer.supportsOnDeviceRecognition { request.requiresOnDeviceRecognition = true }
- self.request = request
- let input = engine.inputNode
- input.removeTap(onBus: 0)
- input.installTap(onBus: 0, bufferSize: 1024, format: format, block: OnDeviceEngine.tap(request) { [weak self] level in
- Task { @MainActor in if self?.listening == true { self?.level = level } }
- })
- engine.prepare()
- do {
- try engine.start()
- } catch {
- return stop()
+ before = draft
+ if let provider = VoiceSettings.dictationProvider {
+ await record(provider, model: model, generation: generation, edit: edit)
+ } else {
+ await recognize(generation: generation, edit: edit)
+ }
+ }
+
+ /// The pill's stop: on-device speech has already typed its words; a recording gets transcribed.
+ func finish() {
+ guard let recording else { return stop() }
+ let edit = edit
+ stop()
+ guard recording.pcm.count >= Self.minBytes else { return }
+ let generation = generation
+ transcribing = true
+ transcription = Task {
+ do {
+ let said = try await Self.transcribe(recording.pcm, provider: recording.provider, on: recording.model)
+ VoiceUsage.add(seconds: recording.pcm.count / (16000 * 2), for: recording.provider)
+ guard generation == self.generation else { return }
+ edit? { Self.join($0, said) }
+ } catch {
+ guard generation == self.generation else { return }
+ failure = error.localizedDescription
+ }
+ transcribing = false
}
- startedAt = .now
- listening = true
- task = recognizer.recognitionTask(with: request, resultHandler: Self.results(self, generation: generation))
}
+ /// Stops now and drops anything still on its way.
func stop() {
generation += 1
+ transcription?.cancel()
+ transcription = nil
task?.cancel()
task = nil
request?.endAudio()
request = nil
+ recording = nil
+ transcribing = false
engine.inputNode.removeTap(onBus: 0)
if engine.isRunning { engine.stop() }
- heard = nil
+ edit = nil
if listening { try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) }
listening = false
level = 0
}
+ private func recognize(generation: Int, edit: @escaping ((String) -> String) -> Void) async {
+ guard await AVAudioApplication.requestRecordPermission(), await Self.authorized(), generation == self.generation else { return }
+ let recognizer = UserDefaults.standard.string(forKey: OnDeviceEngine.languageKey)
+ .flatMap { $0.isEmpty ? nil : SFSpeechRecognizer(locale: Locale(identifier: $0)) } ?? SFSpeechRecognizer()
+ guard let recognizer, recognizer.isAvailable else { return }
+ let request = SFSpeechAudioBufferRecognitionRequest()
+ request.shouldReportPartialResults = true
+ request.addsPunctuation = true
+ if recognizer.supportsOnDeviceRecognition { request.requiresOnDeviceRecognition = true }
+ guard openMic(bufferSize: 1024, tap: { _ in OnDeviceEngine.tap(request) { [weak self] level in
+ Task { @MainActor in if self?.listening == true { self?.level = level } }
+ } }) else { return }
+ self.edit = edit
+ self.request = request
+ startedAt = .now
+ listening = true
+ task = recognizer.recognitionTask(with: request, resultHandler: Self.results(self, generation: generation))
+ }
+
+ /// Records for `provider` once the computer has its key, so nothing said is lost to a missing one.
+ private func record(_ provider: VoiceProvider, model: BotStore, generation: Int, edit: @escaping ((String) -> String) -> Void) async {
+ do {
+ let status = try await model.ready().voiceStatus()
+ VoiceSettings.remember(status)
+ guard generation == self.generation else { return }
+ guard status.configured(provider) else {
+ failure = "Add your \(provider.name) key in Voice chat settings to dictate with it."
+ return
+ }
+ } catch {
+ if generation == self.generation { failure = error.localizedDescription }
+ return
+ }
+ let allowed = await AVAudioApplication.requestRecordPermission()
+ guard generation == self.generation else { return }
+ guard allowed else {
+ failure = "Allow microphone access in Settings to dictate."
+ return
+ }
+ guard openMic(bufferSize: 2048, tap: { format in MicTap.pcm16k(from: format) { [weak self] pcm, level in
+ Task { @MainActor in self?.recorded(pcm, level: level, generation: generation) }
+ } }) else {
+ failure = "The microphone isn't available."
+ return
+ }
+ self.edit = edit
+ recording = (provider, model, Data())
+ startedAt = .now
+ listening = true
+ }
+
+ private func recorded(_ pcm: Data, level: Float, generation: Int) {
+ guard generation == self.generation, recording != nil else { return }
+ recording?.pcm.append(pcm)
+ self.level = level
+ }
+
+ /// The call's audio session (a recording tap on a `.record` session fails on some routes) and
+ /// `tap` on the microphone. False, with everything let go, when the microphone can't be used.
+ private func openMic(bufferSize: AVAudioFrameCount, tap: (AVAudioFormat) -> AVAudioNodeTapBlock) -> Bool {
+ let audio = AVAudioSession.sharedInstance()
+ do {
+ try audio.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothHFP, .duckOthers])
+ try audio.setActive(true)
+ let input = engine.inputNode
+ let format = try MicTap.format(of: input)
+ input.removeTap(onBus: 0)
+ input.installTap(onBus: 0, bufferSize: bufferSize, format: format, block: tap(format))
+ engine.prepare()
+ try engine.start()
+ return true
+ } catch {
+ engine.inputNode.removeTap(onBus: 0)
+ if engine.isRunning { engine.stop() }
+ try? audio.setActive(false, options: .notifyOthersOnDeactivation)
+ return false
+ }
+ }
+
+ /// Byte ranges of a recording's 20 s pieces; a tail under half a second stays with the piece before.
+ static func pieces(of count: Int) -> [Range<Int>] {
+ var starts = Array(stride(from: 0, to: count, by: pieceBytes))
+ if starts.count > 1, let last = starts.last, count - last < minBytes { starts.removeLast() }
+ return zip(starts, starts.dropFirst() + [count]).map { $0..<$1 }
+ }
+
+ /// The recording in pieces, a few transcribed at a time and joined in order.
+ private static func transcribe(_ pcm: Data, provider: VoiceProvider, on store: BotStore) async throws -> String {
+ // Asked for now, not at the start: a reconnect while recording replaces the client.
+ let client = try await store.ready()
+ let model = VoiceSettings.transcribeModel(provider)
+ let wavs = pieces(of: pcm.count).map { MicTap.wav(pcm.subdata(in: $0)) }
+ let texts = try await withThrowingTaskGroup(of: (Int, String).self) { group in
+ var texts = [String](repeating: "", count: wavs.count)
+ func keep(_ result: (Int, String)) { texts[result.0] = result.1.trimmingCharacters(in: .whitespacesAndNewlines) }
+ for (i, wav) in wavs.enumerated() {
+ if i >= inFlight, let done = try await group.next() { keep(done) }
+ try Task.checkCancellation()
+ group.addTask { (i, try await client.voiceTranscribe(provider, model: model, wav: wav)) }
+ }
+ for try await done in group { keep(done) }
+ return texts
+ }
+ return VoiceSettings.inReadersScript(texts.filter { !$0.isEmpty }.reduce("", join))
+ }
+
private func recognized(_ text: String, final: Bool, generation: Int) {
guard generation == self.generation else { return }
- heard?(text)
+ let before = before
+ edit? { _ in Self.join(before, text) }
if final { stop() }
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/DictationEngineMenu.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/DictationEngineMenu.swift
new file mode 100644
index 00000000..8686ac26
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/DictationEngineMenu.swift
@@ -0,0 +1,27 @@
+import CodyncKit
+import SwiftUI
+
+/// Beside the composer's mic, in its capsule: which speech dictation uses, on-device or a provider on the user's own key.
+struct DictationEngineMenu: View {
+ let height: CGFloat
+ @AppStorage(VoiceSettings.dictationEngineKey) private var engine = "device"
+
+ var body: some View {
+ DropdownMenu {
+ [MenuItem("On device", selected: engine == "device") { engine = "device" }]
+ + VoiceProvider.allCases.map { provider in
+ MenuItem(provider.name, selected: engine == provider.rawValue) { engine = provider.rawValue }
+ }
+ } label: {
+ Image(systemName: "chevron.up")
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(Palette.secondary)
+ .frame(width: 14, height: height)
+ // The capsule's end is part of the tap area, away from the mic.
+ .padding(.trailing, 6)
+ .contentShape(Rectangle())
+ }
+ .accessibilityLabel("Dictation engine")
+ .help("Dictation engine")
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/RecordingPill.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/RecordingPill.swift
index 5e20df82..1ca35657 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/RecordingPill.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/RecordingPill.swift
@@ -2,7 +2,8 @@ import CodyncKit
import SwiftUI
/// Dictation in progress, in place of the composer's mic: stop, the time since it started, and
-/// dots that follow the microphone's level (the desktop composer's pill).
+/// dots that follow the microphone's level (the desktop composer's pill); a spinner once a
+/// recording waits for its transcript.
struct RecordingPill: View {
let dictation: Dictation
let height: CGFloat
@@ -10,22 +11,30 @@ struct RecordingPill: View {
var body: some View {
HStack(spacing: 6) {
- Button { dictation.stop() } label: {
- Image(systemName: "stop.fill")
- .font(.system(size: 11, weight: .bold))
- .foregroundStyle(Palette.text)
+ if dictation.transcribing {
+ Spinner(size: 14)
.frame(width: height - 8, height: height - 8)
- .contentShape(Circle())
+ Text("Transcribing…")
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ } else {
+ Button { dictation.finish() } label: {
+ Image(systemName: "stop.fill")
+ .font(.system(size: 11, weight: .bold))
+ .foregroundStyle(Palette.text)
+ .frame(width: height - 8, height: height - 8)
+ .contentShape(Circle())
+ }
+ .buttonStyle(PressScale())
+ .accessibilityLabel("Stop dictating")
+ .help("Stop dictating")
+ Text(timerInterval: dictation.startedAt...Date.distantFuture, countsDown: false)
+ .font(.subheadline.monospacedDigit())
+ .foregroundStyle(Palette.text)
+ LevelDots(level: dictation.level, speaking: false, working: false, color: Palette.text, reduceMotion: reduceMotion)
+ .frame(width: 32, height: 12)
+ .accessibilityLabel("Listening")
}
- .buttonStyle(PressScale())
- .accessibilityLabel("Stop dictating")
- .help("Stop dictating")
- Text(timerInterval: dictation.startedAt...Date.distantFuture, countsDown: false)
- .font(.subheadline.monospacedDigit())
- .foregroundStyle(Palette.text)
- LevelDots(level: dictation.level, speaking: false, working: false, color: Palette.text, reduceMotion: reduceMotion)
- .frame(width: 32, height: 12)
- .accessibilityLabel("Listening")
}
.padding(.leading, 4)
.padding(.trailing, 10)
diff --git a/apps/ios/Kit/Tests/CodyncUITests/DictationTests.swift b/apps/ios/Kit/Tests/CodyncUITests/DictationTests.swift
new file mode 100644
index 00000000..b56c1fb8
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/DictationTests.swift
@@ -0,0 +1,20 @@
+import Testing
+@testable import CodyncUI
+
+/// A provider's recording goes out in 20 s pieces that cover every byte in order; a tail under
+/// half a second (noise a model would invent words for) stays with the piece before.
+@Test @MainActor func dictationPiecesCoverTheRecording() {
+ let piece = Dictation.pieceBytes, min = Dictation.minBytes
+ #expect(Dictation.pieces(of: piece / 2) == [0..<piece / 2])
+ #expect(Dictation.pieces(of: piece * 2) == [0..<piece, piece..<piece * 2])
+ #expect(Dictation.pieces(of: piece * 2 + min) == [0..<piece, piece..<piece * 2, piece * 2..<piece * 2 + min])
+ #expect(Dictation.pieces(of: piece + min - 1) == [0..<piece + min - 1])
+ #expect(Dictation.pieces(of: piece * 2 + 2) == [0..<piece, piece..<piece * 2 + 2])
+}
+
+@Test @MainActor func dictatedWordsGoAfterTheBox() {
+ #expect(Dictation.join("", "hello") == "hello")
+ #expect(Dictation.join("Fix the bug", "in the parser") == "Fix the bug in the parser")
+ #expect(Dictation.join("Fix the bug\n", "now") == "Fix the bug\nnow")
+ #expect(Dictation.join("Fix the bug", "") == "Fix the bug")
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 6d4be6e0..8bd7798c 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -11,7 +11,9 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
- 用麥克風聽寫時,麥克風按鈕會變成錄音膠囊:停止鍵、錄了多久,還有跟著你說話起伏的點點
- Bot 工作中時點一下狀態列,就能即時看它的思考過程和每個步驟
+- 麥克風旁的向上箭頭可以選聽寫要用裝置內建語音,還是用你自己的 OpenAI 或 Gemini 金鑰
### en-US
- While you dictate, the mic turns into a recording pill: a stop button, how long you've been talking, and dots that follow your voice
- While a bot works, tap its status line to watch its thinking and each step live
+- The arrow beside the mic picks how dictation hears you: on-device speech, or your own OpenAI or Gemini key
diff --git a/docs/features/notch-island.md b/docs/features/notch-island.md
index 468b3456..fc03972b 100644
--- a/docs/features/notch-island.md
+++ b/docs/features/notch-island.md
@@ -36,7 +36,7 @@ bar). A bot can be messaged from the island, and ⌥Y / ⌥N answer an approval
Opened by hover, the island folds 0.8 s after the pointer leaves; opened by a click or a tab,
10 s after (a 2 pt line counts down). The message field stays until it sends, Esc or a click in
-another app. An approval opens by itself and stays until answered; the Bots tab puts it off
+another app; switching to another tab while it dictates stops dictation and keeps the words. An approval opens by itself and stays until answered; the Bots tab puts it off
until another arrives. Answers and messages go through the chat window (`respondPermission`,
`send`), like the chat's own cards and composer. The states, sizes and motion are drawn in the
design canvas the island was built from.
diff --git a/docs/features/voice-call.md b/docs/features/voice-call.md
index 7854d219..11ed24ef 100644
--- a/docs/features/voice-call.md
+++ b/docs/features/voice-call.md
@@ -51,15 +51,34 @@ shortcut's tap), which waits for the last words, on an error (shown in the windo
window takes the speech helper; it doesn't stop on a pause. On the iPhone the pill's stop keeps what
was recognized so far. The desktop island's message field has the same mic and pill.
-- Desktop (`views/thread/dictation.ts`): the speech helper, macOS only, so Linux and Windows show
- no mic. An unpackaged `npm run dev` can't use it: macOS stops the helper because the dev Electron
- has no speech usage description, so test it in a packaged build (`dist:mac:dev`), like calls.
+A `chevron.up` beside the composer's mic picks dictation's engine, kept on the device apart from the
+call engine (`dictationEngine`): **On device** (the above), or **OpenAI** / **Gemini** on the user's
+own key. With a provider, the mic first checks that the computer holds its key (`voiceStatus`; no key
+means an error before anything is recorded), then records; nothing is typed while recording. The
+pill's stop turns the pill into "Transcribing…" and the whole recording goes through
+`voiceTranscribe` with the call settings' speech-to-text model; the text lands after what's in the
+box when it arrives (typing goes on while it records). The recording goes in 20 s pieces (one
+channel message each on the iPhone; under the host's 2 MB request body on the desktop), three at a
+time, joined in order; a tail under half a second stays with the piece before, and the first piece
+that fails fails the dictation. Under half a second of audio in all is dropped. Sending a message,
+starting a call or switching chats drops a dictation still recording or transcribing. The
+recording's length counts toward the provider's minutes this month. The island's mic stays
+on-device (its window doesn't reach the host).
+
+- Desktop (`views/thread/dictation.ts`, the model, tested with a stub platform; the helper,
+ microphone and host wired in `dictation-platform.ts`; pieces in `dictation-pieces.ts`; menu in
+ `DictationEngineMenu.tsx`): on-device speech is the speech helper, macOS only. Linux and Windows
+ show the mic too, for a provider; with **On device** picked each press says on-device speech isn't
+ available there. An unpackaged `npm run dev` can't use the helper: macOS stops it because the dev
+ Electron has no speech usage description, so test it in a packaged build (`dist:mac:dev`), like
+ calls.
- Desktop: the speech helper serves one window at a time. When another window starts it (the
island while the chat window dictates or calls, or the other way round), `main/speech.ts` tells
the window that lost it (`stopped`) and ignores that window's stop.
-- iPhone (`Thread/Dictation.swift`, pill in `Thread/RecordingPill.swift`, dots shared with the call
- bar in `LevelDots.swift`): `SFSpeechRecognizer` on device; with no microphone route (some
- simulators) the mic does nothing.
+- iPhone (`Thread/Dictation.swift`, pill in `Thread/RecordingPill.swift`, menu in
+ `Thread/DictationEngineMenu.swift`, dots shared with the call bar in `LevelDots.swift`):
+ `SFSpeechRecognizer` on device; with no microphone route (some simulators) the mic does nothing.
+ A provider's errors (no key, no connection) show in a dialog.
- Android has no composer mic yet.
- The terminal UI has no microphone, so no mic.
@@ -176,7 +195,10 @@ is there and can test it. Picking a cloud engine shows its key form instead of t
to the provider's key page, **Test** (the computer checks a new key with the provider and keeps it
only if it works, otherwise the provider's error is shown; with a key saved, it mints a call
credential for the chosen model and voice), a model picker, a voice picker, and minutes used this month.
-Speech mode adds speech-to-text and text-to-speech pickers and the pause length. The model list comes from the provider through the computer (`voiceModels`: OpenAI `GET /v1/models`
+Speech mode adds speech-to-text and text-to-speech pickers and the pause length; dictating with
+the provider shows its speech-to-text picker too. When dictation's engine is a provider the call
+engine isn't, that provider gets its own section below with just the key and speech-to-text picker
+("For dictation in the message box."), so its key can be added without switching the call engine; its **Test** lists the key's models instead of minting a call credential. The model list comes from the provider through the computer (`voiceModels`: OpenAI `GET /v1/models`
ids sorted into realtime, transcribe and tts models; Gemini `GET v1beta/models` by
`bidiGenerateContent` / `generateContent` and name; translation and diarization models left out), fetched after a successful test and each time the form opens. The call bar
shows the provider's name next to the dots whenever audio leaves the device.
@@ -225,7 +247,8 @@ The realtime model is an operator in front of the bot, not a replacement for it
- No key on the computer, invalid key, quota or network failure at start, or a dropped connection mid-call: the
call switches to On device without hanging up, with a one-line notice under the bar.
- Usage is billed by the provider to the user. The key form shows minutes used this month
- (`VoiceUsage`, counted on each device while a cloud engine is live) as an estimate, not a bill.
+ (`VoiceUsage`, counted on each device while a cloud engine is live and for each recording
+ dictated with the provider) as an estimate, not a bill.
### Verification
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
index 3faf6818..5e99167d 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -18,7 +18,7 @@ emulator against a real host; device acceptance is listed separately.
| Accounts/access | Ported: account sheet and switcher, Computers & settings (connection status, badge color, Revoke this phone's access, older copies removed from the account), account computer access with its code, access banner, `codync-dev://computers` and `codync-dev://plugins` | Provider browser round trip on a device; Revoke and older copies against a signed-in account (covered by cloud request tests only); one computer per phone ([multiple computers are future work](../architecture/overview.md)) |
| Roster | Ported: rows, menus, pin/hide/delete, groups, drag to reorder (host-synced order) and TalkBack Move up/down, computer header, pull to refresh (also in Computers & settings) | Multiple computers |
| Conversation | Ported: bubbles, Markdown/code, permissions, reactions, quote replies, Full conversation, bot-to-bot exchange lines and their conversation, routine notices that open their routine, files a bot shares (verified download, then the share sheet), sent images full size, pull down to reconnect, jump to latest, read receipts for every conversation on screen | Physical keyboard and TalkBack |
-| Composer | Ported: files/photos/paste (groups too, image thumbnails, Paste only when the clipboard holds files), `/` commands (Fast mode, skills listed fresh on `/`), @mentions in groups, call/send/stop/interrupt button | — |
+| Composer | Ported: files/photos/paste (groups too, image thumbnails, Paste only when the clipboard holds files), `/` commands (Fast mode, skills listed fresh on `/`), @mentions in groups, call/send/stop/interrupt button | Dictation ([voice call](../features/voice-call.md)): the mic, its recording pill, the engine menu beside it (On device, or OpenAI / Gemini transcribed on the user's key with *Transcribing…*) and the *Couldn't dictate* dialog |
| Bot and group editors | Ported: avatar, profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills (with their details) | — |
| Memory | Broken since 2.18.0: the screen calls removed host methods (see [Not ported yet](#not-ported-yet)) | Port the read-only memory screen from `MemoryView.swift`, `MemoryFilesView.swift` and `MemoryInfoSheet.swift`, without add, edit, pin or forget |
| Routines | Ported: list with switches, editor (schedule, webhook panel, run settings), test run, delete | Live provider/routine acceptance |