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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(desktop): recover cancelled sign-in and guide voice setup
leepokai7c6372bd4f74
diff --git a/apps/desktop/src/main/account.ts b/apps/desktop/src/main/account.tsindex 1a625e5c..a81a49b0 100644--- a/apps/desktop/src/main/account.ts+++ b/apps/desktop/src/main/account.ts@@ -78,12 +78,14 @@ class ClerkError extends Error {constructor(readonly status: number,message: string,+ readonly code?: string,) {super(message)}}export class AccountService extends EventEmitter {+ private signInAttempt = 0private config = loadConfig()private base = this.config.clerkPublishableKey ? frontendAPI(this.config.clerkPublishableKey) : nullprivate deviceToken: string | null = null@@ -155,7 +157,7 @@ export class AccountService extends EventEmitter {} catch {}}- private async request<T>(method: 'GET' | 'POST' | 'DELETE', path: string, body?: Record<string, string | boolean>, query?: Record<string, string>): Promise<T> {+ private async request<T>(method: 'GET' | 'POST' | 'DELETE', path: string, body?: Record<string, string | boolean>, query?: Record<string, string>, accept?: (response: T) => boolean): Promise<T> {if (!this.base) throw new ClerkError(0, "Sign-in isn't configured in this build.")const url = new URL(`${this.base}${path}`)url.searchParams.set('_is_native', 'true')@@ -168,16 +170,21 @@ export class AccountService extends EventEmitter {payload = new URLSearchParams(Object.entries(body).map(([k, v]) => [k, String(v)])).toString()}const res = await fetch(url, { method, headers, body: payload, signal: AbortSignal.timeout(20_000) })- // A new device token comes back in `Authorization`; "Bearer" alone clears it.- const auth = res.headers.get('authorization')?.trim()- if (auth !== undefined) {- this.deviceToken = !auth || auth.toLowerCase() === 'bearer' ? null : auth- void this.persist()+ const json = (await res.json().catch(() => ({}))) as { response?: T; client?: ClerkClient | null; errors?: { code?: string; long_message?: string; message?: string }[] } & T+ const response = json.response ?? json+ const accepted = res.ok && (!accept || accept(response))+ // Keep normal token rotation (including sign-out responses), but a rejected browser nonce+ // must not replace this attempt's client/token.+ if (accepted || !accept) {+ const auth = res.headers.get('authorization')?.trim()+ if (auth !== undefined) {+ this.deviceToken = !auth || auth.toLowerCase() === 'bearer' ? null : auth+ void this.persist()+ }}- const json = (await res.json().catch(() => ({}))) as { response?: T; client?: ClerkClient | null; errors?: { long_message?: string; message?: string }[] } & T- if (!res.ok) throw new ClerkError(res.status, json.errors?.[0]?.long_message ?? json.errors?.[0]?.message ?? `Clerk error ${res.status}`)- if ('client' in json) this.applyClient(json.client ?? null)- return (json.response ?? json) as T+ if (!res.ok) throw new ClerkError(res.status, json.errors?.[0]?.long_message ?? json.errors?.[0]?.message ?? `Clerk error ${res.status}`, json.errors?.[0]?.code)+ if (accepted && 'client' in json) this.applyClient(json.client ?? null)+ return response}private applyClient(client: ClerkClient | null) {@@ -200,6 +207,38 @@ export class AccountService extends EventEmitter {this.applyClient(client)}+ /** Only a callback verified against this sign-in may finish its browser wait. */+ private async browserSignIn(id: string, redirect: string, attempt: number) {+ let verified: SignInResource | null = null+ const accept = async (url: string, isCurrent: () => boolean) => {+ if (attempt !== this.signInAttempt) return false+ this.set({ busy: true })+ try {+ const nonce = new URL(url).searchParams.get('rotating_token_nonce')+ const matches = (value: SignInResource) => isCurrent() && attempt === this.signInAttempt && (value.status === 'complete'+ || value.status === 'needs_second_factor'+ || [value.first_factor_verification, value.second_factor_verification].some((factor) => factor?.status === 'transferable' || factor?.error))+ const value = await this.request<SignInResource>('GET', `/v1/client/sign_ins/${id}`, undefined,+ nonce ? { rotating_token_nonce: nonce } : undefined, matches)+ if (!matches(value)) return false+ verified = value+ return true+ } catch (error) {+ // Clerk rejects a nonce from a different/expired browser flow without consuming ours.+ if (error instanceof ClerkError && error.code === 'signed_out') return false+ throw error+ } finally {+ if (attempt === this.signInAttempt && !verified) this.set({ busy: false })+ }+ }+ // Closing the browser does not leave the app loading; another sign-in can replace it.+ const authentication = authenticate(redirect, SCHEME, accept)+ this.set({ busy: false })+ const callback = new URL(await authentication)+ if (attempt !== this.signInAttempt || !verified) return null+ return { callback, signIn: verified as SignInResource }+ }+/** Why it ended without an account (`sign_in_failed`); null once signed in. */async signIn(provider: SignInProvider): Promise<SignInFailure | null> {if (this.state.busy) return null@@ -207,6 +246,7 @@ export class AccountService extends EventEmitter {this.set({ error: "Sign-in setup isn't finished yet. You can continue using local pairing." })return 'error'}+ const attempt = ++this.signInAttemptconst name = provider === 'apple' ? 'Apple' : 'Google'let failure: SignInFailure | null = nullthis.set({ busy: true, error: null })@@ -216,9 +256,10 @@ export class AccountService extends EventEmitter {const prepared = await this.request<SignInResource>('POST', `/v1/client/sign_ins/${created.id}/prepare_first_factor`, { strategy, redirect_url: REDIRECT })const redirect = prepared.first_factor_verification?.external_verification_redirect_urlif (!redirect) throw new ClerkError(0, 'Redirect URL is missing. Unable to start the sign-in.')- const callback = new URL(await authenticate(redirect, SCHEME))+ const authenticated = await this.browserSignIn(created.id, redirect, attempt)+ if (!authenticated) return 'cancelled'+ const { callback, signIn } = authenticatedconst nonce = callback.searchParams.get('rotating_token_nonce')- const signIn = await this.request<SignInResource>('GET', `/v1/client/sign_ins/${created.id}`, undefined, nonce ? { rotating_token_nonce: nonce } : undefined)const transferable = signIn.first_factor_verification?.status === 'transferable' || signIn.second_factor_verification?.status === 'transferable'if (!nonce && transferable) {// A new account: Clerk's transfer flow turns the sign-in into a sign-up.@@ -235,13 +276,14 @@ export class AccountService extends EventEmitter {}await this.refreshClient()} catch (error) {+ if (attempt !== this.signInAttempt) return 'cancelled'if (error instanceof AuthenticationEnded) failure = error.reasonelse {failure = 'error'this.set({ error: "Couldn't sign in. Check your connection and try again." })}} finally {- this.set({ busy: false })+ if (attempt === this.signInAttempt) this.set({ busy: false })}return failure}diff --git a/apps/desktop/src/main/auth.ts b/apps/desktop/src/main/auth.tsindex ae743bcc..521c9f1f 100644--- a/apps/desktop/src/main/auth.ts+++ b/apps/desktop/src/main/auth.ts@@ -1,3 +1,4 @@+import { BrowserAuthentication } from './browser-authentication'import { app, ipcMain, shell } from 'electron'import { identity } from './environment'@@ -6,21 +7,9 @@ import { identity } from './environment'export const SCHEMES = [identity.scheme, identity.appId]-interface Pending {- scheme: string- resolve: (url: string) => void- reject: (error: Error) => void- timer: NodeJS.Timeout-}--let pending: Pending | null = null+const browser = new BrowserAuthentication((url) => shell.openExternal(url))-/** The browser never came back: another sign-in took its place, or it ran out of time. */-export class AuthenticationEnded extends Error {- constructor(readonly reason: 'cancelled' | 'timeout', message: string) {- super(message)- }-}+export { AuthenticationEnded } from './browser-authentication'export function registerSchemes() {for (const scheme of SCHEMES) {@@ -35,36 +24,14 @@ export function registerSchemes() {}/** A URL on one of our schemes reached the app (open-url, or a second instance's argv). */-export function handleURL(url: string) {- const scheme = url.split(':')[0]?.toLowerCase()- if (pending && scheme === pending.scheme.toLowerCase()) {- clearTimeout(pending.timer)- pending.resolve(url)- pending = null- }-}+export const handleURL = (url: string) => browser.handleURL(url)export function urlFromArgv(argv: string[]) {return argv.find((a) => SCHEMES.some((s) => a.toLowerCase().startsWith(`${s.toLowerCase()}:`)))}-/** Opens `url` in the browser and waits (up to 10 minutes) for the return on `scheme`. */-export function authenticate(url: string, scheme: string): Promise<string> {- if (!/^https:\/\//.test(url)) return Promise.reject(new Error('Sign-in needs an https address.'))- pending?.reject(new AuthenticationEnded('cancelled', 'Another sign-in started.'))- return new Promise((resolve, reject) => {- pending = {- scheme,- resolve,- reject,- timer: setTimeout(() => {- pending = null- reject(new AuthenticationEnded('timeout', 'Sign-in timed out.'))- }, 10 * 60_000),- }- void shell.openExternal(url)- })-}+export const authenticate = (url: string, scheme: string, accept?: (url: string, isCurrent: () => boolean) => Promise<boolean>) =>+ browser.authenticate(url, scheme, accept)export function registerAuthIPC() {ipcMain.handle('app:authenticate', (_e, url: string, scheme: string) => authenticate(url, scheme))diff --git a/apps/desktop/src/main/browser-authentication.ts b/apps/desktop/src/main/browser-authentication.tsnew file mode 100644index 00000000..b9c71474--- /dev/null+++ b/apps/desktop/src/main/browser-authentication.ts@@ -0,0 +1,67 @@+/** A browser may disappear without a callback; its wait must never own the app's loading state. */+export class AuthenticationEnded extends Error {+ readonly reason: 'cancelled' | 'timeout'++ constructor(reason: 'cancelled' | 'timeout', message: string) {+ super(message)+ this.reason = reason+ }+}++interface Pending {+ scheme: string+ accept: (url: string, isCurrent: () => boolean) => Promise<boolean>+ resolve: (url: string) => void+ reject: (error: unknown) => void+ timer: ReturnType<typeof setTimeout>+ callbacks: Promise<void>+}++/** Owns one browser flow, including validation before a callback can consume it. */+export class BrowserAuthentication {+ private pending: Pending | null = null++ private readonly open: (url: string) => Promise<void>+ private readonly timeoutMs: number++ constructor(open: (url: string) => Promise<void>, timeoutMs = 10 * 60_000) {+ this.open = open+ this.timeoutMs = timeoutMs+ }++ authenticate(url: string, scheme: string, accept: (url: string, isCurrent: () => boolean) => Promise<boolean> = async () => true): Promise<string> {+ if (!/^https:\/\//.test(url)) return Promise.reject(new Error('Sign-in needs an https address.'))+ if (this.pending) this.finish(this.pending, new AuthenticationEnded('cancelled', 'Another sign-in started.'))+ return new Promise((resolve, reject) => {+ const pending: Pending = {+ scheme, accept, resolve, reject, callbacks: Promise.resolve(),+ timer: setTimeout(() => this.finish(pending, new AuthenticationEnded('timeout', 'Sign-in timed out.')), this.timeoutMs),+ }+ this.pending = pending+ void Promise.resolve().then(() => this.open(url)).catch((error: unknown) => this.finish(pending, error))+ })+ }++ handleURL(url: string) {+ const pending = this.pending+ if (!pending || url.split(':')[0]?.toLowerCase() !== pending.scheme.toLowerCase()) return+ // A stale tab may return before the current one. Validate in order; a rejected callback+ // leaves the current wait intact and cannot race another nonce exchange.+ pending.callbacks = pending.callbacks.then(async () => {+ if (this.pending !== pending) return+ try {+ if (await pending.accept(url, () => this.pending === pending)) this.finish(pending, undefined, url)+ } catch (error) {+ this.finish(pending, error)+ }+ })+ }++ private finish(pending: Pending, error?: unknown, url?: string) {+ if (this.pending !== pending) return+ clearTimeout(pending.timer)+ this.pending = null+ if (url !== undefined) pending.resolve(url)+ else pending.reject(error)+ }+}diff --git a/apps/desktop/src/renderer/views/call/CallView.tsx b/apps/desktop/src/renderer/views/call/CallView.tsxindex 3dc55f43..6da05028 100644--- a/apps/desktop/src/renderer/views/call/CallView.tsx+++ b/apps/desktop/src/renderer/views/call/CallView.tsx@@ -12,7 +12,7 @@ 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 { engine as preferredEngine, voiceStatus } from '../settings/voice-settings'import { stopDictation } from '../thread/dictation'import { CallLink } from './call-link'import { CallQuality } from './call-quality'@@ -180,8 +180,9 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {if (closed.current || engineChoice.current !== picked) returnif (configured) {setNotice(`${onDeviceUnavailableReason()} Using ${providerName(configured)}.`)+ if (window.codync.platform !== 'darwin') preferredEngine.set(configured)begin(configured)- engineChoice.current = picked+ if (window.codync.platform === 'darwin') engineChoice.current = picked} else {setBlocked(`${onDeviceUnavailableReason()} Add an OpenAI or Gemini key in call settings.`)// Nothing runs: the next settings close tries again, with a key added there.diff --git a/apps/desktop/src/renderer/views/call/voice.test.ts b/apps/desktop/src/renderer/views/call/voice.test.tsindex f0d5dcb8..7ecec9e1 100644--- a/apps/desktop/src/renderer/views/call/voice.test.ts+++ b/apps/desktop/src/renderer/views/call/voice.test.ts@@ -44,3 +44,19 @@ test('a call takes another engine only when what its engine is built from changeseen.push(choice)}})+++test('Windows and Linux retain automatic call fallback until a provider is explicitly picked', async () => {+ const { VoiceSettings } = await import('./voice.ts')+ const settings = await import('../settings/voice-settings.ts')+ for (const platform of ['win32', 'linux']) {+ Object.assign(window, { codync: { platform } })+ settings.engine.set('device')+ // The picker offers a supported choice, but startup still enters configured-provider fallback.+ assert.equal(settings.engine.get(), 'openai')+ assert.equal(VoiceSettings.provider(), null)+ settings.engine.set('gemini')+ assert.equal(VoiceSettings.provider(), 'gemini')+ assert.equal(settings.engine.get(), 'gemini')+ }+})diff --git a/apps/desktop/src/renderer/views/call/voice.ts b/apps/desktop/src/renderer/views/call/voice.tsindex f998d0a3..95427524 100644--- a/apps/desktop/src/renderer/views/call/voice.ts+++ b/apps/desktop/src/renderer/views/call/voice.ts@@ -7,7 +7,7 @@ import {chosenModel,chosenVoice,dictationEngine,- engine,+ callEngineChoice,isVoiceProvider,language,mode,@@ -36,7 +36,7 @@ export const onDeviceUnavailableReason = () =>export const VoiceSettings = {/** The provider picked in the call settings; null for on-device. */provider: (): VoiceProvider | null => {- const value = engine.get()+ const value = callEngineChoice()return isVoiceProvider(value) ? value : null},/** The provider picked for dictation; null for on-device. */diff --git a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsxindex 9c1180fe..0f9ec657 100644--- a/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx+++ b/apps/desktop/src/renderer/views/settings/VoiceChatSettingsView.tsx@@ -1,6 +1,6 @@import { onDeviceUnavailableReason, voiceSettingsClosed } from '../call/voice'import { useEffect, useMemo, useRef, useState } from 'react'-import type { HostClient } from '../../client/host-client'+import { LoopbackTransport, type HostClient } from '../../client/host-client'import { Button, CardForm, CardSection, ChoicePicker, IconButton, Reveal, Spinner, ValueRow } from '../../components/Controls'import { Icon } from '../../components/Icon'import { ModalHeader, SheetPage } from '../../components/Overlay'@@ -49,7 +49,7 @@ export function VoiceChatSettingsView({ showsHeader = true }: { showsHeader?: bo<ValueRow key="engine" label="Engine"><ChoicePickerselection={engine}- options={[...(window.codync.speech.available || engine === 'device' ? [{ id: 'device', label: 'On device' }] : []), ...voice.VOICE_PROVIDERS.map((p) => ({ id: p, label: voice.voiceInfo[p].name }))]}+ options={voice.engineOptions()}onChange={setEngine}/></ValueRow>,@@ -118,6 +118,7 @@ function ProviderVoiceSettings({ provider, dictationOnly = false }: { provider:/** Speech mode and dictation with this provider both use its speech-to-text model. */const transcribes = dictationOnly || speechMode || dictationEngine === providerconst hasKey = saved === true+ const canEditKey = store.client?.transport instanceof LoopbackTransportconst notConnected = { ok: false, text: `Not connected to ${store.hostName}.` }const loadModels = async (client: HostClient) => {@@ -193,6 +194,7 @@ function ProviderVoiceSettings({ provider, dictationOnly = false }: { provider:else await voice.voiceSession(client, provider, model, chosenVoice)setResult({ ok: true, text: 'Key works' })} else {+ if (!(client.transport instanceof LoopbackTransport)) returnsetSaved(voice.configured(await voice.setVoiceKey(client, provider, typed), provider))setKey('')setReplacing(false)@@ -204,6 +206,7 @@ function ProviderVoiceSettings({ provider, dictationOnly = false }: { provider:const remove = () =>run(async (client) => {+ if (!(client.transport instanceof LoopbackTransport)) returnsetSaved(voice.configured(await voice.setVoiceKey(client, provider, ''), provider))setResult(null)})@@ -233,11 +236,18 @@ function ProviderVoiceSettings({ provider, dictationOnly = false }: { provider:) : (<><IconButton title="Test key" icon="checkmark.seal" onClick={test} />- <IconButton title="Replace key" icon="pencil" onClick={() => { setReplacing(true); setResult(null) }} />- <IconButton title="Remove key" icon="trash" onClick={remove} />+ {canEditKey ? <>+ <IconButton title="Replace key" icon="pencil" onClick={() => { setReplacing(true); setResult(null) }} />+ <IconButton title="Remove key" icon="trash" onClick={remove} />+ </> : null}</>)}</div>+ ) : !canEditKey ? (+ <VStack gap={4} className="settings-row">+ <Text>No {info.name} key on {store.hostName}</Text>+ <Text size="footnote" tone="secondary">Add it in Codync on {store.hostName}: Settings → Voice chat, or connect to that computer over SSH.</Text>+ </VStack>) : (// Paste a key; the computer checks it with the provider before keeping it.<VStack gap={10}>diff --git a/apps/desktop/src/renderer/views/settings/voice-settings.ts b/apps/desktop/src/renderer/views/settings/voice-settings.tsindex ad9a57bd..f424ac00 100644--- a/apps/desktop/src/renderer/views/settings/voice-settings.ts+++ b/apps/desktop/src/renderer/views/settings/voice-settings.ts@@ -1,3 +1,4 @@+import { voiceEngine, voiceEngineIds } from '../../../shared/voice-engine'import type { HostClient } from '../../client/host-client'import { pref, type Pref } from '../../lib/prefs'@@ -54,9 +55,20 @@ export const isVoiceProvider = (s: string): s is VoiceProvider => s === 'openai'export const configured = (s: VoiceStatus, p: VoiceProvider) => s.providers.some((x) => x.provider === p && x.configured)/** `device` (on-device speech) or a provider. */-export const engine = pref('callEngine', 'device')+function enginePref(stored: Pref<string>): Pref<string> {+ return { ...stored, get: () => voiceEngine(stored.get(), window.codync.platform) }+}++export const engineOptions = () => voiceEngineIds(window.codync.platform).map((id) => ({+ id, label: isVoiceProvider(id) ? voiceInfo[id].name : 'On device',+}))++const storedCallEngine = pref('callEngine', 'device')+/** Keep an old/default device choice available to call startup's configured-provider fallback. */+export const callEngineChoice = storedCallEngine.get+export const engine = enginePref(storedCallEngine)/** The same choice for dictation into the message box, picked beside its mic. */-export const dictationEngine = pref('dictationEngine', 'device')+export const dictationEngine = enginePref(pref('dictationEngine', 'device'))/** On-device reading speed (AVSpeechUtterance's scale: 0.5 is normal). */export const DEFAULT_RATE = 0.5export const rate = pref('callRate', DEFAULT_RATE)diff --git a/apps/desktop/src/renderer/views/thread/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsxindex e8f75692..728c6a78 100644--- a/apps/desktop/src/renderer/views/thread/Composer.tsx+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx@@ -6,7 +6,8 @@ import { BotAvatar } from '../../components/Avatar'import { Icon } from '../../components/Icon'import { IconButton } from '../../components/Controls'import { RecordingPill } from '../../components/RecordingPill'-import { usePresence } from '../../components/Overlay'+import { Sheet, usePresence } from '../../components/Overlay'+import { VoiceChatSettingsView } from '../settings/VoiceChatSettingsView'import { HStack, VStack } from '../../components/Stack'import { Text } from '../../components/Text'import { useModel } from '../../lib/observable'@@ -59,7 +60,8 @@ function DestinationComposer({ botId, reply, about, cancelReply, onCall, onInterconst draft = useSyncExternalStore(drafts.subscribe, () => drafts.get(draftKey))const setDraft = (text: string) => drafts.set(draftKey, text)const [files, setFiles] = useState<OutgoingFile[]>([])- const dictation = useDictation((change) => drafts.set(draftKey, change(drafts.get(draftKey))))+ const [voiceSettings, setVoiceSettings] = useState(false)+ const dictation = useDictation((change) => drafts.set(draftKey, change(drafts.get(draftKey))), () => setVoiceSettings(true))const field = useRef<HTMLTextAreaElement>(null)const measure = useRef<HTMLDivElement>(null)const composing = useRef(false)@@ -329,6 +331,9 @@ function DestinationComposer({ botId, reply, about, cancelReply, onCall, onInter</div></div></div>+ <Sheet open={voiceSettings} onClose={() => setVoiceSettings(false)}>+ <VoiceChatSettingsView />+ </Sheet></VStack>)}diff --git a/apps/desktop/src/renderer/views/thread/DictationEngineMenu.tsx b/apps/desktop/src/renderer/views/thread/DictationEngineMenu.tsxindex 8819c4ed..1b1388ec 100644--- a/apps/desktop/src/renderer/views/thread/DictationEngineMenu.tsx+++ b/apps/desktop/src/renderer/views/thread/DictationEngineMenu.tsx@@ -1,9 +1,7 @@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 }))]+import { dictationEngine, engineOptions } from '../settings/voice-settings'/** Beside the mic, in its capsule: which speech dictation uses, on-device or a provider on the user's own key. */export function DictationEngineMenu() {@@ -12,7 +10,7 @@ export function DictationEngineMenu() {<DropdownMenuclassName="press composer-engine"title="Dictation engine"- items={() => ENGINES.map((e) => ({ title: e.title, selected: e.id === engine, action: () => setEngine(e.id) }))}+ items={() => engineOptions().map((e) => ({ title: e.label, 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/dictation-platform.ts b/apps/desktop/src/renderer/views/thread/dictation-platform.tsindex 1c0e4609..fd2bf122 100644--- a/apps/desktop/src/renderer/views/thread/dictation-platform.ts+++ b/apps/desktop/src/renderer/views/thread/dictation-platform.ts@@ -2,7 +2,7 @@ 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 { countVoiceUsage, micPCM16k, onDeviceUnavailableReason, transcribeOnHost, VoiceSettings, wav } from '../call/voice'import { configured, voiceStatus } from '../settings/voice-settings'import { Dictation, type DictationPlatform } from './dictation'@@ -10,7 +10,7 @@ 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 {+export function dictationPlatform(host: (() => Promise<HostClient>) | null = null, report: (message: string) => void = () => {}, configureKey: () => void = () => {}): DictationPlatform {const client = async () => {if (!host) throw new Error('Dictating with a provider needs the chat window.')return host()@@ -22,10 +22,9 @@ export function dictationPlatform(host: (() => Promise<HostClient>) | null = nullanguage: () => 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.`)- }+ return configured(await voiceStatus(await client()), provider)},+ configureKey,microphone: micPCM16k,transcribe: async (provider, piece) => transcribeOnHost(await client(), provider, VoiceSettings.transcribeModel(provider), wav([piece])),count: countVoiceUsage,@@ -34,12 +33,12 @@ export function dictationPlatform(host: (() => Promise<HostClient>) | null = nul}/** 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) {+export function useDictation(editDraft: (change: (box: string) => string) => void, openSettings: () => void) {const store = useStoreRef()const edit = useRef(editDraft)edit.current = editDraftconst [dictation] = useState(- () => new Dictation((change) => edit.current(change), dictationPlatform(() => store.ready(), (message) => store.setError(message))),+ () => new Dictation((change) => edit.current(change), dictationPlatform(() => store.ready(), (message) => store.setError(message), openSettings)),)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.tsindex 28ede72e..d68693a8 100644--- a/apps/desktop/src/renderer/views/thread/dictation.test.ts+++ b/apps/desktop/src/renderer/views/thread/dictation.test.ts@@ -23,7 +23,8 @@ function setup(over: Partial<DictationPlatform> = {}) {host: true,language: () => null,provider: () => null,- checkKey: async () => {},+ checkKey: async () => true,+ configureKey: (provider) => void log.push(`configure ${provider}`),microphone: async (out) => {feed = outlog.push('mic.open')@@ -97,11 +98,12 @@ test('without on-device speech or a provider, the mic says what to pick', () =>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.')) })+test('a provider without a key opens settings without an error or microphone', async () => {+ const s = setup({ provider: () => 'openai', checkKey: async () => false })s.dictation.start(s.box())await settle()- assert.equal(s.dictation.error, 'Add your OpenAI key.')+ assert.equal(s.dictation.error, null)+ assert.deepEqual(s.log, ['configure openai'])assert.ok(!s.log.includes('mic.open'))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.tsindex 4c6da59d..91580038 100644--- a/apps/desktop/src/renderer/views/thread/dictation.ts+++ b/apps/desktop/src/renderer/views/thread/dictation.ts@@ -23,8 +23,9 @@ export interface DictationPlatform {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>+ /** Whether the host holds the provider key. Network failures still reject. */+ checkKey(provider: VoiceProvider): Promise<boolean>+ configureKey(provider: VoiceProvider): 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. */@@ -162,8 +163,13 @@ export class Dictation extends Observable {*/private async record(recording: Recording, generation: number) {try {- await this.platform.checkKey(recording.provider)+ const hasKey = await this.platform.checkKey(recording.provider)if (generation !== this.generation) return+ if (!hasKey) {+ this.end()+ this.platform.configureKey(recording.provider)+ return+ }const stop = await this.platform.microphone((pcm, level) => {recording.pcm.push(pcm)this.level = leveldiff --git a/apps/desktop/src/shared/account-sign-in.test.ts b/apps/desktop/src/shared/account-sign-in.test.tsnew file mode 100644index 00000000..5a7a937c--- /dev/null+++ b/apps/desktop/src/shared/account-sign-in.test.ts@@ -0,0 +1,85 @@+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import path from 'node:path'+import { test } from 'node:test'+import { AuthenticationEnded, BrowserAuthentication } from '../main/browser-authentication.ts'+import { loadMainModule } from './test-support/main-module.ts'++const opened: string[] = []+const platform = { open: async (url: string) => { opened.push(url) } }+const browser = new BrowserAuthentication((url) => platform.open(url))+const handleURL = (url: string) => browser.handleURL(url)+const { AccountService } = loadMainModule<typeof import('../main/account.ts')>('account', {+ 'node:events': { EventEmitter }, 'node:fs': { promises: {} }, 'node:path': path,+ electron: { app: { getVersion: () => '2.33.1' }, ipcMain: {}, safeStorage: {} },+ './auth': { authenticate: browser.authenticate.bind(browser), AuthenticationEnded },+ './environment': {+ identity: { appId: 'test.codync', scheme: 'codync', environment: 'dev' },+ buildConfig: { clerkPublishableKey: `pk_test_${Buffer.from('clerk.example.test$').toString('base64')}`, cloudURL: 'https://cloud.example.test' },+ },+}, { URL, URLSearchParams, Buffer, process: { env: {}, platform: 'win32' }, fetch: (...args: Parameters<typeof fetch>) => globalThis.fetch(...args) })+const until = async (check: () => boolean) => {+ for (let i = 0; i < 50 && !check(); i++) await new Promise<void>((done) => setImmediate(done))+ assert.ok(check())+}+const response = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status })++test('closing the external browser leaves the app usable; retry and a stale nonce do not consume the current sign-in', async () => {+ opened.length = 0+ const account = new AccountService()+ const user = () => account.state.user+ let creates = 0+ const verified: string[] = []+ globalThis.fetch = async (input) => {+ const url = new URL(String(input))+ if (url.pathname.endsWith('/prepare_first_factor')) return response({ response: { id: `login-${creates}`, first_factor_verification: { external_verification_redirect_url: `https://browser.example.test/${creates}` } } })+ if (url.pathname.endsWith('/sign_ins')) return response({ response: { id: `login-${++creates}` } })+ if (url.pathname.includes('/sign_ins/')) {+ verified.push(url.pathname)+ if (url.searchParams.get('rotating_token_nonce') === 'incomplete') return response({ response: { id: `login-${creates}`, status: 'needs_identifier' }, client: { last_active_session_id: 'wrong-session', sessions: [{ id: 'wrong-session', status: 'active', user: { id: 'wrong-user' } }] } })+ if (url.searchParams.get('rotating_token_nonce') === 'stale') return response({ errors: [{ code: 'signed_out', message: 'Signed out' }] }, 401)+ return response({ response: { id: `login-${creates}`, status: 'complete' } })+ }+ return response({ response: { last_active_session_id: 'session', sessions: [{ id: 'session', status: 'active', user: { id: 'user' } }] } })+ }+ const first = account.signIn('apple')+ await until(() => opened.length === 1)+ assert.equal(account.state.busy, false)+ assert.equal(account.state.error, null)+ const second = account.signIn('google')+ await until(() => opened.length === 2)+ assert.equal(await first, 'cancelled')+ handleURL('test.codync://callback?rotating_token_nonce=stale')+ await until(() => verified.length === 1 && !account.state.busy)+ assert.equal(user(), null)+ assert.equal(account.state.error, null)+ handleURL('test.codync://callback?rotating_token_nonce=incomplete')+ await until(() => verified.length === 2 && !account.state.busy)+ assert.equal(user(), null)+ handleURL('test.codync://callback?rotating_token_nonce=current')+ assert.equal(await second, null)+ assert.equal(user()?.userId, 'user')+ assert.equal(account.state.busy, false)+ assert.deepEqual(verified, Array(3).fill('/v1/client/sign_ins/login-2'))+})++test('browser launch and callback network failures reset loading and allow a retry', async () => {+ const account = new AccountService()+ globalThis.fetch = async (input) => {+ const url = new URL(String(input))+ if (url.pathname.endsWith('/sign_ins')) return response({ response: { id: 'login' } })+ if (url.pathname.endsWith('/prepare_first_factor')) return response({ response: { id: 'login', first_factor_verification: { external_verification_redirect_url: 'https://browser.example.test' } } })+ throw new Error('Network unavailable')+ }+ platform.open = async () => { throw new Error('No browser') }+ assert.equal(await account.signIn('google'), 'error')+ assert.equal(account.state.busy, false)+ platform.open = async (url) => { opened.push(url) }+ opened.length = 0+ const retry = account.signIn('apple')+ await until(() => opened.length === 1)+ handleURL('test.codync://callback?rotating_token_nonce=current')+ assert.equal(await retry, 'error')+ assert.equal(account.state.busy, false)+ assert.match(account.state.error ?? '', /Couldn't sign in/)+})diff --git a/apps/desktop/src/shared/browser-authentication.test.ts b/apps/desktop/src/shared/browser-authentication.test.tsnew file mode 100644index 00000000..d6eb8aa9--- /dev/null+++ b/apps/desktop/src/shared/browser-authentication.test.ts@@ -0,0 +1,49 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { AuthenticationEnded, BrowserAuthentication } from '../main/browser-authentication.ts'++const turn = () => new Promise<void>((resolve) => setImmediate(resolve))++test('a stale same-scheme callback leaves the current browser login waiting', async () => {+ const browser = new BrowserAuthentication(async () => {})+ const first = browser.authenticate('https://example.test/first', 'codync')+ const firstEnded = assert.rejects(first, (e: unknown) => e instanceof AuthenticationEnded && e.reason === 'cancelled')+ let resolved = false+ const second = browser.authenticate('https://example.test/second', 'codync', async (url) => url.endsWith('current'))+ void second.then(() => { resolved = true })+ await firstEnded+ browser.handleURL('codync://stale')+ await turn()+ assert.equal(resolved, false)+ browser.handleURL('other://current')+ await turn()+ assert.equal(resolved, false)+ browser.handleURL('codync://current')+ assert.equal(await second, 'codync://current')+})++test('browser-open and callback-validation failures end their waits', async () => {+ const cannotOpen = new BrowserAuthentication(async () => { throw new Error('No browser') })+ await assert.rejects(cannotOpen.authenticate('https://example.test', 'codync'), /No browser/)+ const browser = new BrowserAuthentication(async () => {})+ const result = browser.authenticate('https://example.test', 'codync', async () => { throw new Error('Offline') })+ browser.handleURL('codync://callback')+ await assert.rejects(result, /Offline/)+})++test('replacing a wait clears its timeout and a later open failure cannot reject the replacement', async () => {+ let failOpen: (error: Error) => void = () => {}+ let calls = 0+ const browser = new BrowserAuthentication(async () => {+ if (++calls === 1) await new Promise<void>((_, reject) => { failOpen = reject })+ }, 15)+ const first = browser.authenticate('https://example.test/old', 'codync')+ const rejected = assert.rejects(first, AuthenticationEnded)+ const second = browser.authenticate('https://example.test/new', 'codync')+ await rejected+ failOpen(new Error('Old browser failed'))+ browser.handleURL('codync://callback')+ assert.equal(await second, 'codync://callback')+ const third = browser.authenticate('https://example.test/timeout', 'codync')+ await assert.rejects(third, (e: unknown) => e instanceof AuthenticationEnded && e.reason === 'timeout')+})diff --git a/apps/desktop/src/shared/voice-engine.test.ts b/apps/desktop/src/shared/voice-engine.test.tsnew file mode 100644index 00000000..30c167e9--- /dev/null+++ b/apps/desktop/src/shared/voice-engine.test.ts@@ -0,0 +1,16 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { voiceEngine, voiceEngineIds } from './voice-engine.ts'++test('Windows and Linux never offer or restore the unsupported on-device engine', () => {+ for (const platform of ['win32', 'linux']) {+ assert.deepEqual(voiceEngineIds(platform), ['openai', 'gemini'])+ assert.equal(voiceEngine('device', platform), 'openai')+ assert.equal(voiceEngine('gemini', platform), 'gemini')+ }+})++test('macOS keeps on-device dictation and provider choices', () => {+ assert.deepEqual(voiceEngineIds('darwin'), ['device', 'openai', 'gemini'])+ assert.equal(voiceEngine('device', 'darwin'), 'device')+})diff --git a/apps/desktop/src/shared/voice-engine.ts b/apps/desktop/src/shared/voice-engine.tsnew file mode 100644index 00000000..1216a789--- /dev/null+++ b/apps/desktop/src/shared/voice-engine.ts@@ -0,0 +1,8 @@+/** Desktop on-device recognition is supplied by the macOS speech helper. */+export function voiceEngine(value: string, platform: string): string {+ return platform !== 'darwin' && value === 'device' ? 'openai' : value+}++export function voiceEngineIds(platform: string): string[] {+ return [...(platform === 'darwin' ? ['device'] : []), 'openai', 'gemini']+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swiftindex 9172df52..a27197af 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift@@ -250,6 +250,7 @@ struct Composer: View {}}.animation(Motion.reduced(Motion.morph, reduceMotion), value: dictation.listening || dictation.transcribing)+ .codyncSheet(isPresented: $dictation.needsKey) { VoiceChatSettingsView() }.codyncDialog("Couldn't dictate", isPresented: Binding(get: { dictation.failure != nil }, set: { if !$0 { dictation.failure = nil } }),message: dictation.failure, cancel: "OK") { [] }}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swiftindex cee808b7..284da4d7 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Dictation.swift@@ -47,8 +47,9 @@ final class Dictation {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.+ /// Why the last dictation ended early (no network or microphone access), until the next.var failure: String?+ var needsKey = false@ObservationIgnored private lazy var engine = AVAudioEngine()@ObservationIgnored private var request: SFSpeechAudioBufferRecognitionRequest?@ObservationIgnored private var task: SFSpeechRecognitionTask?@@ -89,6 +90,7 @@ final class Dictation {func start(after draft: String, model: BotStore, edit: @escaping ((String) -> String) -> Void) async {guard !listening, !transcribing else { return }failure = nil+ needsKey = falsegeneration += 1before = draftif let provider = service.picked() {@@ -170,7 +172,7 @@ final class Dictation {let hasKey = try await service.hasKey(provider, model)guard generation == self.generation else { return }guard hasKey else {- failure = "Add your \(provider.name) key in Voice chat settings to dictate with it."+ needsKey = truereturn}} catch {diff --git a/apps/ios/Kit/Tests/CodyncUITests/DictationTests.swift b/apps/ios/Kit/Tests/CodyncUITests/DictationTests.swiftindex 4e828c2c..7d7ffc39 100644--- a/apps/ios/Kit/Tests/CodyncUITests/DictationTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/DictationTests.swift@@ -165,15 +165,15 @@ private extension Dictation {}}-/// Without the provider's key on the computer it says where to add one, and never opens the microphone.-@MainActor @Test func dictatingWithoutAKeySaysWhereToAddOne() async {+/// Without the provider's key on the computer it opens settings, and never opens the microphone.+@MainActor @Test func dictatingWithoutAKeyRequestsSettings() async {let key = Pending<Bool>(), mic = Mic()await dictating(hasKey: { try await key.call() }, mic: mic) { dictation, store inlet starting = Task { await dictation.start(after: "", model: store) { _ in } }#expect(await key.asked())key.answer(false)await starting.value- #expect(dictation.failure == "Add your OpenAI key in Voice chat settings to dictate with it.")+ #expect(dictation.failure == nil && dictation.needsKey)#expect(!dictation.listening && mic.heard == nil)}}diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex e8a8f5f0..58386679 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -6,6 +6,14 @@ any left). tools/asc-submit.py reads the released version's section;a version without one gets a generic "Bug fixes and improvements" line. Delete old sections.-->+## 2.33.2++### zh-Hant+- 語音輸入尚未設定 API key 時,會直接開啟語音設定。++### en-US+- Dictation opens voice settings when your provider API key is missing.+## 2.33.1### zh-Hantdiff --git a/docs/features/voice-call.md b/docs/features/voice-call.mdindex 40cc2a7c..24ba0e59 100644--- a/docs/features/voice-call.md+++ b/docs/features/voice-call.md@@ -63,7 +63,7 @@ was recognized so far. The desktop island's message field has the same mic and pA `chevron.up` beside the composer's mic picks dictation's engine, kept on the device apart from thecall engine (`dictationEngine`): **On device** (the above), or **OpenAI** / **Gemini** on the user'sown 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; the pill (and its time) appears only once+opens Voice chat settings before anything is recorded), then records; the pill (and its time) appears only oncethe microphone is open, so nothing said before it is lost; nothing is typed while recording. Thepill'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@@ -78,8 +78,7 @@ 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+ show the mic too, for a provider; **On device** is hidden and old dictation selections use OpenAI. An unpackaged `npm run dev` can't use the helper: macOS stops it because the devElectron has no speech usage description, so test it in a packaged build (`dist:mac:dev`), likecalls.- Desktop: the speech helper serves one window at a time. When another window starts it (the@@ -171,8 +170,8 @@ at the end, cloud minutes counted up to the switch, mute kept, a fallback noticeto On device tries the picked cloud engine again the same way. Desktop and Android check whenever a voicesettings view closes (desktop: the gear, Settings; Android: the gear, the computer's card in Computermanagement); on the iPhone only the gear is open during a call.-Where on-device speech is missing (desktop on Linux or Windows), the provider standing in for On device keeps-running while On device stays picked.+On Windows and Linux, an old/default On device call preference first selects a configured provider+and remembers it. The picker offers only OpenAI and Gemini.| Engine | Needs | Transport | Code || --- | --- | --- | --- |@@ -437,3 +436,7 @@ simulated: on a physical iPhone, check both engines with a real key (talk over aare you doing?", approve by voice, and turn Wi-Fi off for a moment mid-call: the bar shows Reconnecting, comes backto Listening and still says the replies; with no network at all, after three tries, the call falls back to on-devicevoice).++### Missing dictation keys++Desktop and iPhone dictation open Voice chat settings when the selected provider has no key, before opening the microphone. Connection failures still show an error. Keys can be edited through local or SSH-loopback connections; paired remote connections show instructions to add the key on that computer. Windows and Linux hide On device in both engine pickers; old dictation preferences use OpenAI, while calls keep their configured-provider fallback. macOS keeps its on-device option. Android has voice calls but no composer dictation engine picker; the terminal UI has no microphone input, so this dictation change does not apply to either.diff --git a/web/content/docs/voice.mdx b/web/content/docs/voice.mdxindex c598f693..dd473b12 100644--- a/web/content/docs/voice.mdx+++ b/web/content/docs/voice.mdx@@ -107,13 +107,13 @@ While it listens, the microphone becomes a recording pill with a stop button, thThe small arrow beside the microphone (**Dictation engine**) chooses **On device**, **OpenAI** or **Gemini**. It's kept on this device, separate from the call engine.- **On device:** words appear as they're recognized, in the language set for calls. On the iPhone, stop keeps what was recognized so far. In the desktop app, dictation keeps listening through pauses until you press stop.-- **OpenAI or Gemini:** Codync first checks that the computer has the provider's key (if not, you get an error before anything is recorded). The pill appears once the microphone is open, so nothing you say is lost. Nothing is typed while you record. When you press stop, the pill shows "Transcribing…" and the text lands in the box when it arrives. It uses the **Speech to text** model from Voice chat settings, and the recording counts toward that provider's minutes this month.+- **OpenAI or Gemini:** Codync first checks that the computer has the provider's key (if not, voice settings open so you can configure it before anything is recorded). The pill appears once the microphone is open, so nothing you say is lost. Nothing is typed while you record. When you press stop, the pill shows "Transcribing…" and the text lands in the box when it arrives. It uses the **Speech to text** model from Voice chat settings, and the recording counts toward that provider's minutes this month.If dictation uses a provider that your calls don't, Voice chat settings show a separate section for it ("For dictation in the message box.") with its key status and speech-to-text model.Sending a message, starting a call or switching chats drops a dictation that is still recording or transcribing. A call takes the microphone.-In the desktop app on Windows and Linux, the microphone works with OpenAI or Gemini; with On device picked, it tells you on-device speech isn't available there.+In the desktop app on Windows and Linux, the microphone works with OpenAI or Gemini; On device is hidden, and an earlier On device selection uses OpenAI instead.### Voice input shortcut (Mac)