A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): 输入框能语音输入,识别在服务器上做
lmlihengf9ce8ac9a1d1
diff --git a/changelog/unreleased/2026-11-07-speech-input.md b/changelog/unreleased/2026-11-07-speech-input.mdindex 0dca4bc8..67811c11 100644--- a/changelog/unreleased/2026-11-07-speech-input.md+++ b/changelog/unreleased/2026-11-07-speech-input.md@@ -17,32 +17,60 @@ account; and the provider's key then lives in one place, on the server, insteadevery browser that opens the page. What the page sends is the recording itself, over the session's owncredentials, 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+Which service does the transcribing is a Server setting — the same shape as the other per-deploymentsettings: the address of the service, the model id, and the key. The key is write-only, exactly like aProject's model credentials: the settings page reads back whether one is stored, never the value, so anadmin editing the model does not have to paste the key again.+## One protocol, two addresses++The real-time speech models are served by Alibaba's Bailian and re-served by a gateway in front of it.+Both speak the same protocol at their own path, so **the address is all that separates them**:++| Address | Endpoint |+|---|---|+| `https://tokendance.space` (default) | `wss://…/gateway/alibaba/api-ws/v1/inference` |+| `https://dashscope.aliyuncs.com` | `wss://…/api-ws/v1/inference` |++One utterance is one WebSocket: a `run-task` frame naming the model and the audio's format, the+recording in ~100 ms frames, then `finish-task`; the transcript comes back as `result-generated`+frames and `task-finished` ends it. Both sides answer the same model id,+`qwen-audio-3.1-asr-flash-streaming`, so the address is the only thing that changes.++## A sentence arrives many times++The service does not send a sentence once. While it is still recognizing one it sends the same+`sentence_id` again with more of it. Joining every frame would therefore repeat every word as many+times as it was revised — the first working draft here did exactly that, and only the protocol's own+shape, recorded in the reference app's design notes, showed it. A frame that names its sentence now+replaces the text held for that sentence, and sentences are joined in the order they first appeared.+A frame that names no sentence counts only when it is marked finished, which is the shape the+gateway's own example prints.++Watching the live service send 16 seconds of speech, it revised `sentence_id: 1` about twenty times —+`"" → "呵" → "呵我" → "呵,5月见" → "呵,5月见派" → "呵,五岳剑派,哎呀呀" → …` — and never marked any+of them `sentence_end`, not even the last one before `task-finished`. So the transcript has to be+built from the revisions and not from that flag: an implementation that waited for `sentence_end`+would have returned nothing at all.+## The recording- A click starts the recording, the button turns into the way to end it, and a second click stops andtranscribes. The label says which half is running — a recording nobody has ended and a recordingbeing 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.+ rate the protocol documents — so nothing about the container the browser chose reaches the service.- Two things are said where the draft is, not as a toast that dismisses itself: a recording that cameback 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.+ A refusal from the service — a key it does not accept, a model the account cannot use, an account in+ arrears — is shown in the service'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/services/asr.ts` (new): the protocol, one WebSocket per utterance, its frames+ turned into an ordered queue so a stalled service surfaces as a timeout instead of hanging the+ request, and the transcript folded by `sentence_id` as above.- `packages/server/src/http/routes/asr.ts` (new): `GET|PUT /api/asr/config` is an admin's (it holds thekey); `POST /api/asr/transcribe` is every signed-in user's. An empty or omitted `apiKey` on a PUTkeeps the stored one, and every field is validated before any is written.@@ -58,12 +86,13 @@ admin editing the model does not have to paste the key again.## 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/server/test/asr.test.ts` (new, 17 cases, against a local socket speaking the protocol):+ the `Authorization` header, the model and audio parameters, the audio's own bytes, `finish-task`,+ several sentences joined in arrival order, a revised sentence counted once, a finished sentence that+ names no id, an empty answer as a success, `task-failed` read back in the service's words, an+ unreachable service, the refusals (empty audio, an odd byte count, over the length cap, an+ unaccepted sample rate, a non-admin asking for the key, an invalid address never reaching storage),+ and the endpoint each kind of address resolves to.- `packages/web/test/asr-audio.test.ts` (new, 7 cases): decode, downmix, resample, PCM16 conversionand 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@@ -72,13 +101,23 @@ admin editing the model does not have to paste the key again.the service answers with lands in the draft.- `packages/server/test/hot-replace.test.ts`: the Settings double gains the two new methods.+## Verified against the live service++A throwaway server was pointed at `https://dashscope.aliyuncs.com` with a real Bailian key and 16+seconds of speech posted to `/api/asr/transcribe`. Three runs, each about 3 s, each answering:++> 呵,五岳剑派,哎呀呀,别用这种眼神看着我嘛,人家可是一片好心呢。听说你们掌门身体有恙,可要试试本宫这上等的丹药。++with the model the setting names, `qwen-audio-3.1-asr-flash-streaming`. Before that, the same account+had answered `task-failed / Arrearage / Access denied, please make sure your account is in good+standing` — the gate opens and closes, and the route passes that sentence through verbatim when it+closes. (The reference implementation on this machine, driven with the same key, endpoint and model,+is refused identically, so it is the account's standing and not the integration.)+## CompatibilityNo API removed. One new settings group, stored as KV rows like the rest; an unconfigured server keepsits 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.+settings page. The default address is the gateway's, so a deployment holding a TokenDance key needs+only the key pasted in; one holding a Bailian key sets the address to `https://dashscope.aliyuncs.com`+and keeps the model as it is.diff --git a/changelog/unreleased/2026-11-07-speech-input.zh.md b/changelog/unreleased/2026-11-07-speech-input.zh.mdindex 55f4d285..9c284ebd 100644--- a/changelog/unreleased/2026-11-07-speech-input.zh.md+++ b/changelog/unreleased/2026-11-07-speech-input.zh.md@@ -14,26 +14,50 @@和桌面版上表现不同;密钥也因此只留在这台服务器上,不随每个打开页面的浏览器下发。页面发出去的是录音本身,沿用会话自己的凭据,且不会写进磁盘任何一处。-用哪个服务商来识别是「服务器」分组里的一项设置,与其它部署级设置同一种形态:服务地址、模型 ID、API 密钥。+用哪个服务来识别是「服务器」分组里的一项设置,与其它部署级设置同一种形态:服务地址、模型 ID、API 密钥。密钥是只写的,和项目里的模型凭据一样 —— 设置页读回来的是「有没有存过」,不是密钥本身,管理员只改模型时不必重新贴一遍密钥。+## 一套协议,两个地址++实时语音模型由阿里百炼自己提供,也被它前面的一层网关转售。两家在各自的路径上说同一套协议,所以**区别只+在地址**:++| 地址 | 端点 |+|---|---|+| `https://tokendance.space`(默认) | `wss://…/gateway/alibaba/api-ws/v1/inference` |+| `https://dashscope.aliyuncs.com` | `wss://…/api-ws/v1/inference` |++一句录音一条 WebSocket:`run-task` 帧报出模型与音频格式,录音按约 100 ms 一帧发送,然后 `finish-task`;+转写以 `result-generated` 帧回来,`task-finished` 结束。两边用的是同一个模型 ID+`qwen-audio-3.1-asr-flash-streaming`,变的只有地址。++## 一句话会来很多次++服务不是把一句话发一次就完。它还在识别这一句时会带着同一个 `sentence_id` 再发一次、多出几个字。逐帧拼接+就会把每个词按被修正的次数重复出来 —— 这里的第一版正是这么做的,是协议本来的形态(记在参考应用的设计笔记+里)把这件事揪出来的。现在,带句子编号的帧覆盖该句已存下的文字,各句按首次出现的顺序相接;不带编号的帧只在+被标记为收尾时才算一句,那是网关自己的示例打印的形态。++盯着真服务发完 16 秒语音:它对同一个 `sentence_id: 1` 改了大约二十次 ——+`"" → "呵" → "呵我" → "呵,5月见" → "呵,5月见派" → "呵,五岳剑派,哎呀呀" → …` —— 并且从头到尾+**没有一帧 `sentence_end` 为真**,连 `task-finished` 之前的最后一帧也不是。所以转写只能从一次次修正里+拼出来,不能等那个标志:真按 `sentence_end` 收尾,这段代码会一个字都拿不到。+## 录音这一侧-- 点一下开始录,按钮变成结束它入口,再点一下结束并识别。两个在途状态各自有说明:录完了没人按结束,与正在+- 点一下开始录,按钮变成结束它的入口,再点一下结束并识别。两个在途状态各自有说明:录完了没人按结束,与正在识别,看上去一模一样,但只有一种在等用户动手。-- 音频在页面里解码、混成单声道,按 16 kHz 的 16 位 PCM 发出 —— 流式协议文档上的采样率 —— 浏览器挑了什么- 容器都到不了服务商那边。+- 音频在页面里解码、混成单声道,按 16 kHz 的 16 位 PCM 发出 —— 协议上的采样率 —— 浏览器挑了什么容器都到+ 不了服务那边。- 两件事说在草稿框那儿,而不是丢进一条自己会消失的通知:录到一片安静(「没有听清,请再说一次。」),以及- 还没开录就被拒的麦克风。服务商自己的拒绝 —— 密钥不被接受、账号用不了这个模型 —— 按服务商的原话显示,- 那句话点明了该改什么,而该改的地方就在设置页。+ 还没开录就被拒的麦克风。服务自己的拒绝 —— 密钥不被接受、账号用不了这个模型、账号欠费 —— 按服务商的原话+ 显示,那句话点明了该改什么,而该改的地方就在设置页。## 明细-- `packages/server/src/services/asr.ts`(新):一句录音一条 WebSocket,走流式协议 —— `run-task` 报出- 模型与音频格式,音频按约 100 ms 一帧发送,`finish-task`,然后收 `result-generated` 的句子直到- `task-finished`。传输层的形态不出这个文件:帧排成有序队列,握手与收帧之间不会丢东西,卡住的服务表现为- 超时而不是挂住请求。+- `packages/server/src/services/asr.ts`(新):这套协议,一句录音一条 WebSocket,帧排成有序队列,卡住的+ 服务表现为超时而不是挂住请求;转写按上面的规矩按 `sentence_id` 归并。- `packages/server/src/http/routes/asr.ts`(新):`GET|PUT /api/asr/config` 归管理员(密钥在这儿);`POST /api/asr/transcribe` 归任何已登录用户。PUT 里空着或没给 `apiKey` 就沿用已存的那把,且每个字段都先校验完再落盘。@@ -49,21 +73,31 @@## 测试-- `packages/server/test/asr.test.ts`(新,15 条,对着一个本地说这套协议的套接字跑):`Authorization`- 头、告诉服务商的模型与音频参数、音频本身的字节数、`finish-task`、多句按到达顺序拼接、空结果算成功、- `task-failed` 按服务商原话读回、服务不可达,以及各条拒绝 —— 空音频、奇数长度、超过时长上限、不受支持的- 采样率、非管理员来读密钥、非法地址不落盘。+- `packages/server/test/asr.test.ts`(新,17 条,对着一个本地说这套协议的套接字跑):`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`:设置替身补上这两个新方法。+## 对着真服务验过++起了一个临时服务器指向 `https://dashscope.aliyuncs.com`,用一把真的百炼密钥往 `/api/asr/transcribe` 发了+16 秒语音。跑了三次,每次约 3 秒,每次都回来:++> 呵,五岳剑派,哎呀呀,别用这种眼神看着我嘛,人家可是一片好心呢。听说你们掌门身体有恙,可要试试本宫这上等的丹药。++模型就是设置里那个 `qwen-audio-3.1-asr-flash-streaming`。在这之前,同一个账号回的是+`task-failed / Arrearage / Access denied, please make sure your account is in good standing` ——+这道闸会开也会关,关上时路由把那句话原样透出。(本机上那份参考实现,用同一把密钥、同一个端点、同一个模型+去跑,被拒的回事一模一样,所以那是账号状态,不是这条链路。)+## 兼容性没有删任何接口。多一组设置,与其它设置一样按 KV 行存放;没配过的服务器行为不变 —— 麦克风按钮会说还没有-配置识别模型,并指向设置页。默认地址与模型是词元跳动的,因此手上已有词元跳动密钥的部署只需把密钥贴进去。--**端到端那一次是对着假语音服务验的,不是对着真服务商:** 手上这把词元跳动的密钥被词元跳动自己拒了-(`unauthorized / API 密钥不存在`),因此真识别结果还没有看到过。+配置识别模型,并指向设置页。默认地址是网关那边的,因此手上已有词元跳动密钥的部署只需把密钥贴进去;手上是+百炼密钥的,把地址填成 `https://dashscope.aliyuncs.com`,模型不用动。diff --git a/packages/server/src/http/routes/asr.ts b/packages/server/src/http/routes/asr.tsindex a6b05c8a..cb35ff3c 100644--- a/packages/server/src/http/routes/asr.ts+++ b/packages/server/src/http/routes/asr.ts@@ -25,7 +25,7 @@ import {AsrError,DEFAULT_ASR_BASE_URL,DEFAULT_ASR_MODEL,- transcribeStreaming,+ transcribe,} from "../../services/asr.js";/** Sample rates a recording may arrive at; the protocol accepts these and nothing else. */@@ -96,7 +96,7 @@ export function asrRoutes(deps: AsrRouteDeps): Hono<AppEnv> {const sampleRate = parseSampleRate(body.sampleRate);const pcm = parseAudio(body.dataBase64);try {- const text = await transcribeStreaming({+ const text = await transcribe({baseUrl: stored.baseUrl,model: stored.model,apiKey: stored.apiKey,diff --git a/packages/server/src/services/asr.ts b/packages/server/src/services/asr.tsindex 0c12035e..e695e747 100644--- a/packages/server/src/services/asr.ts+++ b/packages/server/src/services/asr.ts@@ -1,37 +1,41 @@/**- * Speech input: the server's own call to a streaming speech-to-text provider.+ * Speech input: the server's own call to a streaming speech-to-text service.** 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.+ * ONE protocol, two sites — {@link asrWebSocketUrl} picks the path from the configured address.+ * Alibaba's Bailian serves the real-time models directly, and the gateway in front of it+ * re-serves the same models under its own prefix; both speak `run-task`: a frame naming the+ * model and the audio's format, then the recording in ~100 ms frames, then `finish-task`. The+ * transcript arrives as `result-generated` frames, one sentence at a time, and `task-finished`+ * ends it.** 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.+ * service 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. */+/** Site the speech 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.+ * Where the streaming protocol lives on the gateway that re-serves the models, 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";+/** The same protocol as Alibaba's own site serves it, appended to that site's origin. */+export const BAILIAN_WS_PATH = "/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;@@ -85,14 +89,14 @@ export interface AsrRequest {/** One frame of the protocol, reduced to what this product reads out of it. */type AsrEvent =| { kind: "started" }- | { kind: "sentence"; text: string }+ | { kind: "sentence"; id: string | null; text: string; final: boolean }| { 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.+ * 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's mistake.*/export function asrWebSocketUrl(baseUrl: string): string {const site = baseUrl.trim() === "" ? DEFAULT_ASR_BASE_URL : baseUrl.trim();@@ -102,8 +106,10 @@ export function asrWebSocketUrl(baseUrl: string): string {} catch {throw new Error(`ASR base URL is not a URL: ${site}`);}+ // Alibaba's own site, public or international, serves the models itself one path shorter.+ const bailian = url.hostname === "aliyuncs.com" || url.hostname.endsWith(".aliyuncs.com");const scheme = url.protocol === "http:" ? "ws:" : "wss:";- return `${scheme}//${url.host}${ASR_WS_PATH}`;+ return `${scheme}//${url.host}${bailian ? BAILIAN_WS_PATH : ASR_WS_PATH}`;}/** The model id a configured value resolves to. */@@ -123,8 +129,8 @@ export function parseAsrEvent(raw: string): AsrEvent | null {} catch {return null;}- const header = (parsed as { header?: Record<string, unknown> }).header;- if (header === undefined || header === null) return null;+ const header = asRecord(asRecord(parsed)?.header);+ if (header === null) return null;const event = header.event;if (event === "task-started") return { kind: "started" };if (event === "task-finished") return { kind: "finished" };@@ -136,32 +142,73 @@ export function parseAsrEvent(raw: string): AsrEvent | null {};}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 : "" };+ const sentence = asRecord(asRecord(asRecord(parsed)?.payload)?.output)?.sentence;+ if (!isRecord(sentence)) return null;+ const id = sentence.sentence_id;+ return {+ kind: "sentence",+ id: typeof id === "string" || typeof id === "number" ? String(id) : null,+ text: typeof sentence.text === "string" ? sentence.text : "",+ final: sentence.sentence_end === true,+ };}return null;}-/** The transcript a stream of events adds up to, in the order they arrived. */+/** A transcript being built from sentence frames — see {@link Transcript}. */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("");+ const transcript = new Transcript();+ for (const event of events) {+ if (event.kind === "sentence") transcript.add(event);+ }+ return transcript.value;+}++/**+ * The transcript a stream of sentence frames adds up to. A sentence is NOT one frame: while it+ * is still being recognized the service sends the same sentence again with more of it — sixteen+ * seconds of speech arrives as roughly twenty frames revising one sentence, and the earlier+ * guesses contain words the later ones replace. So a frame that names its sentence replaces the+ * text held for that sentence, and the sentences are joined in the order they first appeared.+ *+ * That flag is not what ends a sentence here: the live service never marks `sentence_end`, not+ * even on its last frame before `task-finished`, so waiting for it would return nothing. A frame+ * that names no sentence therefore counts only when it is marked finished — the shape the+ * gateway's own example prints — and everything else is a revision of something already counted.+ */+class Transcript {+ private readonly sentences: { text: string }[] = [];+ private readonly at = new Map<string, number>();++ add(sentence: { id: string | null; text: string; final: boolean }): void {+ if (sentence.id === null) {+ if (sentence.final) this.sentences.push({ text: sentence.text });+ return;+ }+ const index = this.at.get(sentence.id);+ if (index === undefined) {+ this.at.set(sentence.id, this.sentences.length);+ this.sentences.push({ text: sentence.text });+ return;+ }+ this.sentences[index]!.text = sentence.text;+ }++ get value(): string {+ return this.sentences.map((s) => s.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> {+export async function transcribe(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;+ const deadline = Date.now() + OVERALL_SLACK_MS + durationMs(req.pcm.length, req.sampleRate);try {await frames.opened(HANDSHAKE_TIMEOUT_MS);@@ -198,7 +245,7 @@ export async function transcribeStreaming(req: AsrRequest): Promise<string> {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 === "failed") throw upstreamFailure(event.message.trim() || event.code);if (event.kind === "sentence") sentences.push(event);}} finally {@@ -214,18 +261,34 @@ async function untilStarted(frames: FrameStream, deadline: number): Promise<voidfor (;;) {const event = await frames.next(deadline);if (event.kind === "started") return;- if (event.kind === "failed") throw upstreamFailure(event.code, event.message);+ if (event.kind === "failed") throw upstreamFailure(event.message.trim() || event.code);}}/**- * 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.+ * The service refused or failed the task. Its own words are the message: they name what is wrong+ * (an unknown key, a model the account cannot use, an account in arrears) 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(message: string): AsrError {+ return new AsrError("asr_upstream", message.trim(), 502);+}++/**+ * How long an utterance of this many bytes takes to play, in milliseconds — a whole number,+ * because that is all a timer takes when it is handed one.*/-function upstreamFailure(code: string, message: string): AsrError {- return new AsrError("asr_upstream", message.trim() === "" ? code : message.trim(), 502);+function durationMs(bytes: number, sampleRate: number): number {+ return Math.round((bytes / (sampleRate * 2)) * 1000);+}++function asRecord(value: unknown): Record<string, unknown> | null {+ return isRecord(value) ? value : null;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);}function taskId(): string {diff --git a/packages/server/test/asr.test.ts b/packages/server/test/asr.test.tsindex 07013b1c..f2c5d8fe 100644--- a/packages/server/test/asr.test.ts+++ b/packages/server/test/asr.test.ts@@ -1,6 +1,6 @@/*** 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+ * /api/asr/transcribe, the server makes ONE WebSocket call to the configured service and* answers with the transcript.** The upstream is a fake `ws` server on a loopback port, so the cases below drive the real@@ -16,6 +16,7 @@* - 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 sentence the provider revises is counted once, not once per revision.* - 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.@@ -28,6 +29,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } fromimport type { AsrConfig, AsrConfigResponse, AsrTranscribeResponse } from "../src/api/types.js";import {ASR_MAX_BYTES,+ BAILIAN_WS_PATH,DEFAULT_ASR_BASE_URL,DEFAULT_ASR_MODEL,asrWebSocketUrl,@@ -66,10 +68,14 @@ interface FakeUpstream {/*** 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.+ * and on `finish-task` emits the sentences and ends the task. A sentence may be given as a+ * bare string (one finished sentence) or as the frame object itself, which is how the+ * revision cases say what they mean.*/+type FakeSentence = string | Record<string, unknown>;+async function startFakeUpstream(- options: { sentences?: string[]; fail?: { code: string; message: string } } = {},+ options: { sentences?: FakeSentence[]; fail?: { code: string; message: string } } = {},): Promise<FakeUpstream> {const seen: FakeUpstream["seen"] = {authorization: undefined,@@ -109,11 +115,18 @@ async function startFakeUpstream(}if (frame.header?.action === "finish-task") {seen.finished = true;- for (const text of options.sentences ?? ["你好"]) {+ for (const sentence of options.sentences ?? ["你好"]) {socket.send(JSON.stringify({header: { event: "result-generated" },- payload: { output: { sentence: { text, sentence_end: true } } },+ payload: {+ output: {+ sentence:+ typeof sentence === "string"+ ? { text: sentence, sentence_end: true }+ : sentence,+ },+ },}),);}@@ -336,9 +349,46 @@ describe("speech input", () => {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`);+ it("counts a sentence the provider revises once, not once per revision", async () => {+ // The shape the service really sends: the same sentence_id again and again with more of it+ // as the words are recognized, and `sentence_end` on the last of them.+ upstream = await startFakeUpstream({+ sentences: [+ { sentence_id: 1, text: "你好", sentence_end: false },+ { sentence_id: 1, text: "你好,世界", sentence_end: false },+ { sentence_id: 1, text: "你好,世界。", sentence_end: true },+ { sentence_id: 2, text: "再见。" },+ ],+ });+ await putConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-test-key" });++ const res = await transcribe("admin");+ expect(res.status).toBe(200);+ expect(((await res.json()) as AsrTranscribeResponse).text).toBe("你好,世界。再见。");+ });++ it("counts a finished sentence that names no sentence_id, and ignores an unfinished one", async () => {+ // The gateway's own example prints only the frames marked `sentence_end`; a half-sentence+ // with no id has nothing to replace, so it is a revision of something already counted.+ upstream = await startFakeUpstream({+ sentences: [+ { text: "你好" },+ { text: "你好,世界。", sentence_end: true },+ { text: "你好,世界。再见。", sentence_end: true },+ ],+ });+ await putConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-test-key" });++ const res = await transcribe("admin");+ expect(res.status).toBe(200);+ expect(((await res.json()) as AsrTranscribeResponse).text).toBe(+ "你好,世界。你好,世界。再见。",+ );+ });++ // The pure helpers the route and the flows above rest on.+ it("picks the endpoint from the site's origin, however it 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",);@@ -349,6 +399,17 @@ describe("speech input", () => {expect(asrWebSocketUrl("http://127.0.0.1:9000")).toBe("ws://127.0.0.1:9000/gateway/alibaba/api-ws/v1/inference",);+ // Alibaba's own site, public and international alike, serves the models one path shorter.+ expect(asrWebSocketUrl("https://dashscope.aliyuncs.com")).toBe(+ `wss://dashscope.aliyuncs.com${BAILIAN_WS_PATH}`,+ );+ expect(asrWebSocketUrl("https://dashscope-intl.aliyuncs.com/api/v1")).toBe(+ `wss://dashscope-intl.aliyuncs.com${BAILIAN_WS_PATH}`,+ );+ // A name that merely ends in the same letters is not that site.+ expect(asrWebSocketUrl("https://aliyuncs.com.example.test")).toBe(+ "wss://aliyuncs.com.example.test/gateway/alibaba/api-ws/v1/inference",+ );});it("reads the protocol's frames and ignores anything else", () => {@@ -365,7 +426,7 @@ describe("speech input", () => {payload: { output: { sentence: { text: "句一", sentence_end: true } } },}),),- ).toEqual({ kind: "sentence", text: "句一" });+ ).toEqual({ kind: "sentence", id: null, text: "句一", final: true });expect(parseAsrEvent(JSON.stringify({@@ -379,8 +440,8 @@ describe("speech input", () => {expect(transcriptOf([{ kind: "started" },- { kind: "sentence", text: "甲" },- { kind: "sentence", text: "乙" },+ { kind: "sentence", id: null, text: "甲", final: true },+ { kind: "sentence", id: null, text: "乙", final: true },{ kind: "finished" },]),).toBe("甲乙");diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex b4222738..e109b978 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -775,9 +775,11 @@ export const en: Strings = {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.",+ "it is set, the microphone button in the composer works. Both sites speak the same " ++ "protocol with the same model; only the address differs.",speechBaseUrl: "Service address",- speechBaseUrlHint: "The provider's site, e.g. https://tokendance.space",+ speechBaseUrlHint:+ "The provider's site: https://tokendance.space for the gateway, https://dashscope.aliyuncs.com for Alibaba's own",speechModel: "Model",speechModelHint: "The provider's model id, e.g. qwen-audio-3.1-asr-flash-streaming",speechApiKey: "API key",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex f2b3cf35..825d4da9 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -837,9 +837,10 @@ export const zh = {/** Disclosed at the pane heading: where the audio goes, and where the key lives. */speechInfo:"录音在浏览器里完成,识别在服务器上做:录音交给下列服务商转成文字,服务商密钥只留在这台服务器上," +- "不随页面下发。配好之后,聊天输入框的麦克风按钮就能用。",+ "不随页面下发。配好之后,聊天输入框的麦克风按钮就能用。两家用同一套协议、同一个模型,只有站点不同。",speechBaseUrl: "服务地址",- speechBaseUrlHint: "服务商的站点地址,例如 https://tokendance.space",+ speechBaseUrlHint:+ "服务商的站点地址:词元跳动填 https://tokendance.space,阿里百炼填 https://dashscope.aliyuncs.com",speechModel: "识别模型",speechModelHint: "服务商那边的模型 ID,例如 qwen-audio-3.1-asr-flash-streaming",speechApiKey: "API 密钥",