A local-first multi-agent app development platform, built on PenguinHarness
fix(web,server): 麦克风拿不到时不再怪权限,语音设置能测通不通
lmlihengf8cfe8ba2c45
diff --git a/changelog/unreleased/2026-11-07-speech-input.md b/changelog/unreleased/2026-11-07-speech-input.mdindex 67811c11..f85645af 100644--- a/changelog/unreleased/2026-11-07-speech-input.md+++ b/changelog/unreleased/2026-11-07-speech-input.md@@ -61,44 +61,102 @@ would have returned nothing at all.- The audio is decoded and downmixed in the page and sent as raw 16-bit PCM at 16 kHz — the samplerate 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 came- back empty ("没有听清,请再说一次。"), and a microphone that was refused before any recording began.+ back empty ("没有听清,请再说一次。"), and the reason a microphone could not be opened (next section).A refusal from the service — a key it does not accept, a model the account cannot use, an account inarrears — is shown in the service's own words, since that sentence names what to fix and thesettings page is where it is fixed.+## When there is no microphone, say why++A microphone that could not be opened used to get one sentence: "check the browser's or the system's+permission for it". The case users actually hit is the one where **there is no permission to grant**:+a browser offers a microphone only on https or localhost, and `http://<a machine's address>:7777` is+neither. There `navigator.mediaDevices` **does not exist**, so no prompt is ever shown — telling+someone to go check the permission is telling them to look for something that will never appear.++Asked of a real browser against a live address, this is what it answers:++```+http://110.42.63.153:7777/ isSecureContext: false mediaDevices: undefined+ getUserMedia → TypeError: Cannot read properties of undefined+http://localhost:7777/ isSecureContext: true mediaDevices: object+ permissionQuery: prompt getUserMedia → NotFoundError (no sound card on that box)+```++So the page now decides first and asks afterwards, and the four ways it can be closed get four+sentences:++- **The address is not a secure context** — one line naming that, and on hover the three ways out: use+ the Adelie desktop app (it runs on localhost), put Adelie behind https, or add this address to+ `chrome://flags/#unsafely-treat-insecure-origin-as-secure` for now.+- **This browser cannot record from a microphone.**+- **The permission was denied** — undoing that is the icon in the address bar, which is what the line says.+- **No device**, or **another program holding it**.++## The settings page can check the link++Storing an address, a model and a key is not the same as their working, and a microphone is the+slowest way to find that out. The settings page therefore gains "Test connection": one whole task+against the service — open it, feed it half a second of silence, finish it — which is the call a+recording makes minus the recording, so what it proves is what pressing the microphone proves. It+checks the **fields on screen**, not the stored configuration (saving a key in order to learn whether+it works is the wrong order), and a save follows itself with one, so a configuration that cannot+connect is never left looking finished. Each answer names the endpoint it used, because which path a+site address resolves to is exactly the thing the fields cannot show.++**A failed handshake is asked about once more.** A wrong key, a host that does not exist and a path+that is not the endpoint all arrive from the WebSocket layer looking identical (the same bare+`TypeError`, the same code 1006), so all three used to read "could not reach the service" — which+sends an operator to look at the network for a key that is simply wrong. Once the handshake fails,+the same credential is now put to the same address over plain HTTP: 401 is the key being refused, and+any other status is reported as it stands.+## Details- `packages/server/src/services/asr.ts` (new): the protocol, one WebSocket per utterance, its framesturned 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.+ request, and the transcript folded by `sentence_id` as above. Also `probeAsr` (the connectivity+ check) and the HTTP question asked behind a failed handshake.- `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.+ key); `POST /api/asr/test` is an admin's too, and is the settings page's check;+ `POST /api/asr/transcribe` is every signed-in user's. The address, model and key are resolved by one+ rule, so what a save stores is what the check probes. An empty or omitted `apiKey` on a PUT keeps+ the stored one, and every field is validated before any is written.+- `packages/server/src/api/types.ts`: the three interfaces.- `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/lib/mic-access.ts` (new): whether a microphone may be asked for at all, and what a+ refusal was called — two pure functions that touch no browser global, so both are testable.- `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.+ 输入" page under Server, for admins, with the Test connection button and the line its answer lands on.- `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, 17 cases, against a local socket speaking the protocol):+- `packages/server/test/asr.test.ts` (new, 25 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 thatnames 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.+ unreachable service, a refused credential (401), a site that answers without upgrading, 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), the endpoint each kind of address resolves+ to, and the connectivity check's own five situations (the form's fields without storing them, the+ stored ones when it omits them, a refusal and an unreachable site, an unresolvable field and no key,+ and a non-admin).- `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/test/mic-access.test.ts` (new, 7 cases): the insecure origin, the missing support, and+ the name of each refusal.- `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.+ service), three cases: 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; the settings page's check, including an+ address nothing listens on; and the notice on an **http address that is not localhost**, where the+ case first asserts that the browser really has no `mediaDevices`.- `packages/server/test/hot-replace.test.ts`: the Settings double gains the two new methods.## Verified against the live service@@ -108,6 +166,14 @@ seconds of speech posted to `/api/asr/transcribe`. Three runs, each about 3 s, e> 呵,五岳剑派,哎呀呀,别用这种眼神看着我嘛,人家可是一片好心呢。听说你们掌门身体有恙,可要试试本宫这上等的丹药。+The connectivity check was run against the same live site, three inputs, one each:++```+POST /api/asr/test [stored config] : 200 in 444ms {"ok":true,"message":"","endpoint":"wss://dashscope.aliyuncs.com/api-ws/v1/inference"}+POST /api/asr/test [wrong key] : 200 in 404ms {"ok":false,"message":"The speech service refused the credential (HTTP 401).",…}+POST /api/asr/test [nothing there] : 200 in 15ms {"ok":false,"message":"Could not reach the speech service.",…}+```+with the model the setting names, `qwen-audio-3.1-asr-flash-streaming`. Before that, the same accounthad answered `task-failed / Arrearage / Access denied, please make sure your account is in goodstanding` — the gate opens and closes, and the route passes that sentence through verbatim when it@@ -121,3 +187,6 @@ its old behaviour — the microphone button reports that no model is configuredsettings page. The default address is the gateway's, so a deployment holding a TokenDance key needsonly the key pasted in; one holding a Bailian key sets the address to `https://dashscope.aliyuncs.com`and keeps the model as it is.++Using the microphone on a deployment served over http needs that address to be one the browser treats+as secure (https, localhost, or the flag above). That is the browser's rule, not this page's choice.diff --git a/changelog/unreleased/2026-11-07-speech-input.zh.md b/changelog/unreleased/2026-11-07-speech-input.zh.mdindex 9c284ebd..85ff2f2a 100644--- a/changelog/unreleased/2026-11-07-speech-input.zh.md+++ b/changelog/unreleased/2026-11-07-speech-input.zh.md@@ -51,37 +51,83 @@- 音频在页面里解码、混成单声道,按 16 kHz 的 16 位 PCM 发出 —— 协议上的采样率 —— 浏览器挑了什么容器都到不了服务那边。- 两件事说在草稿框那儿,而不是丢进一条自己会消失的通知:录到一片安静(「没有听清,请再说一次。」),以及- 还没开录就被拒的麦克风。服务自己的拒绝 —— 密钥不被接受、账号用不了这个模型、账号欠费 —— 按服务商的原话- 显示,那句话点明了该改什么,而该改的地方就在设置页。+ 还没开录就拿不到麦克风的原因(下一节)。服务自己的拒绝 —— 密钥不被接受、账号用不了这个模型、账号欠费 ——+ 按服务商的原话显示,那句话点明了该改什么,而该改的地方就在设置页。++## 麦克风拿不到时,说的是真原因++麦克风打不开,原来只有一句话:「请检查浏览器或系统的麦克风权限」。可用户最常撞上的那一种,恰恰是**没有权限+可给**的:浏览器只在 https 或 localhost 下才把麦克风交给页面,`http://<某台机器的地址>:7777` 不在其列。在+这样的地址上 `navigator.mediaDevices` **根本不存在**,浏览器连权限框都不会弹 —— 让用户去「检查权限」,等于+让人去找一个永远不出现的东西。++拿真浏览器对着线上地址问过一次,这是它答的:++```+http://110.42.63.153:7777/ isSecureContext: false mediaDevices: undefined+ getUserMedia → TypeError: Cannot read properties of undefined+http://localhost:7777/ isSecureContext: true mediaDevices: object+ permissionQuery: prompt getUserMedia → NotFoundError(那台机器没有声卡)+```++所以现在是先判、再要权限,四种情况四句话:++- **地址不是安全上下文** —— 一句话点出「这个地址拿不到麦克风」,鼠标停上去是三条出路:用桌面版 Adelie+ (它跑在 localhost 上)、让 Adelie 走 https、或临时把这个地址加进+ `chrome://flags/#unsafely-treat-insecure-origin-as-secure`。+- **这个浏览器不支持网页录音。**+- **权限被拒过** —— 该改的地方是地址栏左边那个图标,说得就是这句。+- **没有设备**,或**设备被别的程序占着**。++## 设置里能测这条链路++存下地址、模型和密钥,不等于它们能用;而麦克风是发现这件事最慢的方式。设置页因此多一个「测试连通性」:对+服务跑一遍完整的任务 —— 开一个 task、喂半秒静音、收尾 —— 也就是录音会走的那条路,只少了录音本身,所以它+证明了按下麦克风时会发生什么。它验的是**屏幕上那三个框**,不是已存的配置(为了知道一把密钥能不能用、先把+它存下来,顺序是反的),保存成功之后也会自动跑一次,于是「配好了却连不通」这个状态不会留着不说。回答里带+着这次用的端点地址,因为「这个站点因此走哪条路径」恰恰是从字段里看不出来的那件事。++**握手失败会再问一次。** 一把错密钥、一个不存在的域名、一条不是端点的路径,在 WebSocket 那一层长得一模一样+(同一个空 `TypeError`、同一个 1006),所以过去统统报成「连不上服务」—— 把人打发去查网络,而问题在密钥。+现在握手失败后,会拿同一份凭据对同一个地址发一次普通 HTTP 请求:401 就是密钥被拒,其它状态码也照原样说出。## 明细- `packages/server/src/services/asr.ts`(新):这套协议,一句录音一条 WebSocket,帧排成有序队列,卡住的- 服务表现为超时而不是挂住请求;转写按上面的规矩按 `sentence_id` 归并。+ 服务表现为超时而不是挂住请求;转写按上面的规矩按 `sentence_id` 归并。另有 `probeAsr`(连通性检查)与+ 握手失败后的那次 HTTP 追问。- `packages/server/src/http/routes/asr.ts`(新):`GET|PUT /api/asr/config` 归管理员(密钥在这儿);- `POST /api/asr/transcribe` 归任何已登录用户。PUT 里空着或没给 `apiKey` 就沿用已存的那把,且每个字段都- 先校验完再落盘。+ `POST /api/asr/test` 也归管理员,是设置页的连通性检查;`POST /api/asr/transcribe` 归任何已登录用户。+ 地址、模型和密钥的解析只写一份,保存存的就是检查验的那一份;PUT 里空着或没给 `apiKey` 就沿用已存的那把,+ 且每个字段都先校验完再落盘。+- `packages/server/src/api/types.ts`:这三个接口的类型。- `packages/server/src/db/repos/server-settings.ts`、`.../mechanisms/settings.ts`:这三个取值,多出一组设置。- `packages/web/src/lib/asr-audio.ts`(新):解码、混单声道、重采样、PCM16、base64。+- `packages/web/src/lib/mic-access.ts`(新):先判「能不能要麦克风」,再读「被拒的原因」—— 两个不碰浏览器+ 全局的纯函数,因此可测。- `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`(新,17 条,对着一个本地说这套协议的套接字跑):`Authorization`+- `packages/server/test/asr.test.ts`(新,25 条,对着一个本地说这套协议的套接字跑):`Authorization`头、模型与音频参数、音频本身的字节数、`finish-task`、多句按到达顺序拼接、被修正的一句只算一次、没有编号- 的收尾句、空结果算成功、`task-failed` 按服务原话读回、服务不可达、各条拒绝(空音频、奇数长度、超过时长- 上限、不受支持的采样率、非管理员来读密钥、非法地址不落盘),以及两类地址各自解析出的端点。+ 的收尾句、空结果算成功、`task-failed` 按服务原话读回、服务不可达、被拒的凭据(401)、答了却不是升级的+ 中转站、各条拒绝(空音频、奇数长度、超过时长上限、不受支持的采样率、非管理员来读密钥、非法地址不落盘)、+ 两类地址各自解析出的端点,以及连通性检查本身的五种情形(字段来自表单且不落盘、缺省回落已存配置、被拒与+ 不可达、解析不了与没密钥、非管理员)。- `packages/web/test/asr-audio.test.ts`(新,7 条):解码、混单声道、重采样、PCM16 转换与 base64 ——含立体声与不是录音采样率的那种输入。-- `packages/web/e2e/asr-dictation.spec.mjs`(脚手架里;真浏览器、真服务端、一个假语音服务):设置页存下- 地址、模型与密钥,服务端读回 `hasKey`;随后 Chromium 的假麦克风播放一个 WAV 文件,按钮录到真音频,服务- 答的那句话落进草稿框。+- `packages/web/test/mic-access.test.ts`(新,7 条):不安全上下文、不支持、以及各类拒绝名的归类。+- `packages/web/e2e/asr-dictation.spec.mjs`(脚手架里;真浏览器、真服务端、一个假语音服务)三条:设置页存下+ 地址、模型与密钥,服务端读回 `hasKey`,随后 Chromium 的假麦克风播放一个 WAV 文件,按钮录到真音频,服务+ 答的那句话落进草稿框;设置页的连通性检查(含换一个没人听的地址);以及**非 localhost 的 http 地址**上+ 那一行提示 —— 那里浏览器确实没有 `mediaDevices`,用例先断言这一点。- `packages/server/test/hot-replace.test.ts`:设置替身补上这两个新方法。## 对着真服务验过@@ -91,6 +137,14 @@> 呵,五岳剑派,哎呀呀,别用这种眼神看着我嘛,人家可是一片好心呢。听说你们掌门身体有恙,可要试试本宫这上等的丹药。+连通性检查也是对着这个真站点跑的,三种输入各一次:++```+POST /api/asr/test [存好的配置] : 200 in 444ms {"ok":true,"message":"","endpoint":"wss://dashscope.aliyuncs.com/api-ws/v1/inference"}+POST /api/asr/test [坏 key] : 200 in 404ms {"ok":false,"message":"The speech service refused the credential (HTTP 401).",…}+POST /api/asr/test [没人听的地址] : 200 in 15ms {"ok":false,"message":"Could not reach the speech service.",…}+```+模型就是设置里那个 `qwen-audio-3.1-asr-flash-streaming`。在这之前,同一个账号回的是`task-failed / Arrearage / Access denied, please make sure your account is in good standing` ——这道闸会开也会关,关上时路由把那句话原样透出。(本机上那份参考实现,用同一把密钥、同一个端点、同一个模型@@ -101,3 +155,6 @@没有删任何接口。多一组设置,与其它设置一样按 KV 行存放;没配过的服务器行为不变 —— 麦克风按钮会说还没有配置识别模型,并指向设置页。默认地址是网关那边的,因此手上已有词元跳动密钥的部署只需把密钥贴进去;手上是百炼密钥的,把地址填成 `https://dashscope.aliyuncs.com`,模型不用动。++在一台走 http 的部署上用麦克风,需要那个地址被浏览器当成安全上下文(https、localhost,或上面那条 flag);+这是浏览器的规矩,不是这个页面的选择。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 74f9ded8..f3cbf2e2 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -371,6 +371,29 @@ export interface AsrTranscribeResponse {text: string;}+/**+ * POST /api/asr/test request: the settings page's connectivity check. Every field is optional+ * and falls back to what is stored, so the page can check the form BEFORE saving it — and an+ * omitted or empty `apiKey` means the stored one, exactly as a PUT reads it.+ */+export interface AsrTestRequest {+ baseUrl?: string;+ model?: string;+ apiKey?: string;+}++/**+ * POST /api/asr/test result. `ok: false` is a check that RAN and found a problem, not a failed+ * request: `message` is then the provider's own words (nothing is translated in between), and+ * `endpoint` is the WebSocket the check actually used — the site setting resolves to two+ * different paths, so naming it is how the operator sees which one this site took.+ */+export interface AsrTestResponse {+ ok: boolean;+ message: string;+ endpoint: 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/http/routes/asr.ts b/packages/server/src/http/routes/asr.tsindex cb35ff3c..bfda14a1 100644--- a/packages/server/src/http/routes/asr.ts+++ b/packages/server/src/http/routes/asr.ts@@ -11,9 +11,19 @@* 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.+ *+ * POST /api/asr/test is an admin's too: the settings page's connectivity check. It resolves the+ * fields the same way a PUT does — an omitted one falls back to what is stored — so the page can+ * check a form it has not saved yet, and what it answers is what a save with those fields would+ * produce. Nothing is written either way.*/import { Hono } from "hono";-import type { AsrConfig, AsrConfigResponse, AsrTranscribeResponse } from "../../api/types.js";+import type {+ AsrConfig,+ AsrConfigResponse,+ AsrTestResponse,+ AsrTranscribeResponse,+} from "../../api/types.js";import { HttpError } from "../errors.js";import { readJson } from "../validate.js";import { Bind, Component, Use } from "@adelie/core/kernel";@@ -25,6 +35,8 @@ import {AsrError,DEFAULT_ASR_BASE_URL,DEFAULT_ASR_MODEL,+ asrWebSocketUrl,+ probeAsr,transcribe,} from "../../services/asr.js";@@ -54,11 +66,17 @@ export function asrRoutes(deps: AsrRouteDeps): Hono<AppEnv> {app.get("/config", requireAdmin, (c) => c.json({ config: config() } satisfies AsrConfigResponse));- app.put("/config", requireAdmin, async (c) => {- const body = await readJson(c);+ /**+ * The site, the model and the key a request names. An omitted field falls back to what is+ * stored, `null` means the built-in default, and an omitted or empty key keeps the stored one+ * (the read never hands it back, so a page that only edits the model must not have to blank+ * its own credential to save).+ *+ * One rule for both verbs below: the PUT stores what this returns and the check probes it, so a+ * field the save would refuse is refused by the check as well, with the same code.+ */+ const resolve = (body: Record<string, unknown>) => {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@@ -71,18 +89,41 @@ export function asrRoutes(deps: AsrRouteDeps): Hono<AppEnv> {: 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 { baseUrl, model, apiKey };+ };++ app.put("/config", requireAdmin, async (c) => {+ // Every field is validated before any is written, so a PUT naming one bad value leaves+ // the rest as they were.+ deps.settings.setAsrSettings(resolve(await readJson(c)));return c.json({ config: config() } satisfies AsrConfigResponse);});+ /**+ * The settings page's connectivity check: one whole task against the resolved site. It answers+ * 200 with `ok: false` when the service refused — the check itself ran, and the operator wants+ * the provider's sentence, not an HTTP status. Only the fields being unresolvable (400) or no+ * key being stored (400) are errors here.+ */+ app.post("/test", requireAdmin, async (c) => {+ const { baseUrl, model, apiKey } = resolve(await readJson(c));+ if (apiKey === "") {+ throw new HttpError(+ 400,+ "asr_not_configured",+ "No speech model is configured: set one under Settings > Server > Speech input.",+ );+ }+ const probe = await probeAsr({ baseUrl, model, apiKey });+ return c.json({ ...probe, endpoint: asrWebSocketUrl(baseUrl) } satisfies AsrTestResponse);+ });+app.post("/transcribe", async (c) => {const stored = deps.settings.getAsrSettings();if (stored.apiKey === "") {diff --git a/packages/server/src/services/asr.ts b/packages/server/src/services/asr.tsindex e695e747..a9cf2fbf 100644--- a/packages/server/src/services/asr.ts+++ b/packages/server/src/services/asr.ts@@ -57,11 +57,18 @@ const CHUNK_PAUSE_MS = 10;/** How long the socket itself may take to open. */const HANDSHAKE_TIMEOUT_MS = 15_000;+/**+ * How long the diagnostic below may take. Shorter than the handshake: it runs only once the+ * handshake has already failed, and it asks a question a server that is there answers at once.+ */+const PROBE_TIMEOUT_MS = 8_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 type AsrErrorCode =+ "asr_unreachable" | "asr_credential_refused" | "asr_upstream" | "asr_timeout";export class AsrError extends Error {constructor(@@ -211,7 +218,11 @@ export async function transcribe(req: AsrRequest): Promise<string> {const deadline = Date.now() + OVERALL_SLACK_MS + durationMs(req.pcm.length, req.sampleRate);try {- await frames.opened(HANDSHAKE_TIMEOUT_MS);+ try {+ await frames.opened(HANDSHAKE_TIMEOUT_MS);+ } catch (err) {+ throw err instanceof AsrError ? await explainHandshake(err, req) : err;+ }// 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();@@ -253,6 +264,82 @@ export async function transcribe(req: AsrRequest): Promise<string> {}}+/**+ * How much silence a connectivity check plays: half a second at 16 kHz mono PCM16. Not none —+ * `finish-task` on a task that never carried audio is a shape the protocol does not document,+ * and this is short enough to be free while still being a whole request end to end.+ */+const PROBE_BYTES = ASR_SAMPLE_RATE;++/** What a connectivity check found. */+export interface AsrProbe {+ /** Whether the configured site answered a whole task with this model and key. */+ ok: boolean;+ /** The provider's own words when it refused, this product's sentence when it was unreachable; empty when ok. */+ message: string;+}++/**+ * Ask the configured service whether it will take this site, this model and this key: one task,+ * opened and finished, over half a second of silence. It is the call a recording makes minus the+ * recording, so what it proves is what pressing the microphone proves — `ok` means the next+ * utterance reaches a service that answers it.+ *+ * A refusal is an ANSWER, not a failure of the check: everything comes back as `ok: false`+ * carrying the sentence the provider sent, which is what the settings page puts in front of the+ * operator. Only a bug inside this file throws.+ */+export async function probeAsr(req: Omit<AsrRequest, "pcm" | "sampleRate">): Promise<AsrProbe> {+ try {+ await transcribe({ ...req, pcm: new Uint8Array(PROBE_BYTES), sampleRate: ASR_SAMPLE_RATE });+ return { ok: true, message: "" };+ } catch (err) {+ if (err instanceof AsrError) return { ok: false, message: err.message };+ throw err;+ }+}++/**+ * A handshake that never completed, explained.+ *+ * The transport cannot say WHY: undici's WebSocket reports a refused credential, a path that is+ * not the endpoint and a host that does not exist with the same bare `TypeError` and the same+ * close code, so all three used to arrive as "could not reach" — and an operator sent to look at+ * the network for a key that is simply wrong. The two are told apart by asking the same address+ * once over HTTP with the same credential, which a service that is there answers at once (the+ * path wants an upgrade, so a working credential reads 4xx and a refused one reads 401).+ *+ * When even that request cannot be made, the socket's own sentence stands: nothing is there to+ * ask. Only a handshake failure is explained this way — a socket that dies mid-task is not a+ * configuration problem and keeps its own name.+ */+async function explainHandshake(err: AsrError, req: AsrRequest): Promise<AsrError> {+ if (err.code !== "asr_unreachable") return err;+ let status: number;+ try {+ const res = await fetch(asrWebSocketUrl(req.baseUrl).replace(/^ws/, "http"), {+ headers: { Authorization: `Bearer ${req.apiKey}` },+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ status = res.status;+ await res.text();+ } catch {+ return err;+ }+ if (status === 401 || status === 403) {+ return new AsrError(+ "asr_credential_refused",+ `The speech service refused the credential (HTTP ${status}).`,+ 502,+ );+ }+ return new AsrError(+ "asr_unreachable",+ `The speech service answered HTTP ${status} instead of upgrading the connection.`,+ 502,+ );+}+/*** Wait for `task-started`. A `task-failed` before it — the shape an auth refusal takes — is* reported as it came.diff --git a/packages/server/test/asr.test.ts b/packages/server/test/asr.test.tsindex f2c5d8fe..303d8d29 100644--- a/packages/server/test/asr.test.ts+++ b/packages/server/test/asr.test.ts@@ -18,7 +18,13 @@* 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.+ * connection is a 502 named `asr_unreachable`, not a refusal by the provider. A handshake that+ * never completes is explained by asking the same address once over HTTP, so a refused+ * credential (401) is named as such and any other answer is reported with its status.+ * - The connectivity check (POST /api/asr/test) runs the same task against the fields the form+ * holds — stored ones when it omits them — and writes none of them; a service that refuses or+ * cannot be reached comes back 200 with `ok: false` and the sentence explaining why, while a+ * field it cannot resolve, or no key anywhere, is a 400.* - An empty, non-PCM or over-long body is refused with its own code.*/import { createServer } from "node:http";@@ -26,7 +32,12 @@ 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 type {+ AsrConfig,+ AsrConfigResponse,+ AsrTestResponse,+ AsrTranscribeResponse,+} from "../src/api/types.js";import {ASR_MAX_BYTES,BAILIAN_WS_PATH,@@ -150,6 +161,25 @@ async function startFakeUpstream(/** 100 ms of silence at 16 kHz mono PCM16 — a body the route accepts. */const ONE_FRAME = new Uint8Array(3200);+/**+ * A site that answers every request with one HTTP status and never upgrades: what a service looks+ * like when the credential is wrong, and what the diagnostic behind a failed handshake asks. The+ * WebSocket layer reports this the same way it reports a host that does not exist, so the HTTP+ * answer is the only thing that tells the two apart.+ */+async function startHttpRefuser(status: number): Promise<{ url: string; close(): Promise<void> }> {+ const http: HttpServer = createServer((_req, res) => {+ res.writeHead(status, { "content-type": "text/plain" });+ res.end("no");+ });+ 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}`,+ close: () => new Promise<void>((resolve) => http.close(() => resolve())),+ };+}+describe("speech input", () => {let t: TestApp;let admin: ReturnType<typeof apiClient>;@@ -182,6 +212,7 @@ describe("speech input", () => {return ((await res.json()) as AsrConfigResponse).config;};const putConfig = (body: unknown, client = admin) => client.put("/api/asr/config", body);+ const testConfig = (body: unknown, client = admin) => client.post("/api/asr/test", body);const errorCode = async (res: Response) =>((await res.json()) as { error: { code: string; message: string } }).error;@@ -314,6 +345,116 @@ describe("speech input", () => {expect((await errorCode(res)).code).toBe("asr_unreachable");});+ it("names a refused credential as such, rather than blaming the network", async () => {+ const refusing = await startHttpRefuser(401);+ await putConfig({ baseUrl: refusing.url, model: "m", apiKey: "sk-wrong" });++ const res = await transcribe("admin");+ expect(res.status).toBe(502);+ const err = await errorCode(res);+ expect(err.code).toBe("asr_credential_refused");+ expect(err.message).toContain("401");+ await refusing.close();+ });++ it("reports a site that answers the upgrade with something else, status and all", async () => {+ const plain = await startHttpRefuser(200);+ await putConfig({ baseUrl: plain.url, model: "m", apiKey: "sk-test-key" });++ const res = await transcribe("admin");+ expect(res.status).toBe(502);+ const err = await errorCode(res);+ expect(err.code).toBe("asr_unreachable");+ expect(err.message).toContain("HTTP 200");+ await plain.close();+ });++ it("checks the fields the form holds, before they are saved, and writes none of them", async () => {+ upstream = await startFakeUpstream({ sentences: [] });+ const res = await testConfig({+ baseUrl: upstream.url,+ model: "draft-model",+ apiKey: "sk-draft",+ });+ expect(res.status).toBe(200);+ const body = (await res.json()) as AsrTestResponse;+ expect(body.ok).toBe(true);+ expect(body.message).toBe("");+ // The endpoint reported says which of the two sites this address resolved to.+ expect(body.endpoint).toBe(+ `${upstream.url.replace(/^http/, "ws")}/gateway/alibaba/api-ws/v1/inference`,+ );+ // The form's fields reached the provider, as a whole task from run-task to finish-task…+ expect(upstream.seen.authorization).toBe("Bearer sk-draft");+ expect(upstream.seen.runTask?.payload.model).toBe("draft-model");+ expect(upstream.seen.finished).toBe(true);+ // …and none of them were stored.+ expect(await getConfig()).toEqual({+ baseUrl: DEFAULT_ASR_BASE_URL,+ model: DEFAULT_ASR_MODEL,+ hasKey: false,+ });+ });++ it("falls back to the stored site, model and key when the check omits them", async () => {+ upstream = await startFakeUpstream({ sentences: [] });+ await putConfig({ baseUrl: upstream.url, model: "stored-model", apiKey: "sk-stored" });++ const res = await testConfig({});+ expect(res.status).toBe(200);+ expect(((await res.json()) as AsrTestResponse).ok).toBe(true);+ expect(upstream.seen.authorization).toBe("Bearer sk-stored");+ expect(upstream.seen.runTask?.payload.model).toBe("stored-model");+ });++ it("answers a refusing service as not ok, in the service's own words, and a dead one by name", async () => {+ upstream = await startFakeUpstream({+ fail: {+ code: "Arrearage",+ message: "Access denied, please make sure your account is in good standing.",+ },+ });+ const refused = await testConfig({ baseUrl: upstream.url, model: "m", apiKey: "sk-x" });+ // 200: the check ran. What it found is the body.+ expect(refused.status).toBe(200);+ const body = (await refused.json()) as AsrTestResponse;+ expect(body.ok).toBe(false);+ expect(body.message).toContain("in good standing");+ await upstream.close();+ upstream = null;++ // Nothing listening: the check names the transport rather than inventing a refusal.+ const dead = await testConfig({ baseUrl: "http://127.0.0.1:1", model: "m", apiKey: "sk-x" });+ expect(dead.status).toBe(200);+ const deadBody = (await dead.json()) as AsrTestResponse;+ expect(deadBody.ok).toBe(false);+ expect(deadBody.message).toContain("Could not reach");+ });++ it("refuses a check it cannot resolve, and one with no key anywhere, without opening a socket", async () => {+ const bad = await testConfig({ baseUrl: "not a url", apiKey: "sk-x" });+ expect(bad.status).toBe(400);+ expect((await errorCode(bad)).code).toBe("invalid_asr_base_url");++ const keyless = await testConfig({});+ expect(keyless.status).toBe(400);+ expect((await errorCode(keyless)).code).toBe("asr_not_configured");+ });++ it("tells a wrong key from a site that is not there in the check too", async () => {+ const refusing = await startHttpRefuser(401);+ const res = await testConfig({ baseUrl: refusing.url, model: "m", apiKey: "sk-wrong" });+ expect(res.status).toBe(200);+ const body = (await res.json()) as AsrTestResponse;+ expect(body.ok).toBe(false);+ expect(body.message).toContain("401");+ await refusing.close();+ });++ it("keeps the connectivity check to admins", async () => {+ expect((await testConfig({}, user)).status).toBe(403);+ });+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" });diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 47a5567d..fa6a3111 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -33,6 +33,8 @@ import type {ApprovalDecisionRequest,AsrConfigResponse,AsrConfigUpdateRequest,+ AsrTestRequest,+ AsrTestResponse,AsrTranscribeRequest,AsrTranscribeResponse,AuthLoginRequest,@@ -349,6 +351,14 @@ export const getAsrConfig = () => apiFetch<AsrConfigResponse>("/api/asr/config")export const putAsrConfig = (body: AsrConfigUpdateRequest) =>apiFetch<AsrConfigResponse>("/api/asr/config", { method: "PUT", body });+/**+ * Asks the configured service whether it will take this site, this model and this key: one whole+ * task with no audio in it. An omitted field falls back to what is stored, so a check may be run+ * on a form that has not been saved. `ok: false` is the check's answer, not a failed request.+ */+export const testAsrConfig = (body: AsrTestRequest) =>+ apiFetch<AsrTestResponse>("/api/asr/test", { method: "POST", 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.diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex b710dcb6..35cb5641 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -2492,7 +2492,7 @@ export function ChatInput({{dictation.notice !== null && (<prole="alert"- data-tooltip={dictation.notice.text}+ data-tooltip={dictation.notice.detail ?? 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"diff --git a/packages/web/src/features/chat/use-asr-recorder.ts b/packages/web/src/features/chat/use-asr-recorder.tsindex 5baeee17..6c382cc5 100644--- a/packages/web/src/features/chat/use-asr-recorder.ts+++ b/packages/web/src/features/chat/use-asr-recorder.ts@@ -8,9 +8,10 @@** 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.+ * - On an origin it does not consider secure the microphone is not refused, it is ABSENT: the+ * page has no `navigator.mediaDevices`, so no prompt appears and no permission can be+ * granted. lib/mic-access.ts tells that case apart from a denial, a missing device and a busy+ * one — four sentences, and only one of them is the user's to undo.* - 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.@@ -18,6 +19,8 @@import { useCallback, useEffect, useRef, useState } from "react";import * as api from "../../api/endpoints";import { ASR_SAMPLE_RATE, encodeBase64, toAsrPcm } from "../../lib/asr-audio";+import { microphoneObstacle, microphoneRefusal } from "../../lib/mic-access";+import type { MicrophoneRefusal } from "../../lib/mic-access";import { refusalText } from "../../lib/api-error";import { S } from "../../lib/strings";@@ -31,6 +34,11 @@ export type DictationState = "idle" | "recording" | "transcribing";*/export interface DictationNotice {text: string;+ /**+ * The long version, shown on hover. Set where the one-line text can only name the obstacle and+ * the way out does not fit — an insecure origin, whose three fixes are a paragraph.+ */+ detail?: string;failed: boolean;}@@ -78,11 +86,30 @@ export function useDictation(onTranscript: (text: string) => void): Dictation {const start = useCallback(() => {void (async () => {+ // Asked before anything is asked for: on a page without a microphone the browser would not+ // even show a permission prompt, so "grant it" is advice the user cannot act on. What they+ // can act on is the address — hence the paragraph on hover.+ const obstacle = microphoneObstacle({+ isSecureContext: window.isSecureContext,+ mediaDevices: navigator.mediaDevices,+ });+ if (obstacle === "insecure") {+ setNotice({+ text: S.chat.dictateInsecure,+ detail: S.chat.dictateInsecureHelp,+ failed: true,+ });+ return;+ }+ if (obstacle === "unsupported") {+ setNotice({ text: S.chat.dictateUnsupported, failed: true });+ return;+ }let stream: MediaStream;try {stream = await navigator.mediaDevices.getUserMedia({ audio: true });- } catch {- setNotice({ text: S.chat.dictateUnavailable, failed: true });+ } catch (e) {+ setNotice({ text: refusalNotice(microphoneRefusal(e)), failed: true });return;}const recorder = new MediaRecorder(stream);@@ -118,6 +145,20 @@ export function useDictation(onTranscript: (text: string) => void): Dictation {return { state, notice, clearNotice, toggle };}+/** What a refused `getUserMedia` is worth saying, by what the browser called the refusal. */+function refusalNotice(refusal: MicrophoneRefusal): string {+ switch (refusal) {+ case "denied":+ return S.chat.dictateDenied;+ case "missing":+ return S.chat.dictateNoDevice;+ case "busy":+ return S.chat.dictateBusy;+ case "other":+ return S.chat.dictateUnavailable;+ }+}+/** 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();diff --git a/packages/web/src/features/settings/asr-section.tsx b/packages/web/src/features/settings/asr-section.tsxindex 348a4f4f..a9465f36 100644--- a/packages/web/src/features/settings/asr-section.tsx+++ b/packages/web/src/features/settings/asr-section.tsx@@ -12,11 +12,15 @@* 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.+ * Saving takes effect on the next recording; there is nothing to restart and nothing to warm up.+ * What a save cannot tell the operator is whether the site, the model and the key are any good,+ * and the microphone is a slow way to find out — so "Test connection" runs the same task a+ * recording runs, over silence, against the fields ON SCREEN rather than the stored ones (saving+ * a key just to learn whether it works is the wrong order), and a save follows itself with one so+ * a configuration that cannot connect is never left looking finished.*/import { useCallback, useEffect, useState } from "react";-import type { AsrConfig } from "@adelie/server/api";+import type { AsrConfig, AsrTestResponse } from "@adelie/server/api";import {Button,Input,@@ -43,11 +47,14 @@ export function AsrSection() {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 last save or check was refused for another reason, drawn above the Save row. */+ const [refusal, setRefusal] = 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);+ /** The last connectivity check's answer, drawn under the key's state; cleared by an edit. */+ const [check, setCheck] = useState<AsrTestResponse | null>(null);const [busy, setBusy] = useState(false);+ const [testing, setTesting] = useState(false);/** Adopt server-side truth: the baseline and the drafts move together. */const adopt = useCallback((next: AsrConfig) => {@@ -57,8 +64,9 @@ export function AsrSection() {// Never populated: the value is write-only, so the field is for a new key alone.setApiKey("");setFieldError(null);- setSaveRefusal(null);+ setRefusal(null);setLoadRefusal(null);+ setCheck(null);}, []);useEffect(() => {@@ -76,55 +84,117 @@ export function AsrSection() {};}, [adopt]);+ /** The fields as one body: the typed key only when there is one, an empty box meaning "stored". */+ const fields = () => ({+ baseUrl: baseUrl.trim(),+ model: model.trim(),+ ...(apiKey.trim() !== "" ? { apiKey: apiKey.trim() } : {}),+ });++ /** A refusal both verbs share: the offending field, or the line above the buttons. */+ const showRefusal = (e: unknown): void => {+ const code = e instanceof ApiError ? e.code : "";+ const text = apiErrorText(e);+ // Anything else (a lost session, a dead server) wrote nothing, so the form and the sentence+ // agree and the button is the retry.+ 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 });+ else setRefusal(text);+ };++ /**+ * Ask the service whether it will take what is on screen. `ok: false` comes back as a result+ * rather than as a failure — the check ran, and what it found is the provider's own sentence.+ */+ const runCheck = async () => {+ if (stored === null) return;+ setTesting(true);+ setFieldError(null);+ setRefusal(null);+ setCheck(null);+ try {+ setCheck(await api.testAsrConfig(fields()));+ } catch (e: unknown) {+ showRefusal(e);+ if (!(e instanceof ApiError)) toastError(apiErrorText(e));+ } finally {+ setTesting(false);+ }+ };+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 === "") {+ const next = fields();+ if (+ next.baseUrl === stored.baseUrl &&+ next.model === stored.model &&+ next.apiKey === undefined+ ) {toastInfo(S.common.noChangesToSave);return;}setBusy(true);setFieldError(null);- setSaveRefusal(null);+ setRefusal(null);try {const res = await api.putAsrConfig({- baseUrl: nextBaseUrl,- model: nextModel,+ baseUrl: next.baseUrl,+ model: next.model,// 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 } : {}),+ ...(next.apiKey !== undefined ? { apiKey: next.apiKey } : {}),});adopt(res.config);toastSuccess(S.common.saved);+ // A saved configuration that cannot connect is the state worth catching here rather than+ // at the first recording; the fields have not changed, so this checks what was just stored.+ void runCheck();} 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);+ showRefusal(e);+ if (!(e instanceof ApiError)) toastError(apiErrorText(e));} finally {setBusy(false);}};+ /** The edit this field invalidates: its own error, and any verdict on the fields as a whole. */+ const edited = (clear: () => void) => {+ clear();+ if (fieldError !== null) setFieldError(null);+ if (check !== null) setCheck(null);+ };+const hydrated = stored !== null;+ const checkText =+ check === null+ ? ""+ : check.ok+ ? S.settings.speechTestOk(check.endpoint)+ : S.settings.speechTestFailed(check.endpoint) + check.message;return (<SettingsSectionactions={- <Button- size="sm"- variant="primary"- disabled={!hydrated || busy}- onClick={() => void save()}- >- {S.common.save}- </Button>+ <>+ <Button+ size="sm"+ variant="secondary"+ disabled={!hydrated || busy || testing}+ loading={testing}+ loadingLabel={S.settings.speechTestRunning}+ onClick={() => void runCheck()}+ >+ {S.settings.speechTest}+ </Button>+ <Button+ size="sm"+ variant="primary"+ disabled={!hydrated || busy || testing}+ onClick={() => void save()}+ >+ {S.common.save}+ </Button>+ </>}>{loadRefusal !== null && (@@ -148,10 +218,7 @@ export function AsrSection() {value={baseUrl}disabled={!hydrated}{...(fieldError?.field === "baseUrl" ? { error: fieldError.text } : {})}- onChange={(e) => {- setBaseUrl(e.target.value);- if (fieldError !== null) setFieldError(null);- }}+ onChange={(e) => edited(() => setBaseUrl(e.target.value))}/><Inputlabel={S.settings.speechModel}@@ -162,10 +229,7 @@ export function AsrSection() {value={model}disabled={!hydrated}{...(fieldError?.field === "model" ? { error: fieldError.text } : {})}- onChange={(e) => {- setModel(e.target.value);- if (fieldError !== null) setFieldError(null);- }}+ onChange={(e) => edited(() => setModel(e.target.value))}/><PasswordInputlabel={S.settings.speechApiKey}@@ -175,10 +239,7 @@ export function AsrSection() {value={apiKey}disabled={!hydrated}{...(fieldError?.field === "apiKey" ? { error: fieldError.text } : {})}- onChange={(e) => {- setApiKey(e.target.value);- if (fieldError !== null) setFieldError(null);- }}+ onChange={(e) => edited(() => setApiKey(e.target.value))}/>{/* Whether a key is stored is the one thing this field cannot show: it is always emptyabove, by design. Without this line a configured server looks unconfigured. */}@@ -187,14 +248,29 @@ export function AsrSection() {{stored.hasKey ? S.settings.speechKeyStored : S.settings.speechKeyMissing}</p>)}- {saveRefusal !== null && (+ {/* What the last check found, under the state it is about. The failure carries the+ provider's own sentence — nothing here translates it, because it names what is wrong+ at the provider (a key, a model, an account in arrears) and that is where it is fixed. */}+ {check !== null && (+ <p+ {...(check.ok ? {} : { role: "alert" })}+ data-tooltip={checkText}+ data-tooltip-content="text"+ className={`line-clamp-2 break-words text-xs ${+ check.ok ? "text-fg-muted" : toneInk.danger+ }`}+ >+ {checkText}+ </p>+ )}+ {refusal !== null && (<prole="alert"- data-tooltip={saveRefusal}+ data-tooltip={refusal}data-tooltip-content="text"className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}>- {saveRefusal}+ {refusal}</p>)}</SettingsSection>diff --git a/packages/web/src/lib/mic-access.ts b/packages/web/src/lib/mic-access.tsnew file mode 100644index 00000000..1d347839--- /dev/null+++ b/packages/web/src/lib/mic-access.ts@@ -0,0 +1,55 @@+/**+ * Whether the composer's microphone can be opened at all, and — when it cannot — which of the+ * three ways it was closed. The distinction is the whole point: only one of the three is about+ * permission, and telling a user to grant a permission the browser never offered is a dead end.+ *+ * The first two are decided BEFORE anything is asked, because on those two nothing is ever asked:+ *+ * - The page may sit on an origin the browser does not treat as secure. There `navigator.+ * mediaDevices` does not exist — not "was refused", does not exist — so no prompt is shown+ * and none can be granted. A plain `http://` address that is not `localhost` is that case, and+ * it is the one users hit: the desktop App's own window runs on `http://localhost:<port>` and+ * is fine, while the same server opened at `http://10.0.0.5:7777` in a browser is not.+ * - Otherwise the browser may simply have no capture support.+ *+ * What is left is asked for with `getUserMedia`, and its refusal is named by+ * {@link microphoneRefusal}. Neither function reaches for a browser global, so both are testable+ * without one.+ */++/** Why the microphone cannot be asked for at all, decided before anything is asked. */+export type MicrophoneObstacle = "insecure" | "unsupported";++/** The slice of the page that decides it. */+export interface MicrophoneEnvironment {+ isSecureContext: boolean;+ mediaDevices?: { getUserMedia?: unknown } | undefined;+}++/**+ * The obstacle in the way, or null when the microphone may be asked for. An insecure origin is+ * named as such even if it somehow exposes `mediaDevices`: the address is what would refuse the+ * request, so that is what the notice has to say.+ */+export function microphoneObstacle(env: MicrophoneEnvironment): MicrophoneObstacle | null {+ if (!env.isSecureContext) return "insecure";+ if (typeof env.mediaDevices?.getUserMedia !== "function") return "unsupported";+ return null;+}++/** What a refused `getUserMedia` was refused for, as far as the browser's error name says. */+export type MicrophoneRefusal = "denied" | "missing" | "busy" | "other";++/**+ * The refusal, in the terms the notice can act on: `denied` is the user's to undo (in the address+ * bar, not here), `missing` means no device, `busy` another program holding it. Anything else —+ * including a non-Error rejection, which some browsers produce — is `other`, which is where a+ * guess would otherwise go.+ */+export function microphoneRefusal(error: unknown): MicrophoneRefusal {+ const name = error instanceof Error ? error.name : "";+ if (name === "NotAllowedError" || name === "SecurityError") return "denied";+ if (name === "NotFoundError" || name === "OverconstrainedError") return "missing";+ if (name === "NotReadableError" || name === "AbortError") return "busy";+ return "other";+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e109b978..a05711fa 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -787,6 +787,18 @@ export const en: Strings = {/** 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 connectivity check: one whole task against the site, so an operator learns before+ * recording that the key, the site or the model is wrong. It checks what is on screen rather+ * than what is stored — saving a key just to find out whether it works is the wrong order —+ * and both sentences name the endpoint, because the one thing invisible in the fields is+ * which of the two paths a site address resolves to.+ */+ speechTest: "Test connection",+ speechTestRunning: "Testing…",+ speechTestOk: (endpoint: string): string => `Reachable, at ${endpoint}`,+ /** Followed by the service's own sentence, untranslated. */+ speechTestFailed: (endpoint: string): string => `Not reachable, at ${endpoint}: `,/** 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. */@@ -3992,9 +4004,31 @@ export const en: Strings = {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.",+ /**+ * The microphone could not be asked for at all. The browser exposes one only on an origin it+ * calls secure, and an http address that is not localhost is not one — so this is not a+ * permission the user can go and grant, and the line says so rather than sending them off to+ * look for a prompt that will never appear. `dictateInsecureHelp` is the way out, on hover.+ */+ dictateInsecure:+ "This address has no microphone: the browser only offers one on https or localhost.",+ dictateInsecureHelp:+ "A browser treats an http address that is not localhost as an insecure context, and there " ++ "navigator.mediaDevices does not exist at all — you are not being asked for permission, " ++ "you would never even be prompted. Three ways out: (1) use the Adelie desktop app, which " ++ "runs on localhost; (2) put Adelie behind https; (3) temporarily add this address to " ++ "chrome://flags/#unsafely-treat-insecure-origin-as-secure and restart the browser.",+ /** This browser has no capture support at all. */+ dictateUnsupported: "This browser cannot record from a microphone.",+ /** Denied earlier: undoing that is a click in the address bar, not in this page. */+ dictateDenied:+ "Microphone access is set to Block: choose Allow from the icon in the address bar, then try again.",+ /** No capture device on this machine. */+ dictateNoDevice: "No microphone was found on this machine.",+ /** A device exists but another program is holding it. */+ dictateBusy: "Another program is using the microphone — close it and try again.",+ /** The catch-all: a refusal this product has no name for, said without blaming the user. */+ dictateUnavailable: "The microphone could not be used — please try again.",removeFile: "Remove file",attachmentTooLarge: (name: string, limitMb: number): string =>`${name} exceeds the ${limitMb}MB limit and was not attached.`,@@ -5824,6 +5858,8 @@ export const en: Strings = {"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_credential_refused:+ "The speech service refused this key: check the API key under Settings → Server → Speech input, then run Test connection.",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.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 825d4da9..b52b79e8 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -848,6 +848,18 @@ export const zh = {/** The two states of the stored key, shown beside the key field. */speechKeyStored: "已保存密钥",speechKeyMissing: "尚未保存密钥,语音输入暂不可用",+ /**+ * The connectivity check: one whole task against the site, so an operator learns before+ * recording that the key, the site or the model is wrong. It checks what is on screen rather+ * than what is stored — saving a key just to find out whether it works is the wrong order —+ * and both sentences name the endpoint, because the one thing invisible in the fields is+ * which of the two paths a site address resolves to.+ */+ speechTest: "测试连通性",+ speechTestRunning: "正在测试…",+ speechTestOk: (endpoint: string): string => `连通正常,用的是 ${endpoint}`,+ /** Followed by the service's own sentence, untranslated. */+ speechTestFailed: (endpoint: string): string => `连不通,用的是 ${endpoint}:`,/** The fold holding the fields a settings group marks advanced. */pluginAdvanced: "高级选项",/** A table cell its row does not let change, beside the lock mark. */@@ -4065,8 +4077,29 @@ export const zh = {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: "无法使用麦克风:请检查浏览器或系统的麦克风权限。",+ /**+ * The microphone could not be asked for at all. The browser exposes one only on an origin it+ * calls secure, and an http address that is not localhost is not one — so this is not a+ * permission the user can go and grant, and the line says so rather than sending them off to+ * look for a prompt that will never appear. `dictateInsecureHelp` is the way out, on hover.+ */+ dictateInsecure:+ "这个地址(http 的非本机地址)拿不到麦克风:浏览器只在 https 或 localhost 下才给。",+ dictateInsecureHelp:+ "浏览器把 http 的非本机地址当作「不安全上下文」,在那里 navigator.mediaDevices 根本不存在——" ++ "不是你没授权,是它连权限框都不会弹。三条出路:① 用桌面版 Adelie,它跑在 localhost 上;" ++ "② 让 Adelie 走 https;③ 临时把这个地址加进 " ++ "chrome://flags/#unsafely-treat-insecure-origin-as-secure,重启浏览器后生效。",+ /** This browser has no capture support at all. */+ dictateUnsupported: "这个浏览器不支持网页录音,换一个浏览器再试。",+ /** Denied earlier: undoing that is a click in the address bar, not in this page. */+ dictateDenied: "浏览器里的麦克风权限是「拒绝」:点地址栏左边的图标改成「允许」,再点一次。",+ /** No capture device on this machine. */+ dictateNoDevice: "没有找到可用的麦克风设备。",+ /** A device exists but another program is holding it. */+ dictateBusy: "麦克风被别的程序占着,关掉那个程序再试。",+ /** The catch-all: a refusal this product has no name for, said without blaming the user. */+ dictateUnavailable: "无法使用麦克风,请再试一次。",removeFile: "移除文件",/*** Toast for a picked file rejected before reading. The limit is admin-settable and differs@@ -5860,6 +5893,8 @@ export const zh = {image_too_large: "图片过大,无法随对话发送。",asr_not_configured: "还没有配置语音识别模型,请在「设置 → 服务器 → 语音输入」里配置。",asr_unreachable: "连不上语音服务,请检查设置里的服务地址与网络。",+ asr_credential_refused:+ "语音服务不认这把密钥:到「设置 → 服务器 → 语音输入」检查 API 密钥,改完点「测试连通性」。",asr_timeout: "语音服务没有及时返回结果,请再试一次。",asr_empty_audio: "没有录到声音,请再试一次。",asr_too_long: "录音太长了,请说得短一点。",diff --git a/packages/web/test/mic-access.test.ts b/packages/web/test/mic-access.test.tsnew file mode 100644index 00000000..c2257ae2--- /dev/null+++ b/packages/web/test/mic-access.test.ts@@ -0,0 +1,65 @@+/**+ * Which of the three ways the microphone is closed, decided from what the page looks like and+ * what the browser's refusal is called. The cases are the ones the notices differ on, and the+ * one that matters most is first: an http address that is not `localhost` has no+ * `navigator.mediaDevices` at all, so it is not a permission the user can grant.+ */+import { describe, expect, it } from "vitest";+import { microphoneObstacle, microphoneRefusal } from "../src/lib/mic-access";++describe("microphoneObstacle", () => {+ it("names an insecure origin, where no microphone is exposed and no prompt is ever shown", () => {+ // Exactly what a browser reports on `http://10.0.0.5:7777` — see the live probe in+ // `deploy/`'s notes: mediaDevices is undefined, not merely refused.+ expect(microphoneObstacle({ isSecureContext: false, mediaDevices: undefined })).toBe(+ "insecure",+ );+ });++ it("still names the origin when an insecure page somehow exposes capture", () => {+ expect(+ microphoneObstacle({+ isSecureContext: false,+ mediaDevices: { getUserMedia: () => Promise.resolve() },+ }),+ ).toBe("insecure");+ });++ it("names a secure page whose browser has no capture support", () => {+ expect(microphoneObstacle({ isSecureContext: true, mediaDevices: undefined })).toBe(+ "unsupported",+ );+ expect(microphoneObstacle({ isSecureContext: true, mediaDevices: {} })).toBe("unsupported");+ });++ it("gets out of the way on a secure page that can capture", () => {+ expect(+ microphoneObstacle({+ isSecureContext: true,+ mediaDevices: { getUserMedia: () => Promise.resolve() },+ }),+ ).toBe(null);+ });+});++describe("microphoneRefusal", () => {+ const named = (name: string): Error => Object.assign(new Error(name), { name });++ it("reads a refusal as the user's to undo, and a device problem as the device's", () => {+ expect(microphoneRefusal(named("NotAllowedError"))).toBe("denied");+ expect(microphoneRefusal(named("NotFoundError"))).toBe("missing");+ expect(microphoneRefusal(named("NotReadableError"))).toBe("busy");+ });++ it("reads the alternative names browsers use for the same two situations", () => {+ expect(microphoneRefusal(named("SecurityError"))).toBe("denied");+ expect(microphoneRefusal(named("OverconstrainedError"))).toBe("missing");+ expect(microphoneRefusal(named("AbortError"))).toBe("busy");+ });++ it("falls back rather than guessing when the rejection is not a named error", () => {+ expect(microphoneRefusal(new Error("boom"))).toBe("other");+ expect(microphoneRefusal(undefined)).toBe("other");+ expect(microphoneRefusal("nope")).toBe("other");+ });+});