Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Dictation: two recordings in memory at most, every refusal tested (15d) (#648)

Oleksandr Ivanchenkoaeb854ab8c63
diff --git a/README.md b/README.md
index cc72b0e4..8f98d397 100644
--- a/README.md
+++ b/README.md
@@ -335,6 +335,7 @@ The first start needs `huggingface.co`. Behind a proxy that blocks it, start kwa
- [Parallel Universe](docs/parallel-universe.md)
- [Dev mode](docs/dev-mode.md)
- [Idea jar](docs/idea-jar.md)
+ - [Dictation](docs/dictation.md): `GET /api/spaces/:id/transcribe` says whether the mic button works in a space; `POST /api/spaces/:id/transcribe` turns a recording into text
---
diff --git a/docs/dictation.md b/docs/dictation.md
index 2ebf2390..75c40407 100644
--- a/docs/dictation.md
+++ b/docs/dictation.md
@@ -4,8 +4,9 @@ The message box's mic button records the person's voice and turns it into text i
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):
+The words come from the space's own OpenAI account, in this order (hybrid recall's embeddings use
+the same one, from the same code, `src/server/openai_key.rs`; recall then falls back to 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
@@ -55,25 +56,30 @@ Content-Type: audio/webm;codecs=opus
{"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.
+Only the person can dictate: a bot's turn token (its own tools or an MCP session) gets 403.
+
+At most 2 recordings are read and sent to OpenAI at a time; one more waits up to 30 s for its
+turn **before its body is read**, so a waiting recording holds no memory, and one that gets 429
+`busy` is never read. A call keeps one copy of the recording: the upload to OpenAI sends that same
+buffer between the form fields (for the fallback model too), with its `Content-Length`. So at most
+2 × 25 MB of recordings are in memory at once.
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 |
+| 403 | `forbidden` | `only the person can dictate` |
+| 404 | `not_found` | `no such space` |
+| 409 | `archived` | `this space is archived; restore it first` |
| 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.` |
+| 429 | `busy` | `Other recordings are being turned into text. Try again in a moment.` (no slot within 30 s; the body isn't read) |
+| 400 | `interrupted` | `The recording was interrupted.` (the upload broke off, or sent nothing for 15 s) |
| 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):
@@ -83,7 +89,8 @@ Every refusal is `{"error": "<a sentence for the person>", "code": "<code>"}`; 4
- `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 didn't answer in time. Try again in a minute.` (60 s per model tried, so up to 2 minutes
+ when the fallback model runs)
- `OpenAI couldn't be reached.`
- `OpenAI's answer couldn't be read.`
diff --git a/src/server/memory_recall.rs b/src/server/memory_recall.rs
index 4224713b..49c0f81d 100644
--- a/src/server/memory_recall.rs
+++ b/src/server/memory_recall.rs
@@ -13,11 +13,10 @@
//! background, at most [`FILL_BATCH`] × [`FILL_ROUNDS`] per fill and one fill per kwant at a time;
//! after a provider error that provider is left alone for [`COOLDOWN`].
-use super::{profile_turn, AppState};
+use super::AppState;
use crate::db::continuity::{Memory, MAX_MEMORY_SEARCH_LIMIT};
use crate::db::spaces::SpaceId;
use crate::drivers::engines::{EngineId, EngineStatus};
-use crate::profiles::Engine;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
@@ -108,43 +107,26 @@ pub fn pick_ollama_model<'a>(models: impl IntoIterator<Item = &'a str>) -> Optio
/// The space's embedding provider, or `None`. Reads only the database, the environment and the
/// cached engine checks: never a network call.
///
-/// 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`), when the OpenAI API engine's last
-/// check passed (so a revoked key isn't tried again every minute) and This machine isn't off
-/// for Codex in the space (the rule turns use: [`profile_turn::host_off`]).
-/// 3. A local Ollama whose last check was ready and that has an embedding model pulled.
+/// 1. The space's OpenAI key, in [`super::openai_key`]'s order (the one dictation uses too): an
+/// enabled OpenAI API-key account of the space, else the host's key unless This machine is off
+/// for Codex in the space; neither while the OpenAI API engine is turned off. Recall takes the
+/// host's key only when the OpenAI API engine's last check passed, so a revoked key isn't
+/// tried again every minute.
+/// 2. A local Ollama whose last check was ready and that has an embedding model pulled.
pub async fn source_for_space(state: &AppState, space: &SpaceId) -> Option<EmbedSource> {
- let db = &state.db;
- let openai_on = state.engines.is_enabled(EngineId::OpenaiApi);
- let profiles = db.list_profiles(space).await.unwrap_or_default();
- if openai_on {
- 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() {
- return Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: key.0.trim().to_string() });
- }
- }
- }
- let host_ready = state.engines.report(EngineId::OpenaiApi).status == EngineStatus::Ready;
- if host_ready && !profile_turn::host_off(state, space).await.contains(&Engine::Codex) {
- let 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());
- if let Some(key) = key {
- return Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key: key.trim().to_string() });
- }
- }
+ let mut facts = super::openai_key::facts(state, space).await;
+ if state.engines.report(EngineId::OpenaiApi).status != EngineStatus::Ready {
+ facts.host_key = None;
+ }
+ if let Ok(key) = super::openai_key::pick(&facts) {
+ return Some(EmbedSource::OpenAi { base: "https://api.openai.com".into(), key });
}
let ollama = state.engines.report(EngineId::Ollama);
if ollama.status != EngineStatus::Ready {
return None;
}
let model = pick_ollama_model(ollama.models.iter().map(|m| m.id.as_str()))?;
- let url = db.get_setting("ollama_url").await.ok().flatten();
+ let url = state.db.get_setting("ollama_url").await.ok().flatten();
Some(EmbedSource::Ollama { root: crate::drivers::ollama_root(url.as_deref()), model })
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index c96f552c..829c7d82 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -50,6 +50,7 @@ pub mod mcp_suggest;
pub mod page_source;
pub mod tool_failures;
pub mod tool_notes;
+pub mod openai_key;
pub mod transcribe;
pub mod connection_suggest;
pub mod bot_actions;
@@ -172,6 +173,8 @@ pub struct AppState {
pub spend: Arc<spend_stop::Clock>,
/// Claude replies run inside the VM ("Run Claude inside the VM", Linux only, off by default)
pub agent_vm: Arc<crate::sandbox::agent_vm::AgentVm>,
+ /// Dictation's 2-at-once slots and the wait for one (a test shortens the wait).
+ pub dictation: Arc<transcribe::Slots>,
}
impl AppState {
@@ -228,6 +231,7 @@ impl AppState {
mission_runs: Arc::default(),
spend: Arc::default(),
agent_vm,
+ dictation: Arc::default(),
}
}
diff --git a/src/server/openai_key.rs b/src/server/openai_key.rs
new file mode 100644
index 00000000..77565412
--- /dev/null
+++ b/src/server/openai_key.rs
@@ -0,0 +1,106 @@
+//! Which OpenAI key a space uses. One order for hybrid recall's embeddings
+//! (`memory_recall::source_for_space`) and dictation (`transcribe`), so the two can't drift:
+//!
+//! 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. Recall then falls back to a local
+//! Ollama; dictation has nothing after OpenAI.
+
+use super::AppState;
+use crate::db::spaces::SpaceId;
+use crate::drivers::engines::EngineId;
+use crate::profiles::Engine;
+
+/// What decides a space's OpenAI key, 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>,
+}
+
+/// Why a space has no OpenAI key.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NoKey {
+ /// The OpenAI API engine is off, and the space or the host has a key it would use.
+ EngineOff,
+ /// Only the host has a key, and This machine is off for Codex in the space.
+ HostOff,
+ /// No key anywhere.
+ Missing,
+}
+
+/// The key to use (trimmed), or why there is none. Pure: the order lives here.
+pub fn pick(facts: &KeyFacts) -> Result<String, NoKey> {
+ 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() { NoKey::EngineOff } else { NoKey::Missing });
+ }
+ if let Some(k) = usable(&facts.space_key) {
+ return Ok(k);
+ }
+ match usable(&facts.host_key) {
+ Some(_) if facts.host_off => Err(NoKey::HostOff),
+ Some(k) => Ok(k),
+ None => Err(NoKey::Missing),
+ }
+}
+
+/// Reads [`KeyFacts`] for `space`: only the database, the environment and the cached engine
+/// checks, never a network call.
+pub async fn 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 OpenAI key, or why there is none.
+pub async fn key_for_space(state: &AppState, space: &SpaceId) -> Result<String, NoKey> {
+ pick(&facts(state, space).await)
+}
+
+#[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) }
+ }
+
+ /// The whole order in one table: recall and dictation both read it from here.
+ #[test]
+ fn the_order() {
+ let cases: [(KeyFacts, Result<&str, NoKey>); 9] = [
+ (facts(true, Some("sk-space"), false, Some("sk-host")), Ok("sk-space")),
+ (facts(true, Some(" sk-space \n"), true, None), Ok("sk-space")),
+ (facts(true, Some("sk-space"), true, Some("sk-host")), Ok("sk-space")),
+ (facts(true, None, false, Some(" sk-host ")), Ok("sk-host")),
+ (facts(true, None, true, Some("sk-host")), Err(NoKey::HostOff)),
+ (facts(true, Some(" "), true, Some("sk-host")), Err(NoKey::HostOff)),
+ (facts(true, Some(""), false, Some(" ")), Err(NoKey::Missing)),
+ (facts(false, Some("sk-space"), false, Some("sk-host")), Err(NoKey::EngineOff)),
+ (facts(false, None, false, None), Err(NoKey::Missing)),
+ ];
+ for (f, want) in cases {
+ assert_eq!(pick(&f), want.map(str::to_string), "{f:?}");
+ }
+ }
+}
diff --git a/src/server/transcribe.rs b/src/server/transcribe.rs
index 591ab664..44b3238a 100644
--- a/src/server/transcribe.rs
+++ b/src/server/transcribe.rs
@@ -3,7 +3,8 @@
//! 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:
+//! embeddings ([`super::openai_key`], shared with `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;
@@ -12,16 +13,21 @@
//!
//! 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).
+//! turn token is refused, so no bot can spend the space's OpenAI money through here.
+//!
+//! Memory: at most [`MAX_AT_ONCE`] recordings are in memory at a time. A request takes its slot
+//! before reading the body, so one waiting for its turn (up to [`QUEUE_WAIT`]) holds no audio, and
+//! one that gets `busy` is never read. A call holds one copy of the audio: the upload to OpenAI
+//! sends that same buffer between the form fields, for the fallback model too.
+//!
+//! 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::openai_key::{self, NoKey};
use super::AppState;
use crate::db::spaces::SpaceId;
-use crate::drivers::engines::EngineId;
-use crate::profiles::Engine;
use axum::{
- body::Body,
+ body::{Body, Bytes, HttpBody},
extract::{Path, Query, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
@@ -30,21 +36,28 @@ use axum::{
use futures::StreamExt;
use serde::Deserialize;
use serde_json::{json, Value};
+use std::collections::VecDeque;
+use std::convert::Infallible;
+use std::pin::Pin;
use std::sync::LazyLock;
+use std::task::{Context, Poll};
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.
+/// Longest wait for OpenAI's answer, per model tried (so up to twice this when the fallback runs).
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`.
+/// Recordings read and sent to OpenAI at the same time, across all spaces. One more waits up to
+/// [`QUEUE_WAIT`] for its turn, before its body is read, then gets 429 `busy`.
pub const MAX_AT_ONCE: usize = 2;
pub const QUEUE_WAIT: Duration = Duration::from_secs(30);
+/// How long an upload may send nothing before it counts as interrupted, so a client that goes
+/// quiet mid-upload gives its slot back instead of holding it until the connection drops.
+pub const READ_STALL: Duration = Duration::from_secs(15);
/// 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";
@@ -54,6 +67,7 @@ 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.";
+pub const WHY_TIMEOUT: &str = "OpenAI didn't answer in time. Try again in a minute.";
/// 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
@@ -95,56 +109,25 @@ impl TranscribeSource {
}
}
-/// 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>,
-}
+pub use super::openai_key::KeyFacts;
-/// The key to use, or why there is none (a sentence for the person). Pure: the order lives here.
+/// The key to use, or why there is none (a sentence for the person), in [`openai_key::pick`]'s
+/// order.
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;
- }
- }
+ openai_key::pick(facts).map_err(why_no_key)
+}
+
+fn why_no_key(no: NoKey) -> &'static str {
+ match no {
+ NoKey::EngineOff => WHY_ENGINE_OFF,
+ NoKey::HostOff => WHY_HOST_OFF,
+ NoKey::Missing => WHY_NO_KEY,
}
- 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 })
+ openai_key::key_for_space(state, space).await.map(|key| TranscribeSource::OpenAi { base: api_base(), key }).map_err(why_no_key)
}
fn api_base() -> String {
@@ -211,7 +194,27 @@ pub struct TranscribeQuery {
pub lang: Option<String>,
}
-static AT_ONCE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(MAX_AT_ONCE));
+/// The [`MAX_AT_ONCE`] slots and the wait for one, one per server ([`AppState::dictation`]).
+pub struct Slots {
+ pub at_once: Semaphore,
+ pub queue_wait: Duration,
+ /// [`READ_STALL`], or a test's shorter one.
+ pub read_stall: Duration,
+}
+
+impl Default for Slots {
+ fn default() -> Self {
+ Self::with_wait(QUEUE_WAIT)
+ }
+}
+
+impl Slots {
+ /// [`MAX_AT_ONCE`] slots with another wait (a test's shorter one).
+ pub fn with_wait(queue_wait: Duration) -> Self {
+ Self { at_once: Semaphore::new(MAX_AT_ONCE), queue_wait, read_stall: READ_STALL }
+ }
+}
+
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
@@ -229,8 +232,9 @@ fn client_for(base: &str) -> reqwest::Client {
/// `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).
+/// recording type, 400 a bad `lang`, 409 `no_transcriber`, 429 `busy` (no slot within
+/// [`QUEUE_WAIT`]); then, holding the slot, 400 `interrupted`, 413 at the byte that passes 25 MB,
+/// 400 `empty_audio`, 502 `transcriber_failed` (see docs/dictation.md).
pub async fn transcribe(
State(state): State<AppState>,
Path(id): Path<String>,
@@ -263,23 +267,15 @@ pub async fn transcribe(
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 {
+ // The slot before the body: a recording waiting for its turn holds no memory, and one that
+ // gets `busy` is never read.
+ let Ok(Ok(_slot)) = tokio::time::timeout(state.dictation.queue_wait, state.dictation.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 audio = match read_audio(body, declared, state.dictation.read_stall).await {
+ Ok(a) => a,
+ Err(bad) => return bad.refusal(),
+ };
let size = audio.len();
match send(&source, audio, file_name, lang.as_deref()).await {
Ok((text, model)) => {
@@ -293,13 +289,49 @@ pub async fn transcribe(
}
}
+/// Why a recording's body was refused while reading it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum BadAudio {
+ Interrupted,
+ TooLarge,
+ Empty,
+}
+
+impl BadAudio {
+ fn refusal(self) -> Response {
+ match self {
+ BadAudio::Interrupted => refusal(StatusCode::BAD_REQUEST, "interrupted", "The recording was interrupted."),
+ BadAudio::TooLarge => too_large(),
+ BadAudio::Empty => refusal(StatusCode::BAD_REQUEST, "empty_audio", "The recording is empty."),
+ }
+ }
+}
+
+/// The whole body, refused at the byte that passes [`MAX_AUDIO_BYTES`], when empty, or as
+/// interrupted once `stall` passes with no bytes (the slot is held while this reads).
+async fn read_audio(body: Body, declared: Option<u64>, stall: Duration) -> Result<Bytes, BadAudio> {
+ 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) = tokio::time::timeout(stall, stream.next()).await.map_err(|_| BadAudio::Interrupted)? {
+ let chunk = chunk.map_err(|_| BadAudio::Interrupted)?;
+ if audio.len() as u64 + chunk.len() as u64 > MAX_AUDIO_BYTES {
+ return Err(BadAudio::TooLarge);
+ }
+ audio.extend_from_slice(&chunk);
+ }
+ if audio.is_empty() {
+ return Err(BadAudio::Empty);
+ }
+ Ok(Bytes::from(audio))
+}
+
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> {
+pub async fn send(source: &TranscribeSource, audio: Bytes, 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)),
@@ -327,41 +359,75 @@ impl Upstream {
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::Timeout => WHY_TIMEOUT,
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);
+/// One `multipart/form-data` body for `/v1/audio/transcriptions`: the form fields, then `audio`
+/// itself (the caller's buffer, not a copy), then the closing boundary.
+fn multipart(boundary: &str, audio: &Bytes, file_name: &str, lang: Option<&str>, model: &str) -> Parts {
+ let mut head = String::with_capacity(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());
+ head.push_str(&format!("--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"));
};
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
+ head.push_str(&format!(
+ "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{file_name}\"\r\nContent-Type: application/octet-stream\r\n\r\n"
+ ));
+ Parts::new([Bytes::from(head), audio.clone(), Bytes::from(format!("\r\n--{boundary}--\r\n"))])
+}
+
+/// A request body sent as a few buffers in turn, with its exact length declared up front (so the
+/// upload has a `Content-Length`, as one buffer would).
+struct Parts {
+ parts: VecDeque<Bytes>,
+ left: u64,
+}
+
+impl Parts {
+ fn new(parts: impl IntoIterator<Item = Bytes>) -> Self {
+ let parts: VecDeque<Bytes> = parts.into_iter().filter(|p| !p.is_empty()).collect();
+ let left = parts.iter().map(|p| p.len() as u64).sum();
+ Self { parts, left }
+ }
}
-async fn send_one(source: &TranscribeSource, audio: &[u8], file_name: &str, lang: Option<&str>, model: &str) -> Result<String, Upstream> {
+impl HttpBody for Parts {
+ type Data = Bytes;
+ type Error = Infallible;
+
+ fn poll_frame(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Result<hyper::body::Frame<Bytes>, Infallible>>> {
+ let next = self.parts.pop_front();
+ if let Some(p) = &next {
+ self.left -= p.len() as u64;
+ }
+ Poll::Ready(next.map(|p| Ok(hyper::body::Frame::data(p))))
+ }
+
+ fn is_end_stream(&self) -> bool {
+ self.parts.is_empty()
+ }
+
+ fn size_hint(&self) -> hyper::body::SizeHint {
+ hyper::body::SizeHint::with_exact(self.left)
+ }
+}
+
+async fn send_one(source: &TranscribeSource, audio: &Bytes, 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))
+ .body(reqwest::Body::wrap(multipart(&boundary, audio, file_name, lang, model)))
.timeout(TIMEOUT)
.send()
.await
@@ -464,19 +530,45 @@ mod tests {
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.");
+ // With the fallback model a call can wait 2 × 60 s, so the reason names no number
+ assert_eq!(Upstream::Timeout.why(), "OpenAI didn't answer in time. Try again in a minute.");
+ }
+
+ /// The parts one after another, as the upload sends them.
+ fn flat(mut parts: Parts) -> Vec<u8> {
+ let declared = parts.size_hint().exact().unwrap();
+ let mut out = Vec::new();
+ let waker = futures::task::noop_waker();
+ let mut cx = Context::from_waker(&waker);
+ while let Poll::Ready(Some(Ok(frame))) = Pin::new(&mut parts).poll_frame(&mut cx) {
+ out.extend_from_slice(&frame.into_data().unwrap());
+ }
+ assert!(parts.is_end_stream());
+ assert_eq!(declared, out.len() as u64, "the declared length is the length sent");
+ out
}
#[test]
fn the_multipart_body_has_the_fields_and_the_bytes() {
- let body = multipart("B", b"\x00\x01RIFF", "audio.wav", Some("de"), MODEL);
+ let audio = Bytes::from_static(b"\x00\x01RIFF");
+ let body = flat(multipart("B", &audio, "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.contains("Content-Type: application/octet-stream\r\n\r\n\u{0}\u{1}RIFF\r\n--B--\r\n"), "{text}");
assert!(text.ends_with("\r\n--B--\r\n"));
- assert!(!String::from_utf8_lossy(&multipart("B", b"x", "audio.webm", None, MODEL)).contains("language"));
+ assert!(!String::from_utf8_lossy(&flat(multipart("B", &Bytes::from_static(b"x"), "audio.webm", None, MODEL))).contains("language"));
+ }
+
+ #[test]
+ fn every_model_tried_sends_the_one_audio_buffer() {
+ let audio = Bytes::from(vec![7u8; 4096]);
+ for model in [MODEL, FALLBACK_MODEL] {
+ let parts = multipart("B", &audio, "audio.webm", None, model);
+ let sent = parts.parts.iter().find(|p| p.len() == audio.len()).expect("the audio is one part");
+ assert_eq!(sent.as_ptr(), audio.as_ptr(), "{model}: the same bytes, not a copy");
+ }
}
}
diff --git a/tests/transcribe_test.rs b/tests/transcribe_test.rs
index 9c3fd6a2..8bd41d39 100644
--- a/tests/transcribe_test.rs
+++ b/tests/transcribe_test.rs
@@ -6,7 +6,7 @@ use axum::{
body::{to_bytes, Body, Bytes},
http::{HeaderMap, Request, StatusCode},
response::{IntoResponse, Response},
- routing::post,
+ routing::{get, post},
Json, Router,
};
use kwnt::{
@@ -17,16 +17,20 @@ use kwnt::{
spaces::{NewSpace, SpaceId, DEFAULT_SPACE_ID},
Database,
},
- drivers::engines::EngineId,
+ drivers::engines::{EngineId, EngineStatus, ProbeEnv},
router::LayaRouter,
- server::{continuity::SelfScope, create_router, transcribe, AppState},
+ mcp::{FixedApprover, McpTurnContext},
+ server::{continuity::SelfScope, create_router, mcp_runtime::PermissionSession, memory_recall, transcribe, AppState},
tools::ToolRunner,
};
+use futures::StreamExt;
use serde_json::{json, Value};
use std::collections::HashSet;
use std::io::Write;
use std::path::Path;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
use tempfile::{tempdir, TempDir};
/// The Default space every fresh database starts with (`spc_default`, not "default").
@@ -37,6 +41,8 @@ use tower::ServiceExt;
type Call = (String, String, Option<String>, String, usize);
static CALLS: Mutex<Vec<Call>> = Mutex::new(Vec::new());
+/// Uploads that came without a `Content-Length` matching their size (a chunked upload).
+static UNSIZED: AtomicUsize = AtomicUsize::new(0);
/// The stub's log. Tests run in parallel, so a panic in one must not poison it for the rest.
fn calls() -> std::sync::MutexGuard<'static, Vec<Call>> {
@@ -70,6 +76,10 @@ async fn stub(headers: HeaderMap, body: Bytes) -> Response {
let model = field(&body, "model").unwrap();
assert_eq!(field(&body, "response_format").as_deref(), Some("json"));
let (file, size) = file_part(&body);
+ let declared = headers.get("content-length").and_then(|h| h.to_str().ok()).and_then(|v| v.parse::<usize>().ok());
+ if declared != Some(body.len()) {
+ UNSIZED.fetch_add(1, Ordering::SeqCst);
+ }
calls().push((key.clone(), model.clone(), field(&body, "language"), file, size));
match (key.as_str(), model.as_str()) {
("sk-bad", _) => (
@@ -87,6 +97,11 @@ async fn stub(headers: HeaderMap, body: Bytes) -> Response {
}
}
+/// The OpenAI API engine check: lists models for any key.
+async fn models() -> Json<Value> {
+ Json(json!({"data": [{"id": "whisper-1"}]}))
+}
+
/// 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 {
@@ -98,7 +113,10 @@ fn stub_base() -> &'static str {
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));
+ let app = Router::new()
+ .route("/v1/audio/transcriptions", post(stub))
+ .route("/v1/models", get(models))
+ .layer(axum::extract::DefaultBodyLimit::max(64 << 20));
axum::serve(listener, app).await.unwrap();
});
});
@@ -110,18 +128,24 @@ fn stub_base() -> &'static str {
}
async fn setup() -> (Router, AppState, TempDir) {
+ setup_with(|_| {}).await
+}
+
+/// [`setup`], with a change to the state before the router is made.
+async fn setup_with(change: impl FnOnce(&mut AppState)) -> (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(
+ let mut state = AppState::new(
config.clone(),
db,
ToolRunner::new(tmp.path().join("workspace")),
PermissionBroker::new(),
LayaRouter::new(config.laya_url.clone()),
);
+ change(&mut state);
(create_router(state.clone()), state, tmp)
}
@@ -196,8 +220,8 @@ async fn with_no_key_it_is_unavailable_and_says_why() {
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);
+ let (code, v) = call(&app, audio_post("spc_missing", "", "audio/webm", vec![1; 10])).await;
+ assert_eq!((code, v["code"].clone()), (StatusCode::NOT_FOUND, json!("not_found")));
}
#[tokio::test]
@@ -356,9 +380,226 @@ async fn refusals_come_before_anything_goes_upstream() {
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;
+ let (code, v) = call(&app, req).await;
assert_eq!(code, StatusCode::FORBIDDEN);
+ assert_eq!(v, json!({"error": "only the person can dictate", "code": "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);
}
+
+/// How many rows `table` has, read straight from the database file.
+async fn rows(tmp: &TempDir, table: &str) -> i64 {
+ let url = format!("sqlite://{}?mode=ro", tmp.path().join("kwnt.db").display());
+ let pool = sqlx::SqlitePool::connect(&url).await.unwrap();
+ let n: i64 = sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {table}")).fetch_one(&pool).await.unwrap();
+ pool.close().await;
+ n
+}
+
+#[tokio::test]
+async fn a_transcription_writes_no_chat_message_and_no_memory() {
+ let (app, state, tmp) = setup().await;
+ space_key(&state, &SpaceId::default_space(), "sk-nowrite").await;
+ let (messages, memories) = (rows(&tmp, "messages").await, rows(&tmp, "kwant_memories").await);
+ let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", vec![5; 4096])).await;
+ assert_eq!(code, StatusCode::OK, "{v}");
+ assert_eq!(calls_with("sk-nowrite").len(), 1);
+ assert_eq!(rows(&tmp, "messages").await, messages, "no chat message");
+ assert_eq!(rows(&tmp, "kwant_memories").await, memories, "no memory");
+}
+
+#[tokio::test]
+async fn an_archived_space_or_the_engine_off_is_refused_before_anything_goes_up() {
+ let (app, state, _tmp) = setup().await;
+ let gone = state
+ .db
+ .create_space(&NewSpace { name: "Gone".into(), icon: "x".into(), color: None, this_machine_enabled: true })
+ .await
+ .unwrap();
+ space_key(&state, &SpaceId::new(&gone.id), "sk-archived").await;
+ state.db.archive_space(&SpaceId::new(&gone.id)).await.unwrap();
+ let (code, v) = call(&app, audio_post(&gone.id, "", "audio/webm", vec![1; 10])).await;
+ assert_eq!(code, StatusCode::CONFLICT);
+ assert_eq!(v["code"], "archived", "{v}");
+
+ // The OpenAI API engine off: the space's own key isn't used either
+ space_key(&state, &SpaceId::default_space(), "sk-engine-off").await;
+ state.engines.set_disabled(HashSet::from([EngineId::OpenaiApi]));
+ let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", vec![1; 10])).await;
+ assert_eq!(code, StatusCode::CONFLICT);
+ assert_eq!(v, json!({"error": transcribe::WHY_ENGINE_OFF, "code": "no_transcriber", "why": transcribe::WHY_ENGINE_OFF}));
+
+ assert!(calls_with("sk-archived").is_empty() && calls_with("sk-engine-off").is_empty());
+}
+
+#[tokio::test]
+async fn an_mcp_session_token_is_refused() {
+ let (app, state, _tmp) = setup().await;
+ space_key(&state, &SpaceId::default_space(), "sk-mcp").await;
+ let ctx = McpTurnContext {
+ servers: vec![],
+ approver: Arc::new(FixedApprover(true)),
+ config_dir: std::env::temp_dir(),
+ permission_url: None,
+ gateway: None,
+ max_tool_iterations: 8,
+ approvals: kwnt::mcp::Approvals::Ask,
+ records: Default::default(),
+ kwnt_only: false,
+ };
+ state.mcp_sessions.lock().await.insert("mcp-turn".into(), PermissionSession::new("k1".into(), "Ada".into(), "t1".into(), ctx, None));
+ let mut req = audio_post(DEF, "", "audio/webm", vec![1; 10]);
+ req.headers_mut().insert("authorization", "Bearer mcp-turn".parse().unwrap());
+ let (code, v) = call(&app, req).await;
+ assert_eq!(code, StatusCode::FORBIDDEN);
+ assert_eq!(v, json!({"error": "only the person can dictate", "code": "forbidden"}));
+ assert!(calls_with("sk-mcp").is_empty());
+}
+
+/// A body that notes when it is first read.
+fn watched_body(read: Arc<AtomicBool>) -> Body {
+ Body::from_stream(futures::stream::once(async move {
+ read.store(true, Ordering::SeqCst);
+ Ok::<_, std::io::Error>(Bytes::from(vec![9u8; 1000]))
+ }))
+}
+
+fn watched_post(read: &Arc<AtomicBool>) -> Request<Body> {
+ Request::post(format!("/api/spaces/{DEF}/transcribe")).header("content-type", "audio/webm").body(watched_body(read.clone())).unwrap()
+}
+
+#[tokio::test]
+async fn while_two_are_held_the_next_waits_unread_then_gets_busy_or_its_turn() {
+ // Its own slots, so the other tests running beside it keep theirs
+ let (app, state, _tmp) = setup_with(|s| s.dictation = Arc::new(transcribe::Slots::with_wait(Duration::from_millis(800)))).await;
+ space_key(&state, &SpaceId::default_space(), "sk-busy").await;
+ let one = state.dictation.at_once.acquire().await.unwrap();
+ let two = state.dictation.at_once.acquire().await.unwrap();
+
+ // Both held past the wait: busy, and not a byte of the body was read
+ let read = Arc::new(AtomicBool::new(false));
+ let (code, v) = call(&app, watched_post(&read)).await;
+ assert_eq!(code, StatusCode::TOO_MANY_REQUESTS);
+ assert_eq!(v["code"], "busy", "{v}");
+ assert!(!read.load(Ordering::SeqCst), "a busy request's body is never read");
+
+ // While it waits for its turn it hasn't read its body either; once a slot frees, it goes
+ let read = Arc::new(AtomicBool::new(false));
+ let waiting = tokio::spawn({
+ let app = app.clone();
+ let req = watched_post(&read);
+ async move { call(&app, req).await }
+ });
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(!read.load(Ordering::SeqCst), "a waiting request holds no audio");
+ drop(one);
+ let (code, v) = waiting.await.unwrap();
+ assert_eq!(code, StatusCode::OK, "{v}");
+ assert!(read.load(Ordering::SeqCst));
+ assert_eq!(calls_with("sk-busy").len(), 1, "only the one that got its turn went up");
+ drop(two);
+}
+
+#[tokio::test]
+async fn a_stalled_upload_is_interrupted_and_gives_its_slot_back() {
+ // Its own slots, and a short stall instead of 15 s
+ let (app, state, _tmp) = setup_with(|s| {
+ s.dictation = Arc::new(transcribe::Slots { read_stall: Duration::from_secs(1), ..Default::default() })
+ })
+ .await;
+ space_key(&state, &SpaceId::default_space(), "sk-stall").await;
+ // Two uploads send 1 KB, then nothing, and never end: both slots are taken
+ let stalled = || {
+ let body = Body::from_stream(futures::stream::once(async { Ok::<_, std::io::Error>(Bytes::from(vec![1u8; 1000])) }).chain(futures::stream::pending()));
+ Request::post(format!("/api/spaces/{DEF}/transcribe")).header("content-type", "audio/webm").body(body).unwrap()
+ };
+ let held: Vec<_> = (0..2)
+ .map(|_| {
+ let (app, req) = (app.clone(), stalled());
+ tokio::spawn(async move { call(&app, req).await })
+ })
+ .collect();
+ let taken = tokio::time::timeout(Duration::from_secs(5), async {
+ while state.dictation.at_once.available_permits() > 0 {
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ });
+ taken.await.expect("both stalled uploads hold a slot while they read");
+
+ // After the stall each one is refused as interrupted, nothing went upstream, and both slots are back
+ for h in held {
+ let (code, v) = tokio::time::timeout(Duration::from_secs(5), h).await.expect("a stalled upload ends").unwrap();
+ assert_eq!(code, StatusCode::BAD_REQUEST, "{v}");
+ assert_eq!(v["code"], "interrupted", "{v}");
+ }
+ assert_eq!(state.dictation.at_once.available_permits(), transcribe::MAX_AT_ONCE);
+ assert!(calls_with("sk-stall").is_empty(), "a stalled upload never goes to OpenAI");
+
+ // A normal recording gets a slot and its text
+ let (code, v) = call(&app, audio_post(DEF, "", "audio/webm", vec![1; 100])).await;
+ assert_eq!(code, StatusCode::OK, "{v}");
+ assert_eq!(calls_with("sk-stall").len(), 1);
+}
+
+#[tokio::test]
+async fn every_upload_declares_its_length() {
+ let (app, state, _tmp) = setup().await;
+ space_key(&state, &SpaceId::default_space(), "sk-sized").await;
+ // No length from the browser; the upload to OpenAI still has one (the stub counts any without)
+ let chunks = (0..3).map(|_| Ok::<_, std::io::Error>(Bytes::from(vec![4u8; 70_000])));
+ 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, StatusCode::OK, "{v}");
+ assert_eq!(calls_with("sk-sized")[0].4, 210_000);
+ assert_eq!(UNSIZED.load(Ordering::SeqCst), 0, "every upload had a Content-Length matching its size");
+}
+
+/// Hybrid recall's embeddings and dictation read one key order (`server::openai_key`): the same
+/// key in each case, and neither when OpenAI is out.
+#[tokio::test]
+async fn recall_and_dictation_pick_the_same_key() {
+ let (_app, state, _tmp) = setup().await;
+ let new_space = |name: &str, this_machine_enabled: bool| {
+ let db = state.db.clone();
+ let name = name.to_string();
+ async move { SpaceId::new(&db.create_space(&NewSpace { name, icon: "x".into(), color: None, this_machine_enabled }).await.unwrap().id) }
+ };
+ state.db.set_setting("openai_api_key", " sk-order-host ").await.unwrap();
+ let both = new_space("Both", true).await;
+ space_key(&state, &both, "sk-order-space").await;
+ let host = new_space("Host", true).await;
+ let off = new_space("Off", false).await;
+ let off_own = new_space("Off own", false).await;
+ space_key(&state, &off_own, "sk-order-own").await;
+
+ let keys = |state: AppState, space: SpaceId| async move {
+ let recall = match memory_recall::source_for_space(&state, &space).await {
+ Some(memory_recall::EmbedSource::OpenAi { key, .. }) => Some(key),
+ _ => None,
+ };
+ let dictation = match transcribe::transcribe_source_for_space(&state, &space).await {
+ Ok(transcribe::TranscribeSource::OpenAi { key, .. }) => Some(key),
+ Err(_) => None,
+ };
+ (recall, dictation)
+ };
+ let s = |k: &str| Some(k.to_string());
+ // The one difference, on purpose (#630): until the OpenAI API engine's check has passed,
+ // recall leaves the host's key alone (a revoked key isn't retried every minute in the
+ // background); dictation, which the person starts, still tries it. A space's own key is
+ // used by both either way.
+ assert_ne!(state.engines.report(EngineId::OpenaiApi).status, EngineStatus::Ready);
+ assert_eq!(keys(state.clone(), host.clone()).await, (None, s("sk-order-host")), "host key before the check");
+ assert_eq!(keys(state.clone(), both.clone()).await, (s("sk-order-space"), s("sk-order-space")), "space key before the check");
+ let env = ProbeEnv { openai_key: s("sk-order-host"), openai_base: stub_base().to_string(), ..ProbeEnv::default() };
+ state.engines.recheck_one(EngineId::OpenaiApi, &env).await;
+ assert_eq!(state.engines.report(EngineId::OpenaiApi).status, EngineStatus::Ready);
+ for (space, want) in [(&both, s("sk-order-space")), (&host, s("sk-order-host")), (&off, None), (&off_own, s("sk-order-own"))] {
+ assert_eq!(keys(state.clone(), space.clone()).await, (want.clone(), want), "{space}");
+ }
+ state.engines.set_disabled(HashSet::from([EngineId::OpenaiApi]));
+ for space in [&both, &host, &off, &off_own] {
+ assert_eq!(keys(state.clone(), space.clone()).await, (None, None), "engine off: {space}");
+ }
+}