Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Dictation: GET/POST /api/spaces/:id/transcribe (server half) (#610)
Oleksandr Ivanchenkoc597888842cc
diff --git a/docs/dictation.md b/docs/dictation.mdnew file mode 100644index 00000000..2ebf2390--- /dev/null+++ b/docs/dictation.md@@ -0,0 +1,98 @@+# Dictation++The message box's mic button records the person's voice and turns it into text in the text box,+where they read and edit it. Nothing reaches a bot before they press Send, and nothing is stored:+the recording stays in memory for the one call, with no attachment, file, chat message or memory.++The words come from the space's own OpenAI account, in this order (the same as hybrid recall's+embeddings, minus Ollama, which has no speech-to-text):++1. An enabled OpenAI API-key account of the space (an `api_key` profile on Codex) with a key.+2. The host's OpenAI key (Settings, else `OPENAI_API_KEY`), unless This machine is off for Codex+ in the space.++Neither is used while the OpenAI API engine is turned off. OpenAI's+`POST /v1/audio/transcriptions` gets the recording with the model `gpt-4o-mini-transcribe`, and+`whisper-1` if OpenAI says the first doesn't exist for the key. Local Whisper isn't supported yet.++## `GET /api/spaces/:id/transcribe`++Whether the mic button can work in this space. Reads only the database: no network call.++```json+{"available": true, "source": "openai", "why": null}+```++```json+{"available": false, "source": null, "why": "Add an OpenAI API key in Apps & accounts to dictate."}+```++`why` is one of:++- `Add an OpenAI API key in Apps & accounts to dictate.`+- `This machine is turned off for OpenAI in this space, so its key isn't used. Add an OpenAI API key to this space in Apps & accounts to dictate.`+- `The OpenAI API is turned off in Apps & accounts. Turn it on to dictate.`++404 `{"error": "no such space", "code": "no_space"}` for an unknown space.++## `POST /api/spaces/:id/transcribe[?lang=xx]`++The recording is the raw body. `Content-Type` is `audio/webm`, `audio/mp4`, `audio/mpeg`,+`audio/wav` or `audio/ogg` (also `audio/x-m4a`, `audio/m4a`, `audio/mp3`, `audio/x-wav`,+`audio/wave`); parameters such as `;codecs=opus` are fine. `lang` is an optional two-letter+ISO-639-1 hint (`en`, `de`). At most 25 MB.++```+POST /api/spaces/spc_default/transcribe?lang=en+Content-Type: audio/webm;codecs=opus++<recording bytes>+```++200:++```json+{"text": "Book a table for four on Friday at seven.", "source": "openai"}+```++Only the person can dictate: a bot's turn token gets 403. At most 2 recordings go to OpenAI at a+time; one more waits up to 30 s for its turn.++Every refusal is `{"error": "<a sentence for the person>", "code": "<code>"}`; 409+`no_transcriber` also has `why`. In the order they are checked:++| Status | `code` | `error` |+|---|---|---|+| 403 | none | `only the person can dictate` |+| 404 | none | `no such space` |+| 409 | none | the space is archived |+| 413 | `too_large` | `The recording is over 25 MB. Record a shorter message.` (a declared `Content-Length` over 25 MB, before any byte is read) |+| 415 | `bad_audio_type` | `Send the recording as audio/webm, audio/mp4, audio/mpeg, audio/wav or audio/ogg.` |+| 400 | `bad_lang` | `lang must be a two-letter language code such as en.` |+| 409 | `no_transcriber` | the `why` from GET, also as `why` |+| 400 | `interrupted` | `The recording was interrupted.` |+| 413 | `too_large` | as above, at the byte that passes 25 MB |+| 400 | `empty_audio` | `The recording is empty.` |+| 429 | `busy` | `Other recordings are being turned into text. Try again in a moment.` |+| 502 | `transcriber_failed` | one of the reasons below |++502 reasons (OpenAI's own error text is never passed on, since its 401 quotes part of the key):++- `The OpenAI key was refused.` (401, 403)+- `OpenAI is limiting this key, or its quota is used up. Try again in a minute.` (429)+- `The recording is too large for OpenAI.` (413)+- `OpenAI couldn't read this recording.` (400, 404, 415, 422)+- `OpenAI had a problem. Try again in a minute.` (other statuses)+- `OpenAI didn't answer within 60 seconds.`+- `OpenAI couldn't be reached.`+- `OpenAI's answer couldn't be read.`++The key never appears in an answer or a log line. The log has one line per recording+(`dictation transcribed` or `dictation failed`, with the space, size, model or reason). When+OpenAI can't be reached, one more line has the connection error, without its address.++## Tests++`KWNT_OPENAI_API_BASE` points dictation at another OpenAI address, only in builds with the+`test-seams` feature (as `cargo test` builds). `tests/transcribe_test.rs` uses a stub server; no+test calls the real API.diff --git a/src/server/mod.rs b/src/server/mod.rsindex d497c09b..dfa5b292 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -47,6 +47,7 @@ pub mod mcp_suggest;pub mod page_source;pub mod tool_failures;pub mod tool_notes;+pub mod transcribe;pub mod connection_suggest;pub mod bot_actions;pub mod hires;@@ -465,6 +466,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/hires/:id/accept", post(hires::accept_route)).route("/api/hires/:id/deny", post(hires::deny_route)).route("/api/spaces/:id/hire-policy", get(hires::get_policy).put(hires::put_policy))+ .route("/api/spaces/:id/transcribe", get(transcribe::status).post(transcribe::transcribe)).route("/api/channels/:id", get(continuity::get_channel).patch(continuity::patch_channel)).route("/api/search", get(continuity::search)).route("/api/kwants/:id/memories", get(continuity::list_memories).post(continuity::add_memory))diff --git a/src/server/transcribe.rs b/src/server/transcribe.rsnew file mode 100644index 00000000..591ab664--- /dev/null+++ b/src/server/transcribe.rs@@ -0,0 +1,482 @@+//! Dictation (roadmap Next 12b): the message box's mic button sends its recording here and gets+//! the spoken words back as text, to put in the text box. The person reads and edits them there;+//! nothing reaches a bot before they press Send.+//!+//! The words come from the space's own OpenAI account, in the order hybrid recall uses for+//! embeddings (`memory_recall::source_for_space`), minus Ollama, which has no speech-to-text:+//! 1. an enabled OpenAI API-key account of the space (an `api_key` profile on Codex) with a key;+//! 2. the host's OpenAI key (Settings, else `OPENAI_API_KEY`), unless This machine is off for+//! Codex in the space;+//!+//! and neither while the OpenAI API engine is turned off. Local Whisper is a follow-up.+//!+//! Nothing is stored: the audio stays in memory for the one call (at most [`MAX_AUDIO_BYTES`]),+//! no attachment row, no file, no chat message, no memory. Only the person transcribes: a bot's+//! turn token is refused, so no bot can spend the space's OpenAI money through here. At most+//! [`MAX_AT_ONCE`] recordings are sent at a time; the next waits up to [`QUEUE_WAIT`]. The key never appears in an answer or a log+//! line, and neither does OpenAI's own error text (its 401 quotes part of the key).++use super::AppState;+use crate::db::spaces::SpaceId;+use crate::drivers::engines::EngineId;+use crate::profiles::Engine;+use axum::{+ body::Body,+ extract::{Path, Query, State},+ http::{header, HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use futures::StreamExt;+use serde::Deserialize;+use serde_json::{json, Value};+use std::sync::LazyLock;+use std::time::Duration;+use tokio::sync::Semaphore;++/// OpenAI's own limit for one recording.+pub const MAX_AUDIO_BYTES: u64 = 25 * 1024 * 1024;+/// Longest wait for OpenAI's answer, per model tried.+pub const TIMEOUT: Duration = Duration::from_secs(60);+/// The model asked first, and the one tried when OpenAI says the first doesn't exist.+pub const MODEL: &str = "gpt-4o-mini-transcribe";+pub const FALLBACK_MODEL: &str = "whisper-1";+/// Recordings sent to OpenAI at the same time, across all spaces. One more waits up to+/// [`QUEUE_WAIT`] for its turn, then gets 429 `busy`.+pub const MAX_AT_ONCE: usize = 2;+pub const QUEUE_WAIT: Duration = Duration::from_secs(30);+/// Test seam: another OpenAI address (only with the `test-seams` feature, like Telegram's).+pub const API_BASE_ENV: &str = "KWNT_OPENAI_API_BASE";+const OPENAI_API: &str = "https://api.openai.com";++pub const WHY_NO_KEY: &str = "Add an OpenAI API key in Apps & accounts to dictate.";+pub const WHY_HOST_OFF: &str =+ "This machine is turned off for OpenAI in this space, so its key isn't used. Add an OpenAI API key to this space in Apps & accounts to dictate.";+pub const WHY_ENGINE_OFF: &str = "The OpenAI API is turned off in Apps & accounts. Turn it on to dictate.";+pub const WHY_KEY_REFUSED: &str = "The OpenAI key was refused.";++/// The recording types the mic button can send (`MediaRecorder` gives webm in Chrome and+/// Firefox, mp4 in Safari), with the file name OpenAI is told. Parameters such as+/// `;codecs=opus` are ignored.+const AUDIO_TYPES: [(&str, &str); 10] = [+ ("audio/webm", "audio.webm"),+ ("audio/mp4", "audio.mp4"),+ ("audio/x-m4a", "audio.m4a"),+ ("audio/m4a", "audio.m4a"),+ ("audio/mpeg", "audio.mp3"),+ ("audio/mp3", "audio.mp3"),+ ("audio/wav", "audio.wav"),+ ("audio/x-wav", "audio.wav"),+ ("audio/wave", "audio.wav"),+ ("audio/ogg", "audio.ogg"),+];++/// Where a space's dictation goes.+#[derive(Clone, PartialEq)]+pub enum TranscribeSource {+ /// `base` is the API root without `/v1`.+ OpenAi { base: String, key: String },+}++impl std::fmt::Debug for TranscribeSource {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ TranscribeSource::OpenAi { base, .. } => write!(f, "OpenAi({base}, key <redacted>)"),+ }+ }+}++impl TranscribeSource {+ /// The `source` the routes answer with.+ pub fn name(&self) -> &'static str {+ match self {+ TranscribeSource::OpenAi { .. } => "openai",+ }+ }+}++/// What decides a space's source, read from the database and Settings.+#[derive(Debug, Default, Clone)]+pub struct KeyFacts {+ /// The OpenAI API engine is on (Settings).+ pub openai_on: bool,+ /// The key of the space's first enabled Codex `api_key` account that has one.+ pub space_key: Option<String>,+ /// This machine is off for Codex in the space.+ pub host_off: bool,+ /// The host's key (Settings, else `OPENAI_API_KEY`).+ pub host_key: Option<String>,+}++/// The key to use, or why there is none (a sentence for the person). Pure: the order lives here.+pub fn pick(facts: &KeyFacts) -> Result<String, &'static str> {+ let usable = |k: &Option<String>| k.as_deref().map(str::trim).filter(|k| !k.is_empty()).map(str::to_string);+ if !facts.openai_on {+ return Err(if usable(&facts.space_key).is_some() || usable(&facts.host_key).is_some() { WHY_ENGINE_OFF } else { WHY_NO_KEY });+ }+ if let Some(k) = usable(&facts.space_key) {+ return Ok(k);+ }+ match usable(&facts.host_key) {+ Some(_) if facts.host_off => Err(WHY_HOST_OFF),+ Some(k) => Ok(k),+ None => Err(WHY_NO_KEY),+ }+}++/// Reads [`KeyFacts`] for `space`: only the database and the environment, never a network call.+pub async fn key_facts(state: &AppState, space: &SpaceId) -> KeyFacts {+ let db = &state.db;+ let profiles = db.list_profiles(space).await.unwrap_or_default();+ let mut space_key = None;+ for p in profiles.iter().filter(|p| p.engine == "codex" && p.kind == "api_key" && p.enabled) {+ if let Ok(Some(key)) = db.get_profile_key(&p.id).await {+ if !key.0.trim().is_empty() {+ space_key = Some(key.0);+ break;+ }+ }+ }+ let host_off = profiles.iter().any(|p| p.kind == "system" && !p.enabled && Engine::parse(&p.engine) == Some(Engine::Codex));+ let host_key = db.get_setting("openai_api_key").await.ok().flatten().or_else(|| std::env::var("OPENAI_API_KEY").ok()).filter(|k| !k.trim().is_empty());+ KeyFacts { openai_on: state.engines.is_enabled(EngineId::OpenaiApi), space_key, host_off, host_key }+}++/// The space's dictation source, or why there is none.+pub async fn transcribe_source_for_space(state: &AppState, space: &SpaceId) -> Result<TranscribeSource, &'static str> {+ pick(&key_facts(state, space).await).map(|key| TranscribeSource::OpenAi { base: api_base(), key })+}++fn api_base() -> String {+ base_for(crate::clock::TEST_SEAMS, std::env::var(API_BASE_ENV).ok())+}++/// The override counts only with the test seams built in, and only as an http(s) address, so a+/// shipped build always sends the key to api.openai.com.+fn base_for(seams: bool, override_base: Option<String>) -> String {+ if seams {+ if let Some(b) = override_base {+ let b = b.trim().trim_end_matches('/');+ if b.starts_with("http://") || b.starts_with("https://") {+ return b.to_string();+ }+ }+ }+ OPENAI_API.to_string()+}++/// The file name for a `Content-Type`, or `None` when it isn't a recording type we send.+pub fn audio_file_name(content_type: Option<&str>) -> Option<&'static str> {+ let ct = content_type?.split(';').next()?.trim().to_ascii_lowercase();+ AUDIO_TYPES.iter().find(|(t, _)| *t == ct).map(|(_, name)| *name)+}++/// An ISO-639-1 hint: two ASCII letters, lower-cased.+fn clean_lang(lang: Option<&str>) -> Result<Option<String>, ()> {+ match lang.map(str::trim).filter(|l| !l.is_empty()) {+ None => Ok(None),+ Some(l) if l.len() == 2 && l.bytes().all(|b| b.is_ascii_alphabetic()) => Ok(Some(l.to_ascii_lowercase())),+ Some(_) => Err(()),+ }+}++fn refusal(status: StatusCode, code: &str, message: &str) -> Response {+ (status, Json(json!({"error": message, "code": code}))).into_response()+}++fn no_transcriber(why: &str) -> Response {+ (StatusCode::CONFLICT, Json(json!({"error": why, "code": "no_transcriber", "why": why}))).into_response()+}++/// `GET /api/spaces/:id/transcribe` → `{available, source: "openai"|null, why: string|null}`.+pub async fn status(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let space = SpaceId::new(id.trim());+ match state.db.get_space(&space).await {+ Ok(Some(_)) => {}+ Ok(None) => return refusal(StatusCode::NOT_FOUND, "no_space", "no such space"),+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+ Json(status_json(transcribe_source_for_space(&state, &space).await)).into_response()+}++pub fn status_json(source: Result<TranscribeSource, &'static str>) -> Value {+ match source {+ Ok(s) => json!({"available": true, "source": s.name(), "why": null}),+ Err(why) => json!({"available": false, "source": null, "why": why}),+ }+}++#[derive(Deserialize)]+pub struct TranscribeQuery {+ pub lang: Option<String>,+}++static AT_ONCE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(MAX_AT_ONCE));+static CLIENT: LazyLock<reqwest::Client> = LazyLock::new(reqwest::Client::new);++/// The pooled client for api.openai.com, or a new one for any other base (only a test-seams+/// build has one: a stub). Each `#[tokio::test]` runs on its own runtime, and a connection pooled+/// during one test dies with that test's runtime, so a shared pool let a test's upload ride a+/// connection that was cut halfway ("OpenAI couldn't be reached.", #610 CI at 06:02).+fn client_for(base: &str) -> reqwest::Client {+ if base == OPENAI_API {+ CLIENT.clone()+ } else {+ reqwest::Client::new()+ }+}++/// `POST /api/spaces/:id/transcribe[?lang=xx]` with the recording as the raw body → 200+/// `{text, source}`. Refusals come before any byte is read where they can: 403 for a bot's+/// token, 404 no space, 409 archived space, 413 a declared length over 25 MB, 415 not a+/// recording type, 400 a bad `lang`, 409 `no_transcriber`; then 413 at the byte that passes+/// 25 MB, 400 `empty_audio`, 429 `busy`, 502 `transcriber_failed` (see docs/dictation.md).+pub async fn transcribe(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Query(q): Query<TranscribeQuery>,+ headers: HeaderMap,+ body: Body,+) -> Response {+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person can dictate").await {+ return r;+ }+ let space = match super::spaces::active_space(&state, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let declared = headers.get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());+ if declared.is_some_and(|n| n > MAX_AUDIO_BYTES) {+ return too_large();+ }+ let Some(file_name) = audio_file_name(headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok())) else {+ return refusal(+ StatusCode::UNSUPPORTED_MEDIA_TYPE,+ "bad_audio_type",+ "Send the recording as audio/webm, audio/mp4, audio/mpeg, audio/wav or audio/ogg.",+ );+ };+ let Ok(lang) = clean_lang(q.lang.as_deref()) else {+ return refusal(StatusCode::BAD_REQUEST, "bad_lang", "lang must be a two-letter language code such as en.");+ };+ let source = match transcribe_source_for_space(&state, &space).await {+ Ok(s) => s,+ Err(why) => return no_transcriber(why),+ };+ let mut audio = Vec::with_capacity(declared.unwrap_or(0).min(MAX_AUDIO_BYTES) as usize);+ let mut stream = body.into_data_stream();+ while let Some(chunk) = stream.next().await {+ let Ok(chunk) = chunk else {+ return refusal(StatusCode::BAD_REQUEST, "interrupted", "The recording was interrupted.");+ };+ if audio.len() as u64 + chunk.len() as u64 > MAX_AUDIO_BYTES {+ return too_large();+ }+ audio.extend_from_slice(&chunk);+ }+ if audio.is_empty() {+ return refusal(StatusCode::BAD_REQUEST, "empty_audio", "The recording is empty.");+ }+ let Ok(Ok(_slot)) = tokio::time::timeout(QUEUE_WAIT, AT_ONCE.acquire()).await else {+ return refusal(StatusCode::TOO_MANY_REQUESTS, "busy", "Other recordings are being turned into text. Try again in a moment.");+ };+ let size = audio.len();+ match send(&source, audio, file_name, lang.as_deref()).await {+ Ok((text, model)) => {+ tracing::info!(space = %space, bytes = size, model, "dictation transcribed");+ Json(json!({"text": text, "source": source.name()})).into_response()+ }+ Err(why) => {+ tracing::warn!(space = %space, bytes = size, why, "dictation failed");+ refusal(StatusCode::BAD_GATEWAY, "transcriber_failed", why)+ }+ }+}++fn too_large() -> Response {+ refusal(StatusCode::PAYLOAD_TOO_LARGE, "too_large", "The recording is over 25 MB. Record a shorter message.")+}++/// Sends the recording with [`MODEL`], then [`FALLBACK_MODEL`] if OpenAI says the first doesn't+/// exist. `Ok((text, model))`, or a plain reason that never has the key or OpenAI's own words.+pub async fn send(source: &TranscribeSource, audio: Vec<u8>, file_name: &str, lang: Option<&str>) -> Result<(String, &'static str), &'static str> {+ match send_one(source, &audio, file_name, lang, MODEL).await {+ Err(Upstream::ModelMissing) => match send_one(source, &audio, file_name, lang, FALLBACK_MODEL).await {+ Ok(text) => Ok((text, FALLBACK_MODEL)),+ Err(e) => Err(e.why()),+ },+ Ok(text) => Ok((text, MODEL)),+ Err(e) => Err(e.why()),+ }+}++#[derive(Debug, PartialEq)]+enum Upstream {+ ModelMissing,+ Status(u16),+ Timeout,+ Unreachable,+ Unreadable,+}++impl Upstream {+ fn why(&self) -> &'static str {+ match self {+ Upstream::Status(401 | 403) => WHY_KEY_REFUSED,+ Upstream::Status(429) => "OpenAI is limiting this key, or its quota is used up. Try again in a minute.",+ Upstream::Status(413) => "The recording is too large for OpenAI.",+ Upstream::Status(400 | 404 | 415 | 422) | Upstream::ModelMissing => "OpenAI couldn't read this recording.",+ Upstream::Status(_) => "OpenAI had a problem. Try again in a minute.",+ Upstream::Timeout => "OpenAI didn't answer within 60 seconds.",+ Upstream::Unreachable => "OpenAI couldn't be reached.",+ Upstream::Unreadable => "OpenAI's answer couldn't be read.",+ }+ }+}++/// One `multipart/form-data` body for `/v1/audio/transcriptions`.+fn multipart(boundary: &str, audio: &[u8], file_name: &str, lang: Option<&str>, model: &str) -> Vec<u8> {+ let mut out = Vec::with_capacity(audio.len() + 512);+ let mut field = |name: &str, value: &str| {+ out.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n").as_bytes());+ };+ field("model", model);+ field("response_format", "json");+ if let Some(l) = lang {+ field("language", l);+ }+ out.extend_from_slice(+ format!("--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{file_name}\"\r\nContent-Type: application/octet-stream\r\n\r\n")+ .as_bytes(),+ );+ out.extend_from_slice(audio);+ out.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());+ out+}++async fn send_one(source: &TranscribeSource, audio: &[u8], file_name: &str, lang: Option<&str>, model: &str) -> Result<String, Upstream> {+ let TranscribeSource::OpenAi { base, key } = source;+ let boundary = format!("kwnt-{}", uuid::Uuid::new_v4().simple());+ let resp = client_for(base)+ .post(format!("{}/v1/audio/transcriptions", base.trim_end_matches('/')))+ .bearer_auth(key)+ .header(header::CONTENT_TYPE, format!("multipart/form-data; boundary={boundary}"))+ .body(multipart(&boundary, audio, file_name, lang, model))+ .timeout(TIMEOUT)+ .send()+ .await+ .map_err(|e| {+ if e.is_timeout() {+ return Upstream::Timeout;+ }+ // The error without its address; the key is a header and is never in it.+ tracing::warn!(error = %e.without_url(), "dictation: OpenAI couldn't be reached");+ Upstream::Unreachable+ })?;+ let status = resp.status().as_u16();+ if status != 200 {+ let body: Value = resp.json().await.unwrap_or(Value::Null);+ return Err(if model_missing(status, &body) { Upstream::ModelMissing } else { Upstream::Status(status) });+ }+ let body: Value = resp.json().await.map_err(|e| if e.is_timeout() { Upstream::Timeout } else { Upstream::Unreadable })?;+ body["text"].as_str().map(|t| t.trim().to_string()).ok_or(Upstream::Unreadable)+}++/// OpenAI's answer for a model this key can't use: 404 (or 400) with `error.code`+/// `model_not_found`, or an error about the `model` parameter.+fn model_missing(status: u16, body: &Value) -> bool {+ let e = &body["error"];+ matches!(status, 400 | 404) && (e["code"] == "model_not_found" || e["param"] == "model")+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facts(openai_on: bool, space_key: Option<&str>, host_off: bool, host_key: Option<&str>) -> KeyFacts {+ KeyFacts { openai_on, space_key: space_key.map(Into::into), host_off, host_key: host_key.map(Into::into) }+ }++ #[test]+ fn the_space_key_beats_the_host_key() {+ assert_eq!(pick(&facts(true, Some("sk-space"), false, Some("sk-host"))), Ok("sk-space".into()));+ assert_eq!(pick(&facts(true, Some(" sk-space \n"), true, None)), Ok("sk-space".into()));+ }++ #[test]+ fn the_host_key_is_used_unless_this_machine_is_off() {+ assert_eq!(pick(&facts(true, None, false, Some("sk-host"))), Ok("sk-host".into()));+ assert_eq!(pick(&facts(true, None, true, Some("sk-host"))), Err(WHY_HOST_OFF));+ assert_eq!(pick(&facts(true, Some(" "), true, Some("sk-host"))), Err(WHY_HOST_OFF), "a blank space key is no key");+ }++ #[test]+ fn no_key_or_the_engine_off_gives_the_why() {+ assert_eq!(pick(&facts(true, None, false, None)), Err(WHY_NO_KEY));+ assert_eq!(pick(&facts(true, Some(""), false, Some(" "))), Err(WHY_NO_KEY));+ assert_eq!(pick(&facts(false, Some("sk-space"), false, Some("sk-host"))), Err(WHY_ENGINE_OFF));+ assert_eq!(pick(&facts(false, None, false, None)), Err(WHY_NO_KEY));+ for why in [WHY_NO_KEY, WHY_HOST_OFF, WHY_ENGINE_OFF] {+ assert!(!why.contains("sk-"));+ }+ }++ #[test]+ fn the_source_never_prints_its_key() {+ let s = TranscribeSource::OpenAi { base: OPENAI_API.into(), key: "sk-secret".into() };+ assert!(!format!("{s:?}").contains("sk-secret"));+ assert_eq!(s.name(), "openai");+ let v = status_json(Ok(s));+ assert_eq!(v, json!({"available": true, "source": "openai", "why": null}));+ assert_eq!(status_json(Err(WHY_NO_KEY)), json!({"available": false, "source": null, "why": WHY_NO_KEY}));+ }++ #[test]+ fn recording_types_and_language_hints() {+ assert_eq!(audio_file_name(Some("audio/webm;codecs=opus")), Some("audio.webm"));+ assert_eq!(audio_file_name(Some("Audio/MP4")), Some("audio.mp4"));+ assert_eq!(audio_file_name(Some("audio/mpeg")), Some("audio.mp3"));+ assert_eq!(audio_file_name(Some("audio/wav")), Some("audio.wav"));+ assert_eq!(audio_file_name(Some("audio/ogg; codecs=opus")), Some("audio.ogg"));+ for bad in [Some("text/plain"), Some("video/webm"), Some("application/octet-stream"), Some(""), None] {+ assert_eq!(audio_file_name(bad), None, "{bad:?}");+ }+ assert_eq!(clean_lang(None), Ok(None));+ assert_eq!(clean_lang(Some("")), Ok(None));+ assert_eq!(clean_lang(Some("EN")), Ok(Some("en".into())));+ for bad in ["eng", "e", "e1", "en-US", "ü1"] {+ assert_eq!(clean_lang(Some(bad)), Err(()), "{bad}");+ }+ }++ #[test]+ fn only_test_builds_may_point_elsewhere() {+ assert_eq!(base_for(false, Some("http://127.0.0.1:9".into())), OPENAI_API);+ assert_eq!(base_for(true, Some("http://127.0.0.1:9/".into())), "http://127.0.0.1:9");+ assert_eq!(base_for(true, Some("file:///etc".into())), OPENAI_API);+ assert_eq!(base_for(true, None), OPENAI_API);+ }++ #[test]+ fn a_missing_model_is_told_apart_from_other_errors() {+ assert!(model_missing(404, &json!({"error": {"code": "model_not_found"}})));+ assert!(model_missing(400, &json!({"error": {"param": "model", "message": "invalid model"}})));+ assert!(!model_missing(400, &json!({"error": {"param": "file"}})));+ assert!(!model_missing(401, &json!({"error": {"code": "model_not_found"}})));+ assert_eq!(Upstream::Status(401).why(), WHY_KEY_REFUSED);+ assert_eq!(Upstream::Timeout.why(), "OpenAI didn't answer within 60 seconds.");+ }++ #[test]+ fn the_multipart_body_has_the_fields_and_the_bytes() {+ let body = multipart("B", b"\x00\x01RIFF", "audio.wav", Some("de"), MODEL);+ let text = String::from_utf8_lossy(&body);+ assert!(text.starts_with("--B\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngpt-4o-mini-transcribe\r\n"), "{text}");+ assert!(text.contains("name=\"language\"\r\n\r\nde\r\n"));+ assert!(text.contains("name=\"response_format\"\r\n\r\njson\r\n"));+ assert!(text.contains("filename=\"audio.wav\""));+ assert!(body.windows(6).any(|w| w == b"\x00\x01RIFF"));+ assert!(text.ends_with("\r\n--B--\r\n"));+ assert!(!String::from_utf8_lossy(&multipart("B", b"x", "audio.webm", None, MODEL)).contains("language"));+ }+}diff --git a/tests/transcribe_test.rs b/tests/transcribe_test.rsnew file mode 100644index 00000000..51519f59--- /dev/null+++ b/tests/transcribe_test.rs@@ -0,0 +1,358 @@+//! Dictation (roadmap Next 12b): `GET/POST /api/spaces/:id/transcribe`. A stub OpenAI server+//! stands in for api.openai.com (through the `KWNT_OPENAI_API_BASE` test seam): no test calls+//! the real API. The stub answers by key, so the tests can share it while running in parallel.++use axum::{+ body::{to_bytes, Body, Bytes},+ http::{HeaderMap, Request, StatusCode},+ response::{IntoResponse, Response},+ routing::post,+ Json, Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ models::{NewLlmProfile, ProfileKey},+ spaces::{NewSpace, SpaceId, DEFAULT_SPACE_ID},+ Database,+ },+ drivers::engines::EngineId,+ router::LayaRouter,+ server::{continuity::SelfScope, create_router, transcribe, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::collections::HashSet;+use std::io::Write;+use std::path::Path;+use std::sync::{Arc, Mutex, OnceLock};+use tempfile::{tempdir, TempDir};++/// The Default space every fresh database starts with (`spc_default`, not "default").+const DEF: &str = DEFAULT_SPACE_ID;+use tower::ServiceExt;++/// One request the stub got: (key, model, language, file name, audio bytes).+type Call = (String, String, Option<String>, String, usize);++static CALLS: Mutex<Vec<Call>> = Mutex::new(Vec::new());++fn calls_with(key: &str) -> Vec<Call> {+ CALLS.lock().unwrap().iter().filter(|c| c.0 == key).cloned().collect()+}++/// The value of a multipart text field, or the file part's name and size.+fn field(body: &[u8], name: &str) -> Option<String> {+ let text = String::from_utf8_lossy(body);+ let start = text.find(&format!("name=\"{name}\"\r\n\r\n"))? + name.len() + 11;+ Some(text[start..].split("\r\n").next()?.to_string())+}++fn file_part(body: &[u8]) -> (String, usize) {+ let text = String::from_utf8_lossy(body).to_string();+ let i = text.find("filename=\"").unwrap() + 10;+ let name = text[i..].split('"').next().unwrap().to_string();+ let head = b"Content-Type: application/octet-stream\r\n\r\n";+ let from = body.windows(head.len()).position(|w| w == head).unwrap() + head.len();+ let tail = body.windows(4).rposition(|w| w == b"\r\n--").unwrap();+ (name, tail - from)+}++async fn stub(headers: HeaderMap, body: Bytes) -> Response {+ let key = headers.get("authorization").and_then(|h| h.to_str().ok()).unwrap_or("").trim_start_matches("Bearer ").to_string();+ assert!(headers.get("content-type").unwrap().to_str().unwrap().starts_with("multipart/form-data; boundary="));+ let model = field(&body, "model").unwrap();+ assert_eq!(field(&body, "response_format").as_deref(), Some("json"));+ let (file, size) = file_part(&body);+ CALLS.lock().unwrap().push((key.clone(), model.clone(), field(&body, "language"), file, size));+ match (key.as_str(), model.as_str()) {+ ("sk-bad", _) => (+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": {"message": "Incorrect API key provided: sk-bad. You can find your API key at https://platform.openai.com/account/api-keys.", "type": "invalid_request_error", "code": "invalid_api_key"}})),+ )+ .into_response(),+ ("sk-limit", _) => (StatusCode::TOO_MANY_REQUESTS, Json(json!({"error": {"message": "Rate limit reached", "code": "rate_limit_exceeded"}}))).into_response(),+ ("sk-old", "gpt-4o-mini-transcribe") => (+ StatusCode::NOT_FOUND,+ Json(json!({"error": {"message": "The model `gpt-4o-mini-transcribe` does not exist", "code": "model_not_found"}})),+ )+ .into_response(),+ (_, m) => Json(json!({"text": format!(" hello from {key} via {m} ")})).into_response(),+ }+}++/// Starts the stub once, on its own thread and runtime (each test has its own runtime), and+/// points kwnt at it.+fn stub_base() -> &'static str {+ static BASE: OnceLock<String> = OnceLock::new();+ BASE.get_or_init(|| {+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(1).enable_all().build().unwrap();+ rt.block_on(async move {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ tx.send(format!("http://{}", listener.local_addr().unwrap())).unwrap();+ let app = Router::new().route("/v1/audio/transcriptions", post(stub)).layer(axum::extract::DefaultBodyLimit::max(64 << 20));+ axum::serve(listener, app).await.unwrap();+ });+ });+ let base = rx.recv().unwrap();+ std::env::set_var(transcribe::API_BASE_ENV, &base);+ std::env::remove_var("OPENAI_API_KEY");+ base+ })+}++async fn setup() -> (Router, AppState, TempDir) {+ stub_base();+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ db.set_setting("mission_board", "false").await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ (create_router(state.clone()), state, tmp)+}++async fn space_key(state: &AppState, space: &SpaceId, key: &str) {+ let p = state+ .db+ .create_profile(+ space,+ &NewLlmProfile {+ engine: "codex".into(),+ name: "OpenAI key".into(),+ kind: "api_key".into(),+ home_dir: None,+ priority: 0,+ enabled: true,+ is_default: false,+ },+ )+ .await+ .unwrap();+ state.db.set_profile_key(&p.id, &ProfileKey(key.into())).await.unwrap();+}++async fn call(app: &Router, req: Request<Body>) -> (StatusCode, Value) {+ let resp = app.clone().oneshot(req).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn status(app: &Router, space: &str) -> (StatusCode, Value) {+ call(app, Request::get(format!("/api/spaces/{space}/transcribe")).body(Body::empty()).unwrap()).await+}++fn audio_post(space: &str, query: &str, content_type: &str, audio: Vec<u8>) -> Request<Body> {+ Request::post(format!("/api/spaces/{space}/transcribe{query}"))+ .header("content-type", content_type)+ .header("content-length", audio.len().to_string())+ .body(Body::from(audio))+ .unwrap()+}++fn files(root: &Path) -> HashSet<String> {+ let mut out = HashSet::new();+ let mut dirs = vec![root.to_path_buf()];+ while let Some(d) = dirs.pop() {+ for e in std::fs::read_dir(&d).unwrap().flatten() {+ let p = e.path();+ if p.is_dir() {+ dirs.push(p);+ } else {+ out.insert(p.strip_prefix(root).unwrap().display().to_string());+ }+ }+ }+ out+}++#[tokio::test]+async fn with_no_key_it_is_unavailable_and_says_why() {+ let (app, _state, _tmp) = setup().await;+ let (code, v) = status(&app, DEF).await;+ assert_eq!(code, StatusCode::OK);+ assert_eq!(v, json!({"available": false, "source": null, "why": transcribe::WHY_NO_KEY}));++ let before = CALLS.lock().unwrap().len();+ let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", vec![1; 1000])).await;+ assert_eq!(code, StatusCode::CONFLICT);+ assert_eq!(v, json!({"error": transcribe::WHY_NO_KEY, "code": "no_transcriber", "why": transcribe::WHY_NO_KEY}));+ assert_eq!(CALLS.lock().unwrap().len(), before, "no upstream call without a key");++ let (code, _) = status(&app, "spc_missing").await;+ assert_eq!(code, StatusCode::NOT_FOUND);+ let (code, _) = call(&app, audio_post("spc_missing", "", "audio/webm", vec![1; 10])).await;+ assert_eq!(code, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn the_space_key_transcribes_and_nothing_is_stored() {+ let (app, state, tmp) = setup().await;+ state.db.set_setting("openai_api_key", "sk-host-unused").await.unwrap();+ space_key(&state, &SpaceId::default_space(), "sk-space").await;+ let (_, v) = status(&app, DEF).await;+ assert_eq!(v, json!({"available": true, "source": "openai", "why": null}));++ let before = files(tmp.path());+ let audio: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();+ let (code, v) = call(&app, audio_post(DEF, "?lang=DE", "audio/webm;codecs=opus", audio)).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v, json!({"text": "hello from sk-space via gpt-4o-mini-transcribe", "source": "openai"}));+ assert_eq!(+ calls_with("sk-space"),+ vec![("sk-space".into(), "gpt-4o-mini-transcribe".into(), Some("de".into()), "audio.webm".into(), 300_000)],+ "the space key beats the host key, all bytes go up once"+ );+ assert!(calls_with("sk-host-unused").is_empty());+ assert_eq!(files(tmp.path()), before, "no file is left behind");+ let attachments: Vec<String> = state.db.list_attachments_in(DEF, 10).await.unwrap().into_iter().map(|a| a.id).collect();+ assert!(attachments.is_empty(), "{attachments:?}");+}++#[tokio::test]+async fn the_host_key_is_used_unless_this_machine_is_off() {+ let (app, state, _tmp) = setup().await;+ state.db.set_setting("openai_api_key", "sk-host").await.unwrap();+ let (code, v) = call(&app, audio_post(DEF, "", "audio/mp4", vec![7; 2048])).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v["text"], "hello from sk-host via gpt-4o-mini-transcribe");+ assert!(calls_with("sk-host").iter().any(|c| c.3 == "audio.mp4" && c.4 == 2048 && c.2.is_none()));++ let off = state+ .db+ .create_space(&NewSpace { name: "Off".into(), icon: "x".into(), color: None, this_machine_enabled: false })+ .await+ .unwrap();+ let (_, v) = status(&app, &off.id).await;+ assert_eq!(v, json!({"available": false, "source": null, "why": transcribe::WHY_HOST_OFF}));+ let (code, v) = call(&app, audio_post(&off.id, "", "audio/mp4", vec![7; 10])).await;+ assert_eq!((code, v["code"].clone()), (StatusCode::CONFLICT, json!("no_transcriber")));++ // Its own key works there+ space_key(&state, &SpaceId::new(&off.id), "sk-offspace").await;+ let (code, v) = call(&app, audio_post(&off.id, "", "audio/ogg", vec![7; 10])).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v["text"], "hello from sk-offspace via gpt-4o-mini-transcribe");++ // The OpenAI API engine turned off: nobody's key is used+ state.engines.set_disabled(HashSet::from([EngineId::OpenaiApi]));+ let (_, v) = status(&app, &off.id).await;+ assert_eq!(v["why"], transcribe::WHY_ENGINE_OFF);+}++#[tokio::test]+async fn a_refused_key_is_a_502_without_the_key() {+ let (app, state, _tmp) = setup().await;+ space_key(&state, &SpaceId::default_space(), "sk-bad").await;+ // Everything this test's thread logs+ let log = Arc::new(Mutex::new(Vec::<u8>::new()));+ let sink = log.clone();+ let subscriber = tracing_subscriber::fmt()+ .with_max_level(tracing::Level::TRACE)+ .with_ansi(false)+ .with_writer(move || Capture(sink.clone()))+ .finish();+ let _guard = tracing::subscriber::set_default(subscriber);++ let (code, v) = call(&app, audio_post(DEF, "", "audio/wav", vec![3; 500])).await;+ assert_eq!(code, StatusCode::BAD_GATEWAY);+ assert_eq!(v, json!({"error": "The OpenAI key was refused.", "code": "transcriber_failed"}));+ assert_eq!(calls_with("sk-bad").len(), 1, "a refused key isn't retried with the other model");+ let log = String::from_utf8(log.lock().unwrap().clone()).unwrap();+ assert!(log.contains("dictation failed"), "{log}");+ assert!(!log.contains("sk-bad") && !v.to_string().contains("sk-bad"), "{log}");+ assert!(!log.contains("Incorrect API key"), "OpenAI's own text isn't passed on: {log}");+}++struct Capture(Arc<Mutex<Vec<u8>>>);++impl Write for Capture {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.0.lock().unwrap().extend_from_slice(buf);+ Ok(buf.len())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}++#[tokio::test]+async fn other_upstream_failures_and_the_fallback_model() {+ let (app, state, _tmp) = setup().await;+ space_key(&state, &SpaceId::default_space(), "sk-old").await;+ let (code, v) = call(&app, audio_post(DEF, "", "audio/mpeg", vec![3; 100])).await;+ assert_eq!(code, StatusCode::OK, "{v}");+ assert_eq!(v["text"], "hello from sk-old via whisper-1");+ let models: Vec<String> = calls_with("sk-old").into_iter().map(|c| c.1).collect();+ assert_eq!(models, ["gpt-4o-mini-transcribe", "whisper-1"]);++ let limited = state+ .db+ .create_space(&NewSpace { name: "Limited".into(), icon: "x".into(), color: None, this_machine_enabled: true })+ .await+ .unwrap();+ space_key(&state, &SpaceId::new(&limited.id), "sk-limit").await;+ let (code, v) = call(&app, audio_post(&limited.id, "", "audio/webm", vec![3; 100])).await;+ assert_eq!(code, StatusCode::BAD_GATEWAY);+ assert_eq!(v["code"], "transcriber_failed");+ assert_eq!(v["error"], "OpenAI is limiting this key, or its quota is used up. Try again in a minute.");+}++#[tokio::test]+async fn refusals_come_before_anything_goes_upstream() {+ let (app, state, _tmp) = setup().await;+ space_key(&state, &SpaceId::default_space(), "sk-refusals").await;++ // 26 MB declared: refused before a byte is read+ let req = Request::post(format!("/api/spaces/{DEF}/transcribe"))+ .header("content-type", "audio/webm")+ .header("content-length", (26 * 1024 * 1024).to_string())+ .body(Body::from(vec![0u8; 10]))+ .unwrap();+ let (code, v) = call(&app, req).await;+ assert_eq!(code, StatusCode::PAYLOAD_TOO_LARGE);+ assert_eq!(v["code"], "too_large");++ // No length declared: refused at the byte that passes 25 MB+ let chunks = (0..26).map(|_| Ok::<_, std::io::Error>(Bytes::from(vec![0u8; 1024 * 1024])));+ let req = Request::post(format!("/api/spaces/{DEF}/transcribe"))+ .header("content-type", "audio/webm")+ .body(Body::from_stream(futures::stream::iter(chunks)))+ .unwrap();+ let (code, v) = call(&app, req).await;+ assert_eq!((code, v["code"].clone()), (StatusCode::PAYLOAD_TOO_LARGE, json!("too_large")));++ // Exactly 25 MB goes through+ let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", vec![0u8; transcribe::MAX_AUDIO_BYTES as usize])).await;+ assert_eq!(code, StatusCode::OK, "{v}");++ for (ct, query, want_code, want) in [+ ("text/plain", "", StatusCode::UNSUPPORTED_MEDIA_TYPE, "bad_audio_type"),+ ("video/webm", "", StatusCode::UNSUPPORTED_MEDIA_TYPE, "bad_audio_type"),+ ("audio/webm", "?lang=english", StatusCode::BAD_REQUEST, "bad_lang"),+ ] {+ let (code, v) = call(&app, audio_post(DEF, query, ct, vec![1; 10])).await;+ assert_eq!((code, v["code"].as_str().unwrap()), (want_code, want), "{ct} {query}");+ }+ let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", Vec::new())).await;+ assert_eq!((code, v["code"].clone()), (StatusCode::BAD_REQUEST, json!("empty_audio")));++ // A bot's turn token is refused: dictation is the person's+ state.self_tools.lock().await.insert("turn-token".into(), SelfScope::default());+ let mut req = audio_post(DEF, "", "audio/webm", vec![1; 10]);+ req.headers_mut().insert("authorization", "Bearer turn-token".parse().unwrap());+ let (code, _) = call(&app, req).await;+ assert_eq!(code, StatusCode::FORBIDDEN);++ assert_eq!(calls_with("sk-refusals").len(), 1, "only the 25 MB recording went up");+ assert_eq!(calls_with("sk-refusals")[0].4, transcribe::MAX_AUDIO_BYTES as usize);+}