YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Code Optimisations (#2347)
Leigh Phillips3670f262a43b
diff --git a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsxindex f3a63343c..bfdff7164 100644--- a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx+++ b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx@@ -562,14 +562,16 @@ export function RecordingSettings() {}}, [allOpenAIModels, filterTranscriptionModels]);- // Fetch models when OpenAI Compatible is selected and endpoint changes+ // Fetch models when OpenAI Compatible is selected - manually triggered+ // (not on every keystroke - only on focus change or enter key)useEffect(() => {if (settings.audioTranscriptionEngine === 'openai-compatible') {- const endpoint = settings.openaiCompatibleEndpoint || 'http://127.0.0.1:8080';const apiKey = settings.openaiCompatibleApiKey;+ // Use default endpoint if not set+ const endpoint = settings.openaiCompatibleEndpoint || 'http://127.0.0.1:8080';fetchOpenAIModels(endpoint, apiKey);}- }, [settings.audioTranscriptionEngine, settings.openaiCompatibleEndpoint, settings.openaiCompatibleApiKey, fetchOpenAIModels]);+ }, [settings.audioTranscriptionEngine, settings.openaiCompatibleApiKey, fetchOpenAIModels]);// Run transcription diagnostics (endpoint → auth → models → transcription test)const runTranscriptionDiagnostics = useCallback(async () => {@@ -1400,6 +1402,12 @@ Your screen is a pipe. Everything you see, hear, and type flows through it. Screlabel=""value={settings.openaiCompatibleEndpoint || "http://127.0.0.1:8080"}onChange={(value: string) => handleSettingsChange({ openaiCompatibleEndpoint: value }, true)}+ onBlur={() => fetchOpenAIModels(settings.openaiCompatibleEndpoint || 'http://127.0.0.1:8080', settings.openaiCompatibleApiKey)}+ onKeyDown={(e: React.KeyboardEvent) => {+ if (e.key === 'Enter') {+ fetchOpenAIModels(settings.openaiCompatibleEndpoint || 'http://127.0.0.1:8080', settings.openaiCompatibleApiKey);+ }+ }}placeholder="API Endpoint (e.g., http://127.0.0.1:8080)"className="h-7 text-xs"/>diff --git a/apps/screenpipe-app-tauri/components/ui/validated-input.tsx b/apps/screenpipe-app-tauri/components/ui/validated-input.tsxindex db5b91339..c7c8bdbca 100644--- a/apps/screenpipe-app-tauri/components/ui/validated-input.tsx+++ b/apps/screenpipe-app-tauri/components/ui/validated-input.tsx@@ -35,6 +35,8 @@ export const ValidatedInput = React.forwardRef<HTMLInputElement, ValidatedInputPmaxLength,minLength,className,+ onBlur,+ onKeyDown,...props}, ref) => {const [value, setValue] = useState(props.value?.toString() || "");@@ -138,7 +140,13 @@ export const ValidatedInput = React.forwardRef<HTMLInputElement, ValidatedInputP{...props}value={value}onChange={handleChange}- onBlur={() => setIsTouched(true)}+ onBlur={(e) => {+ setIsTouched(true);+ onBlur?.(e);+ }}+ onKeyDown={(e) => {+ onKeyDown?.(e);+ }}className={cn(getInputVariant(),showValidationIcon && "pr-10",diff --git a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rsindex fdaa38e55..5fa42face 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs@@ -165,6 +165,7 @@ pub async fn start_embedded_server(api_key: config.openai_compatible_api_key.clone(),model: config.openai_compatible_model.clone().unwrap_or_else(|| "whisper-1".to_string()),+ client: None, // Will be created in TranscriptionEngine::new() if needed})} else {Nonediff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rsindex fd9857122..14ec9e62e 100644--- a/crates/screenpipe-audio/src/audio_manager/manager.rs+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs@@ -418,6 +418,7 @@ impl AudioManager {let engine = TranscriptionEngine::new(audio_transcription_engine.clone(),deepgram_api_key.clone(),+ openai_compatible_config.clone(),languages.clone(),vocabulary.clone(),)diff --git a/crates/screenpipe-audio/src/lib.rs b/crates/screenpipe-audio/src/lib.rsindex e9f3ff510..274c153e7 100644--- a/crates/screenpipe-audio/src/lib.rs+++ b/crates/screenpipe-audio/src/lib.rs@@ -7,6 +7,7 @@ pub mod utils;pub mod vad;pub use transcription::stt::stt;pub use transcription::{AudioInput, TranscriptionResult};+pub use transcription::engine::TranscriptionEngine;pub mod speaker;pub mod transcription;pub use transcription::stt::OpenAICompatibleConfig;diff --git a/crates/screenpipe-audio/src/transcription/engine.rs b/crates/screenpipe-audio/src/transcription/engine.rsindex 549a0c32c..46a84dcc1 100644--- a/crates/screenpipe-audio/src/transcription/engine.rs+++ b/crates/screenpipe-audio/src/transcription/engine.rs@@ -4,12 +4,14 @@use crate::core::engine::AudioTranscriptionEngine;use crate::transcription::deepgram::batch::transcribe_with_deepgram;+use crate::transcription::openai_compatible::batch::transcribe_with_openai_compatible;use crate::transcription::whisper::batch::process_with_whisper;use crate::transcription::whisper::model::{create_whisper_context_parameters, download_whisper_model,};use crate::transcription::VocabularyEntry;use anyhow::{anyhow, Result};+use reqwest::Client;use screenpipe_core::Language;use std::sync::Arc;#[cfg(feature = "qwen3-asr")]@@ -37,6 +39,14 @@ pub enum TranscriptionEngine {languages: Vec<Language>,vocabulary: Vec<VocabularyEntry>,},+ OpenAICompatible {+ endpoint: String,+ api_key: Option<String>,+ model: String,+ client: Arc<Client>,+ languages: Vec<Language>,+ vocabulary: Vec<VocabularyEntry>,+ },Disabled,}@@ -45,6 +55,7 @@ impl TranscriptionEngine {pub async fn new(config: Arc<AudioTranscriptionEngine>,deepgram_api_key: Option<String>,+ openai_compatible_config: Option<crate::transcription::stt::OpenAICompatibleConfig>,languages: Vec<Language>,vocabulary: Vec<VocabularyEntry>,) -> Result<Self> {@@ -60,6 +71,26 @@ impl TranscriptionEngine {})}+ AudioTranscriptionEngine::OpenAICompatible => {+ let oc_config = openai_compatible_config.unwrap_or_default();+ let client = oc_config.client.unwrap_or_else(|| {+ Arc::new(+ Client::builder()+ .timeout(std::time::Duration::from_secs(55))+ .build()+ .expect("failed to create reqwest client"),+ )+ });+ Ok(Self::OpenAICompatible {+ endpoint: oc_config.endpoint,+ api_key: oc_config.api_key,+ model: oc_config.model,+ client,+ languages,+ vocabulary,+ })+ }+AudioTranscriptionEngine::Qwen3Asr => {#[cfg(feature = "qwen3-asr")]{@@ -158,6 +189,21 @@ impl TranscriptionEngine {languages: languages.clone(),vocabulary: vocabulary.clone(),}),+ Self::OpenAICompatible {+ endpoint,+ api_key,+ model,+ client,+ languages,+ vocabulary,+ } => Ok(TranscriptionSession::OpenAICompatible {+ endpoint: endpoint.clone(),+ api_key: api_key.clone(),+ model: model.clone(),+ client: client.clone(),+ languages: languages.clone(),+ vocabulary: vocabulary.clone(),+ }),Self::Disabled => Ok(TranscriptionSession::Disabled),}}@@ -177,6 +223,7 @@ impl TranscriptionEngine {#[cfg(feature = "qwen3-asr")]Self::Qwen3Asr { .. } => AudioTranscriptionEngine::Qwen3Asr,Self::Deepgram { .. } => AudioTranscriptionEngine::Deepgram,+ Self::OpenAICompatible { .. } => AudioTranscriptionEngine::OpenAICompatible,Self::Disabled => AudioTranscriptionEngine::Disabled,}}@@ -203,6 +250,14 @@ pub enum TranscriptionSession {languages: Vec<Language>,vocabulary: Vec<VocabularyEntry>,},+ OpenAICompatible {+ endpoint: String,+ api_key: Option<String>,+ model: String,+ client: Arc<Client>,+ languages: Vec<Language>,+ vocabulary: Vec<VocabularyEntry>,+ },Disabled,}@@ -270,6 +325,40 @@ impl TranscriptionSession {vocabulary,..} => process_with_whisper(audio, languages.clone(), state, vocabulary).await,++ Self::OpenAICompatible {+ endpoint,+ api_key,+ model,+ client,+ languages,+ vocabulary,+ } => {+ // Convert vocabulary entries to words for the API+ let vocab_words: Vec<String> = vocabulary.iter().map(|v| v.word.clone()).collect();+ match transcribe_with_openai_compatible(+ Some(client.clone()),+ endpoint,+ api_key.as_deref(),+ model,+ audio,+ device,+ sample_rate,+ languages.clone(),+ &vocab_words,+ )+ .await+ {+ Ok(t) => Ok(t),+ Err(e) => {+ error!(+ "device: {}, openai compatible transcription failed: {:?}",+ device, e+ );+ Err(e)+ }+ }+ }};// Post-processing: apply vocabulary replacements@@ -280,6 +369,7 @@ impl TranscriptionSession {#[cfg(feature = "qwen3-asr")]Self::Qwen3Asr { vocabulary, .. } => vocabulary,Self::Deepgram { vocabulary, .. } => vocabulary,+ Self::OpenAICompatible { vocabulary, .. } => vocabulary,Self::Disabled => return Ok(text),};for entry in vocab {diff --git a/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rs b/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rsindex 7317141d2..02e0b6f2e 100644--- a/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rs+++ b/crates/screenpipe-audio/src/transcription/openai_compatible/batch.rs@@ -8,6 +8,7 @@ use reqwest::{multipart, Client, Response};use screenpipe_core::Language;use serde_json::Value;use std::io::Cursor;+use std::sync::Arc;use std::time::Duration;use tracing::{debug, error, info};@@ -17,6 +18,7 @@ use tracing::{debug, error, info};/// audio transcriptions API format (e.g., mlx-audio, llama.cpp, vLLM, etc.)////// # Arguments+/// * `client` - Optional shared reqwest client for connection pooling. If None, creates a new client./// * `endpoint` - Base URL of the API (e.g., "http://127.0.0.1:8080")/// * `api_key` - Optional API key for authentication/// * `model` - Model ID to use for transcription@@ -27,6 +29,7 @@ use tracing::{debug, error, info};/// * `vocabulary` - Optional vocabulary/hotwords passed as `prompt` field/// (used by VibeVoice-ASR `--context`, Whisper `--initial-prompt`, etc.)pub async fn transcribe_with_openai_compatible(+ client: Option<Arc<Client>>,endpoint: &str,api_key: Option<&str>,model: &str,@@ -44,9 +47,16 @@ pub async fn transcribe_with_openai_compatible(// Create a WAV file in memorylet wav_data = create_wav_file(audio_data, sample_rate)?;- // Build the request (with timeout to prevent hanging on unresponsive endpoints)- let client = Client::builder().timeout(Duration::from_secs(30)).build()?;-+ // Use provided client or create a new one+ let client = match client {+ Some(c) => c,+ None => Arc::new(+ Client::builder()+ .timeout(Duration::from_secs(55))+ .build()?+ ),+ };+// Build multipart formlet mut form = multipart::Form::new().text("model", model.to_string())diff --git a/crates/screenpipe-audio/src/transcription/stt.rs b/crates/screenpipe-audio/src/transcription/stt.rsindex 070008313..48d9e94a4 100644--- a/crates/screenpipe-audio/src/transcription/stt.rs+++ b/crates/screenpipe-audio/src/transcription/stt.rs@@ -18,6 +18,7 @@ use crate::utils::audio::resample;use crate::utils::ffmpeg::{get_new_file_path, write_audio_to_file};use crate::vad::VadEngine;use anyhow::Result;+use reqwest::Client;use screenpipe_core::Language;use std::path::PathBuf;use std::{sync::Arc, sync::Mutex as StdMutex};@@ -50,11 +51,23 @@ impl AlternateStt for audiopipe::Model {}/// Configuration for OpenAI Compatible transcription engine-#[derive(Clone, Debug, Default)]+#[derive(Clone, Debug)]pub struct OpenAICompatibleConfig {pub endpoint: String,pub api_key: Option<String>,pub model: String,+ pub client: Option<Arc<Client>>,+}++impl Default for OpenAICompatibleConfig {+ fn default() -> Self {+ Self {+ endpoint: "http://127.0.0.1:8080".to_string(),+ api_key: None,+ model: "whisper-1".to_string(),+ client: None,+ }+ }}#[allow(clippy::too_many_arguments)]@@ -146,11 +159,13 @@ pub async fn stt(endpoint: "http://127.0.0.1:8080".to_string(),api_key: None,model: "whisper-1".to_string(),+ client: None,});// Collect vocabulary words for the prompt/context fieldlet vocab_words: Vec<String> = vocabulary.iter().map(|v| v.word.clone()).collect();match transcribe_with_openai_compatible(+ config.client.clone(),&config.endpoint,config.api_key.as_deref(),&config.model,diff --git a/crates/screenpipe-server/src/routes/retranscribe.rs b/crates/screenpipe-server/src/routes/retranscribe.rsindex da63b608b..85ae14ec0 100644--- a/crates/screenpipe-server/src/routes/retranscribe.rs+++ b/crates/screenpipe-server/src/routes/retranscribe.rs@@ -116,7 +116,7 @@ pub async fn retranscribe_handler(};let deepgram_api_key = audio_manager.deepgram_api_key().await;- let _openai_compatible_config = audio_manager.openai_compatible_config().await;+ let openai_compatible_config = audio_manager.openai_compatible_config().await;let languages = audio_manager.languages().await;// Build effective vocabulary: user-provided + prompt words as bias entries@@ -137,6 +137,7 @@ pub async fn retranscribe_handler(let transcription_engine = match TranscriptionEngine::new(engine.clone(),deepgram_api_key,+ openai_compatible_config,languages,effective_vocabulary,)