diff --git a/.github/release-notes/v2.4.2.md b/.github/release-notes/v2.4.2.md new file mode 100644 index 00000000..332e4ad7 --- /dev/null +++ b/.github/release-notes/v2.4.2.md @@ -0,0 +1,7 @@ +# V2.4.2 - Watcher + +Dictation keeps the message in your draft until the final transcript is ready. Pressing Send or queuing a follow-up while recording no longer sends a partial message. Releasing push-to-talk during microphone setup cancels the recording, and switching windows won't send your words to another draft. + +You can now collapse a question to read the conversation behind it. Expand it to continue where you left off, including any answer you were typing. + +The CI watcher now recognizes “Hey, set up a watcher as soon as the CI passes” even when you also ask to merge or release. If one check fails while others are still running, Fate posts the failure in the original chat without waiting for every check or calling a model. A busy chat gets the update when it’s idle. The watcher does not merge or publish anything. diff --git a/.github/workflows/cross-platform.yml b/.github/workflows/cross-platform.yml index 126c37d5..c1e1ab64 100644 --- a/.github/workflows/cross-platform.yml +++ b/.github/workflows/cross-platform.yml @@ -314,16 +314,29 @@ jobs: echo "PKG smoke attempt $attempt failed; retrying in 5 seconds." sleep 5 done + - name: Verify packaged spoken transcript + if: runner.os == 'Linux' && github.event_name != 'pull_request' + shell: bash + env: + PI_DESKTOP_SPEECH_STREAM_SMOKE: '1' + INSTALLED_SMOKE_TIMEOUT_MS: '600000' + run: | + version=$(node -p "require('./package.json').version") + appimage="artifacts/Fate-UI-$version-Linux-${{ matrix.arch }}.AppImage" + chmod +x "$appimage" + xvfb-run -a node scripts/smoke-executable.mjs "$appimage" --appimage-extract-and-run - name: Run, install, and smoke Linux installers if: runner.os == 'Linux' shell: bash run: | set -euo pipefail version=$(node -p "require('./package.json').version") - appimage="artifacts/Fate-UI-$version-Linux-${{ matrix.arch }}.AppImage" deb="artifacts/Fate-UI-$version-Linux-${{ matrix.arch }}.deb" - chmod +x "$appimage" - xvfb-run -a node scripts/smoke-executable.mjs "$appimage" --appimage-extract-and-run + if [ "$GITHUB_EVENT_NAME" = pull_request ]; then + appimage="artifacts/Fate-UI-$version-Linux-${{ matrix.arch }}.AppImage" + chmod +x "$appimage" + xvfb-run -a node scripts/smoke-executable.mjs "$appimage" --appimage-extract-and-run + fi package_name=$(dpkg-deb -f "$deb" Package) trap 'sudo apt-get purge -y "$package_name" >/dev/null 2>&1 || true' EXIT @@ -497,6 +510,8 @@ jobs: test "$run_conclusion" = success test "$run_workflow" = .github/workflows/cross-platform.yml test "$run_head" = "$tag_head" + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$PROMOTE_RUN_ID/jobs?per_page=100" | + jq -e 'any(.jobs[]; .name == "Linux x64 / Node 22" and .conclusion == "success" and any(.steps[]; .name == "Verify packaged spoken transcript" and .conclusion == "success"))' git merge-base --is-ancestor "$tag_head" origin/main git checkout --detach "$PROMOTE_TAG" node scripts/release-artifacts.mjs validate-tag --tag "$PROMOTE_TAG" diff --git a/.gitignore b/.gitignore index 7dd11597..65baf944 100644 --- a/.gitignore +++ b/.gitignore @@ -57,6 +57,7 @@ coverage/ .parallax/ .impeccable/ /plans/ +/advisor-plans/ # Local handoff archives are inputs, not source or release artifacts. /pi-fategui-M5-updated-plans.zip /fate-server-*.tar.gz diff --git a/PRODVER b/PRODVER index 58073ef8..acdc3f1b 100644 --- a/PRODVER +++ b/PRODVER @@ -1 +1 @@ -2.4.1 \ No newline at end of file +2.4.2 \ No newline at end of file diff --git a/docs/development.md b/docs/development.md index b0e6c4e6..8134d68c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -56,7 +56,7 @@ The cross-platform GitHub Actions package matrix runs for pull requests, pushes - Native hosted runners build, install or mount, and smoke-test Windows x64, macOS Apple Silicon and Intel, and Linux x64 packages: Windows NSIS, macOS DMG and PKG, Linux AppImage and DEB. - The version in `package.json` and `PRODVER` must match. The release tag is `v`, and `node scripts/release-artifacts.mjs metadata --field display-version` combines that version with the optional `package.json.releaseName` for the display title. -The current source version is `2.4.1` (Watcher). +The current source version is `2.4.2` (Watcher). 1. Merge the version bump and `.github/release-notes/v.md` into `main`. 2. Manually run **Cross-platform installers** on `main` with the promotion inputs empty. Confirm the run used the intended commit, all four native jobs passed, and `verified-release-installers` contains seven installers and `SHA256SUMS`. This artifact is retained for 14 days. This run does not publish anything. diff --git a/docs/features.md b/docs/features.md index 27331240..013795d9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -129,7 +129,7 @@ Attach saved sessions as read-only context, or message a saved session without s ## Native media (optional) -- **Voice transcription** — local, settings-controlled models with bounded and verified downloads. +- **Voice transcription** — audio is decoded locally and the result stays in the draft. Send and queue actions are unavailable from microphone preparation until the transcript is ready; stopping dictation never sends a message. Push-to-talk is bound to one window until release. A recording stops after three minutes. - **Ambient audio** — disabled by default; resolved through a bundled, pinned `yt-dlp` runtime and streamed without saving media into the project. - **Generated images** — select an image model independently of the active chat model. Fate UI supports authenticated OpenAI, Google, OpenRouter, and ChatGPT OAuth routes, plus compatible custom Pi providers. Custom endpoints require HTTPS except on loopback addresses. Generated raster output is validated, rendered inline, and stored under `~/.pi/agent/generated-images//`. diff --git a/docs/mcp.md b/docs/mcp.md index 8e2ab135..37779302 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -44,6 +44,8 @@ A Monitor watch uses a separate, one-shot connection to a named, enabled **local ## Watch CI from chat -In a trusted desktop project, ask: “Watch this PR’s CI and tell me when it finishes.” Fate resolves the branch’s pull request and pins its current commit. You can also include a GitHub pull request or Actions run link in the request. An authenticated local `gh` CLI with access to the repository is required. No workflow is started or modified. +In a trusted desktop project, ask: “Watch this PR’s CI and tell me when it finishes.” Fate resolves the branch’s pull request and pins its current commit. You can also include a GitHub pull request or Actions run link in the request. An authenticated local `gh` CLI with access to the repository is required. -The turn ends normally. **Run → Monitor → Watches** shows the status and lets you stop the watch. When checks finish, Fate posts a text-only update in the original chat, without tools or chat history. Switching projects does not stop the watch. Watches expire after one hour and do not resume after quitting. +You can also say “Hey, set up a watcher as soon as the CI passes.” The watch reports the result, including failures. Asking for a merge or a release in the same message does not schedule either action. + +The turn ends normally. **Run → Monitor → Watches** shows the status and lets you stop the watch. Fate reports the first confirmed failure for the pinned commit, even if other checks are still running. A success report waits for the complete set of checks. Chat watches post directly in the original chat without calling a model; if the chat is busy, the update waits until it is idle. Switching projects does not stop the watch. Watches expire after one hour and do not resume after quitting. diff --git a/package.json b/package.json index 7706449a..535e71e2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pi-fategui", - "version": "2.4.1", + "version": "2.4.2", "releaseName": "Watcher", "description": "A local-first desktop interface for the Pi coding agent", "type": "module", diff --git a/scripts/smoke-executable.mjs b/scripts/smoke-executable.mjs index 7c996244..310a65c4 100644 --- a/scripts/smoke-executable.mjs +++ b/scripts/smoke-executable.mjs @@ -15,9 +15,10 @@ const smokeArguments = process.platform === 'darwin' && process.arch === 'x64' & ? ['--disable-gpu', ...applicationArguments] : applicationArguments; +const { TRANSCRIBE_LIBRARY: _hostSpeechLibrary, ...smokeEnv } = process.env; const child = spawn(executable, smokeArguments, { cwd: path.resolve(import.meta.dirname, '..'), - env: { ...process.env, FATE_NEW_INSTANCE: '1', PI_DESKTOP_SMOKE: '1', PI_OFFLINE: '1' }, + env: { ...smokeEnv, FATE_NEW_INSTANCE: '1', PI_DESKTOP_SMOKE: '1', PI_OFFLINE: '1' }, stdio: ['ignore', 'pipe', 'pipe'], }); const requiredMarkers = ['PI_DESKTOP_RENDERER_OK', 'PI_DESKTOP_SPEECH_OK', 'PI_DESKTOP_YT_DLP_OK', 'PI_DESKTOP_THEMES_OK', 'PI_DESKTOP_TERMINAL_OK', 'PI_DESKTOP_SMOKE_OK']; diff --git a/scripts/smoke-packaged.mjs b/scripts/smoke-packaged.mjs index f01b4f87..70509091 100644 --- a/scripts/smoke-packaged.mjs +++ b/scripts/smoke-packaged.mjs @@ -77,9 +77,10 @@ const timeoutMs = Number(process.env.PACKAGED_SMOKE_TIMEOUT_MS ?? '120000'); const applicationArguments = process.platform === 'darwin' && process.arch === 'x64' && process.env.PI_DESKTOP_SPEECH_STREAM_SMOKE === '1' ? ['--disable-gpu'] : []; +const { TRANSCRIBE_LIBRARY: _hostSpeechLibrary, ...smokeEnv } = process.env; const child = spawn(executable, applicationArguments, { cwd: root, - env: { ...process.env, FATE_NEW_INSTANCE: '1', PI_DESKTOP_SMOKE: '1', PI_OFFLINE: '1' }, + env: { ...smokeEnv, FATE_NEW_INSTANCE: '1', PI_DESKTOP_SMOKE: '1', PI_OFFLINE: '1' }, stdio: ['ignore', 'pipe', 'pipe'], }); const requiredMarkers = ['PI_DESKTOP_RENDERER_OK', 'PI_DESKTOP_SPEECH_OK', 'PI_DESKTOP_YT_DLP_OK', 'PI_DESKTOP_THEMES_OK', 'PI_DESKTOP_TERMINAL_OK', 'PI_DESKTOP_SMOKE_OK']; diff --git a/scripts/verify-speech-models.mjs b/scripts/verify-speech-models.mjs index 5aa56d43..829f8bd8 100644 --- a/scripts/verify-speech-models.mjs +++ b/scripts/verify-speech-models.mjs @@ -1,164 +1,82 @@ -/** - * Spike: prove every new catalog model works with the bundled transcribe-cpp - * binding before shipping it. Downloads the exact pinned GGUF, verifies the - * SHA-256, loads it, runs batch transcription over synthetic speech-shaped PCM, - * and for streaming models exercises the live path (default slot and the - * Parakeet buffered menu) with language handling. - * - * Usage: node scripts/verify-speech-models.mjs [modelId ...] - * Default: all three new models. Files go to a temp dir and are removed. - */ import { createHash } from 'node:crypto'; -import { createWriteStream } from 'node:fs'; -import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises'; -import os from 'node:os'; +import { createReadStream, createWriteStream } from 'node:fs'; +import { mkdir, rm, stat } from 'node:fs/promises'; import path from 'node:path'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; +import { TranscribeModel, getAvailableBackends } from 'transcribe-cpp'; +import { resolveModelLanguage, speechModel, speechModels } from '../src/main/speech/speechModels.ts'; +import { assertSpokenTranscript, readSpokenFixture } from '../src/main/bootstrap/spokenSmokeFixture.ts'; -// Self-contained definitions (mirrors src/main/speech/speechModels.ts) so this -// runs under plain node without a TS loader. -const definitions = [ - { - id: 'nemotron-stream', - bytes: 559_647_200, - fileName: 'nemotron-3.5-asr-streaming-0.6b-Q5_K_M.gguf', - url: 'https://huggingface.co/handy-computer/nemotron-3.5-asr-streaming-0.6b-gguf/resolve/6d44e540bc31b0de1dbe174a3cea87f53a7f22fb/nemotron-3.5-asr-streaming-0.6b-Q5_K_M.gguf', - sha256: '86429e8c4f7fdcf9b3312269ad1ca6669478ba7805331c4aea7a2e33e9910d65', - streaming: true, - languageMap: { en: 'en-US' }, - }, - { - id: 'parakeet-tdt-v3', - bytes: 548_946_272, - fileName: 'parakeet-tdt-0.6b-v3-Q5_K_M.gguf', - url: 'https://huggingface.co/handy-computer/parakeet-tdt-0.6b-v3-gguf/resolve/85ac09ea12fc4b1112fa76810059364bc6adc9de/parakeet-tdt-0.6b-v3-Q5_K_M.gguf', - sha256: 'cc722e76adc1a629fc0b2535de879d99b8160d07ad4c0215e2ca7d7ea0ae4b8f', - streaming: false, - }, - { - id: 'whisper-turbo', - bytes: 619_628_128, - fileName: 'whisper-large-v3-turbo-Q5_K_M.gguf', - url: 'https://huggingface.co/handy-computer/whisper-large-v3-turbo-gguf/resolve/5eaf945c7978e564bae5b28a5b1639dd93c2bfb1/whisper-large-v3-turbo-Q5_K_M.gguf', - sha256: '977b5db4e004349dffd1ab9caa10ba5aaba3fc3edd3ba72cadb84328a3203e36', - streaming: false, - }, -]; -const speechModels = definitions; -const resolveModelLanguage = (definition, language) => - !language ? undefined : language === 'auto' ? (definition.languageMap ? 'auto' : 'en') : (definition.languageMap?.[language] ?? language); -const newIds = ['nemotron-stream', 'parakeet-tdt-v3', 'whisper-turbo']; -const targets = process.argv.slice(2).length ? process.argv.slice(2) : newIds; - -/** Synthetic "speech": 3 s of tone bursts with gaps — never silent overall. */ -function speechPcm(seconds = 3) { - const samples = 16_000 * seconds; - const pcm = new Float32Array(samples); - for (let i = 0; i < samples; i += 1) { - const t = i / 16_000; - const voiced = (t % 0.8) < 0.6; - pcm[i] = voiced ? 0.4 * Math.sin(2 * Math.PI * 220 * t) + 0.2 * Math.sin(2 * Math.PI * 440 * t) : 0; - } - return pcm; -} - -async function download(url, target, expectedBytes, expectedSha) { - const { createReadStream } = await import('node:fs'); - let attempt = 0; - let have = await stat(target).then((s) => s.size, () => 0); - let hash = createHash('sha256'); - while (have < expectedBytes && attempt < 6) { - attempt += 1; - // A fresh digest per attempt: hash the full on-disk prefix, then the bytes - // this attempt appends. Survives any number of interrupted resumes. - hash = createHash('sha256'); - if (have > 0) { - await pipeline(createReadStream(target), async function* (source) { for await (const chunk of source) { hash.update(chunk); } }); - } - const resume = have > 0; - const response = await fetch(url, resume ? { headers: { Range: `bytes=${have}-` } } : {}); - if (!response.ok || !response.body) throw new Error(`HTTP ${response.status} for ${url}`); - const appending = resume && response.status === 206; - if (!appending && resume) have = 0; // server ignored the range: start over +async function download(definition, target) { + const { bytes, sha256, url } = definition; + let size = await stat(target).then((s) => s.size, () => 0); + for (let attempt = 1; size < bytes && attempt <= 6; attempt++) { try { - await pipeline( - Readable.fromWeb(appending && have > 0 ? response.body : response.body), - async function* (source) { for await (const chunk of source) { hash.update(chunk); yield chunk; } }, - createWriteStream(target, appending ? { flags: 'a' } : {}), - ); + const response = await fetch(url, size ? { headers: { Range: `bytes=${size}-` } } : {}); + if (!response.ok || !response.body) throw new Error(`HTTP ${response.status} for ${url}`); + const append = response.status === 206; + if (append && !response.headers.get('content-range')?.startsWith(`bytes ${size}-`)) throw new Error('Invalid download range'); + await pipeline(Readable.fromWeb(response.body), createWriteStream(target, { flags: append ? 'a' : 'w' })); } catch (error) { - console.error(`\n download interrupted (attempt ${attempt}): ${error.cause?.code ?? error.message}; resuming…`); + if (attempt === 6) throw error; + console.warn(`[${definition.id}] download interrupted: ${error.message}; retrying`); } - const size = await stat(target).then((s) => s.size, () => 0); - if (size <= have && size !== expectedBytes) throw new Error('download made no progress; giving up'); - have = size; + size = await stat(target).then((s) => s.size, () => 0); } - if (have !== expectedBytes) throw new Error(`incomplete download: ${have}/${expectedBytes}`); - if (attempt === 0) { - // File was already complete: hash it now. - await pipeline(createReadStream(target), async function* (source) { for await (const chunk of source) { hash.update(chunk); } }); + const hash = createHash('sha256'); + if (size === bytes) for await (const chunk of createReadStream(target)) hash.update(chunk); + if (size !== bytes || hash.digest('hex') !== sha256) { + await rm(target, { force: true }); + throw new Error(`Size or SHA-256 mismatch for ${definition.fileName}`); } - const digest = hash.digest('hex'); - if (digest !== expectedSha) throw new Error(`sha256 mismatch for ${target}: ${digest} — delete and retry`); } -async function main() { - const { getAvailableBackends, TranscribeModel } = await import('transcribe-cpp'); - // Persistent cache so re-runs skip the ~560 MB downloads. - const tmp = path.join(process.cwd(), 'node_modules', '.cache', 'speech-spike'); - await import('node:fs/promises').then((fs) => fs.mkdir(tmp, { recursive: true })); - let failures = 0; +async function verify(definition, file, pcm) { + const { id } = definition; + const model = await TranscribeModel.load(file, { backend: 'cpu' }); try { - console.log('Backends:', getAvailableBackends().map((b) => `${b.kind}(${b.deviceType})`).join(', ')); - for (const id of targets) { - const definition = speechModels.find((model) => model.id === id); - if (!definition) throw new Error(`unknown model ${id}`); - const file = path.join(tmp, definition.fileName); - process.stdout.write(`[${id}] downloading ${definition.bytes.toLocaleString()} bytes… `); - await download(definition.url, file, definition.bytes, definition.sha256); - console.log('ok'); - - const model = await TranscribeModel.load(file, { backend: 'cpu' }); - console.log(`[${id}] loaded arch=${model.arch} backend=${model.backend} device=${model.device.name}`); - + const auto = resolveModelLanguage(definition, 'auto'); + const english = resolveModelLanguage(definition, 'en'); + const batchSession = model.createSession({ nThreads: 4 }); + try { + const batch = await batchSession.run(pcm, { timestamps: 'none', ...(auto ? { language: auto } : {}) }); + assertSpokenTranscript(batch.text, `${id} batch`); + console.log(`[${id}] batch: ${batch.text.trim()}`); + } finally { + batchSession.dispose(); + } + if (!definition.streaming) return; + for (const language of new Set([auto, english])) { const session = model.createSession({ nThreads: 4 }); - const pcm = speechPcm(3); - const started = performance.now(); - const result = await session.run(pcm, { language: resolveModelLanguage(definition, 'en') ?? 'en', timestamps: 'none' }); - const batchMs = performance.now() - started; - console.log(`[${id}] batch ok in ${Math.round(batchMs)} ms (RTF ${(3_000 / batchMs).toFixed(1)}x) text="${(result.text || '').trim().slice(0, 80)}" lang=${result.language}`); - - if (definition.streaming) { - const streamLanguage = resolveModelLanguage(definition, 'en') ?? 'en'; - // Test exactly what the app sends: the model's configured family menu, - // or the default slot when none is configured. - const variants = [definition.streamFamily]; - for (const variant of variants) { - const label = variant ? variant.kind : 'default-slot'; - try { - const stream = await session.stream({ language: streamLanguage, timestamps: 'none', commitPolicy: 'stable_prefix', ...(variant ? { family: variant } : {}) }); - const chunk = speechPcm(2); - await stream.feed(chunk); - await stream.finalize(); - console.log(`[${id}] stream[${label}] ok lang=${streamLanguage} committed="${(stream.text.committed || '').trim().slice(0, 80)}"`); - stream.reset(); - } catch (error) { - failures += 1; - console.error(`[${id}] stream[${label}] FAILED: ${error.message}`); - } - } - // Language handling: 'auto' pass-through and BCP-47 mapping. - console.log(`[${id}] language en->${resolveModelLanguage(definition, 'en')} auto->${resolveModelLanguage(definition, 'auto')}`); + try { + const stream = await session.stream({ + timestamps: 'none', commitPolicy: 'stable_prefix', + ...(language ? { language } : {}), + ...(definition.streamFamily ? { family: definition.streamFamily } : {}), + }); + for (let i = 0; i < pcm.length; i += 2_560) await stream.feed(pcm.subarray(i, i + 2_560)); + await stream.finalize(); + assertSpokenTranscript(stream.text.committed, `${id} stream (${language ?? 'auto'})`); + console.log(`[${id}] stream (${language ?? 'auto'}): ${stream.text.committed.trim()}`); + } finally { + session.dispose(); } - session.dispose(); - model.dispose(); } } finally { - // Cached on purpose: re-runs reuse the files. + model.dispose(); } - if (failures) { console.error(`${failures} streaming variant failure(s)`); process.exit(2); } - console.log('ALL OK'); } -main().catch((error) => { console.error(error); process.exit(1); }); +const root = path.resolve(import.meta.dirname, '..'); +const cache = path.join(root, 'node_modules', '.cache', 'speech-spike'); +const targets = process.argv.length > 2 ? process.argv.slice(2).map(speechModel) : speechModels; +const pcm = await readSpokenFixture(root); +await mkdir(cache, { recursive: true }); +console.log('Backends:', getAvailableBackends().map((b) => `${b.kind}(${b.deviceType})`).join(', ')); +for (const definition of targets) { + const file = path.join(cache, definition.fileName); + console.log(`[${definition.id}] verifying ${definition.fileName}`); + await download(definition, file); + await verify(definition, file, pcm); +} diff --git a/src/main/bootstrap/productionSmoke.test.ts b/src/main/bootstrap/productionSmoke.test.ts index 7885c4d5..f4b7d40f 100644 --- a/src/main/bootstrap/productionSmoke.test.ts +++ b/src/main/bootstrap/productionSmoke.test.ts @@ -10,13 +10,14 @@ function makeDeps(overrides: Partial = {}): { deps: Product const exit = vi.fn(); const deps: ProductionSmokeDeps = { speech: { - getStatus: async () => ({ backend: 'cpu' }), + verifyRuntime: async () => undefined, + setStreamSink: () => undefined, download: async () => undefined, streamStart: async () => undefined, streamFeed: async () => undefined, streamStop: async () => undefined, streamCancel: async () => undefined, - transcribe: async () => undefined, + transcribe: async () => ({ text: '' }), }, music: { getStatus: async () => ({ available: true, version: '2024.01.01', message: undefined }) }, settings: { loadThemes: async () => [{ name: 'Pi · dark', tone: 'dark' }, { name: 'Pi · light', tone: 'light' }] }, @@ -42,7 +43,7 @@ describe('runProductionSmoke', () => { expect(log).toHaveBeenCalledWith('PI_DESKTOP_SMOKE_OK'); expect(log).toHaveBeenCalledWith('PI_DESKTOP_RENDERER_OK'); - expect(log).toHaveBeenCalledWith('PI_DESKTOP_SPEECH_OK cpu'); + expect(log).toHaveBeenCalledWith('PI_DESKTOP_SPEECH_OK native binding'); expect(log).toHaveBeenCalledWith('PI_DESKTOP_YT_DLP_OK 2024.01.01'); expect(log).toHaveBeenCalledWith('PI_DESKTOP_THEMES_OK'); expect(log).toHaveBeenCalledWith('PI_DESKTOP_TERMINAL_OK bash'); diff --git a/src/main/bootstrap/productionSmoke.ts b/src/main/bootstrap/productionSmoke.ts index fd8c0ae0..eda1dc43 100644 --- a/src/main/bootstrap/productionSmoke.ts +++ b/src/main/bootstrap/productionSmoke.ts @@ -1,20 +1,15 @@ -/** - * Opt-in production smoke check wired on the initial window's first load. - * - * Six seconds of silence exercise the buffered streaming window, bounded worker - * feed queue, finalize path, and CPU fallback without a microphone, followed by - * the small batch transcribe path. Music, themes, and the terminal are checked - * alongside speech. All side effects go through injected adapters so the marker - * output and quit/exit ordering are testable without Electron. - */ +import type { SpeechModelId, SpeechStreamUpdate } from '../../shared/contracts/ipc'; +import { assertSpokenTranscript, readSpokenFixture } from './spokenSmokeFixture'; + export interface SpeechSmokeSurface { - download(model: string): Promise; - streamStart(model: string, language: string): Promise; + verifyRuntime(): Promise; + setStreamSink(sink: (update: SpeechStreamUpdate) => void): void; + download(model: SpeechModelId): Promise; + streamStart(model: SpeechModelId, language: string): Promise; streamFeed(samples: ArrayBuffer): Promise; streamStop(): Promise; streamCancel(): Promise; - transcribe(model: string, samples: ArrayBuffer, language: string): Promise; - getStatus(): Promise<{ backend: string }>; + transcribe(model: SpeechModelId, samples: ArrayBuffer, language: string): Promise<{ text: string }>; } export interface MusicStatusSurface { @@ -42,30 +37,37 @@ export interface ProductionSmokeDeps { quitDelayMs?: number; } -async function smokeParakeetStream(speech: SpeechSmokeSurface): Promise { +async function smokeParakeetStream(speech: SpeechSmokeSurface, pcm: Float32Array): Promise { await speech.download('parakeet-unified'); - await speech.streamStart('parakeet-unified', 'en'); + let transcript = ''; + speech.setStreamSink((update) => { if (update.state === 'final') transcript = update.committed; }); + await speech.streamStart('parakeet-unified', 'auto'); try { - const feeds = Array.from({ length: 38 }, () => speech.streamFeed(new Float32Array(16_000 * 0.16).buffer)); - const stopping = speech.streamStop(); - await Promise.all([...feeds, stopping]); + const chunkSize = 2_560; + const padded = new Float32Array(Math.max(38 * chunkSize, pcm.length)); + padded.set(pcm); + const feeds: Promise[] = []; + for (let i = 0; i < padded.length; i += chunkSize) feeds.push(speech.streamFeed(padded.slice(i, i + chunkSize).buffer)); + await Promise.all([...feeds, speech.streamStop()]); + assertSpokenTranscript(transcript, 'Parakeet stream'); } catch (error) { await speech.streamCancel().catch(() => undefined); throw error; } } -async function smokeBatchSpeech(speech: SpeechSmokeSurface): Promise { +async function smokeBatchSpeech(speech: SpeechSmokeSurface, pcm: Float32Array): Promise { await speech.download('canary-flash'); - await speech.transcribe('canary-flash', new Float32Array(16_000 * 6).buffer, 'en'); + const result = await speech.transcribe('canary-flash', pcm.buffer, 'auto'); + assertSpokenTranscript(result.text, 'Canary batch'); } export async function runProductionSmoke(deps: ProductionSmokeDeps): Promise { try { await deps.smokeRenderer(); deps.log('PI_DESKTOP_RENDERER_OK'); - const [speechStatus, musicStatus, themes, terminalShell] = await Promise.all([ - deps.speech.getStatus(), + const [, musicStatus, themes, terminalShell] = await Promise.all([ + deps.speech.verifyRuntime(), deps.music.getStatus(), deps.settings.loadThemes(), deps.smokeTerminalRuntime(deps.cwd), @@ -78,14 +80,15 @@ export async function runProductionSmoke(deps: ProductionSmokeDeps): Promise new Error('Select the local desktop explicitly before using a local workspace operation.'); +const unavailable = () => new PiDesktopError({ + code: 'INVALID_REQUEST', message: 'Select the local desktop explicitly before using a local workspace operation.', retryable: false, +}); /** Process-wide sole selected command target. A failed remote connection stays REMOTE. */ export class DesktopConnectionRouter { diff --git a/src/main/index.ts b/src/main/index.ts index 96d0ba40..f9870548 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -45,7 +45,7 @@ import { TargetProjectService } from './connections/TargetProjectService'; import { RemoteOutcomeStore } from './connections/RemoteOutcomeStore'; import type { PendingRemoteOutcome } from './connections/RemoteCoreClient'; import type { ConnectionSelection } from '../shared/contracts/connections'; -import { createTrustedRendererPolicy, isTrustedAudioPermissionRequest } from './security/trustedRenderer'; +import { createTrustedRendererPolicy, isTrustedAudioPermissionRequest, isTrustedRendererUrl } from './security/trustedRenderer'; import { createDesktopSettingsService } from './settings/DesktopSettingsService'; import { SpeechService } from './speech/SpeechService'; @@ -186,12 +186,24 @@ const music = new MusicService(); const computerUse = new ComputerUseService(logs); const rendererNetworkProxy = new PublicHttpsProxy(); const speech = new SpeechService(logs); -const emitVoiceHotkey = (action: 'start' | 'stop') => { - for (const window of BrowserWindow.getAllWindows()) { - if (!window.isDestroyed()) window.webContents.send(ipcChannels.voiceHotkey, { action, source: 'hotkey' }); - } -}; -const hotkey = new GlobalHotkeyService(logs, () => emitVoiceHotkey('start'), () => emitVoiceHotkey('stop')); +let voiceTarget: () => Electron.WebContents | null = () => null; +let heldTarget: Electron.WebContents | null = null; +const eligibleVoiceTarget = (contents: Electron.WebContents | null | undefined): contents is Electron.WebContents => + !!contents && !contents.isDestroyed() && !contents.isCrashed() && !contents.isLoadingMainFrame() + && BrowserWindow.fromWebContents(contents)?.webContents === contents && isTrustedRendererUrl(contents.getURL(), rendererPolicy); +const hotkey = new GlobalHotkeyService(logs, (action) => { + const owner = voiceTarget(); + if (action === 'start' && owner) return; + const target = owner ?? [BrowserWindow.getFocusedWindow(), dispatcher.activeHandle(), ...BrowserWindow.getAllWindows()] + .find((window) => window && !window.isDestroyed() && eligibleVoiceTarget(window.webContents))?.webContents; + if (!eligibleVoiceTarget(target)) return; + if (action === 'start') heldTarget = target; + target.send(ipcChannels.voiceHotkey, { action, source: 'hotkey' }); +}, () => { + const target = heldTarget; + heldTarget = null; + if (eligibleVoiceTarget(target)) target.send(ipcChannels.voiceHotkey, { action: 'stop', source: 'hotkey' }); +}); let terminal: TerminalService; const rendererPath = path.join(currentDirectory, '../renderer/index.html'); @@ -469,14 +481,19 @@ app.whenReady().then(async () => { logs.write('info', 'app', `Fate UI ${app.getVersion()} started in instance slot ${instanceProfile.slot}.`); session.defaultSession.setPermissionRequestHandler((webContents, permission, callback, details) => { const mediaTypes = 'mediaTypes' in details ? details.mediaTypes : undefined; - callback(permission === 'media' && isTrustedAudioPermissionRequest(rendererPolicy, { - documentUrl: webContents.getURL(), - mediaTypes, - })); + const allowed = () => permission === 'media' && details.isMainFrame && !webContents.isDestroyed() + && (isTrustedRendererUrl(details.requestingUrl, rendererPolicy) + || (!rendererPolicy.developmentOrigin && ['file://', 'file:///'].includes(details.requestingUrl))) + && BrowserWindow.fromWebContents(webContents)?.webContents === webContents + && isTrustedAudioPermissionRequest(rendererPolicy, { documentUrl: webContents.getURL(), mediaTypes }); + if (allowed() && process.platform === 'darwin' && systemPreferences.getMediaAccessStatus('microphone') === 'not-determined') { + void systemPreferences.askForMediaAccess('microphone').then((granted) => callback(granted && allowed()), () => callback(false)); + } else callback(allowed()); }); session.defaultSession.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => ( permission === 'media' - && details.mediaType === 'audio' + && details.isMainFrame && details.mediaType === 'audio' + && !!webContents && BrowserWindow.fromWebContents(webContents)?.webContents === webContents && isTrustedAudioPermissionRequest(rendererPolicy, { // Packaged pages report the broad `file://` origin; the exact WebContents URL is the security boundary. documentUrl: webContents?.getURL(), @@ -484,18 +501,6 @@ app.whenReady().then(async () => { mediaTypes: ['audio'], }) )); - if ( - process.platform === 'darwin' - && process.env.PI_DESKTOP_SMOKE !== '1' - && systemPreferences.getMediaAccessStatus('microphone') === 'not-determined' - ) { - try { - const granted = await systemPreferences.askForMediaAccess('microphone'); - if (!granted) logs.write('warn', 'microphone', 'Microphone permission was denied in macOS System Settings.'); - } catch (error) { - logs.write('warn', 'microphone', `macOS microphone permission could not be requested: ${error instanceof Error ? error.message : String(error)}`); - } - } await recovery.load(); if (settings.get().computerUseElevated) { if (!isElevated()) { @@ -522,13 +527,13 @@ app.whenReady().then(async () => { }, }); monitorWatches = desktopWatches; - desktopRuntime.setChatWatchStarter(async (scope, { url, channel, followUp }, current, signal) => { + desktopRuntime.setChatWatchStarter(async (scope, { url, channel }, current, signal) => { const stillCurrent = () => !hostStopping && connections?.isLocal === true && !signal?.aborted && current(); if (!stillCurrent()) throw new Error('This watch must be started in its original local chat.'); const source = channel ? { kind: 'mcp' as const, ...channel } : await resolveGitHubWatch(scope.workspaceRoot, url ? { url } : {}, signal ?? new AbortController().signal); if (!stillCurrent()) throw new Error('The chat changed before the watch could start.'); - await desktopWatches.start({ ...scope, source, wake: true, followUp: followUp ?? 'Tell me how the watched work finished.' }, stillCurrent, true); + await desktopWatches.start({ ...scope, source, wake: true, followUp: 'Tell me how the watched work finished.' }, stillCurrent, 'watch_ci'); if (source.kind === 'mcp') return `${source.eventId} on ${source.connector}`; return source.kind === 'github-pr' ? `${source.repo} PR #${source.prNumber}` : `${source.repo} run ${source.runId}`; }); @@ -551,9 +556,10 @@ app.whenReady().then(async () => { if (!window.isDestroyed() && state.kind === 'remote') browserHost?.setAppOverlay(window, true); } }); + voiceTarget = mainCommands.voiceTarget; dispatcher.setOpener(mainCommands.openProjectPath); void hotkey.applySpeechSettings((await settings.load()).speech).then((status) => { - if (!status.pushToTalkAvailable) logs.write('warn', 'speech', status.reason ?? 'Push-to-talk is unavailable on this platform.'); + if (status.reason) logs.write('warn', 'speech', status.reason); }); if (hostStopping) return; windows.installMenu(); diff --git a/src/main/ipc/registerIpc.ts b/src/main/ipc/registerIpc.ts index 76560939..b42ad404 100644 --- a/src/main/ipc/registerIpc.ts +++ b/src/main/ipc/registerIpc.ts @@ -96,6 +96,7 @@ import { type ProjectSessionTarget, projectSessionListInputSchema, projectDeleteSessionsResultSchema, + speechAttemptInputSchema, speechCancelResultSchema, speechDownloadProgressSchema, speechHotkeyStatusSchema, @@ -103,7 +104,6 @@ import { speechStatusSchema, speechStreamFeedInputSchema, speechStreamStartInputSchema, - speechStreamUpdateSchema, speechTranscribeInputSchema, speechTranscriptionSchema, setPermissionInputSchema, @@ -162,6 +162,7 @@ import type { MusicService } from '../music/MusicService'; import type { ComputerUseService } from '../computer/ComputerUseService'; import type { SpeechService } from '../speech/SpeechService'; import type { GlobalHotkeyService } from '../speech/GlobalHotkeyService'; +import { SpeechOwnership } from '../speech/SpeechOwnership'; import type { UpdateService } from '../updates/UpdateService'; import type { RecoverySnapshotService } from '../bootstrap/RecoverySnapshot'; import { buildSessionExport } from '../pi/SessionExport'; @@ -653,10 +654,8 @@ export function registerIpc({ runtime, core, monitorCore, connections, connectio const payload = speechDownloadProgressSchema.parse(progress); for (const window of BrowserWindow.getAllWindows()) window.webContents.send(ipcChannels.speechEvents, payload); }); - speech.setStreamSink((update) => { - const payload = speechStreamUpdateSchema.parse(update); - for (const window of BrowserWindow.getAllWindows()) window.webContents.send(ipcChannels.speechStreamEvents, payload); - }); + const voice = new SpeechOwnership(speech, (error) => logs.write('warn', 'speech', `Voice cleanup failed: ${error instanceof Error ? error.message : String(error)}`)); + speech.setStreamSink((update) => voice.update(update)); music.setDurationSink((updates) => { const payload = musicDurationsEventSchema.parse({ updates }); for (const window of BrowserWindow.getAllWindows()) window.webContents.send(ipcChannels.musicDurations, payload); @@ -1656,31 +1655,42 @@ export function registerIpc({ runtime, core, monitorCore, connections, connectio await speech.remove(modelId); return speechStatusSchema.parse(await speech.getStatus()); }); - handle(ipcChannels.speechTranscribe, async (_event, input) => { - const parsed = speechTranscribeInputSchema.parse(input); - return speechTranscriptionSchema.parse(await speech.transcribe(parsed.modelId, parsed.audio, parsed.language)); + const voiceGuard = (event: Electron.IpcMainInvokeEvent) => { + const valid = invocationGuards.get(event); + const sender = event.sender; + return () => valid?.() === true && BrowserWindow.fromWebContents(sender)?.webContents === sender; + }; + handle(ipcChannels.speechClaimAttempt, (event, input) => { + const { attemptId } = speechAttemptInputSchema.parse(input); + voice.claim(event.sender, attemptId, voiceGuard(event)); }); - handle(ipcChannels.speechCancel, (_event, input) => { - emptyInputSchema.parse(input); - return speechCancelResultSchema.parse({ cancelled: speech.cancel() }); + handle(ipcChannels.speechReleaseAttempt, (event, input) => { + const { attemptId } = speechAttemptInputSchema.parse(input); + return voice.release(event.sender, attemptId); }); - handle(ipcChannels.speechStreamStart, async (_event, input) => { - const { modelId, language, refine } = speechStreamStartInputSchema.parse(input); - await speech.streamStart(modelId, language, refine); + handle(ipcChannels.speechTranscribe, async (event, input) => { + const { modelId, audio, language, attemptId } = speechTranscribeInputSchema.parse(input); + return speechTranscriptionSchema.parse(await voice.transcribe(event.sender, attemptId, voiceGuard(event), modelId, audio, language)); }); - handle(ipcChannels.speechStreamFeed, async (_event, input) => { - const { audio } = speechStreamFeedInputSchema.parse(input); - await speech.streamFeed(audio); + handle(ipcChannels.speechCancel, async (event, input) => { + const { attemptId } = speechAttemptInputSchema.parse(input); + return speechCancelResultSchema.parse({ cancelled: await voice.cancelBatch(event.sender, attemptId) }); }); - handle(ipcChannels.speechStreamStop, async (_event, input) => { - emptyInputSchema.parse(input); - await speech.streamStop(); - hotkey.resetActive(); + handle(ipcChannels.speechStreamStart, (event, input) => { + const { modelId, language, refine, attemptId } = speechStreamStartInputSchema.parse(input); + return voice.start(event.sender, attemptId, voiceGuard(event), modelId, language, refine); }); - handle(ipcChannels.speechStreamCancel, async (_event, input) => { - emptyInputSchema.parse(input); - await speech.streamCancel(); - hotkey.resetActive(); + handle(ipcChannels.speechStreamFeed, (event, input) => { + const { audio, attemptId } = speechStreamFeedInputSchema.parse(input); + return voice.feed(event.sender, attemptId, audio); + }); + handle(ipcChannels.speechStreamStop, (event, input) => { + const { attemptId } = speechAttemptInputSchema.parse(input); + return voice.stop(event.sender, attemptId); + }); + handle(ipcChannels.speechStreamCancel, (event, input) => { + const { attemptId } = speechAttemptInputSchema.parse(input); + return voice.cancelStream(event.sender, attemptId); }); handle(ipcChannels.speechHotkeyStatus, (_event, input) => { emptyInputSchema.parse(input); @@ -1797,5 +1807,5 @@ export function registerIpc({ runtime, core, monitorCore, connections, connectio }; return connections ? connections.local(open) : open(); }; - return { openProjectPath: openRecoveredProjectPath, focusProjectPath }; + return { openProjectPath: openRecoveredProjectPath, focusProjectPath, voiceTarget: () => voice.target() }; } diff --git a/src/main/pi/DesktopMonitorWatches.ts b/src/main/pi/DesktopMonitorWatches.ts index 73fd7845..f12dad33 100644 --- a/src/main/pi/DesktopMonitorWatches.ts +++ b/src/main/pi/DesktopMonitorWatches.ts @@ -37,8 +37,10 @@ interface MonitorDependencies { withConnectors?(use: (servers: readonly McpServerDefinition[]) => T): Promise; selectedTarget(scope: Pick): MonitorWatchTarget | null; } +type WatchOrigin = 'monitor' | 'watch_ci'; interface Watch { request: MonitorWatchRequest; + origin: WatchOrigin; key: string; status: MonitorWatchStatus; controller: AbortController; @@ -50,6 +52,14 @@ interface Watch { failures: number; } +function statusNotice(source: MonitorWatchRequest['source'], result: MonitorWatchResult): string { + if (source.kind === 'mcp') return `MCP connector ${source.connector} reported ${result} for event ${source.eventId} at revision ${source.revision}.`; + const [label, path] = source.kind === 'github-pr' ? [`PR #${source.prNumber}`, `commit/${source.sha}/checks`] + : [`run ${source.runId}`, `actions/runs/${source.runId}`]; + const outcome = result === 'failure' ? 'at least one check failed' : `CI result: ${result}`; + return `${source.repo} ${label} at ${source.sha.slice(0, 7)}: ${outcome}.\nhttps://github.com/${source.repo}/${path}`; +} + function sameConnector(left: Connector, right: Connector): boolean { return left.name === right.name && left.command === right.command && left.args.length === right.args.length && left.args.every((arg, i) => arg === right.args[i]); @@ -90,14 +100,15 @@ export class DesktopMonitorWatches { return [...this.watches.values()].some(({ request }) => request.workspaceRoot === workspaceRoot); } - async start(input: unknown, scopeIsCurrent?: () => boolean, waitForFirstSave = false): Promise { + async start(input: unknown, scopeIsCurrent?: () => boolean, origin: WatchOrigin = 'monitor'): Promise { const request = monitorWatchRequestSchema.parse(input); if (!this.deps.isLocal() || this.disposed) throw new Error('Monitor watches require the local desktop.'); if (this.watches.size + this.starting.size >= MAX_WATCHES || this.working.size + this.starting.size >= MAX_WATCHES) throw new Error('Stop a watch before adding another.'); if (this.consumed.size + this.watches.size + this.starting.size >= MAX_COMPLETIONS) throw new Error('The desktop watch limit for this process has been reached.'); const target = this.deps.selectedTarget(request); if (!target) throw new Error('Open the original trusted saved chat before starting a watch.'); - if (request.wake && (!target.answer || !target.report)) throw new Error('A configured chat model is required for an automatic Monitor reply.'); + if (request.wake && !target.report) throw new Error('The original chat is unavailable for Monitor updates.'); + if (request.wake && origin === 'monitor' && !target.answer) throw new Error('A configured chat model is required for an automatic Monitor reply.'); const admission = { workspaceRoot: request.workspaceRoot, sessionId: request.sessionId, cancelled: false }; this.starting.add(admission); try { @@ -108,7 +119,7 @@ export class DesktopMonitorWatches { const roots = await this.deps.trustedRoots(); if (!roots.includes(request.workspaceRoot)) throw new Error('The original trusted chat is unavailable.'); const saved = await target.isSaved(); - if (!saved && !waitForFirstSave) throw new Error('The original trusted saved chat is unavailable.'); + if (!saved && origin !== 'watch_ci') throw new Error('The original trusted saved chat is unavailable.'); if (admission.cancelled || this.disposed || !this.deps.isLocal() || scopeIsCurrent?.() === false) { throw new Error('Monitor scope changed before the watch could start.'); } @@ -117,7 +128,7 @@ export class DesktopMonitorWatches { : [source.kind, source.repo, source.kind === 'github-pr' ? source.prNumber : source.runId, source.sha]]); if (this.consumed.has(key) || [...this.watches.values()].some((watch) => watch.key === key)) throw new Error('This completion is already watched or was already recorded for this chat.'); const id = randomUUID(); - const watch: Watch = { request, key, target, controller: new AbortController(), ...(connector ? { connector } : {}), + const watch: Watch = { request, origin, key, target, controller: new AbortController(), ...(connector ? { connector } : {}), status: { id, source, state: 'waiting', wake: request.wake, expiresAt: Date.now() + TTL_MS }, nextCheck: 0, ...(!saved ? { saveDeadline: Date.now() + FIRST_SAVE_GRACE_MS } : {}), failures: 0 }; this.watches.set(id, watch); @@ -246,7 +257,7 @@ export class DesktopMonitorWatches { return; } await this.revalidate(watch); - this.consumed.add(watch.key); + if (watch.origin === 'monitor' || !watch.request.wake) this.consumed.add(watch.key); watch.status.result = result; watch.status.state = 'completed'; if (!watch.request.wake) { this.finish(watch, 'completed'); return; } @@ -271,7 +282,7 @@ export class DesktopMonitorWatches { private async wake(watch: Watch): Promise { const { request } = watch; const { id, result, expiresAt } = watch.status; - if (!request.wake || result === undefined || !watch.target.answer || !watch.target.report) throw new Error('Monitor reply unavailable.'); + if (!request.wake || result === undefined || !watch.target.report) throw new Error('Monitor reply unavailable.'); const { workspaceRoot, sessionId, source, followUp } = request; const key = JSON.stringify([workspaceRoot, sessionId]); if (this.answering.has(key)) return; @@ -282,12 +293,17 @@ export class DesktopMonitorWatches { revalidate: () => this.revalidate(watch), }; try { - if (watch.answer === undefined) { + if (watch.origin === 'watch_ci') { + watch.answer ??= statusNotice(source, result); + } else if (watch.answer === undefined) { + if (!watch.target.answer) throw new Error('Monitor reply unavailable.'); const text = await watch.target.answer({ id, source, result, followUp }, fence, () => { watch.status.wakeStatus = 'answering'; }); if (text === null || !fence.current()) return; watch.answer = text; + watch.status.wakeStatus = 'queued'; } await watch.target.report(id, watch.answer, fence, () => { + this.consumed.add(watch.key); watch.status.wakeStatus = 'reported'; this.finish(watch, 'completed'); }); diff --git a/src/main/pi/PiRuntimeService.ts b/src/main/pi/PiRuntimeService.ts index 5c94931e..cdb33e33 100644 --- a/src/main/pi/PiRuntimeService.ts +++ b/src/main/pi/PiRuntimeService.ts @@ -1446,9 +1446,10 @@ export class PiRuntimeService { const slot = this.findLiveSlot(sessionId); const turn = slot && this.chatWatchTurns.get(slot); const starter = this.chatWatchStarter; - if (!starter || !turn?.bound || turn.used || !turn.current() || signal?.aborted) { - throw new Error('Send a direct request in this chat, such as “Watch CI on my PR and tell me when it finishes”, when the chat is idle.'); - } + if (!starter) throw new Error('CI watching is unavailable in this session.'); + if (!turn?.bound) throw new Error('No direct watch request was recognized for this turn. In an idle chat in a trusted desktop project, send “Watch CI on my PR”.'); + if (!turn.current() || signal?.aborted) throw new Error('The watch request is no longer current.'); + if (turn.used) throw new Error('This turn has already attempted to start a watch.'); turn.used = true; const combined = signal ? AbortSignal.any([signal, turn.signal]) : turn.signal; const current = () => !combined.aborted && turn.current(); @@ -4048,8 +4049,7 @@ export class PiRuntimeService { return original.path === file.path && original.ino === file.ino && original.dev === file.dev; }, }; - if (!project?.trusted || !selected || !modelRuntime || !model || !permission || !modelAvailable() - || (coldChoice && (model.provider !== coldChoice.provider || model.id !== coldChoice.id))) return target; + if (!project?.trusted || !selected || !permission) return target; const scope = () => { const live = this.findLiveSlot(sessionId); const cold = this.coldSession?.snapshot.summary.id === sessionId ? this.coldSession : null; @@ -4076,7 +4076,7 @@ export class PiRuntimeService { admit(fence); return idle(); }; - target.answer = async ({ source, result, followUp }, fence, onStart) => { + if (modelRuntime && model && modelAvailable() && (!coldChoice || (model.provider === coldChoice.provider && model.id === coldChoice.id))) target.answer = async ({ source, result, followUp }, fence, onStart) => { if (!await ready(fence)) return null; admit(fence); if (!idle()) return null; @@ -4130,7 +4130,7 @@ export class PiRuntimeService { private monitorSessionIdle(sessionId: string): boolean { if (!this.project || this.sessionWriterUnavailable(this.sessionClaimKey(this.project.path, sessionId)) - || this.replacementActive || this.monitorBusyPrompts.has(sessionId) || this.hasOwnedAgentWork(sessionId) + || this.replacementActive || this.monitorBusyPrompts.has(sessionId) || this.hasActiveAgentWork(sessionId) || this.goalMax.hasRunnableGoal(sessionId) || (this.selectedSessionId === sessionId && this.promptOptimizationActive)) return false; const slots = [...this.liveSlots].filter((slot) => !slot.disposed && slot.runtime.session.sessionId === sessionId); if (slots.length === 0) return true; diff --git a/src/main/pi/monitor/ChatWatchTool.ts b/src/main/pi/monitor/ChatWatchTool.ts index ef556881..a9185d11 100644 --- a/src/main/pi/monitor/ChatWatchTool.ts +++ b/src/main/pi/monitor/ChatWatchTool.ts @@ -2,7 +2,7 @@ import { defineTool, type ToolDefinition } from '@earendil-works/pi-coding-agent import { Type } from 'typebox'; type ChatWatchChannel = { connector: string; eventId: string; revision: string }; -export type ChatWatchInput = { url?: string; channel?: ChatWatchChannel; followUp?: string }; +export type ChatWatchInput = { url?: string; channel?: ChatWatchChannel }; export type ChatWatchStarter = ( scope: { workspaceRoot: string; sessionId: string }, input: ChatWatchInput, @@ -10,8 +10,11 @@ export type ChatWatchStarter = ( signal?: AbortSignal, ) => Promise; -const request = /^(?:(?:can|could|would|will) you |i(?:['’]d| would) like you to )?(?:please,? )?(?:watch|monitor|track|keep an eye on|babysit) (.+?)[.!?]*$/iu; -const notification = /(?:,? (?:and |then )?|; )(?:let me know|tell me|notify me|ping me|update me|report back)(?: (?:here|in (?:this|the same) chat))?(?: (?:when|once) (?:(?:it|CI|the (?:CI|checks|run|build)) (?:finishes|passes or fails|completes|ends|is done)|(?:they|(?:the |my )?checks) (?:finish|pass or fail|complete|end|are done)|(?:it['’]s|they['’]re) done))?$/iu; +const request = /^(?:(?:hey|hi|hello),? )?(?:(?:can|could|would|will) you |i(?:['’]d| would) like you to )?(?:please,? )?(?:(?:watch|monitor|track|keep an eye on|babysit) |(?:set up|start|create) a (?:watch|watcher) (?:(?:for|on|to watch) |(as soon as|once|when) ))(.+?)[.!?]*$/iu; +const ciCompletion = /^(?:the )?(?:(?:ci|build) (?:passes|finishes|completes|ends|is done)|checks (?:pass|finish|complete|end|are done))$/iu; +const actionBoundary = /(?:[,;] (?:(?:and )?then |and )?| and then )(?=(?:merge|publish|release|bump|fix|make sure (?:that )?it merges)\b)/iu; +const conflictingAction = /:\/\/|#\d|\b(?:www\.|github\.com\/)|\b(?:watch(?:er|ing)?|monitor(?:ing)?|track(?:ing)?|babysit|keep an eye on|pr|pull request|branch|repo(?:sitory)?|run|workflow|event|revision|connector|channel|instead|rather|another|different|redirect|cancel|stop|no|not|never|unless)\b|n['’]t\b/iu; +const notification = /(?:,? (?:and |then )?|; )(?:let me know|tell me|notify me|ping me|update me|report back)(?: (?:here|in (?:this|the same) chat))?(?: (?:when|once) (?:(?:it|CI|the (?:CI|checks|run|build)) (?:finishes|passes(?: or fails)?|completes|ends|is done)|(?:they|(?:the |my )?checks) (?:finish|pass(?: or fail)?|complete|end|are done)|(?:it['’]s|they['’]re) done))?$/iu; const currentPr = /^(?:(?:the |my |our |this |current )?(?:(?:current |open )?(?:pr|pull request)(?:['’]s)?(?: (?:ci|(?:ci |status )?checks|build))?|(?:ci|(?:ci |status )?checks|build)(?: (?:on|for|of) (?:(?:the |my |our |this )?(?:current |open )?)(?:pr|pull request|branch))?))$/iu; const githubTarget = /^(?:(?:the )?(?:(?:ci|checks|build) (?:on|for) |(?:github )?(?:pr|pull request|actions run|workflow run)(?: at)? ))?(?)$/iu; @@ -22,7 +25,12 @@ export function parseChatWatchRequest(raw: string): ChatWatchInput | null { if (text.length > 500 || /[\r\n\u2028\u2029]/u.test(text)) return null; const match = request.exec(text.replace(/[\t ]+/gu, ' ')); if (!match) return null; - const target = match[1]!.replace(/,? please$/iu, '').replace(notification, ''); + const body = match[2]!; + const boundary = actionBoundary.exec(body); + if (boundary && conflictingAction.test(body.slice(boundary.index))) return null; + const clause = boundary ? body.slice(0, boundary.index) : body; + const target = clause.replace(/,? please$/iu, '').replace(notification, ''); + if (match[1]) return ciCompletion.test(target) ? {} : null; const explicit = githubTarget.exec(target); if (explicit && Boolean(explicit[1]) === Boolean(explicit[3])) return { url: explicit[2]!.replace(/\/checks\/?$/u, '') }; const channel = channelTarget.exec(target); @@ -45,7 +53,7 @@ export function createChatWatchTool(start: (sessionId: string, signal?: AbortSig executionMode: 'sequential', execute: async (_id, _params, signal, _update, ctx) => { const label = await start(ctx.sessionManager.getSessionId(), signal); - return { content: [{ type: 'text' as const, text: `Watching ${label}. I’ll post the result in this chat when it finishes.` }], details: { label } }; + return { content: [{ type: 'text' as const, text: `Watching ${label}. I’ll post the result in this chat.` }], details: { label } }; }, }); } diff --git a/src/main/pi/monitorSources.ts b/src/main/pi/monitorSources.ts index dd5cb50b..8ad15da9 100644 --- a/src/main/pi/monitorSources.ts +++ b/src/main/pi/monitorSources.ts @@ -252,14 +252,13 @@ async function pollPull(executable: string, source: Extract void; + private readonly onPress: (action: 'start' | 'toggle') => void; private readonly onStop: () => void; private uiohookPromise: Promise | null = null; private pushToTalkAvailable = true; private unavailableReason: string | undefined; private current: { cleanup: () => void } | null = null; private combo: KeyCombo | null = null; - private active = false; + private held = false; + private registrationReason: string | undefined; + private generation = 0; + private requested: { accelerator: string; mode: VoiceHotkeyMode; result: Promise } | null = null; private disposed = false; - constructor(logs: AppLogService, onStart: () => void, onStop: () => void, + constructor(logs: AppLogService, onPress: (action: 'start' | 'toggle') => void, onStop: () => void, private readonly startHook: (listener: (event: 'down' | 'up') => void) => Promise = startKeyboardHookProcess) { this.logs = logs; - this.onStart = onStart; + this.onPress = onPress; this.onStop = onStop; } getStatus(): SpeechHotkeyStatus { - return this.pushToTalkAvailable - ? { pushToTalkAvailable: true } - : { pushToTalkAvailable: false, reason: this.unavailableReason }; + return { pushToTalkAvailable: this.pushToTalkAvailable, ...(this.registrationReason ? { reason: this.registrationReason } : {}) }; } /** Register a hotkey. Toggle uses globalShortcut; push-to-talk uses the native @@ -108,20 +109,28 @@ export class GlobalHotkeyService { // A settings save or a late startup step can arrive during quit. Nothing registers then. if (this.disposed) return this.getStatus(); if (mode === 'toggle') { - const registered = globalShortcut.register(accelerator, () => this.toggle()); + let registered = false; + try { registered = globalShortcut.register(accelerator, () => this.onPress('toggle')); } catch { registered = false; } if (!registered) { - return { pushToTalkAvailable: this.pushToTalkAvailable, reason: `The hotkey "${accelerator}" could not be registered. It may be in use by another application.` }; + this.registrationReason = `The hotkey "${accelerator}" could not be registered. Choose another shortcut.`; + return this.getStatus(); } this.current = { cleanup: () => globalShortcut.unregister(accelerator) }; this.logs.write('info', 'speech', `Voice toggle hotkey registered: ${accelerator}`); return this.getStatus(); } + const generation = this.generation; const hook = await this.loadHook(); - if (!hook || this.disposed) return this.getStatus(); + if (this.disposed || generation !== this.generation) return this.getStatus(); + if (!hook) { + this.registrationReason = this.unavailableReason; + return this.getStatus(); + } const combo = parseAccelerator(accelerator, hook.keys as unknown as UiohookModule['UiohookKey']); if (!combo) { - return { pushToTalkAvailable: this.pushToTalkAvailable, reason: `The hotkey "${accelerator}" is not a recognizable key combination for push-to-talk.` }; + this.registrationReason = `The hotkey "${accelerator}" is not a recognizable key combination for push-to-talk.`; + return this.getStatus(); } this.combo = combo; hook.setCombo(combo); @@ -138,21 +147,22 @@ export class GlobalHotkeyService { this.unregister(); return this.getStatus(); } - return this.register(speech.voiceHotkey, speech.voiceHotkeyMode); + const { voiceHotkey: accelerator, voiceHotkeyMode: mode } = speech; + if (this.requested?.accelerator === accelerator && this.requested.mode === mode) return this.requested.result; + const result = this.register(accelerator, mode); + this.requested = { accelerator, mode, result }; + return result; } /** Drop the active hotkey registration (keeps push-to-talk availability). */ unregister(): void { + this.generation++; + this.requested = null; + this.registrationReason = undefined; this.current?.cleanup(); this.current = null; this.combo = null; - this.active = false; - } - - /** Push-to-talk toggle-state debounce, and keeps toggle in sync when recording - * stops for any reason (hotkey or on-screen button). */ - resetActive(): void { - this.active = false; + if (this.held) { this.held = false; this.onStop(); } } /** Release every registration and stop the native hook if it was started. */ @@ -167,17 +177,12 @@ export class GlobalHotkeyService { void started.then((hook) => { hook?.stop(); }); } - private toggle(): void { - if (this.active) { this.active = false; this.onStop(); } - else { this.active = true; this.onStart(); } - } - /** The helper reports only that the registered combination went down or up. */ private onHookEvent(event: 'down' | 'up'): void { if (!this.combo) return; if (event === 'down') { - if (!this.active) { this.active = true; this.onStart(); } - } else if (this.active) { this.active = false; this.onStop(); } + if (!this.held) { this.held = true; this.onPress('start'); } + } else if (this.held) { this.held = false; this.onStop(); } } private loadHook(): Promise { diff --git a/src/main/speech/SpeechOwnership.ts b/src/main/speech/SpeechOwnership.ts new file mode 100644 index 00000000..945879aa --- /dev/null +++ b/src/main/speech/SpeechOwnership.ts @@ -0,0 +1,147 @@ +import { ipcChannels, speechStreamUpdateSchema, type SpeechModelId, type SpeechStreamUpdate } from '../../shared/contracts/ipc'; +import type { SpeechService } from './SpeechService'; + +type Engine = Pick; + +type Owner = { + sender: Electron.WebContents; + attemptId: string; + valid: () => boolean; + detach: () => void; + mode: 'capture' | 'batch' | 'stream'; + starting?: Promise; + stopping?: Promise; + pending: number; + ended: boolean; +}; + +export class SpeechOwnership { + private owner: Owner | null = null; + + constructor(private readonly engine: Engine, private readonly reportError: (error: unknown) => void) {} + + target(): Electron.WebContents | null { + return this.owner?.valid() ? this.owner.sender : null; + } + + claim(sender: Electron.WebContents, attemptId: string, valid: () => boolean): Owner { + if (this.owner) throw new Error('Another voice recording is already running.'); + if (!valid()) throw new Error('The initiating voice window is unavailable.'); + const owner: Owner = { sender, attemptId, valid, mode: 'capture', pending: 0, ended: false, detach: () => { + sender.removeListener('destroyed', abort); + sender.removeListener('render-process-gone', abort); + sender.removeListener('did-start-navigation', navigate); + } }; + const abort = () => { void this.abort(owner).catch(this.reportError); }; + const navigate = (event: { isMainFrame: boolean; isSameDocument: boolean }) => { if (event.isMainFrame && !event.isSameDocument) abort(); }; + sender.once('destroyed', abort); + sender.once('render-process-gone', abort); + sender.on('did-start-navigation', navigate); + this.owner = owner; + return owner; + } + + private match(sender: Electron.WebContents, attemptId: string): Owner | null { + const owner = this.owner; + return owner && owner.sender === sender && owner.attemptId === attemptId && !owner.ended && owner.valid() ? owner : null; + } + + private begin(sender: Electron.WebContents, attemptId: string, valid: () => boolean, mode: 'batch' | 'stream'): Owner { + const owner = this.match(sender, attemptId); + if (!owner || !valid()) throw new Error('This voice recording is not active.'); + if (owner.mode !== 'capture') throw new Error('Another voice transcription is already running.'); + owner.mode = mode; + return owner; + } + + private retire(owner: Owner): void { + if (this.owner !== owner || !owner.ended || owner.pending !== 0) return; + owner.detach(); + this.owner = null; + } + + private async track(owner: Owner, operation: () => Promise): Promise { + owner.pending++; + try { return await operation(); } + finally { owner.pending--; this.retire(owner); } + } + + private async abort(owner: Owner): Promise { + if (this.owner !== owner || owner.ended) return false; + owner.ended = true; + if (owner.mode === 'stream') { + await this.track(owner, () => this.engine.streamCancel()); + return true; + } + try { return owner.mode === 'batch' ? this.engine.cancel() : true; } + finally { this.retire(owner); } + } + + async release(sender: Electron.WebContents, attemptId: string): Promise { + const owner = this.match(sender, attemptId); + if (owner) await this.abort(owner); + } + + async transcribe(sender: Electron.WebContents, attemptId: string, valid: () => boolean, modelId: SpeechModelId, audio: ArrayBuffer, language?: string) { + const owner = this.begin(sender, attemptId, valid, 'batch'); + return this.track(owner, async () => { + try { + const result = await this.engine.transcribe(modelId, audio, language); + if (owner.ended || !owner.valid()) throw new Error('Voice transcription was cancelled.'); + return result; + } finally { owner.ended = true; } + }); + } + + async cancelBatch(sender: Electron.WebContents, attemptId: string): Promise { + const owner = this.match(sender, attemptId); + return owner?.mode === 'batch' && this.abort(owner); + } + + start(sender: Electron.WebContents, attemptId: string, valid: () => boolean, modelId: SpeechModelId, language?: string, refine?: boolean): Promise { + const owner = this.begin(sender, attemptId, valid, 'stream'); + owner.starting = this.track(owner, async () => { + try { + await this.engine.streamStart(modelId, language, refine); + if (owner.ended || !owner.valid()) throw new Error('Live transcription was cancelled.'); + } catch (error) { owner.ended = true; throw error; } + }); + return owner.starting; + } + + feed(sender: Electron.WebContents, attemptId: string, audio: ArrayBuffer): Promise { + const owner = this.match(sender, attemptId); + if (owner?.mode !== 'stream') throw new Error('This voice recording is not active.'); + return this.track(owner, () => this.engine.streamFeed(audio)); + } + + async stop(sender: Electron.WebContents, attemptId: string): Promise { + const owner = this.match(sender, attemptId); + if (owner?.mode !== 'stream') return; + owner.stopping ??= this.track(owner, async () => { + try { + await owner.starting; + if (!owner.ended && owner.valid()) await this.engine.streamStop(); + } finally { owner.ended = true; } + }); + await owner.stopping; + } + + async cancelStream(sender: Electron.WebContents, attemptId: string): Promise { + const owner = this.match(sender, attemptId); + if (owner?.mode === 'stream') await this.abort(owner); + } + + update(update: SpeechStreamUpdate): void { + const owner = this.owner; + if (owner?.mode !== 'stream' || (owner.ended && update.state !== 'cancelled')) return; + try { + if (owner.valid()) owner.sender.send(ipcChannels.speechStreamEvents, speechStreamUpdateSchema.parse({ ...update, attemptId: owner.attemptId })); + } finally { + if (update.state === 'final' || update.state === 'error' || update.state === 'cancelled') { + owner.ended = true; + this.retire(owner); + } + } + } +} diff --git a/src/main/speech/SpeechService.ts b/src/main/speech/SpeechService.ts index 8be0e8b8..94e4b089 100644 --- a/src/main/speech/SpeechService.ts +++ b/src/main/speech/SpeechService.ts @@ -39,7 +39,15 @@ type LoadedModel = Awaited; type SpeechStream = Awaited>; type QueuedStreamFeed = { pcm: Float32Array; resolve: () => void; reject: (error: unknown) => void }; +type NativeSlot = { + kind: 'batch' | 'live'; + modelId: SpeechModelId; + controller: AbortController; + settled: Promise; + release: () => void; +}; type ActiveSpeechStream = { + slot: NativeSlot; definition: SpeechModelDefinition; session: SpeechSession; stream: SpeechStream; @@ -48,8 +56,6 @@ type ActiveSpeechStream = { /** Whether streamStop runs the full-recording accuracy pass. Off unless the * user enabled it: the pass doubles decode work on long dictations. */ refineFinal: boolean; - settled: Promise; - resolveSettled: () => void; accepting: boolean; /** Last committed text seen from the native stream. Failure and cancellation * events carry it so the UI never loses text the user already saw. */ @@ -71,9 +77,9 @@ export class SpeechService { private readonly installedModels = new Set(); private loaded: { id: SpeechModelId; model: LoadedModel } | null = null; private unloadTimer: NodeJS.Timeout | null = null; - private activeRun: AbortController | null = null; - private activeSettled: Promise | null = null; - private resolveActiveSettled: (() => void) | null = null; + private slot: NativeSlot | null = null; + private disposed = false; + private readonly removing = new Set(); private eventSink: ((progress: SpeechDownloadProgress) => void) | null = null; private streamSink: ((update: SpeechStreamUpdate) => void) | null = null; private activeStream: ActiveSpeechStream | null = null; @@ -105,6 +111,10 @@ export class SpeechService { this.streamSink = sink; } + async verifyRuntime(): Promise { + (await this.runtime()).version(); + } + async getStatus(): Promise { await this.cleanupLegacyModels(); const models = await Promise.all(this.definitions.map(async (definition) => { @@ -119,12 +129,16 @@ export class SpeechService { } async download(modelId: SpeechModelId): Promise { - if (await this.isInstalled(this.definition(modelId))) return; + if (this.disposed) throw new Error('Speech service is disposed.'); + if (this.removing.has(modelId)) throw new Error('The voice model is being removed.'); + const definition = this.definition(modelId); const existing = this.downloads.get(modelId); if (existing) return existing; const controller = new AbortController(); this.downloadControllers.set(modelId, controller); - const operation = this.downloadModel(this.definition(modelId), controller.signal).finally(() => { + const operation = this.isInstalled(definition).then((installed) => { + if (!installed) return this.downloadModel(definition, controller.signal); + }).finally(() => { this.downloads.delete(modelId); this.downloadControllers.delete(modelId); }); @@ -141,43 +155,49 @@ export class SpeechService { async remove(modelId: SpeechModelId): Promise { if (this.downloads.has(modelId)) throw new Error('Wait for this model download to finish before removing it.'); - this.installedModels.delete(modelId); - if (this.loaded?.id === modelId) this.unload(); + if (this.slot?.modelId === modelId) throw new Error('The voice model is in use.'); + if (this.removing.has(modelId)) throw new Error('The voice model is being removed.'); const definition = this.definition(modelId); - await Promise.all([ - fs.rm(this.modelPath(definition), { force: true }), - fs.rm(`${this.modelPath(definition)}.partial`, { force: true }), - fs.rm(`${this.modelPath(definition)}.verified`, { force: true }), - ]); + this.removing.add(modelId); + try { + this.installedModels.delete(modelId); + if (this.loaded?.id === modelId) this.unload(); + await Promise.all([ + fs.rm(this.modelPath(definition), { force: true }), + fs.rm(`${this.modelPath(definition)}.partial`, { force: true }), + fs.rm(`${this.modelPath(definition)}.verified`, { force: true }), + ]); + } finally { + this.installedModels.delete(modelId); + this.removing.delete(modelId); + } } async transcribe(modelId: SpeechModelId, audio: ArrayBuffer, language?: string): Promise { if (audio.byteLength === 0 || audio.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0) throw new Error('The captured audio is malformed.'); const pcm = new Float32Array(audio); if (pcm.length > MAX_AUDIO_SAMPLES) throw new Error('Voice recordings are limited to three minutes.'); - if (!(await this.isInstalled(this.definition(modelId)))) throw new Error('Download the selected voice model before transcribing.'); - if (this.activeRun || this.activeStream) throw new Error('Another voice transcription is already running.'); - - const controller = new AbortController(); - this.activeRun = controller; - this.activeSettled = new Promise((resolve) => { this.resolveActiveSettled = resolve; }); + const definition = this.definition(modelId); + const slot = this.reserve('batch', modelId); + const { signal } = slot.controller; try { - const definition = this.definition(modelId); + if (!(await this.isInstalled(definition))) throw new Error('Download the selected voice model before transcribing.'); + signal.throwIfAborted(); const startedAt = performance.now(); const warm = this.loaded?.id === modelId; - const model = await this.load(definition); + const model = await this.load(definition, signal); + signal.throwIfAborted(); const loadMs = performance.now() - startedAt; + const runLanguage = resolveModelLanguage(definition, language); const session = model.createSession({ nThreads: CPU_THREADS }); let result: Awaited>; try { - // 'auto' has no meaning for batch models without detection; explicit - // short codes map (Nemotron needs en-US style locales). - const runLanguage = resolveModelLanguage(definition, language) ?? resolveModelLanguage(definition, 'en') ?? 'en'; result = await session.run(pcm, { - signal: controller.signal, + signal, timestamps: 'none', - language: runLanguage, + ...(runLanguage ? { language: runLanguage } : {}), }); + signal.throwIfAborted(); } finally { session.dispose(); } @@ -185,22 +205,38 @@ export class SpeechService { this.logs.write('info', 'speech', `${definition.model} transcribed ${(pcm.length / 16_000).toFixed(1)}s of audio in ${Math.round(elapsedMs)}ms (${warm ? 'warm' : `${Math.round(loadMs)}ms load`}, ${model.device.name || model.backend}).`); return { text: result.text.trim(), - language: result.language || language || 'unknown', + language: result.language || runLanguage || 'unknown', backend: model.device.name || model.device.description || model.backend, accelerated: model.device.deviceType !== 'cpu', }; } finally { - if (this.loaded?.id === modelId) this.scheduleUnload(); - if (this.activeRun === controller) this.activeRun = null; - this.resolveActiveSettled?.(); - this.resolveActiveSettled = null; - this.activeSettled = null; + slot.release(); } } + private reserve(kind: NativeSlot['kind'], modelId: SpeechModelId): NativeSlot { + if (this.disposed) throw new Error('Speech service is disposed.'); + if (this.slot) throw new Error('Another voice transcription is already running.'); + if (this.removing.has(modelId)) throw new Error('The voice model is being removed.'); + let resolveSettled!: () => void; + const slot = { + kind, modelId, + controller: new AbortController(), + settled: new Promise((resolve) => { resolveSettled = resolve; }), + release: () => { + if (this.slot !== slot) return; + this.slot = null; + if (this.loaded?.id === modelId) this.scheduleUnload(); + resolveSettled(); + }, + }; + this.slot = slot; + return slot; + } + cancel(): boolean { - if (!this.activeRun) return false; - this.activeRun.abort(); + if (this.slot?.kind !== 'batch') return false; + this.slot.controller.abort(); return true; } @@ -209,11 +245,23 @@ export class SpeechService { * single compute slot until streamStop/streamCancel, so batch transcribe() * is refused while it is active. */ async streamStart(modelId: SpeechModelId, language?: string, refine = false): Promise { - if (this.activeRun || this.activeStream) throw new Error('Another voice transcription is already running.'); const definition = this.definition(modelId); if (!definition.streaming) throw new Error('Live transcription is only supported by streaming voice models.'); + const slot = this.reserve('live', modelId); + try { + await this.openStream(slot, definition, language, refine); + } catch (error) { + slot.release(); + throw error; + } + } + + private async openStream(slot: NativeSlot, definition: SpeechModelDefinition, language: string | undefined, refine: boolean): Promise { + const { signal } = slot.controller; if (!(await this.isInstalled(definition))) throw new Error('Download the selected voice model before transcribing.'); - const model = await this.load(definition); + signal.throwIfAborted(); + const model = await this.load(definition, signal); + signal.throwIfAborted(); const session = model.createSession({ nThreads: CPU_THREADS }); const streamLanguage = resolveModelLanguage(definition, language); let stream: SpeechStream; @@ -230,20 +278,18 @@ export class SpeechService { // the engine's default stream slot. ...(definition.streamFamily ? { family: definition.streamFamily } : {}), }); + signal.throwIfAborted(); } catch (error) { session.dispose(); throw new Error(`Live transcription could not start: ${this.message(error)}`); } - let resolveSettled!: () => void; - const settled = new Promise((resolve) => { resolveSettled = resolve; }); this.activeStream = { + slot, definition, session, stream, language: streamLanguage, refineFinal: refine, - settled, - resolveSettled, accepting: true, lastCommitted: '', pendingFeeds: [], @@ -289,7 +335,7 @@ export class SpeechService { if (remaining > 0) { // Keep the part of this capture that still fits, then seal. const trimmed = pcm.subarray(0, remaining); - active.recordedAudio.push(trimmed); + if (active.refineFinal) active.recordedAudio.push(trimmed); active.recordedSamples += trimmed.length; active.pendingFeeds.push({ pcm: trimmed, resolve: () => {}, reject: () => {} }); active.pendingSamples += trimmed.length; @@ -303,7 +349,7 @@ export class SpeechService { this.failStream(active, error); throw error; } - active.recordedAudio.push(pcm); + if (active.refineFinal) active.recordedAudio.push(pcm); active.recordedSamples += pcm.length; return new Promise((resolve, reject) => { active.pendingFeeds.push({ pcm, resolve, reject }); @@ -364,20 +410,26 @@ export class SpeechService { } } catch (error) { // Carry the last committed text so the UI keeps everything the user saw. - this.emitStream({ state: 'error', committed: active.lastCommitted, tentative: '', error: this.message(error) }); + if (this.activeStream === active) this.emitStream({ state: 'error', committed: active.lastCommitted, tentative: '', error: this.message(error) }); + else if (!active.failure) return; throw error; } finally { this.endStream(active); + active.slot.release(); } } /** Abort the active stream without finalizing. Safe to call when idle. */ async streamCancel(): Promise { - const active = this.activeStream; - if (!active) return; - active.refinementAbort?.abort(); - this.emitStream({ state: 'cancelled', committed: active.lastCommitted, tentative: '' }); - this.endStream(active); + const slot = this.slot; + if (slot?.kind !== 'live') return; + if (!slot.controller.signal.aborted) { + slot.controller.abort(new Error('Live transcription cancelled.')); + const active = this.activeStream; + this.emitStream({ state: 'cancelled', committed: active?.lastCommitted ?? '', tentative: '' }); + if (active) this.endStream(active); + } + await slot.settled; } private startStreamDrain(active: ActiveSpeechStream): void { @@ -412,14 +464,12 @@ export class SpeechService { for (const queued of batch) queued.resolve(); // disposal is safe during a native call return; } - active.accepting = false; - active.failure = error; for (const queued of batch) queued.reject(error); - for (const queued of active.pendingFeeds.splice(0)) queued.reject(error); - active.pendingSamples = 0; + this.failStream(active, error instanceof Error ? error : new Error(this.message(error))); return; } finally { active.inFlightSamples = 0; + if (this.activeStream !== active && !active.stopping) active.slot.release(); } } } @@ -457,6 +507,7 @@ export class SpeechService { if (this.activeStream !== active) return; active.accepting = false; active.failure = error; + active.slot.controller.abort(error); for (const queued of active.pendingFeeds.splice(0)) queued.reject(error); active.pendingSamples = 0; // Keep the committed text in the failure event: the user keeps every word @@ -521,6 +572,8 @@ export class SpeechService { } private endStream(active: ActiveSpeechStream): void { + if (this.activeStream !== active) return; + this.activeStream = null; active.accepting = false; active.refinementAbort?.abort(); active.refinementAbort = null; @@ -528,10 +581,8 @@ export class SpeechService { active.pendingSamples = 0; active.recordedAudio.length = 0; active.recordedSamples = 0; - if (this.activeStream === active) this.activeStream = null; try { active.session.dispose(); } catch { /* teardown is best-effort */ } - if (this.loaded?.id === active.definition.id) this.scheduleUnload(); - active.resolveSettled(); + if (!active.inFlightSamples && !active.stopping) active.slot.release(); } private emitStream(update: SpeechStreamUpdate): void { @@ -539,75 +590,70 @@ export class SpeechService { } async dispose(): Promise { + this.disposed = true; for (const controller of this.downloadControllers.values()) controller.abort(); - this.cancel(); - if (this.activeStream) await this.streamCancel(); - const activeSettled = this.activeSettled; - if (activeSettled) await activeSettled.catch(() => undefined); + if (this.slot?.kind === 'live') await this.streamCancel(); + else if (this.slot) { + this.cancel(); + await this.slot.settled; + } this.unload(); } private async downloadModel(definition: SpeechModelDefinition, signal: AbortSignal): Promise { - await fs.mkdir(this.modelRoot, { recursive: true }); const target = this.modelPath(definition); const partial = `${target}.partial`; - const present = await fs.stat(partial).then((stat) => Math.min(stat.size, definition.bytes), () => 0); - if (present === definition.bytes && await this.verify(partial, definition.sha256)) { - await this.installVerified(partial, target, definition); - return; - } - if (present >= definition.bytes) await fs.rm(partial, { force: true }); - const offset = present >= definition.bytes ? 0 : present; - const freeBytes = await fs.statfs(this.modelRoot).then((stats) => stats.bavail * stats.bsize, () => Number.POSITIVE_INFINITY); - const requiredBytes = definition.bytes - offset + 64 * 1024 * 1024; - if (freeBytes < requiredBytes) throw new Error(`Not enough disk space for ${definition.name}. Free at least ${Math.ceil(requiredBytes / 1024 / 1024)} MB and try again.`); - this.emit({ modelId: definition.id, state: 'downloading', downloadedBytes: offset, totalBytes: definition.bytes }); - - let response: Response; + let downloaded = 0; try { - response = await this.fetcher(definition.url, { + signal.throwIfAborted(); + await fs.mkdir(this.modelRoot, { recursive: true }); + downloaded = await fs.stat(partial).then((stat) => Math.min(stat.size, definition.bytes), () => 0); + if (downloaded === definition.bytes && await this.verify(partial, definition.sha256, signal)) { + signal.throwIfAborted(); + await this.installVerified(partial, target, definition); + return; + } + if (downloaded >= definition.bytes) { + await fs.rm(partial, { force: true }); + downloaded = 0; + } + const offset = downloaded; + const freeBytes = await fs.statfs(this.modelRoot).then((stats) => stats.bavail * stats.bsize, () => Number.POSITIVE_INFINITY); + const requiredBytes = definition.bytes - offset + 64 * 1024 * 1024; + if (freeBytes < requiredBytes) throw new Error(`Not enough disk space for ${definition.name}. Free at least ${Math.ceil(requiredBytes / 1024 / 1024)} MB and try again.`); + this.emit({ modelId: definition.id, state: 'downloading', downloadedBytes: offset, totalBytes: definition.bytes }); + signal.throwIfAborted(); + const response = await this.fetcher(definition.url, { redirect: 'follow', signal, ...(offset > 0 ? { headers: { Range: `bytes=${offset}-` } } : {}), }); - } catch (error) { - if (!signal.aborted) throw error; - this.emit({ modelId: definition.id, state: 'cancelled', downloadedBytes: offset, totalBytes: definition.bytes }); - throw new Error('Model download cancelled.'); - } - if (!response.ok || !response.body) throw new Error(`Model download failed with HTTP ${response.status}.`); - const append = offset > 0 && response.status === 206; - const start = append ? offset : 0; - const hash = createHash('sha256'); - if (append) { - try { + if (!response.ok || !response.body) throw new Error(`Model download failed with HTTP ${response.status}.`); + const append = offset > 0 && response.status === 206; + const hash = createHash('sha256'); + if (append) { await pipeline(createReadStream(partial), new Transform({ transform(chunk: Buffer, _encoding, callback) { hash.update(chunk); callback(); } }), { signal }); - } catch (error) { - if (!signal.aborted) throw error; - this.emit({ modelId: definition.id, state: 'cancelled', downloadedBytes: offset, totalBytes: definition.bytes }); - throw new Error('Model download cancelled.'); } - } - let downloaded = start; - let lastUpdate = 0; - const progress = new Transform({ - transform: (chunk: Buffer, _encoding, callback) => { - downloaded += chunk.length; - hash.update(chunk); - if (downloaded > definition.bytes) return callback(new Error('The model download exceeded its declared size.')); - const now = Date.now(); - if (now - lastUpdate > 150 || downloaded === definition.bytes) { - lastUpdate = now; - this.emit({ modelId: definition.id, state: 'downloading', downloadedBytes: downloaded, totalBytes: definition.bytes }); - } - callback(null, chunk); - }, - }); - try { + downloaded = append ? offset : 0; + let lastUpdate = 0; + const progress = new Transform({ + transform: (chunk: Buffer, _encoding, callback) => { + downloaded += chunk.length; + hash.update(chunk); + if (downloaded > definition.bytes) return callback(new Error('The model download exceeded its declared size.')); + const now = Date.now(); + if (now - lastUpdate > 150 || downloaded === definition.bytes) { + lastUpdate = now; + this.emit({ modelId: definition.id, state: 'downloading', downloadedBytes: downloaded, totalBytes: definition.bytes }); + } + callback(null, chunk); + }, + }); await pipeline(Readable.fromWeb(response.body as never), progress, createWriteStream(partial, { flags: append ? 'a' : 'w', mode: 0o600 }), { signal }); if (downloaded !== definition.bytes) throw new Error(`Model download was incomplete (${downloaded} of ${definition.bytes} bytes).`); this.emit({ modelId: definition.id, state: 'verifying', downloadedBytes: downloaded, totalBytes: definition.bytes }); if (hash.digest('hex') !== definition.sha256) throw new Error('Model checksum verification failed. Delete the partial download and try again.'); + signal.throwIfAborted(); await this.installVerified(partial, target, definition); this.logs.write('info', 'speech', `${definition.model} installed and checksum verified.`); } catch (error) { @@ -615,7 +661,7 @@ export class SpeechService { this.emit({ modelId: definition.id, state: 'cancelled', downloadedBytes: downloaded, totalBytes: definition.bytes }); throw new Error('Model download cancelled.'); } - this.emit({ modelId: definition.id, state: 'error', downloadedBytes: downloaded, totalBytes: definition.bytes, error: this.message(error) }); + this.emit({ modelId: definition.id, state: 'error', downloadedBytes: Math.min(downloaded, definition.bytes), totalBytes: definition.bytes, error: this.message(error).slice(0, 1000) || 'Model download failed.' }); throw error; } } @@ -628,9 +674,9 @@ export class SpeechService { this.emit({ modelId: definition.id, state: 'installed', downloadedBytes: definition.bytes, totalBytes: definition.bytes }); } - private async verify(file: string, expected: string): Promise { + private async verify(file: string, expected: string, signal: AbortSignal): Promise { const hash = createHash('sha256'); - await pipeline(createReadStream(file), new Transform({ transform(chunk: Buffer, _encoding, callback) { hash.update(chunk); callback(); } })); + await pipeline(createReadStream(file), new Transform({ transform(chunk: Buffer, _encoding, callback) { hash.update(chunk); callback(); } }), { signal }); return hash.digest('hex') === expected; } @@ -660,25 +706,27 @@ export class SpeechService { this.backendProbe ??= this.runtime().then((runtime) => { const available = runtime.getAvailableBackends(); const gpu = available.find((candidate) => candidate.deviceType === 'gpu' || candidate.deviceType === 'igpu' || candidate.deviceType === 'accel'); + if (!available.length) throw new Error('No speech devices were detected.'); if (!gpu) return { backend: 'CPU', accelerated: false }; const name = gpu.name || gpu.description || gpu.kind; - return gpu.kind === 'vulkan' - ? { backend: `${name} detected · CPU safety mode active`, accelerated: false } - : { backend: name, accelerated: true }; + if (available.some((candidate) => candidate.kind === 'vulkan')) return { backend: `${name} detected · all models use CPU for Vulkan safety`, accelerated: false }; + if (available.some((candidate) => candidate.kind === 'metal')) return { backend: `${name} detected · batch models can use Metal; live models use CPU`, accelerated: true }; + return { backend: `${name} detected · automatic model backend selection`, accelerated: true }; }).catch((error: unknown) => { - this.logs.write('warn', 'speech', `Speech acceleration probe fell back to CPU: ${this.message(error)}`); - return { backend: 'CPU', accelerated: false }; + this.logs.write('warn', 'speech', `Speech runtime unavailable: ${this.message(error)}`); + return { backend: 'Speech runtime unavailable', accelerated: false }; }); return this.backendProbe; } - private async load(definition: SpeechModelDefinition): Promise { + private async load(definition: SpeechModelDefinition, signal: AbortSignal): Promise { if (this.loaded?.id === definition.id) { this.clearUnloadTimer(); return this.loaded.model; } this.unload(); const runtime = await this.runtime(); + signal.throwIfAborted(); try { const backend = this.selectBackend(runtime, definition); const model = await runtime.TranscribeModel.load(this.modelPath(definition), { backend }); @@ -746,7 +794,7 @@ export class SpeechService { } private publicModel(definition: SpeechModelDefinition) { - const { fileName: _fileName, url: _url, sha256: _sha256, streamFamily: _streamFamily, languageMap: _languageMap, ...model } = definition; + const { fileName: _fileName, url: _url, sha256: _sha256, streamFamily: _streamFamily, languageMap: _languageMap, defaultLanguage: _defaultLanguage, ...model } = definition; return model; } diff --git a/src/main/speech/speechModels.ts b/src/main/speech/speechModels.ts index 43d47762..144b1401 100644 --- a/src/main/speech/speechModels.ts +++ b/src/main/speech/speechModels.ts @@ -1,4 +1,4 @@ -import type { SpeechModelId, SpeechModelInfo, SpeechTier } from '../../shared/contracts/ipc'; +import type { SpeechModelId, SpeechModelInfo } from '../../shared/contracts/ipc'; export interface SpeechModelDefinition extends Omit { readonly fileName: string; @@ -13,8 +13,9 @@ export interface SpeechModelDefinition extends Omit>; + readonly defaultLanguage?: string; } /** @@ -37,6 +38,7 @@ export const speechModels: readonly SpeechModelDefinition[] = [ detail: '159 MB · 1.90% WER · English, German, Spanish, French · RTF 21×', bytes: 158_704_320, streaming: false, + defaultLanguage: 'en', fileName: 'canary-180m-flash-Q5_K_M.gguf', url: 'https://huggingface.co/handy-computer/canary-180m-flash-gguf/resolve/b147f9dc52b59f0998e410540a84727bd86457fd/canary-180m-flash-Q5_K_M.gguf', sha256: 'a87992d84aea5329fa5d70f2eb440d3ae4fe47bd774875374ec381472d348299', @@ -50,6 +52,7 @@ export const speechModels: readonly SpeechModelDefinition[] = [ detail: '541 MB · 1.58% WER · English · live · RTF 7.5×', bytes: 540_795_264, streaming: true, + defaultLanguage: 'en', streamFamily: { kind: 'parakeet_buffered' }, fileName: 'parakeet-unified-en-0.6b-Q5_K_M.gguf', url: 'https://huggingface.co/handy-computer/parakeet-unified-en-0.6b-gguf/resolve/7e948f21b7bdbac698d3318db9d350f1096f3b6c/parakeet-unified-en-0.6b-Q5_K_M.gguf', @@ -98,6 +101,7 @@ export const speechModels: readonly SpeechModelDefinition[] = [ detail: '1.56 GB · 1.25% WER · 14 languages · slowest', bytes: 1_558_162_944, streaming: false, + defaultLanguage: 'en', fileName: 'cohere-transcribe-03-2026-Q4_K_M.gguf', url: 'https://huggingface.co/handy-computer/cohere-transcribe-03-2026-gguf/resolve/dfa4adebb64f3076b7b6b90b721275cc069cb421/cohere-transcribe-03-2026-Q4_K_M.gguf', sha256: '0ea56826d8bd5d74b7143a4a04e022dc1bb75452cfae49d98b6acb0c1d16a1fb', @@ -129,7 +133,7 @@ export function speechModel(modelId: SpeechModelId): SpeechModelDefinition { * languageMap (Nemotron needs BCP-47 locales like en-US). */ export function resolveModelLanguage(definition: SpeechModelDefinition, language: string | undefined): string | undefined { if (!language || language === 'auto') { - return definition.languageMap ? undefined : 'en'; + return definition.defaultLanguage; } return definition.languageMap?.[language] ?? language; } diff --git a/src/preload/mediaApi.ts b/src/preload/mediaApi.ts index 53f47fc9..52beb936 100644 --- a/src/preload/mediaApi.ts +++ b/src/preload/mediaApi.ts @@ -8,6 +8,7 @@ import { musicStatusSchema, musicStreamResultSchema, musicTrackInputSchema, + speechAttemptInputSchema, speechCancelResultSchema, speechDownloadProgressSchema, speechHotkeyStatusSchema, @@ -29,12 +30,14 @@ export const mediaApi = { downloadSpeechModel: (modelId) => invoke(ipcChannels.speechDownloadModel, speechModelInputSchema, speechStatusSchema, { modelId }), cancelSpeechModelDownload: (modelId) => invoke(ipcChannels.speechCancelDownload, speechModelInputSchema, speechCancelResultSchema, { modelId }).then((result) => result.cancelled), removeSpeechModel: (modelId) => invoke(ipcChannels.speechRemoveModel, speechModelInputSchema, speechStatusSchema, { modelId }), - transcribeSpeech: (modelId, audio, language) => invoke(ipcChannels.speechTranscribe, speechTranscribeInputSchema, speechTranscriptionSchema, { modelId, audio, language }), - cancelSpeechTranscription: () => invoke(ipcChannels.speechCancel, emptyInputSchema, speechCancelResultSchema).then((result) => result.cancelled), - startSpeechStream: (modelId, language, refine) => invoke(ipcChannels.speechStreamStart, speechStreamStartInputSchema, ignoreResult, { modelId, language, refine }), - feedSpeechStream: (audio) => invoke(ipcChannels.speechStreamFeed, speechStreamFeedInputSchema, ignoreResult, { audio }), - stopSpeechStream: () => invoke(ipcChannels.speechStreamStop, emptyInputSchema, ignoreResult), - cancelSpeechStream: () => invoke(ipcChannels.speechStreamCancel, emptyInputSchema, ignoreResult), + claimSpeechAttempt: (attemptId) => invoke(ipcChannels.speechClaimAttempt, speechAttemptInputSchema, ignoreResult, { attemptId }), + releaseSpeechAttempt: (attemptId) => invoke(ipcChannels.speechReleaseAttempt, speechAttemptInputSchema, ignoreResult, { attemptId }), + transcribeSpeech: (modelId, audio, language, attemptId) => invoke(ipcChannels.speechTranscribe, speechTranscribeInputSchema, speechTranscriptionSchema, { modelId, audio, language, attemptId }), + cancelSpeechTranscription: (attemptId) => invoke(ipcChannels.speechCancel, speechAttemptInputSchema, speechCancelResultSchema, { attemptId }).then((result) => result.cancelled), + startSpeechStream: (modelId, language, refine, attemptId) => invoke(ipcChannels.speechStreamStart, speechStreamStartInputSchema, ignoreResult, { modelId, language, refine, attemptId }), + feedSpeechStream: (audio, attemptId) => invoke(ipcChannels.speechStreamFeed, speechStreamFeedInputSchema, ignoreResult, { audio, attemptId }), + stopSpeechStream: (attemptId) => invoke(ipcChannels.speechStreamStop, speechAttemptInputSchema, ignoreResult, { attemptId }), + cancelSpeechStream: (attemptId) => invoke(ipcChannels.speechStreamCancel, speechAttemptInputSchema, ignoreResult, { attemptId }), getSpeechHotkeyStatus: () => invoke(ipcChannels.speechHotkeyStatus, emptyInputSchema, speechHotkeyStatusSchema), onSpeechDownload: (listener) => subscribe(ipcChannels.speechEvents, speechDownloadProgressSchema, listener), onSpeechStreamUpdate: (listener) => subscribe(ipcChannels.speechStreamEvents, speechStreamUpdateSchema, listener), diff --git a/src/renderer/features/chat/Composer.tsx b/src/renderer/features/chat/Composer.tsx index 4cfccf6a..94e69f9c 100644 --- a/src/renderer/features/chat/Composer.tsx +++ b/src/renderer/features/chat/Composer.tsx @@ -36,6 +36,7 @@ import { agentMentionContext, findLiveAgentMentions, parseAgentStopCommand, sess import { fileTagContext, fileTagText, findFileTags } from './fileTags'; import { findSlashCommands, slashCommandContext, slashCommandDescription, slashCommandLabel, type SlashCommand } from './slashCommands'; import { trimSpeechPcm } from '../../../shared/speechGate'; +import { VoiceDraftRange } from './voiceDraft'; import { VoiceStreamFeedQueue, startVoiceStream, type VoiceStreamController } from './voiceStream'; import { ProviderConnectDialog } from '../../components/ProviderConnectDialog'; import { modelIdentity, visibleModels } from '../../../shared/modelVisibility'; @@ -168,6 +169,7 @@ const MIN_COMPOSER_INPUT_HEIGHT = 53; const COMPACT_MIN_COMPOSER_INPUT_HEIGHT = 36; const COMPOSER_RESIZE_STEP = 18; const MAX_VOICE_DURATION_MS = 180_000; +const FINAL_UPDATE_GRACE_MS = 2_000; /** Live-stream feed chunk size (300 ms of 16 kHz mono = 4 800 samples). The * backend's buffered-stream window (PARAKEET_BUFFERED_WINDOW_MS) is separate * and model-constrained; this only sizes mic captures. */ @@ -177,8 +179,12 @@ const STREAM_CHUNK_SAMPLES = 16_000 * 0.3; const VOICE_LAG_WARN_SECONDS = 5; const afterNextPaint = () => new Promise((resolve) => requestAnimationFrame(() => resolve())); type VoiceState = 'idle' | 'preparing' | 'downloading' | 'recording' | 'transcribing'; -type VoiceInsertionTarget = { start: number; end: number; scrollTop: number; sessionId: string | null; projectPath: string | null }; -type ActiveRecording = { recorder: MediaRecorder; stream: MediaStream; chunks: Blob[]; timeout: number; cancelled: boolean; insertion: VoiceInsertionTarget; attempt: number }; +type VoiceAttempt = { + id: string; live: boolean; hotkey: boolean; draftKey: string | null; sessionId: string | null; projectPath: string | null; + range: VoiceDraftRange; rendererLag: boolean; backendLag: boolean; +}; +type ActiveRecording = { recorder: MediaRecorder; stream: MediaStream; chunks: Blob[]; timeout: number; cancelled: boolean; attempt: VoiceAttempt }; +const voiceSendReason = 'Wait for voice input to finish, then review your draft and send it.'; const thinkingLabel = (level: string) => level === 'xhigh' ? 'Extra high' : level.charAt(0).toUpperCase() + level.slice(1); export function clampComposerInputHeight(contentHeight: number, maximum: number, minimum = MIN_COMPOSER_INPUT_HEIGHT): number { return Math.min(Math.max(minimum, maximum), Math.max(minimum, Math.ceil(contentHeight))); @@ -687,7 +693,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: const historyMutation = useRef(false); const promptOptimizationCancelled = useRef(false); const promptOptimizationEpoch = useRef(0); - const pendingDraftSelection = useRef<{ key: string | null; text: string; start: number; end: number; scrollTop: number; focus?: boolean } | null>(null); + const pendingDraftSelection = useRef<{ key: string | null; text: string; start: number; end: number; scrollTop: number; focus?: boolean; direction?: 'forward' | 'backward' | 'none' } | null>(null); const forkNoticeRef = useRef(forkNotice); const caretPositionRef = useRef(caretPosition); const selectionEndRef = useRef(caretPosition); @@ -700,13 +706,9 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: const thinkingQueue = useRef<{ running: boolean; next: typeof thinkingLevels[number] | null }>({ running: false, next: null }); const permissionBusyRef = useRef(false); const forkingRef = useRef(false); - const voiceRestoreFrames = useRef(new Set()); - const voiceAttempt = useRef(0); + const voiceAttempt = useRef(null); const voiceStateRef = useRef('idle'); - const voiceSelectionKey = useRef(null); - const liveRecording = useRef<{ controller: VoiceStreamController; feedQueue: VoiceStreamFeedQueue; attempt: number } | null>(null); - const liveAnchorRef = useRef(null); - const liveSpanLenRef = useRef(0); + const liveRecording = useRef<{ controller: VoiceStreamController; feedQueue: VoiceStreamFeedQueue; attempt: VoiceAttempt; timeout: number; stopping: boolean; stopDone: boolean; finalSeen: boolean } | null>(null); const mounted = useRef(true); const runtime = useRuntimeStore(useShallow((state) => ({ status: state.runtime.status, @@ -958,38 +960,48 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: useUiStore.getState().setVoiceCapturing(next === 'recording'); if (mounted.current) setVoiceState(next); }, []); - const isCurrentVoiceAttempt = useCallback((attempt: number) => mounted.current && voiceAttempt.current === attempt, []); - - /** Replace the live-transcription span (anchored at liveAnchorRef) with the latest - * committed text. The span grows as Parakeet stabilizes words, giving the - * type-as-you-speak effect without rewriting anything the user typed outside it. */ - const applyLiveText = useCallback((committed: string) => { - const anchor = liveAnchorRef.current; - if (anchor === null || !mounted.current) return; - const text = committed.trim(); - const current = draftRef.current; - const before = current.slice(0, anchor); - const after = current.slice(anchor + liveSpanLenRef.current); - const leading = before && !/\s$/u.test(before) ? ' ' : ''; - const insertion = `${leading}${text}`; - liveSpanLenRef.current = insertion.length; - updateDraft(`${before}${insertion}${after}`); - const caret = anchor + insertion.length; - setCaretPosition(caret); + const isCurrentVoiceAttempt = useCallback((attempt: VoiceAttempt) => mounted.current && voiceAttempt.current === attempt, []); + const applyVoiceText = useCallback((attempt: VoiceAttempt, committed: string) => { const input = textarea.current; - if (input) { input.focus({ preventScroll: true }); input.setSelectionRange(caret, caret); } - }, [updateDraft]); - - const teardownLiveRecording = () => { - const recording = liveRecording.current; - if (recording) { + const runtimeNow = useRuntimeStore.getState().runtime; + if (!input || !isCurrentVoiceAttempt(attempt) || activeDraftKey.current !== attempt.draftKey + || runtimeNow.sessionId !== attempt.sessionId || (runtimeNow.project?.path ?? null) !== attempt.projectPath) return; + const pending = input.value !== draftRef.current && pendingDraftSelection.current?.text === draftRef.current ? pendingDraftSelection.current : null; + const next = attempt.range.apply(committed, pending?.start ?? input.selectionStart, pending?.end ?? input.selectionEnd); + if (!next || next.text === draftRef.current) return; + pendingDraftSelection.current = { ...next, key: attempt.draftKey, scrollTop: pending?.scrollTop ?? input.scrollTop, direction: pending?.direction ?? input.selectionDirection }; + updateDraftForKey(attempt.draftKey, next.text); + setCaretPosition(next.start); + }, [isCurrentVoiceAttempt, updateDraftForKey]); + + const endVoiceAttempt = useCallback((attempt: VoiceAttempt, cancel = false) => { + if (voiceAttempt.current !== attempt) return; + voiceAttempt.current = null; + const live = liveRecording.current; + if (live?.attempt === attempt) { liveRecording.current = null; - recording.feedQueue.cancel(); - void Promise.resolve(recording.controller.stop()).catch(() => undefined); + window.clearTimeout(live.timeout); + live.feedQueue.cancel(); + if (!live.stopping) void Promise.resolve(live.controller.stop()).catch(() => undefined); } - liveAnchorRef.current = null; - liveSpanLenRef.current = 0; - }; + const batch = activeRecording.current; + if (batch?.attempt === attempt) { + activeRecording.current = null; + batch.cancelled = true; + window.clearTimeout(batch.timeout); + batch.stream.getTracks().forEach((track) => track.stop()); + if (batch.recorder.state !== 'inactive') batch.recorder.stop(); + batch.chunks.length = 0; + } + const desktop = getDesktopApiOptional(); + if (cancel) { + if (attempt.live) void desktop?.cancelSpeechStream?.(attempt.id).catch(() => undefined); + else void desktop?.cancelSpeechTranscription?.(attempt.id).catch(() => undefined); + } + void desktop?.releaseSpeechAttempt?.(attempt.id).catch(() => undefined); + if (mounted.current) setVoiceLag(false); + updateVoiceState('idle'); + }, [updateVoiceState]); const commandContext = slashCommandContext(editorDraft, caretPosition); const commandQuery = commandContext?.query ?? null; @@ -1034,6 +1046,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: useLayoutEffect(() => { const synchronize = (key: string, next: SessionDraft) => { if (activeDraftKey.current !== key) return; + if (voiceAttempt.current?.draftKey === key) voiceAttempt.current.range.rebase(next.text); draftRef.current = next.text; draftRevision.current = next.textRevision; imagesRef.current = next.images; @@ -1126,7 +1139,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: const input = textarea.current; if (!pending || !input || pending.key !== activeDraftKey.current || input.value !== pending.text) return; if (pending.focus) input.focus({ preventScroll: true }); - input.setSelectionRange(pending.start, pending.end); + input.setSelectionRange(pending.start, pending.end, pending.direction); input.scrollTop = pending.scrollTop; caretPositionRef.current = pending.start; selectionEndRef.current = pending.end; @@ -1283,111 +1296,21 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: mounted.current = true; return () => { mounted.current = false; - voiceAttempt.current += 1; - voiceStateRef.current = 'idle'; - useUiStore.getState().setVoiceCapturing(false); + if (voiceAttempt.current) endVoiceAttempt(voiceAttempt.current, true); resizeCleanup.current?.(); submittingRef.current = false; queueBusyRef.current = false; modelBusyRef.current = false; permissionBusyRef.current = false; forkingRef.current = false; - for (const frame of voiceRestoreFrames.current) cancelAnimationFrame(frame); - voiceRestoreFrames.current.clear(); - teardownLiveRecording(); - const recording = activeRecording.current; - if (recording) { - recording.cancelled = true; - window.clearTimeout(recording.timeout); - recording.stream.getTracks().forEach((track) => track.stop()); - if (recording.recorder.state !== 'inactive') recording.recorder.stop(); - recording.chunks.length = 0; - activeRecording.current = null; - } - if (Boolean(getFateApiOptional()) && typeof getDesktopApiOptional()?.cancelSpeechTranscription === 'function') { - void getDesktopApi().cancelSpeechTranscription().catch(() => undefined); - } - if (Boolean(getFateApiOptional()) && typeof getDesktopApiOptional()?.cancelSpeechStream === 'function') { - void getDesktopApi().cancelSpeechStream().catch(() => undefined); - } }; - }, []); + }, [endVoiceAttempt]); - useEffect(() => { - const selectionKey = `${runtime.project?.path ?? ''}\u0000${runtime.sessionId ?? ''}`; - if (voiceSelectionKey.current === null) { - voiceSelectionKey.current = selectionKey; - return; - } - if (voiceSelectionKey.current === selectionKey) return; - voiceSelectionKey.current = selectionKey; - if (voiceStateRef.current === 'idle') return; - voiceAttempt.current += 1; - teardownLiveRecording(); - const recording = activeRecording.current; - if (recording) { - recording.cancelled = true; - window.clearTimeout(recording.timeout); - recording.stream.getTracks().forEach((track) => track.stop()); - activeRecording.current = null; - if (recording.recorder.state !== 'inactive') recording.recorder.stop(); - recording.chunks.length = 0; - } - updateVoiceState('idle'); - if (Boolean(getFateApiOptional()) && typeof getDesktopApiOptional()?.cancelSpeechTranscription === 'function') { - void getDesktopApi().cancelSpeechTranscription().catch(() => undefined); - } - if (Boolean(getFateApiOptional()) && typeof getDesktopApiOptional()?.cancelSpeechStream === 'function') { - void getDesktopApi().cancelSpeechStream().catch(() => undefined); - } - }, [runtime.project?.path, runtime.sessionId, updateVoiceState]); - - // Live transcription updates: committed text writes straight into the input box. - useEffect(() => { - if (!hasCapability('microphone') || typeof getDesktopApiOptional()?.onSpeechStreamUpdate !== 'function') return; - return getDesktopApi().onSpeechStreamUpdate((update: SpeechStreamUpdate) => { - if (update.state === 'active' || update.state === 'final') { - if (update.state === 'active' && !update.committed.trim() && liveSpanLenRef.current > 0) { - setVoiceLag((update.backlogSeconds ?? 0) >= VOICE_LAG_WARN_SECONDS); - return; - } - applyLiveText(update.committed); - setVoiceLag(update.state === 'active' && (update.backlogSeconds ?? 0) >= VOICE_LAG_WARN_SECONDS); - } else if (update.state === 'finalizing') { - // Input is closed: stop was pressed, or the main process sealed the - // stream at the three-minute limit. Stop the microphone; the finished - // text arrives with the final update. - setVoiceLag(false); - if (voiceStateRef.current === 'recording') void stopLiveRecording(); - } else if (update.state === 'error') { - // Keep every word the user already saw before reporting the failure. - if (update.committed) applyLiveText(update.committed); - setVoiceLag(false); - teardownLiveRecording(); - if (voiceStateRef.current !== 'idle') updateVoiceState('idle'); - setComposerError(update.error ?? 'Live transcription failed.'); - } else if (update.state === 'cancelled') { - setVoiceLag(false); - teardownLiveRecording(); - if (voiceStateRef.current !== 'idle') updateVoiceState('idle'); - } - }); - // stopLiveRecording is a stable closure over refs + state setters, matching - // the voice hotkey effect below. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [applyLiveText, updateVoiceState]); + useLayoutEffect(() => { + const attempt = voiceAttempt.current; + if (attempt && (attempt.draftKey !== activeSessionDraftKey || attempt.sessionId !== runtime.sessionId || attempt.projectPath !== (runtime.project?.path ?? null))) endVoiceAttempt(attempt, true); + }, [activeSessionDraftKey, runtime.project?.path, runtime.sessionId, endVoiceAttempt]); - // Global voice hotkey (registered by the main process): start/stop from anywhere. - useEffect(() => { - if (!hasCapability('hotkeys') || !hasCapability('microphone') || typeof getDesktopApiOptional()?.onVoiceHotkey !== 'function') return; - return getDesktopApi().onVoiceHotkey((event) => { - if (event.source !== 'hotkey') return; - if (event.action === 'start') { if (voiceStateRef.current === 'idle') void startVoiceRecording(); } - else { if (voiceStateRef.current === 'recording') stopVoiceRecording(); } - }); - // startVoiceRecording/stopVoiceRecording are stable closures over refs + state setters. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); useEffect(() => { if (!compactToolbar) setUtilityMenuOpen(false); @@ -1440,6 +1363,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: }; const submit = async (behavior: PromptInput['behavior']) => { + if (voiceStateRef.current !== 'idle') return; const runtimeNow = useRuntimeStore.getState().runtime; const originDraftKey = sessionDraftKey(runtimeNow.project?.path ?? null, runtimeNow.sessionId, runtimeNow.sessions); const submittedDraft = draftRef.current; @@ -1455,6 +1379,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: || (submittedBrowserAnnotationIds.length > 0 ? 'Address the attached browser annotations.' : ''); if (/^\/login(?:\s+.*)?$/iu.test(text)) { if (optimizingPromptRef.current) await flushPromptOptimizationForSend(); + if (voiceAttempt.current) return; void openProviderLogin(); updateDraft(''); return; @@ -1462,6 +1387,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: const logout = /^\/logout\s+([^\s/]+)\s*$/iu.exec(text); if (logout && Boolean(getFateApiOptional())) { if (optimizingPromptRef.current) await flushPromptOptimizationForSend(); + if (voiceAttempt.current) return; updateDraft(''); void getDesktopApi().logoutProvider(logout[1]!).then((state) => useRuntimeStore.getState().setRuntime(state)).catch((error: unknown) => { if (mounted.current) setComposerError(error instanceof Error ? error.message : 'The provider could not be signed out.'); @@ -1470,6 +1396,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: } if (/^\/logout\s*$/iu.test(text)) { if (optimizingPromptRef.current) await flushPromptOptimizationForSend(); + if (voiceAttempt.current) return; setProviderLoginOpen(true); updateDraft(''); return; @@ -1512,6 +1439,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: }; try { if (optimizingPromptRef.current) await flushPromptOptimizationForSend(); + if (voiceAttempt.current) return; const goalCommand = parseGoalMaxCommand(text); if (goalCommand) { if (submittedImages.length > 0 || submittedBrowserAnnotationIds.length > 0 || submittedSessionReferences.length > 0) throw new Error('Remove image, browser annotation, and session attachments before using GoalMax commands.'); @@ -1681,6 +1609,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: }; const sendLiveAgentMessage = async () => { + if (voiceStateRef.current !== 'idle') return; const target = liveAgentTarget; const message = draftRef.current.trim(); if (!target || !message || liveAgentBusy || !getFateApiOptional()) return; @@ -1695,6 +1624,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: const origin = useRuntimeStore.getState().runtime; try { if (optimizingPromptRef.current) await flushPromptOptimizationForSend(); + if (voiceAttempt.current) return; let state; if (target.kind === 'team-node') { if (typeof getFateApiOptional()?.controlAgentTeam !== 'function') throw new Error('Restart Fate UI to message Agent Team sessions.'); @@ -1789,6 +1719,10 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: const shouldSend = sendMessageWithModifier ? modifierPressed : !event.shiftKey && !event.altKey; + if (event.key === 'Enter' && shouldSend && voiceStateRef.current !== 'idle') { + event.preventDefault(); + return; + } if (event.key === 'Enter' && shouldSend && liveAgentTarget && liveAgentTarget.kind !== 'session') { event.preventDefault(); void sendLiveAgentMessage(); @@ -2042,36 +1976,28 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: }; }, [addImageFiles]); - const startLiveRecording = async () => { - const runtimeNow = useRuntimeStore.getState().runtime; - if (!hasCapability('microphone') || !speech.enabled || speechDownload || voiceStateRef.current !== 'idle' || runtimeNow.status !== 'ready' || !getFateApiOptional()) return; - const attempt = voiceAttempt.current + 1; - voiceAttempt.current = attempt; - const input = textarea.current; - liveAnchorRef.current = input ? Math.max(0, input.selectionStart ?? draftRef.current.length) : draftRef.current.length; - liveSpanLenRef.current = 0; - updateVoiceState('preparing'); - setComposerError(null); + const startLiveRecording = async (attempt: VoiceAttempt) => { let feedQueue: VoiceStreamFeedQueue | null = null; try { if (typeof getDesktopApiOptional()?.startSpeechStream !== 'function') throw new Error('Restart Fate UI to activate live transcription.'); - await afterNextPaint(); - if (!isCurrentVoiceAttempt(attempt)) return; - updateVoiceState('downloading'); - await getDesktopApi().ensureSpeechModel(speech.modelId); - if (!isCurrentVoiceAttempt(attempt)) return; - updateVoiceState('preparing'); - await getDesktopApi().startSpeechStream(speech.modelId, speech.language === 'auto' ? undefined : speech.language, speech.finalAccuracyPass); - if (!isCurrentVoiceAttempt(attempt)) { await getDesktopApi().cancelSpeechStream().catch(() => undefined); return; } + await getDesktopApi().startSpeechStream(speech.modelId, speech.language === 'auto' ? undefined : speech.language, speech.finalAccuracyPass, attempt.id); + if (!isCurrentVoiceAttempt(attempt)) { + void getDesktopApiOptional()?.cancelSpeechStream?.(attempt.id).catch(() => undefined); + return; + } feedQueue = new VoiceStreamFeedQueue( - (audio) => getDesktopApi().feedSpeechStream(audio), + (audio) => getDesktopApi().feedSpeechStream(audio, attempt.id), (error) => { if (!isCurrentVoiceAttempt(attempt)) return; feedQueue?.cancel(); - teardownLiveRecording(); - void getDesktopApi().cancelSpeechStream().catch(() => undefined); setComposerError(error instanceof Error ? error.message : 'Live transcription failed.'); - updateVoiceState('idle'); + endVoiceAttempt(attempt, true); + }, + undefined, + (seconds: number) => { + if (!isCurrentVoiceAttempt(attempt)) return; + attempt.rendererLag = seconds >= VOICE_LAG_WARN_SECONDS; + setVoiceLag(attempt.rendererLag || attempt.backendLag); }, ); const controller = await startVoiceStream(speech.inputDeviceId, STREAM_CHUNK_SAMPLES, (pcm) => { @@ -2083,83 +2009,52 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: if (!isCurrentVoiceAttempt(attempt)) { feedQueue.cancel(); void Promise.resolve(controller.stop()).catch(() => undefined); - await getDesktopApi().cancelSpeechStream().catch(() => undefined); return; } - liveRecording.current = { controller, feedQueue, attempt }; + const timeout = window.setTimeout(() => { + if (isCurrentVoiceAttempt(attempt)) void stopLiveRecording(attempt); + }, MAX_VOICE_DURATION_MS); + liveRecording.current = { controller, feedQueue, attempt, timeout, stopping: false, stopDone: false, finalSeen: false }; updateVoiceState('recording'); } catch (error) { feedQueue?.cancel(); - teardownLiveRecording(); - await getDesktopApi().cancelSpeechStream().catch(() => undefined); if (isCurrentVoiceAttempt(attempt)) { setComposerError(error instanceof Error ? error.message : 'Could not start live transcription.'); - updateVoiceState('idle'); + endVoiceAttempt(attempt, true); } } }; - const stopLiveRecording = async () => { + const stopLiveRecording = useCallback(async (attempt: VoiceAttempt) => { const recording = liveRecording.current; - if (!recording) return; - liveRecording.current = null; - if (voiceStateRef.current === 'recording') updateVoiceState('transcribing'); - try { await recording.controller.stop(); } catch { /* best-effort teardown */ } + if (recording?.attempt !== attempt || recording.stopping) return; + recording.stopping = true; + window.clearTimeout(recording.timeout); + updateVoiceState('transcribing'); try { + await recording.controller.stop(); + if (!isCurrentVoiceAttempt(attempt)) return; await recording.feedQueue.closeAndDrain(); - await getDesktopApi().stopSpeechStream(); - } catch (error) { - if (isCurrentVoiceAttempt(recording.attempt)) setComposerError(error instanceof Error ? error.message : 'Live transcription failed to finalize.'); - } finally { - if (isCurrentVoiceAttempt(recording.attempt)) { - liveAnchorRef.current = null; - liveSpanLenRef.current = 0; - updateVoiceState('idle'); + if (!isCurrentVoiceAttempt(attempt)) return; + await getDesktopApi().stopSpeechStream(attempt.id); + if (!isCurrentVoiceAttempt(attempt)) return; + recording.stopDone = true; + if (recording.finalSeen) endVoiceAttempt(attempt); + else { + const missingFinal = () => { + if (!isCurrentVoiceAttempt(attempt)) return; + setComposerError('The final transcript did not arrive. Review the captured words before sending.'); + endVoiceAttempt(attempt); + }; + if (typeof getDesktopApiOptional()?.onSpeechStreamUpdate === 'function') recording.timeout = window.setTimeout(missingFinal, FINAL_UPDATE_GRACE_MS); + else missingFinal(); } + } catch (error) { + if (!isCurrentVoiceAttempt(attempt)) return; + setComposerError(error instanceof Error ? error.message : 'Live transcription could not finish capturing the microphone audio.'); + endVoiceAttempt(attempt, true); } - }; - - const insertTranscript = (transcript: string, target: VoiceInsertionTarget) => { - const text = transcript.trim(); - if (!text) throw new Error('The voice model returned no text. Try speaking a bit longer, then stop.'); - const current = draftRef.current; - const selectionStart = Number.isFinite(target.start) ? Math.max(0, target.start) : current.length; - const selectionEnd = Number.isFinite(target.end) ? Math.max(selectionStart, target.end) : selectionStart; - const start = Math.min(current.length, selectionStart); - const end = Math.min(current.length, Math.max(start, selectionEnd)); - const before = current.slice(0, start); - const after = current.slice(end); - const leading = before && !/\s$/u.test(before) ? ' ' : ''; - const trailing = after && !/^\s/u.test(after) ? ' ' : ''; - const insertion = `${leading}${text}${trailing}`; - const nextCaret = start + insertion.length; - const nextDraft = `${before}${insertion}${after}`; - updateDraft(nextDraft); - setCaretPosition(nextCaret); - - const scheduleRestore = (callback: () => void) => { - let frame = 0; - frame = requestAnimationFrame(() => { - voiceRestoreFrames.current.delete(frame); - callback(); - }); - voiceRestoreFrames.current.add(frame); - }; - const restoreViewport = () => { - const input = textarea.current; - if (!input || !mounted.current) return; - input.focus({ preventScroll: true }); - input.setSelectionRange(nextCaret, nextCaret); - input.scrollTop = Math.max(0, target.scrollTop); - syncInputFades(); - }; - scheduleRestore(() => { - restoreViewport(); - // Auto-sizing and focus can each adjust the textarea viewport. A second - // paint deterministically restores the viewport after both layout passes. - scheduleRestore(restoreViewport); - }); - }; + }, [isCurrentVoiceAttempt, updateVoiceState, endVoiceAttempt]); const finishVoiceRecording = async (recording: ActiveRecording) => { window.clearTimeout(recording.timeout); @@ -2167,8 +2062,8 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: if (activeRecording.current === recording) activeRecording.current = null; const targetSelectionIsCurrent = () => { const current = useRuntimeStore.getState().runtime; - return current.sessionId === recording.insertion.sessionId - && (current.project?.path ?? null) === recording.insertion.projectPath; + return current.sessionId === recording.attempt.sessionId + && (current.project?.path ?? null) === recording.attempt.projectPath; }; if (recording.cancelled || !isCurrentVoiceAttempt(recording.attempt)) { recording.chunks.length = 0; @@ -2176,7 +2071,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: } if (!targetSelectionIsCurrent()) { recording.chunks.length = 0; - updateVoiceState('idle'); + endVoiceAttempt(recording.attempt, true); return; } updateVoiceState('transcribing'); @@ -2201,47 +2096,50 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: if (spoken.length === 0) throw new Error('No speech was detected. Try again closer to the microphone.'); const audio = spoken.buffer.slice(spoken.byteOffset, spoken.byteOffset + spoken.byteLength) as ArrayBuffer; if (!getFateApiOptional() || typeof getDesktopApiOptional()?.transcribeSpeech !== 'function') throw new Error('Voice transcription is unavailable.'); - const result = await getDesktopApi().transcribeSpeech(speech.modelId, audio, speech.language === 'auto' ? undefined : speech.language); + const result = await getDesktopApi().transcribeSpeech(speech.modelId, audio, speech.language === 'auto' ? undefined : speech.language, recording.attempt.id); if (recording.cancelled || !isCurrentVoiceAttempt(recording.attempt) || !targetSelectionIsCurrent()) return; - insertTranscript(result.text, recording.insertion); + if (!result.text.trim()) throw new Error('The voice model returned no text. Try speaking a bit longer, then stop.'); + applyVoiceText(recording.attempt, result.text); } catch (error) { if (!recording.cancelled && isCurrentVoiceAttempt(recording.attempt)) { setComposerError(error instanceof Error ? error.message : 'Voice transcription failed.'); } } finally { - if (isCurrentVoiceAttempt(recording.attempt)) updateVoiceState('idle'); + endVoiceAttempt(recording.attempt); } }; const stopVoiceRecording = () => { - if (liveRecording.current) { void stopLiveRecording(); return; } + if (liveRecording.current) { void stopLiveRecording(liveRecording.current.attempt); return; } const recording = activeRecording.current; if (!recording || recording.recorder.state === 'inactive') return; updateVoiceState('transcribing'); recording.recorder.stop(); }; - const startVoiceRecording = async () => { - if (!hasCapability('microphone')) return; - if (isLiveModel) return startLiveRecording(); + const startVoiceRecording = async (hotkey = false) => { const runtimeNow = useRuntimeStore.getState().runtime; - if (!speech.enabled || speechDownload || voiceStateRef.current !== 'idle' || runtimeNow.status !== 'ready' || !getFateApiOptional()) return; - const attempt = voiceAttempt.current + 1; - voiceAttempt.current = attempt; + if (!hasCapability('microphone') || !speech.enabled || speechDownload || voiceAttempt.current || runtimeNow.status !== 'ready' || !getFateApiOptional() + || submittingRef.current || liveAgentBusy || optimizingPromptRef.current) return; const input = textarea.current; - const selectionStart = input?.selectionStart ?? draftRef.current.length; - const insertion: VoiceInsertionTarget = { - start: selectionStart, - end: input?.selectionEnd ?? selectionStart, - scrollTop: Math.max(0, input?.scrollTop ?? 0), - sessionId: runtimeNow.sessionId, - projectPath: runtimeNow.project?.path ?? null, + const start = input?.selectionStart ?? draftRef.current.length; + const attempt: VoiceAttempt = { + id: crypto.randomUUID(), live: isLiveModel, hotkey, draftKey: activeDraftKey.current, + sessionId: runtimeNow.sessionId, projectPath: runtimeNow.project?.path ?? null, + range: new VoiceDraftRange(draftRef.current, start, input?.selectionEnd ?? start), rendererLag: false, backendLag: false, }; + voiceAttempt.current = attempt; updateVoiceState('preparing'); setComposerError(null); let acquiredStream: MediaStream | null = null; try { - if (!navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === 'undefined') throw new Error('Microphone recording is not supported on this system.'); + const desktop = getDesktopApi(); + await desktop.claimSpeechAttempt?.(attempt.id); + if (!isCurrentVoiceAttempt(attempt)) { + void desktop.releaseSpeechAttempt?.(attempt.id).catch(() => undefined); + return; + } + if (!attempt.live && (!navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === 'undefined')) throw new Error('Microphone recording is not supported on this system.'); if (typeof getDesktopApiOptional()?.ensureSpeechModel !== 'function') throw new Error('Restart Fate UI to activate voice model preparation.'); // Paint the pressed state before native/filesystem work without delaying by an arbitrary timeout. await afterNextPaint(); @@ -2250,6 +2148,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: await getDesktopApi().ensureSpeechModel(speech.modelId); if (!isCurrentVoiceAttempt(attempt)) return; updateVoiceState('preparing'); + if (attempt.live) return await startLiveRecording(attempt); // Keep the device's native format so capture does not reconfigure shared audio hardware. const audioConstraints: MediaTrackConstraints = { echoCancellation: true, @@ -2279,7 +2178,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: return; } const recorder = new MediaRecorder(stream); - const recording: ActiveRecording = { recorder, stream, chunks: [], timeout: 0, cancelled: false, insertion, attempt }; + const recording: ActiveRecording = { recorder, stream, chunks: [], timeout: 0, cancelled: false, attempt }; recorder.addEventListener('dataavailable', (event) => { if (!recording.cancelled && isCurrentVoiceAttempt(attempt) && event.data.size > 0) recording.chunks.push(event.data); }); @@ -2293,7 +2192,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: if (activeRecording.current === recording) activeRecording.current = null; if (isCurrentVoiceAttempt(attempt)) { setComposerError('The microphone stopped unexpectedly.'); - updateVoiceState('idle'); + endVoiceAttempt(attempt, true); } }, { once: true }); recording.timeout = window.setTimeout(() => { @@ -2315,11 +2214,51 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: } if (isCurrentVoiceAttempt(attempt)) { setComposerError(error instanceof Error ? error.message : 'Could not start voice transcription.'); - updateVoiceState('idle'); + endVoiceAttempt(attempt, true); } } }; + useEffect(() => { + if (!hasCapability('microphone') || typeof getDesktopApiOptional()?.onSpeechStreamUpdate !== 'function') return; + return getDesktopApi().onSpeechStreamUpdate((update: SpeechStreamUpdate) => { + const attempt = voiceAttempt.current; + if (!attempt?.live || update.attemptId !== attempt.id) return; + if (update.state !== 'cancelled') applyVoiceText(attempt, update.committed); + if (update.state === 'active') { + attempt.backendLag = (update.backlogSeconds ?? 0) >= VOICE_LAG_WARN_SECONDS; + setVoiceLag(attempt.rendererLag || attempt.backendLag); + } else if (update.state === 'finalizing') { + void stopLiveRecording(attempt); + } else if (update.state === 'error') { + setComposerError(update.error ?? 'Live transcription failed.'); + endVoiceAttempt(attempt, true); + } else if (update.state === 'cancelled') { + endVoiceAttempt(attempt); + } else if (update.state === 'final') { + const recording = liveRecording.current; + if (!recording?.stopping || recording.stopDone) endVoiceAttempt(attempt); + else recording.finalSeen = true; + } + }); + }, [applyVoiceText, endVoiceAttempt, stopLiveRecording]); + + const hotkeyActions = useRef({ startVoiceRecording, stopVoiceRecording }); + useLayoutEffect(() => { hotkeyActions.current = { startVoiceRecording, stopVoiceRecording }; }); + useEffect(() => { + if (!hasCapability('hotkeys') || !hasCapability('microphone') || typeof getDesktopApiOptional()?.onVoiceHotkey !== 'function') return; + return getDesktopApi().onVoiceHotkey((event) => { + if (event.source !== 'hotkey') return; + const attempt = voiceAttempt.current; + if (!attempt) { + if (event.action !== 'stop') void hotkeyActions.current.startVoiceRecording(true); + } else if (event.action === 'toggle' || event.action === 'stop' && attempt.hotkey) { + if (voiceStateRef.current === 'recording') hotkeyActions.current.stopVoiceRecording(); + else if (voiceStateRef.current === 'preparing' || voiceStateRef.current === 'downloading') endVoiceAttempt(attempt, true); + } + }); + }, [endVoiceAttempt]); + const mutateQueuedMessage = async (id: string, action: QueueMutationInput['action']) => { if (!getFateApiOptional() || queueBusyRef.current) return; if (action === 'edit' && (draftRef.current.trim() || imagesRef.current.length > 0 || browserAnnotationIdsRef.current.length > 0 || sessionReferencesRef.current.length > 0)) { @@ -2804,7 +2743,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: }} inputRef={textarea} inputShellRef={inputShell} inputPrefix={} input={{ - id: 'pi-composer', 'aria-label': 'Message Pi', + id: 'pi-composer', 'aria-label': 'Message Pi', 'aria-describedby': voiceState !== 'idle' ? 'voice-send-instructions' : undefined, 'aria-controls': resourceMenuOpen ? 'file-tag-suggestions' : mentionMenuOpen ? 'agent-suggestions' : slashMenuOpen ? 'slash-suggestions' : undefined, 'aria-expanded': resourceMenuOpen || mentionMenuOpen || slashMenuOpen, 'aria-autocomplete': 'list', 'aria-activedescendant': resourceMenuOpen && resourceSuggestions.length > 0 @@ -2841,9 +2780,9 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: }} action={{ label: liveAgentMessageTarget ? 'Send message to live agent' : sendButtonStops ? goalCancelable ? 'Cancel goal' : 'Stop Pi' : runtime.streaming || runtime.activeSessionRunning ? 'Queue follow-up message' : 'Send message', - disabled: agentTurnedOff || (!connected && runtime.status !== 'auth-required') || liveAgentBusy || (!runtime.streaming && submitting) || (!liveAgentMessageTarget && !runtime.streaming && !activeSessionRunning && !goalCancelable && !childWorkActive && !hasPendingPrompt), + disabled: (voiceState !== 'idle' && !sendButtonStops) || agentTurnedOff || (!connected && runtime.status !== 'auth-required') || liveAgentBusy || (!runtime.streaming && submitting) || (!liveAgentMessageTarget && !runtime.streaming && !activeSessionRunning && !goalCancelable && !childWorkActive && !hasPendingPrompt), attributes: { className: 'send-button', 'data-mode': sendButtonStops ? 'stop' : 'send', - 'aria-describedby': sendButtonStops ? 'streaming-send-instructions' : undefined, 'aria-busy': submitting || liveAgentBusy }, + 'aria-describedby': sendButtonStops ? 'streaming-send-instructions' : voiceState !== 'idle' ? 'voice-send-instructions' : undefined, 'aria-busy': submitting || liveAgentBusy }, content: {submitting && !runtime.streaming ? : sendButtonStops ? , }} submitKey={sendMessageWithModifier ? 'modifier-enter' : 'enter'} @@ -3209,8 +3148,9 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: )} + {voiceState !== 'idle' && {voiceSendReason}} {sendButtonStops && Click to {goalCancelable ? 'cancel the persistent goal and stop its work' : 'stop Pi'}.} - + {sendAction} @@ -3220,6 +3160,7 @@ function DesktopComposer({ onOpenProject, connectRequest = 0 }: { onOpenProject: } + {voiceLag && voiceState === 'recording' &&

Live transcription is falling behind. Stop recording to let it catch up.

} {composerError &&

{composerError}

} { if (!open) setPreviewImage(null); }}> diff --git a/src/renderer/features/chat/ComposerVoice.test.tsx b/src/renderer/features/chat/ComposerVoice.test.tsx index 97abb190..fa8ffc0a 100644 --- a/src/renderer/features/chat/ComposerVoice.test.tsx +++ b/src/renderer/features/chat/ComposerVoice.test.tsx @@ -80,10 +80,10 @@ describe('Composer voice input', () => { video: false, }); expect(window.piDesktop.ensureSpeechModel).toHaveBeenCalledWith('canary-flash'); - expect(window.piDesktop.transcribeSpeech).toHaveBeenCalledWith('canary-flash', expect.any(ArrayBuffer), undefined); + expect(window.piDesktop.transcribeSpeech).toHaveBeenCalledWith('canary-flash', expect.any(ArrayBuffer), undefined, expect.any(String)); }); - it('inserts at the initiation selection and restores its scroll viewport after asynchronous transcription', async () => { + it('inserts at the initiation selection and preserves the latest viewport and caret after asynchronous transcription', async () => { let resolveTranscript: ((value: { text: string; language: string; backend: string; accelerated: boolean }) => void) | undefined; const transcribeSpeech = vi.fn(() => new Promise<{ text: string; language: string; backend: string; accelerated: boolean }>((resolve) => { resolveTranscript = resolve; })); Object.defineProperty(window, 'piDesktop', { configurable: true, value: { @@ -116,8 +116,8 @@ describe('Composer voice input', () => { const expected = latest.replace('TARGET', 'spoken replacement'); await waitFor(() => expect(textarea).toHaveValue(expected)); - await waitFor(() => expect(textarea.scrollTop).toBe(120)); - expect(textarea.selectionStart).toBe(start + 'spoken replacement'.length); + await waitFor(() => expect(textarea.scrollTop).toBe(640)); + expect(textarea.selectionStart).toBe(expected.length); expect(transcribeSpeech).toHaveBeenCalledOnce(); }); diff --git a/src/renderer/features/chat/QuestionCard.tsx b/src/renderer/features/chat/QuestionCard.tsx index cabf6966..aeba52ba 100644 --- a/src/renderer/features/chat/QuestionCard.tsx +++ b/src/renderer/features/chat/QuestionCard.tsx @@ -1,5 +1,5 @@ import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'; -import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp } from 'lucide-react'; import type { PendingQuestionnaire, QuestionnaireAnswerInput, QuestionnaireBackInput } from '../../../shared/contracts/ipc'; export interface QuestionCardProps { @@ -16,6 +16,8 @@ export function QuestionCard(props: QuestionCardProps) { function CurrentQuestion({ questionnaire, onAnswer, onBack }: QuestionCardProps) { const headingId = useId(); const progressId = useId(); + const bodyId = useId(); + const [collapsed, setCollapsed] = useState(false); const heading = useRef(null); const card = useRef(null); const locked = useRef(false); @@ -92,47 +94,57 @@ function CurrentQuestion({ questionnaire, onAnswer, onBack }: QuestionCardProps) locked.current = false; setBusy(false); setError(true); + setCollapsed(false); } } return ( -
+

Question {questionnaire.index + 1} / {questionnaire.total}

+ {collapsed && {questionnaire.question}}
- - + + } +
-

{questionnaire.question}

-
- {questionnaire.options.map((option, index) => ( - - ))} - setDraft(event.target.value)} - onKeyDown={(event) => { - if (event.key !== 'Enter' || event.nativeEvent.isComposing || event.keyCode === 229) return; - event.preventDefault(); - event.stopPropagation(); - answer(draft, 'custom'); - }} - /> + - {error &&

Could not send answer. Try again.

}
); } diff --git a/src/renderer/features/chat/voiceDraft.ts b/src/renderer/features/chat/voiceDraft.ts new file mode 100644 index 00000000..f383a7d6 --- /dev/null +++ b/src/renderer/features/chat/voiceDraft.ts @@ -0,0 +1,50 @@ +export class VoiceDraftRange { + private committed = ''; + private preserved = ''; + + constructor(private draft: string, private start: number, private end: number) {} + + rebase(next: string): void { + if (this.draft === next) return; + let left = 0; + const previous = this.draft; + while (left < previous.length && left < next.length && previous[left] === next[left]) left++; + let oldRight = previous.length; + let newRight = next.length; + while (oldRight > left && newRight > left && previous[oldRight - 1] === next[newRight - 1]) { oldRight--; newRight--; } + if (oldRight <= this.start) { + this.start += newRight - oldRight; + this.end += newRight - oldRight; + } else if (left < this.end) { + this.start = this.end = next.length; + this.preserved = this.committed; + } + this.draft = next; + } + + apply(committed: string, selectionStart: number, selectionEnd: number) { + const words = committed.trim(); + if (!words || words === this.committed) return null; + const firstInsertion = !this.committed; + this.committed = words; + const text = this.preserved && words.startsWith(this.preserved) ? words.slice(this.preserved.length).trimStart() : words; + if (!text) return null; + const before = this.draft.slice(0, this.start); + const after = this.draft.slice(this.end); + const leading = before && !/\s$/u.test(before) ? ' ' : ''; + const trailing = after && !/^\s/u.test(after) ? ' ' : ''; + const insertion = `${leading}${text}${trailing}`; + const nextEnd = this.start + insertion.length; + const offset = (position: number) => { + if (position < this.start) return position; + if (position >= this.end) return position + nextEnd - this.end; + return this.start + Math.min(position - this.start, insertion.length); + }; + const replacingSelection = firstInsertion && selectionStart === this.start && selectionEnd === this.end; + const start = replacingSelection ? nextEnd : offset(selectionStart); + const end = replacingSelection ? nextEnd : selectionStart < this.start && selectionEnd === this.start ? selectionEnd : offset(selectionEnd); + this.draft = before + insertion + after; + this.end = nextEnd; + return { text: this.draft, start, end }; + } +} diff --git a/src/renderer/features/chat/voiceStream.ts b/src/renderer/features/chat/voiceStream.ts index 02b6ef0a..7188391a 100644 --- a/src/renderer/features/chat/voiceStream.ts +++ b/src/renderer/features/chat/voiceStream.ts @@ -22,6 +22,8 @@ export interface VoiceStreamController { const PROCESSOR_NAME = 'fate-voice-downsample'; const TARGET_RATE = SPEECH_SAMPLE_RATE; +const FLUSH_TIMEOUT_MS = 1_000; +const BACKLOG_WARNING_SECONDS = 5; /** Match the main-process IPC limit: combine delayed 300 ms captures, but never * make an unbounded native feed. */ export const MAX_VOICE_STREAM_BATCH_SAMPLES = MAX_SPEECH_STREAM_FEED_SAMPLES; @@ -41,11 +43,13 @@ export class VoiceStreamFeedQueue { private closed = false; private cancelled = false; private failure: unknown | null = null; + private backlogWarning = false; constructor( private readonly send: (audio: ArrayBuffer) => Promise, private readonly onError: (error: unknown) => void, private readonly gate: SpeechGate = new SpeechGate(), + private readonly onBacklogSeconds?: (seconds: number) => void, ) {} push(pcm: Float32Array): boolean { @@ -80,10 +84,19 @@ export class VoiceStreamFeedQueue { } this.pending.push(pcm); this.pendingSamples += pcm.length; + this.reportBacklog(); this.startDrain(); return true; } + private reportBacklog(): void { + const seconds = (this.pendingSamples + this.inFlightSamples) / TARGET_RATE; + const warning = seconds >= BACKLOG_WARNING_SECONDS; + if (warning === this.backlogWarning) return; + this.backlogWarning = warning; + this.onBacklogSeconds?.(seconds); + } + private startDrain(): void { if (this.draining || this.failure || this.cancelled) return; this.draining = this.drain().finally(() => { @@ -104,6 +117,7 @@ export class VoiceStreamFeedQueue { return; } finally { this.inFlightSamples = 0; + if (!this.cancelled && !this.failure) this.reportBacklog(); } } } @@ -134,13 +148,16 @@ class DownsampleProcessor extends AudioWorkletProcessor { super(); this.chunkSamples = (options.processorOptions && options.processorOptions.chunkSamples) || 4800; this.out = []; - this.leftover = []; - this.fraction = 0; - this.ratio = ${TARGET_RATE} / sampleRate; + this.previous = 0; + this.phase = 0; this.stopped = false; this.port.onmessage = (event) => { if (event.data && event.data.type === 'flush' && !this.stopped) { this.stopped = true; + while (this.phase < 0) { + this.out.push(this.previous); + this.phase += sampleRate; + } if (this.out.length > 0) { const buffer = new Float32Array(this.out); this.out = []; @@ -157,18 +174,17 @@ class DownsampleProcessor extends AudioWorkletProcessor { if (sampleRate === ${TARGET_RATE}) { for (let i = 0; i < channel.length; i++) this.out.push(channel[i]); } else { - const combined = this.leftover; - for (let i = 0; i < channel.length; i++) combined.push(channel[i]); - let pos = this.fraction; - while (pos + 1 < combined.length) { - const i0 = pos | 0; - const frac = pos - i0; - this.out.push(combined[i0] + (combined[i0 + 1] - combined[i0]) * frac); - pos += 1 / this.ratio; + const last = channel.length - 1; + while (this.phase <= last * ${TARGET_RATE}) { + const position = this.phase / ${TARGET_RATE}; + const index = Math.floor(position); + const left = index < 0 ? this.previous : channel[index]; + const right = channel[Math.ceil(position)]; + this.out.push(left + (right - left) * (position - index)); + this.phase += sampleRate; } - const consumed = pos | 0; - this.leftover = combined.slice(consumed); - this.fraction = pos - consumed; + this.phase -= channel.length * ${TARGET_RATE}; + this.previous = channel[last]; } while (this.out.length >= this.chunkSamples) { const chunk = this.out.splice(0, this.chunkSamples); @@ -206,20 +222,38 @@ export async function startVoiceStream( } let context: AudioContext; - try { - // Let Chromium perform its native, band-limited conversion when the device - // supports a 16 kHz graph. The worklet keeps its resampler as a fallback. - context = new AudioContext({ sampleRate: TARGET_RATE }); - } catch { - context = new AudioContext(); - } let source: MediaStreamAudioSourceNode; let node: AudioWorkletNode; let mute: GainNode; - let resolveFlush: (() => void) | null = null; - let processorFailed = false; + let finishFlush: ((error?: Error) => void) | null = null; + let captureError: Error | null = null; + const release = async () => { + try { + stream.getTracks().forEach((track) => track.stop()); + if (node) { + node.port.onmessage = null; + node.onprocessorerror = null; + node.port.close(); + } + source?.disconnect(); + node?.disconnect(); + mute?.disconnect(); + } finally { + await context?.close().catch(() => undefined); + } + }; try { - await context.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }))); + try { + context = new AudioContext({ sampleRate: TARGET_RATE }); + } catch { + context = new AudioContext(); + } + const moduleUrl = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' })); + try { + await context.audioWorklet.addModule(moduleUrl); + } finally { + URL.revokeObjectURL(moduleUrl); + } source = context.createMediaStreamSource(stream); node = new AudioWorkletNode(context, PROCESSOR_NAME, { numberOfInputs: 1, @@ -229,15 +263,14 @@ export async function startVoiceStream( }); node.port.onmessage = (event: MessageEvent) => { if ((event.data as { type?: string } | null)?.type === 'flushed') { - resolveFlush?.(); - resolveFlush = null; + finishFlush?.(); return; } if (event.data instanceof Float32Array) onChunk(event.data); }; node.onprocessorerror = () => { - processorFailed = true; - resolveFlush?.(); + captureError = new Error('Microphone capture failed. The recording may be incomplete.'); + finishFlush?.(captureError); }; mute = context.createGain(); mute.gain.value = 0; @@ -245,8 +278,7 @@ export async function startVoiceStream( node.connect(mute); mute.connect(context.destination); } catch (error) { - stream.getTracks().forEach((track) => track.stop()); - await context.close().catch(() => undefined); + await release(); throw error; } @@ -254,17 +286,19 @@ export async function startVoiceStream( return { stop: () => { stopping ??= (async () => { - if (!processorFailed) { - await new Promise((resolve) => { - resolveFlush = resolve; - try { node.port.postMessage({ type: 'flush' }); } catch { resolve(); } + let deadline: ReturnType | undefined; + try { + if (captureError) throw captureError; + await new Promise((resolve, reject) => { + finishFlush = (error) => error ? reject(error) : resolve(); + deadline = setTimeout(() => reject(new Error('Microphone capture did not finish in time. The recording may be incomplete.')), FLUSH_TIMEOUT_MS); + node.port.postMessage({ type: 'flush' }); }); + } finally { + clearTimeout(deadline); + finishFlush = null; + await release(); } - node.port.onmessage = null; - node.onprocessorerror = null; - try { source.disconnect(); node.disconnect(); mute.disconnect(); } catch { /* graph already torn down */ } - stream.getTracks().forEach((track) => track.stop()); - await context.close().catch(() => undefined); })(); return stopping; }, diff --git a/src/renderer/features/settings/SettingsDialog.tsx b/src/renderer/features/settings/SettingsDialog.tsx index 71f3c594..764b329f 100644 --- a/src/renderer/features/settings/SettingsDialog.tsx +++ b/src/renderer/features/settings/SettingsDialog.tsx @@ -329,9 +329,10 @@ export function SettingsDialog({ themeCatalog: initialThemeCatalog = fallbackThe useEffect(() => { if (!open || activeSection !== 'voice' || !voiceHotkeysSupported || typeof getDesktopApiOptional()?.getSpeechHotkeyStatus !== 'function') return; let active = true; + setHotkeyStatus(null); getDesktopApi().getSpeechHotkeyStatus().then((status) => { if (active) setHotkeyStatus(status); }).catch(() => undefined); return () => { active = false; }; - }, [activeSection, open, voiceHotkeysSupported]); + }, [activeSection, open, persistedSettings, voiceHotkeysSupported]); useEffect(() => { if (!capturingHotkey || !voiceHotkeysSupported) return; @@ -649,8 +650,10 @@ export function SettingsDialog({ themeCatalog: initialThemeCatalog = fallbackThe max: 'Highest accuracy', }; const speechBackendLabel = !speechStatus - ? 'Detecting acceleration…' - : speechStatus.accelerated ? 'GPU acceleration active' : 'CPU fallback ready'; + ? (speechStatusError ? 'Hardware status unavailable' : 'Checking local hardware…') + : speechStatus.accelerated ? 'GPU acceleration available' : 'No hardware acceleration reported'; + const hotkeyIssue = hotkeyStatus?.reason ?? (hotkeyStatus && !hotkeyStatus.pushToTalkAvailable && settings.speech.voiceHotkeyMode === 'push-to-talk' + ? 'Push-to-talk is unavailable on this platform.' : null); const selectedInputUnavailable = Boolean( settings.speech.inputDeviceId && !inputDevices.some((device) => device.deviceId === settings.speech.inputDeviceId), @@ -921,7 +924,7 @@ export function SettingsDialog({ themeCatalog: initialThemeCatalog = fallbackThe

Model power

Pick a model per accuracy tier. Mini downloads automatically on first use. “Live” models show words while you speak.

@@ -961,7 +964,7 @@ export function SettingsDialog({ themeCatalog: initialThemeCatalog = fallbackThe
-
Voice hotkey{settings.speech.voiceHotkey ? `Press ${settings.speech.voiceHotkey} ${settings.speech.voiceHotkeyMode === 'push-to-talk' ? 'and hold to talk' : 'to toggle recording'}.` : 'Off — use the microphone button in the composer instead.'}
+
Voice hotkey{settings.speech.voiceHotkey ? `Configured to ${settings.speech.voiceHotkeyMode === 'push-to-talk' ? 'hold for recording' : 'toggle recording'} with ${settings.speech.voiceHotkey}.` : 'Off — use the microphone button in the composer instead.'}
{settings.speech.voiceHotkey && } @@ -969,8 +972,8 @@ export function SettingsDialog({ themeCatalog: initialThemeCatalog = fallbackThe
- {hotkeyStatus && !hotkeyStatus.pushToTalkAvailable && settings.speech.voiceHotkeyMode === 'push-to-talk' && ( -
{hotkeyStatus.reason ?? 'Push-to-talk is unavailable on this platform. Toggle mode still works.'}
+ {hotkeyIssue && ( +
{hotkeyIssue}
)} ) :

{unavailableExplanation.microphone}

)} diff --git a/src/renderer/features/settings/SettingsDialog.ui.test.tsx b/src/renderer/features/settings/SettingsDialog.ui.test.tsx index 79f20a04..b6cb732b 100644 --- a/src/renderer/features/settings/SettingsDialog.ui.test.tsx +++ b/src/renderer/features/settings/SettingsDialog.ui.test.tsx @@ -522,7 +522,7 @@ describe('SettingsDialog feedback', () => { render(); await user.click(await screen.findByRole('tab', { name: /Voice/ })); - expect(await screen.findByText('GPU acceleration active')).toBeInTheDocument(); + expect(await screen.findByText('GPU acceleration available')).toBeInTheDocument(); expect(screen.getByLabelText('Voice transcription models').querySelectorAll('.voice-model-row')).toHaveLength(3); await user.click(screen.getByRole('button', { name: 'Download English Live voice model' })); expect(window.piDesktop.downloadSpeechModel).toHaveBeenCalledWith('parakeet-unified'); diff --git a/src/renderer/platform/DesktopFateApi.ts b/src/renderer/platform/DesktopFateApi.ts index 7c61d093..05d2655d 100644 --- a/src/renderer/platform/DesktopFateApi.ts +++ b/src/renderer/platform/DesktopFateApi.ts @@ -28,6 +28,7 @@ export function selectDesktopMethods(bridge: DesktopOnlyApi): DesktopOnlyApi { cancelSpeechStream: bridge.cancelSpeechStream, cancelSpeechTranscription: bridge.cancelSpeechTranscription, checkForUpdates: bridge.checkForUpdates, + claimSpeechAttempt: bridge.claimSpeechAttempt, clearMusicQueue: bridge.clearMusicQueue, closeBrowserTab: bridge.closeBrowserTab, closeTerminal: bridge.closeTerminal, @@ -122,6 +123,7 @@ export function selectDesktopMethods(bridge: DesktopOnlyApi): DesktopOnlyApi { removeBrowserAnnotation: bridge.removeBrowserAnnotation, removeModelsDevProvider: bridge.removeModelsDevProvider, removeSkinPack: bridge.removeSkinPack, + releaseSpeechAttempt: bridge.releaseSpeechAttempt, removeSpeechModel: bridge.removeSpeechModel, resizeTerminal: bridge.resizeTerminal, resolveMusicTrack: bridge.resolveMusicTrack, diff --git a/src/renderer/styles/global.css b/src/renderer/styles/global.css index 1d6f7207..3805d645 100644 --- a/src/renderer/styles/global.css +++ b/src/renderer/styles/global.css @@ -44,6 +44,11 @@ color: var(--theme-text); cursor: pointer; } +.question-card[data-collapsed] { padding-block: 4px; } +.question-card[data-collapsed] .question-card-header { margin-bottom: 0; } +.question-card .question-card-progress { flex: none; } +.question-card .question-card-preview { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.question-card .question-card-toggle { display: inline-flex; align-items: center; gap: 4px; width: auto; padding-inline: 7px; } .question-card .question-card-nav-button:hover:not(:disabled) { background: var(--theme-raised-hover); } .question-card .question-card-nav-button:disabled { color: var(--theme-muted); opacity: .4; } .question-card .question-card-option[aria-pressed='true'] { background: var(--theme-raised-hover); box-shadow: inset 2px 0 0 var(--theme-accent); } diff --git a/src/shared/contracts/ipc.test.ts b/src/shared/contracts/ipc.test.ts index 90456c0f..92ccf34b 100644 --- a/src/shared/contracts/ipc.test.ts +++ b/src/shared/contracts/ipc.test.ts @@ -381,10 +381,11 @@ describe('IPC contracts', () => { expect(() => appSettingsSchema.parse({ ...defaults, disabledModels: ['x'.repeat(701)] })).toThrow(); expect(speechModelInputSchema.parse({ modelId: 'cohere-transcribe' })).toEqual({ modelId: 'cohere-transcribe' }); expect(() => speechModelInputSchema.parse({ modelId: 'huge' })).toThrow(); - expect(speechTranscribeInputSchema.parse({ modelId: 'canary-flash', audio: new ArrayBuffer(16) }).audio.byteLength).toBe(16); - expect(() => speechTranscribeInputSchema.parse({ modelId: 'canary-flash', audio: new ArrayBuffer(3) })).toThrow(); - expect(speechStreamFeedInputSchema.parse({ audio: new ArrayBuffer(16_000 * 4 * 2) }).audio.byteLength).toBe(16_000 * 4 * 2); - expect(() => speechStreamFeedInputSchema.parse({ audio: new ArrayBuffer(16_000 * 4 * 2 + 4) })).toThrow(); + const attemptId = '4c3d3418-a1a9-44ed-8bd1-8c9490add6f9'; + expect(speechTranscribeInputSchema.parse({ attemptId, modelId: 'canary-flash', audio: new ArrayBuffer(16) }).audio.byteLength).toBe(16); + expect(() => speechTranscribeInputSchema.parse({ attemptId, modelId: 'canary-flash', audio: new ArrayBuffer(3) })).toThrow(); + expect(speechStreamFeedInputSchema.parse({ attemptId, audio: new ArrayBuffer(16_000 * 4 * 2) }).audio.byteLength).toBe(16_000 * 4 * 2); + expect(() => speechStreamFeedInputSchema.parse({ attemptId, audio: new ArrayBuffer(16_000 * 4 * 2 + 4) })).toThrow(); expect(() => appSettingsSchema.parse({ ...defaults, interfaceFont: 'comic-sans' })).toThrow(); }); }); diff --git a/src/shared/contracts/ipc.ts b/src/shared/contracts/ipc.ts index 357595ed..feb6eeb8 100644 --- a/src/shared/contracts/ipc.ts +++ b/src/shared/contracts/ipc.ts @@ -250,6 +250,8 @@ export const ipcChannels = { skinsExport: 'skins:export', skinsOpenFolder: 'skins:open-folder', speechGetStatus: 'speech:get-status', + speechClaimAttempt: 'speech:claim-attempt', + speechReleaseAttempt: 'speech:release-attempt', speechEnsureModel: 'speech:ensure-model', speechDownloadModel: 'speech:download-model', speechCancelDownload: 'speech:cancel-download', @@ -1383,7 +1385,10 @@ export const speechStatusSchema = z.object({ }).strict(); export const speechModelInputSchema = z.object({ modelId: speechModelIdSchema }).strict(); const arrayBufferSchema = z.custom((value) => Object.prototype.toString.call(value) === '[object ArrayBuffer]' && typeof (value as ArrayBuffer).byteLength === 'number'); +const speechAttemptIdSchema = z.string().uuid(); +export const speechAttemptInputSchema = z.object({ attemptId: speechAttemptIdSchema }).strict(); export const speechTranscribeInputSchema = z.object({ + attemptId: speechAttemptIdSchema, modelId: speechModelIdSchema, audio: arrayBufferSchema.refine((value) => value.byteLength > 0 && value.byteLength <= 16_000 * 180 * 4 && value.byteLength % 4 === 0, 'Audio must be bounded 16 kHz Float32 PCM.'), language: z.string().trim().min(2).max(16).optional(), @@ -1404,6 +1409,7 @@ export const speechDownloadProgressSchema = z.object({ export const speechCancelResultSchema = z.object({ cancelled: z.boolean() }).strict(); export const speechStreamStateSchema = z.enum(['active', 'finalizing', 'final', 'error', 'cancelled']); export const speechStreamStartInputSchema = z.object({ + attemptId: speechAttemptIdSchema, modelId: speechModelIdSchema, language: z.string().trim().min(2).max(16).optional(), /** Run the full-recording accuracy pass at stop. Off by default — the pass @@ -1411,9 +1417,11 @@ export const speechStreamStartInputSchema = z.object({ refine: z.boolean().default(false), }).strict(); export const speechStreamFeedInputSchema = z.object({ + attemptId: speechAttemptIdSchema, audio: arrayBufferSchema.refine((value) => value.byteLength > 0 && value.byteLength <= MAX_SPEECH_STREAM_FEED_SAMPLES * SPEECH_PCM_BYTES_PER_SAMPLE && value.byteLength % SPEECH_PCM_BYTES_PER_SAMPLE === 0, 'Audio must be bounded 16 kHz Float32 PCM.'), }).strict(); export const speechStreamUpdateSchema = z.object({ + attemptId: speechAttemptIdSchema.optional(), state: speechStreamStateSchema, committed: z.string().max(200_000), tentative: z.string().max(200_000), @@ -1424,7 +1432,7 @@ export const speechStreamUpdateSchema = z.object({ backlogSeconds: z.number().min(0).max(600).optional(), }).strict(); export const voiceHotkeyEventSchema = z.object({ - action: z.enum(['start', 'stop']), + action: z.enum(['start', 'stop', 'toggle']), source: z.enum(['hotkey', 'button']).default('hotkey'), }).strict(); export const speechHotkeyStatusSchema = z.object({ @@ -1870,12 +1878,14 @@ export interface PiDesktopApi extends LearningApi, AgentsApi, DesktopConnectionA downloadSpeechModel: (modelId: SpeechModelId) => Promise; cancelSpeechModelDownload: (modelId: SpeechModelId) => Promise; removeSpeechModel: (modelId: SpeechModelId) => Promise; - transcribeSpeech: (modelId: SpeechModelId, audio: ArrayBuffer, language?: string) => Promise; - cancelSpeechTranscription: () => Promise; - startSpeechStream: (modelId: SpeechModelId, language?: string, refine?: boolean) => Promise; - feedSpeechStream: (audio: ArrayBuffer) => Promise; - stopSpeechStream: () => Promise; - cancelSpeechStream: () => Promise; + claimSpeechAttempt: (attemptId: string) => Promise; + releaseSpeechAttempt: (attemptId: string) => Promise; + transcribeSpeech: (modelId: SpeechModelId, audio: ArrayBuffer, language: string | undefined, attemptId: string) => Promise; + cancelSpeechTranscription: (attemptId: string) => Promise; + startSpeechStream: (modelId: SpeechModelId, language: string | undefined, refine: boolean | undefined, attemptId: string) => Promise; + feedSpeechStream: (audio: ArrayBuffer, attemptId: string) => Promise; + stopSpeechStream: (attemptId: string) => Promise; + cancelSpeechStream: (attemptId: string) => Promise; getSpeechHotkeyStatus: () => Promise; onSpeechDownload: (listener: (progress: SpeechDownloadProgress) => void) => () => void; onSpeechStreamUpdate: (listener: (update: SpeechStreamUpdate) => void) => () => void; diff --git a/src/shared/speechGate.ts b/src/shared/speechGate.ts index 40ac5b1e..9936088d 100644 --- a/src/shared/speechGate.ts +++ b/src/shared/speechGate.ts @@ -148,33 +148,33 @@ export class SpeechGate { } private pushFrame(frame: Float32Array): Float32Array | null { - this.frameBuffer.push(Float32Array.from(frame)); - const maxBuffered = this.config.prefillFrames + 1; - while (this.frameBuffer.length > maxBuffered) this.frameBuffer.shift(); - const isVoice = frameHasSpeech(frame, this.config); - if (!this.inSpeech && isVoice) { - this.onsetCounter += 1; - if (this.onsetCounter < this.config.onsetFrames) return null; - this.inSpeech = true; - this.hangoverCounter = this.config.hangoverFrames; - this.onsetCounter = 0; - return concatPcm(this.frameBuffer); - } - if (this.inSpeech && isVoice) { - this.hangoverCounter = this.config.hangoverFrames; - return Float32Array.from(frame); - } - if (this.inSpeech && !isVoice) { - this.onsetCounter = 0; + if (this.inSpeech) { + if (isVoice) { + this.hangoverCounter = this.config.hangoverFrames; + return Float32Array.from(frame); + } if (this.hangoverCounter > 0) { this.hangoverCounter -= 1; return Float32Array.from(frame); } this.inSpeech = false; + } + + this.frameBuffer.push(Float32Array.from(frame)); + const maxBuffered = this.config.prefillFrames + 1; + while (this.frameBuffer.length > maxBuffered) this.frameBuffer.shift(); + if (!isVoice) { + this.onsetCounter = 0; return null; } + this.onsetCounter += 1; + if (this.onsetCounter < this.config.onsetFrames) return null; + this.inSpeech = true; + this.hangoverCounter = this.config.hangoverFrames; this.onsetCounter = 0; - return null; + const onset = concatPcm(this.frameBuffer); + this.frameBuffer.length = 0; + return onset; } } diff --git a/tests/e2e/main.ts b/tests/e2e/main.ts index 92e2af46..3dc42e82 100644 --- a/tests/e2e/main.ts +++ b/tests/e2e/main.ts @@ -2,7 +2,7 @@ import { app, BrowserWindow, protocol } from 'electron'; import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import { appCommandSchema, appSettingsSchema, ipcChannels, type AppSettings, type ProjectState, type TerminalEvent } from '../../src/shared/contracts/ipc'; +import { appCommandSchema, appSettingsSchema, ipcChannels, type AppSettings, type ProjectState, type SpeechModelId, type SpeechStreamUpdate, type TerminalEvent } from '../../src/shared/contracts/ipc'; import { browserEventBatchSchema } from '../../src/shared/contracts/browser'; import { builtInThemes } from '../../src/shared/themes'; import { LegacyAutomations } from '../../src/main/automations/LegacyAutomations'; @@ -27,7 +27,7 @@ import { SkinPackService } from '../../src/main/settings/SkinPackService'; import { preparePackBackground } from '../../src/main/settings/DesktopSkinImage'; import { skinPackThemeId } from '../../src/shared/skins'; import { removePackFontPreferences } from '../../src/shared/skinAppearance'; -import type { SpeechService } from '../../src/main/speech/SpeechService'; +import { speechModel, speechModels } from '../../src/main/speech/speechModels'; import type { TerminalService } from '../../src/main/terminal/TerminalService'; import { installWindowZoomShortcuts } from '../../src/main/windowZoom'; import { MINIMUM_WINDOW_SIZE } from '../../src/main/windowState'; @@ -120,25 +120,49 @@ const music = { reset: () => undefined, setDurationSink: () => undefined, } as unknown as MusicService; -const speechModels = [ - { id: 'parakeet-unified', tier: 'mini', name: 'Mini', model: 'Test Mini', description: 'Test model', detail: '1 MB', bytes: 1, installed: true, downloadedBytes: 1, streaming: true }, - { id: 'canary-flash', tier: 'balanced', name: 'Medium', model: 'Test Medium', description: 'Test model', detail: '2 MB', bytes: 2, installed: false, downloadedBytes: 0, streaming: false }, - { id: 'nemotron-stream', tier: 'max', name: 'Max', model: 'Test Max', description: 'Test model', detail: '3 MB', bytes: 3, installed: false, downloadedBytes: 0, streaming: false }, -] as const; -const speech = { +const installedSpeechModels = new Set(['canary-flash', 'parakeet-unified']); +let emitSpeechUpdate = (_update: SpeechStreamUpdate): void => {}; +let streamDraft: string | null = null; +const speech: Parameters[0]['speech'] = { setEventSink: () => undefined, - setStreamSink: () => undefined, - getStatus: async () => ({ models: speechModels, backend: 'E2E CPU', accelerated: false }), - download: async () => undefined, + setStreamSink: (sink) => { emitSpeechUpdate = sink; }, + getStatus: async () => ({ + models: speechModels.map(({ id, tier, name, model, description, detail, bytes, streaming }) => ({ + id, tier, name, model, description, detail, bytes, streaming, + installed: installedSpeechModels.has(id), downloadedBytes: installedSpeechModels.has(id) ? bytes : 0, + })), + backend: 'E2E CPU', accelerated: false, + }), + download: async (id) => { installedSpeechModels.add(id); }, cancelDownload: () => false, - remove: async () => undefined, - transcribe: async () => ({ text: 'voice test', language: 'en', backend: 'E2E CPU', accelerated: false }), + remove: async (id) => { installedSpeechModels.delete(id); }, + transcribe: async (id) => { + if (!installedSpeechModels.has(id)) throw new Error('Voice model not installed.'); + return { text: 'voice test', language: 'en', backend: 'E2E CPU', accelerated: false }; + }, cancel: () => false, - streamStart: async () => undefined, - streamFeed: async () => undefined, - streamStop: async () => undefined, - streamCancel: async () => undefined, -} as unknown as SpeechService; + streamStart: async (id) => { + if (!installedSpeechModels.has(id) || !speechModel(id).streaming) throw new Error('Live model unavailable.'); + if (streamDraft !== null) throw new Error('Live transcription already active.'); + streamDraft = ''; + emitSpeechUpdate({ state: 'active', committed: '', tentative: '' }); + }, + streamFeed: async () => { + if (streamDraft === null) throw new Error('No live transcription.'); + streamDraft = 'voice test'; + emitSpeechUpdate({ state: 'active', committed: 'voice', tentative: ' test' }); + }, + streamStop: async () => { + if (streamDraft === null) return; + emitSpeechUpdate({ state: 'finalizing', committed: streamDraft, tentative: '' }); + emitSpeechUpdate({ state: 'final', committed: streamDraft, tentative: '' }); + streamDraft = null; + }, + streamCancel: async () => { + if (streamDraft !== null) emitSpeechUpdate({ state: 'cancelled', committed: '', tentative: '' }); + streamDraft = null; + }, +}; const updates = { check: async () => ({ status: 'current' as const, message: 'FateGUI is up to date.' }), openDownload: async () => undefined, diff --git a/tests/fixtures/speech/README.md b/tests/fixtures/speech/README.md new file mode 100644 index 00000000..68030634 --- /dev/null +++ b/tests/fixtures/speech/README.md @@ -0,0 +1,3 @@ +`review-changes.s16le` is the project-authored sentence “Please review the current changes before sending the message.” It was synthesized offline with Windows System.Speech into 16 kHz mono signed 16-bit little-endian PCM. No microphone recording, voice model or speech corpus is included. The fixture stays in the checkout, not in the installer. + +From the repository root, `node scripts/verify-speech-models.mjs` checks the fixture against all six production models. Pass one or more catalog IDs to check a subset. The verifier downloads missing pinned GGUFs to `node_modules/.cache/speech-spike` and verifies their size and SHA-256 before use. diff --git a/tests/fixtures/speech/review-changes.s16le b/tests/fixtures/speech/review-changes.s16le new file mode 100644 index 00000000..e81de7b2 Binary files /dev/null and b/tests/fixtures/speech/review-changes.s16le differ