A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): 输入框能语音输入,识别在服务器上做
lmliheng437ff93e8a77
diff --git a/changelog/unreleased/2026-11-07-speech-input.md b/changelog/unreleased/2026-11-07-speech-input.mdnew file mode 100644index 00000000..0dca4bc8--- /dev/null+++ b/changelog/unreleased/2026-11-07-speech-input.md@@ -0,0 +1,84 @@+# The composer takes dictation: a microphone beside the +, transcribed on the server++- **Date:** 2026-11-07+- **Type:** feature+- **Scope:** `server`, `web`, `ui`+- **Breaking:** no++[中文](2026-11-07-speech-input.zh.md)++Until now the only way into a Session was the keyboard. The composer now carries a microphone button,+and what it records is transcribed and dropped into the draft, where it can be read and edited before+it is sent.++The transcription happens on the **server**, not in the page. The desktop shell has no Web Speech API,+so a browser-side recognizer would make the Web App and the desktop app behave differently on the same+account; and the provider's key then lives in one place, on the server, instead of being handed to+every browser that opens the page. What the page sends is the recording itself, over the session's own+credentials, and nothing of it is written to disk.++Which provider does the transcribing is a Server setting — the same shape as the other per-deployment+settings: the address of the service, the model id, and the key. The key is write-only, exactly like a+Project's model credentials: the settings page reads back whether one is stored, never the value, so an+admin editing the model does not have to paste the key again.++## The recording++- A click starts the recording, the button turns into the way to end it, and a second click stops and+ transcribes. The label says which half is running — a recording nobody has ended and a recording+ being transcribed look alike otherwise, and only one of them is waiting on the user.+- The audio is decoded and downmixed in the page and sent as raw 16-bit PCM at 16 kHz — the sample+ rate the streaming protocol documents — so nothing about the container the browser chose reaches the+ provider.+- Two things are said where the draft is, not as a toast that dismisses itself: a recording that came+ back empty ("没有听清,请再说一次。"), and a microphone that was refused before any recording began.+ A refusal from the provider — a key that is not accepted, a model the account cannot use — is shown+ in the provider's own words, since that sentence names what to fix and the settings page is where it+ is fixed.++## Details++- `packages/server/src/services/asr.ts` (new): one WebSocket per utterance against the streaming+ protocol — `run-task` naming the model and the audio format, the audio in ~100 ms frames,+ `finish-task`, then `result-generated` sentences until `task-finished`. The transport's shape never+ leaves the file: frames become an ordered queue so nothing is lost between the handshake and the+ collect loop, and a stalled service surfaces as a timeout rather than a hanging request.+- `packages/server/src/http/routes/asr.ts` (new): `GET|PUT /api/asr/config` is an admin's (it holds the+ key); `POST /api/asr/transcribe` is every signed-in user's. An empty or omitted `apiKey` on a PUT+ keeps the stored one, and every field is validated before any is written.+- `packages/server/src/db/repos/server-settings.ts`, `.../mechanisms/settings.ts`: the three values,+ as one more settings group.+- `packages/web/src/lib/asr-audio.ts` (new): decode, mix to mono, resample, PCM16, base64.+- `packages/web/src/features/chat/use-asr-recorder.ts` (new): the recording's state machine+ (`idle | recording | transcribing`) and its notices.+- `packages/web/src/features/settings/asr-section.tsx` (new) and `.../settings-dialog.tsx`: the "语音+ 输入" page under Server, for admins.+- `packages/web/src/features/chat/chat-input.tsx`: the microphone, the notice line above the composer.+- `packages/ui/src/components/icons/icons.ts`: a `microphone` icon.++## Tests++- `packages/server/test/asr.test.ts` (new, 15 cases, against a local socket speaking the protocol):+ the `Authorization` header, the model and audio parameters the provider is told, the audio's own+ bytes, `finish-task`, several sentences joined in arrival order, an empty answer as a success,+ `task-failed` read back in the provider's words, an unreachable service, and the refusals — empty+ audio, an odd byte count, over the length cap, an unaccepted sample rate, a non-admin asking for the+ key, and an invalid address never reaching storage.+- `packages/web/test/asr-audio.test.ts` (new, 7 cases): decode, downmix, resample, PCM16 conversion+ and base64 — including stereo and a sample rate that is not the recording's.+- `packages/web/e2e/asr-dictation.spec.mjs` (scratchpad; real browser, real server, a fake speech+ service): the settings page saves an address, a model and a key and the server reads back `hasKey`;+ then Chromium's fake microphone plays a WAV file, the button records real audio, and the sentence+ the service answers with lands in the draft.+- `packages/server/test/hot-replace.test.ts`: the Settings double gains the two new methods.++## Compatibility++No API removed. One new settings group, stored as KV rows like the rest; an unconfigured server keeps+its old behaviour — the microphone button reports that no model is configured and points at the+settings page. The default address and model are TokenDance's, so a deployment holding a TokenDance+key needs only the key pasted in.++**The end-to-end run was verified against a fake speech service, not against a live provider:** the+TokenDance key at hand is refused by TokenDance itself (`unauthorized / API 密钥不存在`), so a real+transcript has not been observed yet.diff --git a/changelog/unreleased/2026-11-07-speech-input.zh.md b/changelog/unreleased/2026-11-07-speech-input.zh.mdnew file mode 100644index 00000000..55f4d285--- /dev/null+++ b/changelog/unreleased/2026-11-07-speech-input.zh.md@@ -0,0 +1,69 @@+# 输入框能听写了:加号旁边多一个麦克风,识别在服务器上做++- **日期:** 2026-11-07+- **类型:** feature+- **范围:** `server`、`web`、`ui`+- **破坏性:** 否++[English](2026-11-07-speech-input.md)++此前进入一个 Session 只有键盘一条路。输入框现在多一个麦克风按钮,录下的音频转成文字落进草稿框,发送前+还能读一遍、改一改。++识别在**服务器**上做,不在页面里。桌面外壳没有 Web Speech API,把识别放浏览器里会让同一个账号在网页版+和桌面版上表现不同;密钥也因此只留在这台服务器上,不随每个打开页面的浏览器下发。页面发出去的是录音本身,+沿用会话自己的凭据,且不会写进磁盘任何一处。++用哪个服务商来识别是「服务器」分组里的一项设置,与其它部署级设置同一种形态:服务地址、模型 ID、API 密钥。+密钥是只写的,和项目里的模型凭据一样 —— 设置页读回来的是「有没有存过」,不是密钥本身,管理员只改模型时+不必重新贴一遍密钥。++## 录音这一侧++- 点一下开始录,按钮变成结束它入口,再点一下结束并识别。两个在途状态各自有说明:录完了没人按结束,与正在+ 识别,看上去一模一样,但只有一种在等用户动手。+- 音频在页面里解码、混成单声道,按 16 kHz 的 16 位 PCM 发出 —— 流式协议文档上的采样率 —— 浏览器挑了什么+ 容器都到不了服务商那边。+- 两件事说在草稿框那儿,而不是丢进一条自己会消失的通知:录到一片安静(「没有听清,请再说一次。」),以及+ 还没开录就被拒的麦克风。服务商自己的拒绝 —— 密钥不被接受、账号用不了这个模型 —— 按服务商的原话显示,+ 那句话点明了该改什么,而该改的地方就在设置页。++## 明细++- `packages/server/src/services/asr.ts`(新):一句录音一条 WebSocket,走流式协议 —— `run-task` 报出+ 模型与音频格式,音频按约 100 ms 一帧发送,`finish-task`,然后收 `result-generated` 的句子直到+ `task-finished`。传输层的形态不出这个文件:帧排成有序队列,握手与收帧之间不会丢东西,卡住的服务表现为+ 超时而不是挂住请求。+- `packages/server/src/http/routes/asr.ts`(新):`GET|PUT /api/asr/config` 归管理员(密钥在这儿);+ `POST /api/asr/transcribe` 归任何已登录用户。PUT 里空着或没给 `apiKey` 就沿用已存的那把,且每个字段都+ 先校验完再落盘。+- `packages/server/src/db/repos/server-settings.ts`、`.../mechanisms/settings.ts`:这三个取值,多出+ 一组设置。+- `packages/web/src/lib/asr-audio.ts`(新):解码、混单声道、重采样、PCM16、base64。+- `packages/web/src/features/chat/use-asr-recorder.ts`(新):录音的状态机+ (`idle | recording | transcribing`)与它的提示。+- `packages/web/src/features/settings/asr-section.tsx`(新)与 `.../settings-dialog.tsx`:「服务器」+ 分组下的「语音输入」页,仅管理员。+- `packages/web/src/features/chat/chat-input.tsx`:麦克风按钮,以及输入框上方那一行提示。+- `packages/ui/src/components/icons/icons.ts`:新增 `microphone` 图标。++## 测试++- `packages/server/test/asr.test.ts`(新,15 条,对着一个本地说这套协议的套接字跑):`Authorization`+ 头、告诉服务商的模型与音频参数、音频本身的字节数、`finish-task`、多句按到达顺序拼接、空结果算成功、+ `task-failed` 按服务商原话读回、服务不可达,以及各条拒绝 —— 空音频、奇数长度、超过时长上限、不受支持的+ 采样率、非管理员来读密钥、非法地址不落盘。+- `packages/web/test/asr-audio.test.ts`(新,7 条):解码、混单声道、重采样、PCM16 转换与 base64 ——+ 含立体声与不是录音采样率的那种输入。+- `packages/web/e2e/asr-dictation.spec.mjs`(脚手架里;真浏览器、真服务端、一个假语音服务):设置页存下+ 地址、模型与密钥,服务端读回 `hasKey`;随后 Chromium 的假麦克风播放一个 WAV 文件,按钮录到真音频,服务+ 商答的那句话落进草稿框。+- `packages/server/test/hot-replace.test.ts`:设置替身补上这两个新方法。++## 兼容性++没有删任何接口。多一组设置,与其它设置一样按 KV 行存放;没配过的服务器行为不变 —— 麦克风按钮会说还没有+配置识别模型,并指向设置页。默认地址与模型是词元跳动的,因此手上已有词元跳动密钥的部署只需把密钥贴进去。++**端到端那一次是对着假语音服务验的,不是对着真服务商:** 手上这把词元跳动的密钥被词元跳动自己拒了+(`unauthorized / API 密钥不存在`),因此真识别结果还没有看到过。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex e3ea0caa..74f9ded8 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -320,6 +320,57 @@ export interface ServerSettingsResponse {settings: ServerSettings;}+/**+ * Speech input — the composer's microphone (GET|PUT /api/asr/config, admin only).+ *+ * The recognition runs on the server, never in the browser: the desktop shell has no Web+ * Speech API, so a browser-side recognizer would make the two clients behave differently,+ * and the key would have to be handed to every browser that opens the page. The recording+ * goes up to this server, and this server makes the provider call with the key stored here.+ *+ * `baseUrl` and `model` are never empty (an unset one is the built-in default), so the page+ * shows what a recording would actually use. `apiKey` is write-only — the read carries+ * `hasKey` instead, the same rule a Project's model credentials follow.+ */+export interface AsrConfig {+ /** The speech provider's site, e.g. `https://tokendance.space`. */+ baseUrl: string;+ /** The upstream model id. */+ model: string;+ /** Whether a key is stored. The key itself never crosses this boundary. */+ hasKey: boolean;+}++export interface AsrConfigResponse {+ config: AsrConfig;+}++export interface AsrConfigUpdateRequest {+ baseUrl?: string;+ model?: string;+ /** Omitted or empty keeps the stored key; a non-empty value replaces it. */+ apiKey?: string;+}++/**+ * POST /api/asr/transcribe request: one utterance, base64 as every other binary body in this+ * API is (the composer records raw little-endian PCM16 mono and encodes it here).+ */+export interface AsrTranscribeRequest {+ /** The recording, base64-encoded. */+ dataBase64: string;+ /** 8000 or 16000; omitted takes 16000, the rate the composer records at. */+ sampleRate?: number;+}++/**+ * POST /api/asr/transcribe result: the transcript of one uploaded utterance, which may be+ * empty — silence is a legitimate answer and is not an error.+ */+export interface AsrTranscribeResponse {+ text: string;+}+/*** The data root's storage ledger (GET /api/admin/storage) — what is on disk under* `ADELIE_HOME`, what each thing is for, and what a person could clean up.diff --git a/packages/server/src/db/repos/server-settings.ts b/packages/server/src/db/repos/server-settings.tsindex ee67ea62..41ffdc50 100644--- a/packages/server/src/db/repos/server-settings.ts+++ b/packages/server/src/db/repos/server-settings.ts@@ -8,9 +8,10 @@ import {DEFAULT_ATTACHMENT_MAX_MB,DEFAULT_ATTACHMENT_TOTAL_MB,} from "../../services/attachment-limits.js";+import { DEFAULT_ASR_BASE_URL, DEFAULT_ASR_MODEL } from "../../services/asr.js";import { Component, Use } from "@adelie/core/kernel";import type { Db } from "../../hmr/capabilities.js";-import type { Settings } from "../../mechanisms/settings.js";+import type { AsrSettings, Settings } from "../../mechanisms/settings.js";/** Key of the "application uses the proxy" switch (the server's own outbound dispatcher); default on. */const PROXY_FOR_APP_KEY = "proxy_for_app";@@ -39,6 +40,11 @@ const COMPANY_MODE_KEY = "companyMode";/** Key of the Agent API switch; default on (see getAgentApiEnabled). */const AGENT_API_KEY = "agentApiEnabled";+/** Speech input: the provider site, the model id, and the key to ask it with (see getAsrSettings). */+const ASR_BASE_URL_KEY = "asrBaseUrl";+const ASR_MODEL_KEY = "asrModel";+const ASR_API_KEY = "asrApiKey";+@Component()export class ServerSettingsRepo implements Settings {@Use() private readonly db!: Db;@@ -182,4 +188,36 @@ export class ServerSettingsRepo implements Settings {setAgentApiEnabled(value: boolean): void {this.set(AGENT_API_KEY, JSON.stringify(value));}++ /**+ * Speech input settings. The site and the model read as the built-in defaults when their rows+ * are absent or unreadable — the page must show what a recording would actually use, and a+ * blank field that silently meant "the default" would not. The key has no default: an unset+ * one reads as "", and the transcribe route turns that into its own refusal.+ */+ getAsrSettings(): AsrSettings {+ return {+ baseUrl: this.getString(ASR_BASE_URL_KEY, DEFAULT_ASR_BASE_URL),+ model: this.getString(ASR_MODEL_KEY, DEFAULT_ASR_MODEL),+ apiKey: this.getString(ASR_API_KEY, ""),+ };+ }++ setAsrSettings(value: AsrSettings): void {+ this.set(ASR_BASE_URL_KEY, JSON.stringify(value.baseUrl));+ this.set(ASR_MODEL_KEY, JSON.stringify(value.model));+ this.set(ASR_API_KEY, JSON.stringify(value.apiKey));+ }++ /** A stored JSON string, or `fallback` when the row is absent, unreadable, blank or not a string. */+ private getString(key: string, fallback: string): string {+ const raw = this.get(key);+ if (raw === null) return fallback;+ try {+ const value: unknown = JSON.parse(raw);+ return typeof value === "string" && value.trim() !== "" ? value : fallback;+ } catch {+ return fallback;+ }+ }}diff --git a/packages/server/src/http/routes/asr.ts b/packages/server/src/http/routes/asr.tsnew file mode 100644index 00000000..a6b05c8a--- /dev/null+++ b/packages/server/src/http/routes/asr.ts@@ -0,0 +1,202 @@+/**+ * Speech input routes — the composer's microphone.+ *+ * GET|PUT /api/asr/config is an admin's: it holds the provider key the server transcribes+ * with, and every browser that opens a page would otherwise be able to read it. The read is+ * masked the way a Project's model credentials are — `hasKey`, never the key — and a PUT+ * that omits `apiKey` (or sends an empty one) keeps whatever is stored.+ *+ * POST /api/asr/transcribe is every signed-in user's: the admin configured the key, and+ * anyone may then talk into it. The body carries the utterance itself — raw little-endian+ * PCM16 mono, base64 like every other binary body in this API — which is forwarded to the+ * provider and never written to disk. The answer is the transcript, which may be empty:+ * silence is not an error.+ */+import { Hono } from "hono";+import type { AsrConfig, AsrConfigResponse, AsrTranscribeResponse } from "../../api/types.js";+import { HttpError } from "../errors.js";+import { readJson } from "../validate.js";+import { Bind, Component, Use } from "@adelie/core/kernel";+import type { AppEnv } from "../../auth/middleware.js";+import type { Settings } from "../../mechanisms/settings.js";+import {+ ASR_MAX_BYTES,+ ASR_SAMPLE_RATE,+ AsrError,+ DEFAULT_ASR_BASE_URL,+ DEFAULT_ASR_MODEL,+ transcribeStreaming,+} from "../../services/asr.js";++/** Sample rates a recording may arrive at; the protocol accepts these and nothing else. */+const ACCEPTED_SAMPLE_RATES = [8_000, ASR_SAMPLE_RATE];++/** What this route group reaches — bound by its module (src/modules). */+export interface AsrRouteDeps {+ settings: Settings;+}++export function asrRoutes(deps: AsrRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ /** The masked view: the key is write-only, so only its presence is reported. */+ const config = (): AsrConfig => {+ const stored = deps.settings.getAsrSettings();+ return { baseUrl: stored.baseUrl, model: stored.model, hasKey: stored.apiKey !== "" };+ };++ const requireAdmin = async (c: { var: AppEnv["Variables"] }, next: () => Promise<void>) => {+ if (!c.var.user.isAdmin) {+ throw new HttpError(403, "admin_required", "Only an admin can perform this operation.");+ }+ await next();+ };++ app.get("/config", requireAdmin, (c) => c.json({ config: config() } satisfies AsrConfigResponse));++ app.put("/config", requireAdmin, async (c) => {+ const body = await readJson(c);+ const stored = deps.settings.getAsrSettings();+ // Every field is validated before any is written, so a PUT naming one bad value leaves+ // the rest as they were.+ const baseUrl =+ body.baseUrl === undefined+ ? stored.baseUrl+ : body.baseUrl === null+ ? DEFAULT_ASR_BASE_URL+ : parseBaseUrl(body.baseUrl);+ const model =+ body.model === undefined+ ? stored.model+ : body.model === null+ ? DEFAULT_ASR_MODEL+ : parseModel(body.model);+ // Omitted or empty keeps the stored key — the read never hands it back, so a page that+ // only edits the model must not have to blank its own credential to save.+ const apiKey =+ body.apiKey === undefined+ ? stored.apiKey+ : typeof body.apiKey === "string" && body.apiKey.trim() === ""+ ? stored.apiKey+ : parseApiKey(body.apiKey);+ deps.settings.setAsrSettings({ baseUrl, model, apiKey });+ return c.json({ config: config() } satisfies AsrConfigResponse);+ });++ app.post("/transcribe", async (c) => {+ const stored = deps.settings.getAsrSettings();+ if (stored.apiKey === "") {+ throw new HttpError(+ 400,+ "asr_not_configured",+ "No speech model is configured: set one under Settings > Server > Speech input.",+ );+ }+ const body = await readJson(c);+ const sampleRate = parseSampleRate(body.sampleRate);+ const pcm = parseAudio(body.dataBase64);+ try {+ const text = await transcribeStreaming({+ baseUrl: stored.baseUrl,+ model: stored.model,+ apiKey: stored.apiKey,+ pcm,+ sampleRate,+ });+ return c.json({ text } satisfies AsrTranscribeResponse);+ } catch (err) {+ if (err instanceof AsrError) throw new HttpError(err.status, err.code, err.message);+ throw err;+ }+ });++ return app;+}++/**+ * The recording, decoded. It is forwarded to the provider and never written to disk, but its+ * size is capped first: an unbounded body would be a way to make this server hold as much+ * memory as the client cares to send.+ */+function parseAudio(value: unknown): Uint8Array {+ if (typeof value !== "string" || value === "") {+ throw new HttpError(400, "asr_empty_audio", "The recording is empty.");+ }+ const pcm = new Uint8Array(Buffer.from(value, "base64"));+ if (pcm.length === 0) {+ throw new HttpError(400, "asr_empty_audio", "The recording is empty.");+ }+ if (pcm.length > ASR_MAX_BYTES) {+ throw new HttpError(413, "asr_too_long", "The recording is too long to transcribe.");+ }+ if (pcm.length % 2 !== 0) {+ throw new HttpError(400, "asr_bad_audio", "The recording is not 16-bit PCM.");+ }+ return pcm;+}++/** The configured site: an absolute http(s) URL, or its origin is not something we can call. */+function parseBaseUrl(value: unknown): string {+ if (typeof value === "string") {+ try {+ const url = new URL(value.trim());+ if (url.protocol === "http:" || url.protocol === "https:") return value.trim();+ } catch {+ // falls through to the refusal below+ }+ }+ throw new HttpError(+ 400,+ "invalid_asr_base_url",+ "baseUrl must be an absolute http(s) URL, e.g. https://tokendance.space.",+ );+}++/** The model id: a non-empty string. What the provider accepts is the provider's business. */+function parseModel(value: unknown): string {+ if (typeof value === "string" && value.trim() !== "") return value.trim();+ throw new HttpError(400, "invalid_asr_model", "model must be a non-empty model id.");+}++/** The key: a non-empty string (an empty one was handled as "keep the stored key"). */+function parseApiKey(value: unknown): string {+ if (typeof value === "string" && value.trim() !== "") return value.trim();+ throw new HttpError(400, "invalid_asr_api_key", "apiKey must be a non-empty string.");+}++/**+ * The recording's sample rate. Refused rather than defaulted when it is not one the protocol+ * takes: a mismatch here is audio the provider would transcribe as noise, which reads to the+ * user as a broken microphone.+ */+function parseSampleRate(value: unknown): number {+ if (value === undefined || value === null) return ASR_SAMPLE_RATE;+ if (typeof value !== "number" || !ACCEPTED_SAMPLE_RATES.includes(value)) {+ throw new HttpError(+ 400,+ "asr_bad_sample_rate",+ `sampleRate must be one of ${ACCEPTED_SAMPLE_RATES.join(", ")}.`,+ );+ }+ return value;+}++@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "asr",+ prefix: "/api/asr",+ auth: "user",+ order: 55,+ },+ ],+ },+})+export class AsrRoutes {+ @Use() private readonly settings!: Settings;+ @Bind("asr") routes!: Hono<AppEnv>;+ setup() {+ this.routes = asrRoutes({ settings: this.settings });+ }+}diff --git a/packages/server/src/mechanisms/settings.ts b/packages/server/src/mechanisms/settings.tsindex b8a4de8c..95182b1f 100644--- a/packages/server/src/mechanisms/settings.ts+++ b/packages/server/src/mechanisms/settings.ts@@ -23,6 +23,26 @@ export abstract class Settings {abstract setCompanyMode(value: boolean): void;abstract getAgentApiEnabled(): boolean;abstract setAgentApiEnabled(value: boolean): void;+ abstract getAsrSettings(): AsrSettings;+ abstract setAsrSettings(value: AsrSettings): void;+}++/**+ * What the composer's microphone transcribes with: the speech provider's site, the model id+ * to ask for, and the key to ask with. Server-global, like the other settings here — the+ * recognition runs on the server, so the key belongs to the deployment rather than to each+ * browser that opens the page.+ *+ * `baseUrl` and `model` are never empty: an unset one reads as the built-in default (see+ * services/asr.ts), so the settings page always shows what a recording would actually use.+ */+export interface AsrSettings {+ /** The provider's site, e.g. `https://tokendance.space`. */+ baseUrl: string;+ /** The upstream model id. */+ model: string;+ /** The stored key, or "" when none has been saved yet. */+ apiKey: string;}/** UiPrefsStore: the mechanism UiPrefsRepo implements. */diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 8b40f0dc..c6942491 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -123,6 +123,7 @@ import { OrgRuns, OrgSessions } from "./runtime/organization/deps.js";import { TerminalRelay } from "./machines/terminal-relay.js";import { ProjectAdminRoutes } from "./http/routes/projects.js";import { AdminRoutes } from "./http/routes/admin.js";+import { AsrRoutes } from "./http/routes/asr.js";import { MeRoutes } from "./http/routes/me.js";import { UserVaultRoutes } from "./http/routes/user-vault.js";import { AuthRoutes } from "./http/routes/auth.js";@@ -471,6 +472,7 @@ export class CompanyModule {}InstallRoutes,VersionRoutes,FeedbackRoutes,+ AsrRoutes,HmrRoutes,DesktopRoutes,DesktopUpdateRoutes,diff --git a/packages/server/src/services/asr.ts b/packages/server/src/services/asr.tsnew file mode 100644index 00000000..0c12035e--- /dev/null+++ b/packages/server/src/services/asr.ts@@ -0,0 +1,338 @@+/**+ * Speech input: the server's own call to a streaming speech-to-text provider.+ *+ * The composer's microphone records in the browser, but the TRANSCRIPTION happens here, on+ * the server, for two reasons: the desktop shell has no Web Speech API to fall back on, so a+ * browser-side recognizer would make the two clients behave differently; and the API key then+ * lives in one place instead of being handed to every browser that opens the page.+ *+ * The protocol is the one Alibaba's DashScope documents for its ASR models and the TokenDance+ * gateway re-serves under `/gateway/alibaba/api-ws/v1/inference`: one WebSocket per utterance,+ * a `run-task` frame naming the model and the audio's format, then the audio in ~100 ms frames,+ * then `finish-task`; the transcript arrives as `result-generated` frames carrying one sentence+ * each, and `task-finished` ends it. Every frame is JSON except the audio itself.+ *+ * The transport's shape (undici's EventTarget WebSocket) never leaves this file: {@link+ * FrameStream} turns it into an ordered queue whose reader applies the deadline, so a stalled+ * upstream surfaces as `asr_timeout` instead of hanging the request.+ */+import { setTimeout as sleep } from "node:timers/promises";+import { WebSocket } from "undici";++/** Site the ASR endpoint hangs off when nothing is configured. */+export const DEFAULT_ASR_BASE_URL = "https://tokendance.space";++/** Model transcribed with when nothing is configured. */+export const DEFAULT_ASR_MODEL = "qwen-audio-3.1-asr-flash-streaming";++/**+ * Where the streaming protocol lives, appended to the configured site's ORIGIN. Only the+ * origin is taken from the setting, so an address that also carries a path (a gateway's+ * `/gateway/v1`, say) still resolves to the same endpoint.+ */+export const ASR_WS_PATH = "/gateway/alibaba/api-ws/v1/inference";++/** Sample rate the composer records at; the value travels with the audio and upstream. */+export const ASR_SAMPLE_RATE = 16_000;++/** Longest utterance accepted, in seconds — ~1.9 MB of 16 kHz mono PCM16. */+export const ASR_MAX_SECONDS = 60;++/** Sound-bytes cap for one utterance, derived from {@link ASR_MAX_SECONDS}. */+export const ASR_MAX_BYTES = ASR_SAMPLE_RATE * 2 * ASR_MAX_SECONDS;++/** One frame's worth of audio: ~100 ms at 16 kHz mono PCM16, the pace the protocol documents. */+const CHUNK_BYTES = ASR_SAMPLE_RATE * 0.2;++/**+ * Pause between audio frames. Sending a whole utterance back-to-back works, but this is the+ * pace the protocol asks for and it costs little on the utterance lengths accepted here.+ */+const CHUNK_PAUSE_MS = 10;++/** How long the socket itself may take to open. */+const HANDSHAKE_TIMEOUT_MS = 15_000;++/** How long the whole call may take, on top of the audio's own length. */+const OVERALL_SLACK_MS = 30_000;++/** A failure the route turns into an HTTP answer. `code` is what the Web App localizes. */+export type AsrErrorCode = "asr_unreachable" | "asr_upstream" | "asr_timeout";++export class AsrError extends Error {+ constructor(+ readonly code: AsrErrorCode,+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "AsrError";+ }+}++export interface AsrRequest {+ /** The configured site, e.g. `https://tokendance.space` (empty takes the default). */+ baseUrl: string;+ /** The configured model id (empty takes the default). */+ model: string;+ /** The configured key. An empty one is refused by the route, never sent. */+ apiKey: string;+ /** The utterance: raw little-endian PCM16, mono, at `sampleRate`. */+ pcm: Uint8Array;+ sampleRate: number;+}++/** One frame of the protocol, reduced to what this product reads out of it. */+type AsrEvent =+ | { kind: "started" }+ | { kind: "sentence"; text: string }+ | { kind: "finished" }+ | { kind: "failed"; code: string; message: string };++/**+ * The WebSocket endpoint a configured site resolves to. Throws on an address that is not a+ * URL — the settings route validates before storing, so reaching this with one is a bug, not+ * a user error.+ */+export function asrWebSocketUrl(baseUrl: string): string {+ const site = baseUrl.trim() === "" ? DEFAULT_ASR_BASE_URL : baseUrl.trim();+ let url: URL;+ try {+ url = new URL(site);+ } catch {+ throw new Error(`ASR base URL is not a URL: ${site}`);+ }+ const scheme = url.protocol === "http:" ? "ws:" : "wss:";+ return `${scheme}//${url.host}${ASR_WS_PATH}`;+}++/** The model id a configured value resolves to. */+export function asrModel(model: string): string {+ return model.trim() === "" ? DEFAULT_ASR_MODEL : model.trim();+}++/**+ * Read one inbound frame. Anything this product has no use for (a binary frame, a heartbeat+ * shape, malformed JSON, an event added later) reads as null and is ignored: the protocol is+ * the provider's to extend.+ */+export function parseAsrEvent(raw: string): AsrEvent | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }+ const header = (parsed as { header?: Record<string, unknown> }).header;+ if (header === undefined || header === null) return null;+ const event = header.event;+ if (event === "task-started") return { kind: "started" };+ if (event === "task-finished") return { kind: "finished" };+ if (event === "task-failed") {+ return {+ kind: "failed",+ code: typeof header.error_code === "string" ? header.error_code : "asr_failed",+ message: typeof header.error_message === "string" ? header.error_message : "",+ };+ }+ if (event === "result-generated") {+ const sentence = (parsed as { payload?: { output?: { sentence?: unknown } } }).payload?.output+ ?.sentence as { text?: unknown } | undefined;+ if (sentence === undefined || sentence === null) return null;+ return { kind: "sentence", text: typeof sentence.text === "string" ? sentence.text : "" };+ }+ return null;+}++/** The transcript a stream of events adds up to, in the order they arrived. */+export function transcriptOf(events: readonly AsrEvent[]): string {+ return events+ .filter((e): e is Extract<AsrEvent, { kind: "sentence" }> => e.kind === "sentence")+ .map((e) => e.text)+ .join("");+}++/**+ * Transcribe one utterance and return its transcript. An empty transcript is a legitimate+ * answer — silence is not a failure, and the composer must not report one.+ */+export async function transcribeStreaming(req: AsrRequest): Promise<string> {+ const socket = new WebSocket(asrWebSocketUrl(req.baseUrl), {+ headers: { Authorization: `Bearer ${req.apiKey}` },+ });+ const frames = new FrameStream(socket);+ const deadline = Date.now() + OVERALL_SLACK_MS + (req.pcm.length / (req.sampleRate * 2)) * 1000;++ try {+ await frames.opened(HANDSHAKE_TIMEOUT_MS);+ // One utterance is one task, and both frames have to name the same one: `finish-task`+ // closes the task `run-task` opened.+ const task = taskId();+ socket.send(+ JSON.stringify({+ header: { action: "run-task", task_id: task, streaming: "duplex" },+ payload: {+ task_group: "audio",+ task: "asr",+ function: "recognition",+ model: asrModel(req.model),+ parameters: { format: "pcm", sample_rate: req.sampleRate },+ input: {},+ },+ }),+ );+ await untilStarted(frames, deadline);++ for (let offset = 0; offset < req.pcm.length; offset += CHUNK_BYTES) {+ socket.send(req.pcm.subarray(offset, offset + CHUNK_BYTES));+ if (offset + CHUNK_BYTES < req.pcm.length) await sleep(CHUNK_PAUSE_MS);+ }+ socket.send(+ JSON.stringify({+ header: { action: "finish-task", task_id: task, streaming: "duplex" },+ payload: { input: {} },+ }),+ );++ const sentences: AsrEvent[] = [];+ for (;;) {+ const event = await frames.next(deadline);+ if (event.kind === "finished") return transcriptOf(sentences);+ if (event.kind === "failed") throw upstreamFailure(event.code, event.message);+ if (event.kind === "sentence") sentences.push(event);+ }+ } finally {+ frames.dispose();+ }+}++/**+ * Wait for `task-started`. A `task-failed` before it — the shape an auth refusal takes — is+ * reported as it came.+ */+async function untilStarted(frames: FrameStream, deadline: number): Promise<void> {+ for (;;) {+ const event = await frames.next(deadline);+ if (event.kind === "started") return;+ if (event.kind === "failed") throw upstreamFailure(event.code, event.message);+ }+}++/**+ * The provider refused the task. Its own words are the message: they name what is wrong (an+ * unknown key, a model the account cannot use) and the settings page is where that gets fixed,+ * so wrapping them in this product's English would only put a translation between the operator+ * and the answer.+ */+function upstreamFailure(code: string, message: string): AsrError {+ return new AsrError("asr_upstream", message.trim() === "" ? code : message.trim(), 502);+}++function taskId(): string {+ return `asr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+}++/**+ * A WebSocket as an ordered queue of {@link AsrEvent}. Frames that arrive before anyone is+ * reading are buffered, so nothing is lost between the handshake and the collect loop; the+ * socket's own failure is handed to the reader (and to every later one) as the rejection it+ * is, which is how an unreachable service keeps its own name instead of being read as a+ * refusal by the provider.+ */+class FrameStream {+ private readonly buffered: AsrEvent[] = [];+ private waiting: ((event: AsrEvent) => void) | null = null;+ private readonly openWaiters: {+ resolve: () => void;+ reject: (err: AsrError) => void;+ timer: NodeJS.Timeout;+ }[] = [];+ private isOpen = false;+ private failure: AsrError | null = null;++ constructor(private readonly socket: WebSocket) {+ socket.addEventListener("open", () => {+ this.isOpen = true;+ for (const waiter of this.openWaiters.splice(0)) {+ clearTimeout(waiter.timer);+ waiter.resolve();+ }+ });+ socket.addEventListener("message", (event) => {+ const data = event.data;+ if (typeof data !== "string") return;+ const parsed = parseAsrEvent(data);+ if (parsed !== null) this.push(parsed);+ });+ socket.addEventListener("error", () => {+ this.fail(new AsrError("asr_unreachable", "Could not reach the speech service.", 502));+ });+ socket.addEventListener("close", () => {+ this.fail(new AsrError("asr_unreachable", "The speech service closed the connection.", 502));+ });+ }++ /** Resolves once the socket is open; rejects with `asr_unreachable` if it never is. */+ opened(timeoutMs: number): Promise<void> {+ if (this.failure !== null) return Promise.reject(this.failure);+ if (this.isOpen) return Promise.resolve();+ return new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ const err = new AsrError(+ "asr_unreachable",+ "Could not reach the speech service in time.",+ 502,+ );+ this.fail(err);+ }, timeoutMs);+ timer.unref();+ this.openWaiters.push({ resolve, reject, timer });+ });+ }++ /** The next frame, or a rejection once the socket has failed or `deadline` has passed. */+ next(deadline: number): Promise<AsrEvent> {+ const buffered = this.buffered.shift();+ if (buffered !== undefined) return Promise.resolve(buffered);+ if (this.failure !== null) return Promise.reject(this.failure);+ return new Promise<AsrEvent>((resolve, reject) => {+ const timer = setTimeout(+ () => {+ if (this.waiting !== resolve) return;+ this.waiting = null;+ reject(new AsrError("asr_timeout", "The speech service did not answer in time.", 504));+ },+ Math.max(1, deadline - Date.now()),+ );+ timer.unref();+ this.waiting = (event) => {+ clearTimeout(timer);+ resolve(event);+ };+ });+ }++ dispose(): void {+ this.waiting = null;+ for (const waiter of this.openWaiters.splice(0)) clearTimeout(waiter.timer);+ if (this.socket.readyState < 2) this.socket.close();+ }++ private push(event: AsrEvent): void {+ const waiting = this.waiting;+ if (waiting === null) {+ this.buffered.push(event);+ return;+ }+ this.waiting = null;+ waiting(event);+ }++ private fail(err: AsrError): void {+ if (this.failure === null) this.failure = err;+ for (const waiter of this.openWaiters.splice(0)) {+ clearTimeout(waiter.timer);+ waiter.reject(this.failure);+ }+ }+}diff --git a/packages/server/test/asr.test.ts b/packages/server/test/asr.test.tsnew file mode 100644index 00000000..07013b1c--- /dev/null+++ b/packages/server/test/asr.test.ts@@ -0,0 +1,388 @@+/**+ * Speech input, end to end through the real HTTP app: the composer's recording goes up to+ * /api/asr/transcribe, the server makes ONE WebSocket call to the configured provider and+ * answers with the transcript.+ *+ * The upstream is a fake `ws` server on a loopback port, so the cases below drive the real+ * protocol rather than a stand-in for it: what the server sends (the Authorization header,+ * the `run-task` frame's model and audio parameters, the audio frames, `finish-task`) and+ * what it does with each frame that comes back are all observed on the wire.+ *+ * - The config route is an admin's; a non-admin gets 403 from both verbs and writes nothing.+ * - With no rows stored the read reports the built-in site and model, and no key.+ * - A PUT stores the site, the model and the key; the key never comes back, only `hasKey`.+ * - A PUT that omits the key (or sends an empty one) keeps the stored key.+ * - A PUT naming an unusable site is refused and writes none of its fields.+ * - Transcribing with no key configured is refused before any socket is opened.+ * - Transcribing with one reaches the configured site and returns the provider's sentence+ * frames joined in arrival order; an empty transcript is a 200, not an error.+ * - A `task-failed` frame is a 502 carrying the provider's own words; a site that refuses the+ * connection is a 502 named `asr_unreachable`, not a refusal by the provider.+ * - An empty, non-PCM or over-long body is refused with its own code.+ */+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import { WebSocketServer } from "ws";+import type { Server as HttpServer } from "node:http";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";+import type { AsrConfig, AsrConfigResponse, AsrTranscribeResponse } from "../src/api/types.js";+import {+ ASR_MAX_BYTES,+ DEFAULT_ASR_BASE_URL,+ DEFAULT_ASR_MODEL,+ asrWebSocketUrl,+ parseAsrEvent,+ transcriptOf,+} from "../src/services/asr.js";+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++/** One `run-task` frame as the fake upstream received it. */+interface ReceivedRunTask {+ header: { action: string };+ payload: {+ task_group: string;+ task: string;+ function: string;+ model: string;+ parameters: { format: string; sample_rate: number };+ };+}++interface FakeUpstream {+ /** The site the server should be pointed at, e.g. `http://127.0.0.1:41234`. */+ url: string;+ /** What the server sent, as the upstream saw it. */+ seen: {+ authorization: string | undefined;+ connections: number;+ runTask: ReceivedRunTask | null;+ audio: Buffer;+ finished: boolean;+ };+ close(): Promise<void>;+}++/**+ * A provider that follows the streaming protocol and nothing else: it answers `run-task`+ * with either `task-started` or the failure the case asked for, collects the audio frames,+ * and on `finish-task` emits the sentences and ends the task.+ */+async function startFakeUpstream(+ options: { sentences?: string[]; fail?: { code: string; message: string } } = {},+): Promise<FakeUpstream> {+ const seen: FakeUpstream["seen"] = {+ authorization: undefined,+ connections: 0,+ runTask: null,+ audio: Buffer.alloc(0),+ finished: false,+ };+ const http: HttpServer = createServer();+ const wss = new WebSocketServer({ server: http });+ wss.on("connection", (socket, req) => {+ seen.connections += 1;+ if (seen.authorization === undefined) seen.authorization = req.headers.authorization;+ socket.on("message", (data, isBinary) => {+ if (isBinary) {+ seen.audio = Buffer.concat([seen.audio, Buffer.from(data as Buffer)]);+ return;+ }+ const frame = JSON.parse(data.toString()) as { header?: { action?: string } };+ if (frame.header?.action === "run-task") {+ seen.runTask = frame as unknown as ReceivedRunTask;+ if (options.fail !== undefined) {+ socket.send(+ JSON.stringify({+ header: {+ event: "task-failed",+ error_code: options.fail.code,+ error_message: options.fail.message,+ },+ payload: {},+ }),+ );+ return;+ }+ socket.send(JSON.stringify({ header: { event: "task-started" }, payload: {} }));+ return;+ }+ if (frame.header?.action === "finish-task") {+ seen.finished = true;+ for (const text of options.sentences ?? ["你好"]) {+ socket.send(+ JSON.stringify({+ header: { event: "result-generated" },+ payload: { output: { sentence: { text, sentence_end: true } } },+ }),+ );+ }+ socket.send(JSON.stringify({ header: { event: "task-finished" }, payload: {} }));+ }+ });+ });+ await new Promise<void>((resolve) => http.listen(0, "127.0.0.1", resolve));+ const { port } = http.address() as AddressInfo;+ return {+ url: `http://127.0.0.1:${port}`,+ seen,+ close: () =>+ new Promise<void>((resolve) => {+ for (const client of wss.clients) client.terminate();+ wss.close(() => http.close(() => resolve()));+ }),+ };+}++/** 100 ms of silence at 16 kHz mono PCM16 — a body the route accepts. */+const ONE_FRAME = new Uint8Array(3200);++describe("speech input", () => {+ let t: TestApp;+ let admin: ReturnType<typeof apiClient>;+ let user: ReturnType<typeof apiClient>;+ let adminCookie = "";+ let userCookie = "";+ let upstream: FakeUpstream | null = null;++ beforeAll(async () => {+ t = await createTestApp();+ adminCookie = (await loginAdmin(t.app)).cookie;+ userCookie = (await provisionUser(t.app, "norm")).cookie;+ admin = apiClient(t.app, adminCookie);+ user = apiClient(t.app, userCookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });+ beforeEach(() => {+ t.deps.db.exec("DELETE FROM server_settings");+ });+ afterEach(async () => {+ await upstream?.close();+ upstream = null;+ });++ const getConfig = async (client = admin): Promise<AsrConfig> => {+ const res = await client.get("/api/asr/config");+ expect(res.status).toBe(200);+ return ((await res.json()) as AsrConfigResponse).config;+ };+ const putConfig = (body: unknown, client = admin) => client.put("/api/asr/config", body);+ const errorCode = async (res: Response) =>+ ((await res.json()) as { error: { code: string; message: string } }).error;++ /** Transcribe as one of the two accounts — the utterance rides base64 in the JSON body. */+ const transcribe = async (+ who: "admin" | "user",+ pcm: Uint8Array = ONE_FRAME,+ sampleRate?: number,+ ): Promise<Response> =>+ t.app.request("/api/asr/transcribe", {+ method: "POST",+ headers: {+ cookie: who === "admin" ? adminCookie : userCookie,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ dataBase64: Buffer.from(pcm).toString("base64"),+ ...(sampleRate !== undefined ? { sampleRate } : {}),+ }),+ });++ it("keeps the config route to admins, and writes nothing for anyone else", async () => {+ expect((await user.get("/api/asr/config")).status).toBe(403);+ expect((await putConfig({ model: "x" }, user)).status).toBe(403);+ expect(t.deps.db.prepare("SELECT count(*) AS n FROM server_settings").get()).toEqual({ n: 0 });+ });++ it("reads the built-in site and model, and no key, before anything is stored", async () => {+ expect(await getConfig()).toEqual({+ baseUrl: DEFAULT_ASR_BASE_URL,+ model: DEFAULT_ASR_MODEL,+ hasKey: false,+ });+ });++ it("stores the site, the model and the key, and never hands the key back", async () => {+ const res = await putConfig({+ baseUrl: "https://example.test",+ model: "qwen-audio-3.1-asr-flash-streaming",+ apiKey: "sk-test-key",+ });+ expect(res.status).toBe(200);+ expect(((await res.json()) as AsrConfigResponse).config).toEqual({+ baseUrl: "https://example.test",+ model: "qwen-audio-3.1-asr-flash-streaming",+ hasKey: true,+ });+ // The read is the same masked view, and the stored key is what the route would send.+ expect(await getConfig()).toEqual({+ baseUrl: "https://example.test",+ model: "qwen-audio-3.1-asr-flash-streaming",+ hasKey: true,+ });+ expect(JSON.stringify(await getConfig())).not.toContain("sk-test-key");+ });++ it("keeps the stored key when a PUT omits it or sends an empty one", async () => {+ await putConfig({ baseUrl: "https://example.test", model: "m", apiKey: "sk-keep-me" });+ expect((await putConfig({ model: "other" })).status).toBe(200);+ expect(await getConfig()).toMatchObject({ model: "other", hasKey: true });+ expect((await putConfig({ apiKey: "" })).status).toBe(200);+ expect(await getConfig()).toMatchObject({ hasKey: true });+ });++ it("refuses an unusable site and writes none of the PUT's fields", async () => {+ await putConfig({ baseUrl: "https://example.test", model: "keep", apiKey: "sk-keep-me" });+ const res = await putConfig({ baseUrl: "not a url", model: "changed" });+ expect(res.status).toBe(400);+ expect((await errorCode(res)).code).toBe("invalid_asr_base_url");+ expect(await getConfig()).toEqual({+ baseUrl: "https://example.test",+ model: "keep",+ hasKey: true,+ });+ });++ it("refuses to transcribe before any key is configured, without opening a socket", async () => {+ const res = await transcribe("admin");+ expect(res.status).toBe(400);+ expect((await errorCode(res)).code).toBe("asr_not_configured");+ });++ it("transcribes through the configured site and returns the provider's sentences", async () => {+ upstream = await startFakeUpstream({ sentences: ["你好,", "世界。"] });+ await putConfig({ baseUrl: upstream.url, model: "my-model", apiKey: "sk-test-key" });++ const res = await transcribe("admin");+ expect(res.status).toBe(200);+ expect(((await res.json()) as AsrTranscribeResponse).text).toBe("你好,世界。");++ // What the provider actually received, not what the route logged.+ expect(upstream.seen.authorization).toBe("Bearer sk-test-key");+ expect(upstream.seen.runTask?.header.action).toBe("run-task");+ expect(upstream.seen.runTask?.payload).toMatchObject({+ task_group: "audio",+ task: "asr",+ function: "recognition",+ model: "my-model",+ parameters: { format: "pcm", sample_rate: 16000 },+ });+ expect(upstream.seen.audio.length).toBe(ONE_FRAME.length);+ expect(upstream.seen.finished).toBe(true);+ });++ it("lets any signed-in user transpose the admin's key, and returns an empty transcript", async () => {+ upstream = await startFakeUpstream({ sentences: [] });+ await putConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-test-key" });+ const res = await transcribe("user");+ expect(res.status).toBe(200);+ expect(((await res.json()) as AsrTranscribeResponse).text).toBe("");+ });++ it("reports a provider refusal as a 502 carrying the provider's own words", async () => {+ upstream = await startFakeUpstream({+ fail: { code: "unauthorized", message: "API 密钥不存在" },+ });+ await putConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-nope" });+ const res = await transcribe("admin");+ expect(res.status).toBe(502);+ const err = await errorCode(res);+ expect(err.code).toBe("asr_upstream");+ expect(err.message).toContain("API 密钥不存在");+ });++ it("names a site that refuses the connection as unreachable, not as a refusal", async () => {+ // Port 1 on loopback: nothing listens, so the handshake never completes.+ await putConfig({ baseUrl: "http://127.0.0.1:1", model: "m", apiKey: "sk-test-key" });+ const res = await transcribe("admin");+ expect(res.status).toBe(502);+ expect((await errorCode(res)).code).toBe("asr_unreachable");+ });++ it("refuses an empty, odd-length or over-long recording with its own code", async () => {+ upstream = await startFakeUpstream({ sentences: [] });+ await putConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-test-key" });++ const empty = await transcribe("admin", new Uint8Array(0));+ expect(empty.status).toBe(400);+ expect((await errorCode(empty)).code).toBe("asr_empty_audio");++ const odd = await transcribe("admin", new Uint8Array(3));+ expect(odd.status).toBe(400);+ expect((await errorCode(odd)).code).toBe("asr_bad_audio");++ const long = await transcribe("admin", new Uint8Array(ASR_MAX_BYTES + 2));+ expect(long.status).toBe(413);+ expect((await errorCode(long)).code).toBe("asr_too_long");+ // Nothing was sent upstream for any of them.+ expect(upstream.seen.connections).toBe(0);+ });++ it("refuses a sample rate the protocol does not take", async () => {+ upstream = await startFakeUpstream({ sentences: [] });+ await putConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-test-key" });+ const res = await transcribe("admin", ONE_FRAME, 44100);+ expect(res.status).toBe(400);+ expect((await errorCode(res)).code).toBe("asr_bad_sample_rate");+ });++ it("accepts the documented sample rate explicitly", async () => {+ upstream = await startFakeUpstream({ sentences: ["好"] });+ await putConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-test-key" });+ const res = await transcribe("admin", ONE_FRAME, 16000);+ expect(res.status).toBe(200);+ expect(upstream.seen.runTask?.payload.parameters.sample_rate).toBe(16000);+ });++ // The two pure helpers the route and the flow above rest on.+ it("derives the endpoint from the site's origin, however the site was spelled", () => {+ expect(asrWebSocketUrl("")).toBe(`wss://tokendance.space/gateway/alibaba/api-ws/v1/inference`);+ expect(asrWebSocketUrl("https://tokendance.space")).toBe(+ "wss://tokendance.space/gateway/alibaba/api-ws/v1/inference",+ );+ // A gateway's own `/v1` path must not end up in front of the protocol's path.+ expect(asrWebSocketUrl("https://tokendance.space/gateway/v1")).toBe(+ "wss://tokendance.space/gateway/alibaba/api-ws/v1/inference",+ );+ expect(asrWebSocketUrl("http://127.0.0.1:9000")).toBe(+ "ws://127.0.0.1:9000/gateway/alibaba/api-ws/v1/inference",+ );+ });++ it("reads the protocol's frames and ignores anything else", () => {+ expect(parseAsrEvent(JSON.stringify({ header: { event: "task-started" } }))).toEqual({+ kind: "started",+ });+ expect(parseAsrEvent(JSON.stringify({ header: { event: "task-finished" } }))).toEqual({+ kind: "finished",+ });+ expect(+ parseAsrEvent(+ JSON.stringify({+ header: { event: "result-generated" },+ payload: { output: { sentence: { text: "句一", sentence_end: true } } },+ }),+ ),+ ).toEqual({ kind: "sentence", text: "句一" });+ expect(+ parseAsrEvent(+ JSON.stringify({+ header: { event: "task-failed", error_code: "unauthorized", error_message: "no" },+ }),+ ),+ ).toEqual({ kind: "failed", code: "unauthorized", message: "no" });+ expect(parseAsrEvent("not json")).toBeNull();+ expect(parseAsrEvent(JSON.stringify({ header: { event: "something-new" } }))).toBeNull();+ expect(parseAsrEvent(JSON.stringify({ payload: {} }))).toBeNull();+ expect(+ transcriptOf([+ { kind: "started" },+ { kind: "sentence", text: "甲" },+ { kind: "sentence", text: "乙" },+ { kind: "finished" },+ ]),+ ).toBe("甲乙");+ });+});diff --git a/packages/server/test/hot-replace.test.ts b/packages/server/test/hot-replace.test.tsindex 07ea13a6..602e9a62 100644--- a/packages/server/test/hot-replace.test.ts+++ b/packages/server/test/hot-replace.test.ts@@ -58,6 +58,9 @@ function memorySettings(maxMb = 7): Settings {getAttachmentTotalMb: () => maxMb * 10,setAttachmentTotalMb: () => {},getAttachmentLimitsMb: () => ({ attachmentMaxMb: maxMb, attachmentTotalMb: maxMb * 10 }),+ // Speech input is not what this file is about; the stub reads as "nothing configured".+ getAsrSettings: () => ({ baseUrl: "", model: "", apiKey: "" }),+ setAsrSettings: () => {},};}diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.tsindex 594269d6..088981cc 100644--- a/packages/ui/src/components/icons/icons.ts+++ b/packages/ui/src/components/icons/icons.ts@@ -281,6 +281,12 @@ export const ICONS = {/** A picture: the rounded frame, and a mountain line across its lower half. */image:"M6 5h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3zM3 15l5-5 4 4 3-3 6 6",+ /**+ * A microphone: the capsule, its yoke and the stand. Speech input — the composer's record+ * button, and the settings page that holds the model it transcribes with.+ */+ microphone:+ "M12 14a3 3 0 0 0 3-3V6a3 3 0 1 0-6 0v5a3 3 0 0 0 3 3zM19 11a7 7 0 0 1-14 0M12 18v3M9 21h6",/** Three sliders set at different heights (feather sliders): how something behaves, adjustable. */sliders: "M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6",/** A four-pointed spark: effort and thought, the dial a model thinks harder on. */diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 6eab8ae9..47a5567d 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -31,6 +31,10 @@ import type {AgentVaultConfigDto,AllProjectSchedulesResponse,ApprovalDecisionRequest,+ AsrConfigResponse,+ AsrConfigUpdateRequest,+ AsrTranscribeRequest,+ AsrTranscribeResponse,AuthLoginRequest,AuthResponse,BenchmarkCasesResponse,@@ -335,6 +339,23 @@ export const adminDeleteUser = (userId: string) =>/** Server-global settings (admin only): currently the "use system HTTP proxy" switch. */export const adminGetSettings = () => apiFetch<ServerSettingsResponse>("/api/admin/settings");+/**+ * Speech input (admin only): the provider site, model and key the server transcribes the+ * composer's recording with. The read is masked — it carries `hasKey`, never the key.+ */+export const getAsrConfig = () => apiFetch<AsrConfigResponse>("/api/asr/config");++/** Stores the speech-model settings; an omitted or empty `apiKey` keeps the stored one. */+export const putAsrConfig = (body: AsrConfigUpdateRequest) =>+ apiFetch<AsrConfigResponse>("/api/asr/config", { method: "PUT", body });++/**+ * Transcribes one recording (any signed-in user — the admin configured the key). The audio+ * rides base64 because it is binary, as every other binary body in this API does.+ */+export const asrTranscribe = (body: AsrTranscribeRequest) =>+ apiFetch<AsrTranscribeResponse>("/api/asr/transcribe", { method: "POST", body });+/** Plugin configuration is kept by each server in its own database, so `server` names the* machine whose settings are read or written — through this server's tunnel to it — and nulldiff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 18cfda75..b710dcb6 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -118,6 +118,7 @@ import {SlashMenu,SlashPicker,TagInput,+ ToolbarTrigger,ZoomableImage,noAutofill,toastError,@@ -125,6 +126,7 @@ import {} from "@adelie/ui";import type { MenuSelectOption, TagInputChip } from "@adelie/ui";import { S } from "../../lib/strings";+import { toneInk } from "../../lib/tone";import { formatBytes, humanizeTokens } from "../../lib/format";import { fitTextarea } from "../../lib/textarea-fit";import { useLocale } from "../../state/locale";@@ -156,6 +158,7 @@ import type { HistoryStep } from "./input-history";import { isStopAction, midRunAction } from "./composer-send";import { steeringSummary } from "./queued-summary";import { PAPERCLIP_ICON } from "./attached-files-banner";+import { useDictation } from "./use-asr-recorder";import { FileDropZone } from "./drop-zone";import { ContextGauge } from "./context-gauge";import { modelWindowBelowCompactionLimit } from "../../lib/context";@@ -881,6 +884,28 @@ export function ChatInput({/** Live text mirror for slash-command run() closures (the commands memo deliberately doesn't depend on text). */const textRef = useRef(text);textRef.current = text;+ /**+ * The microphone. A transcript is appended to whatever is already typed rather than replacing+ * it: dictation is a way to write into this draft, not a way to write a new one, and someone+ * who has typed half a sentence should not lose it by speaking the rest.+ */+ const dictation = useDictation(+ useCallback(+ (transcript: string) => {+ const spoken = transcript.trim();+ if (spoken === "") return;+ // Read the draft from the mirror rather than from a state updater: the append has a+ // second effect (telling the host), and an updater may run twice.+ const previous = textRef.current;+ const joined =+ previous.trim() === "" ? spoken : `${previous.replace(/\s+$/, "")} ${spoken}`;+ setText(joined);+ onTextChange?.(joined);+ textareaRef.current?.focus();+ },+ [onTextChange],+ ),+ );const [images, setImages] = useState<string[]>([]);/*** The staged images as one batch for the lightbox: opening any of them lets the reader step@@ -2460,6 +2485,23 @@ export function ChatInput({onChange={onPickAttachments}/>+ {/* What the microphone has to say: a refused transcription, or a recording that came back+ empty. Drawn here, above the card, for the same reason the queued-follow-up hint is —+ it belongs to the input, and a toast would be gone while the empty box it explains+ stays. Cleared by the next keystroke or the next recording. */}+ {dictation.notice !== null && (+ <p+ role="alert"+ data-tooltip={dictation.notice.text}+ data-tooltip-content="text"+ className={`anim-fade mb-1 line-clamp-2 break-words text-xs ${+ dictation.notice.failed ? toneInk.danger : "text-gray-400 dark:text-gray-500"+ }`}+ >+ {dictation.notice.text}+ </p>+ )}+{/* Unified input card: the multi-line text body occupies the top area, with all controlscollected onto a single bottom row that never shares a line with the text. The cardcollapses its toolbar by its own width (help text and button text hide under its@@ -2520,6 +2562,8 @@ export function ChatInput({const caretNow = e.target.selectionStart ?? value.length;setText(value);onTextChange?.(value);+ // Typing answers whatever the last recording said, so the line stops claiming it.+ dictation.clearNotice();setCaret(caretNow);setSlashIndex(0);// Closing via Escape only persists for "the same token": continuing to type within@@ -2549,8 +2593,8 @@ export function ChatInput({: S.chat.inputPlaceholder,}}tools={- // The three icon buttons — +, permission, skills — sit as one tight cluster: the row's- // wider gap would read them as unrelated controls.+ // The four icon buttons — +, microphone, permission, skills — sit as one tight cluster:+ // the row's wider gap would read them as unrelated controls.<>{/* "+" extension menu, leading the row: input add-ons (image upload, video upload,file attachment, goal mode) plus the input settings footer (mid-run send mode —@@ -2613,6 +2657,36 @@ export function ChatInput({direction={models && onChangeModel ? "down" : "up"}/>)}+ {/* The microphone, right beside the "+": the other way to put words in the box.+ One click starts recording, the next ends it and transcribes; the server does+ the recognizing (Settings > Server > Speech input holds the model and key), so+ this button needs nothing from the model picked for the conversation. Disabled+ only while a recording is being transcribed — speaking is orthogonal to a run,+ and the draft stays writable throughout one. */}+ {variant === "session" && (+ <ToolbarTrigger+ glyph={+ <GlyphIcon+ d={ICONS.microphone}+ size={ICON_SIZE.iconButton}+ className={+ dictation.state === "recording" ? toneInk.danger : "shrink-0 text-fg-muted"+ }+ />+ }+ ariaLabel={dictation.state === "recording" ? S.chat.dictateStop : S.chat.dictate}+ tooltip={+ dictation.state === "recording"+ ? S.chat.dictateStop+ : dictation.state === "transcribing"+ ? S.chat.transcribing+ : S.chat.dictate+ }+ disabled={dictation.state === "transcribing"}+ {...(dictation.state === "idle" ? {} : { "data-state": dictation.state })}+ onClick={dictation.toggle}+ />+ )}<PermissionSelectapprovalMode={approvalMode}approvalModes={approvalModes}diff --git a/packages/web/src/features/chat/use-asr-recorder.ts b/packages/web/src/features/chat/use-asr-recorder.tsnew file mode 100644index 00000000..5baeee17--- /dev/null+++ b/packages/web/src/features/chat/use-asr-recorder.ts@@ -0,0 +1,135 @@+/**+ * The composer's microphone: record, hand the utterance to the server, get a transcript back.+ *+ * MediaRecorder does the recording (it needs no worklet and no deprecated node), and the page+ * decodes what it produced with `decodeAudioData` and converts it to the PCM the server takes+ * (lib/asr-audio.ts, which is where the conversion and its tests live). The server does the+ * recognizing, so nothing here talks to a provider and no key ever reaches the page.+ *+ * Two things the browser will not do for us:+ *+ * - `getUserMedia` is refused outright on an insecure origin, and a refused one is+ * indistinguishable from a permission the user denied. Both read as "no microphone", which+ * is what the notice says.+ * - A recording of silence transcribes to the empty string. That is a legitimate answer from+ * the provider, not a failure, so it is reported as "nothing was heard" rather than as an+ * error — and the draft is left exactly as it was.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import * as api from "../../api/endpoints";+import { ASR_SAMPLE_RATE, encodeBase64, toAsrPcm } from "../../lib/asr-audio";+import { refusalText } from "../../lib/api-error";+import { S } from "../../lib/strings";++/** Which half of the round trip is running, if either. */+export type DictationState = "idle" | "recording" | "transcribing";++/**+ * What the composer has to say about the last attempt. `failed` is the difference between a+ * refusal (something went wrong) and a recording that simply came back empty — both need saying,+ * and only the first is a failure.+ */+export interface DictationNotice {+ text: string;+ failed: boolean;+}++export interface Dictation {+ state: DictationState;+ /** The last outcome worth saying (a refusal, or a recording that came back empty); null otherwise. */+ notice: DictationNotice | null;+ /** Drops `notice` — the composer calls this when the draft changes under it. */+ clearNotice(): void;+ /** Starts a recording, or ends the running one and transcribes it. Never rejects. */+ toggle(): void;+}++/**+ * `onTranscript` receives a non-empty transcript to put in the draft. It is held in a ref so+ * that a re-render mid-recording cannot detach the recording from the draft it belongs to.+ */+export function useDictation(onTranscript: (text: string) => void): Dictation {+ const [state, setState] = useState<DictationState>("idle");+ const [notice, setNotice] = useState<DictationNotice | null>(null);+ const recorderRef = useRef<MediaRecorder | null>(null);+ const chunksRef = useRef<Blob[]>([]);+ const transcriptRef = useRef(onTranscript);+ useEffect(() => {+ transcriptRef.current = onTranscript;+ }, [onTranscript]);++ const finish = useCallback(async (blob: Blob) => {+ setState("transcribing");+ try {+ const decoded = await decode(blob);+ const pcm = toAsrPcm(decoded.channels, decoded.sampleRate, ASR_SAMPLE_RATE);+ const res = await api.asrTranscribe({+ dataBase64: encodeBase64(pcm),+ sampleRate: ASR_SAMPLE_RATE,+ });+ if (res.text.trim() === "") setNotice({ text: S.chat.dictateHeardNothing, failed: false });+ else transcriptRef.current(res.text);+ } catch (e) {+ setNotice({ text: refusalText(e), failed: true });+ } finally {+ setState("idle");+ }+ }, []);++ const start = useCallback(() => {+ void (async () => {+ let stream: MediaStream;+ try {+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ } catch {+ setNotice({ text: S.chat.dictateUnavailable, failed: true });+ return;+ }+ const recorder = new MediaRecorder(stream);+ chunksRef.current = [];+ recorder.ondataavailable = (event) => {+ if (event.data.size > 0) chunksRef.current.push(event.data);+ };+ recorder.onstop = () => {+ // The device stays open until every track is stopped; a mic left live shows as a+ // recording indicator the user cannot get rid of.+ for (const track of stream.getTracks()) track.stop();+ recorderRef.current = null;+ void finish(new Blob(chunksRef.current, { type: recorder.mimeType }));+ chunksRef.current = [];+ };+ recorderRef.current = recorder;+ setNotice(null);+ recorder.start();+ setState("recording");+ })();+ }, [finish]);++ const toggle = useCallback(() => {+ const recorder = recorderRef.current;+ // A second click ends the recording; `onstop` is what starts the transcription, so the+ // state only reaches "transcribing" once the device has actually let go.+ if (recorder !== null && recorder.state === "recording") recorder.stop();+ else start();+ }, [start]);++ const clearNotice = useCallback(() => setNotice(null), []);++ return { state, notice, clearNotice, toggle };+}++/** The decoded recording, as the channels themselves — what the PCM conversion consumes. */+async function decode(blob: Blob): Promise<{ channels: Float32Array[]; sampleRate: number }> {+ const bytes = await blob.arrayBuffer();+ const context = new AudioContext();+ try {+ const buffer = await context.decodeAudioData(bytes);+ const channels: Float32Array[] = [];+ for (let channel = 0; channel < buffer.numberOfChannels; channel++) {+ channels.push(buffer.getChannelData(channel));+ }+ return { channels, sampleRate: buffer.sampleRate };+ } finally {+ void context.close();+ }+}diff --git a/packages/web/src/features/settings/asr-section.tsx b/packages/web/src/features/settings/asr-section.tsxnew file mode 100644index 00000000..348a4f4f--- /dev/null+++ b/packages/web/src/features/settings/asr-section.tsx@@ -0,0 +1,202 @@+/**+ * Speech input (admin only, server-global). Three fields — the provider's site, the model id+ * and the key — written together by one PUT, so a rejected field writes nothing.+ *+ * The key is write-only: the read carries `hasKey`, never the key, so the field starts empty on+ * every visit and an empty one means "keep what is stored". That is why the field's hint says so+ * and why the stored key's state is drawn under it: without both, a page that shows an empty key+ * box over a configured server looks like the key was lost.+ *+ * The read hydrates on mount, and the controls and Save stay disabled until it lands — a failed+ * read leaves the fields showing nothing, so the reason is drawn above them rather than in a+ * toast that dismisses itself, and leaving the section and coming back is the retry (7.19's rule,+ * the one every settings page here follows).+ *+ * Saving takes effect on the next recording; there is nothing to restart and nothing to warm up,+ * so there is no warning to carry.+ */+import { useCallback, useEffect, useState } from "react";+import type { AsrConfig } from "@adelie/server/api";+import {+ Button,+ Input,+ PasswordInput,+ SettingsSection,+ toastError,+ toastInfo,+ toastSuccess,+} from "@adelie/ui";+import * as api from "../../api/endpoints";+import { ApiError } from "../../api/client";+import { apiErrorText } from "../../lib/api-error";+import { S } from "../../lib/strings";+import { toneInk } from "../../lib/tone";++export function AsrSection() {+ /** The stored config as hydrated on mount (null until then) — the no-change baseline. */+ const [stored, setStored] = useState<AsrConfig | null>(null);+ const [baseUrl, setBaseUrl] = useState("");+ const [model, setModel] = useState("");+ const [apiKey, setApiKey] = useState("");+ /** The field a refusal is about, drawn under it. */+ const [fieldError, setFieldError] = useState<{+ field: "baseUrl" | "model" | "apiKey";+ text: string;+ } | null>(null);+ /** Why the last save was refused for another reason, drawn above the Save row. */+ const [saveRefusal, setSaveRefusal] = useState<string | null>(null);+ /** Why the config could not be read, drawn above the controls it left dead. */+ const [loadRefusal, setLoadRefusal] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ /** Adopt server-side truth: the baseline and the drafts move together. */+ const adopt = useCallback((next: AsrConfig) => {+ setStored(next);+ setBaseUrl(next.baseUrl);+ setModel(next.model);+ // Never populated: the value is write-only, so the field is for a new key alone.+ setApiKey("");+ setFieldError(null);+ setSaveRefusal(null);+ setLoadRefusal(null);+ }, []);++ useEffect(() => {+ let cancelled = false;+ void (async () => {+ try {+ const res = await api.getAsrConfig();+ if (!cancelled) adopt(res.config);+ } catch (e: unknown) {+ if (!cancelled) setLoadRefusal(apiErrorText(e));+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [adopt]);++ const save = async () => {+ if (stored === null) return;+ const nextBaseUrl = baseUrl.trim();+ const nextModel = model.trim();+ const nextApiKey = apiKey.trim();+ if (nextBaseUrl === stored.baseUrl && nextModel === stored.model && nextApiKey === "") {+ toastInfo(S.common.noChangesToSave);+ return;+ }+ setBusy(true);+ setFieldError(null);+ setSaveRefusal(null);+ try {+ const res = await api.putAsrConfig({+ baseUrl: nextBaseUrl,+ model: nextModel,+ // Omitted rather than sent empty: the server keeps what is stored for both spellings,+ // but omitting says the intent instead of relying on it.+ ...(nextApiKey !== "" ? { apiKey: nextApiKey } : {}),+ });+ adopt(res.config);+ toastSuccess(S.common.saved);+ } catch (e: unknown) {+ const code = e instanceof ApiError ? e.code : "";+ const text = apiErrorText(e);+ if (code === "invalid_asr_base_url") setFieldError({ field: "baseUrl", text });+ else if (code === "invalid_asr_model") setFieldError({ field: "model", text });+ else if (code === "invalid_asr_api_key") setFieldError({ field: "apiKey", text });+ // Anything else (a lost session, a dead server) wrote nothing, so the form and the+ // sentence agree and Save is the retry.+ else setSaveRefusal(text);+ if (code === "") toastError(text);+ } finally {+ setBusy(false);+ }+ };++ const hydrated = stored !== null;+ return (+ <SettingsSection+ actions={+ <Button+ size="sm"+ variant="primary"+ disabled={!hydrated || busy}+ onClick={() => void save()}+ >+ {S.common.save}+ </Button>+ }+ >+ {loadRefusal !== null && (+ <p+ role="alert"+ data-tooltip={loadRefusal}+ data-tooltip-content="text"+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {loadRefusal}+ </p>+ )}+ <Input+ label={S.settings.speechBaseUrl}+ required+ size="sm"+ type="url"+ inputMode="url"+ placeholder="https://tokendance.space"+ hint={S.settings.speechBaseUrlHint}+ value={baseUrl}+ disabled={!hydrated}+ {...(fieldError?.field === "baseUrl" ? { error: fieldError.text } : {})}+ onChange={(e) => {+ setBaseUrl(e.target.value);+ if (fieldError !== null) setFieldError(null);+ }}+ />+ <Input+ label={S.settings.speechModel}+ required+ size="sm"+ placeholder="qwen-audio-3.1-asr-flash-streaming"+ hint={S.settings.speechModelHint}+ value={model}+ disabled={!hydrated}+ {...(fieldError?.field === "model" ? { error: fieldError.text } : {})}+ onChange={(e) => {+ setModel(e.target.value);+ if (fieldError !== null) setFieldError(null);+ }}+ />+ <PasswordInput+ label={S.settings.speechApiKey}+ size="sm"+ autoComplete="off"+ hint={S.settings.speechApiKeyHint}+ value={apiKey}+ disabled={!hydrated}+ {...(fieldError?.field === "apiKey" ? { error: fieldError.text } : {})}+ onChange={(e) => {+ setApiKey(e.target.value);+ if (fieldError !== null) setFieldError(null);+ }}+ />+ {/* Whether a key is stored is the one thing this field cannot show: it is always empty+ above, by design. Without this line a configured server looks unconfigured. */}+ {hydrated && (+ <p className={`text-xs ${stored.hasKey ? "text-fg-muted" : toneInk.danger}`}>+ {stored.hasKey ? S.settings.speechKeyStored : S.settings.speechKeyMissing}+ </p>+ )}+ {saveRefusal !== null && (+ <p+ role="alert"+ data-tooltip={saveRefusal}+ data-tooltip-content="text"+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {saveRefusal}+ </p>+ )}+ </SettingsSection>+ );+}diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsxindex a5d57258..cdeff8da 100644--- a/packages/web/src/features/settings/settings-dialog.tsx+++ b/packages/web/src/features/settings/settings-dialog.tsx@@ -26,6 +26,7 @@ import { ShortcutsSection } from "./shortcuts-section";import { AccountSection } from "./account-section";import { ProxySection } from "./proxy-section";import { UploadsSection } from "./uploads-section";+import { AsrSection } from "./asr-section";import { CompanySection } from "./company-section";import { AgentApiSection } from "./agent-api-section";import { PluginsSection } from "./plugins-section";@@ -54,6 +55,8 @@ const SECTION_ICONS: Record<SettingsSectionKey, string> = {"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 0 0 0 18M12 3a15 15 0 0 1 0 18",/** Up arrow over a base: uploads. */uploads: "M12 15V4m0 0L7 9m5-5l5 5M4 20h16",+ /** Microphone: speech input. */+ speech: ICONS.microphone,/** The building the mode switch wears: company mode. */company: ICONS.building,/** Angle brackets: programs calling the Agents. */@@ -111,6 +114,7 @@ export function SettingsDialog({credits: S.settings.creditsTitle,proxy: S.settings.proxyTitle,uploads: S.settings.uploadLimitsTitle,+ speech: S.settings.speechTitle,company: S.settings.companyModeTitle,agentApi: S.settings.agentApiTitle,plugins: S.settings.pluginsTitle,@@ -127,6 +131,7 @@ export function SettingsDialog({shortcuts: S.settings.shortcutsInfo,proxy: S.settings.proxyInfo,uploads: S.settings.uploadLimitsInfo(uploadLimits.attachmentMaxCount, uploadLimits.imageMaxMb),+ speech: S.settings.speechInfo,company: S.settings.companyModeServerInfo,agentApi: S.settings.agentApiHint,plugins: S.settings.pluginsInfo,@@ -174,6 +179,7 @@ export function SettingsDialog({{current === "credits" && <CreditsSection />}{current === "proxy" && <ProxySection />}{current === "uploads" && <UploadsSection />}+ {current === "speech" && <AsrSection />}{current === "company" && <CompanySection />}{current === "agentApi" && <AgentApiSection />}{current === "plugins" && (diff --git a/packages/web/src/lib/asr-audio.ts b/packages/web/src/lib/asr-audio.tsnew file mode 100644index 00000000..0bc31785--- /dev/null+++ b/packages/web/src/lib/asr-audio.ts@@ -0,0 +1,95 @@+/**+ * The composer's microphone, reduced to the one thing the server can send upstream: raw+ * little-endian PCM16, mono, 16 kHz.+ *+ * The browser records whatever the platform gives it — usually Opus in a WebM container at the+ * audio device's own rate — so the recording is decoded and converted here, in the page, rather+ * than on the server: the server then needs no audio decoder, and the conversion is testable+ * without a microphone or a browser.+ *+ * Everything below is pure. `use-asr-recorder.ts` is the part that touches MediaRecorder.+ */++/** The rate the server sends upstream and tells the provider to expect. */+export const ASR_SAMPLE_RATE = 16_000;++/** How long one recording may run, matching the server's own cap (60 s of 16 kHz PCM16). */+export const ASR_MAX_SECONDS = 60;++/**+ * Average every channel into one. A microphone's channels are near-identical, so this is a+ * formality — but a decoder may hand back stereo, and the provider is told "mono", so the+ * samples have to actually be one channel rather than a second one ignored.+ */+export function mixToMono(channels: readonly Float32Array[]): Float32Array {+ const first = channels[0];+ if (first === undefined) return new Float32Array(0);+ if (channels.length === 1) return first;+ const mono = new Float32Array(first.length);+ for (let i = 0; i < mono.length; i++) {+ let sum = 0;+ for (const channel of channels) sum += channel[i] ?? 0;+ mono[i] = sum / channels.length;+ }+ return mono;+}++/**+ * Resample by linear interpolation. Not the highest-quality resampler there is, but a speech+ * recognizer is insensitive to the difference and this one is a handful of lines: each output+ * sample is read at its exact position in the input and blended from the two neighbours.+ */+export function resampleMono(input: Float32Array, fromRate: number, toRate: number): Float32Array {+ if (fromRate === toRate || input.length === 0) return input;+ const ratio = fromRate / toRate;+ const length = Math.floor(input.length / ratio);+ const output = new Float32Array(length);+ for (let i = 0; i < length; i++) {+ const position = i * ratio;+ const left = Math.floor(position);+ const right = Math.min(left + 1, input.length - 1);+ const weight = position - left;+ output[i] = (input[left] ?? 0) * (1 - weight) + (input[right] ?? 0) * weight;+ }+ return output;+}++/**+ * Float samples to PCM16. Clamped before scaling: a decoder may hand back values outside+ * [-1, 1], and Int16Array truncation would wrap those around into a loud click.+ */+export function toPcm16Le(samples: Float32Array): Uint8Array {+ const bytes = new Uint8Array(samples.length * 2);+ const view = new DataView(bytes.buffer);+ for (let i = 0; i < samples.length; i++) {+ const sample = Math.max(-1, Math.min(1, samples[i] ?? 0));+ view.setInt16(i * 2, Math.round(sample * 32767), true);+ }+ return bytes;+}++/**+ * The whole conversion: decoded channels at `fromRate` and `toRate` (the device's rate) become+ * the bytes the transcribe route takes.+ */+export function toAsrPcm(+ channels: readonly Float32Array[],+ fromRate: number,+ toRate: number = ASR_SAMPLE_RATE,+): Uint8Array {+ return toPcm16Le(resampleMono(mixToMono(channels), fromRate, toRate));+}++/**+ * base64, in chunks. `String.fromCharCode(...bytes)` on a whole recording would blow the+ * argument limit, so the bytes go through in 32k slices — which is also why this does not use+ * a one-line `btoa(String.fromCharCode(...))`.+ */+export function encodeBase64(bytes: Uint8Array): string {+ const CHUNK = 0x8000;+ let binary = "";+ for (let offset = 0; offset < bytes.length; offset += CHUNK) {+ binary += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK));+ }+ return btoa(binary);+}diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.tsindex 1dd04030..0e5a2ba0 100644--- a/packages/web/src/lib/settings-sections.ts+++ b/packages/web/src/lib/settings-sections.ts@@ -34,6 +34,7 @@ export type SettingsSectionKey =| "credits"| "proxy"| "uploads"+ | "speech"| "company"| "agentApi"| "plugins"@@ -75,6 +76,9 @@ const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsV{ key: "credits", group: "personal", visible: () => true },{ key: "proxy", group: "server", visible: (v) => v.isAdmin },{ key: "uploads", group: "server", visible: (v) => v.isAdmin },+ // Speech input: the key the server transcribes with is one per deployment, so this is the+ // admin's page too — the microphone in every composer then works for every member.+ { key: "speech", group: "server", visible: (v) => v.isAdmin },// The company-mode master switch: server-global like the proxy and upload limits.{ key: "company", group: "server", visible: (v) => v.isAdmin },// Whether any Agent's public API answers at all: server-global, like company mode.diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 45cc51bd..cf18af5b 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -770,6 +770,21 @@ export const en: Strings = {`conversation keep a separate ${imageMb}MB limit that this setting does not raise — an ` +`inline image enters the conversation and the Trace, where its size is paid again on ` +`every history page and resume.`,+ speechTitle: "Speech input",+ /** Disclosed at the pane heading: where the audio goes, and where the key lives. */+ speechInfo:+ "The browser records; the server transcribes. The recording goes to the provider below, " ++ "and the provider key stays on this server rather than being handed to every page. Once " ++ "it is set, the microphone button in the composer works.",+ speechBaseUrl: "Service address",+ speechBaseUrlHint: "The provider's site, e.g. https://tokendance.space",+ speechModel: "Model",+ speechModelHint: "The provider's model id, e.g. qwen-audio-3.1-asr-flash-streaming",+ speechApiKey: "API key",+ speechApiKeyHint: "Leave empty to keep the stored key",+ /** The two states of the stored key, shown beside the key field. */+ speechKeyStored: "A key is stored",+ speechKeyMissing: "No key yet — speech input is unavailable",/** The fold holding the fields a settings group marks advanced. */pluginAdvanced: "Advanced",/** A table cell its row does not let change, beside the lock mark. */@@ -3955,6 +3970,21 @@ export const en: Strings = {uploadVideoDesc: "Attach a video to this message",uploadFile: "Upload file",uploadFileDesc: "Saved to the session scratchpad; the model reads them by path",+ /**+ * The composer's microphone, beside the "+": `dictate` starts a recording, `dictateStop`+ * ends it and transcribes. The two in-flight labels say which half is running — a recording+ * nobody has ended and a recording being transcribed look alike otherwise, and only one of+ * them needs the user to do something.+ */+ dictate: "Voice input",+ dictateStop: "Stop and transcribe",+ dictating: "Recording",+ transcribing: "Transcribing…",+ /** A recording that came back as nothing, said where the draft is rather than as a toast. */+ dictateHeardNothing: "Nothing was heard — please try again.",+ /** The microphone was refused before any recording started (no device, or permission denied). */+ dictateUnavailable:+ "The microphone is unavailable: check the browser's or the system's permission for it.",removeFile: "Remove file",attachmentTooLarge: (name: string, limitMb: number): string =>`${name} exceeds the ${limitMb}MB limit and was not attached.`,@@ -5780,6 +5810,18 @@ export const en: Strings = {too_many_files: "Too many files attached to one message.",payload_too_large: "The request is too large.",image_too_large: "The image is too large to send inline.",+ asr_not_configured:+ "No speech model is configured — set one under Settings → Server → Speech input.",+ asr_unreachable:+ "The speech service could not be reached; check the service address and the network.",+ asr_timeout: "The speech service did not answer in time; please try again.",+ asr_empty_audio: "Nothing was recorded; please try again.",+ asr_too_long: "The recording is too long; please say less.",+ asr_bad_audio: "The recording is incomplete; please try again.",+ asr_bad_sample_rate: "The recording's sample rate is not supported.",+ invalid_asr_base_url: "The service address must be a full http(s) URL.",+ invalid_asr_model: "The model id cannot be empty.",+ invalid_asr_api_key: "The API key cannot be empty.",dir_not_absolute: "The directory must be an absolute path.",dir_not_found: "That directory does not exist or is inaccessible.",dir_permission_denied: "The server is not allowed to access that directory.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 4436bade..9d69a45f 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -833,6 +833,20 @@ export const zh = {uploadLimitsInfo: (count: number, imageMb: number): string =>`一条消息最多 ${count} 个附件;对话内嵌图片另有 ${imageMb}MB 上限,不随此设置变化——` +`图片会进入对话与轨迹,每次翻阅历史与恢复会话都要重新付出它的体积。`,+ speechTitle: "语音输入",+ /** Disclosed at the pane heading: where the audio goes, and where the key lives. */+ speechInfo:+ "录音在浏览器里完成,识别在服务器上做:录音交给下列服务商转成文字,服务商密钥只留在这台服务器上," ++ "不随页面下发。配好之后,聊天输入框的麦克风按钮就能用。",+ speechBaseUrl: "服务地址",+ speechBaseUrlHint: "服务商的站点地址,例如 https://tokendance.space",+ speechModel: "识别模型",+ speechModelHint: "服务商那边的模型 ID,例如 qwen-audio-3.1-asr-flash-streaming",+ speechApiKey: "API 密钥",+ speechApiKeyHint: "留空表示沿用已保存的密钥",+ /** The two states of the stored key, shown beside the key field. */+ speechKeyStored: "已保存密钥",+ speechKeyMissing: "尚未保存密钥,语音输入暂不可用",/** The fold holding the fields a settings group marks advanced. */pluginAdvanced: "高级选项",/** A table cell its row does not let change, beside the lock mark. */@@ -4030,6 +4044,20 @@ export const zh = {uploadVideoDesc: "为本条消息附加视频",uploadFile: "上传文件",uploadFileDesc: "文件存入会话临时目录,模型按路径读取",+ /**+ * The composer's microphone, beside the "+": `dictate` starts a recording, `dictateStop`+ * ends it and transcribes. The two in-flight labels say which half is running — a recording+ * nobody has ended and a recording being transcribed look alike otherwise, and only one of+ * them needs the user to do something.+ */+ dictate: "语音输入",+ dictateStop: "结束录音并识别",+ dictating: "正在录音",+ transcribing: "正在识别…",+ /** A recording that came back as nothing, said where the draft is rather than as a toast. */+ dictateHeardNothing: "没有听清,请再说一次。",+ /** The microphone was refused before any recording started (no device, or permission denied). */+ dictateUnavailable: "无法使用麦克风:请检查浏览器或系统的麦克风权限。",removeFile: "移除文件",/*** Toast for a picked file rejected before reading. The limit is admin-settable and differs@@ -5821,6 +5849,16 @@ export const zh = {too_many_files: "一条消息附加的文件过多。",payload_too_large: "请求体过大。",image_too_large: "图片过大,无法随对话发送。",+ asr_not_configured: "还没有配置语音识别模型,请在「设置 → 服务器 → 语音输入」里配置。",+ asr_unreachable: "连不上语音服务,请检查设置里的服务地址与网络。",+ asr_timeout: "语音服务没有及时返回结果,请再试一次。",+ asr_empty_audio: "没有录到声音,请再试一次。",+ asr_too_long: "录音太长了,请说得短一点。",+ asr_bad_audio: "录音数据不完整,请再试一次。",+ asr_bad_sample_rate: "录音的采样率不受支持。",+ invalid_asr_base_url: "服务地址必须是完整的 http(s) 地址。",+ invalid_asr_model: "识别模型不能为空。",+ invalid_asr_api_key: "API 密钥不能为空。",dir_not_absolute: "目录必须是绝对路径。",dir_not_found: "该目录不存在或不可访问。",dir_permission_denied: "没有访问该目录的权限。",diff --git a/packages/web/test/asr-audio.test.ts b/packages/web/test/asr-audio.test.tsnew file mode 100644index 00000000..b9aaafc3--- /dev/null+++ b/packages/web/test/asr-audio.test.ts@@ -0,0 +1,76 @@+/**+ * The composer's recording, converted to what the transcribe route takes.+ *+ * These are the steps between the decoder's float channels and the PCM16 bytes the server+ * forwards: down-mixing, resampling and quantising. They are pure, which is the point — a+ * microphone is not needed to know that a 48 kHz recording arrives as half as many samples, or+ * that a stereo pair becomes one channel, or that a sample outside [-1, 1] is clamped rather+ * than wrapped around into a click.+ */+import { describe, expect, it } from "vitest";+import {+ ASR_SAMPLE_RATE,+ encodeBase64,+ mixToMono,+ resampleMono,+ toAsrPcm,+ toPcm16Le,+} from "../src/lib/asr-audio";++/** Read one little-endian 16-bit sample back out of the bytes. */+const sampleAt = (bytes: Uint8Array, index: number): number =>+ new DataView(bytes.buffer, bytes.byteOffset).getInt16(index * 2, true);++describe("the recording's conversion to PCM16", () => {+ it("averages every channel into one", () => {+ const mono = mixToMono([Float32Array.of(1, 0, -1), Float32Array.of(0, 0, 1)]);+ expect(Array.from(mono)).toEqual([0.5, 0, 0]);+ });++ it("leaves a single channel exactly as it is", () => {+ const only = Float32Array.of(0.25, -0.5);+ expect(mixToMono([only])).toBe(only);+ expect(mixToMono([]).length).toBe(0);+ });++ it("resamples to the count the rate ratio asks for, holding a constant signal", () => {+ const input = new Float32Array(300).fill(0.5);+ const output = resampleMono(input, 48_000, ASR_SAMPLE_RATE);+ expect(output.length).toBe(100);+ expect(output.every((v) => Math.abs(v - 0.5) < 1e-6)).toBe(true);+ });++ it("returns the input unchanged at the same rate, or when there is nothing to convert", () => {+ const input = Float32Array.of(0.1, 0.2);+ expect(resampleMono(input, ASR_SAMPLE_RATE, ASR_SAMPLE_RATE)).toBe(input);+ expect(resampleMono(new Float32Array(0), 48_000, ASR_SAMPLE_RATE).length).toBe(0);+ });++ it("writes little-endian 16-bit samples, clamped to the range Int16 has", () => {+ const bytes = toPcm16Le(Float32Array.of(0, 1, -1, 2, -2));+ expect(sampleAt(bytes, 0)).toBe(0);+ expect(sampleAt(bytes, 1)).toBe(32767);+ expect(sampleAt(bytes, 2)).toBe(-32767);+ // Beyond the range: clamped, not wrapped — a wrap is the loud click this guards against.+ expect(sampleAt(bytes, 3)).toBe(32767);+ expect(sampleAt(bytes, 4)).toBe(-32767);+ expect(bytes.length).toBe(10);+ });++ it("converts a decoded recording end to end", () => {+ // Two channels of a 48 kHz recording, one second long: 48 000 frames become 16 000 samples+ // of one channel, which is 32 000 bytes.+ const pcm = toAsrPcm([new Float32Array(48_000).fill(0.5), new Float32Array(48_000)], 48_000);+ expect(pcm.length).toBe(ASR_SAMPLE_RATE * 2);+ expect(sampleAt(pcm, 0)).toBe(Math.round(0.25 * 32767));+ });++ it("base64-encodes a whole recording, not just the first chunk", () => {+ // Longer than the encoder's internal slice (0x8000), so a one-shot implementation would+ // either throw on the argument limit or quietly encode only the beginning.+ const bytes = new Uint8Array(200_000);+ for (let i = 0; i < bytes.length; i++) bytes[i] = i % 256;+ expect(encodeBase64(bytes)).toBe(Buffer.from(bytes).toString("base64"));+ expect(encodeBase64(new Uint8Array(0))).toBe("");+ });+});diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.tsindex be7b6994..85a9dab5 100644--- a/packages/web/test/settings-sections.test.ts+++ b/packages/web/test/settings-sections.test.ts@@ -55,6 +55,7 @@ describe("visibleSettingsSections", () => {"credits","proxy","uploads",+ "speech","company","agentApi","plugins",@@ -93,6 +94,7 @@ describe("visibleSettingsSections", () => {"credits","proxy","uploads",+ "speech","company","agentApi","plugins",@@ -112,6 +114,7 @@ describe("visibleSettingsSections", () => {"credits","proxy","uploads",+ "speech","company","agentApi","plugins",