Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(desktop): on-device voice input for every composer, with local history (MUL-9218) (#10572)
Jiayuan Zhang00b87d3172e0
diff --git a/apps/desktop/.gitignore b/apps/desktop/.gitignoreindex a95e840530..f96eeb2ea8 100644--- a/apps/desktop/.gitignore+++ b/apps/desktop/.gitignore@@ -6,3 +6,5 @@ out*.log*# CLI binary bundled at build time (from server/bin/)resources/bin/+# Speech engine staged at build time (scripts/bundle-voice-engine.mjs)+resources/voice-engine/diff --git a/apps/desktop/build/entitlements.mac.plist b/apps/desktop/build/entitlements.mac.plistindex f453dfe1a1..58632ba0d6 100644--- a/apps/desktop/build/entitlements.mac.plist+++ b/apps/desktop/build/entitlements.mac.plist@@ -20,5 +20,9 @@<true/><key>com.apple.security.network.server</key><true/>+ <!-- Voice input records from the microphone (getUserMedia); without it+ the hardened runtime denies audio capture without asking. -->+ <key>com.apple.security.device.audio-input</key>+ <true/></dict></plist>diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.ymlindex a5050ef3ba..e55fa0d2cb 100644--- a/apps/desktop/electron-builder.yml+++ b/apps/desktop/electron-builder.yml@@ -43,6 +43,9 @@ mac:# Electron 44 requires macOS 13 Ventura; declare it on every mac bundle.minimumSystemVersion: "13.0.0"entitlementsInherit: build/entitlements.mac.plist+ extendInfo:+ # Shown in the macOS prompt the first time voice input opens the mic.+ NSMicrophoneUsageDescription: Multica uses the microphone for voice input when you dictate into chat or comments.target:- dmg- zipdiff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 9f1f16696e..fd367021cb 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -18,10 +18,11 @@"main": "./out/main/index.js","scripts": {"bundle-cli": "node scripts/bundle-cli.mjs",+ "bundle-voice-engine": "node scripts/bundle-voice-engine.mjs","brand-dev-electron": "node scripts/brand-dev-electron.mjs","dev": "node scripts/dev.mjs","dev:staging": "node scripts/dev.mjs --mode staging",- "build": "pnpm run bundle-cli && electron-vite build",+ "build": "pnpm run bundle-cli && pnpm run bundle-voice-engine && electron-vite build","typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false","typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false","typecheck": "pnpm run typecheck:node && pnpm run typecheck:web",@@ -76,6 +77,7 @@"electron-vite": "^5.0.0","globals": "^16.0.0","jsdom": "catalog:",+ "sherpa-onnx-node": "2.0.1","tailwindcss": "catalog:","typescript": "catalog:","vitest": "catalog:"diff --git a/apps/desktop/scripts/bundle-voice-engine.mjs b/apps/desktop/scripts/bundle-voice-engine.mjsnew file mode 100644index 0000000000..1f833341d2--- /dev/null+++ b/apps/desktop/scripts/bundle-voice-engine.mjs@@ -0,0 +1,125 @@+#!/usr/bin/env node+// Copies the on-device speech engine (sherpa-onnx's native addon and the+// ONNX Runtime libraries next to it) for one platform/arch into+// apps/desktop/resources/voice-engine/, where the voice worker loads it from+// (`asarUnpack: resources/**` keeps it on disk in packaged builds).+//+// The files come from sherpa-onnx's per-platform npm package. pnpm only+// installs the host's, so a cross-arch package build (`--x64 --arm64` on one+// runner) fetches the other one with `npm pack` at the version pinned by the+// `sherpa-onnx-node` devDependency.+//+// Graceful in dev: if the engine can't be staged, voice input reports itself+// unavailable and everything else works. `--required` (package builds) makes+// a failure fatal so a release never ships without it.++import { execFileSync } from "node:child_process";+import { copyFile, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const desktopRoot = resolve(here, "..");+const destDir = join(desktopRoot, "resources", "voice-engine");+const NATIVE_FILE = /\.(node|dylib|dll|so(\.\d+)*)$/;+const SUPPORTED = new Set(["darwin-x64", "darwin-arm64", "win-x64", "win-arm64", "linux-x64", "linux-arm64"]);++// The npm packages carry no license files, so the binaries ship with this.+const NOTICES = `Third-party software in this directory++sherpa-onnx (sherpa-onnx.node, libsherpa-onnx-*)+https://github.com/k2-fsa/sherpa-onnx+Copyright (c) 2022-2025 Xiaomi Corporation+Licensed under the Apache License, Version 2.0:+https://www.apache.org/licenses/LICENSE-2.0++ONNX Runtime (libonnxruntime*, onnxruntime*)+https://github.com/microsoft/onnxruntime+Copyright (c) Microsoft Corporation++MIT License++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+`;++function argValue(flag, fallback) {+ const index = process.argv.indexOf(flag);+ return index === -1 ? fallback : process.argv[index + 1];+}++const platform = argValue("--target-platform", process.platform);+const arch = argValue("--target-arch", process.arch);+const required = process.argv.includes("--required");+const target = `${platform === "win32" ? "win" : platform}-${arch}`;+const pkg = `sherpa-onnx-${target}`;++async function installedPackageDir(version) {+ const require = createRequire(join(desktopRoot, "package.json"));+ const searchFrom = [desktopRoot, dirname(require.resolve("sherpa-onnx-node/package.json"))];+ for (const base of searchFrom) {+ try {+ const manifest = createRequire(join(base, "package.json")).resolve(`${pkg}/package.json`);+ const { version: found } = JSON.parse(await readFile(manifest, "utf8"));+ if (found === version) return dirname(manifest);+ } catch {+ // Not installed for this platform; fetch it below.+ }+ }+ return null;+}++async function fetchedPackageDir(version) {+ const scratch = await mkdtemp(join(tmpdir(), "voice-engine-"));+ const npm = process.platform === "win32" ? "npm.cmd" : "npm";+ const tarball = execFileSync(npm, ["pack", `${pkg}@${version}`, "--silent", "--pack-destination", scratch], {+ encoding: "utf8",+ shell: process.platform === "win32",+ })+ .trim()+ .split("\n")+ .pop();+ execFileSync("tar", ["-xzf", join(scratch, tarball), "-C", scratch]);+ return join(scratch, "package");+}++async function main() {+ if (!SUPPORTED.has(target)) throw new Error(`no speech engine for ${target}`);+ const require = createRequire(join(desktopRoot, "package.json"));+ const { version } = JSON.parse(await readFile(require.resolve("sherpa-onnx-node/package.json"), "utf8"));+ const sourceDir = (await installedPackageDir(version)) ?? (await fetchedPackageDir(version));+ const files = (await readdir(sourceDir)).filter((name) => NATIVE_FILE.test(name));+ if (!files.includes("sherpa-onnx.node")) throw new Error(`${pkg}@${version} has no sherpa-onnx.node`);+ await rm(destDir, { recursive: true, force: true });+ await mkdir(destDir, { recursive: true });+ for (const name of files) await copyFile(join(sourceDir, name), join(destDir, name));+ await writeFile(join(destDir, "THIRD_PARTY_NOTICES.txt"), NOTICES);+ console.log(`[bundle-voice-engine] ${pkg}@${version} → resources/voice-engine (${files.length} files)`);+}++main().catch(async (err) => {+ await rm(destDir, { recursive: true, force: true });+ const message = `[bundle-voice-engine] ${err instanceof Error ? err.message : String(err)}`;+ if (required) {+ console.error(message);+ process.exit(1);+ }+ console.warn(`${message} — voice input will be unavailable in this build.`);+});diff --git a/apps/desktop/scripts/dev.mjs b/apps/desktop/scripts/dev.mjsindex 022d489577..0c87d24916 100644--- a/apps/desktop/scripts/dev.mjs+++ b/apps/desktop/scripts/dev.mjs@@ -41,6 +41,7 @@ function run(command, args, { shell = false, env = process.env } = {}) {const node = process.execPath;run(node, [join(here, "bundle-cli.mjs")]);+run(node, [join(here, "bundle-voice-engine.mjs")]);run(node, [join(here, "brand-dev-electron.mjs")]);const isWin = process.platform === "win32";diff --git a/apps/desktop/scripts/package.mjs b/apps/desktop/scripts/package.mjsindex 02f1d07181..f5070a6e68 100644--- a/apps/desktop/scripts/package.mjs+++ b/apps/desktop/scripts/package.mjs@@ -34,6 +34,7 @@ import { fileURLToPath } from "node:url";const here = dirname(fileURLToPath(import.meta.url));const desktopRoot = resolve(here, "..");const bundleCliScript = resolve(here, "bundle-cli.mjs");+const bundleVoiceEngineScript = resolve(here, "bundle-voice-engine.mjs");const PLATFORM_CONFIG = {mac: {@@ -444,6 +445,23 @@ function main() {},);+ console.log(`[package] bundling voice engine → ${formatTarget(target)}`);+ execFileSync(+ "node",+ [+ bundleVoiceEngineScript,+ "--target-platform",+ PLATFORM_CONFIG[target.platform].runtimePlatform,+ "--target-arch",+ target.arch,+ "--required",+ ],+ {+ stdio: "inherit",+ cwd: desktopRoot,+ },+ );+const builderArgs = builderArgsForTarget(target, parsed, version, {disableMacNotarize,hostPlatform: process.platform,diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 8fcc37b559..4f5227f1a9 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -21,6 +21,7 @@ import {} from "./daemon-manager";import { setupLocalDirectory } from "./local-directory";import { setupThemeFolder } from "./theme-folder";+import { setupVoiceInput } from "./voice";import { configureLinuxFileDialogs } from "./linux-file-dialog";import { openExternalSafely, downloadURLSafely } from "./external-url";import { installContextMenu } from "./context-menu";@@ -1098,6 +1099,7 @@ if (!gotTheLock) {);setupLocalDirectory(() => mainWindows.mostRecent());setupThemeFolder();+ setupVoiceInput();// Registered after the updater and daemon gates, so a quit they hold// (busy daemon, pending install) leaves the session writable; only thediff --git a/apps/desktop/src/main/voice/catalog.ts b/apps/desktop/src/main/voice/catalog.tsnew file mode 100644index 0000000000..903a8ad537--- /dev/null+++ b/apps/desktop/src/main/voice/catalog.ts@@ -0,0 +1,153 @@+/**+ * Speech models Desktop offers for download. Files are pinned to a Hugging+ * Face commit and checked against their size and SHA-256, so a mirror can+ * serve them without being trusted.+ */++export interface CatalogFile {+ name: string;+ size: number;+ sha256: string;+}++export type RecognizerKind = "qwen3-asr" | "sense-voice" | "nemo-transducer";++export interface CatalogModel {+ id: string;+ name: string;+ author: string;+ licenseUrl: string;+ repo: string;+ revision: string;+ languages: string[];+ languageHint: boolean;+ /** Takes a word list that biases recognition toward names and terms. */+ hotwords: boolean;+ highlight?: "accurate" | "fast";+ recognizer: RecognizerKind;+ files: CatalogFile[];+}++/** Tried in order; each serves `{base}/{repo}/resolve/{revision}/{file}`. */+export const MODEL_MIRRORS = ["https://huggingface.co", "https://hf-mirror.com"];++export const VOICE_MODELS: readonly CatalogModel[] = [+ {+ id: "qwen3-asr-0.6b",+ name: "Qwen3-ASR 0.6B",+ author: "Alibaba Qwen",+ licenseUrl: "https://huggingface.co/Qwen/Qwen3-ASR-0.6B",+ repo: "csukuangfj2/sherpa-onnx-qwen3-asr-0.6B-int8-2026-03-25",+ revision: "68818b2313fe77bd06f6a7c5068ff3ef59d02b8a",+ languages: [+ "zh", "en", "yue", "ja", "ko", "de", "fr", "es", "pt", "it", "ru", "ar", "id", "th", "vi",+ "tr", "hi", "ms", "nl", "sv", "da", "fi", "pl", "cs", "fil", "fa", "el", "hu", "mk", "ro",+ ],+ languageHint: false,+ hotwords: true,+ highlight: "accurate",+ recognizer: "qwen3-asr",+ files: [+ {+ name: "conv_frontend.onnx",+ size: 44148281,+ sha256: "d22dc4423e0940e49884e903d2ea2f7e5567c14fc1aed97e4e26d6b8f208ef9e",+ },+ {+ name: "encoder.int8.onnx",+ size: 182491662,+ sha256: "60748d3e6744a57c9c91e1b17424a6c2990567e8adceb0783940c03ed98fa9d9",+ },+ {+ name: "decoder.int8.onnx",+ size: 755914231,+ sha256: "4f6885be5959ae26af3089d38ee7972c5fafbeeb1cf8d5e76eab6d8b61ca5771",+ },+ {+ name: "tokenizer/merges.txt",+ size: 1671853,+ sha256: "8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5",+ },+ {+ name: "tokenizer/tokenizer_config.json",+ size: 12487,+ sha256: "4942d005604266809309cabc9f4e9cb89ce855d59b14681fdc0e1cc62ea26c4c",+ },+ {+ name: "tokenizer/vocab.json",+ size: 2776833,+ sha256: "ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910",+ },+ ],+ },+ {+ id: "sensevoice-small",+ name: "SenseVoice Small",+ author: "Alibaba FunAudioLLM",+ licenseUrl: "https://github.com/modelscope/FunASR/blob/main/MODEL_LICENSE",+ repo: "csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17",+ revision: "2365baeacb507f821a0c8120fcee3d484dba7a07",+ languages: ["zh", "en", "ja", "ko", "yue"],+ languageHint: true,+ hotwords: false,+ highlight: "fast",+ recognizer: "sense-voice",+ files: [+ {+ name: "model.int8.onnx",+ size: 239233841,+ sha256: "c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51",+ },+ {+ name: "tokens.txt",+ size: 315894,+ sha256: "f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc",+ },+ ],+ },+ {+ id: "parakeet-tdt-0.6b-v3",+ name: "Parakeet V3",+ author: "NVIDIA",+ licenseUrl: "https://creativecommons.org/licenses/by/4.0/",+ repo: "csukuangfj/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8",+ revision: "ed5d745623472f97cfc2e6c2916ee248798fc5a8",+ languages: [+ "en", "de", "es", "fr", "it", "pt", "nl", "ru", "uk", "pl", "cs", "sk", "sl",+ "hr", "bg", "ro", "hu", "el", "sv", "da", "fi", "et", "lv", "lt", "mt",+ ],+ languageHint: false,+ hotwords: false,+ recognizer: "nemo-transducer",+ files: [+ {+ name: "encoder.int8.onnx",+ size: 652282294,+ sha256: "1afbe69c1ffdabee94755f42e4daf1d93549131a3da11356bda84fcef0f2c479",+ },+ {+ name: "decoder.int8.onnx",+ size: 11845274,+ sha256: "0222a86147299d4dee90edf95b6d13827edb42ad8b7c9cf0b2582f030937c0b5",+ },+ {+ name: "joiner.int8.onnx",+ size: 6355277,+ sha256: "cbd02f3696e9944970111fb439d9c3fd365a80374565f13f2b9c7007d253fc98",+ },+ {+ name: "tokens.txt",+ size: 93939,+ sha256: "d58544679ea4bc6ac563d1f545eb7d474bd6cfa467f0a6e2c1dc1c7d37e3c35d",+ },+ ],+ },+];++export function findVoiceModel(id: string): CatalogModel | undefined {+ return VOICE_MODELS.find((model) => model.id === id);+}++export function modelSize(model: CatalogModel): number {+ return model.files.reduce((sum, file) => sum + file.size, 0);+}diff --git a/apps/desktop/src/main/voice/engine.test.ts b/apps/desktop/src/main/voice/engine.test.tsnew file mode 100644index 0000000000..e8f12662b6--- /dev/null+++ b/apps/desktop/src/main/voice/engine.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { EventEmitter } from "events";+import { afterEach, describe, expect, it, vi } from "vitest";+import { VoiceEngine, type WorkerProcess } from "./engine";+import type { LoadSpec, WorkerRequest } from "./worker-protocol";++const SPEC: LoadSpec = { key: "m@1:auto:", recognizer: "sense-voice", dir: "/models/m", language: "auto", hotwords: "" };++class FakeWorker extends EventEmitter implements WorkerProcess {+ sent: WorkerRequest[] = [];+ killed = false;+ constructor(private readonly reply: (request: WorkerRequest) => unknown) {+ super();+ }+ postMessage(message: unknown) {+ const request = message as WorkerRequest;+ this.sent.push(request);+ const response = this.reply(request);+ if (response) queueMicrotask(() => this.emit("message", response));+ }+ kill() {+ this.killed = true;+ queueMicrotask(() => this.emit("exit", 0));+ return true;+ }+}++function engine(reply: (request: WorkerRequest) => unknown, options: { idleMs?: number; timeoutMs?: number } = {}) {+ const workers: FakeWorker[] = [];+ const voice = new VoiceEngine({+ engineDir: "/engine",+ fork: (args) => {+ expect(args).toEqual(["/engine"]);+ const worker = new FakeWorker(reply);+ workers.push(worker);+ return worker;+ },+ ...options,+ });+ return { voice, workers };+}++afterEach(() => {+ vi.useRealTimers();+});++describe("VoiceEngine", () => {+ it("keeps one worker warm across dictations", async () => {+ const { voice, workers } = engine((request) => ({ id: request.id, ok: true, text: "hi" }));+ voice.prepare(SPEC);+ const samples = new Float32Array(16000);+ await expect(voice.transcribe(SPEC, samples, 16000)).resolves.toBe("hi");+ await expect(voice.transcribe(SPEC, samples, 16000)).resolves.toBe("hi");+ expect(workers).toHaveLength(1);+ expect(workers[0]!.sent.map((r) => r.type)).toEqual(["load", "transcribe", "transcribe"]);+ });++ it("surfaces worker errors", async () => {+ const { voice } = engine((request) => ({ id: request.id, ok: false, error: "bad model" }));+ await expect(voice.transcribe(SPEC, new Float32Array(10), 16000)).rejects.toThrow("bad model");+ });++ it("restarts after the worker dies or hangs", async () => {+ vi.useFakeTimers();+ let hang = true;+ const { voice, workers } = engine((request) => (hang ? null : { id: request.id, ok: true, text: "ok" }), {+ timeoutMs: 1000,+ });+ const first = voice.transcribe(SPEC, new Float32Array(10), 16000);+ const assertion = expect(first).rejects.toThrow("timed out");+ await vi.advanceTimersByTimeAsync(1001);+ await assertion;+ expect(workers[0]!.killed).toBe(true);++ hang = false;+ await expect(voice.transcribe(SPEC, new Float32Array(10), 16000)).resolves.toBe("ok");+ expect(workers).toHaveLength(2);+ });++ it("stops the worker once idle", async () => {+ vi.useFakeTimers();+ const { voice, workers } = engine((request) => ({ id: request.id, ok: true, text: "" }), { idleMs: 5000 });+ await voice.transcribe(SPEC, new Float32Array(10), 16000);+ await vi.advanceTimersByTimeAsync(4999);+ expect(workers[0]!.killed).toBe(false);+ await vi.advanceTimersByTimeAsync(1);+ expect(workers[0]!.killed).toBe(true);+ });+});diff --git a/apps/desktop/src/main/voice/engine.ts b/apps/desktop/src/main/voice/engine.tsnew file mode 100644index 0000000000..a21c45be28--- /dev/null+++ b/apps/desktop/src/main/voice/engine.ts@@ -0,0 +1,126 @@+import { existsSync } from "fs";+import { join } from "path";+import type { LoadSpec, WorkerRequest, WorkerResponse } from "./worker-protocol";++/** The slice of Electron's UtilityProcess the engine uses. */+export interface WorkerProcess {+ postMessage(message: unknown): void;+ kill(): boolean;+ on(event: "message", listener: (message: unknown) => void): unknown;+ on(event: "exit", listener: (code: number) => void): unknown;+}++export interface VoiceEngineOptions {+ /** Folder with `sherpa-onnx.node`, passed to the worker. */+ engineDir: string;+ fork: (args: string[]) => WorkerProcess;+ /** Free the model's memory after this long without a request. */+ idleMs?: number;+ /** Give up on (and restart) a worker that takes longer than this. */+ timeoutMs?: number;+}++interface Pending {+ resolve: (response: WorkerResponse) => void;+ reject: (error: Error) => void;+ timer: ReturnType<typeof setTimeout>;+}++type Request = { type: "load"; spec: LoadSpec } | { type: "transcribe"; spec: LoadSpec; samples: Float32Array; sampleRate: number };++/**+ * Owns the transcription worker: started on first use, kept warm between+ * dictations so the model loads once, and stopped when idle.+ */+export class VoiceEngine {+ private child: WorkerProcess | null = null;+ private readonly pending = new Map<number, Pending>();+ private nextId = 1;+ private idleTimer: ReturnType<typeof setTimeout> | null = null;+ private readonly idleMs: number;+ private readonly timeoutMs: number;++ constructor(private readonly options: VoiceEngineOptions) {+ this.idleMs = options.idleMs ?? 5 * 60_000;+ this.timeoutMs = options.timeoutMs ?? 120_000;+ }++ available(): boolean {+ return existsSync(join(this.options.engineDir, "sherpa-onnx.node"));+ }++ /** Load the model ahead of time so the first transcript comes back fast. */+ prepare(spec: LoadSpec): void {+ this.send({ type: "load", spec }).catch(() => {});+ }++ async transcribe(spec: LoadSpec, samples: Float32Array, sampleRate: number): Promise<string> {+ const response = await this.send({ type: "transcribe", spec, samples, sampleRate });+ if (!response.ok) throw new Error(response.error);+ return response.text ?? "";+ }++ /** Stop the worker, failing anything in flight. */+ stop(): void {+ this.clearIdle();+ const child = this.child;+ this.child = null;+ this.failAll(new Error("voice engine stopped"));+ child?.kill();+ }++ private send(request: Request): Promise<WorkerResponse> {+ this.clearIdle();+ const child = this.ensureChild();+ const id = this.nextId++;+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error("voice engine timed out"));+ this.stop();+ }, this.timeoutMs);+ this.pending.set(id, { resolve, reject, timer });+ child.postMessage({ ...request, id } satisfies WorkerRequest);+ });+ }++ private ensureChild(): WorkerProcess {+ if (this.child) return this.child;+ const child = this.options.fork([this.options.engineDir]);+ child.on("message", (message) => {+ const response = message as WorkerResponse;+ const pending = this.pending.get(response.id);+ if (!pending) return;+ this.pending.delete(response.id);+ clearTimeout(pending.timer);+ pending.resolve(response);+ if (this.pending.size === 0) this.scheduleIdle();+ });+ child.on("exit", () => {+ if (this.child !== child) return;+ this.child = null;+ this.clearIdle();+ this.failAll(new Error("voice engine exited"));+ });+ this.child = child;+ return child;+ }++ private failAll(error: Error) {+ for (const pending of this.pending.values()) {+ clearTimeout(pending.timer);+ pending.reject(error);+ }+ this.pending.clear();+ }++ private scheduleIdle() {+ this.clearIdle();+ this.idleTimer = setTimeout(() => this.stop(), this.idleMs);+ }++ private clearIdle() {+ if (this.idleTimer !== null) clearTimeout(this.idleTimer);+ this.idleTimer = null;+ }+}diff --git a/apps/desktop/src/main/voice/history-store.test.ts b/apps/desktop/src/main/voice/history-store.test.tsnew file mode 100644index 0000000000..5a8911367d--- /dev/null+++ b/apps/desktop/src/main/voice/history-store.test.ts@@ -0,0 +1,150 @@+// @vitest-environment node+import { existsSync } from "fs";+import { mkdtemp, readdir, rm, writeFile } from "fs/promises";+import { tmpdir } from "os";+import { join } from "path";+import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from "vitest";+import { MAX_HISTORY_ENTRIES, VoiceHistoryStore } from "./history-store";++const DAY = 24 * 60 * 60 * 1000;+const audio = new Uint8Array([1, 2, 3]);++let root: string;+let now: number;+let onChange: Mock<() => void>;++async function open() {+ const store = new VoiceHistoryStore({ root, onChange, now: () => now });+ await store.init();+ return store;+}++beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), "voice-history-"));+ now = 10 * DAY;+ onChange = vi.fn<() => void>();+});++afterEach(async () => {+ await rm(root, { recursive: true, force: true });+});++describe("VoiceHistoryStore", () => {+ it("keeps a recording before it is transcribed, then its text", async () => {+ const store = await open();+ const entry = await store.save(audio, "audio/webm;codecs=opus", 1500, null);+ expect(entry).toMatchObject({ status: "transcribing", text: "", durationMs: 1500 });+ await store.update(entry.id, { status: "done", text: "你好" });++ const reopened = await open();+ expect(reopened.list()).toEqual([{ ...entry, status: "done", text: "你好" }]);+ expect(await reopened.audio(entry.id)).toEqual({ audio, mimeType: "audio/webm;codecs=opus" });+ expect(onChange).toHaveBeenCalled();+ });++ it("reads a transcription the app quit during as interrupted", async () => {+ const entry = await (await open()).save(audio, "audio/webm", 900, null);+ expect((await open()).list()[0]).toMatchObject({ id: entry.id, status: "interrupted" });+ });++ it("lists newest first and deletes the audio with the entry", async () => {+ const store = await open();+ const first = await store.save(audio, "audio/webm", 1, null);+ now += 1000;+ const second = await store.save(audio, "audio/ogg", 1, null);+ expect(store.list().map((e) => e.id)).toEqual([second.id, first.id]);+ await store.remove(second.id);+ expect(store.list().map((e) => e.id)).toEqual([first.id]);+ expect((await readdir(root)).filter((f) => f.endsWith(".ogg"))).toEqual([]);+ });++ it("expires by the retention given when saving or chosen in Settings", async () => {+ const store = await open();+ const old = await store.save(audio, "audio/webm", 1, null);+ await store.update(old.id, { status: "done", text: "old" });+ now += 8 * DAY;+ const fresh = await store.save(audio, "audio/webm", 1, 7);+ expect(store.list().map((e) => e.id)).toEqual([fresh.id]);++ await store.setRetention(0);+ expect(store.list()).toEqual([]);+ expect((await readdir(root)).filter((f) => f.endsWith(".webm"))).toEqual([]);+ });++ it("keeps expiring by the chosen retention with no new recordings", async () => {+ const store = await open();+ await store.setRetention(1);+ const entry = await store.save(audio, "audio/webm", 1, 1);+ await store.update(entry.id, { status: "done", text: "yesterday" });++ now += DAY / 2;+ expect(await store.expire()).toBe(false);+ expect(store.list()).toHaveLength(1);++ now += 2 * DAY;+ const reopened = await open();+ expect(reopened.list()).toEqual([]);+ expect((await readdir(root)).filter((f) => f.endsWith(".webm"))).toEqual([]);+ });++ it("expires on read once a recording passes the retention", async () => {+ const store = await open();+ await store.save(audio, "audio/webm", 1, 1);+ now += 2 * DAY;+ expect(store.list()).toHaveLength(1);+ expect(await store.expire()).toBe(true);+ expect(store.list()).toEqual([]);+ });++ it("clears a recording still being transcribed, and its late result stays gone", async () => {+ const store = await open();+ await store.setRetention(30);+ const done = await store.save(audio, "audio/webm", 1, 30);+ await store.update(done.id, { status: "done", text: "done" });+ const inFlight = await store.save(audio, "audio/webm", 1, 30);++ await store.clear();+ expect(store.list()).toEqual([]);+ expect((await readdir(root)).filter((f) => f.endsWith(".webm"))).toEqual([]);++ await store.update(inFlight.id, { status: "done", text: "late" });+ expect(store.list()).toEqual([]);+ expect((await open()).list()).toEqual([]);++ const next = await store.save(audio, "audio/webm", 1, 30);+ now += 10 * DAY;+ expect((await open()).list().map((e) => e.id)).toEqual([next.id]);+ });++ it("caps the number of entries even when keeping forever", async () => {+ // Newest first, as the store writes it; only the oldest needs its audio on disk.+ const full = Array.from({ length: MAX_HISTORY_ENTRIES }, (_, i) => ({+ id: `e${i}`, createdAt: now - i, durationMs: 1, status: "done", text: String(i),+ file: `e${i}.webm`, mimeType: "audio/webm",+ }));+ await writeFile(join(root, "history.json"), JSON.stringify(full));+ await writeFile(join(root, `e${MAX_HISTORY_ENTRIES - 1}.webm`), audio);++ const store = await open();+ const newest = await store.save(audio, "audio/webm", 1, null);+ const list = store.list();+ expect(list).toHaveLength(MAX_HISTORY_ENTRIES);+ expect(list[0]?.id).toBe(newest.id);+ expect(list.at(-1)?.id).toBe(`e${MAX_HISTORY_ENTRIES - 2}`);+ expect(existsSync(join(root, `e${MAX_HISTORY_ENTRIES - 1}.webm`))).toBe(false);+ expect((await open()).list()).toHaveLength(MAX_HISTORY_ENTRIES);+ });++ it("ignores a corrupt index and entries that point outside the folder", async () => {+ await writeFile(join(root, "history.json"), JSON.stringify([+ { id: "x", createdAt: 1, durationMs: 1, status: "done", text: "", file: "../escape", mimeType: "audio/webm" },+ "junk",+ ]));+ const store = await open();+ expect(store.list()).toEqual([]);+ expect(await store.audio("x")).toBeNull();+ await writeFile(join(root, "history.json"), "{not json");+ expect((await open()).list()).toEqual([]);+ expect(existsSync(join(root, "history.json"))).toBe(true);+ });+});diff --git a/apps/desktop/src/main/voice/history-store.ts b/apps/desktop/src/main/voice/history-store.tsnew file mode 100644index 0000000000..9105849273--- /dev/null+++ b/apps/desktop/src/main/voice/history-store.ts@@ -0,0 +1,204 @@+import { randomUUID } from "crypto";+import { mkdir, readFile, rename, rm, writeFile } from "fs/promises";+import { join } from "path";+import type {+ VoiceHistoryAudio,+ VoiceHistoryEntry,+ VoiceHistoryStatus,+ VoiceHistoryUpdate,+} from "../../shared/voice";++const INDEX = "history.json";+const RETENTION = "retention.json";+const DAY_MS = 24 * 60 * 60 * 1000;+/** Bounds the folder even when history is kept forever. */+export const MAX_HISTORY_ENTRIES = 1000;+/** A recording is capped at two minutes; compressed it stays far below this. */+export const MAX_HISTORY_AUDIO_BYTES = 16 * 1024 * 1024;++const STATUSES = new Set<VoiceHistoryStatus>(["transcribing", "done", "failed", "interrupted"]);++interface StoredEntry extends VoiceHistoryEntry {+ /** Audio file name inside the history folder. */+ file: string;+ mimeType: string;+}++export interface VoiceHistoryStoreOptions {+ /** Folder for the index and one audio file per recording. */+ root: string;+ onChange: () => void;+ now?: () => number;+}++function extensionOf(mimeType: string): string {+ if (mimeType.includes("ogg")) return "ogg";+ if (mimeType.includes("mp4") || mimeType.includes("aac")) return "m4a";+ if (mimeType.includes("wav")) return "wav";+ return "webm";+}++function isStoredEntry(value: unknown): value is StoredEntry {+ if (!value || typeof value !== "object") return false;+ const entry = value as Record<string, unknown>;+ return (+ typeof entry.id === "string" &&+ typeof entry.createdAt === "number" &&+ typeof entry.durationMs === "number" &&+ STATUSES.has(entry.status as VoiceHistoryStatus) &&+ typeof entry.text === "string" &&+ typeof entry.file === "string" &&+ !entry.file.includes("/") &&+ !entry.file.includes("\\") &&+ typeof entry.mimeType === "string"+ );+}++function isKeepDays(value: unknown): value is number | null {+ return value === null || (typeof value === "number" && Number.isFinite(value) && value >= 0);+}++function publicEntry({ id, createdAt, durationMs, status, text }: StoredEntry): VoiceHistoryEntry {+ return { id, createdAt, durationMs, status, text };+}++/**+ * Recordings and their transcripts, kept on this device. The index lives in+ * `<root>/history.json`, newest first; each recording is its own file next+ * to it. Writes are serialized so concurrent saves never lose an entry.+ *+ * The retention last chosen in Settings is kept in `<root>/retention.json`+ * so old recordings expire on launch and on read, not only when recording.+ */+export class VoiceHistoryStore {+ private entries: StoredEntry[] = [];+ /** Undefined until a retention has been chosen; nothing expires by age. */+ private keepDays: number | null | undefined;+ private writes: Promise<void> = Promise.resolve();+ private readonly now: () => number;++ constructor(private readonly options: VoiceHistoryStoreOptions) {+ this.now = options.now ?? Date.now;+ }++ async init(): Promise<void> {+ await mkdir(this.options.root, { recursive: true });+ try {+ const raw: unknown = JSON.parse(await readFile(join(this.options.root, INDEX), "utf8"));+ this.entries = Array.isArray(raw) ? raw.filter(isStoredEntry) : [];+ } catch {+ this.entries = [];+ }+ try {+ const raw: unknown = JSON.parse(await readFile(join(this.options.root, RETENTION), "utf8"));+ const keepDays = (raw as { keepDays?: unknown } | null)?.keepDays;+ if (isKeepDays(keepDays)) this.keepDays = keepDays;+ } catch {+ this.keepDays = undefined;+ }+ // The app quit while these were being transcribed.+ let interrupted = false;+ for (const entry of this.entries) {+ if (entry.status !== "transcribing") continue;+ entry.status = "interrupted";+ interrupted = true;+ }+ const expired = await this.expire(false);+ if (interrupted || expired) await this.persist();+ }++ list(): VoiceHistoryEntry[] {+ return this.entries.map(publicEntry);+ }++ async save(audio: Uint8Array, mimeType: string, durationMs: number, keepDays: number | null): Promise<VoiceHistoryEntry> {+ const id = randomUUID();+ const file = `${id}.${extensionOf(mimeType)}`;+ await writeFile(join(this.options.root, file), audio);+ const entry: StoredEntry = { id, createdAt: this.now(), durationMs, status: "transcribing", text: "", file, mimeType };+ this.entries.unshift(entry);+ await this.rememberRetention(keepDays);+ await this.expire(false);+ await this.persist();+ return publicEntry(entry);+ }++ /** Remember the retention chosen in Settings and apply it now. */+ async setRetention(keepDays: number | null): Promise<void> {+ await this.rememberRetention(keepDays);+ await this.expire();+ }++ /** Drop entries past the remembered retention. Resolves whether any were dropped. */+ async expire(persist = true): Promise<boolean> {+ const keepDays = this.keepDays;+ const cutoff = keepDays === undefined || keepDays === null ? -Infinity : this.now() - keepDays * DAY_MS;+ return this.drop((entry, index) => keepDays === 0 || entry.createdAt < cutoff || index >= MAX_HISTORY_ENTRIES, persist);+ }++ /**+ * Delete every recording, including one still being transcribed; its+ * late result finds no entry and is discarded.+ */+ async clear(): Promise<void> {+ await this.drop(() => true);+ }++ async update(id: string, patch: VoiceHistoryUpdate): Promise<void> {+ const entry = this.entries.find((e) => e.id === id);+ if (!entry || !STATUSES.has(patch.status)) return;+ entry.status = patch.status;+ if (typeof patch.text === "string") entry.text = patch.text;+ await this.persist();+ }++ async audio(id: string): Promise<VoiceHistoryAudio | null> {+ const entry = this.entries.find((e) => e.id === id);+ if (!entry) return null;+ try {+ return { audio: new Uint8Array(await readFile(join(this.options.root, entry.file))), mimeType: entry.mimeType };+ } catch {+ return null;+ }+ }++ async remove(id: string): Promise<void> {+ const entry = this.entries.find((e) => e.id === id);+ if (!entry) return;+ this.entries = this.entries.filter((e) => e !== entry);+ await rm(join(this.options.root, entry.file), { force: true });+ await this.persist();+ }++ private async rememberRetention(keepDays: number | null): Promise<void> {+ if (this.keepDays === keepDays) return;+ this.keepDays = keepDays;+ const path = join(this.options.root, RETENTION);+ await writeFile(`${path}.tmp`, JSON.stringify({ keepDays }));+ await rename(`${path}.tmp`, path);+ }++ private async drop(shouldDrop: (entry: StoredEntry, index: number) => boolean, persist = true): Promise<boolean> {+ const dropped = this.entries.filter(shouldDrop);+ if (dropped.length === 0) return false;+ const gone = new Set(dropped);+ this.entries = this.entries.filter((entry) => !gone.has(entry));+ await Promise.all(dropped.map((entry) => rm(join(this.options.root, entry.file), { force: true })));+ if (persist) await this.persist();+ return true;+ }++ private persist(): Promise<void> {+ const snapshot = JSON.stringify(this.entries);+ const path = join(this.options.root, INDEX);+ this.writes = this.writes+ .catch(() => {})+ .then(async () => {+ await writeFile(`${path}.tmp`, snapshot);+ await rename(`${path}.tmp`, path);+ });+ const written = this.writes;+ void written.then(this.options.onChange, () => {});+ return written;+ }+}diff --git a/apps/desktop/src/main/voice/index.ts b/apps/desktop/src/main/voice/index.tsnew file mode 100644index 0000000000..3e29e0e7f8--- /dev/null+++ b/apps/desktop/src/main/voice/index.ts@@ -0,0 +1,167 @@+import { app, BrowserWindow, ipcMain, net, utilityProcess } from "electron";+import { join } from "path";+import {+ MAX_VOICE_SAMPLES,+ VOICE_HISTORY_AUDIO_CHANNEL,+ VOICE_HISTORY_CHANGED_CHANNEL,+ VOICE_HISTORY_CLEAR_CHANNEL,+ VOICE_HISTORY_LIST_CHANNEL,+ VOICE_HISTORY_REMOVE_CHANNEL,+ VOICE_HISTORY_RETENTION_CHANNEL,+ VOICE_HISTORY_SAVE_CHANNEL,+ VOICE_HISTORY_UPDATE_CHANNEL,+ VOICE_MODEL_CANCEL_CHANNEL,+ VOICE_MODEL_DELETE_CHANNEL,+ VOICE_MODEL_DOWNLOAD_CHANNEL,+ VOICE_MODELS_CHANGED_CHANNEL,+ VOICE_MODELS_LIST_CHANNEL,+ VOICE_PREPARE_CHANNEL,+ VOICE_SAMPLE_RATE,+ VOICE_TRANSCRIBE_CHANNEL,+ type VoiceHistoryAudio,+ type VoiceHistoryEntry,+ type VoiceHistoryStatus,+ type VoiceModelsSnapshot,+ type VoiceTranscribeResult,+} from "../../shared/voice";+import { findVoiceModel } from "./catalog";+import { VoiceEngine } from "./engine";+import { MAX_HISTORY_AUDIO_BYTES, VoiceHistoryStore } from "./history-store";+import { ModelStore } from "./model-store";+import { hotwordList, type LoadSpec } from "./worker-protocol";+import workerPath from "./worker?modulePath";++const HISTORY_STATUSES = new Set<VoiceHistoryStatus>(["transcribing", "done", "failed", "interrupted"]);++function keepDaysOf(value: unknown): number | null {+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;+}++function broadcast(channel: string, payload?: unknown) {+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.isDestroyed()) win.webContents.send(channel, payload);+ }+}++/** Matches VOICE_LANGUAGES in @multica/core/voice. */+const LANGUAGES = new Set(["auto", "zh", "en", "ja", "ko", "yue"]);++/**+ * `asarUnpack: resources/**` puts the engine's native files next to the+ * archive; in dev the path has no `app.asar` and the replace is a no-op.+ */+function engineDir(): string {+ return join(app.getAppPath(), "resources", "voice-engine").replace("app.asar", "app.asar.unpacked");+}++export function setupVoiceInput(): void {+ const engine = new VoiceEngine({+ engineDir: engineDir(),+ fork: (args) => utilityProcess.fork(workerPath, args, { serviceName: "Multica Voice" }),+ });+ const snapshot = (): VoiceModelsSnapshot => ({ engineAvailable: engine.available(), models: store.list() });+ const store: ModelStore = new ModelStore({+ root: join(app.getPath("userData"), "voice-models"),+ fetch: (url, init) => net.fetch(url, init),+ onChange: () => broadcast(VOICE_MODELS_CHANGED_CHANNEL, snapshot()),+ });+ const ready = store.init();+ const history = new VoiceHistoryStore({+ root: join(app.getPath("userData"), "voice-history"),+ onChange: () => broadcast(VOICE_HISTORY_CHANGED_CHANNEL),+ });+ const historyReady = history.init().catch(() => {});++ const loadSpec = (request: unknown): LoadSpec | null => {+ if (!request || typeof request !== "object") return null;+ const { modelId, language, hotwords } = request as { modelId?: unknown; language?: unknown; hotwords?: unknown };+ const model = typeof modelId === "string" ? findVoiceModel(modelId) : undefined;+ if (!model) return null;+ const hint = model.languageHint && typeof language === "string" && LANGUAGES.has(language) ? language : "auto";+ const words = model.hotwords ? hotwordList(hotwords) : "";+ return {+ key: `${model.id}@${model.revision}:${hint}:${words}`,+ recognizer: model.recognizer,+ dir: store.modelDir(model.id),+ language: hint,+ hotwords: words,+ };+ };+ const modelIdOf = (request: unknown) => (request as { modelId: string }).modelId;++ ipcMain.handle(VOICE_MODELS_LIST_CHANNEL, async () => {+ await ready;+ return snapshot();+ });+ ipcMain.handle(VOICE_MODEL_DOWNLOAD_CHANNEL, async (_event, id: unknown) => {+ await ready;+ if (typeof id === "string") void store.download(id);+ });+ ipcMain.handle(VOICE_MODEL_CANCEL_CHANNEL, (_event, id: unknown) => {+ if (typeof id === "string") store.cancel(id);+ });+ ipcMain.handle(VOICE_MODEL_DELETE_CHANNEL, async (_event, id: unknown) => {+ if (typeof id !== "string" || !findVoiceModel(id)) return;+ await ready;+ engine.stop();+ await store.remove(id);+ });+ ipcMain.on(VOICE_PREPARE_CHANNEL, (_event, request: unknown) => {+ void ready.then(() => {+ const spec = loadSpec(request);+ if (spec && engine.available() && store.isReady(modelIdOf(request))) engine.prepare(spec);+ });+ });+ ipcMain.handle(VOICE_TRANSCRIBE_CHANNEL, async (_event, request: unknown): Promise<VoiceTranscribeResult> => {+ await ready;+ const spec = loadSpec(request);+ const samples = (request as { samples?: unknown } | null)?.samples;+ if (!spec || !(samples instanceof Float32Array) || samples.length === 0 || samples.length > MAX_VOICE_SAMPLES) {+ return { ok: false, reason: "failed", error: "invalid request" };+ }+ if (!engine.available()) return { ok: false, reason: "engine-unavailable" };+ if (!store.isReady(modelIdOf(request))) return { ok: false, reason: "model-missing" };+ try {+ return { ok: true, text: await engine.transcribe(spec, samples, VOICE_SAMPLE_RATE) };+ } catch (err) {+ return { ok: false, reason: "failed", error: err instanceof Error ? err.message : String(err) };+ }+ });++ ipcMain.handle(VOICE_HISTORY_LIST_CHANNEL, async (): Promise<VoiceHistoryEntry[]> => {+ await historyReady;+ await history.expire();+ return history.list();+ });+ ipcMain.handle(VOICE_HISTORY_SAVE_CHANNEL, async (_event, request: unknown): Promise<VoiceHistoryEntry | null> => {+ await historyReady;+ const { audio, mimeType, durationMs, keepDays } = (request ?? {}) as Record<string, unknown>;+ if (!(audio instanceof Uint8Array) || audio.byteLength === 0 || audio.byteLength > MAX_HISTORY_AUDIO_BYTES) return null;+ if (typeof mimeType !== "string" || typeof durationMs !== "number" || !Number.isFinite(durationMs)) return null;+ return history.save(audio, mimeType.slice(0, 100), Math.max(0, durationMs), keepDaysOf(keepDays));+ });+ ipcMain.handle(VOICE_HISTORY_UPDATE_CHANNEL, async (_event, id: unknown, patch: unknown) => {+ await historyReady;+ const { status, text } = (patch ?? {}) as Record<string, unknown>;+ if (typeof id !== "string" || !HISTORY_STATUSES.has(status as VoiceHistoryStatus)) return;+ await history.update(id, { status: status as VoiceHistoryStatus, text: typeof text === "string" ? text : undefined });+ });+ ipcMain.handle(VOICE_HISTORY_AUDIO_CHANNEL, async (_event, id: unknown): Promise<VoiceHistoryAudio | null> => {+ await historyReady;+ return typeof id === "string" ? history.audio(id) : null;+ });+ ipcMain.handle(VOICE_HISTORY_REMOVE_CHANNEL, async (_event, id: unknown) => {+ await historyReady;+ if (typeof id === "string") await history.remove(id);+ });+ ipcMain.handle(VOICE_HISTORY_RETENTION_CHANNEL, async (_event, keepDays: unknown) => {+ await historyReady;+ if (keepDays === null || typeof keepDays === "number") await history.setRetention(keepDaysOf(keepDays));+ });+ ipcMain.handle(VOICE_HISTORY_CLEAR_CHANNEL, async () => {+ await historyReady;+ await history.clear();+ });++ app.on("will-quit", () => engine.stop());+}diff --git a/apps/desktop/src/main/voice/model-store.test.ts b/apps/desktop/src/main/voice/model-store.test.tsnew file mode 100644index 0000000000..c4e2bb97f6--- /dev/null+++ b/apps/desktop/src/main/voice/model-store.test.ts@@ -0,0 +1,168 @@+// @vitest-environment node+import { createHash } from "crypto";+import { existsSync } from "fs";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "fs/promises";+import { tmpdir } from "os";+import { join } from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { CatalogModel } from "./catalog";+import { ModelStore } from "./model-store";++const encoder = new TextEncoder();+const FILES: Record<string, Uint8Array> = {+ "model.onnx": encoder.encode("weights ".repeat(4000)),+ "tokens.txt": encoder.encode("a b c"),+ "tokenizer/vocab.json": encoder.encode('{"a":1}'),+};++function sha256(data: Uint8Array) {+ return createHash("sha256").update(data).digest("hex");+}++const MODEL: CatalogModel = {+ id: "tiny",+ name: "Tiny",+ author: "Test",+ licenseUrl: "https://example.com/license",+ repo: "org/tiny",+ revision: "rev1",+ languages: ["en"],+ languageHint: false,+ hotwords: false,+ recognizer: "sense-voice",+ files: Object.entries(FILES).map(([name, data]) => ({ name, size: data.byteLength, sha256: sha256(data) })),+};++type Served = { url: string; range?: string };++/** Serves FILES, honouring Range; `failAfter` cuts a body short once. */+function server(options: { failHosts?: string[]; failAfter?: number; corrupt?: string } = {}) {+ const requests: Served[] = [];+ let cutOnce = options.failAfter;+ const fetch = vi.fn(async (url: string, init: { signal: AbortSignal; headers: Record<string, string> }) => {+ requests.push({ url, range: init.headers.Range });+ const host = new URL(url).host;+ if (options.failHosts?.includes(host)) return new Response("down", { status: 503 });+ const name = url.split("/resolve/rev1/")[1]!;+ let data = FILES[name]!;+ if (options.corrupt === name) data = encoder.encode("x".repeat(data.byteLength));+ const start = init.headers.Range ? Number(/bytes=(\d+)-/.exec(init.headers.Range)![1]) : 0;+ const slice = data.subarray(start);+ const cut = cutOnce;+ cutOnce = undefined;+ let sent = false;+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ if (init.signal.aborted) controller.error(init.signal.reason);+ else if (sent) controller[cut !== undefined ? "error" : "close"](new Error("connection reset"));+ else controller.enqueue(cut !== undefined ? slice.subarray(0, cut) : slice);+ sent = true;+ },+ });+ return new Response(body, { status: start > 0 ? 206 : 200 });+ });+ return { fetch, requests };+}++let root: string;+const onChange = vi.fn();++function store(fetch: ReturnType<typeof server>["fetch"]) {+ return new ModelStore({+ root,+ fetch,+ onChange,+ catalog: [MODEL],+ mirrors: ["https://primary.test", "https://mirror.test"],+ });+}++beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), "voice-models-"));+ onChange.mockReset();+});++afterEach(async () => {+ await rm(root, { recursive: true, force: true });+});++describe("ModelStore", () => {+ it("downloads, verifies and installs a model", async () => {+ const { fetch, requests } = server();+ const models = store(fetch);+ await models.init();+ expect(models.list()[0]).toMatchObject({ status: "absent", sizeBytes: 32012 });++ await models.download("tiny");+ expect(models.isReady("tiny")).toBe(true);+ expect(models.list()[0]).toMatchObject({ status: "ready" });+ expect(await readFile(join(root, "tiny", "tokens.txt"), "utf8")).toBe("a b c");+ expect(await readFile(join(root, "tiny", "tokenizer", "vocab.json"), "utf8")).toBe('{"a":1}');+ expect(existsSync(join(root, ".partial", "tiny"))).toBe(false);+ expect(requests.map((r) => r.url)).toEqual([+ "https://primary.test/org/tiny/resolve/rev1/model.onnx",+ "https://primary.test/org/tiny/resolve/rev1/tokens.txt",+ "https://primary.test/org/tiny/resolve/rev1/tokenizer/vocab.json",+ ]);++ const reopened = store(fetch);+ await reopened.init();+ expect(reopened.isReady("tiny")).toBe(true);+ });++ it("falls back to the mirror", async () => {+ const { fetch, requests } = server({ failHosts: ["primary.test"] });+ const models = store(fetch);+ await models.download("tiny");+ expect(models.isReady("tiny")).toBe(true);+ expect(requests.filter((r) => r.url.startsWith("https://mirror.test"))).toHaveLength(3);+ });++ it("resumes a cut-off download with a Range request", async () => {+ const { fetch, requests } = server({ failHosts: ["mirror.test"], failAfter: 1000 });+ const models = store(fetch);+ await models.download("tiny");+ expect(models.isReady("tiny")).toBe(false);+ expect(models.list()[0]?.error).toBeTruthy();++ await models.download("tiny");+ expect(models.isReady("tiny")).toBe(true);+ expect(requests.some((r) => r.range === "bytes=1000-")).toBe(true);+ expect(await readFile(join(root, "tiny", "model.onnx"))).toEqual(Buffer.from(FILES["model.onnx"]!));+ });++ it("rejects a file that fails its checksum and throws it away", async () => {+ const { fetch } = server({ corrupt: "tokens.txt" });+ const models = store(fetch);+ await models.download("tiny");+ expect(models.isReady("tiny")).toBe(false);+ expect(models.list()[0]?.error).toMatch(/checksum/);+ expect(existsSync(join(root, ".partial", "tiny", "tokens.txt"))).toBe(false);+ });++ it("cancelling discards the partial download without an error", async () => {+ const { fetch } = server();+ const models = store(fetch);+ const pending = models.download("tiny");+ models.cancel("tiny");+ await pending;+ expect(models.list()[0]).toMatchObject({ status: "absent" });+ expect(models.list()[0]?.error).toBeUndefined();+ expect(existsSync(join(root, ".partial", "tiny"))).toBe(false);+ });++ it("ignores a model installed from another revision, and deletes", async () => {+ await mkdir(join(root, "tiny"), { recursive: true });+ await writeFile(join(root, "tiny", "model.json"), JSON.stringify({ revision: "old" }));+ const { fetch } = server();+ const models = store(fetch);+ await models.init();+ expect(models.isReady("tiny")).toBe(false);++ await models.download("tiny");+ expect(models.isReady("tiny")).toBe(true);+ await models.remove("tiny");+ expect(models.isReady("tiny")).toBe(false);+ expect(existsSync(join(root, "tiny"))).toBe(false);+ });+});diff --git a/apps/desktop/src/main/voice/model-store.ts b/apps/desktop/src/main/voice/model-store.tsnew file mode 100644index 0000000000..e4b1638297--- /dev/null+++ b/apps/desktop/src/main/voice/model-store.ts@@ -0,0 +1,216 @@+import { createHash } from "crypto";+import { createReadStream, createWriteStream } from "fs";+import { mkdir, readFile, rename, rm, stat, writeFile } from "fs/promises";+import { dirname, join } from "path";+import { once } from "events";+import type { VoiceModelInfo } from "../../shared/voice";+import {+ MODEL_MIRRORS,+ VOICE_MODELS,+ modelSize,+ type CatalogFile,+ type CatalogModel,+} from "./catalog";++const MARKER = "model.json";+const PROGRESS_INTERVAL_MS = 200;++type Fetch = (url: string, init: { signal: AbortSignal; headers: Record<string, string> }) => Promise<Response>;++export interface ModelStoreOptions {+ /** Folder that holds one subfolder per installed model. */+ root: string;+ fetch: Fetch;+ onChange: () => void;+ catalog?: readonly CatalogModel[];+ mirrors?: readonly string[];+}++interface Download {+ controller: AbortController;+ /** Bytes on disk per file name. */+ bytes: Map<string, number>;+}++async function sizeOf(path: string): Promise<number> {+ try {+ return (await stat(path)).size;+ } catch {+ return 0;+ }+}++async function sha256Of(path: string): Promise<string> {+ const hash = createHash("sha256");+ for await (const chunk of createReadStream(path)) hash.update(chunk as Buffer);+ return hash.digest("hex");+}++/**+ * Installed speech models and their downloads. A model is installed once all+ * its files are verified and moved into `<root>/<id>` with a marker naming+ * the pinned revision; partial files wait in `<root>/.partial/<id>` so a+ * failed download resumes where it stopped.+ */+export class ModelStore {+ private readonly catalog: readonly CatalogModel[];+ private readonly mirrors: readonly string[];+ private readonly installed = new Set<string>();+ private readonly downloads = new Map<string, Download>();+ private readonly errors = new Map<string, string>();+ private lastProgress = 0;++ constructor(private readonly options: ModelStoreOptions) {+ this.catalog = options.catalog ?? VOICE_MODELS;+ this.mirrors = options.mirrors ?? MODEL_MIRRORS;+ }++ /** Read which models are installed. */+ async init(): Promise<void> {+ await Promise.all(+ this.catalog.map(async (model) => {+ try {+ const marker = JSON.parse(await readFile(join(this.modelDir(model.id), MARKER), "utf8")) as {+ revision?: unknown;+ };+ if (marker.revision === model.revision) this.installed.add(model.id);+ } catch {+ // Not installed, or installed from another revision.+ }+ }),+ );+ }++ modelDir(id: string): string {+ return join(this.options.root, id);+ }++ isReady(id: string): boolean {+ return this.installed.has(id);+ }++ list(): VoiceModelInfo[] {+ return this.catalog.map((model) => {+ const download = this.downloads.get(model.id);+ let received = 0;+ download?.bytes.forEach((bytes) => (received += bytes));+ const error = this.errors.get(model.id);+ return {+ id: model.id,+ name: model.name,+ author: model.author,+ licenseUrl: model.licenseUrl,+ languages: [...model.languages],+ languageHint: model.languageHint,+ ...(model.highlight ? { highlight: model.highlight } : {}),+ sizeBytes: modelSize(model),+ status: download ? "downloading" : this.installed.has(model.id) ? "ready" : "absent",+ receivedBytes: received,+ ...(error ? { error } : {}),+ };+ });+ }++ /** Download and install a model; resolves once it is installed or has failed. */+ async download(id: string): Promise<void> {+ const model = this.catalog.find((entry) => entry.id === id);+ if (!model || this.installed.has(id) || this.downloads.has(id)) return;+ const download: Download = { controller: new AbortController(), bytes: new Map() };+ this.downloads.set(id, download);+ this.errors.delete(id);+ this.options.onChange();+ const partialDir = join(this.options.root, ".partial", id);+ try {+ await mkdir(partialDir, { recursive: true });+ for (const file of model.files) {+ await mkdir(dirname(join(partialDir, file.name)), { recursive: true });+ download.bytes.set(file.name, await sizeOf(join(partialDir, file.name)));+ }+ for (const file of model.files) {+ await this.fetchFile(model, file, join(partialDir, file.name), download);+ }+ download.controller.signal.throwIfAborted();+ const dir = this.modelDir(id);+ await rm(dir, { recursive: true, force: true });+ await rename(partialDir, dir);+ await writeFile(join(dir, MARKER), JSON.stringify({ id, revision: model.revision }));+ this.installed.add(id);+ } catch (err) {+ if (download.controller.signal.aborted) {+ await rm(partialDir, { recursive: true, force: true });+ } else {+ this.errors.set(id, err instanceof Error ? err.message : String(err));+ }+ } finally {+ this.downloads.delete(id);+ this.options.onChange();+ }+ }++ /** Stop a download and throw away what it fetched. */+ cancel(id: string): void {+ this.downloads.get(id)?.controller.abort();+ }++ async remove(id: string): Promise<void> {+ this.cancel(id);+ this.installed.delete(id);+ this.errors.delete(id);+ await rm(this.modelDir(id), { recursive: true, force: true });+ this.options.onChange();+ }++ private async fetchFile(model: CatalogModel, file: CatalogFile, dest: string, download: Download) {+ const { signal } = download.controller;+ let lastError: unknown;+ for (const base of this.mirrors) {+ let have = await sizeOf(dest);+ if (have > file.size) {+ await rm(dest, { force: true });+ have = 0;+ }+ if (have === file.size) break;+ try {+ const url = `${base}/${model.repo}/resolve/${model.revision}/${file.name}`;+ const response = await this.options.fetch(url, {+ signal,+ headers: have > 0 ? { Range: `bytes=${have}-` } : {},+ });+ if (!response.ok || !response.body) throw new Error(`HTTP ${response.status} from ${new URL(url).host}`);+ if (response.status !== 206) have = 0;+ download.bytes.set(file.name, have);+ const out = createWriteStream(dest, { flags: have > 0 ? "a" : "w" });+ try {+ for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {+ signal.throwIfAborted();+ if (!out.write(chunk)) await once(out, "drain");+ have += chunk.byteLength;+ download.bytes.set(file.name, have);+ this.progress();+ }+ } finally {+ out.end();+ await once(out, "close");+ }+ if (have === file.size) break;+ lastError = new Error(`${file.name} ended early`);+ } catch (err) {+ if (signal.aborted) throw err;+ lastError = err;+ }+ }+ if ((await sizeOf(dest)) !== file.size) throw lastError ?? new Error(`${file.name} is incomplete`);+ if ((await sha256Of(dest)) !== file.sha256) {+ await rm(dest, { force: true });+ download.bytes.set(file.name, 0);+ throw new Error(`${file.name} failed its checksum`);+ }+ }++ private progress() {+ const now = Date.now();+ if (now - this.lastProgress < PROGRESS_INTERVAL_MS) return;+ this.lastProgress = now;+ this.options.onChange();+ }+}diff --git a/apps/desktop/src/main/voice/worker-protocol.test.ts b/apps/desktop/src/main/voice/worker-protocol.test.tsnew file mode 100644index 0000000000..006f88f3b9--- /dev/null+++ b/apps/desktop/src/main/voice/worker-protocol.test.ts@@ -0,0 +1,65 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { hotwordList, joinTranscripts, recognizerConfig, splitAtPauses, type LoadSpec } from "./worker-protocol";++const RATE = 16000;++/** Loud noise with quiet stretches centred at the given seconds. */+function speech(seconds: number, pausesAt: number[]): Float32Array {+ const samples = new Float32Array(seconds * RATE);+ for (let i = 0; i < samples.length; i++) samples[i] = Math.sin(i * 0.3) * 0.5;+ for (const at of pausesAt) samples.fill(0, (at - 0.2) * RATE, (at + 0.2) * RATE);+ return samples;+}++describe("splitAtPauses", () => {+ it("keeps a short clip whole", () => {+ const samples = speech(12, []);+ expect(splitAtPauses(samples, RATE)).toEqual([samples]);+ });++ it("cuts long clips at pauses into pieces of at most 20 seconds", () => {+ const samples = speech(50, [14, 31]);+ const segments = splitAtPauses(samples, RATE);+ expect(segments.map((s) => Math.round(s.length / RATE))).toEqual([14, 17, 19]);+ expect(segments.reduce((sum, s) => sum + s.length, 0)).toBe(samples.length);+ });++ it("cuts at 20 seconds when there is no pause", () => {+ const segments = splitAtPauses(speech(45, []), RATE);+ expect(segments.every((s) => s.length <= 20 * RATE)).toBe(true);+ expect(segments.length).toBe(3);+ });+});++describe("joinTranscripts", () => {+ it("spaces Latin text and runs CJK together", () => {+ expect(joinTranscripts(["Assign it to Lambda.", " Then ship it. "])).toBe("Assign it to Lambda. Then ship it.");+ expect(joinTranscripts(["把这个交给", "Lambda", "处理。", ""])).toBe("把这个交给Lambda处理。");+ });+});++describe("hotwordList", () => {+ it("strips separators and ignores non-strings", () => {+ expect(hotwordList(["Multica", "a,b", "张,三", 3, " "])).toBe("Multica,a b,张 三");+ expect(hotwordList("Multica")).toBe("");+ });+});++describe("recognizerConfig", () => {+ it("points Qwen3-ASR at its files and passes hotwords", () => {+ const spec: LoadSpec = { key: "k", recognizer: "qwen3-asr", dir: "/m", language: "auto", hotwords: "Multica,Lambda" };+ const config = recognizerConfig(spec, 4) as { modelConfig: Record<string, unknown> };+ expect(config.modelConfig).toMatchObject({+ qwen3Asr: {+ convFrontend: "/m/conv_frontend.onnx",+ encoder: "/m/encoder.int8.onnx",+ decoder: "/m/decoder.int8.onnx",+ tokenizer: "/m/tokenizer",+ hotwords: "Multica,Lambda",+ },+ tokens: "",+ numThreads: 4,+ });+ });+});diff --git a/apps/desktop/src/main/voice/worker-protocol.ts b/apps/desktop/src/main/voice/worker-protocol.tsnew file mode 100644index 0000000000..6aedd2bec0--- /dev/null+++ b/apps/desktop/src/main/voice/worker-protocol.ts@@ -0,0 +1,136 @@+import { join } from "path";+import type { RecognizerKind } from "./catalog";++/** Which recognizer to have loaded; `key` changes whenever any field does. */+export interface LoadSpec {+ key: string;+ recognizer: RecognizerKind;+ dir: string;+ /** A VOICE_LANGUAGES value. */+ language: string;+ /** Comma-separated words to favour, for recognizers that take them. */+ hotwords: string;+}++export type WorkerRequest =+ | { id: number; type: "load"; spec: LoadSpec }+ | { id: number; type: "transcribe"; spec: LoadSpec; samples: Float32Array; sampleRate: number };++export type WorkerResponse = { id: number; ok: true; text?: string } | { id: number; ok: false; error: string };++/** sherpa-onnx's offline recognizer config for a model folder. */+export function recognizerConfig(spec: LoadSpec, numThreads: number): Record<string, unknown> {+ const file = (name: string) => join(spec.dir, name);+ let model: Record<string, unknown>;+ if (spec.recognizer === "qwen3-asr") {+ model = {+ qwen3Asr: {+ convFrontend: file("conv_frontend.onnx"),+ encoder: file("encoder.int8.onnx"),+ decoder: file("decoder.int8.onnx"),+ tokenizer: file("tokenizer"),+ hotwords: spec.hotwords,+ // The defaults (512 / 128) cut a segment's transcript short once+ // hotwords lengthen the prompt.+ maxTotalLen: 1024,+ maxNewTokens: 256,+ },+ tokens: "",+ };+ } else if (spec.recognizer === "sense-voice") {+ model = {+ senseVoice: {+ model: file("model.int8.onnx"),+ language: spec.language === "auto" ? "" : spec.language,+ useInverseTextNormalization: 1,+ },+ tokens: file("tokens.txt"),+ };+ } else {+ model = {+ transducer: {+ encoder: file("encoder.int8.onnx"),+ decoder: file("decoder.int8.onnx"),+ joiner: file("joiner.int8.onnx"),+ },+ modelType: "nemo_transducer",+ tokens: file("tokens.txt"),+ };+ }+ return {+ featConfig: { sampleRate: 16000, featureDim: 80 },+ modelConfig: { ...model, numThreads, provider: "cpu", debug: 0 },+ decodingMethod: "greedy_search",+ };+}++/** Every hotword sits in the model's prompt, which shares a fixed budget with the audio. */+const MAX_HOTWORDS = 60;+const MAX_HOTWORD_CHARS = 600;++/** Renderer-supplied hotwords as sherpa's comma-separated list. */+export function hotwordList(value: unknown): string {+ if (!Array.isArray(value)) return "";+ const words: string[] = [];+ let chars = 0;+ for (const raw of value) {+ if (typeof raw !== "string") continue;+ const word = raw.replace(/[,,\s]+/g, " ").trim().slice(0, 40);+ if (!word || chars + word.length > MAX_HOTWORD_CHARS) continue;+ words.push(word);+ chars += word.length + 1;+ if (words.length >= MAX_HOTWORDS) break;+ }+ return words.join(",");+}++const MAX_SEGMENT_SECONDS = 20;+const MIN_SEGMENT_SECONDS = 10;+const PAUSE_WINDOW_SECONDS = 0.3;++/**+ * Cut a long clip into pieces of at most 20 seconds, each ending at the+ * quietest stretch between 10 and 20 seconds in, so cuts fall between words.+ * Qwen3-ASR loses everything past ~40 seconds in one pass, and decode time+ * grows faster than the clip.+ */+export function splitAtPauses(samples: Float32Array, sampleRate: number): Float32Array[] {+ const max = MAX_SEGMENT_SECONDS * sampleRate;+ if (samples.length <= max) return [samples];+ const window = Math.round(PAUSE_WINDOW_SECONDS * sampleRate);+ const hop = Math.round(window / 3);+ const segments: Float32Array[] = [];+ let start = 0;+ while (samples.length - start > max) {+ let cut = start + max;+ let quietest = Infinity;+ // Latest first, moving earlier only for a clearly quieter stretch, so+ // evenly loud audio still gets the longest segments.+ for (let at = start + max - window; at >= start + MIN_SEGMENT_SECONDS * sampleRate; at -= hop) {+ let energy = 0;+ for (let i = at; i < at + window; i++) energy += samples[i]! * samples[i]!;+ if (energy < quietest / 2 || quietest === Infinity) {+ quietest = energy;+ cut = at + Math.round(window / 2);+ }+ }+ segments.push(samples.subarray(start, cut));+ start = cut;+ }+ segments.push(samples.subarray(start));+ return segments;+}++const CJK_EDGE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uff00-\uffef]/;++/** Join segment transcripts: no space where either side is CJK. */+export function joinTranscripts(parts: readonly string[]): string {+ let out = "";+ for (const raw of parts) {+ const part = raw.trim();+ if (!part) continue;+ const spaced = out && !CJK_EDGE.test(out[out.length - 1]!) && !CJK_EDGE.test(part[0]!);+ out += (spaced ? " " : "") + part;+ }+ return out;+}diff --git a/apps/desktop/src/main/voice/worker.ts b/apps/desktop/src/main/voice/worker.tsnew file mode 100644index 0000000000..4c4f88a162--- /dev/null+++ b/apps/desktop/src/main/voice/worker.ts@@ -0,0 +1,67 @@+/**+ * Utility-process entry that runs sherpa-onnx. Kept out of the main process+ * because loading a model and decoding are synchronous native calls that+ * would freeze every window while they run. argv[2] is the folder holding+ * this platform's `sherpa-onnx.node` and its libraries.+ */+import { availableParallelism } from "os";+import { createRequire } from "module";+import { join } from "path";+import {+ joinTranscripts,+ recognizerConfig,+ splitAtPauses,+ type LoadSpec,+ type WorkerRequest,+ type WorkerResponse,+} from "./worker-protocol";++interface SherpaAddon {+ createOfflineRecognizer(config: Record<string, unknown>): unknown;+ createOfflineStream(recognizer: unknown): unknown;+ acceptWaveformOffline(stream: unknown, wave: { samples: Float32Array; sampleRate: number }): void;+ decodeOfflineStream(recognizer: unknown, stream: unknown): void;+ getOfflineStreamResultAsJson(stream: unknown): string;+}++const engineDir = process.argv[2] ?? "";+const numThreads = Math.max(1, Math.min(4, Math.floor(availableParallelism() / 2)));++let addon: SherpaAddon | null = null;+let loaded: { key: string; recognizer: unknown } | null = null;++function recognizerFor(spec: LoadSpec): unknown {+ if (loaded?.key === spec.key) return loaded.recognizer;+ addon ??= createRequire(__filename)(join(engineDir, "sherpa-onnx.node")) as SherpaAddon;+ loaded = null;+ loaded = { key: spec.key, recognizer: addon.createOfflineRecognizer(recognizerConfig(spec, numThreads)) };+ return loaded.recognizer;+}++function decode(recognizer: unknown, samples: Float32Array, sampleRate: number): string {+ const stream = addon!.createOfflineStream(recognizer);+ addon!.acceptWaveformOffline(stream, { samples, sampleRate });+ addon!.decodeOfflineStream(recognizer, stream);+ const result = JSON.parse(addon!.getOfflineStreamResultAsJson(stream)) as { text?: unknown };+ return typeof result.text === "string" ? result.text : "";+}++function handle(request: WorkerRequest): WorkerResponse {+ const recognizer = recognizerFor(request.spec);+ if (request.type === "load") return { id: request.id, ok: true };+ const parts = splitAtPauses(request.samples, request.sampleRate).map((segment) =>+ decode(recognizer, segment, request.sampleRate),+ );+ return { id: request.id, ok: true, text: joinTranscripts(parts) };+}++process.parentPort.on("message", (event) => {+ const request = event.data as WorkerRequest;+ let response: WorkerResponse;+ try {+ response = handle(request);+ } catch (err) {+ response = { id: request.id, ok: false, error: err instanceof Error ? err.message : String(err) };+ }+ process.parentPort.postMessage(response);+});diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex a3bd0a813e..94680fcbea 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -27,6 +27,16 @@ import type {WorkspacePathOptions,WorkspacePathRequest,} from "../shared/workspace-window";+import type {+ VoiceHistoryAudio,+ VoiceHistoryEntry,+ VoiceHistorySaveRequest,+ VoiceHistoryUpdate,+ VoiceModelRequest,+ VoiceModelsSnapshot,+ VoiceTranscribeRequest,+ VoiceTranscribeResult,+} from "../shared/voice";interface DesktopAPI {/** App version + normalized OS, captured synchronously at preload time. */@@ -131,6 +141,35 @@ interface DesktopAPI {openThemeFolder: (name?: string) => Promise<{ ok: boolean; error?: string }>;/** Create a theme folder from files; never replaces an existing one. */writeThemeFolder: (name: string, files: ThemeFolderFile[]) => Promise<ThemeFolderWriteResult>;+ /** On-device voice input: speech models and transcription in main. */+ voice: {+ listModels: () => Promise<VoiceModelsSnapshot>;+ /** Called on every model status or download-progress change. Returns an unsubscribe function. */+ onModelsChanged: (callback: (snapshot: VoiceModelsSnapshot) => void) => () => void;+ /** Start a download; progress arrives through onModelsChanged. */+ downloadModel: (id: string) => Promise<void>;+ cancelDownload: (id: string) => Promise<void>;+ deleteModel: (id: string) => Promise<void>;+ /** Load the model while the user is still speaking. */+ prepare: (request: VoiceModelRequest) => void;+ transcribe: (request: VoiceTranscribeRequest) => Promise<VoiceTranscribeResult>;+ /** Recordings and their transcripts, kept on this device. */+ history: {+ /** Newest first. */+ list: () => Promise<VoiceHistoryEntry[]>;+ /** Called after any change. Returns an unsubscribe function. */+ onChanged: (callback: () => void) => () => void;+ /** Null when the request is invalid. */+ save: (request: VoiceHistorySaveRequest) => Promise<VoiceHistoryEntry | null>;+ update: (id: string, patch: VoiceHistoryUpdate) => Promise<void>;+ audio: (id: string) => Promise<VoiceHistoryAudio | null>;+ remove: (id: string) => Promise<void>;+ /** Remember how many days to keep (0 keeps none, null forever) and drop older entries now. */+ setRetention: (keepDays: number | null) => Promise<void>;+ /** Delete every entry, including one still being transcribed. */+ clear: () => Promise<void>;+ };+ };/** Listen for Cmd/Ctrl+W tab-close requests from the main process.* Returns an unsubscribe function. */onCloseActiveTab: (callback: () => void) => () => void;diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 6b141dcda2..ba79e2a6f2 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -44,6 +44,31 @@ import type {DaemonStatus,LocalRuntimeProbe,} from "../shared/daemon-types";+import {+ VOICE_HISTORY_AUDIO_CHANNEL,+ VOICE_HISTORY_CHANGED_CHANNEL,+ VOICE_HISTORY_LIST_CHANNEL,+ VOICE_HISTORY_RETENTION_CHANNEL,+ VOICE_HISTORY_CLEAR_CHANNEL,+ VOICE_HISTORY_REMOVE_CHANNEL,+ VOICE_HISTORY_SAVE_CHANNEL,+ VOICE_HISTORY_UPDATE_CHANNEL,+ VOICE_MODEL_CANCEL_CHANNEL,+ VOICE_MODEL_DELETE_CHANNEL,+ VOICE_MODEL_DOWNLOAD_CHANNEL,+ VOICE_MODELS_CHANGED_CHANNEL,+ VOICE_MODELS_LIST_CHANNEL,+ VOICE_PREPARE_CHANNEL,+ VOICE_TRANSCRIBE_CHANNEL,+ type VoiceHistoryAudio,+ type VoiceHistoryEntry,+ type VoiceHistorySaveRequest,+ type VoiceHistoryUpdate,+ type VoiceModelRequest,+ type VoiceModelsSnapshot,+ type VoiceTranscribeRequest,+ type VoiceTranscribeResult,+} from "../shared/voice";import {MAIN_RENDERER_CHANNEL_STATE_CHANNEL,NEW_WINDOW_SHORTCUT_CHANNEL,@@ -277,6 +302,43 @@ const desktopAPI = {/** Create a theme folder from files; never replaces an existing one. */writeThemeFolder: (name: string, files: ThemeFolderFile[]): Promise<ThemeFolderWriteResult> =>ipcRenderer.invoke(THEME_FOLDER_WRITE_CHANNEL, name, files),+ /** On-device voice input: speech models and transcription in main. */+ voice: {+ listModels: (): Promise<VoiceModelsSnapshot> => ipcRenderer.invoke(VOICE_MODELS_LIST_CHANNEL),+ onModelsChanged: (callback: (snapshot: VoiceModelsSnapshot) => void) => {+ const handler = (_event: Electron.IpcRendererEvent, snapshot: VoiceModelsSnapshot) =>+ callback(snapshot);+ ipcRenderer.on(VOICE_MODELS_CHANGED_CHANNEL, handler);+ return () => {+ ipcRenderer.removeListener(VOICE_MODELS_CHANGED_CHANNEL, handler);+ };+ },+ downloadModel: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_MODEL_DOWNLOAD_CHANNEL, id),+ cancelDownload: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_MODEL_CANCEL_CHANNEL, id),+ deleteModel: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_MODEL_DELETE_CHANNEL, id),+ prepare: (request: VoiceModelRequest) => ipcRenderer.send(VOICE_PREPARE_CHANNEL, request),+ transcribe: (request: VoiceTranscribeRequest): Promise<VoiceTranscribeResult> =>+ ipcRenderer.invoke(VOICE_TRANSCRIBE_CHANNEL, request),+ history: {+ list: (): Promise<VoiceHistoryEntry[]> => ipcRenderer.invoke(VOICE_HISTORY_LIST_CHANNEL),+ onChanged: (callback: () => void) => {+ const handler = () => callback();+ ipcRenderer.on(VOICE_HISTORY_CHANGED_CHANNEL, handler);+ return () => {+ ipcRenderer.removeListener(VOICE_HISTORY_CHANGED_CHANNEL, handler);+ };+ },+ save: (request: VoiceHistorySaveRequest): Promise<VoiceHistoryEntry | null> =>+ ipcRenderer.invoke(VOICE_HISTORY_SAVE_CHANNEL, request),+ update: (id: string, patch: VoiceHistoryUpdate): Promise<void> =>+ ipcRenderer.invoke(VOICE_HISTORY_UPDATE_CHANNEL, id, patch),+ audio: (id: string): Promise<VoiceHistoryAudio | null> => ipcRenderer.invoke(VOICE_HISTORY_AUDIO_CHANNEL, id),+ remove: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_HISTORY_REMOVE_CHANNEL, id),+ setRetention: (keepDays: number | null): Promise<void> =>+ ipcRenderer.invoke(VOICE_HISTORY_RETENTION_CHANNEL, keepDays),+ clear: (): Promise<void> => ipcRenderer.invoke(VOICE_HISTORY_CLEAR_CHANNEL),+ },+ },/** Listen for Cmd/Ctrl+W tab-close requests from the main process.* The renderer should close the active tab; if it was the last tab,* call `closeWindow()` to dismiss the window. Returns an unsubscribe fn. */diff --git a/apps/desktop/src/renderer/src/components/issue-window.test.tsx b/apps/desktop/src/renderer/src/components/issue-window.test.tsxindex 3e878850e0..d63a7b27c9 100644--- a/apps/desktop/src/renderer/src/components/issue-window.test.tsx+++ b/apps/desktop/src/renderer/src/components/issue-window.test.tsx@@ -46,6 +46,10 @@ vi.mock("@multica/views/layout", () => ({WorkspacePresencePrefetch: () => null,}));+vi.mock("@multica/views/voice", () => ({+ VoiceWorkspaceWords: () => null,+}));+vi.mock("@multica/views/platform", () => ({DragStrip: () => <div data-testid="drag-strip" />,WindowTitleBarProvider: ({diff --git a/apps/desktop/src/renderer/src/components/issue-window.tsx b/apps/desktop/src/renderer/src/components/issue-window.tsxindex a1872f1db9..79d1aa3dd3 100644--- a/apps/desktop/src/renderer/src/components/issue-window.tsx+++ b/apps/desktop/src/renderer/src/components/issue-window.tsx@@ -14,6 +14,7 @@ import { Button } from "@multica/ui/components/ui/button";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";import { ModalRegistry } from "@multica/views/modals/registry";import { WorkspacePresencePrefetch } from "@multica/views/layout";+import { VoiceWorkspaceWords } from "@multica/views/voice";import { DragStrip, WindowTitleBarProvider } from "@multica/views/platform";import type { IssueWindowContext } from "../../../shared/issue-window";import { DesktopAuthRecoveryPage } from "../pages/auth-recovery";@@ -82,6 +83,7 @@ function IssueWindowRoute() {<WorkspaceSlugProvider slug={workspaceSlug}><IssueWindowNavigationProvider><WorkspacePresencePrefetch />+ <VoiceWorkspaceWords /><IssueWindowFrame pageOwnsTitleBar><IssueDetailPage onDelete={() => window.desktopAPI.closeWindow()} /></IssueWindowFrame>diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsxindex 3e83ec4b82..ec3db73bdc 100644--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx@@ -93,6 +93,10 @@ vi.mock("@multica/views/layout", () => ({WorkspacePresencePrefetch: () => null,}));+vi.mock("@multica/views/voice", () => ({+ VoiceWorkspaceWords: () => null,+}));+// The point of this whole test: assert the desktop layout mounts the// SourceBackfillModal. We stub the real component with a marker that// renders only when the layout actually rendered it (and not e.g.diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsxindex 86df481d76..8c7ad257c7 100644--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx@@ -11,6 +11,7 @@ import { isWorkspaceDeletePending } from "@multica/core/workspace/pending-deleteimport { useAuthStore } from "@multica/core/auth";import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";import { WorkspacePresencePrefetch } from "@multica/views/layout";+import { VoiceWorkspaceWords } from "@multica/views/voice";import { SourceBackfillModal } from "@multica/views/onboarding";import { useTabStore } from "@/stores/tab-store";import { useWindowOverlayStore } from "@/stores/window-overlay-store";@@ -176,6 +177,7 @@ export function WorkspaceRouteLayout() {return (<WorkspaceSlugProvider slug={workspaceSlug}><WorkspacePresencePrefetch />+ <VoiceWorkspaceWords /><Outlet />{/* Source-attribution backfill: same Dialog the web shell mounts* inside DashboardLayout. Desktop's WorkspaceRouteLayout doesn'tdiff --git a/apps/desktop/src/shared/voice.ts b/apps/desktop/src/shared/voice.tsnew file mode 100644index 0000000000..0b7390861d--- /dev/null+++ b/apps/desktop/src/shared/voice.ts@@ -0,0 +1,107 @@+/**+ * On-device voice input: main downloads speech models into user data and+ * transcribes in a utility process, so audio never leaves the machine. The+ * renderer records, decodes to 16 kHz mono samples and asks for text.+ */++export const VOICE_MODELS_LIST_CHANNEL = "voice:models:list";+export const VOICE_MODELS_CHANGED_CHANNEL = "voice:models:changed";+export const VOICE_MODEL_DOWNLOAD_CHANNEL = "voice:models:download";+export const VOICE_MODEL_CANCEL_CHANNEL = "voice:models:cancel";+export const VOICE_MODEL_DELETE_CHANNEL = "voice:models:delete";+export const VOICE_PREPARE_CHANNEL = "voice:prepare";+export const VOICE_TRANSCRIBE_CHANNEL = "voice:transcribe";+export const VOICE_HISTORY_LIST_CHANNEL = "voice:history:list";+export const VOICE_HISTORY_CHANGED_CHANNEL = "voice:history:changed";+export const VOICE_HISTORY_SAVE_CHANNEL = "voice:history:save";+export const VOICE_HISTORY_UPDATE_CHANNEL = "voice:history:update";+export const VOICE_HISTORY_AUDIO_CHANNEL = "voice:history:audio";+export const VOICE_HISTORY_REMOVE_CHANNEL = "voice:history:remove";+export const VOICE_HISTORY_RETENTION_CHANNEL = "voice:history:retention";+export const VOICE_HISTORY_CLEAR_CHANNEL = "voice:history:clear";++/** The sample rate every model expects. */+export const VOICE_SAMPLE_RATE = 16000;+/** Matches the renderer's two-minute recording cap, with headroom. */+export const MAX_VOICE_SAMPLES = VOICE_SAMPLE_RATE * 150;++export type VoiceModelStatus = "absent" | "downloading" | "ready";++export interface VoiceModelInfo {+ id: string;+ name: string;+ /** Who trained the model, for attribution. */+ author: string;+ licenseUrl: string;+ /** BCP 47 codes the model transcribes. */+ languages: string[];+ /** The model takes a spoken-language hint; others always detect. */+ languageHint: boolean;+ /** What the model is best at, shown as a badge. */+ highlight?: "accurate" | "fast";+ sizeBytes: number;+ status: VoiceModelStatus;+ /** Bytes on disk so far while downloading. */+ receivedBytes: number;+ /** Why the last download failed. */+ error?: string;+}++export interface VoiceModelsSnapshot {+ /** False when this build has no speech engine for this platform. */+ engineAvailable: boolean;+ models: VoiceModelInfo[];+}++export interface VoiceModelRequest {+ modelId: string;+ /** A VOICE_LANGUAGES value; ignored by models without a language hint. */+ language: string;+ /** Names and terms to favour; ignored by models without hotword support. */+ hotwords?: string[];+}++export interface VoiceTranscribeRequest extends VoiceModelRequest {+ /** Mono PCM at VOICE_SAMPLE_RATE, in [-1, 1]. */+ samples: Float32Array;+}++export type VoiceTranscribeResult =+ | { ok: true; text: string }+ | { ok: false; reason: "model-missing" | "engine-unavailable" | "failed"; error?: string };++/**+ * Dictation history: every recording is kept on this device with its text,+ * so a failed or interrupted transcription can be run again from the audio.+ * `transcribing` left over from a previous run reads as `interrupted`.+ */+export type VoiceHistoryStatus = "transcribing" | "done" | "failed" | "interrupted";++export interface VoiceHistoryEntry {+ id: string;+ /** Epoch milliseconds. */+ createdAt: number;+ durationMs: number;+ status: VoiceHistoryStatus;+ /** The transcript as inserted; empty until one succeeds. */+ text: string;+}++export interface VoiceHistorySaveRequest {+ /** The recording as captured (compressed, e.g. webm/opus). */+ audio: Uint8Array;+ mimeType: string;+ durationMs: number;+ /** Prune entries older than this many days; null keeps everything. */+ keepDays: number | null;+}++export interface VoiceHistoryUpdate {+ status: VoiceHistoryStatus;+ text?: string;+}++export interface VoiceHistoryAudio {+ audio: Uint8Array;+ mimeType: string;+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex a4a1a9c6b3..e853d1b918 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -190,6 +190,7 @@"./drafts": "./drafts/index.ts","./drafts/*": "./drafts/*.ts","./shortcuts": "./shortcuts/index.ts",+ "./voice": "./voice/index.ts","./analytics": "./analytics/index.ts","./diagnostics": "./diagnostics/index.ts","./client-usage": "./client-usage/index.ts",diff --git a/packages/core/shortcuts/definitions.test.ts b/packages/core/shortcuts/definitions.test.tsindex d5ec51a20a..85e095ae6d 100644--- a/packages/core/shortcuts/definitions.test.ts+++ b/packages/core/shortcuts/definitions.test.ts@@ -341,6 +341,29 @@ describe("keyboard shortcut definitions", () => {}});+ it("lets voice input use Option chords that do not type a character", () => {+ const allowed = (key: string, modifiers: Parameters<typeof createShortcutChord>[1]) =>+ isShortcutAllowedForAction("voiceInput", createShortcutChord(key, modifiers), "macos", "web");+ expect(allowed("Space", { alt: true })).toBe(true);+ expect(allowed("F8", { alt: true })).toBe(true);+ expect(allowed("G", { primary: true, shift: true })).toBe(true);+ // Option+letter types a character on macOS.+ expect(allowed("V", { alt: true })).toBe(false);+ expect(allowed("Space", {})).toBe(false);+ expect(allowed("Space", { shift: true })).toBe(false);+ // Spotlight.+ expect(allowed("Space", { primary: true })).toBe(false);+ expect(SHORTCUT_ACTION_BY_ID.voiceInput.defaultShortcut).toBeNull();+ // macOS reports Option+Space as a non-breaking space.+ expect(+ shortcutMatchesEvent(+ createShortcutChord("Space", { alt: true }),+ keyEvent("\u00a0", { altKey: true }),+ "macos",+ ),+ ).toBe(true);+ });+it("prevents unsafe plain keys from hijacking editors and global navigation", () => {expect(isShortcutAllowedForAction("openSearch", createShortcutChord("J"), "macos"),diff --git a/packages/core/shortcuts/definitions.ts b/packages/core/shortcuts/definitions.tsindex 49111949a6..a54ec9cd1c 100644--- a/packages/core/shortcuts/definitions.ts+++ b/packages/core/shortcuts/definitions.ts@@ -15,6 +15,7 @@ export type ShortcutActionId =| "findInIssue"| "archiveInboxItem"| "send"+ | "voiceInput"| "goBack"| "goForward"| "goInbox"@@ -110,6 +111,16 @@ export const SHORTCUT_ACTIONS: readonly ShortcutActionDefinition[] = [allowInEditable: false,},{ id: "send", category: "general", defaultShortcut: primary("Enter"), allowInEditable: true },+ // Voice input works where the caret is, so it must fire inside editors. It+ // is matched on keydown AND keyup (holding it is push-to-talk), so the voice+ // layer handles it rather than the global dispatcher. Unassigned by default:+ // users pick their own chord in Settings.+ {+ id: "voiceInput",+ category: "general",+ defaultShortcut: null,+ allowInEditable: true,+ },// Browser-style history navigation (Mod+[ / Mod+]). Neither bracket is// app-owned (PRIMARY_RESERVED_KEYS) nor browser-owned// (BROWSER_ONLY_PRIMARY_RESERVED_KEYS), so both are recordable on every@@ -142,6 +153,8 @@ const MODIFIER_KEYS = new Set([const NON_ACTIONABLE_KEYS = new Set(["Dead", "Process", "Unidentified"]);const KEY_LABELS: Record<string, string> = {" ": "Space",+ // macOS types a non-breaking space for Option+Space.+ "\u00a0": "Space",ArrowUp: "Up",ArrowDown: "Down",ArrowLeft: "Left",@@ -398,6 +411,11 @@ export function isShortcutAllowedForAction(createShortcutChord("Enter", { primary: true }),);}+ // Held while talking, so Option/Alt chords are allowed too: they leave+ // typing alone as long as the key is not a printable character.+ if (actionId === "voiceInput") {+ return hasCommand || (shortcut.modifiers.alt && (shortcut.key === "Space" || shortcut.key.length > 1));+ }if (SHORTCUT_ACTION_BY_ID[actionId].allowInEditable) {return hasCommand;}diff --git a/packages/core/voice/history.ts b/packages/core/voice/history.tsnew file mode 100644index 0000000000..d89d976365--- /dev/null+++ b/packages/core/voice/history.ts@@ -0,0 +1,35 @@+/**+ * Dictation history: recordings kept on this device with their transcripts,+ * so one that failed or was interrupted can be transcribed again.+ */++export type VoiceHistoryStatus = "transcribing" | "done" | "failed" | "interrupted";++export interface VoiceHistoryEntry {+ id: string;+ /** Epoch milliseconds. */+ createdAt: number;+ durationMs: number;+ status: VoiceHistoryStatus;+ /** The transcript as inserted; empty until one succeeds. */+ text: string;+}++export const VOICE_HISTORY_RETENTIONS = ["off", "1d", "7d", "30d", "forever"] as const;+export type VoiceHistoryRetention = (typeof VOICE_HISTORY_RETENTIONS)[number];++/** Days to keep entries for; 0 keeps none, null keeps them all. */+export function voiceHistoryDays(retention: VoiceHistoryRetention): number | null {+ switch (retention) {+ case "off":+ return 0;+ case "1d":+ return 1;+ case "7d":+ return 7;+ case "30d":+ return 30;+ case "forever":+ return null;+ }+}diff --git a/packages/core/voice/hotwords.test.ts b/packages/core/voice/hotwords.test.tsnew file mode 100644index 0000000000..efab45ea02--- /dev/null+++ b/packages/core/voice/hotwords.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";+import { MAX_VOICE_HOTWORDS, voiceHotwords } from "./hotwords";++describe("voiceHotwords", () => {+ it("puts vocabulary first and drops case-insensitive repeats and blanks", () => {+ expect(voiceHotwords(["Multica", " "], ["Lambda", "MULTICA", " Jiayuan "])).toEqual([+ "Multica",+ "Lambda",+ "Jiayuan",+ ]);+ });++ it("caps the list", () => {+ const context = Array.from({ length: 100 }, (_, i) => `name${i}`);+ const words = voiceHotwords(["Mine"], context);+ expect(words).toHaveLength(MAX_VOICE_HOTWORDS);+ expect(words[0]).toBe("Mine");+ });+});diff --git a/packages/core/voice/hotwords.ts b/packages/core/voice/hotwords.tsnew file mode 100644index 0000000000..b733bdb5eb--- /dev/null+++ b/packages/core/voice/hotwords.ts@@ -0,0 +1,30 @@+/**+ * Names the speech model should favour: the user's vocabulary plus the+ * current workspace's people, agents and projects. Models that take hotwords+ * spell these right far more often than post-correction can fix them.+ */++/** Each word lengthens the model's prompt; past this, decoding slows with little gain. */+export const MAX_VOICE_HOTWORDS = 60;++let contextWords: readonly string[] = [];++/** Replace the workspace names offered as hotwords; the app keeps this current. */+export function setVoiceContextWords(words: readonly string[]) {+ contextWords = [...words];+}++/** Vocabulary first, then context names; deduped case-insensitively and capped. */+export function voiceHotwords(vocabulary: readonly string[], context: readonly string[] = contextWords): string[] {+ const seen = new Set<string>();+ const words: string[] = [];+ for (const raw of [...vocabulary, ...context]) {+ const word = raw.trim();+ const key = word.toLowerCase();+ if (!word || seen.has(key)) continue;+ seen.add(key);+ words.push(word);+ if (words.length >= MAX_VOICE_HOTWORDS) break;+ }+ return words;+}diff --git a/packages/core/voice/index.ts b/packages/core/voice/index.tsnew file mode 100644index 0000000000..2f0a3a20f1--- /dev/null+++ b/packages/core/voice/index.ts@@ -0,0 +1,51 @@+export {+ DEFAULT_VOICE_SETTINGS,+ MAX_VOCABULARY_WORDS,+ VOICE_LANGUAGES,+ sanitizeVoiceSettings,+ useVoiceSettingsStore,+ type VoiceActivation,+ type VoiceLanguage,+ type VoiceSettings,+} from "./store";+export {+ VOICE_HISTORY_RETENTIONS,+ voiceHistoryDays,+ type VoiceHistoryEntry,+ type VoiceHistoryRetention,+ type VoiceHistoryStatus,+} from "./history";+export { applyVocabulary, dictationSeparator, removeSpokenFillers } from "./text";+export { MAX_VOICE_HOTWORDS, setVoiceContextWords, voiceHotwords } from "./hotwords";+export {+ pickVoiceModel,+ useVoiceModelsStore,+ type VoiceModel,+ type VoiceModels,+ type VoiceTranscription,+} from "./models";+export {+ VoiceRecorderError,+ cancelVoice,+ connectVoiceRuntime,+ getVoiceState,+ noteVoiceFocus,+ pressVoice,+ registerVoiceTarget,+ releaseVoice,+ retryVoice,+ stopVoice,+ toggleVoice,+ transcribeVoiceClip,+ useVoiceMeter,+ useVoiceState,+ type VoiceClip,+ type VoiceDecodeOptions,+ type VoiceErrorKind,+ type VoiceHistoryRuntime,+ type VoiceMeter,+ type VoiceRecorder,+ type VoiceRecorderFailure,+ type VoiceRuntime,+ type VoiceState,+} from "./session";diff --git a/packages/core/voice/models.ts b/packages/core/voice/models.tsnew file mode 100644index 0000000000..374bb669eb--- /dev/null+++ b/packages/core/voice/models.ts@@ -0,0 +1,56 @@+"use client";++import { create } from "zustand";+import { useVoiceSettingsStore } from "./store";++export type VoiceModelStatus = "absent" | "downloading" | "ready";++/** A speech model the on-device engine can run. */+export interface VoiceModel {+ id: string;+ name: string;+ author: string;+ licenseUrl: string;+ /** BCP 47 codes the model transcribes. */+ languages: string[];+ /** The model takes a spoken-language hint; others always detect. */+ languageHint: boolean;+ /** What the model is best at, shown as a badge. */+ highlight?: "accurate" | "fast";+ sizeBytes: number;+ status: VoiceModelStatus;+ receivedBytes: number;+ error?: string;+}++export interface VoiceModels {+ /** False when this build has no speech engine for this platform. */+ engineAvailable: boolean;+ models: VoiceModel[];+}++export type VoiceTranscription =+ | { ok: true; text: string }+ | { ok: false; reason: "model-missing" | "engine-unavailable" | "failed"; error?: string };++interface VoiceModelsState {+ /** Null on web and until the engine first answers. */+ models: VoiceModels | null;+ setModels: (models: VoiceModels) => void;+}++/** The engine's model list, kept live by the connected voice runtime. */+export const useVoiceModelsStore = create<VoiceModelsState>()((set) => ({+ models: null,+ setModels: (models) => set({ models }),+}));++/** The installed model to use: the chosen one, else the first installed. */+export function pickVoiceModel(models: VoiceModels | null, preferred: string | null): VoiceModel | null {+ const ready = models?.models.filter((model) => model.status === "ready") ?? [];+ return ready.find((model) => model.id === preferred) ?? ready[0] ?? null;+}++export function activeVoiceModel(): VoiceModel | null {+ return pickVoiceModel(useVoiceModelsStore.getState().models, useVoiceSettingsStore.getState().modelId);+}diff --git a/packages/core/voice/session.test.ts b/packages/core/voice/session.test.tsnew file mode 100644index 0000000000..a575984cf7--- /dev/null+++ b/packages/core/voice/session.test.ts@@ -0,0 +1,394 @@+/**+ * @vitest-environment jsdom+ */+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { setVoiceContextWords } from "./hotwords";+import { useVoiceModelsStore, type VoiceModel, type VoiceModels } from "./models";+import {+ cancelVoice,+ connectVoiceRuntime,+ getVoiceState,+ noteVoiceFocus,+ pressVoice,+ registerVoiceTarget,+ releaseVoice,+ retryVoice,+ toggleVoice,+ transcribeVoiceClip,+ type VoiceTarget,+} from "./session";+import { DEFAULT_VOICE_SETTINGS, useVoiceSettingsStore } from "./store";+import { createShortcutChord } from "../shortcuts/definitions";+import { useShortcutStore } from "../shortcuts/store";++const MODEL: VoiceModel = {+ id: "sensevoice-small",+ name: "SenseVoice Small",+ author: "FunAudioLLM",+ licenseUrl: "https://example.com/license",+ languages: ["zh", "en"],+ languageHint: true,+ sizeBytes: 1,+ status: "ready",+ receivedBytes: 1,+};+const INSTALLED: VoiceModels = { engineAvailable: true, models: [MODEL] };++const clip = { durationMs: 1500, heardSpeech: true };+const recordings = { started: 0, discarded: 0 };+const engine = { transcribe: vi.fn(), prepare: vi.fn() };+const history = { save: vi.fn(), update: vi.fn() };++beforeAll(() => {+ connectVoiceRuntime(() => ({+ record: () => ({+ start: () => {+ recordings.started++;+ return Promise.resolve();+ },+ finish: () => Promise.resolve({ blob: new Blob(["audio"], { type: "audio/webm" }), ...clip }),+ discard: () => {+ recordings.discarded++;+ },+ }),+ prepare: (...args) => engine.prepare(...args),+ transcribe: (...args) => engine.transcribe(...args),+ watchModels: (onChange) => onChange(INSTALLED),+ history: {+ save: (...args) => history.save(...args),+ update: (...args) => history.update(...args),+ },+ }));+});++const unregister: Array<() => void> = [];++function target(id: string, overrides: Partial<VoiceTarget> = {}) {+ const inserted: string[] = [];+ const submit = vi.fn();+ const activate = vi.fn();+ const insert = vi.fn((text: string) => {+ inserted.push(text);+ return true;+ });+ unregister.push(registerVoiceTarget(id, { insert, submit, activate, ...overrides }));+ return { inserted, submit, activate, insert };+}++async function untilPhase(phase: string) {+ await vi.waitFor(() => expect(getVoiceState().phase).toBe(phase));+}++function key(type: "keydown" | "keyup", init: KeyboardEventInit) {+ window.dispatchEvent(new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }));+}++function shortcut() {+ key("keydown", { key: " ", altKey: true });+ key("keyup", { key: " ", altKey: true });+}++beforeEach(() => {+ clip.durationMs = 1500;+ clip.heardSpeech = true;+ recordings.started = 0;+ recordings.discarded = 0;+ useVoiceModelsStore.getState().setModels(INSTALLED);+ engine.prepare.mockReset();+ engine.transcribe.mockReset();+ engine.transcribe.mockResolvedValue({ ok: true, text: "hello world" });+ history.save.mockReset();+ history.save.mockResolvedValue("h1");+ history.update.mockReset();+ useVoiceSettingsStore.getState().update(DEFAULT_VOICE_SETTINGS);+ useShortcutStore.getState().setShortcut("voiceInput", createShortcutChord("Space", { alt: true }));+});++afterEach(() => {+ useShortcutStore.getState().resetShortcut("voiceInput");+ cancelVoice();+ unregister.splice(0).forEach((fn) => fn());+ vi.useRealTimers();+});++describe("voice session", () => {+ it("a tap opens the strip and a second tap inserts into that composer", async () => {+ const chat = target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ expect(getVoiceState()).toMatchObject({ targetId: "chat", mode: "strip" });+ expect(chat.activate).toHaveBeenCalled();+ expect(engine.prepare).toHaveBeenCalledWith(MODEL, { language: "auto", hotwords: [] });++ pressVoice("chat");+ await untilPhase("idle");+ expect(chat.inserted).toEqual(["hello world"]);+ expect(chat.submit).not.toHaveBeenCalled();+ });++ it("holding switches to the HUD and releasing inserts", async () => {+ vi.useFakeTimers();+ const chat = target("chat");+ pressVoice("chat");+ await vi.advanceTimersByTimeAsync(300);+ expect(getVoiceState()).toMatchObject({ phase: "recording", mode: "hud" });+ releaseVoice();+ vi.useRealTimers();+ await untilPhase("idle");+ expect(chat.inserted).toEqual(["hello world"]);+ });++ it("Enter during the strip inserts and sends; Escape cancels without transcribing", async () => {+ const chat = target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ key("keydown", { key: "Enter" });+ await untilPhase("idle");+ expect(chat.inserted).toEqual(["hello world"]);+ expect(chat.submit).toHaveBeenCalledTimes(1);++ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ key("keydown", { key: "Escape" });+ expect(getVoiceState().phase).toBe("idle");+ expect(engine.transcribe).toHaveBeenCalledTimes(1);+ });++ it("has no shortcut until the user assigns one", () => {+ useShortcutStore.getState().resetShortcut("voiceInput");+ target("chat");+ noteVoiceFocus("chat");+ shortcut();+ expect(getVoiceState().phase).toBe("idle");+ expect(recordings.started).toBe(0);+ });++ it("the shortcut dictates into the composer focused last", async () => {+ const chat = target("chat");+ const comment = target("comment");+ noteVoiceFocus("chat");+ shortcut();+ await untilPhase("recording");+ expect(getVoiceState().targetId).toBe("chat");+ key("keydown", { key: " ", altKey: true });+ await untilPhase("idle");+ expect(chat.inserted).toEqual(["hello world"]);+ expect(comment.inserted).toEqual([]);+ });++ it("the shortcut skips composers that are off screen", async () => {+ target("comment");+ target("chat", { isShown: () => false });+ noteVoiceFocus("chat");+ shortcut();+ await untilPhase("recording");+ expect(getVoiceState().targetId).toBe("comment");+ });++ it("the shortcut does nothing when every composer is off screen", () => {+ target("chat", { isShown: () => false });+ shortcut();+ expect(getVoiceState().phase).toBe("idle");+ expect(recordings.started).toBe(0);+ });++ it("does not transcribe silence", async () => {+ clip.heardSpeech = false;+ target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ pressVoice("chat");+ await untilPhase("error");+ expect(getVoiceState().error).toBe("no-speech");+ expect(engine.transcribe).not.toHaveBeenCalled();+ });++ it("keeps a failed clip and retries it without recording again", async () => {+ engine.transcribe.mockResolvedValueOnce({ ok: false, reason: "failed", error: "decoder crashed" });+ const chat = target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ pressVoice("chat");+ await untilPhase("error");+ expect(getVoiceState()).toMatchObject({ error: "transcription-failed", canRetry: true });++ retryVoice();+ await untilPhase("idle");+ expect(chat.inserted).toEqual(["hello world"]);+ expect(engine.transcribe).toHaveBeenCalledTimes(2);+ expect(recordings.started).toBe(1);+ });++ it("waits for a lazily mounted editor before inserting", async () => {+ let ready = false;+ const inserted: string[] = [];+ target("reply", {+ insert: (text) => {+ if (!ready) return false;+ inserted.push(text);+ return true;+ },+ });+ pressVoice("reply");+ releaseVoice();+ await untilPhase("recording");+ pressVoice("reply");+ setTimeout(() => {+ ready = true;+ }, 150);+ await untilPhase("idle");+ expect(inserted).toEqual(["hello world"]);+ });++ it("ignores another composer while one is recording, and cancels when its composer unmounts", async () => {+ target("chat");+ target("comment");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ pressVoice("comment");+ expect(getVoiceState()).toMatchObject({ targetId: "chat", phase: "recording" });++ unregister.shift()?.();+ expect(getVoiceState().phase).toBe("idle");+ expect(recordings.discarded).toBeGreaterThan(0);+ expect(engine.transcribe).not.toHaveBeenCalled();+ });++ it("drops a transcript still on its way when its composer unregisters", async () => {+ let resolve!: (value: unknown) => void;+ engine.transcribe.mockReturnValueOnce(new Promise((done) => (resolve = done)));+ const chat = target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ key("keydown", { key: "Enter" });+ await untilPhase("transcribing");++ unregister.shift()?.();+ const next = target("chat");+ resolve({ ok: true, text: "meant for the old conversation" });+ await Promise.resolve();+ await Promise.resolve();+ expect(getVoiceState().phase).toBe("idle");+ expect(chat.inserted).toEqual([]);+ expect(next.inserted).toEqual([]);+ expect(next.submit).not.toHaveBeenCalled();+ });++ it("opens setup instead of recording when no model is installed", async () => {+ useVoiceModelsStore.getState().setModels({ engineAvailable: true, models: [{ ...MODEL, status: "absent" }] });+ const chat = target("chat");+ pressVoice("chat");+ releaseVoice();+ expect(getVoiceState()).toMatchObject({ targetId: "chat", phase: "setup" });+ expect(recordings.started).toBe(0);+ expect(chat.activate).not.toHaveBeenCalled();++ pressVoice("chat");+ expect(getVoiceState().phase).toBe("setup");++ useVoiceModelsStore.getState().setModels(INSTALLED);+ toggleVoice("chat");+ await untilPhase("recording");+ expect(getVoiceState()).toMatchObject({ targetId: "chat", mode: "strip" });+ });++ it("returns to setup when the model was deleted mid-dictation", async () => {+ engine.transcribe.mockResolvedValueOnce({ ok: false, reason: "model-missing" });+ target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ pressVoice("chat");+ await untilPhase("setup");+ });++ it("spells vocabulary words the user's way and drops fillers", async () => {+ engine.transcribe.mockResolvedValueOnce({ ok: true, text: "um, assign it to lambda" });+ useVoiceSettingsStore.getState().update({ vocabulary: ["Lambda"] });+ const chat = target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ pressVoice("chat");+ await untilPhase("idle");+ expect(chat.inserted).toEqual(["assign it to Lambda"]);+ });++ it("offers vocabulary and workspace names to the model as hotwords", async () => {+ useVoiceSettingsStore.getState().update({ vocabulary: ["Multica"], language: "zh" });+ setVoiceContextWords(["Lambda", "multica", "Jiayuan"]);+ target("chat");+ pressVoice("chat");+ releaseVoice();+ await untilPhase("recording");+ pressVoice("chat");+ await untilPhase("idle");+ const options = { language: "zh", hotwords: ["Multica", "Lambda", "Jiayuan"] };+ expect(engine.prepare).toHaveBeenCalledWith(MODEL, options);+ expect(engine.transcribe).toHaveBeenCalledWith(expect.any(Blob), MODEL, options);+ setVoiceContextWords([]);+ });+});++describe("voice history", () => {+ async function dictate(id = "chat") {+ pressVoice(id);+ releaseVoice();+ await untilPhase("recording");+ pressVoice(id);+ }++ it("keeps the recording before transcribing, then its text as inserted", async () => {+ engine.transcribe.mockResolvedValueOnce({ ok: true, text: "呃,assign it to lambda" });+ useVoiceSettingsStore.getState().update({ vocabulary: ["Lambda"], keepHistory: "7d" });+ target("chat");+ await dictate();+ await untilPhase("idle");+ expect(history.save).toHaveBeenCalledWith(expect.objectContaining({ durationMs: 1500 }), 7);+ await vi.waitFor(() => expect(history.update).toHaveBeenCalledWith("h1", "done", "assign it to Lambda"));+ });++ it("marks a failed transcription failed, and a retry runs on the same entry", async () => {+ engine.transcribe.mockResolvedValueOnce({ ok: false, reason: "failed" });+ target("chat");+ await dictate();+ await untilPhase("error");+ await vi.waitFor(() => expect(history.update).toHaveBeenCalledWith("h1", "failed", undefined));+ retryVoice();+ await untilPhase("idle");+ expect(history.save).toHaveBeenCalledTimes(1);+ await vi.waitFor(() => expect(history.update).toHaveBeenLastCalledWith("h1", "done", "hello world"));+ });++ it("keeps a recording cancelled mid-transcription as interrupted", async () => {+ engine.transcribe.mockReturnValueOnce(new Promise(() => {}));+ target("chat");+ await dictate();+ await untilPhase("transcribing");+ await vi.waitFor(() => expect(history.save).toHaveBeenCalled());+ cancelVoice();+ await vi.waitFor(() => expect(history.update).toHaveBeenCalledWith("h1", "interrupted", undefined));+ });++ it("keeps nothing when history is off", async () => {+ useVoiceSettingsStore.getState().update({ keepHistory: "off" });+ target("chat");+ await dictate();+ await untilPhase("idle");+ expect(history.save).not.toHaveBeenCalled();+ });++ it("transcribes a kept recording again outside any composer", async () => {+ engine.transcribe.mockResolvedValueOnce({ ok: true, text: "嗯,再试一次" });+ await expect(transcribeVoiceClip(new Blob(["audio"]))).resolves.toBe("再试一次");+ engine.transcribe.mockResolvedValueOnce({ ok: false, reason: "failed" });+ await expect(transcribeVoiceClip(new Blob(["audio"]))).resolves.toBeNull();+ });+});diff --git a/packages/core/voice/session.ts b/packages/core/voice/session.tsnew file mode 100644index 0000000000..26616c2065--- /dev/null+++ b/packages/core/voice/session.ts@@ -0,0 +1,529 @@+"use client";++/**+ * The single voice-input session shared by every composer.+ *+ * Composers (chat, issue comment, reply) register as targets; one recording+ * exists at a time and its text goes to the composer it was started from. A+ * tap starts the inline strip and a second tap inserts; holding (button or+ * shortcut) shows the floating HUD and releasing inserts. Speech is+ * transcribed on this device; with no model installed, a press opens the+ * setup dialog instead of recording.+ *+ * Recording and transcription are platform work behind `VoiceRuntime`. The+ * app connects one (Desktop's on-device engine); without it nothing records.+ */+import { create } from "zustand";+import { getShortcut } from "../shortcuts/store";+import { shortcutMatchesEvent } from "../shortcuts/definitions";+import { activeVoiceModel, useVoiceModelsStore, type VoiceModel, type VoiceModels, type VoiceTranscription } from "./models";+import { voiceHistoryDays, type VoiceHistoryStatus } from "./history";+import { voiceHotwords } from "./hotwords";+import { useVoiceSettingsStore } from "./store";+import { applyVocabulary, removeSpokenFillers } from "./text";++export type VoiceRecorderFailure = "permission-denied" | "no-microphone" | "failed";++export class VoiceRecorderError extends Error {+ constructor(readonly failure: VoiceRecorderFailure) {+ super(failure);+ this.name = "VoiceRecorderError";+ }+}++export interface VoiceMeter {+ levels: number[];+ elapsedMs: number;+}++export interface VoiceClip {+ blob: Blob;+ durationMs: number;+ /** False when the clip is too short or never rose above background noise. */+ heardSpeech: boolean;+}++export interface VoiceRecorder {+ /** Resolves once audio is flowing; rejects with a VoiceRecorderError. */+ start: (deviceId: string | null) => Promise<void>;+ finish: () => Promise<VoiceClip>;+ discard: () => void;+}++export interface VoiceDecodeOptions {+ /** A VOICE_LANGUAGES value. */+ language: string;+ /** Names and terms to favour, for models that take them. */+ hotwords: string[];+}++export interface VoiceRuntime {+ /** `onLimit` fires when the recording hits its length cap. */+ record: (onMeter: (meter: VoiceMeter) => void, onLimit: () => void) => VoiceRecorder;+ /** Load the model while the user is still talking. */+ prepare: (model: VoiceModel, options: VoiceDecodeOptions) => void;+ transcribe: (clip: Blob, model: VoiceModel, options: VoiceDecodeOptions) => Promise<VoiceTranscription>;+ /** Report the model list now and whenever it changes. */+ watchModels: (onChange: (models: VoiceModels) => void) => void;+ /** Keep recordings on this device; absent where there is nowhere to keep them. */+ history?: VoiceHistoryRuntime;+}++export interface VoiceHistoryRuntime {+ /** Resolves to the entry id, or null when it could not be kept. */+ save: (clip: VoiceClip, keepDays: number | null) => Promise<string | null>;+ update: (id: string, status: VoiceHistoryStatus, text?: string) => void;+}++/** `setup`: no speech model is installed yet, so the setup dialog is open. */+export type VoicePhase = "idle" | "setup" | "requesting" | "recording" | "transcribing" | "error";+/** `pending` is a press in "auto" activation that is not yet a tap or a hold. */+export type VoiceMode = "pending" | "strip" | "hud";+export type VoiceErrorKind = VoiceRecorderFailure | "no-speech" | "unavailable" | "transcription-failed";++export interface VoiceState {+ targetId: string | null;+ phase: VoicePhase;+ mode: VoiceMode;+ error: VoiceErrorKind | null;+ /** The failed clip is still held and can be sent again. */+ canRetry: boolean;+}++export interface VoiceTarget {+ /** Insert the transcript; false while the editor is not mounted yet. */+ insert: (text: string) => boolean;+ /** Send the composer after inserting (Enter while dictating). */+ submit?: () => void;+ /** Mount a lazily-created editor so the transcript has somewhere to go. */+ activate?: () => void;+ /** False while the composer is mounted but off screen; the shortcut skips it. */+ isShown?: () => boolean;+}++/** A press shorter than this is a tap; longer is push-to-talk. */+const HOLD_MS = 250;+const INSERT_ATTEMPTS = 20;++const IDLE: VoiceState = {+ targetId: null,+ phase: "idle",+ mode: "strip",+ error: null,+ canRetry: false,+};+const EMPTY_METER: VoiceMeter = { levels: [], elapsedMs: 0 };++interface VoiceSessionState {+ session: VoiceState;+ /** Level history and elapsed time; changes ~20 times a second while recording. */+ meter: VoiceMeter;+}++export const useVoiceSessionStore = create<VoiceSessionState>()(() => ({+ session: IDLE,+ meter: EMPTY_METER,+}));++let runtime: VoiceRuntime | null = null;+let runtimeConnected = false;++const targets = new Map<string, VoiceTarget>();+let focusedId: string | null = null;++let session = 0;+let recording: VoiceRecorder | null = null;+let lastClip: Blob | null = null;+/** The history entry for `lastClip`, and whether its outcome is still open. */+let historyEntry: Promise<string | null> | null = null;+let historyOpen = false;+let sendAfterInsert = false;+let held = false;+let heldByKey = false;+let holdTimer: ReturnType<typeof setTimeout> | null = null;++/** Connect the platform's recorder and engine; later calls are no-ops. */+export function connectVoiceRuntime(factory: () => VoiceRuntime | null) {+ if (runtimeConnected) return;+ runtimeConnected = true;+ runtime = factory();+ runtime?.watchModels((models) => useVoiceModelsStore.getState().setModels(models));+}++function state(): VoiceState {+ return useVoiceSessionStore.getState().session;+}++function setState(patch: Partial<VoiceState>) {+ useVoiceSessionStore.setState((current) => ({ session: { ...current.session, ...patch } }));+}++function setMeter(meter: VoiceMeter) {+ useVoiceSessionStore.setState({ meter });+}++function isCapturing() {+ const { phase } = state();+ return phase === "requesting" || phase === "recording";+}++function decodeOptions(): VoiceDecodeOptions {+ const { language, vocabulary } = useVoiceSettingsStore.getState();+ return { language, hotwords: voiceHotwords(vocabulary) };+}++function keepInHistory(clip: VoiceClip) {+ const keepDays = voiceHistoryDays(useVoiceSettingsStore.getState().keepHistory);+ const history = runtime?.history;+ historyEntry = history && keepDays !== 0 ? history.save(clip, keepDays).catch(() => null) : null;+ historyOpen = historyEntry !== null;+}++function settleHistory(status: VoiceHistoryStatus, text?: string) {+ const entry = historyEntry;+ const history = runtime?.history;+ historyOpen = status === "transcribing";+ if (!entry || !history) return;+ void entry.then((id) => {+ if (id) history.update(id, status, text);+ });+}++/** The transcript as it is inserted: fillers dropped, vocabulary spelled. */+function cleanTranscript(text: string): string {+ const settings = useVoiceSettingsStore.getState();+ const spoken = settings.removeFillers ? removeSpokenFillers(text) : text;+ return applyVocabulary(spoken, settings.vocabulary).trim();+}++/**+ * Transcribe a kept recording again, outside any composer (history). Null+ * when there is no model or engine, or nothing was heard.+ */+export async function transcribeVoiceClip(clip: Blob): Promise<string | null> {+ const model = activeVoiceModel();+ if (!runtime || !model) return null;+ const result = await runtime.transcribe(clip, model, decodeOptions()).catch(() => null);+ if (!result?.ok) return null;+ return cleanTranscript(result.text) || null;+}++function clearHold() {+ held = false;+ heldByKey = false;+ if (holdTimer !== null) clearTimeout(holdTimer);+ holdTimer = null;+}++function begin(targetId: string, mode: VoiceMode) {+ const target = targets.get(targetId);+ if (!target || !runtime) return;+ const model = activeVoiceModel();+ if (!model) {+ openSetup(targetId);+ return;+ }+ target.activate?.();+ runtime.prepare(model, decodeOptions());+ const token = ++session;+ recording?.discard();+ lastClip = null;+ historyEntry = null;+ historyOpen = false;+ sendAfterInsert = false;+ const current = runtime.record(+ (next) => {+ if (token === session) setMeter(next);+ },+ () => {+ if (token === session) void finish(false);+ },+ );+ recording = current;+ setMeter(EMPTY_METER);+ setState({ targetId, phase: "requesting", mode, error: null, canRetry: false });+ current.start(useVoiceSettingsStore.getState().deviceId).then(+ () => {+ if (token === session) setState({ phase: "recording" });+ },+ (err: unknown) => {+ if (token !== session) return;+ recording = null;+ clearHold();+ fail(err instanceof VoiceRecorderError ? err.failure : "failed", false);+ },+ );+}++async function finish(send: boolean) {+ const current = recording;+ if (!current || !isCapturing()) return;+ if (state().phase === "requesting") {+ // Released while the permission prompt is still open: keep going as a+ // tap so the user can answer the prompt and then speak.+ if (state().mode !== "strip") setState({ mode: "strip" });+ return;+ }+ recording = null;+ clearHold();+ sendAfterInsert = send;+ const token = session;+ setState({ phase: "transcribing", mode: state().mode === "pending" ? "strip" : state().mode });+ const clip = await current.finish();+ if (token !== session) return;+ if (!clip.heardSpeech) {+ // An accidental tap of a hold-to-talk control is not worth an error.+ if (clip.durationMs < HOLD_MS) cancelVoice();+ else fail("no-speech", false);+ return;+ }+ lastClip = clip.blob;+ keepInHistory(clip);+ await transcribe(token);+}++async function transcribe(token: number) {+ const clip = lastClip;+ const model = activeVoiceModel();+ if (!clip || !runtime) return;+ const { targetId } = state();+ if (!model) {+ settleHistory("failed");+ if (targetId) openSetup(targetId);+ return;+ }+ const result = await runtime.transcribe(clip, model, decodeOptions()).catch(() => null);+ if (token !== session) return;+ if (!result?.ok) {+ settleHistory("failed");+ if (result?.reason === "model-missing" && targetId) openSetup(targetId);+ else if (result?.reason === "engine-unavailable") fail("unavailable", false);+ else fail("transcription-failed", true);+ return;+ }+ const cleaned = cleanTranscript(result.text);+ if (!cleaned) {+ settleHistory("failed");+ fail("no-speech", false);+ return;+ }+ // Kept before inserting: the text survives a composer that went away.+ settleHistory("done", cleaned);+ deliver(token, cleaned);+}++function deliver(token: number, text: string, attempt = 0) {+ if (token !== session) return;+ const { targetId } = state();+ const target = targetId ? targets.get(targetId) : undefined;+ if (!target) {+ // The composer went away (navigation) before the text arrived.+ cancelVoice();+ return;+ }+ if (!target.insert(text)) {+ // A lazily-mounted editor may still be coming up.+ if (attempt < INSERT_ATTEMPTS) {+ setTimeout(() => deliver(token, text, attempt + 1), 100);+ } else {+ fail("transcription-failed", true);+ }+ return;+ }+ const send = sendAfterInsert;+ lastClip = null;+ sendAfterInsert = false;+ setState(IDLE);+ if (send) target.submit?.();+}++function openSetup(targetId: string) {+ session++;+ recording?.discard();+ recording = null;+ clearHold();+ setMeter(EMPTY_METER);+ setState({ targetId, phase: "setup", mode: "strip", error: null, canRetry: false });+}++function fail(error: VoiceErrorKind, canRetry: boolean) {+ setMeter(EMPTY_METER);+ setState({ phase: "error", mode: "strip", error, canRetry: canRetry && lastClip !== null });+}++/** Abandon whatever is in flight, including a failed clip. */+export function cancelVoice() {+ // Cancelled while transcribing: the recording stays in history to retry.+ if (historyOpen) settleHistory("interrupted");+ historyEntry = null;+ historyOpen = false;+ session++;+ recording?.discard();+ recording = null;+ lastClip = null;+ sendAfterInsert = false;+ clearHold();+ setMeter(EMPTY_METER);+ setState(IDLE);+}++export function retryVoice() {+ const { phase, targetId, canRetry } = state();+ if (phase !== "error" || !targetId) return;+ if (canRetry && lastClip) {+ if (historyEntry) settleHistory("transcribing");+ const token = ++session;+ setState({ phase: "transcribing", error: null, canRetry: false });+ void transcribe(token);+ return;+ }+ begin(targetId, "strip");+}++/** Stop recording and insert (or insert and send). */+export function stopVoice(send = false) {+ void finish(send);+}++/** Mic button or shortcut pressed for `targetId`. */+export function pressVoice(targetId: string) {+ const current = state();+ if (current.phase === "setup") return;+ if (current.targetId !== null && current.targetId !== targetId && current.phase !== "error") return;+ if (isCapturing()) {+ // A second tap ends a tap-started recording.+ if (current.mode === "strip" && !held) void finish(false);+ return;+ }+ if (current.phase === "transcribing") return;+ const { activation } = useVoiceSettingsStore.getState();+ held = true;+ if (activation === "hold") {+ begin(targetId, "hud");+ return;+ }+ if (activation === "toggle") {+ begin(targetId, "strip");+ return;+ }+ begin(targetId, "pending");+ holdTimer = setTimeout(() => {+ holdTimer = null;+ if (held && isCapturing() && state().mode === "pending") setState({ mode: "hud" });+ }, HOLD_MS);+}++/** Mic button or shortcut released. */+export function releaseVoice() {+ if (!held) return;+ const wasHolding = state().mode === "hud";+ clearHold();+ if (!isCapturing()) return;+ if (wasHolding) void finish(false);+ else if (state().mode === "pending") setState({ mode: "strip" });+}++/** A press that cannot be held (keyboard activation, or starting from setup). */+export function toggleVoice(targetId: string) {+ const current = state();+ const free = current.phase === "error" || (current.phase === "setup" && current.targetId === targetId);+ if (current.targetId !== null && current.targetId !== targetId && !free) return;+ if (isCapturing()) {+ void finish(false);+ return;+ }+ if (current.phase === "transcribing") return;+ begin(targetId, "strip");+}++export function noteVoiceFocus(targetId: string) {+ focusedId = targetId;+}++function isShown(id: string): boolean {+ return targets.get(id)?.isShown?.() ?? true;+}++/** The composer focused last if it is on screen, else the newest one that is. */+function pickTarget(): string | null {+ if (focusedId && targets.has(focusedId) && isShown(focusedId)) return focusedId;+ return [...targets.keys()].reverse().find(isShown) ?? null;+}++function onKeyDown(event: KeyboardEvent) {+ const current = state();+ if (event.key === "Escape" && (isCapturing() || current.phase === "transcribing")) {+ event.preventDefault();+ event.stopPropagation();+ cancelVoice();+ return;+ }+ if (isCapturing() && !heldByKey) {+ if (+ event.key === "Enter" &&+ !event.shiftKey &&+ !event.isComposing &&+ current.mode === "strip" &&+ current.phase === "recording"+ ) {+ event.preventDefault();+ event.stopPropagation();+ void finish(Boolean(current.targetId && targets.get(current.targetId)?.submit));+ return;+ }+ }+ if (!shortcutMatchesEvent(getShortcut("voiceInput"), event)) return;+ event.preventDefault();+ event.stopPropagation();+ if (event.repeat) return;+ const targetId = isCapturing() ? current.targetId : pickTarget();+ if (!targetId) return;+ pressVoice(targetId);+ if (held) heldByKey = true;+}++function onKeyUp() {+ // Releasing either key of the chord ends a push-to-talk hold.+ if (heldByKey) releaseVoice();+}++function onWindowBlur() {+ if (held) releaseVoice();+}++/**+ * Register a composer; returns the unregister function. Unregistering the+ * composer that owns the session cancels it, so a transcript still on its+ * way is dropped rather than delivered.+ */+export function registerVoiceTarget(id: string, target: VoiceTarget): () => void {+ if (targets.size === 0) {+ window.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("keyup", onKeyUp, true);+ window.addEventListener("blur", onWindowBlur);+ }+ targets.set(id, target);+ return () => {+ if (targets.get(id) !== target) return;+ targets.delete(id);+ if (focusedId === id) focusedId = null;+ if (state().targetId === id) cancelVoice();+ if (targets.size === 0) {+ window.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("keyup", onKeyUp, true);+ window.removeEventListener("blur", onWindowBlur);+ }+ };+}++export function useVoiceState(): VoiceState {+ return useVoiceSessionStore((s) => s.session);+}++export function useVoiceMeter(): VoiceMeter {+ return useVoiceSessionStore((s) => s.meter);+}++export function getVoiceState(): VoiceState {+ return state();+}diff --git a/packages/core/voice/store.ts b/packages/core/voice/store.tsnew file mode 100644index 0000000000..2513e1bedf--- /dev/null+++ b/packages/core/voice/store.ts@@ -0,0 +1,126 @@+"use client";++import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";+import { defaultStorage } from "../platform/storage";+import { VOICE_HISTORY_RETENTIONS, type VoiceHistoryRetention } from "./history";++/**+ * How a press of the mic (or the voice shortcut) starts a recording.+ * - auto: a tap toggles dictation, holding talks until release+ * - toggle: every press toggles+ * - hold: record only while held+ */+export type VoiceActivation = "auto" | "toggle" | "hold";++/**+ * Languages a model can be told to expect, for models that take a hint;+ * "auto" lets the model detect.+ */+export const VOICE_LANGUAGES = ["auto", "zh", "en", "ja", "ko", "yue"] as const;+export type VoiceLanguage = (typeof VOICE_LANGUAGES)[number];++export const MAX_VOCABULARY_WORDS = 40;+export const MAX_VOCABULARY_WORD_LENGTH = 40;++export interface VoiceSettings {+ activation: VoiceActivation;+ language: VoiceLanguage;+ /** Input device id; null follows the system default. */+ deviceId: string | null;+ removeFillers: boolean;+ /** Words to spell the way the user writes them. */+ vocabulary: string[];+ /** The local speech model to use; null picks the first one installed. */+ modelId: string | null;+ /** How long recordings and transcripts stay on this device. */+ keepHistory: VoiceHistoryRetention;+}++export const DEFAULT_VOICE_SETTINGS: VoiceSettings = {+ activation: "auto",+ language: "auto",+ deviceId: null,+ removeFillers: true,+ vocabulary: [],+ modelId: null,+ keepHistory: "30d",+};++interface VoiceSettingsState extends VoiceSettings {+ update: (patch: Partial<VoiceSettings>) => void;+ addWord: (word: string) => void;+ removeWord: (word: string) => void;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++/** Keep what is valid from storage and fall back to defaults for the rest. */+export function sanitizeVoiceSettings(value: unknown): VoiceSettings {+ const raw = isRecord(value) ? value : {};+ const activation = ["auto", "toggle", "hold"].includes(raw.activation as string)+ ? (raw.activation as VoiceActivation)+ : DEFAULT_VOICE_SETTINGS.activation;+ const language = (VOICE_LANGUAGES as readonly string[]).includes(raw.language as string)+ ? (raw.language as VoiceLanguage)+ : DEFAULT_VOICE_SETTINGS.language;+ const deviceId = typeof raw.deviceId === "string" && raw.deviceId ? raw.deviceId : null;+ const removeFillers =+ typeof raw.removeFillers === "boolean" ? raw.removeFillers : DEFAULT_VOICE_SETTINGS.removeFillers;+ const vocabulary = Array.isArray(raw.vocabulary)+ ? normalizeVocabulary(raw.vocabulary.filter((w): w is string => typeof w === "string"))+ : [];+ const modelId = typeof raw.modelId === "string" && raw.modelId ? raw.modelId : null;+ const keepHistory = (VOICE_HISTORY_RETENTIONS as readonly string[]).includes(raw.keepHistory as string)+ ? (raw.keepHistory as VoiceHistoryRetention)+ : DEFAULT_VOICE_SETTINGS.keepHistory;+ return { activation, language, deviceId, removeFillers, vocabulary, modelId, keepHistory };+}++function normalizeVocabulary(words: readonly string[]): string[] {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const word of words) {+ const trimmed = word.trim().slice(0, MAX_VOCABULARY_WORD_LENGTH);+ const key = trimmed.toLowerCase();+ if (!trimmed || seen.has(key)) continue;+ seen.add(key);+ out.push(trimmed);+ if (out.length >= MAX_VOCABULARY_WORDS) break;+ }+ return out;+}++export const useVoiceSettingsStore = create<VoiceSettingsState>()(+ persist(+ (set) => ({+ ...DEFAULT_VOICE_SETTINGS,+ update: (patch) => set((state) => sanitizeVoiceSettings({ ...pickSettings(state), ...patch })),+ addWord: (word) =>+ set((state) => ({ vocabulary: normalizeVocabulary([...state.vocabulary, word]) })),+ removeWord: (word) =>+ set((state) => ({ vocabulary: state.vocabulary.filter((w) => w !== word) })),+ }),+ {+ name: "multica_voice_input",+ storage: createJSONStorage(() => defaultStorage),+ version: 1,+ partialize: (state): VoiceSettings => pickSettings(state),+ merge: (persisted, current): VoiceSettingsState => ({ ...current, ...sanitizeVoiceSettings(persisted) }),+ },+ ),+);++function pickSettings(state: VoiceSettings): VoiceSettings {+ return {+ activation: state.activation,+ language: state.language,+ deviceId: state.deviceId,+ removeFillers: state.removeFillers,+ vocabulary: state.vocabulary,+ modelId: state.modelId,+ keepHistory: state.keepHistory,+ };+}diff --git a/packages/core/voice/text.ts b/packages/core/voice/text.tsnew file mode 100644index 0000000000..8378e6265b--- /dev/null+++ b/packages/core/voice/text.ts@@ -0,0 +1,73 @@+const CJK = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uff00-\uffef]/;++const OPENING = /[([{“‘«¿¡]/;+const CLOSING = /[)\]}”’».,!?;:%…'"]/;++/**+ * The separator to put between two adjacent pieces of text when dictation+ * joins them (draft then transcript, or transcript then draft): a space+ * between two words of a spaced language, nothing where either side is CJK,+ * whitespace already separates them, or punctuation hugs the word.+ */+export function dictationSeparator(before: string, after: string): string {+ if (!before || !after) return "";+ const last = before[before.length - 1]!;+ const first = after[0]!;+ if (/\s/.test(last) || /\s/.test(first)) return "";+ if (CJK.test(last) || CJK.test(first)) return "";+ if (OPENING.test(last) || CLOSING.test(first)) return "";+ return " ";+}++// Hesitations that carry no meaning on their own. 额 is also part of words+// (金额, 额外), so it only goes when it stands alone between punctuation.+const SPOKEN_FILLERS = [+ /(^|[\s,.!?;:,。!?;:、])额+(?=[\s,.!?;:,。!?;:、]|$)[,、,]?\s*/gu,+ /(^|[\s,.!?;:])(?:u+m+|u+h+|e+r+m+|h+m+)(?=[\s,.!?;:]|$)[,]?\s*/giu,+];++// 呃 and 嗯 are hesitations wherever they land, glued to the words around them+// too ("就是呃,", "那个呃标识"), with the pause the model wrote after them.+// 呃逆 and 嗯哼 are words.+const GLUED_FILLER = /(?:呃(?!逆)|嗯(?!哼))+(?:[,、,]\s*|\s+)?/gu;+const BREAK = /[\s\p{P}]/u;++/** Remove hesitation words ("um", "uh", "嗯", "呃") from a transcript. */+export function removeSpokenFillers(text: string): string {+ let out = text.replace(GLUED_FILLER, (match, offset: number, whole: string) => {+ const before = whole[offset - 1];+ const after = whole[offset + match.length];+ if (!before || !after || BREAK.test(before) || BREAK.test(after)) return "";+ // Words on both sides: keep them apart, except between two CJK characters.+ return CJK.test(before) && CJK.test(after) ? "" : " ";+ });+ for (const filler of SPOKEN_FILLERS) out = out.replace(filler, "$1");+ return out+ .replace(/\s{2,}/g, " ")+ .replace(/^[\s,,、]+/, "")+ .trim();+}++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++/**+ * Spell vocabulary words the way the user wrote them: "multica" becomes+ * "Multica", and a CamelCase word also matches its spoken split, so "git hub"+ * becomes "GitHub". Only whole words are replaced.+ */+export function applyVocabulary(text: string, words: readonly string[]): string {+ let out = text;+ for (const word of words) {+ const trimmed = word.trim();+ if (!/\p{L}/u.test(trimmed) || trimmed.toLowerCase() === trimmed.toUpperCase()) continue;+ const parts = trimmed+ .split(/\s+|(?<=\p{Ll})(?=\p{Lu})/u)+ .filter(Boolean)+ .map(escapeRegExp);+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}])${parts.join("[\\s-]?")}(?![\\p{L}\\p{N}])`, "giu");+ out = out.replace(pattern, trimmed);+ }+ return out;+}diff --git a/packages/core/voice/voice.test.ts b/packages/core/voice/voice.test.tsnew file mode 100644index 0000000000..ea86731930--- /dev/null+++ b/packages/core/voice/voice.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_VOICE_SETTINGS,+ MAX_VOCABULARY_WORDS,+ applyVocabulary,+ dictationSeparator,+ removeSpokenFillers,+ sanitizeVoiceSettings,+} from ".";++describe("dictationSeparator", () => {+ it.each([+ ["", "hello", ""],+ ["Fix the", "badge", " "],+ ["Fix the ", "badge", ""],+ ["切换工作区以后", "角标不更新", ""],+ ["Design 工作区", "badge", ""],+ ["the badge", "不更新", ""],+ ["line\n", "next", ""],+ ["brave", "world", " "],+ ["brave", ", then", ""],+ ["brave", "'s", ""],+ ["see (", "docs", ""],+ ["缓存", "first", ""],+ ])("between %j and %j", (before, text, sep) => {+ expect(dictationSeparator(before, text)).toBe(sep);+ });+});++describe("removeSpokenFillers", () => {+ it.each([+ ["嗯,我刚在 Design 工作区复现了", "我刚在 Design 工作区复现了"],+ ["我觉得,呃,应该是缓存", "我觉得,应该是缓存"],+ ["Um, I think uh it's the cache", "I think it's the cache"],+ ["the umbrella and the hmm", "the umbrella and the"],+ ["Uhh the drum", "the drum"],+ // Glued to the words around them, as the model writes them mid-sentence.+ ["还有一个场景,就是呃,annotation的功能", "还有一个场景,就是 annotation的功能"],+ ["转写的那个呃标识会和呃 reply 左下角的", "转写的那个标识会和 reply 左下角的"],+ ["will work 的那个呃呃,就是重叠在一起。", "will work 的那个就是重叠在一起。"],+ ["我嗯觉得可以", "我觉得可以"],+ ["那个呃。", "那个。"],+ ])("%j", (input, output) => {+ expect(removeSpokenFillers(input)).toBe(output);+ });++ it("leaves meaningful words alone", () => {+ expect(removeSpokenFillers("嗯哼是一个词 human umami")).toBe("嗯哼是一个词 human umami");+ expect(removeSpokenFillers("金额,额外的额度和呃逆")).toBe("金额,额外的额度和呃逆");+ });+});++describe("applyVocabulary", () => {+ it.each([+ ["assign it to lambda in multica", "assign it to Lambda in Multica"],+ ["open the git hub link", "open the GitHub link"],+ ["Git-Hub and github", "GitHub and GitHub"],+ ["lambdas and multicast stay", "lambdas and multicast stay"],+ ["交给 lambda 处理", "交给 Lambda 处理"],+ ])("%j", (input, output) => {+ expect(applyVocabulary(input, [" Multica ", "", "Lambda", "GitHub", "工作区"])).toBe(output);+ });+});++describe("sanitizeVoiceSettings", () => {+ it("falls back to defaults for junk", () => {+ expect(sanitizeVoiceSettings(null)).toEqual(DEFAULT_VOICE_SETTINGS);+ expect(+ sanitizeVoiceSettings({ activation: "shout", language: "xx", deviceId: 3, removeFillers: "yes" }),+ ).toEqual(DEFAULT_VOICE_SETTINGS);+ });++ it("keeps valid values and dedupes the vocabulary", () => {+ const words = Array.from({ length: MAX_VOCABULARY_WORDS + 5 }, (_, i) => `w${i}`);+ const settings = sanitizeVoiceSettings({+ activation: "hold",+ language: "zh",+ deviceId: "mic-1",+ removeFillers: false,+ vocabulary: ["Multica", "multica", " ", 7, ...words],+ modelId: "sensevoice-small",+ });+ expect(settings.activation).toBe("hold");+ expect(settings.language).toBe("zh");+ expect(settings.deviceId).toBe("mic-1");+ expect(settings.removeFillers).toBe(false);+ expect(settings.vocabulary[0]).toBe("Multica");+ expect(settings.vocabulary).toHaveLength(MAX_VOCABULARY_WORDS);+ expect(settings.modelId).toBe("sensevoice-small");+ });+});diff --git a/packages/ui/components/common/file-upload-button.tsx b/packages/ui/components/common/file-upload-button.tsxindex d36d5daf77..63dd1a1d8b 100644--- a/packages/ui/components/common/file-upload-button.tsx+++ b/packages/ui/components/common/file-upload-button.tsx@@ -35,7 +35,7 @@ function FileUploadButton({// `size-*`, not `h-* w-*`: the icon button's own `[&_svg:not([class*='size-'])]`// rule would otherwise override it (icon-xs forces 12px).- const iconSize = size === "sm" ? "size-3.5" : "size-4.5";+ const iconSize = size === "sm" ? "size-3.5" : "size-4";const buttonSize = size === "sm" ? "icon-xs" : "icon-sm";return (diff --git a/packages/ui/components/common/shimmer-text.tsx b/packages/ui/components/common/shimmer-text.tsxindex 53b4861f4d..e3a4d1b276 100644--- a/packages/ui/components/common/shimmer-text.tsx+++ b/packages/ui/components/common/shimmer-text.tsx@@ -6,7 +6,10 @@ interface ShimmerTextProps extends Omit<ComponentProps<"span">, "children"> {active?: boolean;}-/** A single-line activity label. Only the decorative highlight moves. */+/**+ * A single-line activity label. Only the decorative highlight moves. Space it+ * with margin, never padding: the highlight copy is laid from the padding edge.+ */export function ShimmerText({children,active = true,diff --git a/packages/ui/components/common/submit-button.tsx b/packages/ui/components/common/submit-button.tsxindex 9fb2bd8690..4dbc4a962b 100644--- a/packages/ui/components/common/submit-button.tsx+++ b/packages/ui/components/common/submit-button.tsx@@ -44,6 +44,8 @@ interface SubmitButtonProps {stopTooltip?: ReactNode;/** Accessible name for the icon-only stop button. */stopAriaLabel?: string;+ /** Applied to the send button, after its own classes. */+ className?: string;}/** Keep the composer focused so Send and Stop do not dismiss Android's keyboard. */@@ -63,6 +65,7 @@ function SubmitButton({ariaLabel,stopTooltip,stopAriaLabel,+ className,}: SubmitButtonProps) {if (running) {const stopButton = (@@ -95,6 +98,7 @@ function SubmitButton({// eslint-disable-next-line no-restricted-syntax -- composer send button, the one round button"rounded-full",showReason && "aria-disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:active:translate-y-0",+ className,)}disabled={isDisabled}focusableWhenDisabled={showReason}diff --git a/packages/ui/icons/drawings/drawings.mjs b/packages/ui/icons/drawings/drawings.mjsindex 5819e76997..745666e6e2 100644--- a/packages/ui/icons/drawings/drawings.mjs+++ b/packages/ui/icons/drawings/drawings.mjs@@ -76,6 +76,8 @@ export const DRAWINGS = {<path d="M14.5 3.25h6.25V9.5M20.75 3.25 12.5 11.5"/>`,Bell: `<path class="b" d="M5 17.25h14l-1.35-1.95a3 3 0 0 1-.55-1.73V10a5.1 5.1 0 0 0-10.2 0v3.57c0 .62-.19 1.22-.55 1.73Z"/><path d="M9.5 20.25c.55.95 1.5 1.5 2.5 1.5s1.95-.55 2.5-1.5"/>`,+ Mic: `<path class="b" d="M8.25 6.5a3.75 3.75 0 0 1 7.5 0v4.25a3.75 3.75 0 0 1-7.5 0Z"/>+ <path d="M5 11a7 7 0 0 0 14 0M12 18v3.25"/>`,Filter: `<path d="M3.75 6.5h16.5M7 12h10M10.25 17.5h3.5"/>`,Pin: `<path class="b" d="${shape([[9.25, 3, 1], [14.75, 3, 1], [14.75, 8.25, 1], [18, 12.75, 1.5], [6, 12.75, 1.5], [9.25, 8.25, 1]])}"/><path d="M12 12.75v8.5M8 3h8"/>`,@@ -427,6 +429,7 @@ Object.assign(DRAWINGS, {GitPullRequestClosed: `<circle cx="6.25" cy="6" r="2.75"/><circle cx="17.75" cy="18" r="2.75"/><path d="M6.25 8.75v12.5M17.75 15.25V11M15.5 3.5 20 8M20 3.5 15.5 8"/>`,GitPullRequestDraft: `<circle cx="6.25" cy="6" r="2.75"/><circle cx="17.75" cy="18" r="2.75"/><path d="M6.25 8.75v12.5"/>${dot(17.75, 6, 1.3)}${dot(17.75, 11, 1.3)}`,BotOff: `${DRAWINGS.Bot}<path d="m2.5 2.5 19 19"/>`,+ MicOff: `${DRAWINGS.Mic}<path d="m3 3 18 18"/>`,PencilLine: `${DRAWINGS.Pencil}<path d="M13 20.25h7.5"/>`,// Command palettediff --git a/packages/ui/icons/glyphs.ts b/packages/ui/icons/glyphs.tsindex c504729db3..0a6c424224 100644--- a/packages/ui/icons/glyphs.ts+++ b/packages/ui/icons/glyphs.ts@@ -177,6 +177,8 @@ export const MessageCircleQuestion: IconNode = [["path",{"d":"M12 21a9 9 0 1 0-7export const MessageSquare: IconNode = [["path",{"d":"M2.75 9 C2.75 6.25 2.75 5.11 3.55 4.3 C4.36 3.5 5.5 3.5 8.25 3.5 L14.25 3.5 C17.75 3.5 19.2 3.5 20.23 4.52 C21.25 5.55 21.25 7 21.25 10.5 L21.25 11.5 C21.25 14.5 21.25 15.74 20.37 16.62 C19.49 17.5 18.25 17.5 15.25 17.5 L11 17.5 C10 17.5 9.59 17.5 9.05 17.66 C8.51 17.83 8.17 18.05 7.34 18.61 L4.58 20.45 C4.17 20.72 3.99 20.84 3.85 20.77 C3.71 20.71 3.67 20.51 3.6 20.01 L3.05 16.48 C2.9 15.49 2.84 15.08 2.79 14.5 C2.75 13.91 2.75 13.5 2.75 12.5 Z","className":"icon-body"}],["path",{"d":"M8 9.5h8M8 13h4.5","className":"icon-cut"}]];export const MessageSquarePlus: IconNode = [["path",{"d":"M2.75 9 C2.75 6.25 2.75 5.11 3.55 4.3 C4.36 3.5 5.5 3.5 8.25 3.5 L14.25 3.5 C17.75 3.5 19.2 3.5 20.23 4.52 C21.25 5.55 21.25 7 21.25 10.5 L21.25 11.5 C21.25 14.5 21.25 15.74 20.37 16.62 C19.49 17.5 18.25 17.5 15.25 17.5 L11 17.5 C10 17.5 9.59 17.5 9.05 17.66 C8.51 17.83 8.17 18.05 7.34 18.61 L4.58 20.45 C4.17 20.72 3.99 20.84 3.85 20.77 C3.71 20.71 3.67 20.51 3.6 20.01 L3.05 16.48 C2.9 15.49 2.84 15.08 2.79 14.5 C2.75 13.91 2.75 13.5 2.75 12.5 Z","className":"icon-body"}],["path",{"d":"M12 7.5v6M9 10.5h6"}]];export const MessagesSquare: IconNode = [["path",{"d":"M8.75 8.75 L8.75 5.88 C8.75 4.44 8.75 3.84 9.17 3.42 C9.59 3 10.19 3 11.63 3 L17.25 3 C19.25 3 20.08 3 20.67 3.58 C21.25 4.17 21.25 5 21.25 7 L21.25 14 C21.25 14.5 21.25 14.71 21.14 14.76 C21.03 14.81 20.87 14.68 20.49 14.35 L18.76 12.9 C18.38 12.57 18.22 12.44 17.97 12.34 C17.71 12.25 17.5 12.25 17 12.25 L15.25 12.25"}],["path",{"d":"M2.75 13 C2.75 11 2.75 10.17 3.33 9.58 C3.92 9 4.75 9 6.75 9 L11.25 9 C13.25 9 14.08 9 14.67 9.58 C15.25 10.17 15.25 11 15.25 13 L15.25 13.5 C15.25 15.5 15.25 16.33 14.67 16.92 C14.08 17.5 13.25 17.5 11.25 17.5 L8.25 17.5 C7.75 17.5 7.54 17.5 7.28 17.59 C7.02 17.68 6.86 17.81 6.46 18.11 L3.54 20.39 C3.14 20.69 2.98 20.82 2.87 20.76 C2.75 20.71 2.75 20.5 2.75 20 Z","className":"icon-body"}]];+export const Mic: IconNode = [["path",{"d":"M8.25 6.5a3.75 3.75 0 0 1 7.5 0v4.25a3.75 3.75 0 0 1-7.5 0Z","className":"icon-body"}],["path",{"d":"M5 11a7 7 0 0 0 14 0M12 18v3.25"}]];+export const MicOff: IconNode = [["path",{"d":"M8.25 6.5a3.75 3.75 0 0 1 7.5 0v4.25a3.75 3.75 0 0 1-7.5 0Z","className":"icon-body"}],["path",{"d":"M5 11a7 7 0 0 0 14 0M12 18v3.25"}],["path",{"d":"m3 3 18 18"}]];export const Milestone: IconNode = [["path",{"d":"M3.25 8 C3.25 7 3.25 6.59 3.54 6.29 C3.84 6 4.25 6 5.25 6 L14.5 6 C15.5 6 15.91 6 16.43 6.19 C16.95 6.37 17.27 6.64 18.04 7.27 L19.59 8.55 C20.17 9.02 20.41 9.22 20.41 9.5 C20.41 9.78 20.17 9.98 19.59 10.45 L18.04 11.73 C17.27 12.36 16.95 12.63 16.43 12.81 C15.91 13 15.5 13 14.5 13 L5.25 13 C4.25 13 3.84 13 3.54 12.71 C3.25 12.41 3.25 12 3.25 11 Z","className":"icon-body"}],["path",{"d":"M12 2.75V6M12 13v8.25"}]];export const Minimize2: IconNode = [["path",{"d":"M4 14 L10 14 C10 14 10 14 10 14 C10 14 10 14 10 14 L10 20"}],["path",{"d":"M20 10 L14 10 C14 10 14 10 14 10 C14 10 14 10 14 10 L14 4"}],["path",{"d":"m10 14-6.5 6.5M14 10l6.5-6.5"}]];export const Minus: IconNode = [["path",{"d":"M4.5 12h15"}]];diff --git a/packages/ui/icons/index.ts b/packages/ui/icons/index.tsindex e12e9de7df..e6f7e870ad 100644--- a/packages/ui/icons/index.ts+++ b/packages/ui/icons/index.ts@@ -203,6 +203,8 @@ export const MessageSquare = /* @__PURE__ */ createIcon("MessageSquare", glyph.Mexport const MessageSquarePlus = /* @__PURE__ */ createIcon("MessageSquarePlus", glyph.MessageSquarePlus);export const MessageSquareText = /* @__PURE__ */ createIcon("MessageSquareText", glyph.MessageSquare);export const MessagesSquare = /* @__PURE__ */ createIcon("MessagesSquare", glyph.MessagesSquare);+export const Mic = /* @__PURE__ */ createIcon("Mic", glyph.Mic);+export const MicOff = /* @__PURE__ */ createIcon("MicOff", glyph.MicOff);export const Milestone = /* @__PURE__ */ createIcon("Milestone", glyph.Milestone);export const Minimize2 = /* @__PURE__ */ createIcon("Minimize2", glyph.Minimize2);export const Minus = /* @__PURE__ */ createIcon("Minus", glyph.Minus);diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 441362d401..14cadd7b3e 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -15,6 +15,18 @@ import enIssues from "../../locales/en/issues.json";// link/markdownLink fields are ignored by the engine, which re-derives them).const mockApiUploadFile = vi.hoisted(() => vi.fn());const mockToastInfo = vi.hoisted(() => vi.fn());+const voiceOptions = vi.hoisted(() => ({ last: null as { scope?: string; hidden?: boolean } | null }));++vi.mock("../../voice/use-composer-voice", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../../voice/use-composer-voice")>();+ return {+ ...actual,+ useComposerVoice: (options: Parameters<typeof actual.useComposerVoice>[0]) => {+ voiceOptions.last = options;+ return actual.useComposerVoice(options);+ },+ };+});vi.mock("sonner", () => ({toast: Object.assign(vi.fn(), { info: mockToastInfo, error: vi.fn(), success: vi.fn() }),}));@@ -538,6 +550,43 @@ describe("ChatInput new-chat draft identity", () => {});});+// The editor is shared across sessions and agents, so voice input is scoped to+// what the composer is writing to: changing it cancels dictation in flight.+describe("ChatInput voice scope", () => {+ const state = () =>+ useChatStore.getState() as unknown as { activeSessionId: string | null; selectedAgentId: string };++ it("changes when the conversation or the agent changes", () => {+ state().activeSessionId = "session-a";+ const { rerender } = render(element({}));+ expect(voiceOptions.last?.scope).toBe("session-a:agent-1");++ state().activeSessionId = "session-b";+ rerender(element({}));+ expect(voiceOptions.last?.scope).toBe("session-b:agent-1");++ state().activeSessionId = null;+ rerender(element({}));+ expect(voiceOptions.last?.scope).toBe("__draft_new__:agent-1");++ state().selectedAgentId = "agent-2";+ rerender(element({}));+ expect(voiceOptions.last?.scope).toBe("__draft_new__:agent-2");+ });++ it("uses an embedded surface's own draft key", () => {+ render(element({ draftKeyOverride: "builder:agent-9" }));+ expect(voiceOptions.last?.scope).toBe("builder:agent-9");+ });++ it("passes hidden through so a closed window stops listening", () => {+ const { rerender } = render(element({}));+ expect(voiceOptions.last?.hidden).toBe(false);+ rerender(element({ hidden: true }));+ expect(voiceOptions.last?.hidden).toBe(true);+ });+});+describe("ChatInput focusRequest", () => {it("focuses the editor when focusRequest becomes a non-zero value (new chat)", () => {const { rerender } = render(diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 7c794672c8..2cc7098b92 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -33,6 +33,14 @@ import type { Attachment, Project } from "@multica/core/types";import { ProjectPicker } from "../../projects/components/project-picker";import { ClearablePillButton } from "../../common/pill-button";import { useT } from "../../i18n";+import {+ useComposerVoice,+ VoiceErrorRow,+ VoiceHud,+ VoiceMicButton,+ VoiceSetupDialog,+ VoiceStrip,+} from "../../voice";import { useCommentDraftStore } from "@multica/core/issues/stores";import { composeAnnotatedReply, EMPTY_REPLY_ANNOTATIONS, hasReplyIntent } from "@multica/core/drafts/reply-annotation";import { ReplyAnnotations } from "../../issues/components/reply-annotations";@@ -155,6 +163,8 @@ interface ChatInputProps {*/draftKeyOverride?: string;editorKeyOverride?: string;+ /** Mounted but not shown (the closed floating window): voice input is off. */+ hidden?: boolean;/** Saved quotes from this session's replies, sent ahead of the typed text. */annotations?: Pick<ChatAnnotations, "draftKey" | "composer" | "editAnnotation">;}@@ -191,6 +201,7 @@ export function ChatInput({focusRequest,draftKeyOverride,editorKeyOverride,+ hidden = false,annotations: annotationSlot,}: ChatInputProps) {const { t } = useT("chat");@@ -200,6 +211,7 @@ export function ChatInput({const editorAreaRef = useRef<HTMLDivElement>(null);const composerRef = useRef<HTMLDivElement>(null);const activeSessionId = useChatStore((s) => s.activeSessionId);+ const selectedAgentId = useChatStore((s) => s.selectedAgentId);// Two keys with deliberately different concerns://// `draftKey` — zustand storage key. Scopes the in-progress draft per session@@ -695,6 +707,15 @@ export function ChatInput({!isProjectUpdating;const selectedProject = projects.find((project) => project.id === projectId);const canSubmitNow = !disabled && !noAgent && (!isRunning || !!allowSubmitWhileRunning);+ const voice = useComposerVoice({+ insert: (text) => editorRef.current?.insertText(text) ?? false,+ submit: canSubmitNow ? () => void submit() : undefined,+ // The editor is shared across sessions and agents; a switch must not+ // carry a transcript (or its send) over to the new conversation.+ scope: draftKeyOverride ?? `${draftKey}:${selectedAgentId ?? ""}`,+ hidden,+ disabled: !!disabled || !!noAgent,+ });return (<>@@ -747,6 +768,8 @@ export function ChatInput({noAgent && "pointer-events-none opacity-60",)}aria-disabled={noAgent || undefined}+ ref={voice.rootRef}+ onFocusCapture={voice.onFocusCapture}onKeyDown={(event) => {// Tab is the editor's when it wants it (list indent, the @ and /// pickers): those handle the key first and prevent its default.@@ -853,7 +876,15 @@ export function ChatInput({showBubbleMenu/></div>- {(uploadEnabled || projectSelectionEnabled || leftAdornment) && (+ <VoiceHud voice={voice} />+ <VoiceSetupDialog voice={voice} />+ <VoiceErrorRow voice={voice} className="mx-2 mb-1" />+ {voice.showStrip && (+ <div className="absolute inset-x-1.5 bottom-1 flex items-center">+ <VoiceStrip voice={voice} />+ </div>+ )}+ {!voice.showStrip && (uploadEnabled || projectSelectionEnabled || leftAdornment) && (<div className="absolute bottom-1.5 left-1.5 flex items-center gap-1">{(uploadEnabled || projectSelectionEnabled) && (<ChatAddMenu@@ -869,7 +900,8 @@ export function ChatInput({{leftAdornment}</div>)}- <div className="absolute bottom-1 right-1.5 flex items-center gap-1">+ <div className={cn("absolute bottom-1 right-1.5 flex items-center gap-1", voice.showStrip && "hidden")}>+ <VoiceMicButton voice={voice} />{pageContext && (<IconButtontype="button"diff --git a/packages/views/chat/components/chat-window.test.tsx b/packages/views/chat/components/chat-window.test.tsxindex d92f0ae698..7d11e70cf1 100644--- a/packages/views/chat/components/chat-window.test.tsx+++ b/packages/views/chat/components/chat-window.test.tsx@@ -61,7 +61,13 @@ vi.mock("./use-chat-resize", () => ({vi.mock("./use-chat-context-items", () => ({ useChatContextItems: () => [] }));vi.mock("./chat-window-messages", () => ({ ChatWindowMessages: () => null }));vi.mock("../../common/app-requests", () => ({ ChatAppRequests: () => null }));-vi.mock("./chat-input", () => ({ ChatInput: () => null }));+const chatInputProps = vi.hoisted(() => ({ last: null as { hidden?: boolean } | null }));+vi.mock("./chat-input", () => ({+ ChatInput: (props: { hidden?: boolean }) => {+ chatInputProps.last = props;+ return null;+ },+}));vi.mock("./chat-queue", () => ({ ChatQueue: () => null }));vi.mock("./chat-empty-state", () => ({ EmptyState: () => null }));vi.mock("./session-history-list", () => ({ SessionHistoryList: () => null }));@@ -166,4 +172,13 @@ describe("ChatWindow minimize and close", () => {expect(state.chatBarKept).toEqual([]);expect(state.chatBarDismissed).toEqual({ [session.id]: session.updated_at });});++ it("turns off voice input in the composer while the window is closed", () => {+ renderWindow();+ expect(chatInputProps.last?.hidden).toBe(false);++ fireEvent.click(screen.getByRole("button", { name: enChat.window.minimize_tooltip }));++ expect(chatInputProps.last?.hidden).toBe(true);+ });});diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex 70771628ed..495ea0fe9c 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -413,6 +413,7 @@ export function ChatWindow() {* agent has been archived (read-only); locked out entirely when there's* no agent (the EmptyState above carries the CTA). */}<ChatInput+ hidden={!isOpen}onSend={c.handleSend}restoreDraftRequest={c.restoreDraftRequest}conversationStarterRequest={c.conversationStarterRequest}diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 3667881796..43e98e9caf 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -70,6 +70,7 @@ import { resolveClickIntent, useAppOrigin } from "../navigation";import { openLink, isMentionHref } from "./utils/link-handler";import { EditorBubbleMenu } from "./bubble-menu";import { posFromAnchor, type TextAnchor } from "./text-anchor";+import { insertDictation } from "./utils/insert-dictation";import { useLinkHover, LinkHoverCard } from "./link-hover-card";import { AttachmentDownloadProvider } from "./attachment-download-context";import "katex/dist/katex.min.css";@@ -303,6 +304,15 @@ interface ContentEditorRef {* losing the fragment.*/insertMarkdownAtEnd: (markdown: string) => boolean;+ /**+ * Insert plain text where the user would type next — the caret, or the end+ * of the document when the editor has not been focused since it mounted —+ * with a space before it when two words of a spaced language would touch.+ * Fires the normal `onUpdate` pipeline. For voice input, whose text arrives+ * after focus has moved to the mic button. Returns false while the Tiptap+ * instance is not up.+ */+ insertText: (text: string) => boolean;/*** Draw a placeholder for an upload this document is not showing yet, and* report whether it landed.@@ -569,6 +579,9 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(// auto-focusing a brand-new conversation) would hit a null editor and no-op.// Latch the intent here and honor it in `onCreate` once the editor exists.const focusOnReadyRef = useRef(false);+ // Whether the user has placed a caret in this instance; until then the+ // selection is the parser's default at the start of the document.+ const caretPlacedRef = useRef(false);// Large markdown is parsed in chunks to dodge marked's O(n²) tokenizer (see// parseMarkdownChunked). Small docs stay on the single-parse fast path.const mountChunked = initialContent.length > MARKDOWN_CHUNK_THRESHOLD;@@ -653,6 +666,9 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(onUpdateRef.current?.(md, base);}, debounceMs);},+ onFocus: () => {+ caretPlacedRef.current = true;+ },onBlur: () => {onBlurRef.current?.();},@@ -982,6 +998,11 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(});return true;},+ insertText: (text: string) => {+ if (!editor || editor.isDestroyed) return false;+ insertDictation(editor, text, caretPlacedRef.current);+ return true;+ },flushPendingUpdate: () => {// No armed timer = nothing typed since the last emit. The editor is// already clean, so the host has nothing to re-route.diff --git a/packages/views/editor/utils/insert-dictation.test.ts b/packages/views/editor/utils/insert-dictation.test.tsnew file mode 100644index 0000000000..23c5d304b6--- /dev/null+++ b/packages/views/editor/utils/insert-dictation.test.ts@@ -0,0 +1,95 @@+import { afterEach, describe, expect, it } from "vitest";+import { Editor } from "@tiptap/core";+import { createEditorExtensions } from "../extensions";+import { insertDictation } from "./insert-dictation";++let editor: Editor | undefined;++function makeEditor(content?: string): Editor {+ const el = document.createElement("div");+ document.body.appendChild(el);+ editor = new Editor({+ element: el,+ extensions: createEditorExtensions({}),+ content,+ contentType: content ? "markdown" : undefined,+ });+ return editor;+}++function markdown(ed: Editor): string {+ return ed.getMarkdown().trim();+}++afterEach(() => {+ editor?.destroy();+ editor = undefined;+ document.body.innerHTML = "";+});++describe("insertDictation", () => {+ it("fills an empty editor", () => {+ const ed = makeEditor();+ insertDictation(ed, "Ship the fix today", false);+ expect(markdown(ed)).toBe("Ship the fix today");+ });++ it("appends to the last paragraph with a space when the caret was never placed", () => {+ const ed = makeEditor("First line\n\nSecond line");+ insertDictation(ed, "and more", false);+ expect(markdown(ed)).toBe("First line\n\nSecond line and more");+ insertDictation(ed, "then done", false);+ expect(markdown(ed)).toBe("First line\n\nSecond line and more then done");+ });++ it("does not put a space between Chinese characters", () => {+ const ed = makeEditor("今天");+ insertDictation(ed, "发布修复", false);+ expect(markdown(ed)).toBe("今天发布修复");+ });++ it("inserts at the caret and replaces a selection", () => {+ const ed = makeEditor("Hello world");+ // "Hello |world": position 1 is the paragraph start.+ ed.commands.setTextSelection({ from: 7, to: 12 });+ insertDictation(ed, "there", true);+ expect(markdown(ed)).toBe("Hello there");+ });++ it("keeps the following word separate mid-sentence and leaves the caret after the dictation", () => {+ const ed = makeEditor("Hello world");+ ed.commands.setTextSelection(7);+ insertDictation(ed, "brave", true);+ expect(markdown(ed)).toBe("Hello brave world");+ insertDictation(ed, "new", true);+ expect(markdown(ed)).toBe("Hello brave new world");+ });++ it("does not add a space before the punctuation that follows", () => {+ const ed = makeEditor("Hello, world");+ ed.commands.setTextSelection(6);+ insertDictation(ed, "there", true);+ expect(markdown(ed)).toBe("Hello there, world");+ });++ it("does not add spaces inside Chinese text", () => {+ const ed = makeEditor("今天发布");+ ed.commands.setTextSelection(3);+ insertDictation(ed, "我们", true);+ expect(markdown(ed)).toBe("今天我们发布");+ });++ it("collapses line breaks and inserts nothing for blank text", () => {+ const ed = makeEditor();+ insertDictation(ed, "one\n\ntwo\nthree", false);+ expect(markdown(ed)).toBe("one two three");+ insertDictation(ed, " \n ", false);+ expect(markdown(ed)).toBe("one two three");+ });++ it("inserts markdown-looking text literally", () => {+ const ed = makeEditor();+ insertDictation(ed, "# not a heading", false);+ expect(ed.state.doc.firstChild?.type.name).toBe("paragraph");+ });+});diff --git a/packages/views/editor/utils/insert-dictation.ts b/packages/views/editor/utils/insert-dictation.tsnew file mode 100644index 0000000000..7d38206b4b--- /dev/null+++ b/packages/views/editor/utils/insert-dictation.ts@@ -0,0 +1,29 @@+import type { Editor } from "@tiptap/core";+import { Selection } from "@tiptap/pm/state";+import { dictationSeparator } from "@multica/core/voice";++/**+ * Insert dictated text as plain text where the user would type next: over+ * the selection when `atCaret`, otherwise at the end of the document. Line+ * breaks collapse to spaces, and a space goes on either side where two words+ * of a spaced language would otherwise touch. Leaves the caret right after+ * the dictated words.+ */+export function insertDictation(editor: Editor, text: string, atCaret: boolean): void {+ const clean = text.replace(/\s*\n+\s*/g, " ").trim();+ if (!clean) return;+ // `.to`: when the document ends in a node (an image), atEnd selects that+ // node, and the text goes after it rather than over it.+ const { doc } = editor.state;+ const end = Selection.atEnd(doc).to;+ const { from, to } = atCaret ? editor.state.selection : { from: end, to: end };+ const before = doc.textBetween(Math.max(0, from - 1), from, "\n", " ");+ const after = doc.textBetween(to, Math.min(doc.content.size, to + 1), "\n", " ");+ const lead = dictationSeparator(before, clean) + clean;+ editor+ .chain()+ .insertContentAt({ from, to }, { type: "text", text: lead + dictationSeparator(clean, after) })+ .setTextSelection(from + lead.length)+ .focus()+ .run();+}diff --git a/packages/views/issues/components/annotation-composer.test.tsx b/packages/views/issues/components/annotation-composer.test.tsxnew file mode 100644index 0000000000..3713bace57--- /dev/null+++ b/packages/views/issues/components/annotation-composer.test.tsx@@ -0,0 +1,103 @@+import { createRef } from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { EditorView } from "@tiptap/pm/view";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import {+ cancelVoice,+ connectVoiceRuntime,+ getVoiceState,+ stopVoice,+ useVoiceModelsStore,+} from "@multica/core/voice";+import type { ReplyAnnotation } from "@multica/core/drafts/reply-annotation";+import { renderWithI18n } from "../../test/i18n";+import type { ContentEditorRef } from "../../editor";+import { AnnotationComposer } from "./annotation-composer";++const engine = vi.hoisted(() => ({ transcribe: vi.fn() }));++vi.mock("../../voice/recorder", () => ({ voiceInputSupported: () => true }));+vi.mock("../../voice/engine", async () => {+ const { useVoiceModelsStore } = await import("@multica/core/voice");+ return { useVoiceModels: () => useVoiceModelsStore((s) => s.models) };+});++const annotation: ReplyAnnotation = {+ id: "a1", sourceCommentId: "root", sourceActorName: "Root", quote: "Root text",+ start: 0, prefix: "", suffix: "", note: "",+};++beforeAll(() => {+ // jsdom has no layout, so ProseMirror's post-dispatch scroll walks+ // coordsAtPos into getClientRects() on nodes jsdom does not implement.+ (EditorView.prototype as unknown as { scrollToSelection: () => void }).scrollToSelection = () => {};+ connectVoiceRuntime(() => ({+ record: () => ({+ start: () => Promise.resolve(),+ finish: () => Promise.resolve({ blob: new Blob(["clip"]), heardSpeech: true, durationMs: 1500 }),+ discard: () => {},+ }),+ prepare: () => {},+ transcribe: (...args) => engine.transcribe(...args),+ watchModels: () => {},+ }));+});++beforeEach(() => {+ act(() => useVoiceModelsStore.getState().setModels({+ engineAvailable: true,+ models: [{ id: "m", name: "M", author: "A", licenseUrl: "https://example.com", languages: ["zh"],+ languageHint: true, sizeBytes: 1, status: "ready", receivedBytes: 1 }],+ }));+});++afterEach(() => {+ act(() => cancelVoice());+ cleanup();+});++function renderComposer(onChange = vi.fn()) {+ const editorRef = createRef<ContentEditorRef>();+ renderWithI18n(<QueryClientProvider client={new QueryClient()}>+ <AnnotationComposer owner="reply:issue:root" annotation={annotation} existing={false} number={1}+ editorRef={editorRef} sourceMissing={false} sourceChanged={false} canSave+ onChange={onChange} onSave={() => true} onBusyChange={() => {}}+ controls={{+ submit: async () => {}, submitting: false, uploading: false, restart: false,+ recipients: <span>Lambda · Will start when sent</span>, draftContent: "", annotations: [],+ }} />+ </QueryClientProvider>);+ return editorRef;+}++describe("AnnotationComposer voice input", () => {+ it("dictates into the note, keeping the recipient beside the strip", async () => {+ engine.transcribe.mockResolvedValue({ ok: true, text: "请改一下" });+ const onChange = vi.fn();+ const editorRef = renderComposer(onChange);++ const mic = screen.getByRole("button", { name: /^Dictate/ });+ const send = screen.getByRole("button", { name: "Send" });+ expect(mic.compareDocumentPosition(send) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();++ await act(async () => fireEvent.click(mic, { detail: 0 }));+ expect(getVoiceState().phase).toBe("recording");+ expect(screen.getByText("Lambda · Will start when sent")).toBeVisible();+ expect(screen.getByRole("button", { name: "Insert" })).toBeInTheDocument();+ // Enter saves a note, so dictation here only inserts; nothing sends from the strip.+ expect(screen.queryByRole("button", { name: "Send" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Add annotation" })).not.toBeInTheDocument();++ await act(async () => stopVoice(false));+ await waitFor(() => expect(editorRef.current?.getMarkdown()).toContain("请改一下"));+ expect(screen.getByRole("button", { name: "Add annotation" })).toBeInTheDocument();+ });++ it("opens model setup as part of the annotation, so it does not dismiss it", async () => {+ act(() => useVoiceModelsStore.getState().setModels({ engineAvailable: true, models: [] }));+ renderComposer();+ await act(async () => fireEvent.click(screen.getByRole("button", { name: /^Dictate/ }), { detail: 0 }));+ expect(await screen.findByRole("dialog")).toHaveAttribute("data-editor-overlay-owner", "reply:issue:root");+ });+});diff --git a/packages/views/issues/components/annotation-composer.tsx b/packages/views/issues/components/annotation-composer.tsxindex 8fcd4e4183..17a2a6ad99 100644--- a/packages/views/issues/components/annotation-composer.tsx+++ b/packages/views/issues/components/annotation-composer.tsx@@ -10,6 +10,14 @@ import { ContentEditor, type ContentEditorRef } from "../../editor";import { EditorOverlayOwnerContext } from "../../editor/overlay-owner";import { ShortcutKeycaps } from "../../common/shortcut-keycaps";import { useT } from "../../i18n";+import {+ useComposerVoice,+ VoiceErrorRow,+ VoiceHud,+ VoiceMicButton,+ VoiceSetupDialog,+ VoiceStrip,+} from "../../voice";/** The existing reply/comment composer owns routing, uploads and submission. */export interface AnnotationSendControls {@@ -86,9 +94,16 @@ export function AnnotationComposer({setSending(false);}};+ // No voice send: Enter saves the note here, so dictation only inserts.+ const voice = useComposerVoice({+ insert: (text) => editorRef.current?.insertText(text) ?? false,+ scope: annotation.id,+ disabled: busy,+ });return <EditorOverlayOwnerContext.Provider value={owner}>- <div className="flex w-80 max-w-[calc(100vw-26px)] flex-col gap-1" aria-busy={busy || undefined}>+ <div ref={voice.rootRef} onFocusCapture={voice.onFocusCapture}+ className="relative flex w-96 max-w-[calc(100vw-26px)] flex-col gap-1" aria-busy={busy || undefined}><div className={busy ? "pointer-events-none opacity-60" : undefined} inert={busy || undefined}><ContentEditor ref={editorRef} defaultValue={initialNote}ariaLabel={t(($) => $.reply.annotations.note_label)}@@ -97,6 +112,9 @@ export function AnnotationComposer({currentIssueId={issueId} showBubbleMenu={false} debounceMs={100}onUpdate={onChange} onEnter={save} onSubmit={send} /></div>+ <VoiceHud voice={voice} />+ <VoiceSetupDialog voice={voice} />+ <VoiceErrorRow voice={voice} className="mx-1" />{(sourceMissing || sourceChanged) && <p role={sourceMissing ? "alert" : undefined} className="px-2 text-caption text-muted-foreground">{t(($) => $.reply.annotations.source_changed)}</p>}@@ -108,12 +126,16 @@ export function AnnotationComposer({{otherAnnotations ? t(($) => hasBody ? $.reply.annotations.send_with_annotations_and_body : $.reply.annotations.send_with_annotations, { count: otherAnnotations }): t(($) => $.reply.annotations.send_with_body)}</p>}- <div className="flex flex-wrap items-center gap-1 px-1 pb-1" inert={busy || undefined}>+ {voice.showStrip ? <div className="flex items-center gap-1 px-1 pb-1">+ {controls?.recipients && <div className="min-w-0 max-w-[60%] shrink-0 overflow-hidden">{controls.recipients}</div>}+ <VoiceStrip voice={voice} />+ </div> : <div className="flex flex-wrap items-center gap-1 px-1 pb-1" inert={busy || undefined}>{existing && onRemove && <IconButton variant="ghost" size="icon-sm"className="text-muted-foreground hover:text-destructive" label={t(($) => $.reply.annotations.remove, { number })}disabled={busy} onClick={onRemove}><Trash2 /></IconButton>}<div className="min-w-0 flex-1">{controls?.recipients}</div><div className="ml-auto flex items-center gap-1">+ <VoiceMicButton voice={voice} />{controls && (controls.restart// Stopping a run must stay spelled out, never an unlabeled icon.? <Button size="sm" variant="destructive" disabled={sendDisabled} onClick={send} aria-busy={busy || undefined}>@@ -132,7 +154,7 @@ export function AnnotationComposer({<ShortcutKeycaps shortcut={ENTER} decorative /></Button></div>- </div>+ </div>}</div></EditorOverlayOwnerContext.Provider>;}diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsxindex e36557f558..f26efbd584 100644--- a/packages/views/issues/components/comment-composers.test.tsx+++ b/packages/views/issues/components/comment-composers.test.tsx@@ -433,6 +433,9 @@ describe("comment composers", () => {activateComposer("reply-composer-shell");expect(screen.getByPlaceholderText("Leave a reply...")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Attach file" })).toBeInTheDocument();+ expect(container.querySelectorAll("button")).toHaveLength(1);+ act(() => screen.getByTestId("editor").focus());+ expect(screen.getByRole("button", { name: "Send" })).toBeInTheDocument();expect(container.querySelectorAll("button")).toHaveLength(2);const shell = screen.getByTestId("drop-zone");@@ -455,7 +458,7 @@ describe("comment composers", () => {expect(screen.getByTestId("reply-composer-shell")).toBeInTheDocument();await screen.findByRole("button", { name: /Lambda trigger/ }, { timeout: 5000 });- expect(screen.getByTestId("drop-zone").className).toContain("pb-9");+ expect(screen.getByRole("button", { name: "Send" })).toBeInTheDocument();});it("keeps main comment submission wired after removing expand", async () => {@@ -1344,7 +1347,9 @@ describe.each(["reply", "description"])("annotations in %s drafts", (source) =>useCommentDraftStore.getState().addAnnotation(draftKey, { ...annotation, note: "" });const onSubmit = vi.fn().mockResolvedValue(false);renderAnnotatedComposer(onSubmit);- expect(isSendBlocked(screen.getByRole("button", { name: "Send" }) as HTMLButtonElement)).toBe(true);+ // Nothing to send: the comment box keeps a blocked send, a reply rests as one line.+ if (source === "description") expect(isSendBlocked(screen.getByRole("button", { name: "Send" }) as HTMLButtonElement)).toBe(true);+ else expect(screen.queryByRole("button", { name: "Send" })).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: /1 annotation/ })).not.toBeInTheDocument();act(() => { useCommentDraftStore.getState().addAnnotation(draftKey, { ...annotation, note: "New note" }); });fireEvent.click(screen.getByRole("button", { name: "Send" }));diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsxindex 8d0f586e6f..6981d7ed61 100644--- a/packages/views/issues/components/comment-input.tsx+++ b/packages/views/issues/components/comment-input.tsx@@ -3,7 +3,6 @@import { useRef, useState, useEffect, useMemo } from "react";import { cn } from "@multica/ui/lib/utils";import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";-import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { SubmitButton } from "@multica/ui/components/common/submit-button";import { Button } from "@multica/ui/components/ui/button";import { contentReferencesAttachment, type AgentTask } from "@multica/core/types";@@ -14,7 +13,19 @@ import { composeAnnotatedReply, hasReplyIntent } from "@multica/core/drafts/replimport { annotationsWithPending, type AnnotationComposerSlot } from "./annotation-composer";import { ReplyAnnotations } from "./reply-annotations";import { useT } from "../../i18n";+import {+ useComposerVoice,+ VoiceErrorRow,+ VoiceHud,+ VoiceSetupDialog,+} from "../../voice";import { CommentTriggerChips } from "./comment-trigger-chips";+import {+ ComposerToolbar,+ ComposerTools,+ QUIET_SEND_CLASS,+ useComposerFocus,+} from "./composer-frame";import { commentTriggerPreviewSignature, useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";import { useRecipientActions } from "../hooks/use-recipient-actions";import { SteerAttachmentNotice } from "./steer-attachment-notice";@@ -223,6 +234,17 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat},});+ const voice = useComposerVoice({+ insert: (text) => editorRef.current?.insertText(text) ?? false,+ // Sending while a run would be restarted stays an explicit click on the+ // destructive button.+ submit: routing.restartTaskIds.length === 0 ? () => void submit() : undefined,+ activate: () => lazy.activate(),+ scope: issueId,+ });+ const { focused, focusProps } = useComposerFocus();+ const showsTriggerChips = recipients.length > 0 || triggerPreview.blocked.length > 0 || triggerPreview.hasAllMembersMention;+return (<>{annotationComposer?.render({submit, submitting, uploading: gate.uploading, restart: routing.restartTaskIds.length > 0,@@ -233,7 +255,13 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat<divdata-mc="comment-composer"{...dropZoneProps}- className="relative flex flex-col rounded-lg bg-card pb-8 ring-1 ring-border"+ {...focusProps}+ className={cn(+ "relative flex flex-col rounded-lg bg-card ring-1 transition-shadow",+ focused ? "ring-foreground/25" : "ring-border",+ )}+ ref={voice.rootRef}+ onFocusCapture={voice.onFocusCapture}>{attachmentsBlockSteer && <div className="px-3 pt-2"><SteerAttachmentNotice />@@ -311,33 +339,34 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat</div></div>)}- <div className="absolute bottom-1 left-2 right-28 min-w-0">- <CommentTriggerChips+ <VoiceHud voice={voice} />+ <VoiceSetupDialog voice={voice} />+ <VoiceErrorRow voice={voice} className="mx-2 mb-1" />+ <ComposerToolbar+ className="px-1.5 pb-1"+ voice={voice}+ hasRecipients={showsTriggerChips}+ recipients={<CommentTriggerChipsrecipients={recipients}blocked={triggerPreview.blocked}hasAllMembersMention={triggerPreview.hasAllMembersMention}draftContent={composedContent}onActionChange={setAction}- />- </div>- <div className="absolute bottom-1 right-1.5 flex items-center gap-1">- <FileUploadButton- size="sm"- multiple- onSelect={(file) => lazy.uploadOrQueue([file])}- />- {routing.restartTaskIds.length > 0 ? (+ />}+ tools={<ComposerTools voice={voice} onAttach={(file) => lazy.uploadOrQueue([file])} />}+ send={routing.restartTaskIds.length > 0 ? (<Buttonsize="sm"variant="destructive"// eslint-disable-next-line no-restricted-syntax -- composer send button, the one round button- className="rounded-full"+ className="rounded-full px-3"onClick={submit}disabled={!canSend || submitting || gate.uploading}>{t(($) => $.comment.restart_send)}</Button>) : <SubmitButton+ className={QUIET_SEND_CLASS}onClick={submit}disabled={!canSend}loading={submitting}@@ -359,7 +388,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat? tEditor(($) => $.upload.in_progress): t(($) => $.comment.send_tooltip)}/>}- </div>+ />{isDragOver && <FileDropOverlay />}</div></>);diff --git a/packages/views/issues/components/comment-trigger-chips.tsx b/packages/views/issues/components/comment-trigger-chips.tsxindex ac0c3f06cc..a451ee7f36 100644--- a/packages/views/issues/components/comment-trigger-chips.tsx+++ b/packages/views/issues/components/comment-trigger-chips.tsx@@ -292,8 +292,8 @@ function SingleRecipientChip({t: IssuesT;}) {const label = actionLabel(entry.action, entry.state, t);- // The avatar carries "who"; the sentence carries only the outcome, so it- // stays fixed-width and never truncates on long agent names.+ // Name, then outcome. A long name truncates; the outcome never does.+ const quiet = entry.action !== "steer" && entry.action !== "restart" && entry.action !== "skip";return (<RecipientActionMenuentry={entry}@@ -309,7 +309,11 @@ function SingleRecipientChip({)}><TriggerAgentAvatar agent={entry.agent} suppressed={entry.action === "skip"} />- <span className="truncate">{label}</span>+ <span className="inline-flex min-w-0 items-center gap-1">+ <span className={cn("truncate", quiet && "text-foreground")}>{entry.agent.name}</span>+ <span aria-hidden className="shrink-0">·</span>+ <span className="shrink-0">{label}</span>+ </span><ChevronDown aria-hidden className="size-3 shrink-0 text-faint-foreground" /></button>}diff --git a/packages/views/issues/components/composer-frame.test.tsx b/packages/views/issues/components/composer-frame.test.tsxnew file mode 100644index 0000000000..9c969defb2--- /dev/null+++ b/packages/views/issues/components/composer-frame.test.tsx@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { renderHook, screen } from "@testing-library/react";+import type { VoiceState } from "@multica/core/voice";+import { renderWithI18n } from "../../test/i18n";+import type { ComposerVoice } from "../../voice";+import { ComposerToolbar, useComposerExpanded } from "./composer-frame";++function voice(patch: Partial<ComposerVoice> = {}): ComposerVoice {+ return {+ id: "v",+ available: true,+ session: null,+ busyElsewhere: false,+ showStrip: false,+ showHud: false,+ holding: false,+ showSetup: false,+ canSubmit: true,+ onFocusCapture: () => {},+ rootRef: () => {},+ ...patch,+ };+}++const transcribing: VoiceState = { targetId: "v", phase: "transcribing", mode: "strip", error: null, canRetry: false };++describe("ComposerToolbar", () => {+ it("keeps the recipients beside the transcribing strip instead of covering them", () => {+ renderWithI18n(+ <ComposerToolbar+ voice={voice({ session: transcribing, showStrip: true })}+ hasRecipients+ recipients={<span>Lambda · Will start when sent</span>}+ tools={<button type="button">Attach file</button>}+ send={<button type="button">Send</button>}+ />,+ );+ expect(screen.getByText("Lambda · Will start when sent")).toBeVisible();+ expect(screen.getAllByText("Transcribing…").length).toBeGreaterThan(0);+ expect(screen.queryByRole("button", { name: "Send" })).not.toBeInTheDocument();+ });++ it("shows the tools and send when not dictating", () => {+ renderWithI18n(+ <ComposerToolbar+ voice={voice()}+ hasRecipients={false}+ recipients={null}+ tools={<button type="button">Attach file</button>}+ send={<button type="button">Send</button>}+ />,+ );+ expect(screen.getAllByRole("button").map((b) => b.textContent)).toEqual(["Attach file", "Send"]);+ });+});++describe("useComposerExpanded", () => {+ it("holds its shape while the mic is pressed, then follows again", () => {+ const { result, rerender } = renderHook(({ wanted, holding }) => useComposerExpanded(wanted, voice({ holding })), {+ initialProps: { wanted: false, holding: false },+ });+ expect(result.current).toBe(false);+ rerender({ wanted: true, holding: true });+ expect(result.current).toBe(false);+ rerender({ wanted: true, holding: false });+ expect(result.current).toBe(true);+ rerender({ wanted: false, holding: true });+ expect(result.current).toBe(true);+ });+});diff --git a/packages/views/issues/components/composer-frame.tsx b/packages/views/issues/components/composer-frame.tsxnew file mode 100644index 0000000000..3e484c0f1a--- /dev/null+++ b/packages/views/issues/components/composer-frame.tsx@@ -0,0 +1,122 @@+"use client";++import { useState, type FocusEvent, type MouseEvent, type ReactNode } from "react";+import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";+import { cn } from "@multica/ui/lib/utils";+import { VoiceMicButton, VoiceStrip, type ComposerVoice } from "../../voice";++/**+ * Shared by the issue comment box and thread replies: one line with attach+ * and mic at rest, a toolbar row with recipients and send once focused or+ * written in.+ */++/** Send stays a light tint until there is something to send. */+export const QUIET_SEND_CLASS =+ "disabled:opacity-100 disabled:bg-muted disabled:text-faint-foreground aria-disabled:opacity-100 aria-disabled:bg-muted aria-disabled:text-faint-foreground";++const IDLE_TOOLS = "data-composer-idle-tools";++/**+ * Whether focus is inside the box. Focus on the resting attach and mic does+ * not count: expanding would unmount the button before its click lands.+ */+export function useComposerFocus() {+ const [focused, setFocused] = useState(false);+ return {+ focused,+ focusProps: {+ onFocus: (event: FocusEvent<HTMLElement>) => {+ if (!(event.target as HTMLElement).closest(`[${IDLE_TOOLS}]`)) setFocused(true);+ },+ onBlur: (event: FocusEvent<HTMLElement>) => {+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false);+ },+ },+ };+}++/**+ * Whether the box shows its toolbar. Frozen while the mic is held: dictation+ * focuses the editor, and the pressed mic must not unmount before release.+ */+export function useComposerExpanded(wanted: boolean, voice: ComposerVoice): boolean {+ const [settled, setSettled] = useState(wanted);+ if (!voice.holding && settled !== wanted) setSettled(wanted);+ return voice.holding ? settled : wanted;+}++/** Attach, then mic: the mic sits next to send, where its recording strip grows from. */+export function ComposerTools({ voice, onAttach }: { voice: ComposerVoice; onAttach: (file: File) => void }) {+ return (+ <>+ <FileUploadButton multiple onSelect={onAttach} />+ <VoiceMicButton voice={voice} />+ </>+ );+}++/** The tools at the end of the one-line box at rest. */+export function ComposerIdleTools({+ voice,+ onAttach,+ className,+}: {+ voice: ComposerVoice;+ onAttach: (file: File) => void;+ className?: string;+}) {+ return (+ <div {...{ [IDLE_TOOLS]: "" }} className={cn("flex shrink-0 items-center gap-1", className)}>+ <ComposerTools voice={voice} onAttach={onAttach} />+ </div>+ );+}++/** A click on the toolbar's empty space must not take focus out of the box and fold it. */+function keepFocus(event: MouseEvent<HTMLElement>) {+ if (!(event.target as HTMLElement).closest("button, a, input, [role='button']")) event.preventDefault();+}++/**+ * The expanded box's bottom row. Recipients keep their place on the left+ * while dictating; the strip takes the rest of the row instead of covering+ * them.+ */+export function ComposerToolbar({+ voice,+ recipients,+ hasRecipients,+ tools,+ send,+ className,+}: {+ voice: ComposerVoice;+ recipients: ReactNode;+ hasRecipients: boolean;+ tools: ReactNode;+ send: ReactNode;+ className?: string;+}) {+ return (+ <div+ className={cn("flex h-9 items-center gap-1", className)}+ onMouseDown={keepFocus}+ >+ {hasRecipients && (+ <div className={cn("min-w-0 overflow-hidden", voice.showStrip ? "max-w-[45%] shrink-0" : "flex-1")}>+ {recipients}+ </div>+ )}+ {voice.showStrip ? (+ <VoiceStrip voice={voice} />+ ) : (+ <>+ {!hasRecipients && <div className="flex-1" />}+ {tools}+ {send}+ </>+ )}+ </div>+ );+}diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsxindex 3e9beeb181..02a8249027 100644--- a/packages/views/issues/components/reply-input.tsx+++ b/packages/views/issues/components/reply-input.tsx@@ -3,10 +3,9 @@import { composeAnnotatedReply, EMPTY_REPLY_ANNOTATIONS, hasReplyIntent } from "@multica/core/drafts/reply-annotation";import { annotationsWithPending, type AnnotationComposerSlot } from "./annotation-composer";import { ReplyAnnotations } from "./reply-annotations";-import { useRef, useState, useEffect, useImperativeHandle, useMemo, type Ref } from "react";+import { useCallback, useRef, useState, useEffect, useImperativeHandle, useMemo, type Ref } from "react";import { toast } from "sonner";import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";-import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { SubmitButton } from "@multica/ui/components/common/submit-button";import { Button } from "@multica/ui/components/ui/button";import { ActorAvatar } from "../../common/actor-avatar";@@ -17,7 +16,21 @@ import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issuesimport { cn } from "@multica/ui/lib/utils";import type { AvatarSize } from "@multica/ui/lib/avatar-size";import { useT } from "../../i18n";+import {+ useComposerVoice,+ VoiceErrorRow,+ VoiceHud,+ VoiceSetupDialog,+} from "../../voice";import { CommentTriggerChips } from "./comment-trigger-chips";+import {+ ComposerIdleTools,+ ComposerToolbar,+ ComposerTools,+ QUIET_SEND_CLASS,+ useComposerExpanded,+ useComposerFocus,+} from "./composer-frame";import { commentTriggerPreviewSignature, useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";import { useRecipientActions } from "../hooks/use-recipient-actions";import { SteerAttachmentNotice } from "./steer-attachment-notice";@@ -248,6 +261,24 @@ function ReplyInput({});const avatarSize: AvatarSize = size === "sm" ? "sm" : "md";+ const voice = useComposerVoice({+ insert: (text) => editorRef.current?.insertText(text) ?? false,+ // A send that would restart a run stays an explicit click — see CommentInput.+ submit: routing.restartTaskIds.length === 0 ? () => void submit() : undefined,+ activate: () => lazy.activate(),+ scope: `${issueId}:${parentId}`,+ });+ const { focused, focusProps } = useComposerFocus();+ // One line at rest, like the comment box — see CommentInput.+ const expanded = useComposerExpanded(+ focused || !isEmpty || annotations.length > 0 || showsTriggerChips || voice.showStrip || submitting || gate.uploading,+ voice,+ );+ const voiceRootRef = voice.rootRef;+ const bindComposer = useCallback((element: HTMLDivElement | null) => {+ composerRef.current = element;+ voiceRootRef(element);+ }, [voiceRootRef]);return (<>{annotationComposer?.render({@@ -265,11 +296,10 @@ function ReplyInput({/><div{...dropZoneProps}- ref={composerRef}- className={cn(- "relative min-w-0 flex-1 flex flex-col",- (!isEmpty || annotations.length > 0 || showsTriggerChips) && "pb-9",- )}+ {...focusProps}+ ref={bindComposer}+ className="relative flex min-w-0 flex-1 flex-col"+ onFocusCapture={voice.onFocusCapture}>{attachmentsBlockSteer && <SteerAttachmentNotice />}{draftKey && annotations.length > 0 && <>@@ -277,11 +307,12 @@ function ReplyInput({<ReplyAnnotations draftKey={draftKey} annotations={annotations}disabled={submitting} onEditAnnotation={onEditAnnotation} /></>}+ <div className="flex min-h-0 flex-1 items-center">{/* Lock the editor while the reply is in flight — see CommentInput. */}{lazy.active && (<divclassName={cn(- "flex-1 min-h-0 overflow-y-auto",+ "min-w-0 flex-1 min-h-0 overflow-y-auto",submitting && "pointer-events-none opacity-60",!lazy.ready && "hidden",)}@@ -319,7 +350,7 @@ function ReplyInput({role="button"tabIndex={0}aria-label={placeholderText}- className="flex-1 min-h-0 cursor-text rich-text-editor text-body"+ className="min-w-0 flex-1 cursor-text rich-text-editor text-body"onClick={() => lazy.activate()}onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {@@ -333,33 +364,36 @@ function ReplyInput({<p className="text-muted-foreground">{placeholderText}</p></div>)}- <div className="absolute bottom-0 left-0 right-24 min-w-0">- <CommentTriggerChips+ {!expanded && <ComposerIdleTools className="-my-1" voice={voice} onAttach={(file) => lazy.uploadOrQueue([file])} />}+ </div>+ <VoiceHud voice={voice} />+ <VoiceSetupDialog voice={voice} />+ <VoiceErrorRow voice={voice} className="mt-1" />+ {expanded && <ComposerToolbar+ className="mt-1 animate-in fade-in slide-in-from-top-1 duration-150"+ voice={voice}+ hasRecipients={showsTriggerChips}+ recipients={<CommentTriggerChipsrecipients={recipients}blocked={triggerPreview.blocked}hasAllMembersMention={triggerPreview.hasAllMembersMention}draftContent={composedContent}onActionChange={setAction}- />- </div>- <div className="absolute bottom-0 right-0 flex items-center gap-1">- <FileUploadButton- size="sm"- multiple- onSelect={(file) => lazy.uploadOrQueue([file])}- />- {routing.restartTaskIds.length > 0 ? (+ />}+ tools={<ComposerTools voice={voice} onAttach={(file) => lazy.uploadOrQueue([file])} />}+ send={routing.restartTaskIds.length > 0 ? (<Buttonsize="sm"variant="destructive"// eslint-disable-next-line no-restricted-syntax -- composer send button, the one round button- className="rounded-full"+ className="rounded-full px-3"onClick={submit}disabled={!canSend || submitting || gate.uploading}>{t(($) => $.comment.restart_send)}</Button>) : <SubmitButton+ className={QUIET_SEND_CLASS}onClick={submit}disabled={!canSend}loading={submitting}@@ -381,7 +415,7 @@ function ReplyInput({? tEditor(($) => $.upload.in_progress): t(($) => $.comment.send_tooltip)}/>}- </div>+ />}{isDragOver && <FileDropOverlay />}</div></div>diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex b53e73efce..0b43b8dbca 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -182,5 +182,49 @@"clear_filter": "Clear filter","no_matches": "No matching rows","close": "Close"+ },+ "voice": {+ "dictate": "Dictate",+ "hold_to_talk": "Hold to talk",+ "tap_or_hold": "Dictate (tap, or hold to talk)",+ "cancel": "Cancel",+ "insert": "Insert",+ "send": "Send",+ "retry": "Retry",+ "dismiss": "Dismiss",+ "requesting": "Waiting for the microphone…",+ "transcribing": "Transcribing…",+ "release_to_insert": "Release to insert",+ "recording": "Recording",+ "errors": {+ "permission_denied": "Microphone access is blocked. Allow it in your browser or system settings, then retry.",+ "no_microphone": "No microphone found. Connect one, then retry.",+ "microphone_failed": "Couldn't start the microphone.",+ "no_speech": "Didn't catch any speech. Try again a little closer to the mic.",+ "unavailable": "Voice input can't transcribe on this computer.",+ "transcription_failed": "Transcription failed. Your recording is kept, so you can retry."+ },+ "models": {+ "more_languages": "{{more}} more",+ "in_use": "In use",+ "recommended": "Recommended",+ "most_accurate": "Most accurate",+ "fastest": "Fastest",+ "by": "By {{author}}",+ "license": "License",+ "downloading": "Downloading, {{percent}}%",+ "failed": "Download failed. Retry to pick up where it stopped.",+ "download": "Download",+ "retry": "Retry",+ "cancel": "Cancel",+ "use": "Use",+ "delete": "Delete {{name}}"+ },+ "setup": {+ "title": "Set up voice input",+ "description": "Speech is transcribed on this computer, so recordings never leave it. Download a speech model once to start.",+ "later": "Not now",+ "start": "Start dictating"+ }}}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 9af1409ff5..11f6cb1fd0 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -490,6 +490,10 @@"goSettings": {"label": "Go to Settings","description": "Open workspace settings."+ },+ "voiceInput": {+ "label": "Voice input",+ "description": "Dictate into the composer you used last. Hold to talk."}},"fixed": {@@ -586,7 +590,8 @@"code": "Code","channels": "Messaging","apps": "Connected apps",- "workflows": "Workflows"+ "workflows": "Workflows",+ "voice_input": "Voice input"},"groups": {"personal": "Personal",@@ -1853,5 +1858,100 @@"admin_required": "A workspace admin can restore access.","account_link": "This account has saved action restrictions. Restore access in Connected apps."}+ },+ "voice_input": {+ "description": "Dictate into chat, comments and replies. Speech is transcribed on this computer and never leaves it.",+ "model_title": "Speech model",+ "model_hint": "Models run on this computer. Download one, or switch between the ones you have.",+ "engine_unavailable": "On-device transcription isn't available for this computer.",+ "input_title": "Input",+ "shortcut": {+ "title": "Shortcut",+ "hint": "Works whenever a composer is on screen, even if it isn't focused.",+ "change": "Change",+ "unassigned": "Not set"+ },+ "activation": {+ "title": "Activation",+ "auto": "Tap or hold",+ "toggle": "Tap",+ "hold": "Hold",+ "hints": {+ "auto": "Tap to start and tap again to insert. Hold to talk and release to insert.",+ "toggle": "Tap to start, tap again to insert.",+ "hold": "Hold to talk, release to insert."+ }+ },+ "recognition_title": "Recognition",+ "language": {+ "title": "Spoken language",+ "hint": "Auto-detect handles most speech. Pick a language if short phrases come out in the wrong one.",+ "auto": "Auto-detect"+ },+ "fillers": {+ "title": "Remove filler words",+ "hint": "Drop “um”, “uh” and similar hesitations."+ },+ "vocabulary": {+ "title": "Vocabulary",+ "hint": "Names and terms to spell your way, such as product or teammate names. Up to {{max}}.",+ "placeholder": "Add a word",+ "remove": "Remove {{word}}"+ },+ "microphone_title": "Microphone",+ "device": {+ "title": "Input device",+ "default": "System default",+ "unnamed": "Microphone {{index}}",+ "permission_hint": "Test the microphone once to see device names."+ },+ "test": {+ "title": "Test microphone",+ "hint": "Speak to check the level. Nothing is recorded.",+ "blocked": "Microphone access is blocked. Allow it in your browser or system settings.",+ "start": "Test",+ "stop": "Stop"+ },+ "history": {+ "title": "History",+ "description": "Recordings and their text stay on this computer and are never uploaded. One that failed or was interrupted can be transcribed again from its audio.",+ "keep": {+ "title": "Keep history",+ "hint": "How long recordings stay on this computer.",+ "options": {+ "off": "Don't keep",+ "1d": "1 day",+ "7d": "7 days",+ "30d": "30 days",+ "forever": "Forever"+ }+ },+ "clear": "Clear all",+ "clear_dialog": {+ "title": "Clear voice history?",+ "description": "Every recording and transcript kept on this computer will be deleted.",+ "cancel": "Cancel"+ },+ "empty": "Your dictations will appear here.",+ "off": "History is off. New recordings are not kept.",+ "today": "Today",+ "yesterday": "Yesterday",+ "status": {+ "transcribing": "Transcribing…",+ "failed": "Transcription failed",+ "interrupted": "Interrupted before it was transcribed"+ },+ "actions": {+ "play": "Play recording",+ "pause": "Pause",+ "retranscribe": "Transcribe again",+ "copy": "Copy text",+ "delete": "Delete"+ },+ "copied": "Copied",+ "copy_failed": "Couldn't copy",+ "retry_failed": "Couldn't transcribe this recording",+ "show_more": "Show more"+ }}}diff --git a/packages/views/locales/es/editor.json b/packages/views/locales/es/editor.jsonindex 09f558b536..8573928166 100644--- a/packages/views/locales/es/editor.json+++ b/packages/views/locales/es/editor.json@@ -182,5 +182,49 @@"clear_filter": "Borrar filtro","no_matches": "Ninguna fila coincide","close": "Cerrar"+ },+ "voice": {+ "dictate": "Dictar",+ "hold_to_talk": "Mantén pulsado para hablar",+ "tap_or_hold": "Dictar (toca, o mantén pulsado para hablar)",+ "cancel": "Cancelar",+ "insert": "Insertar",+ "send": "Enviar",+ "retry": "Reintentar",+ "dismiss": "Cerrar",+ "requesting": "Esperando el micrófono…",+ "transcribing": "Transcribiendo…",+ "release_to_insert": "Suelta para insertar",+ "recording": "Grabando",+ "errors": {+ "permission_denied": "El acceso al micrófono está bloqueado. Permítelo en el navegador o en la configuración del sistema y vuelve a intentarlo.",+ "no_microphone": "No se encontró ningún micrófono. Conecta uno y vuelve a intentarlo.",+ "microphone_failed": "No se pudo iniciar el micrófono.",+ "no_speech": "No se detectó voz. Vuelve a intentarlo un poco más cerca del micrófono.",+ "unavailable": "La entrada de voz no puede transcribir en este ordenador.",+ "transcription_failed": "La transcripción falló. La grabación se conserva, así que puedes reintentarlo."+ },+ "models": {+ "more_languages": "{{more}} más",+ "in_use": "En uso",+ "recommended": "Recomendado",+ "most_accurate": "Más preciso",+ "fastest": "Más rápido",+ "by": "De {{author}}",+ "license": "Licencia",+ "downloading": "Descargando, {{percent}} %",+ "failed": "La descarga falló. Reinténtala para continuar donde se quedó.",+ "download": "Descargar",+ "retry": "Reintentar",+ "cancel": "Cancelar",+ "use": "Usar",+ "delete": "Eliminar {{name}}"+ },+ "setup": {+ "title": "Configurar la entrada de voz",+ "description": "La voz se transcribe en este ordenador, así que las grabaciones nunca salen de él. Descarga un modelo de voz una vez para empezar.",+ "later": "Ahora no",+ "start": "Empezar a dictar"+ }}}diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex e770182037..c97dbed0c5 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -490,6 +490,10 @@"goSettings": {"label": "Ir a Configuración","description": "Abre la configuración del espacio de trabajo."+ },+ "voiceInput": {+ "label": "Entrada de voz",+ "description": "Dicta en el último editor que usaste. Mantén pulsado para hablar."}},"fixed": {@@ -586,7 +590,8 @@"apps": "Apps conectadas","channels": "Mensajería","code": "Código",- "workflows": "Flujos de trabajo"+ "workflows": "Flujos de trabajo",+ "voice_input": "Entrada de voz"},"groups": {"personal": "Personal",@@ -1853,5 +1858,100 @@"admin_required": "Un administrador puede restablecer el acceso.","account_link": "Esta cuenta conserva restricciones. Restablece el acceso en Apps conectadas."}+ },+ "voice_input": {+ "description": "Dicta en el chat, los comentarios y las respuestas. La voz se transcribe en este ordenador y nunca sale de él.",+ "model_title": "Modelo de voz",+ "model_hint": "Los modelos se ejecutan en este ordenador. Descarga uno o cambia entre los que tienes.",+ "engine_unavailable": "La transcripción en el dispositivo no está disponible en este ordenador.",+ "input_title": "Entrada",+ "shortcut": {+ "title": "Atajo",+ "hint": "Funciona siempre que haya un editor en pantalla, aunque no tenga el foco.",+ "change": "Cambiar",+ "unassigned": "Sin asignar"+ },+ "activation": {+ "title": "Activación",+ "auto": "Tocar o mantener",+ "toggle": "Tocar",+ "hold": "Mantener",+ "hints": {+ "auto": "Toca para empezar y vuelve a tocar para insertar. Mantén pulsado para hablar y suelta para insertar.",+ "toggle": "Toca para empezar y vuelve a tocar para insertar.",+ "hold": "Mantén pulsado para hablar y suelta para insertar."+ }+ },+ "recognition_title": "Reconocimiento",+ "language": {+ "title": "Idioma hablado",+ "hint": "La detección automática sirve para casi todo. Elige un idioma si las frases cortas salen en otro.",+ "auto": "Detección automática"+ },+ "fillers": {+ "title": "Quitar muletillas",+ "hint": "Elimina “eh”, “em” y vacilaciones similares."+ },+ "vocabulary": {+ "title": "Vocabulario",+ "hint": "Nombres y términos que quieres escritos a tu manera, como productos o compañeros. Hasta {{max}}.",+ "placeholder": "Añadir una palabra",+ "remove": "Quitar {{word}}"+ },+ "microphone_title": "Micrófono",+ "device": {+ "title": "Dispositivo de entrada",+ "default": "Predeterminado del sistema",+ "unnamed": "Micrófono {{index}}",+ "permission_hint": "Prueba el micrófono una vez para ver los nombres de los dispositivos."+ },+ "test": {+ "title": "Probar micrófono",+ "hint": "Habla para comprobar el nivel. No se graba nada.",+ "blocked": "El acceso al micrófono está bloqueado. Permítelo en el navegador o en la configuración del sistema.",+ "start": "Probar",+ "stop": "Detener"+ },+ "history": {+ "title": "Historial",+ "description": "Las grabaciones y su texto se quedan en este ordenador y nunca se suben. Una que falló o se interrumpió puede transcribirse de nuevo desde su audio.",+ "keep": {+ "title": "Conservar historial",+ "hint": "Cuánto tiempo se guardan las grabaciones en este ordenador.",+ "options": {+ "off": "No conservar",+ "1d": "1 día",+ "7d": "7 días",+ "30d": "30 días",+ "forever": "Siempre"+ }+ },+ "clear": "Borrar todo",+ "clear_dialog": {+ "title": "¿Borrar el historial de voz?",+ "description": "Se eliminarán todas las grabaciones y transcripciones guardadas en este ordenador.",+ "cancel": "Cancelar"+ },+ "empty": "Tus dictados aparecerán aquí.",+ "off": "El historial está desactivado. Las nuevas grabaciones no se guardan.",+ "today": "Hoy",+ "yesterday": "Ayer",+ "status": {+ "transcribing": "Transcribiendo…",+ "failed": "La transcripción falló",+ "interrupted": "Interrumpida antes de transcribirse"+ },+ "actions": {+ "play": "Reproducir grabación",+ "pause": "Pausar",+ "retranscribe": "Transcribir de nuevo",+ "copy": "Copiar texto",+ "delete": "Eliminar"+ },+ "copied": "Copiado",+ "copy_failed": "No se pudo copiar",+ "retry_failed": "No se pudo transcribir esta grabación",+ "show_more": "Mostrar más"+ }}}diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.jsonindex e1bfb82788..3af2dd6975 100644--- a/packages/views/locales/fr/editor.json+++ b/packages/views/locales/fr/editor.json@@ -182,5 +182,49 @@"clear_filter": "Effacer le filtre","no_matches": "Aucune ligne correspondante","close": "Fermer"+ },+ "voice": {+ "dictate": "Dicter",+ "hold_to_talk": "Maintenir pour parler",+ "tap_or_hold": "Dicter (appuyez, ou maintenez pour parler)",+ "cancel": "Annuler",+ "insert": "Insérer",+ "send": "Envoyer",+ "retry": "Réessayer",+ "dismiss": "Fermer",+ "requesting": "En attente du micro…",+ "transcribing": "Transcription…",+ "release_to_insert": "Relâchez pour insérer",+ "recording": "Enregistrement",+ "errors": {+ "permission_denied": "L’accès au micro est bloqué. Autorisez-le dans le navigateur ou les réglages système, puis réessayez.",+ "no_microphone": "Aucun micro trouvé. Branchez-en un, puis réessayez.",+ "microphone_failed": "Impossible de démarrer le micro.",+ "no_speech": "Aucune parole détectée. Réessayez un peu plus près du micro.",+ "unavailable": "La saisie vocale ne peut pas transcrire sur cet ordinateur.",+ "transcription_failed": "La transcription a échoué. L’enregistrement est conservé, vous pouvez réessayer."+ },+ "models": {+ "more_languages": "{{more}} autres",+ "in_use": "Utilisé",+ "recommended": "Recommandé",+ "most_accurate": "Le plus précis",+ "fastest": "Le plus rapide",+ "by": "Par {{author}}",+ "license": "Licence",+ "downloading": "Téléchargement, {{percent}} %",+ "failed": "Le téléchargement a échoué. Réessayez pour reprendre là où il s’est arrêté.",+ "download": "Télécharger",+ "retry": "Réessayer",+ "cancel": "Annuler",+ "use": "Utiliser",+ "delete": "Supprimer {{name}}"+ },+ "setup": {+ "title": "Configurer la saisie vocale",+ "description": "La voix est transcrite sur cet ordinateur : les enregistrements ne le quittent jamais. Téléchargez un modèle vocal une fois pour commencer.",+ "later": "Plus tard",+ "start": "Commencer à dicter"+ }}}diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 888e17b30b..d995f3fac8 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -490,6 +490,10 @@"goSettings": {"label": "Aller aux paramètres","description": "Ouvrir les paramètres de l'espace de travail."+ },+ "voiceInput": {+ "label": "Saisie vocale",+ "description": "Dictez dans le dernier éditeur utilisé. Maintenez pour parler."}},"fixed": {@@ -586,7 +590,8 @@"code": "Code","channels": "Messagerie","apps": "Applications connectées",- "workflows": "Workflows"+ "workflows": "Workflows",+ "voice_input": "Saisie vocale"},"groups": {"personal": "Personnel",@@ -1853,5 +1858,100 @@"admin_required": "Un administrateur peut rétablir l’accès.","account_link": "Ce compte conserve des restrictions. Rétablissez l’accès dans les apps connectées."}+ },+ "voice_input": {+ "description": "Dictez dans le chat, les commentaires et les réponses. La voix est transcrite sur cet ordinateur et ne le quitte jamais.",+ "model_title": "Modèle vocal",+ "model_hint": "Les modèles s’exécutent sur cet ordinateur. Téléchargez-en un, ou passez de l’un à l’autre.",+ "engine_unavailable": "La transcription sur l’appareil n’est pas disponible sur cet ordinateur.",+ "input_title": "Saisie",+ "shortcut": {+ "title": "Raccourci",+ "hint": "Fonctionne dès qu’un éditeur est à l’écran, même sans le focus.",+ "change": "Modifier",+ "unassigned": "Non défini"+ },+ "activation": {+ "title": "Activation",+ "auto": "Appui ou maintien",+ "toggle": "Appui",+ "hold": "Maintien",+ "hints": {+ "auto": "Appuyez pour commencer, appuyez à nouveau pour insérer. Maintenez pour parler, relâchez pour insérer.",+ "toggle": "Appuyez pour commencer, appuyez à nouveau pour insérer.",+ "hold": "Maintenez pour parler, relâchez pour insérer."+ }+ },+ "recognition_title": "Reconnaissance",+ "language": {+ "title": "Langue parlée",+ "hint": "La détection automatique convient dans la plupart des cas. Choisissez une langue si de courtes phrases sortent dans une autre.",+ "auto": "Détection automatique"+ },+ "fillers": {+ "title": "Supprimer les hésitations",+ "hint": "Retire « euh », « hum » et les hésitations similaires."+ },+ "vocabulary": {+ "title": "Vocabulaire",+ "hint": "Noms et termes à écrire à votre façon, comme des produits ou des collègues. Jusqu’à {{max}}.",+ "placeholder": "Ajouter un mot",+ "remove": "Retirer {{word}}"+ },+ "microphone_title": "Micro",+ "device": {+ "title": "Périphérique d’entrée",+ "default": "Par défaut du système",+ "unnamed": "Micro {{index}}",+ "permission_hint": "Testez le micro une fois pour voir le nom des périphériques."+ },+ "test": {+ "title": "Tester le micro",+ "hint": "Parlez pour vérifier le niveau. Rien n’est enregistré.",+ "blocked": "L’accès au micro est bloqué. Autorisez-le dans le navigateur ou les réglages système.",+ "start": "Tester",+ "stop": "Arrêter"+ },+ "history": {+ "title": "Historique",+ "description": "Les enregistrements et leur texte restent sur cet ordinateur et ne sont jamais envoyés. Un enregistrement qui a échoué ou a été interrompu peut être retranscrit à partir de son audio.",+ "keep": {+ "title": "Conserver l'historique",+ "hint": "Durée de conservation des enregistrements sur cet ordinateur.",+ "options": {+ "off": "Ne pas conserver",+ "1d": "1 jour",+ "7d": "7 jours",+ "30d": "30 jours",+ "forever": "Toujours"+ }+ },+ "clear": "Tout effacer",+ "clear_dialog": {+ "title": "Effacer l'historique vocal ?",+ "description": "Tous les enregistrements et transcriptions conservés sur cet ordinateur seront supprimés.",+ "cancel": "Annuler"+ },+ "empty": "Vos dictées apparaîtront ici.",+ "off": "L'historique est désactivé. Les nouveaux enregistrements ne sont pas conservés.",+ "today": "Aujourd'hui",+ "yesterday": "Hier",+ "status": {+ "transcribing": "Transcription…",+ "failed": "Échec de la transcription",+ "interrupted": "Interrompu avant la transcription"+ },+ "actions": {+ "play": "Lire l'enregistrement",+ "pause": "Pause",+ "retranscribe": "Retranscrire",+ "copy": "Copier le texte",+ "delete": "Supprimer"+ },+ "copied": "Copié",+ "copy_failed": "Impossible de copier",+ "retry_failed": "Impossible de transcrire cet enregistrement",+ "show_more": "Afficher plus"+ }}}diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex 12c3f1dd40..227b70248b 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -178,5 +178,49 @@"clear_filter": "絞り込みを解除","no_matches": "一致する行がありません","close": "閉じる"+ },+ "voice": {+ "dictate": "音声入力",+ "hold_to_talk": "押している間だけ話す",+ "tap_or_hold": "音声入力(タップ、または長押しで話す)",+ "cancel": "キャンセル",+ "insert": "挿入",+ "send": "送信",+ "retry": "再試行",+ "dismiss": "閉じる",+ "requesting": "マイクを待っています…",+ "transcribing": "文字起こし中…",+ "release_to_insert": "離すと挿入",+ "recording": "録音中",+ "errors": {+ "permission_denied": "マイクへのアクセスがブロックされています。ブラウザまたはシステム設定で許可してから再試行してください。",+ "no_microphone": "マイクが見つかりません。接続してから再試行してください。",+ "microphone_failed": "マイクを起動できませんでした。",+ "no_speech": "音声を聞き取れませんでした。マイクに近づいてもう一度お試しください。",+ "unavailable": "このコンピューターでは音声を文字起こしできません。",+ "transcription_failed": "文字起こしに失敗しました。録音は保持されているので再試行できます。"+ },+ "models": {+ "more_languages": "ほか {{more}} 言語",+ "in_use": "使用中",+ "recommended": "おすすめ",+ "most_accurate": "高精度",+ "fastest": "高速",+ "by": "提供: {{author}}",+ "license": "ライセンス",+ "downloading": "ダウンロード中 {{percent}}%",+ "failed": "ダウンロードに失敗しました。再試行すると中断したところから再開します。",+ "download": "ダウンロード",+ "retry": "再試行",+ "cancel": "キャンセル",+ "use": "使用する",+ "delete": "{{name}} を削除"+ },+ "setup": {+ "title": "音声入力を設定",+ "description": "音声はこのコンピューター上で文字起こしされ、録音が外部に送られることはありません。まず音声モデルを一度ダウンロードしてください。",+ "later": "後で",+ "start": "音声入力を開始"+ }}}diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex e8b2493437..0dcbd594d4 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -484,6 +484,10 @@"goSettings": {"label": "設定へ移動","description": "ワークスペース設定を開きます。"+ },+ "voiceInput": {+ "label": "音声入力",+ "description": "最後に使った入力欄に口述します。長押しで話します。"}},"fixed": {@@ -580,7 +584,8 @@"code": "コード","channels": "メッセージング","apps": "接続済みアプリ",- "workflows": "ワークフロー"+ "workflows": "ワークフロー",+ "voice_input": "音声入力"},"groups": {"personal": "個人",@@ -1832,5 +1837,100 @@"admin_required": "ワークスペース管理者が制限を解除できます。","account_link": "このアカウントには保存済みの操作制限があります。接続済みアプリで解除してください。"}+ },+ "voice_input": {+ "description": "チャット、コメント、返信を音声で入力します。音声はこのコンピューター上で文字起こしされ、外部に送られません。",+ "model_title": "音声モデル",+ "model_hint": "モデルはこのコンピューター上で動作します。ダウンロードするか、ダウンロード済みのモデルを切り替えます。",+ "engine_unavailable": "このコンピューターではオンデバイスの文字起こしを利用できません。",+ "input_title": "入力",+ "shortcut": {+ "title": "ショートカット",+ "hint": "入力欄が画面にあれば、フォーカスしていなくても使えます。",+ "change": "変更",+ "unassigned": "未設定"+ },+ "activation": {+ "title": "起動方法",+ "auto": "タップまたは長押し",+ "toggle": "タップ",+ "hold": "長押し",+ "hints": {+ "auto": "タップで開始し、もう一度タップで挿入。長押しで話し、離すと挿入。",+ "toggle": "タップで開始し、もう一度タップで挿入。",+ "hold": "長押しで話し、離すと挿入。"+ }+ },+ "recognition_title": "認識",+ "language": {+ "title": "話す言語",+ "hint": "ほとんどの場合は自動検出で十分です。短いフレーズが別の言語として認識される場合は指定してください。",+ "auto": "自動検出"+ },+ "fillers": {+ "title": "フィラーを除去",+ "hint": "「えー」「あの」などのつなぎ言葉を取り除きます。"+ },+ "vocabulary": {+ "title": "語彙",+ "hint": "製品名や同僚の名前など、表記を指定したい名称や用語。最大 {{max}} 件。",+ "placeholder": "単語を追加",+ "remove": "{{word}} を削除"+ },+ "microphone_title": "マイク",+ "device": {+ "title": "入力デバイス",+ "default": "システムのデフォルト",+ "unnamed": "マイク {{index}}",+ "permission_hint": "一度マイクをテストするとデバイス名が表示されます。"+ },+ "test": {+ "title": "マイクをテスト",+ "hint": "話して音量を確認します。録音はされません。",+ "blocked": "マイクへのアクセスがブロックされています。ブラウザまたはシステム設定で許可してください。",+ "start": "テスト",+ "stop": "停止"+ },+ "history": {+ "title": "履歴",+ "description": "録音と文字起こしはこのコンピューターにのみ保存され、アップロードされません。失敗または中断した録音は、元の音声から再度文字起こしできます。",+ "keep": {+ "title": "履歴の保存期間",+ "hint": "録音をこのコンピューターに保存する期間です。",+ "options": {+ "off": "保存しない",+ "1d": "1 日",+ "7d": "7 日",+ "30d": "30 日",+ "forever": "無期限"+ }+ },+ "clear": "すべて消去",+ "clear_dialog": {+ "title": "音声入力の履歴を消去しますか?",+ "description": "このコンピューターに保存されたすべての録音と文字起こしが削除されます。",+ "cancel": "キャンセル"+ },+ "empty": "音声入力の履歴がここに表示されます。",+ "off": "履歴はオフです。新しい録音は保存されません。",+ "today": "今日",+ "yesterday": "昨日",+ "status": {+ "transcribing": "文字起こし中…",+ "failed": "文字起こしに失敗しました",+ "interrupted": "文字起こし前に中断されました"+ },+ "actions": {+ "play": "録音を再生",+ "pause": "一時停止",+ "retranscribe": "もう一度文字起こし",+ "copy": "テキストをコピー",+ "delete": "削除"+ },+ "copied": "コピーしました",+ "copy_failed": "コピーできませんでした",+ "retry_failed": "この録音を文字起こしできませんでした",+ "show_more": "さらに表示"+ }}}diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex ea12cf524c..2f6e9ac210 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -178,5 +178,49 @@"clear_filter": "필터 지우기","no_matches": "일치하는 행이 없습니다","close": "닫기"+ },+ "voice": {+ "dictate": "음성 입력",+ "hold_to_talk": "누르고 말하기",+ "tap_or_hold": "음성 입력 (탭하거나 길게 눌러 말하기)",+ "cancel": "취소",+ "insert": "삽입",+ "send": "보내기",+ "retry": "다시 시도",+ "dismiss": "닫기",+ "requesting": "마이크를 기다리는 중…",+ "transcribing": "받아쓰는 중…",+ "release_to_insert": "손을 떼면 삽입",+ "recording": "녹음 중",+ "errors": {+ "permission_denied": "마이크 접근이 차단되어 있습니다. 브라우저나 시스템 설정에서 허용한 뒤 다시 시도하세요.",+ "no_microphone": "마이크를 찾을 수 없습니다. 연결한 뒤 다시 시도하세요.",+ "microphone_failed": "마이크를 시작할 수 없습니다.",+ "no_speech": "말소리를 듣지 못했습니다. 마이크에 조금 더 가까이에서 다시 시도하세요.",+ "unavailable": "이 컴퓨터에서는 음성을 받아쓸 수 없습니다.",+ "transcription_failed": "받아쓰기에 실패했습니다. 녹음은 보관되어 있으니 다시 시도할 수 있습니다."+ },+ "models": {+ "more_languages": "그 외 {{more}}개 언어",+ "in_use": "사용 중",+ "recommended": "추천",+ "most_accurate": "가장 정확함",+ "fastest": "가장 빠름",+ "by": "제공: {{author}}",+ "license": "라이선스",+ "downloading": "다운로드 중 {{percent}}%",+ "failed": "다운로드에 실패했습니다. 다시 시도하면 중단된 지점부터 이어서 받습니다.",+ "download": "다운로드",+ "retry": "다시 시도",+ "cancel": "취소",+ "use": "사용",+ "delete": "{{name}} 삭제"+ },+ "setup": {+ "title": "음성 입력 설정",+ "description": "음성은 이 컴퓨터에서 받아쓰므로 녹음이 외부로 나가지 않습니다. 먼저 음성 모델을 한 번 다운로드하세요.",+ "later": "나중에",+ "start": "받아쓰기 시작"+ }}}diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex b9f071e545..e07b5d6460 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -484,6 +484,10 @@"goSettings": {"label": "설정으로 이동","description": "워크스페이스 설정을 엽니다."+ },+ "voiceInput": {+ "label": "음성 입력",+ "description": "마지막으로 사용한 입력란에 받아쓰기합니다. 길게 눌러 말합니다."}},"fixed": {@@ -580,7 +584,8 @@"code": "코드","channels": "메신저","apps": "연결된 앱",- "workflows": "워크플로"+ "workflows": "워크플로",+ "voice_input": "음성 입력"},"groups": {"personal": "개인",@@ -1832,5 +1837,100 @@"admin_required": "워크스페이스 관리자가 제한을 해제할 수 있습니다.","account_link": "이 계정에 저장된 작업 제한이 있습니다. 연결된 앱에서 해제하세요."}+ },+ "voice_input": {+ "description": "채팅, 댓글, 답글을 말로 입력합니다. 음성은 이 컴퓨터에서 받아쓰며 외부로 나가지 않습니다.",+ "model_title": "음성 모델",+ "model_hint": "모델은 이 컴퓨터에서 실행됩니다. 하나를 다운로드하거나 받은 모델 사이에서 전환하세요.",+ "engine_unavailable": "이 컴퓨터에서는 기기 내 받아쓰기를 사용할 수 없습니다.",+ "input_title": "입력",+ "shortcut": {+ "title": "단축키",+ "hint": "화면에 입력란이 있으면 포커스가 없어도 동작합니다.",+ "change": "변경",+ "unassigned": "설정 안 됨"+ },+ "activation": {+ "title": "실행 방식",+ "auto": "탭 또는 길게 누르기",+ "toggle": "탭",+ "hold": "길게 누르기",+ "hints": {+ "auto": "탭하면 시작, 다시 탭하면 삽입. 길게 눌러 말하고 손을 떼면 삽입.",+ "toggle": "탭하면 시작, 다시 탭하면 삽입.",+ "hold": "길게 눌러 말하고 손을 떼면 삽입."+ }+ },+ "recognition_title": "인식",+ "language": {+ "title": "말하는 언어",+ "hint": "대부분은 자동 감지로 충분합니다. 짧은 문장이 다른 언어로 인식되면 언어를 지정하세요.",+ "auto": "자동 감지"+ },+ "fillers": {+ "title": "군말 제거",+ "hint": "“음”, “어” 같은 머뭇거림을 지웁니다."+ },+ "vocabulary": {+ "title": "어휘",+ "hint": "제품명이나 동료 이름처럼 원하는 표기로 적고 싶은 이름과 용어. 최대 {{max}}개.",+ "placeholder": "단어 추가",+ "remove": "{{word}} 삭제"+ },+ "microphone_title": "마이크",+ "device": {+ "title": "입력 장치",+ "default": "시스템 기본값",+ "unnamed": "마이크 {{index}}",+ "permission_hint": "마이크를 한 번 테스트하면 장치 이름이 표시됩니다."+ },+ "test": {+ "title": "마이크 테스트",+ "hint": "말해서 음량을 확인하세요. 녹음되지 않습니다.",+ "blocked": "마이크 접근이 차단되어 있습니다. 브라우저나 시스템 설정에서 허용하세요.",+ "start": "테스트",+ "stop": "중지"+ },+ "history": {+ "title": "기록",+ "description": "녹음과 텍스트는 이 컴퓨터에만 저장되며 업로드되지 않습니다. 실패하거나 중단된 녹음은 원본 오디오로 다시 변환할 수 있습니다.",+ "keep": {+ "title": "기록 보관",+ "hint": "녹음을 이 컴퓨터에 보관하는 기간입니다.",+ "options": {+ "off": "보관 안 함",+ "1d": "1일",+ "7d": "7일",+ "30d": "30일",+ "forever": "계속"+ }+ },+ "clear": "모두 지우기",+ "clear_dialog": {+ "title": "음성 기록을 지울까요?",+ "description": "이 컴퓨터에 보관된 모든 녹음과 텍스트가 삭제됩니다.",+ "cancel": "취소"+ },+ "empty": "음성 입력 기록이 여기에 표시됩니다.",+ "off": "기록이 꺼져 있습니다. 새 녹음은 보관되지 않습니다.",+ "today": "오늘",+ "yesterday": "어제",+ "status": {+ "transcribing": "변환 중…",+ "failed": "변환 실패",+ "interrupted": "변환 전에 중단됨"+ },+ "actions": {+ "play": "녹음 재생",+ "pause": "일시 정지",+ "retranscribe": "다시 변환",+ "copy": "텍스트 복사",+ "delete": "삭제"+ },+ "copied": "복사됨",+ "copy_failed": "복사하지 못했습니다",+ "retry_failed": "이 녹음을 변환하지 못했습니다",+ "show_more": "더 보기"+ }}}diff --git a/packages/views/locales/ru/editor.json b/packages/views/locales/ru/editor.jsonindex 05621c2bbb..aae93109d1 100644--- a/packages/views/locales/ru/editor.json+++ b/packages/views/locales/ru/editor.json@@ -190,5 +190,49 @@"clear_filter": "Сбросить фильтр","no_matches": "Подходящих строк нет","close": "Закрыть"+ },+ "voice": {+ "dictate": "Диктовать",+ "hold_to_talk": "Удерживайте, чтобы говорить",+ "tap_or_hold": "Диктовать (нажмите или удерживайте, чтобы говорить)",+ "cancel": "Отмена",+ "insert": "Вставить",+ "send": "Отправить",+ "retry": "Повторить",+ "dismiss": "Закрыть",+ "requesting": "Ожидание микрофона…",+ "transcribing": "Расшифровка…",+ "release_to_insert": "Отпустите, чтобы вставить",+ "recording": "Запись",+ "errors": {+ "permission_denied": "Доступ к микрофону заблокирован. Разрешите его в браузере или в настройках системы и повторите попытку.",+ "no_microphone": "Микрофон не найден. Подключите его и повторите попытку.",+ "microphone_failed": "Не удалось включить микрофон.",+ "no_speech": "Речь не распознана. Попробуйте ещё раз ближе к микрофону.",+ "unavailable": "На этом компьютере голосовой ввод не может расшифровывать речь.",+ "transcription_failed": "Не удалось расшифровать запись. Она сохранена, можно повторить."+ },+ "models": {+ "more_languages": "ещё {{more}}",+ "in_use": "Используется",+ "recommended": "Рекомендуется",+ "most_accurate": "Самая точная",+ "fastest": "Самая быстрая",+ "by": "Автор: {{author}}",+ "license": "Лицензия",+ "downloading": "Загрузка, {{percent}}%",+ "failed": "Загрузка не удалась. Повторите — она продолжится с места остановки.",+ "download": "Скачать",+ "retry": "Повторить",+ "cancel": "Отмена",+ "use": "Использовать",+ "delete": "Удалить {{name}}"+ },+ "setup": {+ "title": "Настройка голосового ввода",+ "description": "Речь расшифровывается на этом компьютере, поэтому записи никуда не отправляются. Чтобы начать, один раз скачайте речевую модель.",+ "later": "Не сейчас",+ "start": "Начать диктовку"+ }}}diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 29c3443ae4..4adffcafc0 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -501,6 +501,10 @@"goSettings": {"label": "Перейти в настройки","description": "Открыть настройки рабочего пространства."+ },+ "voiceInput": {+ "label": "Голосовой ввод",+ "description": "Диктовка в последнее использованное поле ввода. Удерживайте, чтобы говорить."}},"fixed": {@@ -597,7 +601,8 @@"code": "Код","channels": "Мессенджеры","apps": "Подключённые приложения",- "workflows": "Рабочие процессы"+ "workflows": "Рабочие процессы",+ "voice_input": "Голосовой ввод"},"groups": {"personal": "Личное",@@ -1894,5 +1899,100 @@"admin_required": "Администратор может восстановить доступ.","account_link": "У этого аккаунта сохранились ограничения. Восстановите доступ в подключённых приложениях."}+ },+ "voice_input": {+ "description": "Диктуйте в чат, комментарии и ответы. Речь расшифровывается на этом компьютере и никуда не отправляется.",+ "model_title": "Речевая модель",+ "model_hint": "Модели работают на этом компьютере. Скачайте модель или переключайтесь между скачанными.",+ "engine_unavailable": "Расшифровка на устройстве недоступна на этом компьютере.",+ "input_title": "Ввод",+ "shortcut": {+ "title": "Сочетание клавиш",+ "hint": "Работает, когда на экране есть поле ввода, даже без фокуса.",+ "change": "Изменить",+ "unassigned": "Не задано"+ },+ "activation": {+ "title": "Активация",+ "auto": "Нажатие или удержание",+ "toggle": "Нажатие",+ "hold": "Удержание",+ "hints": {+ "auto": "Нажмите, чтобы начать, и ещё раз, чтобы вставить. Удерживайте, чтобы говорить, отпустите, чтобы вставить.",+ "toggle": "Нажмите, чтобы начать, и ещё раз, чтобы вставить.",+ "hold": "Удерживайте, чтобы говорить, отпустите, чтобы вставить."+ }+ },+ "recognition_title": "Распознавание",+ "language": {+ "title": "Язык речи",+ "hint": "Автоопределение подходит в большинстве случаев. Выберите язык, если короткие фразы распознаются как другой.",+ "auto": "Автоопределение"+ },+ "fillers": {+ "title": "Убирать слова-паразиты",+ "hint": "Удаляет «э-э», «м-м» и подобные запинки."+ },+ "vocabulary": {+ "title": "Словарь",+ "hint": "Имена и термины, которые нужно писать по-вашему, например названия продуктов или имена коллег. До {{max}}.",+ "placeholder": "Добавить слово",+ "remove": "Удалить {{word}}"+ },+ "microphone_title": "Микрофон",+ "device": {+ "title": "Устройство ввода",+ "default": "По умолчанию в системе",+ "unnamed": "Микрофон {{index}}",+ "permission_hint": "Проверьте микрофон один раз, чтобы увидеть названия устройств."+ },+ "test": {+ "title": "Проверить микрофон",+ "hint": "Говорите, чтобы проверить уровень. Ничего не записывается.",+ "blocked": "Доступ к микрофону заблокирован. Разрешите его в браузере или в настройках системы.",+ "start": "Проверить",+ "stop": "Остановить"+ },+ "history": {+ "title": "История",+ "description": "Записи и их текст хранятся только на этом компьютере и никуда не отправляются. Запись, которую не удалось расшифровать или которая была прервана, можно расшифровать заново по исходному аудио.",+ "keep": {+ "title": "Хранить историю",+ "hint": "Сколько записи хранятся на этом компьютере.",+ "options": {+ "off": "Не хранить",+ "1d": "1 день",+ "7d": "7 дней",+ "30d": "30 дней",+ "forever": "Всегда"+ }+ },+ "clear": "Очистить всё",+ "clear_dialog": {+ "title": "Очистить историю голосового ввода?",+ "description": "Все записи и расшифровки на этом компьютере будут удалены.",+ "cancel": "Отмена"+ },+ "empty": "Здесь появятся ваши диктовки.",+ "off": "История отключена. Новые записи не сохраняются.",+ "today": "Сегодня",+ "yesterday": "Вчера",+ "status": {+ "transcribing": "Расшифровка…",+ "failed": "Не удалось расшифровать",+ "interrupted": "Прервано до расшифровки"+ },+ "actions": {+ "play": "Воспроизвести запись",+ "pause": "Пауза",+ "retranscribe": "Расшифровать заново",+ "copy": "Копировать текст",+ "delete": "Удалить"+ },+ "copied": "Скопировано",+ "copy_failed": "Не удалось скопировать",+ "retry_failed": "Не удалось расшифровать эту запись",+ "show_more": "Показать ещё"+ }}}diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex b45fbad958..4cc0e04447 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -178,5 +178,49 @@"clear_filter": "清除筛选","no_matches": "没有匹配的行","close": "关闭"+ },+ "voice": {+ "dictate": "语音输入",+ "hold_to_talk": "按住说话",+ "tap_or_hold": "语音输入(点按,或按住说话)",+ "cancel": "取消",+ "insert": "插入",+ "send": "发送",+ "retry": "重试",+ "dismiss": "关闭",+ "requesting": "正在等待麦克风…",+ "transcribing": "正在转写…",+ "release_to_insert": "松开插入",+ "recording": "录音中",+ "errors": {+ "permission_denied": "麦克风权限被阻止。请在浏览器或系统设置中允许后重试。",+ "no_microphone": "未找到麦克风。连接后重试。",+ "microphone_failed": "无法启动麦克风。",+ "no_speech": "没有听到说话声。靠近麦克风再试一次。",+ "unavailable": "这台电脑无法在本地转写语音。",+ "transcription_failed": "转写失败。录音已保留,可以重试。"+ },+ "models": {+ "more_languages": "其他 {{more}} 种语言",+ "in_use": "使用中",+ "recommended": "推荐",+ "most_accurate": "最准确",+ "fastest": "最快",+ "by": "来自 {{author}}",+ "license": "许可协议",+ "downloading": "正在下载,{{percent}}%",+ "failed": "下载失败。重试会从中断处继续。",+ "download": "下载",+ "retry": "重试",+ "cancel": "取消",+ "use": "使用",+ "delete": "删除 {{name}}"+ },+ "setup": {+ "title": "设置语音输入",+ "description": "语音在这台电脑上转写,录音不会离开本机。先下载一个语音模型即可开始。",+ "later": "以后再说",+ "start": "开始口述"+ }}}diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 47fd0f62b2..ddc78bcdac 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -484,6 +484,10 @@"goSettings": {"label": "前往设置","description": "打开工作区设置。"+ },+ "voiceInput": {+ "label": "语音输入",+ "description": "向最近使用的输入框口述。按住说话。"}},"fixed": {@@ -580,7 +584,8 @@"code": "代码","channels": "消息渠道","apps": "已连接应用",- "workflows": "工作流"+ "workflows": "工作流",+ "voice_input": "语音输入"},"groups": {"personal": "个人",@@ -1832,5 +1837,100 @@"admin_required": "请工作区管理员解除限制。","account_link": "此账号仍有旧操作限制。请在已连接应用中解除。"}+ },+ "voice_input": {+ "description": "在对话、评论和回复中口述输入。语音在这台电脑上转写,不会离开本机。",+ "model_title": "语音模型",+ "model_hint": "模型在这台电脑上运行。下载一个,或在已下载的模型之间切换。",+ "engine_unavailable": "这台电脑暂不支持本地语音转写。",+ "input_title": "输入",+ "shortcut": {+ "title": "快捷键",+ "hint": "只要页面上有输入框就能使用,无需先聚焦。",+ "change": "修改",+ "unassigned": "未设置"+ },+ "activation": {+ "title": "触发方式",+ "auto": "点按或按住",+ "toggle": "点按",+ "hold": "按住",+ "hints": {+ "auto": "点按开始,再点一次插入。按住说话,松开插入。",+ "toggle": "点按开始,再点一次插入。",+ "hold": "按住说话,松开插入。"+ }+ },+ "recognition_title": "识别",+ "language": {+ "title": "说话语言",+ "hint": "自动检测适用于大多数情况。如果短句被识别成了别的语言,可以指定语言。",+ "auto": "自动检测"+ },+ "fillers": {+ "title": "去除语气词",+ "hint": "去掉“嗯”“呃”等停顿词。"+ },+ "vocabulary": {+ "title": "词汇表",+ "hint": "希望按你的写法输出的名称和术语,例如产品名或同事名字。最多 {{max}} 个。",+ "placeholder": "添加词语",+ "remove": "移除 {{word}}"+ },+ "microphone_title": "麦克风",+ "device": {+ "title": "输入设备",+ "default": "系统默认",+ "unnamed": "麦克风 {{index}}",+ "permission_hint": "测试一次麦克风后即可看到设备名称。"+ },+ "test": {+ "title": "测试麦克风",+ "hint": "说几句话查看音量。不会录音。",+ "blocked": "麦克风权限被阻止。请在浏览器或系统设置中允许。",+ "start": "测试",+ "stop": "停止"+ },+ "history": {+ "title": "历史记录",+ "description": "录音和转写文字只保存在这台电脑上,不会上传。转写失败或被中断的录音可以用原始音频重新转写。",+ "keep": {+ "title": "保留历史记录",+ "hint": "录音在这台电脑上保留多久。",+ "options": {+ "off": "不保留",+ "1d": "1 天",+ "7d": "7 天",+ "30d": "30 天",+ "forever": "永久"+ }+ },+ "clear": "全部清除",+ "clear_dialog": {+ "title": "清除语音历史记录?",+ "description": "这台电脑上保存的所有录音和转写文字都会被删除。",+ "cancel": "取消"+ },+ "empty": "你的语音输入会显示在这里。",+ "off": "历史记录已关闭,新的录音不会被保留。",+ "today": "今天",+ "yesterday": "昨天",+ "status": {+ "transcribing": "转写中…",+ "failed": "转写失败",+ "interrupted": "转写前被中断"+ },+ "actions": {+ "play": "播放录音",+ "pause": "暂停",+ "retranscribe": "重新转写",+ "copy": "复制文字",+ "delete": "删除"+ },+ "copied": "已复制",+ "copy_failed": "复制失败",+ "retry_failed": "这段录音转写失败",+ "show_more": "显示更多"+ }}}diff --git a/packages/views/locales/zh-Hant/editor.json b/packages/views/locales/zh-Hant/editor.jsonindex 61f1ddd93f..b74419d23a 100644--- a/packages/views/locales/zh-Hant/editor.json+++ b/packages/views/locales/zh-Hant/editor.json@@ -178,5 +178,49 @@"clear_filter": "清除篩選","no_matches": "沒有匹配的行","close": "關閉"+ },+ "voice": {+ "dictate": "語音輸入",+ "hold_to_talk": "按住說話",+ "tap_or_hold": "語音輸入(點按,或按住說話)",+ "cancel": "取消",+ "insert": "插入",+ "send": "傳送",+ "retry": "重試",+ "dismiss": "關閉",+ "requesting": "正在等待麥克風…",+ "transcribing": "正在轉寫…",+ "release_to_insert": "放開插入",+ "recording": "錄音中",+ "errors": {+ "permission_denied": "麥克風權限被封鎖。請在瀏覽器或系統設定中允許後重試。",+ "no_microphone": "找不到麥克風。連接後重試。",+ "microphone_failed": "無法啟動麥克風。",+ "no_speech": "沒有聽到說話聲。靠近麥克風再試一次。",+ "unavailable": "這台電腦無法在本機轉寫語音。",+ "transcription_failed": "轉寫失敗。錄音已保留,可以重試。"+ },+ "models": {+ "more_languages": "其他 {{more}} 種語言",+ "in_use": "使用中",+ "recommended": "推薦",+ "most_accurate": "最準確",+ "fastest": "最快",+ "by": "來自 {{author}}",+ "license": "授權條款",+ "downloading": "正在下載,{{percent}}%",+ "failed": "下載失敗。重試會從中斷處繼續。",+ "download": "下載",+ "retry": "重試",+ "cancel": "取消",+ "use": "使用",+ "delete": "刪除 {{name}}"+ },+ "setup": {+ "title": "設定語音輸入",+ "description": "語音在這台電腦上轉寫,錄音不會離開本機。先下載一個語音模型即可開始。",+ "later": "稍後再說",+ "start": "開始口述"+ }}}diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex c999c4c75e..09155e042a 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -484,6 +484,10 @@"goSettings": {"label": "前往設定","description": "開啟工作區設定。"+ },+ "voiceInput": {+ "label": "語音輸入",+ "description": "向最近使用的輸入框口述。按住說話。"}},"fixed": {@@ -580,7 +584,8 @@"code": "程式碼","channels": "訊息渠道","apps": "已連線應用",- "workflows": "工作流"+ "workflows": "工作流",+ "voice_input": "語音輸入"},"groups": {"personal": "個人",@@ -1832,5 +1837,100 @@"admin_required": "請工作區管理員解除限制。","account_link": "此帳號仍有舊操作限制。請在已連接應用中解除。"}+ },+ "voice_input": {+ "description": "在對話、留言和回覆中口述輸入。語音在這台電腦上轉寫,不會離開本機。",+ "model_title": "語音模型",+ "model_hint": "模型在這台電腦上執行。下載一個,或在已下載的模型之間切換。",+ "engine_unavailable": "這台電腦暫不支援本機語音轉寫。",+ "input_title": "輸入",+ "shortcut": {+ "title": "快捷鍵",+ "hint": "只要頁面上有輸入框就能使用,不需要先聚焦。",+ "change": "修改",+ "unassigned": "未設定"+ },+ "activation": {+ "title": "觸發方式",+ "auto": "點按或按住",+ "toggle": "點按",+ "hold": "按住",+ "hints": {+ "auto": "點按開始,再點一次插入。按住說話,放開插入。",+ "toggle": "點按開始,再點一次插入。",+ "hold": "按住說話,放開插入。"+ }+ },+ "recognition_title": "辨識",+ "language": {+ "title": "說話語言",+ "hint": "自動偵測適用於大多數情況。如果短句被辨識成其他語言,可以指定語言。",+ "auto": "自動偵測"+ },+ "fillers": {+ "title": "移除語助詞",+ "hint": "去掉「嗯」「呃」等停頓詞。"+ },+ "vocabulary": {+ "title": "詞彙表",+ "hint": "希望按你的寫法輸出的名稱和術語,例如產品名稱或同事名字。最多 {{max}} 個。",+ "placeholder": "新增詞語",+ "remove": "移除 {{word}}"+ },+ "microphone_title": "麥克風",+ "device": {+ "title": "輸入裝置",+ "default": "系統預設",+ "unnamed": "麥克風 {{index}}",+ "permission_hint": "測試一次麥克風後即可看到裝置名稱。"+ },+ "test": {+ "title": "測試麥克風",+ "hint": "說幾句話查看音量。不會錄音。",+ "blocked": "麥克風權限被封鎖。請在瀏覽器或系統設定中允許。",+ "start": "測試",+ "stop": "停止"+ },+ "history": {+ "title": "歷史記錄",+ "description": "錄音和轉寫文字只保存在這台電腦上,不會上傳。轉寫失敗或被中斷的錄音可以用原始音訊重新轉寫。",+ "keep": {+ "title": "保留歷史記錄",+ "hint": "錄音在這台電腦上保留多久。",+ "options": {+ "off": "不保留",+ "1d": "1 天",+ "7d": "7 天",+ "30d": "30 天",+ "forever": "永久"+ }+ },+ "clear": "全部清除",+ "clear_dialog": {+ "title": "清除語音歷史記錄?",+ "description": "這台電腦上保存的所有錄音和轉寫文字都會被刪除。",+ "cancel": "取消"+ },+ "empty": "你的語音輸入會顯示在這裡。",+ "off": "歷史記錄已關閉,新的錄音不會被保留。",+ "today": "今天",+ "yesterday": "昨天",+ "status": {+ "transcribing": "轉寫中…",+ "failed": "轉寫失敗",+ "interrupted": "轉寫前被中斷"+ },+ "actions": {+ "play": "播放錄音",+ "pause": "暫停",+ "retranscribe": "重新轉寫",+ "copy": "複製文字",+ "delete": "刪除"+ },+ "copied": "已複製",+ "copy_failed": "複製失敗",+ "retry_failed": "這段錄音轉寫失敗",+ "show_more": "顯示更多"+ }}}diff --git a/packages/views/modals/create-issue-batch-continuation.test.tsx b/packages/views/modals/create-issue-batch-continuation.test.tsxindex cb5ba32826..1c40f2f1c0 100644--- a/packages/views/modals/create-issue-batch-continuation.test.tsx+++ b/packages/views/modals/create-issue-batch-continuation.test.tsx@@ -5,6 +5,18 @@ import { forwardRef, useImperativeHandle, useRef, useState, type ReactNode } froimport { beforeEach, describe, expect, it, vi } from "vitest";import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";+type VoiceOptions = { insert: (text: string) => boolean; submit?: () => void };+const voiceOptions = vi.hoisted(() => ({ last: null as VoiceOptions | null }));++// Voice input has its own tests; here only its wiring to the editor matters.+vi.mock("../voice", () => ({+ useComposerVoice: (options: VoiceOptions) => {+ voiceOptions.last = options;+ return { rootRef: () => {}, onFocusCapture: () => {} };+ },+ VoiceDialogFooter: ({ children }: { children: ReactNode }) => children,+ VoiceMicButton: () => null,+}));import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsxindex ad1b258519..8585e38d44 100644--- a/packages/views/modals/create-issue.test.tsx+++ b/packages/views/modals/create-issue.test.tsx@@ -34,6 +34,18 @@ function I18nWrapper({ children }: { children: ReactNode }) {const mockParentIssue = vi.hoisted(() => ({ value: null as Issue | null }));const mockPush = vi.hoisted(() => vi.fn());const mockCreateIssue = vi.hoisted(() => vi.fn());+type VoiceOptions = { insert: (text: string) => boolean; submit?: () => void };+const voiceOptions = vi.hoisted(() => ({ last: null as VoiceOptions | null }));++// Voice input has its own tests; here only its wiring to the editor matters.+vi.mock("../voice", () => ({+ useComposerVoice: (options: VoiceOptions) => {+ voiceOptions.last = options;+ return { rootRef: () => {}, onFocusCapture: () => {} };+ },+ VoiceDialogFooter: ({ children }: { children: ReactNode }) => children,+ VoiceMicButton: () => null,+}));const mockCreateCommentSubIssue = vi.hoisted(() => vi.fn());const mockAttachLabel = vi.hoisted(() => vi.fn());const mockListProperties = vi.hoisted(() => vi.fn());@@ -389,6 +401,12 @@ vi.mock("../editor", async () => {if (inFlightRef.current === 0) onUploadingChange?.(false);}},+ insertText: (text: string) => {+ valueRef.current += text;+ setValue(valueRef.current);+ onUpdate?.(valueRef.current);+ return true;+ },hasActiveUploads: () => inFlightRef.current > 0,// Placeholder rebuild contract: the real handle draws a card for an// upload the document is not showing and reports whether it landed.@@ -803,6 +821,21 @@ describe("CreateIssueModal", () => {}));});+ it("dictates into the description and leaves creating to the button", async () => {+ const user = userEvent.setup();+ mockDraftStore.draft.manual.title = "Voice issue";+ mockDraftStore.draft.manual.description = "Steps:";+ renderModal(<CreateIssueModal onClose={vi.fn()} />);+ expect(voiceOptions.last?.submit).toBeUndefined();+ act(() => {+ expect(voiceOptions.last?.insert(" open the inbox")).toBe(true);+ });+ await user.click(screen.getByRole("button", { name: "Create Issue" }));+ expect(mockCreateIssue).toHaveBeenCalledWith(expect.objectContaining({+ title: "Voice issue", description: "Steps: open the inbox",+ }));+ });+it("uses the same compact attachment control as agent mode", () => {renderModal(<CreateIssueModal onClose={vi.fn()} />);diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex 6ea8216003..e2e516b8bd 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -91,6 +91,7 @@ import {import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { BorderBeam } from "@multica/ui/components/common/border-beam";import { ClearablePillButton, PillButton } from "../common/pill-button";+import { useComposerVoice, VoiceDialogFooter, VoiceMicButton } from "../voice";import { ActorAvatar } from "../common/actor-avatar";import { PropertyIcon } from "../common/property-icon";import {@@ -277,6 +278,11 @@ export function ManualCreatePanel({const [formResetKey, setFormResetKey] = useState(0);const titleEditorRef = useRef<TitleEditorRef>(null);const descEditorRef = useRef<ContentEditorRef>(null);+ // Dictation lands in the description. No send from the strip: creating+ // needs a title, which voice does not fill.+ const voice = useComposerVoice({+ insert: (text) => descEditorRef.current?.insertText(text) ?? false,+ });const { isDragOver: descDragOver, dropZoneProps: descDropZoneProps } = useFileDropZone({onDrop: (files) => files.forEach((f) => descEditorRef.current?.uploadFile(f)),});@@ -1025,7 +1031,7 @@ export function ManualCreatePanel({</div>{/* Title */}- <div className="px-5 pb-2 shrink-0">+ <div className="px-5 pb-2 shrink-0" onFocusCapture={voice.onFocusCapture}><TitleEditorkey={formResetKey}ref={titleEditorRef}@@ -1040,7 +1046,12 @@ export function ManualCreatePanel({</div>{/* Description — takes remaining space */}- <div {...descDropZoneProps} className="relative flex flex-1 min-h-0 overflow-y-auto px-5">+ <div+ {...descDropZoneProps}+ ref={voice.rootRef}+ onFocusCapture={voice.onFocusCapture}+ className="relative flex flex-1 min-h-0 overflow-y-auto px-5"+ ><ContentEditorref={descEditorRef}defaultValue={draft.manual.description}@@ -1497,48 +1508,51 @@ export function ManualCreatePanel({for why (MUL-6236). Tooltip renders no DOM andTooltipContent is portaled, so the Create button stays a directgrid child in both branches below. */}- <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-2.5 border-t px-4 py-3 shrink-0 sm:flex sm:flex-wrap">- <div className="flex min-h-7 items-center gap-2 sm:mr-auto">- <FileUploadButton- size="sm"- multiple- onSelect={(file) => descEditorRef.current?.uploadFile(file)}- />+ <VoiceDialogFooter voice={voice}>+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-2.5 border-t px-4 py-3 shrink-0 sm:flex sm:flex-wrap">+ <div className="flex min-h-7 items-center gap-2 sm:mr-auto">+ <FileUploadButton+ size="sm"+ multiple+ onSelect={(file) => descEditorRef.current?.uploadFile(file)}+ />+ <VoiceMicButton voice={voice} />+ </div>+ <TooltipHint label={t(($) => $.create_issue.switch_to_agent_tooltip)}>+ <button+ type="button"+ onClick={switchToAgent}+ disabled={gate.uploading}+ aria-disabled={gate.uploading || undefined}+ aria-busy={gate.uploading || undefined}+ className="relative group flex shrink-0 items-center gap-1.5 justify-self-end text-caption px-2 py-1 rounded-sm text-muted-foreground bg-brand/5 hover:bg-brand/10 hover:text-foreground transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"+ >+ <ArrowLeftRight className="size-3.5 text-brand transition-transform duration-300 group-hover:rotate-180" />+ {t(($) => $.create_issue.switch_to_agent)}+ <BorderBeam />+ </button>+ </TooltipHint>+ <label className="flex shrink-0 items-center gap-1.5 text-caption text-muted-foreground cursor-pointer select-none">+ <Switch+ size="sm"+ checked={keepOpen}+ onCheckedChange={setKeepOpen}+ />+ {t(($) => $.create_issue.create_another)}+ </label>+ {submitState === "missing_title" ? (+ <Tooltip>+ {/* No `<span>` wrapper needed now: aria-disabled leaves the+ button focusable and hoverable, so it can anchor its own+ tooltip. */}+ <TooltipTrigger render={createButton} />+ <TooltipContent side="top">{t(($) => $.create_issue.title_required)}</TooltipContent>+ </Tooltip>+ ) : (+ createButton+ )}</div>- <TooltipHint label={t(($) => $.create_issue.switch_to_agent_tooltip)}>- <button- type="button"- onClick={switchToAgent}- disabled={gate.uploading}- aria-disabled={gate.uploading || undefined}- aria-busy={gate.uploading || undefined}- className="relative group flex shrink-0 items-center gap-1.5 justify-self-end text-caption px-2 py-1 rounded-sm text-muted-foreground bg-brand/5 hover:bg-brand/10 hover:text-foreground transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"- >- <ArrowLeftRight className="size-3.5 text-brand transition-transform duration-300 group-hover:rotate-180" />- {t(($) => $.create_issue.switch_to_agent)}- <BorderBeam />- </button>- </TooltipHint>- <label className="flex shrink-0 items-center gap-1.5 text-caption text-muted-foreground cursor-pointer select-none">- <Switch- size="sm"- checked={keepOpen}- onCheckedChange={setKeepOpen}- />- {t(($) => $.create_issue.create_another)}- </label>- {submitState === "missing_title" ? (- <Tooltip>- {/* No `<span>` wrapper needed now: aria-disabled leaves the- button focusable and hoverable, so it can anchor its own- tooltip. */}- <TooltipTrigger render={createButton} />- <TooltipContent side="top">{t(($) => $.create_issue.title_required)}</TooltipContent>- </Tooltip>- ) : (- createButton- )}- </div>+ </VoiceDialogFooter></>);}diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsxindex b0933f1c1c..54c26852e1 100644--- a/packages/views/modals/quick-create-issue.test.tsx+++ b/packages/views/modals/quick-create-issue.test.tsx@@ -12,6 +12,18 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"import userEvent from "@testing-library/user-event";const mockQuickCreateIssue = vi.hoisted(() => vi.fn());+type VoiceOptions = { insert: (text: string) => boolean; submit?: () => void };+const voiceOptions = vi.hoisted(() => ({ last: null as VoiceOptions | null }));++// Voice input has its own tests; here only its wiring to the editor matters.+vi.mock("../voice", () => ({+ useComposerVoice: (options: VoiceOptions) => {+ voiceOptions.last = options;+ return { rootRef: () => {}, onFocusCapture: () => {} };+ },+ VoiceDialogFooter: ({ children }: { children: ReactNode }) => children,+ VoiceMicButton: () => null,+}));const mockCreateCommentSubIssue = vi.hoisted(() => vi.fn());const mockSetLastActor = vi.hoisted(() => vi.fn());const mockSetQuickCreateFieldVisible = vi.hoisted(() => vi.fn());@@ -361,6 +373,12 @@ vi.mock("../editor", async () => {},uploadFile: runUpload,focus: vi.fn(),+ insertText: (text: string) => {+ valueRef.current += text;+ setValue(valueRef.current);+ onUpdate?.(valueRef.current);+ return true;+ },hasActiveUploads: () => inFlightRef.current > 0,// Placeholder rebuild contract: the real handle draws a card for an// upload the document is not showing and reports whether it landed.@@ -686,6 +704,20 @@ describe("AgentCreatePanel", () => {expect(onClose).toHaveBeenCalled();});+ it("dictates into the prompt and lets voice send it to the agent", async () => {+ renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });+ act(() => {+ expect(voiceOptions.last?.insert("fix the inbox")).toBe(true);+ });+ expect(mockSetAgent).toHaveBeenLastCalledWith({ prompt: expect.stringContaining("fix the inbox") });+ act(() => voiceOptions.last?.submit?.());+ await waitFor(() => {+ expect(mockQuickCreateIssue).toHaveBeenCalledWith(+ expect.objectContaining({ agent_id: "agent-1", prompt: expect.stringContaining("fix the inbox") }),+ );+ });+ });+it("shows the upgrade recovery immediately when quick create is rejected by the issue preflight", async () => {const user = userEvent.setup();const onClose = vi.fn();diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsxindex 044bedc6ff..a1517e3422 100644--- a/packages/views/modals/quick-create-issue.tsx+++ b/packages/views/modals/quick-create-issue.tsx@@ -62,6 +62,7 @@ import {} from "@multica/core/types";import { ActorAvatar } from "../common/actor-avatar";import { ClearablePillButton, PillButton } from "../common/pill-button";+import { useComposerVoice, VoiceDialogFooter, VoiceMicButton } from "../voice";import { ProjectPicker } from "../projects/components/project-picker";import { DueDatePicker, PriorityIcon, PriorityPicker } from "../issues/components";import { canAssignAgent } from "../issues/components/pickers/assignee-picker";@@ -594,6 +595,11 @@ export function AgentCreatePanel({void composer.submit();};const submitting = composer.submitting;+ const canCreate = !!actor && !versionBlocked && !qoderAttachmentBlocked && !(anchorCommentId && !sourcePreview);+ const voice = useComposerVoice({+ insert: (text) => editorRef.current?.insertText(text) ?? false,+ submit: canCreate ? submit : undefined,+ });// Switch to the manual form WITHOUT destroying the agent draft. The agent// slot (prompt + actor) is left untouched so a later manual→agent flip@@ -768,6 +774,8 @@ export function AgentCreatePanel({editor unbounded and pushed the modal past the viewport. */}<div{...dropZoneProps}+ ref={voice.rootRef}+ onFocusCapture={voice.onFocusCapture}className="relative px-5 pb-3 flex flex-1 min-h-[140px] overflow-y-auto"><ContentEditor@@ -938,54 +946,57 @@ export function AgentCreatePanel({attach group reproduces what `justify-between` did when thechildren were two wrapper divs, and `justify-self-end` goesinert on flex items. */}- <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-2.5 border-t px-4 py-3 shrink-0 sm:flex sm:flex-wrap">- <div className="flex min-h-7 items-center gap-2 sm:mr-auto">- {/* Deliberately NOT disabled while uploading: each file is its- own queue entry, so queueing a second one is safe and waiting- for the first to land just to attach the next is busywork. */}- <FileUploadButton- size="sm"- multiple- onSelect={(file) => editorRef.current?.uploadFile(file)}- />- {keepOpen && sentCount > 0 && (- <span className="text-caption text-emerald-600 dark:text-emerald-400">- {t(($) => $.create_issue.agent.sent_count, { count: sentCount })}- </span>+ <VoiceDialogFooter voice={voice}>+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-2.5 border-t px-4 py-3 shrink-0 sm:flex sm:flex-wrap">+ <div className="flex min-h-7 items-center gap-2 sm:mr-auto">+ {/* Deliberately NOT disabled while uploading: each file is its+ own queue entry, so queueing a second one is safe and waiting+ for the first to land just to attach the next is busywork. */}+ <FileUploadButton+ size="sm"+ multiple+ onSelect={(file) => editorRef.current?.uploadFile(file)}+ />+ <VoiceMicButton voice={voice} />+ {keepOpen && sentCount > 0 && (+ <span className="text-caption text-emerald-600 dark:text-emerald-400">+ {t(($) => $.create_issue.agent.sent_count, { count: sentCount })}+ </span>+ )}+ </div>+ <TooltipHint label={t(($) => $.create_issue.switch_to_manual_tooltip)}>+ <button+ type="button"+ onClick={switchToManual}+ disabled={gate.uploading}+ aria-disabled={gate.uploading || undefined}+ aria-busy={gate.uploading || undefined}+ className="flex shrink-0 items-center gap-1.5 justify-self-end text-caption px-2 py-1 rounded-sm text-muted-foreground hover:text-foreground hover:bg-accent/60 transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"+ >+ <ArrowLeftRight className="size-3.5" />+ {t(($) => $.create_issue.switch_to_manual)}+ </button>+ </TooltipHint>+ <label className="flex shrink-0 items-center gap-1.5 text-caption text-muted-foreground cursor-pointer select-none">+ <Switch+ size="sm"+ checked={keepOpen}+ onCheckedChange={setKeepOpen}+ />+ {t(($) => $.create_issue.create_another)}+ </label>+ {versionBlocked ? (+ <Tooltip>+ <TooltipTrigger render={createButton} />+ <TooltipContent side="top">+ {t(($) => $.create_issue.agent.version_blocked_tooltip, { min: versionCheck.min })}+ </TooltipContent>+ </Tooltip>+ ) : (+ createButton)}</div>- <TooltipHint label={t(($) => $.create_issue.switch_to_manual_tooltip)}>- <button- type="button"- onClick={switchToManual}- disabled={gate.uploading}- aria-disabled={gate.uploading || undefined}- aria-busy={gate.uploading || undefined}- className="flex shrink-0 items-center gap-1.5 justify-self-end text-caption px-2 py-1 rounded-sm text-muted-foreground hover:text-foreground hover:bg-accent/60 transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"- >- <ArrowLeftRight className="size-3.5" />- {t(($) => $.create_issue.switch_to_manual)}- </button>- </TooltipHint>- <label className="flex shrink-0 items-center gap-1.5 text-caption text-muted-foreground cursor-pointer select-none">- <Switch- size="sm"- checked={keepOpen}- onCheckedChange={setKeepOpen}- />- {t(($) => $.create_issue.create_another)}- </label>- {versionBlocked ? (- <Tooltip>- <TooltipTrigger render={createButton} />- <TooltipContent side="top">- {t(($) => $.create_issue.agent.version_blocked_tooltip, { min: versionCheck.min })}- </TooltipContent>- </Tooltip>- ) : (- createButton- )}- </div>+ </VoiceDialogFooter></>);}diff --git a/packages/views/package.json b/packages/views/package.jsonindex 44699f60a3..17cb01543e 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -73,6 +73,7 @@"./platform": "./platform/index.ts","./i18n": "./i18n/index.ts","./attachments": "./attachments/index.ts",+ "./voice": "./voice/index.ts","./locales": "./locales/index.ts","./locales/en": "./locales/en.ts","./locales/zh-Hans": "./locales/zh-Hans.ts",diff --git a/packages/views/platform/index.ts b/packages/views/platform/index.tsindex 1ec740c495..1fdf64eac9 100644--- a/packages/views/platform/index.ts+++ b/packages/views/platform/index.ts@@ -23,6 +23,10 @@ export {type ThemeFolderSnapshot,type ThemeFolderWriteResult,} from "./theme-folder";+export {+ localVoiceAPI,+ type LocalVoiceAPI,+} from "./local-voice";export {useLocalDaemonStatus,type LocalDaemonStatus,diff --git a/packages/views/platform/local-voice.ts b/packages/views/platform/local-voice.tsnew file mode 100644index 0000000000..7af7161821--- /dev/null+++ b/packages/views/platform/local-voice.ts@@ -0,0 +1,47 @@+// Desktop's on-device speech engine, through the preload `desktopAPI.voice`.+// Undefined on web and on Desktop builds that predate it.+import type { VoiceHistoryEntry, VoiceHistoryStatus, VoiceModels, VoiceTranscription } from "@multica/core/voice";++export interface LocalVoiceRequest {+ modelId: string;+ language: string;+ hotwords: string[];+}++export interface LocalVoiceHistoryAPI {+ /** Newest first. */+ list: () => Promise<VoiceHistoryEntry[]>;+ onChanged: (callback: () => void) => () => void;+ save: (request: {+ audio: Uint8Array;+ mimeType: string;+ durationMs: number;+ keepDays: number | null;+ }) => Promise<VoiceHistoryEntry | null>;+ update: (id: string, patch: { status: VoiceHistoryStatus; text?: string }) => Promise<void>;+ audio: (id: string) => Promise<{ audio: Uint8Array<ArrayBuffer>; mimeType: string } | null>;+ remove: (id: string) => Promise<void>;+ /** Remember how many days to keep (0 keeps none, null forever) and drop older entries now. */+ setRetention: (keepDays: number | null) => Promise<void>;+ /** Delete every entry, including one still being transcribed. */+ clear: () => Promise<void>;+}++export interface LocalVoiceAPI {+ listModels: () => Promise<VoiceModels>;+ onModelsChanged: (callback: (snapshot: VoiceModels) => void) => () => void;+ downloadModel: (id: string) => Promise<void>;+ cancelDownload: (id: string) => Promise<void>;+ deleteModel: (id: string) => Promise<void>;+ prepare: (request: LocalVoiceRequest) => void;+ /** `samples` is mono PCM at 16 kHz. */+ transcribe: (request: LocalVoiceRequest & { samples: Float32Array }) => Promise<VoiceTranscription>;+ /** Absent on Desktop builds that predate history. */+ history?: LocalVoiceHistoryAPI;+}++export function localVoiceAPI(): LocalVoiceAPI | undefined {+ if (typeof window === "undefined") return undefined;+ const api = (window as unknown as { desktopAPI?: { voice?: Partial<LocalVoiceAPI> } }).desktopAPI?.voice;+ return api?.listModels && api.onModelsChanged && api.transcribe ? (api as LocalVoiceAPI) : undefined;+}diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex 61bcb15cf9..d15a1ac58b 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -11,6 +11,7 @@ import {ListPlus,Lock,MessagesSquare,+ Mic,Palette,Plug,Search,@@ -50,6 +51,8 @@ import { WorkflowsTab } from "../../workflows/workflows-tab";import { PropertiesTab } from "./properties-tab";import { QuickActionsTab } from "./quick-actions-tab";import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";+import { localVoiceAPI } from "../../platform/local-voice";+import { VoiceInputTab } from "./voice-input-tab";import { PluginsTab } from "./plugins-tab";import { McpTab } from "./mcp-tab";import { BillingTab } from "./billing-tab";@@ -136,6 +139,7 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {false,);const appsAvailable = useComposioAvailable();+ const voiceInputAvailable = localVoiceAPI() !== undefined;const entry = (value: string,label: string,@@ -177,6 +181,9 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {Keyboard,<KeyboardShortcutsTab />,),+ ...(voiceInputAvailable+ ? [entry("voice-input", t(($) => $.page.tabs.voice_input), Mic, <VoiceInputTab />)]+ : []),entry("tokens", t(($) => $.page.tabs.tokens), KeyRound, <TokensTab />),],},diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex 65b208b236..f5269e8d57 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -211,6 +211,61 @@ export function useSettingsSearchIndex(title: t(($) => $.page.tabs.shortcuts),description: t(($) => $.shortcuts.description),},+ {+ tab: "voice-input",+ title: t(($) => $.page.tabs.voice_input),+ description: t(($) => $.voice_input.description),+ },+ {+ tab: "voice-input",+ anchor: "voice-model",+ title: t(($) => $.voice_input.model_title),+ description: t(($) => $.voice_input.model_hint),+ },+ {+ tab: "voice-input",+ anchor: "voice-shortcut",+ title: t(($) => $.voice_input.shortcut.title),+ description: t(($) => $.voice_input.shortcut.hint),+ },+ {+ tab: "voice-input",+ anchor: "voice-activation",+ title: t(($) => $.voice_input.activation.title),+ },+ {+ tab: "voice-input",+ anchor: "voice-language",+ title: t(($) => $.voice_input.language.title),+ description: t(($) => $.voice_input.language.hint),+ },+ {+ tab: "voice-input",+ anchor: "voice-fillers",+ title: t(($) => $.voice_input.fillers.title),+ description: t(($) => $.voice_input.fillers.hint),+ },+ {+ tab: "voice-input",+ anchor: "voice-vocabulary",+ title: t(($) => $.voice_input.vocabulary.title),+ },+ {+ tab: "voice-input",+ anchor: "voice-device",+ title: t(($) => $.voice_input.device.title),+ },+ {+ tab: "voice-input",+ anchor: "voice-test",+ title: t(($) => $.voice_input.test.title),+ },+ {+ tab: "voice-input",+ anchor: "voice-history",+ title: t(($) => $.voice_input.history.title),+ description: t(($) => $.voice_input.history.description),+ },{tab: "apps",title: t(($) => $.page.tabs.apps),diff --git a/packages/views/settings/components/voice-history.test.tsx b/packages/views/settings/components/voice-history.test.tsxnew file mode 100644index 0000000000..5c40763fc9--- /dev/null+++ b/packages/views/settings/components/voice-history.test.tsx@@ -0,0 +1,93 @@+import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_VOICE_SETTINGS, useVoiceModelsStore, useVoiceSettingsStore, type VoiceHistoryEntry } from "@multica/core/voice";+import { renderWithI18n } from "../../test/i18n";+import { VoiceHistorySection } from "./voice-history";++const transcribe = vi.hoisted(() => vi.fn());+vi.mock("@multica/core/voice", async (original) => ({+ ...(await original<typeof import("@multica/core/voice")>()),+ transcribeVoiceClip: transcribe,+}));+vi.mock("../../voice/engine", async () => {+ const { useVoiceModelsStore } = await import("@multica/core/voice");+ return { useVoiceModels: () => useVoiceModelsStore((s) => s.models) };+});++const now = Date.now();+let entries: VoiceHistoryEntry[];+const api = {+ list: vi.fn(async () => entries),+ onChanged: vi.fn(() => () => {}),+ save: vi.fn(),+ update: vi.fn(async () => {}),+ audio: vi.fn(async () => ({ audio: new Uint8Array([1]), mimeType: "audio/webm" })),+ remove: vi.fn(async () => {}),+ setRetention: vi.fn(async () => {}),+ clear: vi.fn(async () => {}),+};++beforeEach(() => {+ entries = [+ { id: "a", createdAt: now, durationMs: 4200, status: "done", text: "今天的第一条" },+ { id: "b", createdAt: now - 60_000, durationMs: 9000, status: "failed", text: "" },+ { id: "c", createdAt: now - 3 * 24 * 60 * 60 * 1000, durationMs: 1000, status: "interrupted", text: "" },+ ];+ Object.values(api).forEach((fn) => fn.mockClear());+ transcribe.mockReset();+ useVoiceSettingsStore.getState().update(DEFAULT_VOICE_SETTINGS);+ useVoiceModelsStore.getState().setModels({+ engineAvailable: true,+ models: [{ id: "m", name: "M", author: "A", licenseUrl: "", languages: ["zh"], languageHint: true,+ sizeBytes: 1, status: "ready", receivedBytes: 1 }],+ });+ (window as unknown as { desktopAPI: unknown }).desktopAPI = {+ voice: { listModels: vi.fn(), onModelsChanged: vi.fn(), transcribe: vi.fn(), history: api },+ };+});++afterEach(() => {+ delete (window as unknown as { desktopAPI?: unknown }).desktopAPI;+});++describe("VoiceHistorySection", () => {+ it("lists dictations by day, with what happened to the ones without text", async () => {+ renderWithI18n(<VoiceHistorySection />);+ expect(await screen.findByText("今天的第一条")).toBeInTheDocument();+ expect(screen.getByText("Today")).toBeInTheDocument();+ expect(screen.getByText("Transcription failed")).toBeInTheDocument();+ expect(screen.getByText("Interrupted before it was transcribed")).toBeInTheDocument();+ expect(screen.getByText("0:04")).toBeInTheDocument();+ });++ it("transcribes a failed recording again from its audio", async () => {+ transcribe.mockResolvedValue("找回来了");+ renderWithI18n(<VoiceHistorySection />);+ await screen.findByText("Transcription failed");+ await act(async () => fireEvent.click(screen.getAllByRole("button", { name: "Transcribe again" })[1]!));+ expect(api.update).toHaveBeenNthCalledWith(1, "b", { status: "transcribing" });+ expect(api.audio).toHaveBeenCalledWith("b");+ await waitFor(() => expect(api.update).toHaveBeenLastCalledWith("b", { status: "done", text: "找回来了" }));+ });++ it("applies the new retention when it changes", async () => {+ const user = userEvent.setup();+ renderWithI18n(<VoiceHistorySection />);+ await screen.findByText("今天的第一条");+ await user.click(screen.getByRole("combobox", { name: "Keep history" }));+ await user.click(await screen.findByRole("option", { name: "7 days" }));+ expect(useVoiceSettingsStore.getState().keepHistory).toBe("7d");+ expect(api.setRetention).toHaveBeenCalledWith(7);+ });++ it("clears everything after confirming, without changing the retention", async () => {+ renderWithI18n(<VoiceHistorySection />);+ await screen.findByText("今天的第一条");+ fireEvent.click(screen.getByRole("button", { name: "Clear all" }));+ fireEvent.click(within(await screen.findByRole("alertdialog")).getByRole("button", { name: "Clear all" }));+ expect(api.clear).toHaveBeenCalledOnce();+ expect(api.setRetention).not.toHaveBeenCalled();+ expect(useVoiceSettingsStore.getState().keepHistory).toBe("30d");+ });+});diff --git a/packages/views/settings/components/voice-history.tsx b/packages/views/settings/components/voice-history.tsxnew file mode 100644index 0000000000..8470267b68--- /dev/null+++ b/packages/views/settings/components/voice-history.tsx@@ -0,0 +1,335 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Copy, Pause, Play, RotateCcw, Trash2 } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { IconButton } from "@multica/ui/components/common/icon-button";+import { ShimmerText } from "@multica/ui/components/common/shimmer-text";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import { copyText } from "@multica/ui/lib/clipboard";+import { cn } from "@multica/ui/lib/utils";+import {+ pickVoiceModel,+ transcribeVoiceClip,+ useVoiceSettingsStore,+ VOICE_HISTORY_RETENTIONS,+ voiceHistoryDays,+ type VoiceHistoryEntry,+ type VoiceHistoryRetention,+} from "@multica/core/voice";+import { useLocale, useT } from "../../i18n";+import { localVoiceAPI, type LocalVoiceHistoryAPI } from "../../platform/local-voice";+import { useVoiceModels } from "../../voice";+import { SettingsCard, SettingsRow, SettingsSection } from "./settings-layout";++const PAGE = 50;++function useHistory(api: LocalVoiceHistoryAPI | undefined): VoiceHistoryEntry[] | null {+ const [entries, setEntries] = useState<VoiceHistoryEntry[] | null>(null);+ useEffect(() => {+ if (!api) return;+ let live = true;+ const load = () =>+ void api.list().then(+ (next) => live && setEntries(next),+ () => live && setEntries([]),+ );+ load();+ const unsubscribe = api.onChanged(load);+ return () => {+ live = false;+ unsubscribe();+ };+ }, [api]);+ return entries;+}++/** One recording at a time, from its kept audio. */+function usePlayer(api: LocalVoiceHistoryAPI | undefined) {+ const [playing, setPlaying] = useState<string | null>(null);+ const current = useRef<{ audio: HTMLAudioElement; url: string } | null>(null);+ const release = () => {+ if (!current.current) return;+ current.current.audio.pause();+ URL.revokeObjectURL(current.current.url);+ current.current = null;+ };+ const stop = () => {+ release();+ setPlaying(null);+ };+ useEffect(() => release, []);+ const toggle = async (id: string) => {+ const wasPlaying = playing === id;+ stop();+ if (wasPlaying || !api) return;+ const kept = await api.audio(id);+ if (!kept) return;+ const url = URL.createObjectURL(new Blob([kept.audio], { type: kept.mimeType }));+ const audio = new Audio(url);+ current.current = { audio, url };+ audio.onended = stop;+ setPlaying(id);+ await audio.play().catch(stop);+ };+ return { playing, toggle };+}++function dayKey(time: number): string {+ const date = new Date(time);+ return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;+}++function formatDuration(ms: number): string {+ const seconds = Math.max(1, Math.round(ms / 1000));+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;+}++/**+ * Dictations kept on this computer, newest first and grouped by day. Each+ * one can be played, transcribed again from its audio, copied or deleted.+ */+export function VoiceHistorySection() {+ const { t } = useT("settings");+ const api = useMemo(() => localVoiceAPI()?.history, []);+ const entries = useHistory(api);+ const keepHistory = useVoiceSettingsStore((state) => state.keepHistory);+ const [confirmClear, setConfirmClear] = useState(false);+ if (!api) return null;+ return (+ <SettingsSection+ title={t(($) => $.voice_input.history.title)}+ description={t(($) => $.voice_input.history.description)}+ anchor="voice-history"+ action={+ entries && entries.length > 0 ? (+ <Button size="xs" variant="outline" onClick={() => setConfirmClear(true)}>+ {t(($) => $.voice_input.history.clear)}+ </Button>+ ) : undefined+ }+ >+ <SettingsCard>+ <KeepHistoryRow api={api} />+ </SettingsCard>+ {entries && entries.length > 0 ? (+ <HistoryList api={api} entries={entries} />+ ) : entries ? (+ <p className="px-0.5 text-caption text-muted-foreground">+ {keepHistory === "off" ? t(($) => $.voice_input.history.off) : t(($) => $.voice_input.history.empty)}+ </p>+ ) : null}+ <AlertDialog open={confirmClear} onOpenChange={setConfirmClear}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.voice_input.history.clear_dialog.title)}</AlertDialogTitle>+ <AlertDialogDescription>{t(($) => $.voice_input.history.clear_dialog.description)}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t(($) => $.voice_input.history.clear_dialog.cancel)}</AlertDialogCancel>+ <AlertDialogAction variant="destructive" onClick={() => void api.clear()}>+ {t(($) => $.voice_input.history.clear)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </SettingsSection>+ );+}++function KeepHistoryRow({ api }: { api: LocalVoiceHistoryAPI }) {+ const { t } = useT("settings");+ const keepHistory = useVoiceSettingsStore((state) => state.keepHistory);+ const update = useVoiceSettingsStore((state) => state.update);+ const label = t(($) => $.voice_input.history.keep.title);+ const options = VOICE_HISTORY_RETENTIONS.map((value) => ({+ value,+ label: t(($) => $.voice_input.history.keep.options[value]),+ }));+ return (+ <SettingsRow+ anchor="voice-history-keep"+ label={label}+ description={t(($) => $.voice_input.history.keep.hint)}+ size="select"+ >+ <Select+ items={options}+ value={keepHistory}+ onValueChange={(next) => {+ if (!next) return;+ const retention = next as VoiceHistoryRetention;+ update({ keepHistory: retention });+ void api.setRetention(voiceHistoryDays(retention));+ }}+ >+ <SelectTrigger size="sm" className="w-full" aria-label={label}>+ <SelectValue>{options.find((option) => option.value === keepHistory)?.label}</SelectValue>+ </SelectTrigger>+ <SelectContent align="end">+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ );+}++function HistoryList({ api, entries }: { api: LocalVoiceHistoryAPI; entries: VoiceHistoryEntry[] }) {+ const { t } = useT("settings");+ const locale = useLocale();+ const [shown, setShown] = useState(PAGE);+ const player = usePlayer(api);+ const modelId = useVoiceSettingsStore((state) => state.modelId);+ const canTranscribe = pickVoiceModel(useVoiceModels(), modelId) !== null;+ const groups = useMemo(() => {+ const today = dayKey(Date.now());+ const yesterday = dayKey(Date.now() - 24 * 60 * 60 * 1000);+ const dayLabel = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", weekday: "short" });+ const out: { key: string; label: string; entries: VoiceHistoryEntry[] }[] = [];+ for (const entry of entries.slice(0, shown)) {+ const key = dayKey(entry.createdAt);+ const last = out[out.length - 1];+ if (last?.key === key) {+ last.entries.push(entry);+ continue;+ }+ const label =+ key === today+ ? t(($) => $.voice_input.history.today)+ : key === yesterday+ ? t(($) => $.voice_input.history.yesterday)+ : dayLabel.format(entry.createdAt);+ out.push({ key, label, entries: [entry] });+ }+ return out;+ }, [entries, shown, locale, t]);+ const time = useMemo(() => new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit" }), [locale]);++ const transcribeAgain = async (entry: VoiceHistoryEntry) => {+ const previous = entry.text;+ await api.update(entry.id, { status: "transcribing" });+ const kept = await api.audio(entry.id);+ const text = kept ? await transcribeVoiceClip(new Blob([kept.audio], { type: kept.mimeType })) : null;+ await api.update(entry.id, text ? { status: "done", text } : { status: previous ? "done" : "failed" });+ if (!text) toast.error(t(($) => $.voice_input.history.retry_failed));+ };+ const copy = async (text: string) => {+ if (await copyText(text)) toast.success(t(($) => $.voice_input.history.copied));+ else toast.error(t(($) => $.voice_input.history.copy_failed));+ };++ return (+ <div className="space-y-4">+ {groups.map((group) => (+ <div key={group.key} className="space-y-1.5">+ <h4 className="px-0.5 text-caption font-medium text-muted-foreground">{group.label}</h4>+ <SettingsCard>+ {group.entries.map((entry) => (+ <div+ key={entry.id}+ className="group/entry flex items-start gap-4 border-b border-surface-border px-4 py-3 last:border-b-0"+ >+ <div className="flex min-w-20 shrink-0 gap-2 whitespace-nowrap pt-0.5 text-caption tabular-nums text-muted-foreground">+ <span>{time.format(entry.createdAt)}</span>+ <span className="text-faint-foreground">{formatDuration(entry.durationMs)}</span>+ </div>+ <div className="min-w-0 flex-1 text-body">+ {entry.status === "transcribing" ? (+ <ShimmerText className="text-caption font-medium">+ {t(($) => $.voice_input.history.status.transcribing)}+ </ShimmerText>+ ) : entry.text ? (+ <p className="whitespace-pre-wrap break-words">{entry.text}</p>+ ) : (+ <p className={cn("text-caption", entry.status === "failed" ? "text-destructive" : "text-muted-foreground")}>+ {entry.status === "failed"+ ? t(($) => $.voice_input.history.status.failed)+ : t(($) => $.voice_input.history.status.interrupted)}+ </p>+ )}+ </div>+ <div+ className={cn(+ "-my-1 flex shrink-0 items-center gap-0.5 transition-opacity",+ // Recordings without text keep their actions in view: retrying is the point.+ entry.text && player.playing !== entry.id &&+ "opacity-0 group-hover/entry:opacity-100 group-focus-within/entry:opacity-100",+ )}+ >+ <IconButton+ variant="ghost"+ size="icon-sm"+ label={+ player.playing === entry.id+ ? t(($) => $.voice_input.history.actions.pause)+ : t(($) => $.voice_input.history.actions.play)+ }+ onClick={() => void player.toggle(entry.id)}+ >+ {player.playing === entry.id ? <Pause /> : <Play />}+ </IconButton>+ <IconButton+ variant="ghost"+ size="icon-sm"+ label={t(($) => $.voice_input.history.actions.retranscribe)}+ disabled={!canTranscribe || entry.status === "transcribing"}+ onClick={() => void transcribeAgain(entry)}+ >+ <RotateCcw />+ </IconButton>+ {entry.text && (+ <IconButton+ variant="ghost"+ size="icon-sm"+ label={t(($) => $.voice_input.history.actions.copy)}+ onClick={() => void copy(entry.text)}+ >+ <Copy />+ </IconButton>+ )}+ <IconButton+ variant="ghost"+ size="icon-sm"+ className="hover:text-destructive"+ label={t(($) => $.voice_input.history.actions.delete)}+ onClick={() => void api.remove(entry.id)}+ >+ <Trash2 />+ </IconButton>+ </div>+ </div>+ ))}+ </SettingsCard>+ </div>+ ))}+ {entries.length > shown && (+ <div className="flex justify-center">+ <Button size="xs" variant="outline" onClick={() => setShown((n) => n + PAGE)}>+ {t(($) => $.voice_input.history.show_more)}+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/packages/views/settings/components/voice-input-tab.tsx b/packages/views/settings/components/voice-input-tab.tsxnew file mode 100644index 0000000000..962265bfd3--- /dev/null+++ b/packages/views/settings/components/voice-input-tab.tsx@@ -0,0 +1,459 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { X } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import { Switch } from "@multica/ui/components/ui/switch";+import { cn } from "@multica/ui/lib/utils";+import { useShortcut } from "@multica/core/shortcuts";+import {+ MAX_VOCABULARY_WORDS,+ pickVoiceModel,+ useVoiceSettingsStore,+ VOICE_LANGUAGES,+ type VoiceActivation,+ type VoiceLanguage,+} from "@multica/core/voice";+import { SegmentedToggle } from "../../common/segmented-toggle";+import { ShortcutKeycaps } from "../../common/shortcut-keycaps";+import { AppLink, useOptionalNavigation } from "../../navigation";+import { useLocale, useT } from "../../i18n";+import { useVoiceModels, VoiceModelRows, voiceInputSupported } from "../../voice";+import { settingsHref } from "./settings-navigation";+import { VoiceHistorySection } from "./voice-history";+import {+ SettingsCard,+ SettingsRow,+ SettingsSection,+ SettingsTab,+} from "./settings-layout";++/**+ * Speech models and how dictation behaves on this computer. Desktop only:+ * transcription runs on the device, so the tab needs Desktop's engine.+ */+export function VoiceInputTab() {+ const { t } = useT("settings");+ const engineAvailable = useVoiceModels()?.engineAvailable;+ return (+ <SettingsTab+ title={t(($) => $.page.tabs.voice_input)}+ description={t(($) => $.voice_input.description)}+ scope="device"+ >+ <SettingsSection+ title={t(($) => $.voice_input.model_title)}+ description={+ engineAvailable === false+ ? t(($) => $.voice_input.engine_unavailable)+ : t(($) => $.voice_input.model_hint)+ }+ anchor="voice-model"+ >+ {engineAvailable && (+ <SettingsCard>+ <VoiceModelRows manage />+ </SettingsCard>+ )}+ </SettingsSection>+ <SettingsSection title={t(($) => $.voice_input.input_title)} anchor="voice-input">+ <SettingsCard>+ <ShortcutRow />+ <ActivationRow />+ </SettingsCard>+ </SettingsSection>+ <SettingsSection+ title={t(($) => $.voice_input.recognition_title)}+ anchor="voice-recognition"+ >+ <SettingsCard>+ <LanguageRow />+ <FillersRow />+ <VocabularyRow />+ </SettingsCard>+ </SettingsSection>+ <SettingsSection+ title={t(($) => $.voice_input.microphone_title)}+ anchor="voice-microphone"+ >+ <SettingsCard>+ <MicrophoneRows />+ </SettingsCard>+ </SettingsSection>+ <VoiceHistorySection />+ </SettingsTab>+ );+}++function ShortcutRow() {+ const { t } = useT("settings");+ const shortcut = useShortcut("voiceInput");+ const navigation = useOptionalNavigation();+ const href = navigation+ ? settingsHref(navigation.pathname, navigation.searchParams, "shortcuts")+ : "?tab=shortcuts";+ return (+ <SettingsRow+ anchor="voice-shortcut"+ label={t(($) => $.voice_input.shortcut.title)}+ description={t(($) => $.voice_input.shortcut.hint)}+ >+ <div className="flex items-center gap-3">+ {shortcut ? (+ <ShortcutKeycaps shortcut={shortcut} size="md" />+ ) : (+ <span className="text-caption text-muted-foreground">+ {t(($) => $.voice_input.shortcut.unassigned)}+ </span>+ )}+ <Button size="xs" variant="outline" render={<AppLink href={href} />} nativeButton={false}>+ {t(($) => $.voice_input.shortcut.change)}+ </Button>+ </div>+ </SettingsRow>+ );+}++function ActivationRow() {+ const { t } = useT("settings");+ const activation = useVoiceSettingsStore((state) => state.activation);+ const update = useVoiceSettingsStore((state) => state.update);+ const label = t(($) => $.voice_input.activation.title);+ return (+ <SettingsRow+ anchor="voice-activation"+ label={label}+ description={t(($) => $.voice_input.activation.hints[activation])}+ >+ <div role="group" aria-label={label}>+ <SegmentedToggle<VoiceActivation>+ value={activation}+ onChange={(next) => update({ activation: next })}+ buttonClassName="px-3 py-1 text-label"+ options={[+ ["auto", t(($) => $.voice_input.activation.auto)],+ ["toggle", t(($) => $.voice_input.activation.toggle)],+ ["hold", t(($) => $.voice_input.activation.hold)],+ ]}+ />+ </div>+ </SettingsRow>+ );+}++function LanguageRow() {+ const { t } = useT("settings");+ const locale = useLocale();+ const language = useVoiceSettingsStore((state) => state.language);+ const modelId = useVoiceSettingsStore((state) => state.modelId);+ const update = useVoiceSettingsStore((state) => state.update);+ const model = pickVoiceModel(useVoiceModels(), modelId);+ const label = t(($) => $.voice_input.language.title);+ const options = useMemo(() => {+ let names: Intl.DisplayNames | null = null;+ try {+ names = new Intl.DisplayNames([locale], { type: "language" });+ } catch {+ names = null;+ }+ return VOICE_LANGUAGES.map((value) => ({+ value,+ label:+ value === "auto"+ ? t(($) => $.voice_input.language.auto)+ : (names?.of(value) ?? value),+ }));+ }, [locale, t]);+ // Models without a language hint always detect the language themselves.+ if (model && !model.languageHint) return null;+ return (+ <SettingsRow+ anchor="voice-language"+ label={label}+ description={t(($) => $.voice_input.language.hint)}+ size="select"+ >+ <Select+ items={options}+ value={language}+ onValueChange={(next) => {+ if (next) update({ language: next as VoiceLanguage });+ }}+ >+ <SelectTrigger size="sm" className="w-full" aria-label={label}>+ <SelectValue>{options.find((option) => option.value === language)?.label}</SelectValue>+ </SelectTrigger>+ <SelectContent align="end">+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ );+}++function FillersRow() {+ const { t } = useT("settings");+ const removeFillers = useVoiceSettingsStore((state) => state.removeFillers);+ const update = useVoiceSettingsStore((state) => state.update);+ const label = t(($) => $.voice_input.fillers.title);+ return (+ <SettingsRow+ anchor="voice-fillers"+ label={label}+ description={t(($) => $.voice_input.fillers.hint)}+ >+ <Switch+ checked={removeFillers}+ onCheckedChange={(checked) => update({ removeFillers: checked })}+ aria-label={label}+ />+ </SettingsRow>+ );+}++function VocabularyRow() {+ const { t } = useT("settings");+ const vocabulary = useVoiceSettingsStore((state) => state.vocabulary);+ const addWord = useVoiceSettingsStore((state) => state.addWord);+ const removeWord = useVoiceSettingsStore((state) => state.removeWord);+ const [draft, setDraft] = useState("");+ const full = vocabulary.length >= MAX_VOCABULARY_WORDS;+ const label = t(($) => $.voice_input.vocabulary.title);+ const add = () => {+ addWord(draft);+ setDraft("");+ };+ return (+ <SettingsRow+ anchor="voice-vocabulary"+ label={label}+ description={t(($) => $.voice_input.vocabulary.hint, { max: MAX_VOCABULARY_WORDS })}+ size="text"+ align="start"+ >+ <div className="flex min-h-8 flex-wrap items-center gap-1 rounded-md border border-input px-1.5 py-1 focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50">+ {vocabulary.map((word) => (+ <span+ key={word}+ className="inline-flex h-6 items-center gap-1 rounded-sm bg-muted pl-2 pr-1 text-caption"+ >+ {word}+ <button+ type="button"+ aria-label={t(($) => $.voice_input.vocabulary.remove, { word })}+ onClick={() => removeWord(word)}+ className="flex size-4 items-center justify-center rounded-xs text-muted-foreground hover:bg-surface-hover hover:text-foreground"+ >+ <X className="size-3" aria-hidden />+ </button>+ </span>+ ))}+ {!full && (+ <input+ value={draft}+ aria-label={label}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => {+ if (draft.trim()) add();+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {+ event.preventDefault();+ add();+ } else if (event.key === "Backspace" && !draft && vocabulary.length > 0) {+ removeWord(vocabulary[vocabulary.length - 1]!);+ }+ }}+ placeholder={t(($) => $.voice_input.vocabulary.placeholder)}+ className="h-6 min-w-24 flex-1 bg-transparent px-1 text-caption outline-none placeholder:text-muted-foreground"+ />+ )}+ </div>+ </SettingsRow>+ );+}++// Chrome lists pseudo-devices that duplicate a real one.+const PSEUDO_DEVICE_IDS = new Set(["default", "communications"]);+const DEFAULT_DEVICE_VALUE = "__default__";++function useAudioInputs() {+ const [inputs, setInputs] = useState<MediaDeviceInfo[]>([]);+ const refresh = useCallback(() => {+ if (!navigator.mediaDevices?.enumerateDevices) return;+ void navigator.mediaDevices.enumerateDevices().then(+ (devices) =>+ setInputs(+ devices.filter(+ (device) => device.kind === "audioinput" && !PSEUDO_DEVICE_IDS.has(device.deviceId),+ ),+ ),+ () => setInputs([]),+ );+ }, []);+ useEffect(() => {+ if (!navigator.mediaDevices) return;+ refresh();+ navigator.mediaDevices.addEventListener("devicechange", refresh);+ return () => navigator.mediaDevices.removeEventListener("devicechange", refresh);+ }, [refresh]);+ return { inputs, refresh };+}++type MicTest = { state: "off" } | { state: "on"; level: number } | { state: "blocked" };++/** Live input level from the chosen microphone; nothing is recorded. */+function useMicTest(deviceId: string | null, onGranted: () => void) {+ const [test, setTest] = useState<MicTest>({ state: "off" });+ const running = test.state === "on";+ useEffect(() => {+ if (!running) return;+ let cancelled = false;+ let stream: MediaStream | null = null;+ let context: AudioContext | null = null;+ let timer: number | null = null;+ const audio: MediaTrackConstraints = deviceId ? { deviceId: { exact: deviceId } } : {};+ navigator.mediaDevices.getUserMedia({ audio }).then(+ (granted) => {+ if (cancelled) {+ granted.getTracks().forEach((track) => track.stop());+ return;+ }+ stream = granted;+ onGranted();+ context = new AudioContext();+ const analyser = context.createAnalyser();+ analyser.fftSize = 512;+ context.createMediaStreamSource(granted).connect(analyser);+ const samples = new Uint8Array(analyser.fftSize);+ timer = window.setInterval(() => {+ analyser.getByteTimeDomainData(samples);+ let sum = 0;+ for (const sample of samples) {+ const v = (sample - 128) / 128;+ sum += v * v;+ }+ const level = Math.min(1, Math.sqrt(sum / samples.length) * 5);+ setTest((prev) =>+ prev.state === "on" ? { state: "on", level: prev.level * 0.4 + level * 0.6 } : prev,+ );+ }, 50);+ },+ () => {+ if (!cancelled) setTest({ state: "blocked" });+ },+ );+ return () => {+ cancelled = true;+ if (timer !== null) window.clearInterval(timer);+ stream?.getTracks().forEach((track) => track.stop());+ void context?.close().catch(() => {});+ };+ }, [running, deviceId, onGranted]);+ return {+ test,+ start: () => setTest({ state: "on", level: 0 }),+ stop: () => setTest({ state: "off" }),+ };+}++const METER_SEGMENTS = 16;++function MicrophoneRows() {+ const { t } = useT("settings");+ const deviceId = useVoiceSettingsStore((state) => state.deviceId);+ const update = useVoiceSettingsStore((state) => state.update);+ const { inputs, refresh } = useAudioInputs();+ const { test, start, stop } = useMicTest(deviceId, refresh);+ const supported = voiceInputSupported();+ const deviceLabel = t(($) => $.voice_input.device.title);+ const options = [+ { value: DEFAULT_DEVICE_VALUE, label: t(($) => $.voice_input.device.default) },+ ...inputs.map((input, index) => ({+ value: input.deviceId,+ label: input.label || t(($) => $.voice_input.device.unnamed, { index: index + 1 }),+ })),+ ];+ // An unplugged device reads as the default, which is what recording falls+ // back to; the saved choice comes back when the device does.+ const value =+ deviceId && options.some((option) => option.value === deviceId) ? deviceId : DEFAULT_DEVICE_VALUE;+ const level = test.state === "on" ? test.level : 0;+ const unlabeled = inputs.length > 0 && inputs.every((input) => !input.label);+ return (+ <>+ <SettingsRow+ anchor="voice-device"+ label={deviceLabel}+ description={unlabeled ? t(($) => $.voice_input.device.permission_hint) : undefined}+ size="select-wide"+ >+ <Select+ items={options}+ value={value}+ onValueChange={(next) => {+ if (next) update({ deviceId: next === DEFAULT_DEVICE_VALUE ? null : next });+ }}+ >+ <SelectTrigger size="sm" className="w-full" aria-label={deviceLabel}>+ <SelectValue>{options.find((option) => option.value === value)?.label}</SelectValue>+ </SelectTrigger>+ <SelectContent align="end">+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ <SettingsRow+ anchor="voice-test"+ label={t(($) => $.voice_input.test.title)}+ description={+ test.state === "blocked"+ ? t(($) => $.voice_input.test.blocked)+ : t(($) => $.voice_input.test.hint)+ }+ size="select-wide"+ >+ <div className="flex items-center gap-3">+ <div className="flex h-3 flex-1 items-center gap-[3px]" aria-hidden>+ {Array.from({ length: METER_SEGMENTS }, (_, index) => (+ <span+ key={index}+ className={cn(+ "h-full flex-1 rounded-xs transition-colors duration-75",+ index / METER_SEGMENTS < level+ ? index > METER_SEGMENTS * 0.8+ ? "bg-warning"+ : "bg-success"+ : "bg-muted",+ )}+ />+ ))}+ </div>+ <Button+ size="xs"+ variant="outline"+ disabled={!supported}+ onClick={test.state === "on" ? stop : start}+ >+ {test.state === "on" ? t(($) => $.voice_input.test.stop) : t(($) => $.voice_input.test.start)}+ </Button>+ </div>+ </SettingsRow>+ </>+ );+}diff --git a/packages/views/voice/dialog-footer.tsx b/packages/views/voice/dialog-footer.tsxnew file mode 100644index 0000000000..45098e7767--- /dev/null+++ b/packages/views/voice/dialog-footer.tsx@@ -0,0 +1,28 @@+"use client";++import type { ReactNode } from "react";+import type { ComposerVoice } from "./use-composer-voice";+import { VoiceSetupDialog } from "./voice-models";+import { VoiceErrorRow, VoiceHud, VoiceStrip } from "./voice-ui";++/**+ * A dialog footer that voice input can take over: the recording strip+ * replaces the footer row while dictating, and the push-to-talk pill floats+ * above it.+ */+export function VoiceDialogFooter({ voice, children }: { voice: ComposerVoice; children: ReactNode }) {+ return (+ <div className="relative shrink-0">+ <VoiceHud voice={voice} />+ <VoiceSetupDialog voice={voice} />+ <VoiceErrorRow voice={voice} className="mx-4 mb-2" />+ {voice.showStrip ? (+ <div className="flex items-center border-t px-4 py-3">+ <VoiceStrip voice={voice} />+ </div>+ ) : (+ children+ )}+ </div>+ );+}diff --git a/packages/views/voice/engine.ts b/packages/views/voice/engine.tsnew file mode 100644index 0000000000..2f2a0e9adb--- /dev/null+++ b/packages/views/voice/engine.ts@@ -0,0 +1,79 @@+/**+ * Desktop's on-device engine as the voice session's runtime: the microphone+ * recorder, the preload IPC to the speech engine, and decoding a clip to the+ * samples the engine takes.+ */+import { useEffect } from "react";+import {+ connectVoiceRuntime,+ useVoiceModelsStore,+ type VoiceDecodeOptions,+ type VoiceModel,+ type VoiceModels,+ type VoiceRuntime,+} from "@multica/core/voice";+import { localVoiceAPI } from "../platform/local-voice";+import { Recording } from "./recorder";++const SAMPLE_RATE = 16000;++/** Mono samples at 16 kHz; the decoder resamples to the context's rate. */+async function decodeClip(clip: Blob): Promise<Float32Array> {+ const context = new OfflineAudioContext(1, 1, SAMPLE_RATE);+ const audio = await context.decodeAudioData(await clip.arrayBuffer());+ if (audio.numberOfChannels === 1) return audio.getChannelData(0);+ const mixed = new Float32Array(audio.length);+ for (let channel = 0; channel < audio.numberOfChannels; channel++) {+ const data = audio.getChannelData(channel);+ for (let i = 0; i < data.length; i++) mixed[i]! += data[i]! / audio.numberOfChannels;+ }+ return mixed;+}++function desktopVoiceRuntime(): VoiceRuntime | null {+ const api = localVoiceAPI();+ if (!api) return null;+ const history = api.history;+ const request = (model: VoiceModel, { language, hotwords }: VoiceDecodeOptions) => ({+ modelId: model.id,+ language,+ hotwords,+ });+ return {+ record: (onMeter, onLimit) => new Recording(onMeter, onLimit),+ prepare: (model, options) => api.prepare(request(model, options)),+ transcribe: async (clip, model, options) =>+ api.transcribe({ ...request(model, options), samples: await decodeClip(clip) }),+ history: history && {+ save: async (clip, keepDays) => {+ const entry = await history.save({+ audio: new Uint8Array(await clip.blob.arrayBuffer()),+ mimeType: clip.blob.type,+ durationMs: clip.durationMs,+ keepDays,+ });+ return entry?.id ?? null;+ },+ update: (id, status, text) => void history.update(id, { status, text }).catch(() => {}),+ },+ watchModels: (onChange) => {+ let changed = false;+ api.onModelsChanged((models) => {+ changed = true;+ onChange(models);+ });+ void api.listModels().then(+ (models) => {+ if (!changed) onChange(models);+ },+ () => {},+ );+ },+ };+}++/** Desktop's speech models; null on web and until the engine first answers. */+export function useVoiceModels(): VoiceModels | null {+ useEffect(() => connectVoiceRuntime(desktopVoiceRuntime), []);+ return useVoiceModelsStore((s) => s.models);+}diff --git a/packages/views/voice/index.ts b/packages/views/voice/index.tsnew file mode 100644index 0000000000..3c2c2bb96f--- /dev/null+++ b/packages/views/voice/index.ts@@ -0,0 +1,7 @@+export { useComposerVoice, type ComposerVoice, type ComposerVoiceOptions } from "./use-composer-voice";+export { VoiceErrorRow, VoiceHud, VoiceMicButton, VoiceStrip } from "./voice-ui";+export { VoiceDialogFooter } from "./dialog-footer";+export { voiceInputSupported } from "./recorder";+export { useVoiceModels } from "./engine";+export { VoiceModelRows, VoiceSetupDialog } from "./voice-models";+export { VoiceWorkspaceWords } from "./workspace-words";diff --git a/packages/views/voice/recorder.ts b/packages/views/voice/recorder.tsnew file mode 100644index 0000000000..95d4e6e3d9--- /dev/null+++ b/packages/views/voice/recorder.ts@@ -0,0 +1,170 @@+/**+ * One microphone recording: open the device, record, meter the level, and+ * hand back the clip. Knows nothing about composers or transcription.+ */+import {+ VoiceRecorderError,+ type VoiceClip,+ type VoiceMeter,+ type VoiceRecorder,+ type VoiceRecorderFailure,+} from "@multica/core/voice";++/** The recording stops itself here; Desktop's engine accepts a little more. */+const MAX_RECORDING_MS = 120_000;+/** Shorter clips, or clips that never rise above the noise floor, are not sent. */+const MIN_RECORDING_MS = 400;+const SPEECH_LEVEL = 0.04;+/** Enough history to fill a full-width strip at the waveform's 5 px pitch. */+const LEVEL_HISTORY = 288;+export const METER_INTERVAL_MS = 50;++const MIME_TYPES = ["audio/webm;codecs=opus", "audio/webm", "audio/mp4", "audio/ogg;codecs=opus"];++export function voiceInputSupported(): boolean {+ return (+ typeof navigator !== "undefined" &&+ typeof navigator.mediaDevices?.getUserMedia === "function" &&+ typeof MediaRecorder !== "undefined"+ );+}++function failureOf(err: unknown): VoiceRecorderFailure {+ const name = err instanceof DOMException || err instanceof Error ? err.name : "";+ if (name === "NotAllowedError" || name === "SecurityError" || name === "PermissionDeniedError") {+ return "permission-denied";+ }+ if (name === "NotFoundError" || name === "DevicesNotFoundError") return "no-microphone";+ return "failed";+}++async function openMicrophone(deviceId: string | null): Promise<MediaStream> {+ // Noise suppression and gain control are tuned for calls; they smear+ // consonants and pump the level, which costs recognition accuracy.+ const base = { echoCancellation: true, noiseSuppression: false, autoGainControl: false };+ if (deviceId) {+ try {+ return await navigator.mediaDevices.getUserMedia({ audio: { ...base, deviceId: { exact: deviceId } } });+ } catch (err) {+ // The saved device was unplugged: fall back to the system default.+ const name = err instanceof Error ? err.name : "";+ if (name !== "OverconstrainedError" && name !== "NotFoundError") throw err;+ }+ }+ return navigator.mediaDevices.getUserMedia({ audio: base });+}++export class Recording implements VoiceRecorder {+ private stream: MediaStream | null = null;+ private recorder: MediaRecorder | null = null;+ private audio: AudioContext | null = null;+ private chunks: Blob[] = [];+ private startedAt = 0;+ private peak = 0;+ private timer: number | null = null;+ private closed = false;+ private levels: number[] = [];++ constructor(+ private readonly onMeter: (meter: VoiceMeter) => void,+ private readonly onLimit: () => void,+ ) {}++ /** Resolves once audio is flowing; rejects with a VoiceRecorderError. */+ async start(deviceId: string | null): Promise<void> {+ let stream: MediaStream;+ try {+ stream = await openMicrophone(deviceId);+ } catch (err) {+ throw new VoiceRecorderError(failureOf(err));+ }+ if (this.closed) {+ stream.getTracks().forEach((track) => track.stop());+ return;+ }+ this.stream = stream;+ const mimeType = MIME_TYPES.find((type) => MediaRecorder.isTypeSupported(type));+ try {+ this.recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);+ } catch {+ this.release();+ throw new VoiceRecorderError("failed");+ }+ this.recorder.ondataavailable = (event) => {+ if (event.data.size > 0) this.chunks.push(event.data);+ };+ this.recorder.start(250);+ this.startedAt = performance.now();+ this.startMeter(stream);+ }++ private startMeter(stream: MediaStream) {+ try {+ this.audio = new AudioContext();+ const analyser = this.audio.createAnalyser();+ analyser.fftSize = 512;+ this.audio.createMediaStreamSource(stream).connect(analyser);+ const samples = new Uint8Array(analyser.fftSize);+ this.timer = window.setInterval(() => {+ analyser.getByteTimeDomainData(samples);+ let sum = 0;+ for (const sample of samples) {+ const v = (sample - 128) / 128;+ sum += v * v;+ }+ const level = Math.min(1, Math.sqrt(sum / samples.length) * 5);+ this.peak = Math.max(this.peak, level);+ this.levels = [...this.levels.slice(-(LEVEL_HISTORY - 1)), level];+ const elapsedMs = performance.now() - this.startedAt;+ this.onMeter({ levels: this.levels, elapsedMs });+ if (elapsedMs >= MAX_RECORDING_MS) this.onLimit();+ }, METER_INTERVAL_MS);+ } catch {+ // Metering is cosmetic; record without it. Without a meter there is no+ // level to judge silence by, so treat the clip as speech.+ this.peak = 1;+ }+ }++ /** Stop and return the clip. */+ finish(): Promise<VoiceClip> {+ const recorder = this.recorder;+ const durationMs = performance.now() - this.startedAt;+ const heardSpeech = durationMs >= MIN_RECORDING_MS && this.peak >= SPEECH_LEVEL;+ return new Promise((resolve) => {+ const done = () => {+ const type = recorder?.mimeType || this.chunks[0]?.type || "audio/webm";+ const blob = new Blob(this.chunks, { type });+ this.release();+ resolve({ blob, durationMs, heardSpeech: heardSpeech && blob.size > 0 });+ };+ if (!recorder || recorder.state === "inactive") {+ done();+ return;+ }+ recorder.onstop = done;+ recorder.stop();+ });+ }++ /** Stop without keeping anything. Safe to call at any point, repeatedly. */+ discard() {+ this.closed = true;+ if (this.recorder && this.recorder.state !== "inactive") {+ this.recorder.onstop = null;+ this.recorder.stop();+ }+ this.chunks = [];+ this.release();+ }++ private release() {+ this.closed = true;+ if (this.timer !== null) window.clearInterval(this.timer);+ this.timer = null;+ this.stream?.getTracks().forEach((track) => track.stop());+ this.stream = null;+ void this.audio?.close().catch(() => {});+ this.audio = null;+ }+}diff --git a/packages/views/voice/use-composer-voice.test.tsx b/packages/views/voice/use-composer-voice.test.tsxnew file mode 100644index 0000000000..42e70cfa46--- /dev/null+++ b/packages/views/voice/use-composer-voice.test.tsx@@ -0,0 +1,170 @@+import { act, cleanup, render, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import {+ cancelVoice,+ connectVoiceRuntime,+ getVoiceState,+ pressVoice,+ releaseVoice,+ stopVoice,+ useVoiceModelsStore,+ type VoiceModels,+} from "@multica/core/voice";+import { createShortcutChord, useShortcutStore } from "@multica/core/shortcuts";+import { useComposerVoice, type ComposerVoiceOptions } from "./use-composer-voice";++const INSTALLED: VoiceModels = {+ engineAvailable: true,+ models: [+ {+ id: "sensevoice-small",+ name: "SenseVoice Small",+ author: "FunAudioLLM",+ licenseUrl: "https://example.com/license",+ languages: ["zh", "en"],+ languageHint: true,+ sizeBytes: 1,+ status: "ready",+ receivedBytes: 1,+ },+ ],+};++const engine = vi.hoisted(() => ({ transcribe: vi.fn(), started: 0 }));++vi.mock("./recorder", () => ({ voiceInputSupported: () => true }));+vi.mock("./engine", async () => {+ const { useVoiceModelsStore } = await import("@multica/core/voice");+ return { useVoiceModels: () => useVoiceModelsStore((s) => s.models) };+});++beforeAll(() => {+ connectVoiceRuntime(() => ({+ record: () => ({+ start: () => {+ engine.started++;+ return Promise.resolve();+ },+ finish: () => Promise.resolve({ blob: new Blob(["clip"]), heardSpeech: true, durationMs: 1500 }),+ discard: () => {},+ }),+ prepare: () => {},+ transcribe: (...args) => engine.transcribe(...args),+ watchModels: () => {},+ }));+});++beforeEach(() => {+ engine.started = 0;+ engine.transcribe.mockReset();+ act(() => useVoiceModelsStore.getState().setModels(INSTALLED));+ useShortcutStore.getState().setShortcut("voiceInput", createShortcutChord("Space", { alt: true }));+});++afterEach(() => {+ useShortcutStore.getState().resetShortcut("voiceInput");+ act(() => cancelVoice());+ cleanup();+});++function shortcut() {+ window.dispatchEvent(new KeyboardEvent("keydown", { key: " ", altKey: true, bubbles: true }));+ window.dispatchEvent(new KeyboardEvent("keyup", { key: " ", altKey: true, bubbles: true }));+}++describe("useComposerVoice", () => {+ // One ChatInput serves every conversation: what changes is its scope.+ it.each([+ ["switching to another session", "session-a:agent-1", "session-b:agent-1"],+ ["starting a new chat", "session-a:agent-1", "__draft_new__:agent-1"],+ ["switching agent in a new chat", "__draft_new__:agent-1", "__draft_new__:agent-2"],+ ])("drops the transcript and its send after %s", async (_name, from, to) => {+ let resolve!: (value: unknown) => void;+ engine.transcribe.mockReturnValue(new Promise((done) => (resolve = done)));+ const before = { insert: vi.fn(() => true), submit: vi.fn() };+ const after = { insert: vi.fn(() => true), submit: vi.fn() };+ const hook = renderHook((options: ComposerVoiceOptions) => useComposerVoice(options), {+ initialProps: { ...before, scope: from },+ });+ await act(async () => {+ pressVoice(hook.result.current.id);+ releaseVoice();+ });+ await act(async () => stopVoice(true));+ expect(getVoiceState().phase).toBe("transcribing");++ hook.rerender({ ...after, scope: to });+ expect(getVoiceState().phase).toBe("idle");+ await act(async () => resolve({ ok: true, text: "meant for the previous conversation" }));++ expect(getVoiceState().phase).toBe("idle");+ for (const callbacks of [before, after]) {+ expect(callbacks.insert).not.toHaveBeenCalled();+ expect(callbacks.submit).not.toHaveBeenCalled();+ }+ });++ it("keeps dictating when only the callbacks change", async () => {+ engine.transcribe.mockResolvedValue({ ok: true, text: "still here" });+ const insert = vi.fn(() => true);+ const hook = renderHook((options: ComposerVoiceOptions) => useComposerVoice(options), {+ initialProps: { insert: () => true, scope: "session-a:agent-1" } as ComposerVoiceOptions,+ });+ await act(async () => {+ pressVoice(hook.result.current.id);+ releaseVoice();+ });+ hook.rerender({ insert, submit: undefined, scope: "session-a:agent-1" });+ await act(async () => stopVoice(false));+ await waitFor(() => expect(insert).toHaveBeenCalledWith("still here"));+ });++ it("does not listen while hidden, and hiding cancels a recording", async () => {+ const hook = renderHook((options: ComposerVoiceOptions) => useComposerVoice(options), {+ initialProps: { insert: () => true, hidden: true },+ });+ await act(async () => shortcut());+ expect(getVoiceState().phase).toBe("idle");+ expect(engine.started).toBe(0);++ hook.rerender({ insert: () => true, hidden: false });+ await act(async () => shortcut());+ expect(getVoiceState().phase).toBe("recording");++ hook.rerender({ insert: () => true, hidden: true });+ expect(getVoiceState().phase).toBe("idle");+ });++ it("points the shortcut at a composer that is on screen", async () => {+ const offScreen = vi.fn(() => true);+ const onScreen = vi.fn(() => true);+ function Composer({ insert, shown }: { insert: () => boolean; shown: boolean }) {+ const voice = useComposerVoice({ insert });+ return (+ <div+ ref={(element) => {+ if (element) element.checkVisibility = () => shown;+ voice.rootRef(element);+ }}+ onFocusCapture={voice.onFocusCapture}+ >+ <input />+ </div>+ );+ }+ const view = render(+ <>+ <Composer insert={onScreen} shown />+ <Composer insert={offScreen} shown={false} />+ </>,+ );+ act(() => view.container.querySelectorAll("input")[1]!.focus());+ await act(async () => shortcut());+ expect(getVoiceState().phase).toBe("recording");++ engine.transcribe.mockResolvedValue({ ok: true, text: "for the visible one" });+ await act(async () => stopVoice(false));+ await waitFor(() => expect(onScreen).toHaveBeenCalledWith("for the visible one"));+ expect(offScreen).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/voice/use-composer-voice.ts b/packages/views/voice/use-composer-voice.tsnew file mode 100644index 0000000000..3bcec13acd--- /dev/null+++ b/packages/views/voice/use-composer-voice.ts@@ -0,0 +1,108 @@+import { useCallback, useEffect, useId, useRef, useSyncExternalStore } from "react";+import { noteVoiceFocus, registerVoiceTarget, useVoiceState, type VoiceState } from "@multica/core/voice";+import { useVoiceModels } from "./engine";+import { voiceInputSupported } from "./recorder";++export interface ComposerVoiceOptions {+ /** Insert the transcript into the editor; false while it is not mounted. */+ insert: (text: string) => boolean;+ /** Send the composer; omit where Enter-to-send does not apply. */+ submit?: () => void;+ /** Mount a lazily-created editor. */+ activate?: () => void;+ /**+ * What the composer is writing to (a session and its agent, an issue).+ * When it changes under a mounted composer, dictation in flight is+ * cancelled so its text never lands in, or sends to, the new one.+ */+ scope?: string;+ /** Mounted but not on screen (a closed floating window): no dictation. */+ hidden?: boolean;+ disabled?: boolean;+}++export interface ComposerVoice {+ id: string;+ /** Show the mic: this app has a speech engine and can record. */+ available: boolean;+ /** The session, when this composer owns it. */+ session: VoiceState | null;+ /** Another composer is recording or transcribing. */+ busyElsewhere: boolean;+ /** The inline strip replaces the composer's toolbar row. */+ showStrip: boolean;+ /** The push-to-talk pill floats above the composer. */+ showHud: boolean;+ /** The mic is pressed, or held to talk: its button must stay where it is. */+ holding: boolean;+ /** No speech model is installed; the setup dialog is open for this composer. */+ showSetup: boolean;+ canSubmit: boolean;+ /** Spread on the composer root so the shortcut targets the last-used one. */+ onFocusCapture: () => void;+ /** Attach to the composer root so the shortcut skips it while it is off screen. */+ rootRef: (element: HTMLElement | null) => void;+}++const noSubscribe = () => () => {};++function onScreen(element: HTMLElement | null): boolean {+ if (!element) return true;+ if (!element.isConnected) return false;+ return typeof element.checkVisibility !== "function" || element.checkVisibility({ visibilityProperty: true });+}++export function useComposerVoice({+ insert,+ submit,+ activate,+ scope,+ hidden = false,+ disabled = false,+}: ComposerVoiceOptions): ComposerVoice {+ const id = useId();+ const engineAvailable = useVoiceModels()?.engineAvailable ?? false;+ const supported = useSyncExternalStore(noSubscribe, voiceInputSupported, () => false);+ const available = engineAvailable && supported && !disabled;+ const listening = available && !hidden;++ const callbacks = useRef({ insert, submit, activate });+ callbacks.current = { insert, submit, activate };+ const root = useRef<HTMLElement | null>(null);+ const rootRef = useCallback((element: HTMLElement | null) => {+ root.current = element;+ }, []);+ const canSubmit = submit !== undefined;++ useEffect(() => {+ if (!listening) return;+ return registerVoiceTarget(id, {+ insert: (text) => callbacks.current.insert(text),+ // Read at delivery: whether the composer can send may change mid-dictation.+ submit: () => callbacks.current.submit?.(),+ activate: () => callbacks.current.activate?.(),+ isShown: () => onScreen(root.current),+ });+ }, [listening, id, scope]);++ const state = useVoiceState();+ const session = listening && state.targetId === id ? state : null;+ const live =+ session?.phase === "requesting" ||+ session?.phase === "recording" ||+ session?.phase === "transcribing";+ return {+ id,+ available,+ session,+ busyElsewhere:+ state.targetId !== null && state.targetId !== id && state.phase !== "error" && state.phase !== "setup",+ showStrip: live && session?.mode === "strip",+ showHud: live && session?.mode === "hud",+ holding: live && session?.mode !== "strip",+ showSetup: session?.phase === "setup",+ canSubmit,+ onFocusCapture: () => noteVoiceFocus(id),+ rootRef,+ };+}diff --git a/packages/views/voice/voice-models.tsx b/packages/views/voice/voice-models.tsxnew file mode 100644index 0000000000..14289094be--- /dev/null+++ b/packages/views/voice/voice-models.tsx@@ -0,0 +1,220 @@+"use client";++import { useMemo } from "react";+import { Download, Mic, Trash2 } from "@multica/ui/icons";+import { Badge } from "@multica/ui/components/ui/badge";+import { Button } from "@multica/ui/components/ui/button";+import { IconButton } from "@multica/ui/components/common/icon-button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Progress } from "@multica/ui/components/ui/progress";+import {+ cancelVoice,+ pickVoiceModel,+ toggleVoice,+ useVoiceSettingsStore,+ type VoiceModel,+} from "@multica/core/voice";+import { formatBytes } from "../common/format-bytes";+import { useEditorOverlayOwner } from "../editor/overlay-owner";+import { useLocale, useT } from "../i18n";+import { localVoiceAPI } from "../platform/local-voice";+import { openExternal } from "../platform/open-external";+import { useVoiceModels } from "./engine";+import type { ComposerVoice } from "./use-composer-voice";++const LISTED_LANGUAGES = 5;++/** The first model that speaks the interface language, else the first one. */+function recommendedModel(models: VoiceModel[], locale: string): string | undefined {+ const base = locale.split("-")[0]?.toLowerCase() ?? "";+ return (models.find((model) => model.languages.includes(base)) ?? models[0])?.id;+}++function useLanguageList(languages: string[]): string {+ const { t } = useT("editor");+ const locale = useLocale();+ return useMemo(() => {+ let names: Intl.DisplayNames | null = null;+ try {+ names = new Intl.DisplayNames([locale], { type: "language" });+ } catch {+ names = null;+ }+ const shown = languages.slice(0, LISTED_LANGUAGES).map((code) => names?.of(code) ?? code);+ const more = languages.length - shown.length;+ if (more > 0) shown.push(t(($) => $.voice.models.more_languages, { more }));+ return new Intl.ListFormat(locale, { type: "conjunction" }).format(shown);+ }, [languages, locale, t]);+}++function ModelRow({+ model,+ recommended,+ active,+ manage,+ onDownload,+}: {+ model: VoiceModel;+ recommended: boolean;+ active: boolean;+ manage: boolean;+ onDownload: (id: string) => void;+}) {+ const { t } = useT("editor");+ const update = useVoiceSettingsStore((state) => state.update);+ const languages = useLanguageList(model.languages);+ const api = localVoiceAPI();+ const percent = model.sizeBytes > 0 ? Math.floor((model.receivedBytes / model.sizeBytes) * 100) : 0;+ const download = () => {+ onDownload(model.id);+ void api?.downloadModel(model.id);+ };+ return (+ <div className="flex items-center gap-4 px-4 py-3.5">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2 text-body font-medium">+ {model.name}+ {active && <Badge variant="secondary">{t(($) => $.voice.models.in_use)}</Badge>}+ {recommended && !active && <Badge variant="outline">{t(($) => $.voice.models.recommended)}</Badge>}+ {model.highlight && (+ <Badge variant="outline">+ {model.highlight === "accurate"+ ? t(($) => $.voice.models.most_accurate)+ : t(($) => $.voice.models.fastest)}+ </Badge>+ )}+ </div>+ <div className="mt-0.5 text-caption leading-5 text-muted-foreground">+ {languages} · <span className="whitespace-nowrap">{formatBytes(model.sizeBytes)}</span>+ </div>+ <div className="text-caption leading-5 text-muted-foreground">+ {t(($) => $.voice.models.by, { author: model.author })} ·{" "}+ <button+ type="button"+ className="underline underline-offset-3 hover:text-foreground"+ onClick={() => openExternal(model.licenseUrl)}+ >+ {t(($) => $.voice.models.license)}+ </button>+ </div>+ {model.status === "downloading" && (+ <Progress value={percent} className="mt-2" aria-label={t(($) => $.voice.models.downloading, { percent })} />+ )}+ {model.status === "absent" && model.error && (+ <div role="alert" className="mt-1 text-caption leading-5 text-destructive">+ {t(($) => $.voice.models.failed)}+ </div>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {model.status === "absent" && (+ <Button size="xs" variant="outline" onClick={download}>+ <Download />+ {model.error ? t(($) => $.voice.models.retry) : t(($) => $.voice.models.download)}+ </Button>+ )}+ {model.status === "downloading" && (+ <>+ <span className="text-caption tabular-nums text-muted-foreground">{percent}%</span>+ <Button size="xs" variant="ghost" onClick={() => void api?.cancelDownload(model.id)}>+ {t(($) => $.voice.models.cancel)}+ </Button>+ </>+ )}+ {model.status === "ready" && manage && (+ <>+ {!active && (+ <Button size="xs" variant="outline" onClick={() => update({ modelId: model.id })}>+ {t(($) => $.voice.models.use)}+ </Button>+ )}+ <IconButton+ label={t(($) => $.voice.models.delete, { name: model.name })}+ onClick={() => void api?.deleteModel(model.id)}+ >+ <Trash2 />+ </IconButton>+ </>+ )}+ </div>+ </div>+ );+}++/**+ * Desktop's speech models as rows, for a bordered list. `manage` adds+ * choosing between installed models and deleting them.+ */+export function VoiceModelRows({+ manage = false,+ onDownload = () => {},+}: {+ manage?: boolean;+ onDownload?: (id: string) => void;+}) {+ const snapshot = useVoiceModels();+ const preferred = useVoiceSettingsStore((state) => state.modelId);+ const locale = useLocale();+ if (!snapshot) return null;+ const active = pickVoiceModel(snapshot, preferred);+ const recommended = recommendedModel(snapshot.models, locale);+ return (+ <>+ {snapshot.models.map((model) => (+ <ModelRow+ key={model.id}+ model={model}+ active={model.id === active?.id}+ recommended={model.id === recommended}+ manage={manage}+ onDownload={onDownload}+ />+ ))}+ </>+ );+}++/** Shown when the mic is pressed before any speech model is installed. */+export function VoiceSetupDialog({ voice }: { voice: ComposerVoice }) {+ const { t } = useT("editor");+ const snapshot = useVoiceModels();+ const preferred = useVoiceSettingsStore((state) => state.modelId);+ const update = useVoiceSettingsStore((state) => state.update);+ const ready = pickVoiceModel(snapshot, preferred) !== null;+ // Opened from a popover composer (an annotation), it must not dismiss it.+ const overlayOwner = useEditorOverlayOwner();+ return (+ <Dialog+ open={voice.showSetup}+ onOpenChange={(open) => {+ if (!open) cancelVoice();+ }}+ >+ <DialogContent className="sm:max-w-lg" data-editor-overlay-owner={overlayOwner}>+ <DialogHeader>+ <DialogTitle>{t(($) => $.voice.setup.title)}</DialogTitle>+ <DialogDescription>{t(($) => $.voice.setup.description)}</DialogDescription>+ </DialogHeader>+ <div className="divide-y divide-surface-border rounded-lg border border-surface-border">+ <VoiceModelRows onDownload={(id) => update({ modelId: id })} />+ </div>+ <DialogFooter>+ <Button variant="ghost" onClick={cancelVoice}>+ {t(($) => $.voice.setup.later)}+ </Button>+ <Button disabled={!ready} onClick={() => toggleVoice(voice.id)}>+ <Mic />+ {t(($) => $.voice.setup.start)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/voice/voice-ui.tsx b/packages/views/voice/voice-ui.tsxnew file mode 100644index 0000000000..544db27ab2--- /dev/null+++ b/packages/views/voice/voice-ui.tsx@@ -0,0 +1,381 @@+"use client";++import { useEffect, useRef, type PointerEvent, type SyntheticEvent } from "react";+import { AlertCircle, Check, Mic, MicOff, RotateCcw, X } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { IconButton } from "@multica/ui/components/common/icon-button";+import { ShimmerText } from "@multica/ui/components/common/shimmer-text";+import { SubmitButton } from "@multica/ui/components/common/submit-button";+import { cn } from "@multica/ui/lib/utils";+import { createShortcutChord } from "@multica/core/shortcuts";+import {+ cancelVoice,+ noteVoiceFocus,+ pressVoice,+ releaseVoice,+ retryVoice,+ stopVoice,+ toggleVoice,+ useVoiceMeter,+ useVoiceSettingsStore,+ type VoiceErrorKind,+} from "@multica/core/voice";+import { ActionShortcutKeycaps, ShortcutKeycaps } from "../common/shortcut-keycaps";+import { useT } from "../i18n";+import { METER_INTERVAL_MS } from "./recorder";+import type { ComposerVoice } from "./use-composer-voice";++const ESCAPE = createShortcutChord("Escape");+const ENTER = createShortcutChord("Enter");++/** Keep the caret in the composer when a voice control is clicked. */+function keepFocusInComposer(event: SyntheticEvent) {+ event.preventDefault();+}++function formatElapsed(ms: number): string {+ const total = Math.floor(ms / 1000);+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;+}++const clamp01 = (value: number) => Math.min(1, Math.max(0, value));++/** Recorder level (RMS × 5) to bar height: a noise gate, then a gentle curve so quiet speech still moves. */+function perceptual(level: number): number {+ return Math.pow(clamp01((level - 0.035) / 0.6), 0.8);+}++const easeOut = (t: number) => 1 - Math.pow(1 - t, 3);++const WAVE_GEOMETRY = {+ strip: { pitch: 5, bar: 3, fade: 24 },+ hud: { pitch: 4.5, bar: 2.5, fade: 14 },+} as const;++/**+ * Scrolling level history, newest sample on the right. Silence is a row of+ * faint dots; speech stretches dots into capsules. Drawn on a canvas so it+ * glides between the recorder's samples instead of stepping.+ */+function Waveform({ density, className }: { density: keyof typeof WAVE_GEOMETRY; className?: string }) {+ const { levels } = useVoiceMeter();+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const latest = useRef({ levels, at: 0 });++ useEffect(() => {+ latest.current = { levels, at: performance.now() };+ }, [levels]);++ useEffect(() => {+ const canvas = canvasRef.current;+ const ctx = canvas?.getContext("2d");+ if (!canvas || !ctx) return;+ const { pitch, bar, fade } = WAVE_GEOMETRY[density];+ const still = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;+ const color = getComputedStyle(canvas).color;+ let width = 0;+ let height = 0;+ const resize = () => {+ const rect = canvas.getBoundingClientRect();+ const dpr = window.devicePixelRatio || 1;+ width = rect.width;+ height = rect.height;+ canvas.width = Math.round(width * dpr);+ canvas.height = Math.round(height * dpr);+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ };+ const capsule = (x: number, length: number) => {+ const h = Math.max(bar, length);+ ctx.beginPath();+ ctx.roundRect(x, (height - h) / 2, bar, h, bar / 2);+ ctx.fill();+ };+ const observer = new ResizeObserver(resize);+ observer.observe(canvas);+ resize();++ let raf = 0;+ const frame = () => {+ const { levels, at } = latest.current;+ const progress = still ? 1 : clamp01((performance.now() - at) / METER_INTERVAL_MS);+ ctx.clearRect(0, 0, width, height);+ ctx.fillStyle = color;+ const slots = Math.ceil(width / pitch) + 2;+ for (let k = 0; k < slots; k++) {+ const x = width - bar - (k + progress) * pitch;+ if (x < -bar) break;+ const edge = clamp01(x / fade);+ const p = perceptual(levels[levels.length - 1 - k] ?? 0);+ if (p < 0.08) {+ ctx.globalAlpha = 0.4 * edge;+ capsule(x, bar);+ continue;+ }+ ctx.globalAlpha = edge;+ capsule(x, bar + (height - bar) * p * (k === 0 ? easeOut(progress) : 1));+ }+ raf = requestAnimationFrame(frame);+ };+ raf = requestAnimationFrame(frame);+ return () => {+ cancelAnimationFrame(raf);+ observer.disconnect();+ };+ }, [density]);++ return <canvas ref={canvasRef} aria-hidden className={cn("block h-5 w-full", className)} />;+}++/** Three bars that fit where the mic icon was. */+function LevelBars() {+ const { levels } = useVoiceMeter();+ const n = levels.length;+ const picks = [levels[n - 3] ?? 0, levels[n - 1] ?? 0, levels[n - 5] ?? 0];+ const shape = [0.7, 1, 0.8];+ return (+ <span aria-hidden className="flex h-3.5 items-center gap-[2px]">+ {picks.map((level, index) => (+ <span+ key={index}+ className="w-[3px] rounded-full bg-current transition-[height] duration-75"+ style={{ height: `${Math.max(22, Math.min(100, level * (shape[index] ?? 1) * 130))}%` }}+ />+ ))}+ </span>+ );+}++function Elapsed({ className }: { className?: string }) {+ const { elapsedMs } = useVoiceMeter();+ return <span className={cn("text-caption tabular-nums", className)}>{formatElapsed(elapsedMs)}</span>;+}++function RecDot({ className }: { className?: string }) {+ return (+ <span+ aria-hidden+ className={cn("size-2 shrink-0 rounded-full bg-destructive motion-safe:animate-pulse", className)}+ />+ );+}++/**+ * The mic every composer carries. Tap to dictate into the toolbar strip;+ * press and hold to talk, release to insert.+ */+export function VoiceMicButton({ voice, className }: { voice: ComposerVoice; className?: string }) {+ const { t } = useT("editor");+ const activation = useVoiceSettingsStore((state) => state.activation);+ if (!voice.available) return null;+ const { session } = voice;+ const live =+ session !== null &&+ (session.phase === "requesting" || session.phase === "recording") &&+ session.mode !== "strip";+ const label =+ activation === "hold"+ ? t(($) => $.voice.hold_to_talk)+ : activation === "toggle"+ ? t(($) => $.voice.dictate)+ : t(($) => $.voice.tap_or_hold);+ return (+ <IconButton+ label={label}+ shortcut={<ActionShortcutKeycaps action="voiceInput" />}+ disabled={voice.busyElsewhere}+ aria-pressed={live}+ onMouseDown={keepFocusInComposer}+ onPointerDown={(event: PointerEvent<HTMLButtonElement>) => {+ if (event.button !== 0) return;+ event.preventDefault();+ event.currentTarget.setPointerCapture(event.pointerId);+ noteVoiceFocus(voice.id);+ pressVoice(voice.id);+ }}+ onPointerUp={releaseVoice}+ onPointerCancel={releaseVoice}+ onClick={(event) => {+ // Keyboard activation (Enter/Space on the focused button) has no+ // pointer phase and cannot be held.+ if (event.detail === 0) toggleVoice(voice.id);+ }}+ className={cn(+ "touch-none text-muted-foreground",+ live && "bg-brand/10 text-brand hover:bg-brand/15 hover:text-brand",+ className,+ )}+ >+ {live && session.phase === "recording" ? <LevelBars /> : <Mic />}+ </IconButton>+ );+}++/**+ * The recording strip. Replaces the composer's toolbar row while a tapped+ * recording runs: cancel, timer, waveform, insert, send.+ */+export function VoiceStrip({ voice }: { voice: ComposerVoice }) {+ const { t } = useT("editor");+ const phase = voice.session?.phase;+ if (!voice.showStrip) return null;+ if (phase === "transcribing") {+ return (+ <div className="flex min-w-0 flex-1 items-center gap-1" aria-live="polite">+ <span className="flex size-[var(--button-height-sm)] shrink-0 items-center justify-center">+ <Mic className="size-4 text-muted-foreground" />+ </span>+ <ShimmerText className="ml-1 truncate text-caption font-medium text-muted-foreground">+ {t(($) => $.voice.transcribing)}+ </ShimmerText>+ </div>+ );+ }+ return (+ <div className="flex min-w-0 flex-1 items-center gap-1">+ <IconButton+ label={t(($) => $.voice.cancel)}+ shortcut={<ShortcutKeycaps shortcut={ESCAPE} decorative />}+ onMouseDown={keepFocusInComposer}+ onClick={cancelVoice}+ className="text-muted-foreground"+ >+ <X />+ </IconButton>+ {phase === "requesting" ? (+ <ShimmerText className="ml-1 min-w-0 flex-1 truncate text-caption font-medium text-muted-foreground">+ {t(($) => $.voice.requesting)}+ </ShimmerText>+ ) : (+ <>+ <span className="flex shrink-0 items-center gap-1.5 pl-1 pr-2" role="status">+ <RecDot />+ <span className="sr-only">{t(($) => $.voice.recording)}</span>+ <Elapsed className="text-muted-foreground" />+ </span>+ <Waveform density="strip" className="min-w-0 flex-1 text-foreground" />+ <IconButton+ label={t(($) => $.voice.insert)}+ shortcut={<ActionShortcutKeycaps action="voiceInput" />}+ onMouseDown={keepFocusInComposer}+ onClick={() => stopVoice(false)}+ className="ml-1 text-foreground"+ >+ <Check />+ </IconButton>+ {voice.canSubmit && (+ <SubmitButton+ onClick={() => stopVoice(true)}+ ariaLabel={t(($) => $.voice.send)}+ tooltip={+ <>+ {t(($) => $.voice.send)}+ <ShortcutKeycaps shortcut={ENTER} decorative />+ </>+ }+ />+ )}+ </>+ )}+ </div>+ );+}++/**+ * The push-to-talk pill, anchored above the composer that receives the text.+ * Always dark ink, like a system indicator, so it reads over any page. The+ * composer root must be `relative`.+ */+export function VoiceHud({ voice }: { voice: ComposerVoice }) {+ const { t } = useT("editor");+ const phase = voice.session?.phase;+ if (!voice.showHud) return null;+ return (+ <div className="pointer-events-none absolute bottom-full left-1/2 z-30 mb-3 -translate-x-1/2">+ <div+ role="status"+ className="flex h-10 items-center gap-2.5 whitespace-nowrap rounded-full bg-multica-ink pl-3.5 pr-4 text-multica-paper shadow-[var(--floating-shadow)] animate-in fade-in zoom-in-95 slide-in-from-bottom-2"+ >+ {phase === "recording" ? (+ <>+ <RecDot className="bg-[#ff5a52]" />+ <span className="sr-only">{t(($) => $.voice.recording)}</span>+ <Waveform density="hud" className="w-[86px]" />+ <Elapsed className="opacity-70" />+ <span className="text-caption opacity-70">{t(($) => $.voice.release_to_insert)}</span>+ </>+ ) : (+ <>+ <Mic className="size-4 opacity-70" />+ <span className="text-caption opacity-80">+ {phase === "transcribing" ? t(($) => $.voice.transcribing) : t(($) => $.voice.requesting)}+ </span>+ </>+ )}+ </div>+ </div>+ );+}++function useErrorMessage(error: VoiceErrorKind): string {+ const { t } = useT("editor");+ switch (error) {+ case "permission-denied":+ return t(($) => $.voice.errors.permission_denied);+ case "no-microphone":+ return t(($) => $.voice.errors.no_microphone);+ case "no-speech":+ return t(($) => $.voice.errors.no_speech);+ case "unavailable":+ return t(($) => $.voice.errors.unavailable);+ case "transcription-failed":+ return t(($) => $.voice.errors.transcription_failed);+ case "failed":+ return t(($) => $.voice.errors.microphone_failed);+ }+}++/** One-line error inside the composer, above its toolbar. */+export function VoiceErrorRow({ voice, className }: { voice: ComposerVoice; className?: string }) {+ const error = voice.session?.phase === "error" ? voice.session.error : null;+ if (!error) return null;+ return <VoiceErrorContent error={error} className={className} />;+}++function VoiceErrorContent({ error, className }: { error: VoiceErrorKind; className?: string }) {+ const { t } = useT("editor");+ const message = useErrorMessage(error);+ const Icon = error === "permission-denied" || error === "no-microphone" ? MicOff : AlertCircle;+ return (+ <div+ role="alert"+ className={cn(+ "flex items-center gap-2 rounded-md bg-destructive/8 px-2 py-1 text-caption text-destructive",+ className,+ )}+ >+ <Icon className="size-3.5 shrink-0" aria-hidden />+ <span className="min-w-0 flex-1">{message}</span>+ {error !== "unavailable" && (+ <Button+ size="xs"+ variant="ghost"+ className="text-destructive hover:text-destructive"+ onMouseDown={keepFocusInComposer}+ onClick={retryVoice}+ >+ <RotateCcw />+ {t(($) => $.voice.retry)}+ </Button>+ )}+ <Button+ size="xs"+ variant="ghost"+ className="text-muted-foreground"+ onMouseDown={keepFocusInComposer}+ onClick={cancelVoice}+ >+ {t(($) => $.voice.dismiss)}+ </Button>+ </div>+ );+}diff --git a/packages/views/voice/workspace-words.tsx b/packages/views/voice/workspace-words.tsxnew file mode 100644index 0000000000..e2b9dc2b93--- /dev/null+++ b/packages/views/voice/workspace-words.tsx@@ -0,0 +1,32 @@+"use client";++import { useEffect } from "react";+import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core";+import { projectListOptions } from "@multica/core/projects/queries";+import { setVoiceContextWords } from "@multica/core/voice";+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";++/**+ * Offer the workspace's agent, member and project names to the speech model+ * as hotwords. Mount once inside a resolved workspace, next to+ * WorkspacePresencePrefetch.+ */+export function VoiceWorkspaceWords() {+ const wsId = useWorkspaceId();+ const { data: agents } = useQuery(agentListOptions(wsId));+ const { data: members } = useQuery(memberListOptions(wsId));+ const { data: projects } = useQuery(projectListOptions(wsId));++ useEffect(() => {+ setVoiceContextWords([+ ...(agents ?? []).filter((agent) => !agent.archived_at).map((agent) => agent.name),+ ...(members ?? []).map((member) => member.name),+ ...(projects ?? []).map((project) => project.title),+ ]);+ }, [agents, members, projects]);++ useEffect(() => () => setVoiceContextWords([]), [wsId]);++ return null;+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8e06a54147..f0a232d5a8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -363,6 +363,9 @@ importers:jsdom:specifier: 'catalog:'version: 29.0.1(@noble/[email protected])+ sherpa-onnx-node:+ specifier: 2.0.1+ version: 2.0.1tailwindcss:specifier: 'catalog:'version: 4.2.2@@ -10623,6 +10626,44 @@ packages:resolution: {integrity: sha512-Iov+JwFv/2HcTpcwNMKd8+IWNb8tboQJNQTkAY/LLVK7gGH9jy+LGkVqPxfekHl+yMmiqXszdGWXgkfml7hjqA==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-agXmbbwiVPUSMViMhWhYAt59iG21ui7x6HxQFU35XzHOfQe9x6Pg9V160Pzak/66x0ePMjixsLUtMaaUrLfCwQ==}+ cpu: [arm64]+ os: [darwin]++ resolution: {integrity: sha512-SBnHa3LDOSI/5/rpBHGxKQDFq+yIdxowYY0InLzfojTUx+yGgqu7cYBrRxjzvHOiOKi0O4rmlFVZboyhIqpDgA==}+ cpu: [x64]+ os: [darwin]++ resolution: {integrity: sha512-5CJvLjFYIg23oELCsT7l07fMLT3PdquZ3tqh7KZK3Pzi+c2YiPKRe1DDUxoNdtCaw3ZiS4aQSQPBblB9JStuDA==}+ cpu: [arm64]+ os: [linux]++ resolution: {integrity: sha512-w5mRRrIvPvcNWac7rQ8AN/t/cwElPGoRpH+ceCRBV7XfjCIQ9Rcr3Ig/kXcJLNOxgK4bGmef+Y47lIWiesDODw==}+ cpu: [x64]+ os: [linux]++ resolution: {integrity: sha512-1PSACfQgPXAD7ExwCv1QW09EXTjcNlpZKBqDY+jxSdIzlyOSq0M13SILBoUQUfeJqiTTXnqp6Ha9jjMUQ6efXg==}++ resolution: {integrity: sha512-Mb9iqy2Zp7GC5a99dk5E8EQJsEBnapf+IcwHLVCgtIf5mxYHO9Q8YptnAoOHZOD0Zi+R+MblFyG9qv0Q6tin4Q==}+ cpu: [arm64]+ os: [win32]++ resolution: {integrity: sha512-q7qFCA3FK+tYc8pexC9Kzu9WGGoZ9X//UkpxVp6iT4E4W5tPhOEirPyvawS6zgfEW6K/GOISMcYe996Yc7d6iw==}+ cpu: [ia32]+ os: [win32]++ resolution: {integrity: sha512-7vwdAw9PGEb0JLSpK7UFxAdp1vabBHK9Nhw2jFRBWSFgtslUPHIB0T6syJfRgiUGyCeNW9fJvcFAk2F2u7hBEw==}+ cpu: [x64]+ os: [win32]+resolution: {integrity: sha512-55Dj73uq9ZXL5zyeRPzHQsK7Nbyt6Y10k5s7OjuFZGMhpp4r/rsLBH0o/0fstIzX1Lep9VxefWljK/SKCzygIA==}@@ -22785,6 +22826,37 @@ snapshots:+ optional: true++ optional: true++ optional: true++ optional: true++ optionalDependencies:+ sherpa-onnx-darwin-arm64: 2.0.1+ sherpa-onnx-darwin-x64: 2.0.1+ sherpa-onnx-linux-arm64: 2.0.1+ sherpa-onnx-linux-x64: 2.0.1+ sherpa-onnx-win-arm64: 2.0.1+ sherpa-onnx-win-ia32: 2.0.1+ sherpa-onnx-win-x64: 2.0.1++ optional: true++ optional: true++ optional: true+dependencies:'@shikijs/core': 3.23.0