diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml index 346f1cfb4b12..4967de07ca21 100644 --- a/.github/workflows/ui-self-hosted.yml +++ b/.github/workflows/ui-self-hosted.yml @@ -19,6 +19,7 @@ on: '.github/workflows/ui-build-self-hosted.yml', 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', + 'ui/lib/voice/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -28,6 +29,7 @@ on: '.github/workflows/ui-build-self-hosted.yml', 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', + 'ui/lib/voice/**.*', 'tools/server/tests/**.*' ] diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 10d7ed0ed5e4..65e5c36ffdbf 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -150,6 +150,37 @@ jobs: run: npm run prepack working-directory: ui/lib/ui + voice-checks: + name: Voice checks + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/lib/voice + + - name: Run type checking + run: npm run check + working-directory: ui/lib/voice + + - name: Run tests + run: npm test + working-directory: ui/lib/voice + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/voice + e2e-tests: name: E2E Tests needs: ui-build diff --git a/ui/README.md b/ui/README.md index b70228d0de7c..0f210a40c80c 100644 --- a/ui/README.md +++ b/ui/README.md @@ -5,7 +5,8 @@ The UI of llama.cpp: the packages in `lib` and the apps built on them. ```text ui/ ├── lib/ -│ └── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ └── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation └── apps/ └── chat/ Llama Chat, the chat app that llama-server serves ``` @@ -13,12 +14,15 @@ ui/ - [`lib/ui`](lib/ui/README.md) draws the parts and handles interaction, with no business logic. It is built with `@sveltejs/package` and published to npm as `@ggml-org/llama-ui`. Apps in this repo skip the package: they compile its sources as part of their own build, so they hold no copy of a component, a token or a font. +- [`lib/voice`](lib/voice/README.md) records the microphone and turns speech into text through llama-server, with no + UI: Llama UI draws the voice parts. It is plain TypeScript built with `tsc`, plus a Svelte entry + (`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet. - [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop. CMake builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as `@ggml-org/llama-chat` (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server. Each folder is its own npm package with its own `package-lock.json`: run `npm ci` in the one you work on. Building, -checking and testing `apps/chat` needs no install in `lib/ui`. +checking and testing `apps/chat` needs no install in `lib/ui` or `lib/voice`. ## Releases diff --git a/ui/apps/chat/.storybook/main.ts b/ui/apps/chat/.storybook/main.ts index 3e8c1a39d8dc..e2b8dad14377 100644 --- a/ui/apps/chat/.storybook/main.ts +++ b/ui/apps/chat/.storybook/main.ts @@ -16,7 +16,7 @@ const config: StorybookConfig = { '../tests/stories/**/*.stories.@(js|ts|svelte)', { directory: '../../../lib/ui/tests/stories', - files: '{foundations,components,app,models,mockups}/**/*.stories.svelte' + files: '{foundations,components,app,models,mockups,voice}/**/*.stories.svelte' } ], addons: [ diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index 971685e1bc51..79e5215286f3 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -1151,6 +1151,12 @@ icon buttons in the chat form are fully round. (`--sidebar-reveal-x`), taking no taps while the page is aside. The page keeps room under its last row (`max-md:pb-safe-24`) so the key never covers it. One per page, only for its main action; from `md` up the action stays a button in the header. +- **Voice clips:** a recorded clip is a round primary play key, its waveform and the time in + `caption`: bars in the muted foreground at 40%, the played part in the primary colour, so + the clip stays neutral in both modes. The live waveform while recording is as tall as the + input's line (24px), the newest level on the right, and holds still with reduced motion. A + voice message's transcript opens under the clip on hover, keyboard focus or a tap, and + stays in the DOM for screen readers while closed. - **Copy feedback:** a copy action turns its icon into a `fg-success` check for 1.5s (`COPY_FEEDBACK_RESET_MS`), only when the copy succeeded, then back. The icon pops in with a 150ms fade and scale, skipped on first render and with reduced motion. diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index 5fa37286aadf..abee5d43bb0d 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -89,6 +89,7 @@ The app imports the library as `@ggml-org/llama-ui/ui/` and compiles its s | Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | | App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area | | UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | +| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) | | Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | | Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | | Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox | diff --git a/ui/apps/chat/demo/README.md b/ui/apps/chat/demo/README.md index 8769da6ef4ff..e929626870d0 100644 --- a/ui/apps/chat/demo/README.md +++ b/ui/apps/chat/demo/README.md @@ -115,7 +115,7 @@ Records every `scripts/docs/*.demo.ts` from the storage target and uploads `vide ## Writing a demo -Scripts get `test` and `expect` from `helpers.ts` without importing them. `demo.click`, `demo.hover` and `demo.type` glide a visible cursor to the target before acting, with timing varied like a person's (seeded per demo, so re-takes match); `demo.scroll` turns the mouse wheel over a target; `demo.zoom` pinches in on a control or a point to show a detail too small to read in the frame, holds, and pinches back out (with the fingertips drawn on a touch device); `demo.caption` shows a caption at the top of the frame. Use `test.use({ settings, startPath })` to seed other settings or start on another route. +Scripts get `test` and `expect` from `helpers.ts` without importing them. `demo.click`, `demo.hover` and `demo.type` glide a visible cursor to the target before acting, with timing varied like a person's (seeded per demo, so re-takes match); `demo.scroll` turns the mouse wheel over a target; `demo.zoom` pinches in on a control or a point to show a detail too small to read in the frame, holds, and pinches back out (with the fingertips drawn on a touch device); `demo.caption` shows a caption at the top of the frame. For voice input, `demo.microphone()` gives the page a microphone that hears nothing but `demo.speak(text)`, which reads the text in a synthetic voice (macOS `say`) and shows it as a caption, since the video has no sound. Use `test.use({ settings, startPath })` to seed other settings or start on another route. ## Conversations diff --git a/ui/apps/chat/demo/helpers.ts b/ui/apps/chat/demo/helpers.ts index 1c0ad7734f4e..97e7bdb11c75 100644 --- a/ui/apps/chat/demo/helpers.ts +++ b/ui/apps/chat/demo/helpers.ts @@ -3,7 +3,15 @@ import { generateTrace } from './fixtures/traces.ts'; import { ScreencastRecorder } from './recorder.ts'; import { type CDPSession, type Locator, type Page, test as base } from '@playwright/test'; import { execFileSync } from 'node:child_process'; -import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { + appendFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync +} from 'node:fs'; +import { tmpdir } from 'node:os'; import { basename, join, resolve } from 'node:path'; const VIDEOS_DIR = resolve(import.meta.dirname, 'videos'); @@ -112,6 +120,68 @@ function seedSettings(config: Record): void { } } +/** + * Swaps the page's microphone for one that hears only what `window.demoSpeak` plays into it, + * silence otherwise. Chromium's fake capture device crashes the page, so voice input is + * recorded with this instead. Runs in the page. + */ +function installFakeMicrophone(): void { + const context = new AudioContext(); + const output = context.createMediaStreamDestination(); + + navigator.mediaDevices.getUserMedia = async (constraints) => { + if (!constraints?.audio || constraints.video) { + throw new DOMException('demo: only the microphone is faked', 'NotSupportedError'); + } + + await context.resume(); + + // each opening gets its own tracks, so a recording that stops them leaves the source on + return new MediaStream(output.stream.getAudioTracks().map((track) => track.clone())); + }; + + Object.assign(window, { + demoSpeak: async (wavBase64: string) => { + const bytes = Uint8Array.from(atob(wavBase64), (c) => c.charCodeAt(0)); + const source = context.createBufferSource(); + + source.buffer = await context.decodeAudioData(bytes.buffer); + source.connect(output); + await context.resume(); + await new Promise((done) => { + source.onended = done; + source.start(); + }); + } + }); +} + +/** `text` read by a synthetic voice, as a base64 WAV. Uses macOS `say`. */ +function synthesizeSpeech(text: string, voice: string): string { + const dir = mkdtempSync(join(tmpdir(), 'demo-speech-')); + const file = join(dir, 'speech.wav'); + + try { + execFileSync('say', [ + '-v', + voice, + '-o', + file, + '--file-format=WAVE', + '--data-format=LEI16@24000', + text + ]); + + return readFileSync(file).toString('base64'); + } catch (error) { + throw new Error(`demo: speak() needs macOS \`say\` with the voice ${voice}`, { + cause: error + }); + } finally { + rmSync(dir, { force: true, recursive: true }); + } +} + /** Seeded randomness, so a demo moves the same way on every recording. */ function createRandom(seed: string): () => number { let state = [...seed].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 2654435761), 1); @@ -143,19 +213,9 @@ export class Demo { /** Shows a caption at the top of the frame for `ms`, clear of the chat form. */ async caption(text: string, ms = 2200): Promise { - await this.page.evaluate((t) => { - const el = document.getElementById('demo-caption'); - - if (!el) return; - - el.textContent = t; - el.classList.add('visible'); - }, text); + await this.showCaption(text); await this.page.waitForTimeout(ms); - await this.page.evaluate(() => - document.getElementById('demo-caption')?.classList.remove('visible') - ); - await this.page.waitForTimeout(250); + await this.hideCaption(); } async click(target: Locator, ms = 400): Promise { @@ -182,6 +242,15 @@ export class Demo { await this.pause(ms); } + /** + * Gives the page a microphone that hears only what `speak` says, and allows the page to + * use it. Call it before the microphone is first used. + */ + async microphone(): Promise { + await this.page.context().grantPermissions(['microphone']); + await this.page.evaluate(installFakeMicrophone); + } + /** Glides the cursor to a point near the center of `target`. */ async moveTo(target: Locator): Promise { await target.scrollIntoViewIfNeeded(); @@ -240,6 +309,23 @@ export class Demo { await this.pause(ms); } + /** + * Says `text` into the microphone from `microphone` in a synthetic voice (macOS `say`), and + * returns once it is said. The words show as a caption, since the video has no sound. + */ + async speak(text: string, voice = 'Samantha', ms = 400): Promise { + const wav = synthesizeSpeech(text, voice); + + await this.showCaption(`“${text}”`); + await this.page.evaluate( + (base64) => + (window as unknown as { demoSpeak(wav: string): Promise }).demoSpeak(base64), + wav + ); + await this.hideCaption(); + await this.pause(ms); + } + /** Types quickly with uneven key timing, a little slower after spaces and punctuation. */ async type(target: Locator, text: string, ms = 500): Promise { await this.click(target, 200); @@ -305,6 +391,13 @@ export class Demo { return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; } + private async hideCaption(): Promise { + await this.page.evaluate(() => + document.getElementById('demo-caption')?.classList.remove('visible') + ); + await this.page.waitForTimeout(250); + } + /** A pinch that reaches the screen's edge can end without its last touchend reaching the page. */ private async liftFingers(): Promise { await this.page.evaluate(() => @@ -340,6 +433,17 @@ export class Demo { return this.cdp; } + + private async showCaption(text: string): Promise { + await this.page.evaluate((t) => { + const el = document.getElementById('demo-caption'); + + if (!el) return; + + el.textContent = t; + el.classList.add('visible'); + }, text); + } } interface DemoOptions { diff --git a/ui/apps/chat/scripts/llama-ui.js b/ui/apps/chat/scripts/llama-ui.js index c4eb26af77c9..f8963593a33b 100644 --- a/ui/apps/chat/scripts/llama-ui.js +++ b/ui/apps/chat/scripts/llama-ui.js @@ -26,6 +26,7 @@ const LLAMA_UI_EXPORTS = [ ['@ggml-org/llama-ui/enums', `${source}/enums/index.ts`], ['@ggml-org/llama-ui/code', `${source}/utils/index.ts`], ['@ggml-org/llama-ui/utils', `${source}/components/ui/utils.ts`], + ['@ggml-org/llama-ui/voice', `${source}/components/voice/index.ts`], ['@ggml-org/llama-ui/styles/*', `${source}/styles/*`], ['@ggml-org/llama-ui/theme.css', `${source}/styles/theme.css`], ['@ggml-org/llama-ui/tokens.css', `${source}/styles/tokens.css`], diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte index 5bb7a47d71ea..eb1a8163c43a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte @@ -3,7 +3,8 @@ ChatAttachmentsListItemMcpPrompt, ChatAttachmentsListItemMcpResource, ChatAttachmentsListItemThumbnailFile, - ChatAttachmentsListItemThumbnailImage + ChatAttachmentsListItemThumbnailImage, + ChatAttachmentsListItemVoice } from '#lib/components/app/index.ts'; import { AttachmentType } from '#lib/enums/index.ts'; import type { @@ -12,7 +13,7 @@ DatabaseMessageExtraMcpResource, MCPResourceAttachment } from '#lib/types/index.ts'; - import { isMcpPrompt, isMcpResource, isPdfFile } from '#lib/utils/index.ts'; + import { isAudioFile, isMcpPrompt, isMcpResource, isPdfFile } from '#lib/utils/index.ts'; interface Props { class?: string; @@ -93,6 +94,15 @@ class="flex-shrink-0 {className} {scrollClasses}" onclick={() => onMcpResourcePreview?.(mcpResource)} /> +{:else if isAudioFile(item.attachment, item.uploadedFile)} + + {:else if item.isImage && item.preview} + + +
+ {#key collapsed} + + + + {/key} + + {#if !source.voice} +

{source.name}

+ {/if} + + {#if !readonly && onRemove} +
+ onRemove?.(item.id)} + stopPropagationOnClick + tooltip="Remove" + /> +
+ {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte index 53653599f8a7..3f60ac1bf6a1 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte @@ -1,12 +1,22 @@
@@ -21,6 +31,19 @@

Audio preview not available

{/if} -

{currentItem?.name || 'Audio'}

+

+ {source?.voice ? VOICE_MESSAGE_LABEL : currentItem?.name || 'Audio'} +

+ + {#if transcript} +

+ Transcript: {transcript} +

+ {:else if transcribing} +

Transcribing...

+ {/if}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index 0c44d125fb9c..bf6d60b264be 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -1,10 +1,13 @@ + +
{ event.preventDefault(); - - if (!canSubmit || disabled || hasLoadingAttachments) return; - - onSubmit?.(); + void submit(); }} > @@ -755,13 +808,14 @@ {disabled} expanded={isExpanded} onInput={() => { + voice.handleUserInput(); expansion.handleInput(); pickers.handleInput(); onValueChange?.(value); }} onKeydown={handleKeydown} onPaste={handlePaste} - {placeholder} + placeholder={voicePlaceholder ?? placeholder} /> {#if mcpStore.resources.hasAttachments} @@ -776,29 +830,55 @@
- - onSystemPromptClick?.({ files: uploadedFiles, message: value })} - onWorkingDirectoryClick={isWorkingDirectoryInAddMenu - ? pickers.handleWorkingDirectoryOpen - : undefined} - {showAddButton} - {showModelSelector} - {uploadedFiles} - workingDirectory={cwd} - /> + {#if voice.isActive} + void handleStopAndSend()} + onStop={() => void voice.stop()} + quiet={voice.quiet} + state={voice.state} + /> + {/if} + + +
+ + onSystemPromptClick?.({ files: uploadedFiles, message: value })} + onWorkingDirectoryClick={isWorkingDirectoryInAddMenu + ? pickers.handleWorkingDirectoryOpen + : undefined} + {showAddButton} + {showModelSelector} + voice={{ + action: voice.label, + hint: voice.hint, + prepare: () => void voice.prepare(), + show: voice.showButton, + unavailableReason: voice.unavailableReason, + unprepare: voice.unprepare + }} + workingDirectory={cwd} + /> +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte index 8664af6b2ea7..7485f5e4202c 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte @@ -2,34 +2,91 @@ import { Button } from '@ggml-org/llama-ui/ui/button'; import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip'; import { Mic, MicOff, Square } from '@lucide/svelte'; - import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; + import { ICON_CLASS_DEFAULT, VOICE_MODE_MESSAGE } from '#lib/constants/index.ts'; interface Props { + /** What a press does: send a voice message or dictate. */ + action?: string; class?: string; disabled?: boolean; - hasAudioModality?: boolean; + /** Said after the action in the tooltip, e.g. that another model may be loaded. */ + hint?: string | null; isLoading?: boolean; isRecording?: boolean; /** Why the microphone can't record (no HTTPS, access denied...), shown on the button. */ micWarning?: string | null; + /** Why no model can take the recording; disables the button. */ + unavailableReason?: string | null; + /** A quieter (tertiary) button, beside the main one: send or stop. */ + secondary?: boolean; + /** With `secondary`: filled like the stop button it stands beside, not bare. */ + filled?: boolean; onMicClick?: () => void; + /** A mouse or the focus came to the button: a press may follow, the microphone can open. */ + onPrepare?: () => void; + /** It left again without a press. */ + onPrepareEnd?: () => void; } let { + action = VOICE_MODE_MESSAGE.voiceMessage, class: className = '', disabled = false, - hasAudioModality = false, + filled = false, + hint = null, isLoading = false, isRecording = false, micWarning = null, - onMicClick + onMicClick, + onPrepare, + onPrepareEnd, + secondary = false, + unavailableReason = null }: Props = $props(); - // a model without audio input disables the button; a microphone that can't record keeps it + // no model to take the recording disables the button; a microphone that can't record keeps it // tappable, so a tap can say why - const showWarning = $derived(hasAudioModality && !isRecording && !!micWarning); + const showWarning = $derived(!unavailableReason && !isRecording && !!micWarning); + // a mouse starts recording on press, not on release, so the first words are not lost; + // a touch or a key goes through the click, which is when the browser allows it + const PRESS_CLICK_MS = 1000; + let pressedAt = -Infinity; + + function handlePointerDown(event: PointerEvent) { + if (isRecording || disabled || isLoading || unavailableReason) return; + + if (event.pointerType !== 'mouse' || event.button !== 0) return; + + pressedAt = performance.now(); + onMicClick?.(); + } + + // a touch presses at once, so only a mouse, a pen or the keyboard come ahead of the press + function handlePointerEnter(event: PointerEvent) { + if (event.pointerType !== 'touch' && !isRecording) onPrepare?.(); + } + + function handlePointerLeave(event: PointerEvent) { + if (event.pointerType !== 'touch') onPrepareEnd?.(); + } + + function handleClick() { + // the click that ends the press that already started it; the recording bar may have + // taken the button's place meanwhile, so this one can also never come + if (performance.now() - pressedAt < PRESS_CLICK_MS) { + pressedAt = -Infinity; + + return; + } + + onMicClick?.(); + } + const tooltip = $derived( - !hasAudioModality ? 'Current model does not support audio' : showWarning ? micWarning : null + isRecording + ? null + : (unavailableReason ?? + (showWarning ? micWarning : [action, hint].filter(Boolean).join('. '))) ); @@ -37,28 +94,41 @@ {/snippet} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte index 987c5a350cac..371209f618a6 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -1,6 +1,6 @@ + + + {#snippet stop({ disabled })} + + {/snippet} + diff --git a/ui/apps/chat/src/lib/components/app/chat/index.ts b/ui/apps/chat/src/lib/components/app/chat/index.ts index fce3962c4fe4..f7626c73a4f5 100644 --- a/ui/apps/chat/src/lib/components/app/chat/index.ts +++ b/ui/apps/chat/src/lib/components/app/chat/index.ts @@ -79,6 +79,14 @@ export { default as ChatAttachmentsListItemMcpResource } from './ChatAttachments */ export { default as ChatAttachmentsListItemThumbnailFile } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte'; +/** + * An audio attachment drawn as a clip: a playable waveform (peaks computed from + * the audio when it was stored without them) and, for a voice message, its + * transcript under it on hover, focus or a tap, with the transcribing and failed + * states. `sm` in the chat form, removable; `md` in a sent message. + */ +export { default as ChatAttachmentsListItemVoice } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemVoice.svelte'; + /** * Thumbnail for image attachments with lazy loading and error fallback. * Displays image preview with configurable dimensions. Falls back to placeholder @@ -170,12 +178,20 @@ export { default as ChatForm } from './ChatForm/ChatForm.svelte'; export { default as ChatFormActionsAdd } from './ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte'; /** - * Audio recording button with real-time recording indicator. Records audio - * and converts to WAV format for upload. Only visible when the active model - * supports audio modality and setting for automatic audio input is enabled. Shows recording duration while active. + * Microphone button: starts a voice message or a dictation (its label says which), + * or, disabled, says why no model can take a recording; while recording it is the + * stop button. Shown on an empty message when voice input is available and the + * setting for the microphone on empty input is on. */ export { default as ChatFormActionRecord } from './ChatForm/ChatFormActions/ChatFormActionRecord.svelte'; +/** + * The actions row while the chat form records: cancel, the live waveform and the + * elapsed time, and stop, with a voice message's streaming text under the waveform + * and a waiting state while dictated text is transcribed after recording. + */ +export { default as ChatFormActionsRecording } from './ChatForm/ChatFormActions/ChatFormActionsRecording.svelte'; + /** * Container for chat form action buttons. Arranges file attachment, audio record, * and submit/stop buttons in a horizontal layout. Handles conditional visibility diff --git a/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte index 33be4c624d35..892ae879c286 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte @@ -1,7 +1,8 @@ @@ -24,6 +32,19 @@ onkeydown={(event) => event.stopPropagation()} role="presentation" > + {#if canDictate} + + voiceStore.useForDictation(option.model)} + tooltip="Use for dictation" + tooltipAsTitle + /> + + {/if} + + + +{#if role} + {@const Icon = ICONS[role]} + + + + {#snippet child({ props })} + + + {/snippet} + + + +

{description}

+
+
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte index 1f25c3a5553c..1ad0dfcc0529 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerModelRow.svelte @@ -4,6 +4,7 @@ import ModelContext from '../ModelContext.svelte'; import ModelDraftSubline from '../ModelDraftSubline.svelte'; import ModelId from '../ModelId.svelte'; + import ModelVoiceRole from '../ModelVoiceRole.svelte'; import ModelsManagerStatusCell from './ModelsManagerStatusCell.svelte'; import { modelRowActions } from './row-actions'; import { configuredContext, downloadProgressFor, isRowControlClick } from './utils'; @@ -101,6 +102,8 @@ title={option.model} /> + + diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte index 4e0b81d97bd3..fce6ffc623d4 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte @@ -16,7 +16,7 @@ SETTINGS_KEYS } from '#lib/constants/index.ts'; import { ModelDownloadConfirmAction } from '#lib/enums/index.ts'; - import { modelsStore, settingsStore } from '#lib/stores/index.ts'; + import { modelsStore, settingsStore, voiceStore } from '#lib/stores/index.ts'; import { type GroupedModelOptions, groupModelFamilies, @@ -53,6 +53,12 @@ showOrgName = true }: Props = $props(); let render = $derived(renderOption ?? defaultOption); + // a loaded model that only transcribes dictation is listed apart from the chat models; + // the conversation's own model stays with them, even when it also dictates + const isDictationOnly = (item: ModelItem) => + item.option.model === voiceStore.dictationModel && item.option.model !== currentModel; + let loadedForDictation = $derived(loaded.filter(isDictationOnly)); + let loadedForChat = $derived(loaded.filter((item) => !isDictationOnly(item))); // a large catalog mounts a window at a time: the sentinel at the end of the list // grows the window when it scrolls into view let visibleCount = $state(MODEL_ROW_WINDOW); @@ -180,9 +186,25 @@ {/snippet} - {#each loaded as item (item.option.id)} + {#each loadedForChat as item (item.option.id)} {@render render(item, !showOrgName)} {/each} + + {#if loadedForDictation.length > 0} + + {#if loadedForChat.length > 0} +

+ For dictation +

+ {/if} + + {#each loadedForDictation as item (item.option.id)} + {@render render(item, !showOrgName)} + {/each} + {/if} {/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorOption.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorOption.svelte index b3cb31fa4072..8d87b85b8106 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorOption.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorOption.svelte @@ -5,7 +5,8 @@ ModelCapabilities, ModelId, ModelLoadControl, - ModelRowActions + ModelRowActions, + ModelVoiceRole } from '#lib/components/app/index.ts'; import { SETTINGS_KEYS } from '#lib/constants/index.ts'; import { ServerModelStatus } from '#lib/enums/index.ts'; @@ -89,6 +90,8 @@ title={option.model} /> + + {#if showCapabilities} {/if} diff --git a/ui/apps/chat/src/lib/components/app/models/index.ts b/ui/apps/chat/src/lib/components/app/models/index.ts index 19f043b6b1b5..d379f3d191a6 100644 --- a/ui/apps/chat/src/lib/components/app/models/index.ts +++ b/ui/apps/chat/src/lib/components/app/models/index.ts @@ -53,6 +53,8 @@ export { default as ModelLoadControl } from './ModelLoadControl.svelte'; export { default as ModelOrgAvatar } from './ModelOrgAvatar.svelte'; export { default as ModelRowActions } from './ModelRowActions.svelte'; export { default as ModelsSection } from './ModelsSection.svelte'; +/** **ModelVoiceRole** - a model's part in voice input (dictation, speech to text, voice), as a badge. */ +export { default as ModelVoiceRole } from './ModelVoiceRole.svelte'; /** Capability and modality icon row, shared by every model-id surface. */ export { ModelCapabilityIcons } from '@ggml-org/llama-ui/models'; diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte index 38452cbb951e..40308317396f 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte @@ -7,6 +7,7 @@ SettingsChatImportExportTab, SettingsChatMobileHeader, SettingsChatToolsTab, + SettingsChatVoiceTab, SettingsFooter, SettingsResetButton } from '#lib/components/app/settings/index.ts'; @@ -185,6 +186,12 @@ {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.IMPORT_EXPORT} + {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.VOICE && currentSection.fields} + {:else if currentSection.fields}
+ + +
+ + +
+ + + onConfigChange(MIC_KEY, value)} + type="single" + value={micCurrent} + > + {micLabel} + + + {#each micOptions as option (option.value)} + {option.label} + {/each} + + + +

{SETTING_CONFIG_INFO[MIC_KEY]}

+ + {#if micNamesHidden} +

+ The browser names your microphones once you have allowed one, e.g. after your first + recording. +

+ {/if} +
+ +
+ + + {#if isRouter} + onConfigChange(KEY, value)} + type="single" + value={current} + > + {selectedLabel} + + + + {AUTO_LABEL} + + + {#each optionGroups as group (group.heading)} + + {group.heading} + + {#each group.items as option (option.value)} + {option.label} + {/each} + + {/each} + + + +

+ {SETTING_CONFIG_INFO[KEY]} Only models with audio input are listed. +

+ +

+ A model you pick here is loaded on the server when you dictate, alongside the chat model, if + it isn't loaded already. A server that keeps one model at a time (--models-max 1) unloads the chat model to do it. +

+ {:else} +

+ {#if singleModel} + This server runs one model, {singleModel}. + {singleModelHasAudio + ? 'It has audio input, so it transcribes your voice.' + : 'It has no audio input, so voice input is not available on this server.'} + {:else} + This server runs one model, which transcribes your voice when it has audio input. + {/if} +

+ {/if} +
+ + +
diff --git a/ui/apps/chat/src/lib/components/app/settings/index.ts b/ui/apps/chat/src/lib/components/app/settings/index.ts index 2d2aca5af17a..2d44c88921ba 100644 --- a/ui/apps/chat/src/lib/components/app/settings/index.ts +++ b/ui/apps/chat/src/lib/components/app/settings/index.ts @@ -52,6 +52,15 @@ export { default as SettingsResetButton } from './SettingsResetButton.svelte'; */ export { default as SettingsChatImportExportTab } from './SettingsChat/SettingsChatImportExportTab.svelte'; +/** + * **SettingsChatVoiceTab** - Voice section of the settings + * + * The registry's voice fields, with the transcription model picker between them: + * in router mode it lists the server's models with audio input, on a single-model + * server it says whether that model can transcribe. + */ +export { default as SettingsChatVoiceTab } from './SettingsChat/SettingsChatVoiceTab.svelte'; + /** * Section wrapper for import/export sections. Displays a title, description, * icon button, and optional summary of recent actions. diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts index 46feb4a6dd4a..84275fa6a202 100644 --- a/ui/apps/chat/src/lib/constants/index.ts +++ b/ui/apps/chat/src/lib/constants/index.ts @@ -46,7 +46,6 @@ export * from './mcp-form.constants'; export * from './mcp-resource.constants'; export * from './mention-badge.constants'; export * from './message-export.constants'; -export * from './microphone.constants'; export * from './path-display.constants'; export * from './model-id.constants'; export * from './model-loading.constants'; @@ -74,3 +73,4 @@ export * from './read-media'; export * from './get-datetime'; export * from './browser-info'; export * from './search-chats'; +export * from './voice.constants'; diff --git a/ui/apps/chat/src/lib/constants/microphone.constants.ts b/ui/apps/chat/src/lib/constants/microphone.constants.ts deleted file mode 100644 index 170299f9b875..000000000000 --- a/ui/apps/chat/src/lib/constants/microphone.constants.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** Why the chat form's microphone can't record, as its button and toast tell the user. */ -export const MICROPHONE_UNAVAILABLE_MESSAGE = { - busy: 'The microphone is in use by another app.', - denied: "Microphone access was denied. Allow it in the browser's site settings to record.", - failed: "The microphone couldn't start.", - insecure: - 'The microphone only works over HTTPS or on localhost. Open this page over HTTPS to record.', - notFound: 'No microphone was found.', - unsupported: "This browser can't record audio." -} as const; diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts index 03e9a39d54c6..5bb1bb4ec12e 100644 --- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts @@ -87,6 +87,17 @@ export const SETTINGS_KEYS = { TYP_P: 'typ_p', // General USE_HUGGING_FACE_HUB: 'useHuggingFaceHub', + // Voice + VOICE_AUTO_GAIN: 'voiceAutoGain', + VOICE_BOOST: 'voiceBoost', + VOICE_COLLAPSE_TRANSCRIPTS: 'voiceCollapseTranscripts', + VOICE_ECHO_CANCELLATION: 'voiceEchoCancellation', + VOICE_INPUT_MODE: 'voiceInputMode', + VOICE_MICROPHONE: 'voiceMicrophone', + VOICE_NOISE_SUPPRESSION: 'voiceNoiseSuppression', + VOICE_TRANSCRIBE_MESSAGES: 'voiceTranscribeMessages', + VOICE_TRANSCRIPTION_LANGUAGE: 'voiceTranscriptionLanguage', + VOICE_TRANSCRIPTION_MODEL: 'voiceTranscriptionModel', XTC_PROBABILITY: 'xtc_probability', XTC_THRESHOLD: 'xtc_threshold' } as const; diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index 4f1f77237a6e..4df67abefb18 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -4,19 +4,24 @@ import { COMPACTION } from './compaction.constants'; import { DEFAULT_MCP_CONFIG } from './mcp.constants'; import { SETTINGS_KEYS } from './settings-keys.constants'; import { TITLE_GENERATION } from './title-generation.constants'; +import { VOICE_TRANSCRIPTION_MODEL_AUTO } from './voice.constants'; import { FILE_GLOB_SEARCH_PICKERS } from './working-directory.constants'; +import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice'; +import AudioLines from '@lucide/svelte/icons/audio-lines'; import Code from '@lucide/svelte/icons/code'; import Database from '@lucide/svelte/icons/database'; import File from '@lucide/svelte/icons/file'; import Funnel from '@lucide/svelte/icons/funnel'; import GlassWater from '@lucide/svelte/icons/glass-water'; import ListRestart from '@lucide/svelte/icons/list-restart'; +import Mic from '@lucide/svelte/icons/mic'; import Monitor from '@lucide/svelte/icons/monitor'; import Moon from '@lucide/svelte/icons/moon'; import PencilRuler from '@lucide/svelte/icons/pencil-ruler'; import SlidersVertical from '@lucide/svelte/icons/sliders-vertical'; import Sun from '@lucide/svelte/icons/sun'; -import { SurfaceTheme, SyncableParameterType } from '#lib/enums/index.ts'; +import TextCursorInput from '@lucide/svelte/icons/text-cursor-input'; +import { SurfaceTheme, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts'; import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; import { ColorMode } from '#lib/enums/ui.enums.ts'; import type { @@ -35,7 +40,8 @@ export const SETTINGS_SECTIONS = { GENERAL: { slug: 'general', title: 'General' }, IMPORT_EXPORT: { slug: 'import-export', title: 'Import/Export' }, SAMPLING_PENALTIES: { slug: 'sampling-penalties', title: 'Sampling & Penalties' }, - TOOLS: { slug: 'tools', title: 'Tools' } + TOOLS: { slug: 'tools', title: 'Tools' }, + VOICE: { slug: 'voice', title: 'Voice' } } as const; export const SETTINGS_SECTION_SLUGS = { @@ -45,7 +51,8 @@ export const SETTINGS_SECTION_SLUGS = { GENERAL: SETTINGS_SECTIONS.GENERAL.slug, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.slug, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.slug, - TOOLS: SETTINGS_SECTIONS.TOOLS.slug + TOOLS: SETTINGS_SECTIONS.TOOLS.slug, + VOICE: SETTINGS_SECTIONS.VOICE.slug } as const; export const SETTINGS_SECTION_TITLES = { @@ -55,7 +62,8 @@ export const SETTINGS_SECTION_TITLES = { GENERAL: SETTINGS_SECTIONS.GENERAL.title, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.title, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.title, - TOOLS: SETTINGS_SECTIONS.TOOLS.title + TOOLS: SETTINGS_SECTIONS.TOOLS.title, + VOICE: SETTINGS_SECTIONS.VOICE.title } as const; export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ @@ -132,7 +140,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ }, { defaultValue: true, - help: 'Automatically show microphone button instead of send button when textarea is empty for models with audio modality support.', + help: 'Show the microphone beside the send button while the message is empty, whenever voice input is available (see Voice).', key: SETTINGS_KEYS.AUTO_MIC_ON_EMPTY, label: 'Show microphone on empty input', type: SettingsFieldType.CHECKBOX @@ -405,6 +413,91 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ slug: SETTINGS_SECTION_SLUGS.DISPLAY, title: SETTINGS_SECTION_TITLES.DISPLAY }, + // Voice: the transcription model picker lists the server's models (SettingsChatVoiceTab) + { + icon: Mic, + settings: [ + { + defaultValue: VoiceInputMode.AUTO, + help: 'Automatic sends your voice to a model that understands audio, as a voice message with its transcript, and turns it into text in the message input for any other model. Always dictate turns it into text for every model, so only the text reaches the chat.', + key: SETTINGS_KEYS.VOICE_INPUT_MODE, + label: 'Voice input', + options: [ + { icon: AudioLines, label: 'Automatic', value: VoiceInputMode.AUTO }, + { icon: TextCursorInput, label: 'Always dictate', value: VoiceInputMode.DICTATION } + ], + type: SettingsFieldType.SELECT + }, + { + defaultValue: VOICE_TRANSCRIPTION_MODEL_AUTO, + help: 'The model that turns speech into text when the chat model has no audio input. Automatic uses a model with audio input that is already loaded, so dictating loads nothing.', + key: SETTINGS_KEYS.VOICE_TRANSCRIPTION_MODEL, + label: 'Transcription model', + standaloneField: false, + type: SettingsFieldType.SELECT + }, + { + defaultValue: VOICE_MICROPHONE_AUTO, + help: "The microphone you record from. Automatic takes the system's default one, unless that is a Bluetooth headset's: recording from it switches the headset to its call mode, which plays music in low quality, so the built-in microphone is used instead.", + key: SETTINGS_KEYS.VOICE_MICROPHONE, + label: 'Microphone', + standaloneField: false, + type: SettingsFieldType.SELECT + }, + { + defaultValue: true, + help: 'Write down what was said in each voice message, to read under its waveform. The chat model writes it, and a model without audio input gets it in place of the audio.', + key: SETTINGS_KEYS.VOICE_TRANSCRIBE_MESSAGES, + label: 'Transcribe voice messages', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Show the transcript of a voice message folded under its waveform, to open on hover or with a tap, instead of open.', + key: SETTINGS_KEYS.VOICE_COLLAPSE_TRANSCRIPTS, + label: 'Collapse transcripts', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: true, + help: 'Raise quiet speech to a level the model hears well, up to eight times louder, so a quiet microphone or a voice from afar is still understood. Only speech is measured, never the silence around it, and loud speech is left as it is.', + key: SETTINGS_KEYS.VOICE_BOOST, + label: 'Boost quiet speech', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Let the browser filter background noise out of what the microphone records. Off, the model gets the raw signal, which speech models take well.', + key: SETTINGS_KEYS.VOICE_NOISE_SUPPRESSION, + label: 'Noise suppression', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Let the browser remove what your speakers play from the recording. It makes the system treat a recording as a call, which can lower or pause music and other sound while you record.', + key: SETTINGS_KEYS.VOICE_ECHO_CANCELLATION, + label: 'Echo cancellation', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Let the browser even out how loud you sound. It fades the microphone in, so the first words of a recording can come out quiet.', + key: SETTINGS_KEYS.VOICE_AUTO_GAIN, + label: 'Automatic gain', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: '', + help: 'The language you speak, as a two-letter code such as en or de, passed to the transcription. Leave it empty to let the model tell.', + key: SETTINGS_KEYS.VOICE_TRANSCRIPTION_LANGUAGE, + label: 'Transcription language', + placeholder: 'Automatic', + type: SettingsFieldType.INPUT + } + ], + slug: SETTINGS_SECTION_SLUGS.VOICE, + title: SETTINGS_SECTION_TITLES.VOICE + }, // MCP Servers (non-UI config object) { icon: PencilRuler, diff --git a/ui/apps/chat/src/lib/constants/voice.constants.ts b/ui/apps/chat/src/lib/constants/voice.constants.ts new file mode 100644 index 000000000000..22eb15bec147 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/voice.constants.ts @@ -0,0 +1,61 @@ +import { STORAGE_APP_NAME } from './storage.constants'; + +/** What the chat form's microphone says it will do, or why it can't, on its button. */ +export const VOICE_MODE_MESSAGE = { + dictate: 'Dictate', + dictating: 'Dictating', + recording: 'Recording a voice message', + refining: 'Refining transcript...', + sendAfterRefining: 'Sending once the transcript is refined', + separateModelHint: + 'The transcription model is loaded on the server alongside the chat model, which a server that keeps one model at a time unloads.', + starting: 'Starting...', + tooQuiet: + 'Your microphone sounds quiet. Move closer, or turn its input level up in your system settings.', + transcribing: 'Transcribing...', + unavailable: + 'No model with audio input is available. In router mode, load one or pick a transcription model in Settings > Voice.', + voiceMessage: 'Send a voice message' +} as const; + +/** Where the chat form remembers that it showed the hint about a separate transcription model. */ +export const VOICE_SEPARATE_MODEL_HINT_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.voiceSeparateModelHintSeen`; + +/** Name prefix of a voice message's WAV file; the rest makes it unique per recording. */ +export const VOICE_CLIP_NAME_PREFIX = 'voice-'; + +/** What a voice message attachment is called, in place of its file name. */ +export const VOICE_MESSAGE_LABEL = 'Voice message'; + +/** + * The Transcription model setting's Automatic choice: the chat model when it hears, else a + * model with audio input that is already loaded, so dictating loads nothing. + */ +export const VOICE_TRANSCRIPTION_MODEL_AUTO = ''; + +/** + * Names of speech-to-text models, which write down what is said and are not meant to chat + * (Qwen3-ASR, Whisper, Parakeet...). The server tells them apart by their chat template and + * does not say so, so the app goes by the name. + */ +export const VOICE_TRANSCRIPTION_ONLY_PATTERN = + /(^|[^a-z0-9])(asr|whisper|parakeet|canary|moonshine|sensevoice|stt)([^a-z0-9]|$)/i; + +/** How the model picker and the Models manager name a model's part in voice input. */ +export const VOICE_MODEL_ROLE_LABEL = { + dictation: 'Dictation', + transcription: 'Speech to text', + voice: 'Voice' +} as const; + +/** What each part means, in the badge's tooltip. */ +export const VOICE_MODEL_ROLE_DESCRIPTION = { + dictationAuto: + 'Transcribes your dictation with chat models that cannot hear. Picked automatically, as a loaded model with audio input; choose one in Settings > Voice.', + dictationChosen: + 'Transcribes your dictation with chat models that cannot hear, as chosen in Settings > Voice.', + transcription: + 'A speech-to-text model: it writes down what is said, for dictation, and is not meant to chat.', + voice: + 'Hears audio: as the chat model it gets your voice messages, and it can also transcribe dictation.' +} as const; diff --git a/ui/apps/chat/src/lib/enums/attachment.enums.ts b/ui/apps/chat/src/lib/enums/attachment.enums.ts index 5f096b974486..035fdac9cdd0 100644 --- a/ui/apps/chat/src/lib/enums/attachment.enums.ts +++ b/ui/apps/chat/src/lib/enums/attachment.enums.ts @@ -50,5 +50,6 @@ export enum AttachmentLabel { FILE = 'File', MCP_PROMPT = 'MCP Prompt', MCP_RESOURCE = 'MCP Resource', - PDF_FILE = 'PDF File' + PDF_FILE = 'PDF File', + VOICE_TRANSCRIPT = 'Voice message transcript' } diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 29fd94373ee0..8ffd6398bb7d 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -121,3 +121,5 @@ export { } from './tools.enums'; export { SplashOrientation } from './splash.enums'; + +export { VoiceInputMode, VoiceMode, VoiceModelRole } from './voice.enums'; diff --git a/ui/apps/chat/src/lib/enums/voice.enums.ts b/ui/apps/chat/src/lib/enums/voice.enums.ts new file mode 100644 index 000000000000..0980b3aed5db --- /dev/null +++ b/ui/apps/chat/src/lib/enums/voice.enums.ts @@ -0,0 +1,27 @@ +/** The Voice input setting: what the microphone does with a model that understands audio. */ +export enum VoiceInputMode { + /** Send the voice to a model with audio input, dictate otherwise. */ + AUTO = 'auto', + /** Always turn speech into text; only the text reaches the chat. */ + DICTATION = 'dictation' +} + +/** What a recording becomes for the conversation's model, as the chat form resolves it. */ +export enum VoiceMode { + /** Speech becomes text in the input; no audio is attached. */ + DICTATION = 'dictation', + /** No model can take audio, so the microphone has nothing to do. */ + UNAVAILABLE = 'unavailable', + /** The clip is attached and sent as audio, with a transcript to read. */ + VOICE_MESSAGE = 'voice-message' +} + +/** A model's part in voice input, as the model picker and the Models manager show it. */ +export enum VoiceModelRole { + /** The model that transcribes dictation for chat models that cannot hear */ + DICTATION = 'dictation', + /** A speech-to-text model: for dictation, not for chat */ + TRANSCRIPTION = 'transcription', + /** A chat model with audio input: it gets voice messages */ + VOICE = 'voice' +} diff --git a/ui/apps/chat/src/lib/hooks/use-chat-form-voice.svelte.ts b/ui/apps/chat/src/lib/hooks/use-chat-form-voice.svelte.ts new file mode 100644 index 000000000000..16e57a5844c9 --- /dev/null +++ b/ui/apps/chat/src/lib/hooks/use-chat-form-voice.svelte.ts @@ -0,0 +1,405 @@ +/** + * Voice input for the chat form. + * + * Resolves what the microphone does for the conversation's model (a voice message, + * dictation, or nothing, see resolveVoiceMode) and runs a recording: live levels and + * elapsed time, and on stop either a voice message attachment, whose transcript follows, + * or the dictated text. Writing the text into the message is createDictation()'s; this + * adds what is the chat form's own around it. + * A voice message's live text shows as the empty message box's placeholder; focusing + * the box makes it editable text there until the recording stops, when it goes with + * the clip (edited, as its transcript). + */ + +import { + createDictation, + describeMicrophoneError, + MicrophoneWarmup, + VoiceCaptureError, + type VoiceRecorderStatus, + type VoiceSessionOptions, + type VoiceSessionResult +} from '@ggml-org/llama-voice'; +import { + SETTINGS_KEYS, + VOICE_CLIP_NAME_PREFIX, + VOICE_MODE_MESSAGE, + VOICE_SEPARATE_MODEL_HINT_LOCALSTORAGE_KEY +} from '#lib/constants/index.ts'; +import { MimeTypeAudio, VoiceMode } from '#lib/enums/index.ts'; +import { VoiceService } from '#lib/services/voice.service.ts'; +import { + serverStore, + settingsStore, + voiceStore, + voiceTranscriptsStore +} from '#lib/stores/index.ts'; +import type { ChatUploadedFile } from '#lib/types/index.ts'; +import { uuid } from '#lib/utils/index.ts'; +import { voiceModeLabel } from '#lib/utils/voice-mode.ts'; +import { onDestroy } from 'svelte'; +import { toast } from 'svelte-sonner'; + +/** What the form needs of a VoiceRecorder; tests and stories pass a fake. */ +export interface VoiceRecorderLike { + readonly levels: number[]; + readonly live: boolean; + readonly liveText: string; + /** The speech stays quiet even at the highest gain; a recorder that cannot tell leaves it out */ + readonly quiet?: boolean; + readonly status: VoiceRecorderStatus; + start(options?: VoiceSessionOptions): Promise; + stop(): Promise; + cancel(): void; +} + +/** Where a recording is: off, waiting for the microphone, recording, or waiting for dictated text. */ +export type ChatFormVoiceState = 'idle' | 'starting' | 'recording' | 'transcribing'; + +interface UseChatFormVoiceOptions { + recorder: VoiceRecorderLike; + getValue: () => string; + /** Writes the message as dictation changes it; not a user edit. */ + setValue: (value: string) => void; + getCaretOffset: () => number; + /** Puts the caret after the dictated text once it is final. */ + setCaretOffset: (offset: number) => void; + addVoiceFile: (file: ChatUploadedFile) => void; + /** Why the last start failed, for the microphone button; null once one worked. */ + onMicError: (message: string | null) => void; +} + +const ELAPSED_TICK_MS = 200; + +function readHintSeen(): boolean { + try { + return localStorage.getItem(VOICE_SEPARATE_MODEL_HINT_LOCALSTORAGE_KEY) === 'true'; + } catch { + return false; + } +} + +function writeHintSeen(): void { + try { + localStorage.setItem(VOICE_SEPARATE_MODEL_HINT_LOCALSTORAGE_KEY, 'true'); + } catch { + // private mode: the hint shows again next time + } +} + +function readAsDataUrl(blob: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + + reader.onload = () => resolve(reader.result as string); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} + +export function useChatFormVoice(options: UseChatFormVoiceOptions) { + const config = $derived(settingsStore.config); + const isRouter = $derived(serverStore.isRouterMode); + // what the microphone does for the conversation's model, shared with the model lists + const resolution = $derived(voiceStore.resolution); + // a router with a model that hears keeps the button, so it can say where to pick it + const anyAudioModel = $derived(voiceStore.anyAudioModel); + + let hintSeen = $state(readHintSeen()); + let state = $state('idle'); + let elapsedMs = $state(0); + // the mode of the recording under way, fixed when it starts + let recordingMode = $state(VoiceMode.UNAVAILABLE); + let ticker: ReturnType | undefined; + // bumped when the dictation changes, so the getters that read it follow + let dictationVersion = $state(0); + // bumped by cancel, so a recording still starting or stopping is dropped + let generation = 0; + // the pointer or the focus is on the microphone button, see prepare + let preparing = false; + + const warmup = new MicrophoneWarmup(); + const dictation = createDictation({ + getCaretOffset: options.getCaretOffset, + getValue: options.getValue, + onChange: () => dictationVersion++, + onError: (error) => + toast.error(error instanceof Error ? error.message : 'Transcription failed'), + setCaretOffset: options.setCaretOffset, + setValue: options.setValue + }); + const recorder = options.recorder; + const unavailableReason = $derived( + resolution.mode === VoiceMode.UNAVAILABLE ? resolution.reason : null + ); + const hint = $derived( + resolution.mode === VoiceMode.DICTATION && resolution.separateModel && !hintSeen + ? VOICE_MODE_MESSAGE.separateModelHint + : null + ); + + function startTicker() { + const startedAt = Date.now(); + + elapsedMs = 0; + ticker = setInterval(() => (elapsedMs = Date.now() - startedAt), ELAPSED_TICK_MS); + } + + function stopTicker() { + clearInterval(ticker); + ticker = undefined; + } + + /** + * A voice message's live text moves from the placeholder into the message, as text the + * user can edit, and what is said next follows it there. + */ + function adoptLiveText() { + if (recordingMode !== VoiceMode.VOICE_MESSAGE || dictation.active) return; + + if (state !== 'starting' && state !== 'recording') return; + + dictation.begin({ at: options.getValue().length, keepsEdits: true }); + dictation.write(recorder?.liveText ?? ''); + options.setCaretOffset(dictation.end); + } + + /** The session options of a recording started now: the settings, the server and the mode. */ + function wiringFor(mode: VoiceMode, model: string | null) { + const transcribe = + mode === VoiceMode.DICTATION || config[SETTINGS_KEYS.VOICE_TRANSCRIBE_MESSAGES] !== false; + + return VoiceService.sessionOptions(config, { isRouter, model, transcribe }); + } + + /** + * Opens the microphone while the pointer or the focus is on its button, if the page may + * already use it: by the click it has settled, so the first words are not quiet, and the + * recording starts at once. Let go shortly after the pointer leaves (unprepare). + */ + async function prepare() { + if (!recorder || state !== 'idle' || resolution.mode === VoiceMode.UNAVAILABLE) return; + + preparing = true; + + const wiring = await wiringFor(resolution.mode, resolution.transcriptionModel); + + // the pointer may have left meanwhile, and a press asks for its own microphone + if (preparing && state === 'idle') warmup.open(wiring.capture); + } + + function unprepare() { + preparing = false; + warmup.release(); + } + + async function start() { + if (!recorder || state !== 'idle' || resolution.mode === VoiceMode.UNAVAILABLE) return; + + const mode = resolution.mode; + const model = resolution.transcriptionModel; + + if (hint) { + hintSeen = true; + writeHintSeen(); + } + + recordingMode = mode; + state = 'starting'; + + if (mode === VoiceMode.DICTATION) dictation.begin(); + + const run = ++generation; + + try { + const wiring = await wiringFor(mode, model); + // the microphone the hover opened, when it is open for the same options + const stream = await warmup.take(wiring.capture); + + // cancelled while the microphone opened + if (run !== generation) { + for (const track of stream?.getTracks() ?? []) track.stop(); + + return; + } + + await recorder.start({ + ...wiring, + capture: { ...wiring.capture, ...(stream ? { stream } : {}) }, + // a voice message's text reaches the message only once the user made it editable + onText: (text) => dictation.write(text) + }); + } catch (error) { + if (run !== generation) return; + + state = 'idle'; + dictation.cancel(); + + const message = + error instanceof VoiceCaptureError ? error.message : describeMicrophoneError(error); + + options.onMicError(message); + toast.error(message); + + return; + } + + // cancelled meanwhile: the recorder dropped its own session + if (run !== generation) return; + + options.onMicError(null); + state = 'recording'; + startTicker(); + } + + async function stop() { + if (!recorder || state !== 'recording') return; + + const run = generation; + const mode = recordingMode; + + stopTicker(); + + let result: VoiceSessionResult; + + try { + result = await recorder.stop(); + } catch (error) { + console.error('Failed to stop the recording:', error); + dictation.cancel(); + state = 'idle'; + + return; + } + + if (run !== generation) return; + + if (mode === VoiceMode.VOICE_MESSAGE) { + // the clip carries the text from here: what the user edited is its transcript + const taken = dictation.take(); + + state = 'idle'; + await attachVoiceMessage(result, taken?.userEdited ? taken.text : null); + + return; + } + + // with live text the message already shows it and can be edited, while the whole + // recording is transcribed once more to refine it; otherwise wait for the text + state = result.transcript && !result.liveText ? 'transcribing' : 'idle'; + await dictation.finish(result); + + if (run === generation) state = 'idle'; + } + + async function attachVoiceMessage( + { clip, transcript }: VoiceSessionResult, + edited: string | null = null + ) { + const name = `${VOICE_CLIP_NAME_PREFIX}${Date.now()}-${uuid().slice(0, 8)}.wav`; + const file = new File([clip.blob], name, { type: MimeTypeAudio.WAV }); + + if (transcript) voiceTranscriptsStore.track(name, transcript); + + if (edited !== null) voiceTranscriptsStore.setTranscript(name, edited); + + options.addVoiceFile({ + file, + id: uuid(), + name, + preview: await readAsDataUrl(clip.blob), + size: file.size, + type: MimeTypeAudio.WAV, + voice: { durationMs: clip.durationMs, peaks: clip.peaks } + }); + } + + /** Drops the recording and any text it dictated. */ + function cancel() { + generation++; + stopTicker(); + recorder?.cancel(); + dictation.cancel(); + state = 'idle'; + } + + /** Follows an edit the user typed while dictation writes into the message. */ + function handleUserInput() { + dictation.edited(); + } + + onDestroy(() => { + preparing = false; + warmup.drop(); + + if (state !== 'idle') cancel(); + }); + + return { + adoptLiveText, + cancel, + get elapsedMs() { + return elapsedMs; + }, + handleUserInput, + get hint() { + return hint; + }, + /** A recording (or its dictated text) is under way: the form shows the recording bar. */ + get isActive() { + return state !== 'idle'; + }, + /** The dictated text shown is still being refined by a pass over the whole recording. */ + get isRefining() { + void dictationVersion; + + return dictation.refining; + }, + /** What the microphone button says it will do. */ + get label() { + return voiceModeLabel(resolution); + }, + get levels() { + return recorder?.levels ?? []; + }, + /** Text streaming while a voice message is recorded, shown under the waveform. */ + get liveCaption() { + void dictationVersion; + + // once made editable, the text is in the message instead + return recordingMode === VoiceMode.VOICE_MESSAGE && !dictation.active + ? (recorder?.liveText ?? '') + : ''; + }, + get mode() { + return state === 'idle' ? resolution.mode : recordingMode; + }, + /** The pointer or the focus is on the microphone button: see prepare(). */ + prepare, + /** The recording's speech is too quiet even at the highest gain: the form says so. */ + get quiet() { + return state === 'recording' && (recorder?.quiet ?? false); + }, + get resolution() { + return resolution; + }, + /** Resolves once the text in the message is final, at once when nothing is refining it. */ + settled(): Promise { + return dictation.settled(); + }, + /** Whether the form shows a microphone button at all. */ + get showButton() { + return resolution.mode !== VoiceMode.UNAVAILABLE || anyAudioModel; + }, + start, + get state() { + return state; + }, + stop, + get unavailableReason() { + return unavailableReason; + }, + /** The pointer or the focus left the microphone button without a press. */ + unprepare + }; +} diff --git a/ui/apps/chat/src/lib/services/chat.service.ts b/ui/apps/chat/src/lib/services/chat.service.ts index 848bd06efb39..38c7eba144b1 100644 --- a/ui/apps/chat/src/lib/services/chat.service.ts +++ b/ui/apps/chat/src/lib/services/chat.service.ts @@ -50,6 +50,12 @@ import { getAuthHeaders, getJsonHeaders } from '#lib/utils/api-headers.ts'; import { formatAttachmentText } from '#lib/utils/formatters.ts'; import { streamIdentity } from '#lib/utils/stream-identity.ts'; +/** How stored messages are shaped for the model a request goes to. */ +export interface ApiMessageConversionOptions { + /** False when the model has no audio input: voice messages go as their transcript. */ + audioInput?: boolean; +} + interface ResumableStreamState { bytesReceived: number; updatedAt: number; @@ -133,13 +139,24 @@ export class ChatService { } } + /** + * How messages are shaped for `model`: whether it takes audio, known only once its + * modalities are. Unknown modalities keep the audio, as before voice messages. + */ + static conversionOptionsFor(model?: string | null): ApiMessageConversionOptions { + const modalities = modelsStore.props.getModelModalities(model ?? ''); + + return modalities ? { audioInput: modalities.audio } : {}; + } + /** * Converts a database message with attachments to API chat message format. * Processes various attachment types (images, text files, PDFs) and formats them * as content parts suitable for the chat completion API. */ static async convertDbMessageToApiChatMessageData( - message: DatabaseMessage & { extra?: DatabaseMessageExtra[] } + message: DatabaseMessage & { extra?: DatabaseMessageExtra[] }, + options: ApiMessageConversionOptions = {} ): Promise { // Handle tool result messages (role: 'tool') if (message.role === MessageRole.TOOL && message.toolCallId) { @@ -231,6 +248,20 @@ export class ChatService { ); for (const audio of audioFiles) { + // a model that cannot hear reads what was said instead; one that can gets the audio alone + if (options.audioInput === false && audio.transcript) { + contentParts.push({ + text: formatAttachmentText( + AttachmentLabel.VOICE_TRANSCRIPT, + audio.name, + audio.transcript + ), + type: ContentPartType.TEXT + }); + + continue; + } + contentParts.push({ input_audio: { data: audio.base64Data, @@ -816,14 +847,18 @@ export class ChatService { * messages. Shared by sendMessage, preEncode and the agentic flow. */ static async normalizeMessagesForApi( - messages: ApiChatMessageData[] | (DatabaseMessage & { extra?: DatabaseMessageExtra[] })[] + messages: ApiChatMessageData[] | (DatabaseMessage & { extra?: DatabaseMessageExtra[] })[], + model?: string | null ): Promise { + const options = ChatService.conversionOptionsFor(model); + return ( await Promise.all( messages.map((msg) => { if ('id' in msg && 'convId' in msg && 'timestamp' in msg) { return ChatService.convertDbMessageToApiChatMessageData( - msg as DatabaseMessage & { extra?: DatabaseMessageExtra[] } + msg as DatabaseMessage & { extra?: DatabaseMessageExtra[] }, + options ); } @@ -855,8 +890,10 @@ export class ChatService { signal?: AbortSignal, tools?: OpenAIToolDefinition[] ): Promise { - const normalizedMessages: ApiChatMessageData[] = - await ChatService.normalizeMessagesForApi(messages); + const normalizedMessages: ApiChatMessageData[] = await ChatService.normalizeMessagesForApi( + messages, + model + ); const requestBody: Record = { messages: normalizedMessages.map((msg: ApiChatMessageData) => { const mapped: Record = { @@ -1106,8 +1143,10 @@ export class ChatService { xtc_probability, xtc_threshold } = options; - const normalizedMessages: ApiChatMessageData[] = - await ChatService.normalizeMessagesForApi(messages); + const normalizedMessages: ApiChatMessageData[] = await ChatService.normalizeMessagesForApi( + messages, + options.model + ); // Filter out image attachments if the model doesn't support vision if (options.model && !modelsStore.props.modelSupportsVision(options.model)) { diff --git a/ui/apps/chat/src/lib/services/database.service.ts b/ui/apps/chat/src/lib/services/database.service.ts index de8ed4701e12..e77b97a964ca 100644 --- a/ui/apps/chat/src/lib/services/database.service.ts +++ b/ui/apps/chat/src/lib/services/database.service.ts @@ -572,6 +572,16 @@ export class DatabaseService { return result; } + /** + * Gets the messages written at or after `timestamp`, in any conversation. + * + * @param timestamp - Epoch ms + * @returns Messages, oldest first + */ + static async getMessagesSince(timestamp: number): Promise { + return await db[IDXDB_TABLES.messages].where('timestamp').aboveOrEqual(timestamp).toArray(); + } + /** * Imports multiple conversations and their messages. * Skips conversations that already exist. diff --git a/ui/apps/chat/src/lib/services/index.ts b/ui/apps/chat/src/lib/services/index.ts index 04b522538c8e..cb98696f8fbe 100644 --- a/ui/apps/chat/src/lib/services/index.ts +++ b/ui/apps/chat/src/lib/services/index.ts @@ -367,3 +367,15 @@ export { MigrationService } from './migration.service'; * @see settingsStore in stores/settings/index.svelte.ts - reactive state + business logic */ export { SettingsService } from './settings.service'; + +/** + * **VoiceService** - Wiring between the voice engine and this app + * + * Builds what the engine (@ggml-org/llama-voice) is handed from outside: how it reaches the active + * server (routes, API key, whether realtime can be used) and the capture and transcribe + * options the Voice settings ask for. Every feature that records starts its session with + * these, so they all reach the server the same way and follow the same settings. + * + * @see voice.service.ts + */ +export { VoiceService } from './voice.service'; diff --git a/ui/apps/chat/src/lib/services/voice.service.ts b/ui/apps/chat/src/lib/services/voice.service.ts new file mode 100644 index 000000000000..b75f14b6db79 --- /dev/null +++ b/ui/apps/chat/src/lib/services/voice.service.ts @@ -0,0 +1,116 @@ +import { + resolveMicrophone, + VOICE_MICROPHONE_AUTO, + type VoiceCaptureOptions, + type VoiceServerContext, + type VoiceSessionOptions +} from '@ggml-org/llama-voice'; +import { SETTINGS_KEYS } from '#lib/constants/index.ts'; +import type { SettingsConfigType } from '#lib/types/index.ts'; +import { getAuthHeaders } from '#lib/utils/api-headers.ts'; +import { withBase } from '#lib/utils/base-path.ts'; + +/** What a feature asks of the voice wiring, besides the settings. */ +export interface VoiceSessionRequest { + /** The model that transcribes, from resolveVoiceMode(); null leaves it to the server */ + model: string | null; + /** Router mode: the model goes in the request, as the router routes on it */ + isRouter: boolean; + /** False records without transcribing, e.g. a voice message when transcripts are off */ + transcribe?: boolean; + /** + * The microphone processing to ask for, in place of what the Voice settings switch on, + * e.g. echo cancellation for a spoken conversation that plays replies aloud + */ + constraints?: MediaTrackConstraints; +} + +/** + * The session options voice features share: where to capture from, and how to transcribe. + * The capture is always plain options, so a feature can also open a VoiceCapture of its own + * with them. + */ +export type VoiceSessionWiring = Pick & { + capture: VoiceCaptureOptions; +}; + +/** + * **VoiceService** - How the voice engine (@ggml-org/llama-voice) reaches this app's server and settings + * + * The engine imports no app code: it is handed a VoiceServerContext and plain capture + * options. This builds both from the active server and the Voice settings, once for every + * feature that records (the chat form's dictation and voice messages, voice mode), so they + * reach the server the same way and follow the same settings. + */ +export class VoiceService { + /** The transcription language from the Voice settings, undefined to let the model tell. */ + static language(config: SettingsConfigType): string | undefined { + return String(config[SETTINGS_KEYS.VOICE_TRANSCRIPTION_LANGUAGE] ?? '').trim() || undefined; + } + + /** + * The microphone processing the Voice settings switch on, laid over the engine's raw + * signal; undefined when none is. + */ + static processing(config: SettingsConfigType): MediaTrackConstraints | undefined { + const processing: MediaTrackConstraints = { + ...(config[SETTINGS_KEYS.VOICE_NOISE_SUPPRESSION] === true ? { noiseSuppression: true } : {}), + ...(config[SETTINGS_KEYS.VOICE_ECHO_CANCELLATION] === true ? { echoCancellation: true } : {}), + ...(config[SETTINGS_KEYS.VOICE_AUTO_GAIN] === true ? { autoGainControl: true } : {}) + }; + + return Object.keys(processing).length > 0 ? processing : undefined; + } + + /** + * The server's routes and auth for the engine, and whether its realtime socket can be + * used: a browser websocket can not send the API key, so a server that needs one gets + * HTTP only. + */ + static serverContext(): { context: VoiceServerContext; realtime: boolean } { + const hasAuth = Object.keys(getAuthHeaders()).some( + (key) => key.toLowerCase() === 'authorization' + ); + + return { + context: { + getHeaders: () => getAuthHeaders(), + resolveUrl: (path) => withBase(path.replace(/^\./, '')) + }, + realtime: !hasAuth + }; + } + + /** + * The capture, realtime and transcribe options of a voice session, from the Voice + * settings (microphone, processing, boost, language) and the active server. Async: + * picking the microphone may list the devices. + */ + static async sessionOptions( + config: SettingsConfigType, + request: VoiceSessionRequest + ): Promise { + const { context, realtime } = VoiceService.serverContext(); + const deviceId = await resolveMicrophone( + String(config[SETTINGS_KEYS.VOICE_MICROPHONE] ?? VOICE_MICROPHONE_AUTO) + ); + const constraints = request.constraints ?? VoiceService.processing(config); + + return { + capture: { + boost: config[SETTINGS_KEYS.VOICE_BOOST] !== false, + ...(deviceId ? { deviceId } : {}), + ...(constraints ? { constraints } : {}) + }, + realtime, + transcribe: + request.transcribe === false + ? undefined + : { + context, + language: VoiceService.language(config), + model: request.isRouter && request.model ? request.model : undefined + } + }; + } +} diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts index b607a1373c56..2eb93ad3aa98 100644 --- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts @@ -347,8 +347,10 @@ class AgenticStore { console.log(`[AgenticStore] Starting agentic flow with ${tools.length} tools`); - const normalizedMessages: ApiChatMessageData[] = - await ChatService.normalizeMessagesForApi(messages); + const normalizedMessages: ApiChatMessageData[] = await ChatService.normalizeMessagesForApi( + messages, + options.model + ); this.updateSession(conversationId, { currentTurn: 0, diff --git a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts index ef8a1110035b..20c95be39867 100644 --- a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts @@ -1480,7 +1480,7 @@ class ChatStore implements ChatStreamHost, ChatFlowsHost { const allMessages = await conversationsStore.getConversationMessages(convId); const branchPath = [...filterByLeafNodeId(allMessages, leafId, false)]; const request = await agenticStore.requestFor( - await ChatService.normalizeMessagesForApi(sliceAtLastCompaction(branchPath)), + await ChatService.normalizeMessagesForApi(sliceAtLastCompaction(branchPath), model), this.toolPolicy() ); @@ -1646,7 +1646,7 @@ class ChatStore implements ChatStreamHost, ChatFlowsHost { // message shaping, cut before the preserved steps: the server // reuses the prefix it cached and only the instruction is new. const request = await agenticStore.requestFor( - await ChatService.normalizeMessagesForApi(source.slice(0, cut)), + await ChatService.normalizeMessagesForApi(source.slice(0, cut), effectiveModel), this.toolPolicy() ); const configValue = settingsStore.config; diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts index e98a48d06c45..3a2c5914c771 100644 --- a/ui/apps/chat/src/lib/stores/index.ts +++ b/ui/apps/chat/src/lib/stores/index.ts @@ -61,6 +61,10 @@ export { permissionsStore } from './permissions.svelte'; // TOOLS export { toolsStore } from './tools.svelte'; +// VOICE (which model does what, and transcripts of voice messages on their way) +export { voiceStore } from './voice.svelte'; +export { voiceTranscriptsStore } from './voice-transcripts.svelte'; + // ENVIRONMENT / META export { versionStore } from './version.svelte'; diff --git a/ui/apps/chat/src/lib/stores/voice-transcripts.svelte.ts b/ui/apps/chat/src/lib/stores/voice-transcripts.svelte.ts new file mode 100644 index 000000000000..1fa9d8dc1ec4 --- /dev/null +++ b/ui/apps/chat/src/lib/stores/voice-transcripts.svelte.ts @@ -0,0 +1,163 @@ +/** + * voiceTranscriptsStore - Transcripts of voice messages that are on their way + * + * A voice message is attached as soon as the recording stops, while its transcript + * can take a few seconds more. This keeps each pending transcript by the clip's name + * (unique per recording), so the chip in the form and the sent message show its + * state, a send picks it up once it is there, and a message sent before it arrived + * gets it written into its stored attachment afterwards. Kept in memory only. + */ + +import type { VoiceTranscriptStatus } from '@ggml-org/llama-ui/voice'; +import { AttachmentType } from '#lib/enums/index.ts'; +import { DatabaseService } from '#lib/services/database.service.ts'; +// direct imports between stores, not via the barrel, to avoid circular deps +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import type { + DatabaseMessage, + DatabaseMessageExtra, + DatabaseMessageExtraAudioFile +} from '#lib/types/index.ts'; +import { SvelteMap } from 'svelte/reactivity'; + +export type VoiceTranscriptState = + | { status: 'transcribing' } + | { status: 'done'; transcript: string } + | { status: 'error'; message: string }; + +/** How long a transcript that came back keeps looking for the message it belongs to. */ +const APPLY_RETRY_DELAYS_MS = [500, 1500, 4000]; + +function isPendingClip(extra: DatabaseMessageExtra, name: string): boolean { + return ( + extra.type === AttachmentType.AUDIO && + extra.name === name && + extra.voice === true && + extra.transcript === undefined + ); +} + +/** The extras with the clip's transcript filled in, or null when none of them is that clip. */ +export function withTranscript( + extras: DatabaseMessageExtra[] | undefined, + name: string, + transcript: string +): DatabaseMessageExtra[] | null { + if (!extras?.some((extra) => isPendingClip(extra, name))) return null; + + return extras.map((extra) => + isPendingClip(extra, name) + ? ({ ...(extra as DatabaseMessageExtraAudioFile), transcript } as DatabaseMessageExtra) + : extra + ); +} + +class VoiceTranscriptsStore { + // clips whose transcript the user wrote while recording: the model's does not replace it + private edited = new Set(); + private entries = new SvelteMap(); + private recordedAt = new Map(); + + /** Drops a clip removed from the form before it was sent, or whose message has its transcript. */ + forget(name: string): void { + this.entries.delete(name); + this.recordedAt.delete(name); + this.edited.delete(name); + } + + /** The state of a clip's transcript, undefined when none was asked for in this session. */ + get(name: string): VoiceTranscriptState | undefined { + return this.entries.get(name); + } + + /** Sets a clip's transcript to the text the user edited while recording; the model's is ignored. */ + setTranscript(name: string, transcript: string): void { + this.edited.add(name); + this.recordedAt.set(name, this.recordedAt.get(name) ?? Date.now()); + this.entries.set(name, { status: 'done', transcript }); + } + + /** A clip's transcript as it is shown: the one stored with it, else the one on its way. */ + shown(name: string, stored?: string): { status: VoiceTranscriptStatus; transcript?: string } { + const transcript = stored ?? this.transcriptOf(name); + + if (transcript !== undefined) return { status: 'done', transcript }; + + return { status: this.entries.get(name)?.status ?? 'idle' }; + } + + /** Follows a clip's transcript, and writes it into the message it went out with. */ + track(name: string, transcript: Promise): void { + this.entries.set(name, { status: 'transcribing' }); + this.recordedAt.set(name, Date.now()); + + transcript.then( + (text) => { + if (!this.entries.has(name) || this.edited.has(name)) return; + + this.entries.set(name, { status: 'done', transcript: text }); + void this.applyToMessage(name, text); + }, + (error: unknown) => { + if (!this.entries.has(name) || this.edited.has(name)) return; + + console.warn('Voice message transcription failed:', error); + this.entries.set(name, { + message: error instanceof Error ? error.message : String(error), + status: 'error' + }); + } + ); + } + + /** The transcript once it is there. */ + transcriptOf(name: string): string | undefined { + const entry = this.entries.get(name); + + return entry?.status === 'done' ? entry.transcript : undefined; + } + + private async applyToMessage(name: string, transcript: string): Promise { + for (const delay of [0, ...APPLY_RETRY_DELAYS_MS]) { + if (delay) await new Promise((resolve) => setTimeout(resolve, delay)); + + // in its message now, which shows it from there + if (await this.writeTranscript(name, transcript)) return this.forget(name); + } + // not sent (still in the form, or dropped): a send reads it from here + } + + private async writeTranscript(name: string, transcript: string): Promise { + const active = (conversationsStore.activeMessages as DatabaseMessage[]).find((message) => + message.extra?.some((extra) => isPendingClip(extra, name)) + ); + + if (active) { + // plain objects: IndexedDB cannot clone the state proxies + const extra = withTranscript($state.snapshot(active.extra), name, transcript)!; + + await DatabaseService.updateMessage(active.id, { extra }); + conversationsStore.updateMessageAtIndex(conversationsStore.findMessageIndex(active.id), { + extra + }); + + return true; + } + + // the chat was left before the transcript came back: the message is newer than the clip + const since = this.recordedAt.get(name) ?? Date.now(); + const stored = (await DatabaseService.getMessagesSince(since)).find( + (message: DatabaseMessage) => message.extra?.some((extra) => isPendingClip(extra, name)) + ); + + if (!stored) return false; + + await DatabaseService.updateMessage(stored.id, { + extra: withTranscript(stored.extra, name, transcript)! + }); + + return true; + } +} + +export const voiceTranscriptsStore = new VoiceTranscriptsStore(); diff --git a/ui/apps/chat/src/lib/stores/voice.svelte.ts b/ui/apps/chat/src/lib/stores/voice.svelte.ts new file mode 100644 index 000000000000..8db801d342f9 --- /dev/null +++ b/ui/apps/chat/src/lib/stores/voice.svelte.ts @@ -0,0 +1,98 @@ +/** + * voiceStore - Which model does what in voice input + * + * One place for what the microphone does with the conversation's model (a voice message, + * dictation, or nothing, see resolveVoiceMode) and for the model that transcribes + * dictation, so the chat form, the model picker and the Models manager agree on it: a + * model's part (roleOf) is shown as a badge where models are listed. + */ + +import { SETTINGS_KEYS, VOICE_TRANSCRIPTION_MODEL_AUTO } from '#lib/constants/index.ts'; +import { VoiceInputMode, VoiceModelRole } from '#lib/enums/index.ts'; +import { serverStore } from '#lib/stores/llama-server.svelte.ts'; +// direct imports between stores, not via the barrel, to avoid circular deps +import { modelsStore } from '#lib/stores/models/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { dictationModelFor, resolveVoiceMode, voiceModelRole } from '#lib/utils/voice-mode.ts'; + +class VoiceStore { + /** A router with a model that hears: the microphone stays, so it can say where to pick one. */ + readonly anyAudioModel = $derived.by(() => { + void modelsStore.props.cacheVersion; + + return ( + serverStore.isRouterMode && modelsStore.models.some((option) => this.hasAudio(option.model)) + ); + }); + private readonly config = $derived(settingsStore.config); + + private readonly transcriptionSetting = $derived( + String(this.config[SETTINGS_KEYS.VOICE_TRANSCRIPTION_MODEL] ?? VOICE_TRANSCRIPTION_MODEL_AUTO) + ); + + /** The dictation model is picked automatically, not chosen in Settings > Voice. */ + readonly dictationIsAutomatic = $derived( + this.transcriptionSetting.trim() === VOICE_TRANSCRIPTION_MODEL_AUTO + ); + + /** Router mode: what Automatic transcribes with when the chat model can't hear, a loaded model with audio input. */ + readonly loadedAudioModel = $derived.by(() => { + void modelsStore.props.cacheVersion; + + if (!serverStore.isRouterMode) return null; + + return ( + modelsStore.models.find( + (option) => this.hasAudio(option.model) && modelsStore.isModelLoaded(option.model) + )?.model ?? null + ); + }); + + /** The model that transcribes dictation for chat models that can't hear, null when none can. */ + readonly dictationModel = $derived.by(() => { + const singleModel = serverStore.isRouterMode ? null : modelsStore.activeModelId; + + return dictationModelFor({ + isRouter: serverStore.isRouterMode, + loadedAudioModel: this.loadedAudioModel, + singleModel, + singleModelHasAudio: this.hasAudio(singleModel), + transcriptionModel: this.transcriptionSetting, + transcriptionModelHasAudio: this.hasAudio(this.transcriptionSetting || null) + }); + }); + + /** What the microphone does for the conversation's model. */ + readonly resolution = $derived.by(() => { + const chatModel = modelsStore.activeModelId; + + return resolveVoiceMode({ + chatModel, + chatModelHasAudio: this.hasAudio(chatModel), + isRouter: serverStore.isRouterMode, + loadedAudioModel: this.loadedAudioModel, + setting: String(this.config[SETTINGS_KEYS.VOICE_INPUT_MODE] ?? VoiceInputMode.AUTO), + transcriptionModel: this.transcriptionSetting, + transcriptionModelHasAudio: this.hasAudio(this.transcriptionSetting || null) + }); + }); + + /** Whether a model has audio input, as far as its props say. */ + hasAudio(model: string | null): boolean { + void modelsStore.props.cacheVersion; + + return model ? modelsStore.props.modelSupportsAudio(model) : false; + } + + /** A model's part in voice input, null when it has none. */ + roleOf(model: string): VoiceModelRole | null { + return voiceModelRole(model, this.hasAudio(model), this.dictationModel); + } + + /** Makes a model the one that transcribes dictation (Settings > Voice > Transcription model). */ + useForDictation(model: string): void { + settingsStore.updateConfig(SETTINGS_KEYS.VOICE_TRANSCRIPTION_MODEL, model); + } +} + +export const voiceStore = new VoiceStore(); diff --git a/ui/apps/chat/src/lib/types/chat.d.ts b/ui/apps/chat/src/lib/types/chat.d.ts index eca0dbec87f8..a72a8dfff984 100644 --- a/ui/apps/chat/src/lib/types/chat.d.ts +++ b/ui/apps/chat/src/lib/types/chat.d.ts @@ -48,6 +48,14 @@ export interface ChatUploadedFile { }; isLoading?: boolean; loadError?: string; + /** A voice message recorded in the chat form. */ + voice?: ChatUploadedVoice; +} + +/** What a voice message recorded in the chat form carries besides its WAV file. */ +export interface ChatUploadedVoice { + durationMs: number; + peaks: number[]; } export interface ChatAttachmentDisplayItem { diff --git a/ui/apps/chat/src/lib/types/database.d.ts b/ui/apps/chat/src/lib/types/database.d.ts index 50f54dc0b556..e47d60fffb7c 100644 --- a/ui/apps/chat/src/lib/types/database.d.ts +++ b/ui/apps/chat/src/lib/types/database.d.ts @@ -38,6 +38,13 @@ export interface DatabaseMessageExtraAudioFile { size?: number; base64Data: string; mimeType: string; + /** Recorded in the app as a voice message, as opposed to an uploaded audio file. */ + voice?: true; + /** What was said, for reading; a model without audio input gets it in place of the audio. */ + transcript?: string; + /** Normalised 0..1 waveform of the clip; computed from the audio when left out. */ + peaks?: number[]; + durationMs?: number; } export interface DatabaseMessageExtraVideoFile { diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts index 68cd6e92f1e7..bfed7569c17f 100644 --- a/ui/apps/chat/src/lib/types/index.ts +++ b/ui/apps/chat/src/lib/types/index.ts @@ -57,6 +57,7 @@ export type { export type { AttachmentMenuItem, ChatUploadedFile, + ChatUploadedVoice, ChatAttachmentDisplayItem, ChatMessageSiblingInfo, ChatMessageActions, diff --git a/ui/apps/chat/src/lib/utils/audio-recording.ts b/ui/apps/chat/src/lib/utils/audio-recording.ts index d733fc4ef4b9..24570ceba47f 100644 --- a/ui/apps/chat/src/lib/utils/audio-recording.ts +++ b/ui/apps/chat/src/lib/utils/audio-recording.ts @@ -1,158 +1,5 @@ -import { MICROPHONE_UNAVAILABLE_MESSAGE } from '#lib/constants/index.ts'; import { MimeTypeAudio } from '#lib/enums/index.ts'; -/** - * AudioRecorder - Browser-based audio recording with MediaRecorder API - * - * This class provides a complete audio recording solution using the browser's MediaRecorder API. - * It handles microphone access, recording state management, and audio format optimization. - * - * **Features:** - * - Automatic microphone permission handling - * - Audio enhancement (echo cancellation, noise suppression, auto gain) - * - Multiple format support with fallback (WAV, WebM, MP4, AAC) - * - Real-time recording state tracking - * - Proper cleanup and resource management - */ -export class AudioRecorder { - private audioChunks: Blob[] = []; - private mediaRecorder: MediaRecorder | null = null; - private recordingState: boolean = false; - private stream: MediaStream | null = null; - - cancelRecording(): void { - const recorder = this.mediaRecorder; - const stream = this.stream; - - this.mediaRecorder = null; - this.audioChunks = []; - this.stream = null; - this.recordingState = false; - - if (recorder && recorder.state !== 'inactive') { - // Drop the original handlers so the pending stop event does not touch the instance - recorder.onstop = null; - recorder.onerror = null; - recorder.stop(); - } - - if (stream) { - for (const track of stream.getTracks()) { - track.stop(); - } - } - } - - isRecording(): boolean { - return this.recordingState; - } - - async startRecording(): Promise { - try { - this.stream = await navigator.mediaDevices.getUserMedia({ - audio: { - autoGainControl: true, - echoCancellation: true, - noiseSuppression: true - } - }); - - this.initializeRecorder(this.stream); - - this.audioChunks = []; - // Start recording with a small timeslice to ensure we get data - this.mediaRecorder!.start(100); - this.recordingState = true; - } catch (error) { - console.error('Failed to start recording:', error); - - // the browser's own error, which says why: see describeMicrophoneError - throw error; - } - } - - async stopRecording(): Promise { - return new Promise((resolve, reject) => { - const recorder = this.mediaRecorder; - const chunks = this.audioChunks; - const stream = this.stream; - - if (!recorder || recorder.state === 'inactive') { - reject(new Error('No active recording to stop')); - - return; - } - - // Detach instance state right away so a new startRecording can take over without race - this.mediaRecorder = null; - this.audioChunks = []; - this.stream = null; - this.recordingState = false; - - recorder.onstop = () => { - const audioBlob = new Blob(chunks, { - type: recorder.mimeType || MimeTypeAudio.WAV - }); - - if (stream) { - for (const track of stream.getTracks()) { - track.stop(); - } - } - - resolve(audioBlob); - }; - - recorder.onerror = (event) => { - console.error('Recording error:', event); - - if (stream) { - for (const track of stream.getTracks()) { - track.stop(); - } - } - - reject(new Error('Recording failed')); - }; - - recorder.stop(); - }); - } - - private initializeRecorder(stream: MediaStream): void { - const options: MediaRecorderOptions = {}; - - if (MediaRecorder.isTypeSupported(MimeTypeAudio.WAV)) { - options.mimeType = MimeTypeAudio.WAV; - } else if (MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM_OPUS)) { - options.mimeType = MimeTypeAudio.WEBM_OPUS; - } else if (MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM)) { - options.mimeType = MimeTypeAudio.WEBM; - } else if (MediaRecorder.isTypeSupported(MimeTypeAudio.MP4)) { - options.mimeType = MimeTypeAudio.MP4; - } else { - console.warn('No preferred audio format supported, using default'); - } - - this.mediaRecorder = new MediaRecorder(stream, options); - - this.mediaRecorder.ondataavailable = (event) => { - if (event.data.size > 0) { - this.audioChunks.push(event.data); - } - }; - - this.mediaRecorder.onstop = () => { - this.recordingState = false; - }; - - this.mediaRecorder.onerror = (event) => { - console.error('MediaRecorder error:', event); - this.recordingState = false; - }; - } -} - export async function convertToWav(audioBlob: Blob): Promise { try { if (audioBlob.type.includes('wav')) { @@ -249,51 +96,3 @@ export function createAudioFile(audioBlob: Blob, filename?: string): File { type: audioBlob.type }); } - -/** - * Check if audio recording is supported in the current browser - * @returns True if MediaRecorder and getUserMedia are available - */ -export function isAudioRecordingSupported(): boolean { - return !!( - typeof navigator !== 'undefined' && - navigator.mediaDevices && - typeof navigator.mediaDevices.getUserMedia === 'function' && - typeof window !== 'undefined' && - window.MediaRecorder - ); -} - -/** - * Why this page can't record at all, or null when it can: a reason no tap will fix. Browsers - * only expose the microphone to a secure context, HTTPS or localhost, so a llama-server - * opened over plain HTTP on the local network or over Tailscale can't record. - */ -export function microphoneUnavailableReason(): string | null { - if (typeof window === 'undefined') return null; - - if (!window.isSecureContext) return MICROPHONE_UNAVAILABLE_MESSAGE.insecure; - - if (!isAudioRecordingSupported()) return MICROPHONE_UNAVAILABLE_MESSAGE.unsupported; - - return null; -} - -/** Why the microphone would not start, from the error the browser raised. */ -export function describeMicrophoneError(error: unknown): string { - switch (error instanceof DOMException ? error.name : '') { - case 'NotAllowedError': - case 'SecurityError': - return MICROPHONE_UNAVAILABLE_MESSAGE.denied; - case 'NotFoundError': - case 'OverconstrainedError': - return MICROPHONE_UNAVAILABLE_MESSAGE.notFound; - case 'AbortError': - case 'NotReadableError': - return MICROPHONE_UNAVAILABLE_MESSAGE.busy; - default: - return error instanceof Error && error.message - ? `${MICROPHONE_UNAVAILABLE_MESSAGE.failed} ${error.message}` - : MICROPHONE_UNAVAILABLE_MESSAGE.failed; - } -} diff --git a/ui/apps/chat/src/lib/utils/browser-only.ts b/ui/apps/chat/src/lib/utils/browser-only.ts index 64eedc140dfb..7a1468e2a482 100644 --- a/ui/apps/chat/src/lib/utils/browser-only.ts +++ b/ui/apps/chat/src/lib/utils/browser-only.ts @@ -6,15 +6,8 @@ * only in client-side code or components that are not server-rendered. */ -// Audio utilities (MediaRecorder API) -export { - AudioRecorder, - convertToWav, - createAudioFile, - describeMicrophoneError, - isAudioRecordingSupported, - microphoneUnavailableReason -} from './audio-recording'; +// Audio file utilities (Web Audio decoding); microphone support lives in @ggml-org/llama-voice +export { convertToWav, createAudioFile } from './audio-recording'; // PDF processing utilities (pdfjs-dist with DOMMatrix) export { diff --git a/ui/apps/chat/src/lib/utils/clipboard.ts b/ui/apps/chat/src/lib/utils/clipboard.ts index a5c75e873317..c2b05985e0e0 100644 --- a/ui/apps/chat/src/lib/utils/clipboard.ts +++ b/ui/apps/chat/src/lib/utils/clipboard.ts @@ -110,6 +110,16 @@ export function formatMessageForClipboard( extras?: DatabaseMessageExtra[], asPlainText: boolean = false ): string { + // what was said in a voice message reads as the message's text + const transcripts = + extras?.flatMap((extra) => + extra.type === AttachmentType.AUDIO && extra.transcript ? [extra.transcript] : [] + ) ?? []; + + if (transcripts.length > 0) { + content = [...transcripts, content].filter((part) => part.trim()).join('\n\n'); + } + // Filter text-like attachments (TEXT, LEGACY_CONTEXT, MCP_PROMPT, and MCP_RESOURCE types) const textAttachments = extras?.filter( diff --git a/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts b/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts index 43d29f43c119..4e50b089c5bc 100644 --- a/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts +++ b/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts @@ -6,6 +6,7 @@ import { SETTINGS_KEYS } from '#lib/constants/index.ts'; import { AttachmentType, FileTypeCategory, SpecialFileType } from '#lib/enums/index.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { voiceTranscriptsStore } from '#lib/stores/voice-transcripts.svelte.ts'; import type { ChatUploadedFile, DatabaseMessageExtra, @@ -83,13 +84,21 @@ export async function parseFilesToMessageExtras( // Process audio files (MP3 and WAV) try { const base64Data = await readFileAsBase64(file.file); + // a voice message keeps its waveform, and its transcript once it is there + const transcript = file.voice ? voiceTranscriptsStore.transcriptOf(file.name) : undefined; extras.push({ base64Data: base64Data, mimeType: file.type, name: file.name, size: file.size, - type: AttachmentType.AUDIO + type: AttachmentType.AUDIO, + ...(file.voice && { + durationMs: file.voice.durationMs, + peaks: file.voice.peaks, + voice: true as const, + ...(transcript !== undefined && { transcript }) + }) }); } catch (error) { console.error(`Failed to process audio file ${file.name}:`, error); diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index a0544551393e..f52f25a655f5 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -384,3 +384,15 @@ export { groupModelFamilies, modelFamilyKey, type ModelFamilyGroup } from './mod // Svelte actions export { nearViewport } from './near-viewport'; + +// Voice: what a recording becomes for the conversation's model +export { + type DictationModelInput, + dictationModelFor, + isTranscriptionOnlyModel, + resolveVoiceMode, + voiceModeLabel, + type VoiceModeInput, + voiceModelRole, + type VoiceModeResolution +} from './voice-mode'; diff --git a/ui/apps/chat/src/lib/utils/voice-attachment.ts b/ui/apps/chat/src/lib/utils/voice-attachment.ts new file mode 100644 index 000000000000..c3aafaadca3c --- /dev/null +++ b/ui/apps/chat/src/lib/utils/voice-attachment.ts @@ -0,0 +1,104 @@ +import { base64ToBytes, computePeaksFromAudio } from '@ggml-org/llama-voice'; +import { AttachmentType, MimeTypeAudio } from '#lib/enums/index.ts'; +import type { ChatAttachmentDisplayItem, DatabaseMessageExtraAudioFile } from '#lib/types/index.ts'; + +// peaks of clips stored without them, kept for the session only +const peaksCache = new Map>(); + +/** What a list item needs to draw an audio attachment as a clip. */ +export interface VoiceAttachmentSource { + /** Base64 or a URL of the audio, or the file itself. */ + audio: string | Blob | null; + durationMs?: number; + mimeType: string; + name: string; + peaks?: number[]; + /** Recorded in the app, as opposed to an uploaded file. */ + voice: boolean; + transcript?: string; +} + +/** The clip behind an audio item of the form or of a message. */ +export function voiceAttachmentSource(item: ChatAttachmentDisplayItem): VoiceAttachmentSource { + const uploaded = item.uploadedFile; + + if (uploaded) { + return { + audio: uploaded.preview ?? (uploaded.file.size > 0 ? uploaded.file : null), + durationMs: uploaded.voice?.durationMs, + mimeType: uploaded.type, + name: uploaded.name, + peaks: uploaded.voice?.peaks, + voice: !!uploaded.voice + }; + } + + const attachment = + item.attachment?.type === AttachmentType.AUDIO + ? (item.attachment as DatabaseMessageExtraAudioFile) + : null; + + return { + audio: attachment?.base64Data || null, + durationMs: attachment?.durationMs, + mimeType: attachment?.mimeType ?? '', + name: item.name, + peaks: attachment?.peaks, + transcript: attachment?.transcript, + voice: attachment?.voice === true + }; +} + +/** A URL an