Skip to content

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

refactor: remove dead realtime WebSocket streaming code

Louis Beaumont679006498936
diff --git a/Cargo.lock b/Cargo.lock
index 3a968c00a..7d2cb23fd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -639,7 +639,7 @@ dependencies = [
"sha1 0.10.6",
"sync_wrapper",
"tokio",
- "tokio-tungstenite 0.24.0",
+ "tokio-tungstenite",
"tower 0.5.3",
"tower-layer",
"tower-service",
@@ -1789,33 +1789,6 @@ dependencies = [
"uuid",
]
-[[package]]
-name = "deepgram"
-version = "0.6.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b7e55d68eeaf55308feb5cb6e948d49efa8564d0536a7375d8a9e06acbb5773a"
-dependencies = [
- "anyhow",
- "bytes",
- "futures",
- "http",
- "pin-project",
- "reqwest",
- "serde",
- "serde_json",
- "serde_urlencoded",
- "sha256",
- "thiserror 2.0.18",
- "tokio",
- "tokio-stream",
- "tokio-tungstenite 0.27.0",
- "tokio-util",
- "tracing",
- "tungstenite 0.27.0",
- "url",
- "uuid",
-]
-
[[package]]
name = "delegate"
version = "0.13.5"
@@ -2702,11 +2675,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
- "js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
- "wasm-bindgen",
]
[[package]]
@@ -3129,7 +3100,6 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
- "webpki-roots 1.0.6",
]
[[package]]
@@ -3977,12 +3947,6 @@ dependencies = [
"hashbrown 0.16.1",
]
-[[package]]
-name = "lru-slab"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
-
[[package]]
name = "lzma-sys"
version = "0.1.20"
@@ -5667,61 +5631,6 @@ dependencies = [
"memchr",
]
-[[package]]
-name = "quinn"
-version = "0.11.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
-dependencies = [
- "bytes",
- "cfg_aliases",
- "pin-project-lite",
- "quinn-proto",
- "quinn-udp",
- "rustc-hash 2.1.1",
- "rustls",
- "socket2 0.6.3",
- "thiserror 2.0.18",
- "tokio",
- "tracing",
- "web-time",
-]
-
-[[package]]
-name = "quinn-proto"
-version = "0.11.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
-dependencies = [
- "bytes",
- "getrandom 0.3.4",
- "lru-slab",
- "rand 0.9.2",
- "ring",
- "rustc-hash 2.1.1",
- "rustls",
- "rustls-pki-types",
- "slab",
- "thiserror 2.0.18",
- "tinyvec",
- "tracing",
- "web-time",
-]
-
-[[package]]
-name = "quinn-udp"
-version = "0.5.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
-dependencies = [
- "cfg_aliases",
- "libc",
- "once_cell",
- "socket2 0.6.3",
- "tracing",
- "windows-sys 0.60.2",
-]
-
[[package]]
name = "quote"
version = "1.0.45"
@@ -6028,10 +5937,7 @@ dependencies = [
"once_cell",
"percent-encoding",
"pin-project-lite",
- "quinn",
- "rustls",
"rustls-pemfile",
- "rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
@@ -6039,7 +5945,6 @@ dependencies = [
"system-configuration",
"tokio",
"tokio-native-tls",
- "tokio-rustls",
"tokio-util",
"tower 0.5.3",
"tower-service",
@@ -6048,7 +5953,6 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
- "webpki-roots 0.26.11",
"windows-registry",
]
@@ -6350,7 +6254,6 @@ version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
dependencies = [
- "web-time",
"zeroize",
]
@@ -6523,7 +6426,6 @@ dependencies = [
"criterion",
"crossbeam",
"dashmap",
- "deepgram",
"dirs 5.0.1",
"env_logger",
"esaxx-rs",
@@ -6729,7 +6631,7 @@ dependencies = [
"tempfile",
"tokio",
"tokio-stream",
- "tokio-tungstenite 0.24.0",
+ "tokio-tungstenite",
"tokio-util",
"tower 0.4.13",
"tower-http",
@@ -7202,19 +7104,6 @@ dependencies = [
"digest 0.11.2",
]
-[[package]]
-name = "sha256"
-version = "1.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f880fc8562bdeb709793f00eb42a2ad0e672c4f883bbe59122b926eca935c8f6"
-dependencies = [
- "async-trait",
- "bytes",
- "hex",
- "sha2 0.10.9",
- "tokio",
-]
-
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -8263,23 +8152,7 @@ dependencies = [
"futures-util",
"log",
"tokio",
- "tungstenite 0.24.0",
-]
-
-[[package]]
-name = "tokio-tungstenite"
-version = "0.27.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "489a59b6730eda1b0171fcfda8b121f4bee2b35cba8645ca35c5f7ba3eb736c1"
-dependencies = [
- "futures-util",
- "log",
- "rustls",
- "rustls-pki-types",
- "tokio",
- "tokio-rustls",
- "tungstenite 0.27.0",
- "webpki-roots 0.26.11",
+ "tungstenite",
]
[[package]]
@@ -8618,25 +8491,6 @@ dependencies = [
"utf-8",
]
-[[package]]
-name = "tungstenite"
-version = "0.27.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eadc29d668c91fcc564941132e17b28a7ceb2f3ebf0b9dae3e03fd7a6748eb0d"
-dependencies = [
- "bytes",
- "data-encoding",
- "http",
- "httparse",
- "log",
- "rand 0.9.2",
- "rustls",
- "rustls-pki-types",
- "sha1 0.10.6",
- "thiserror 2.0.18",
- "utf-8",
-]
-
[[package]]
name = "typenum"
version = "1.19.0"
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index cbe84f2d5..2a5a4e331 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -192,6 +192,14 @@ async getAudioDevices() : Promise<Result<AudioDeviceInfo[], string>> {
async isEnterpriseBuildCmd() : Promise<boolean> {
return await TAURI_INVOKE("is_enterprise_build_cmd");
},
+/**
+ * Read the enterprise license key from `enterprise.json` next to the executable.
+ * Admins push this file via Intune/MDM to a protected directory (e.g. Program Files)
+ * that employees cannot modify. Returns None if the file doesn't exist or is invalid.
+ */
+async getEnterpriseLicenseKey() : Promise<string | null> {
+ return await TAURI_INVOKE("get_enterprise_license_key");
+},
async getDiskUsage(forceRefresh: boolean | null, dataDir: string | null) : Promise<Result<JsonValue, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("get_disk_usage", { forceRefresh, dataDir }) };
@@ -656,7 +664,9 @@ async piInstall() : Promise<Result<null, string>> {
}
},
/**
- * Send a prompt to Pi, optionally with images
+ * Send a prompt to Pi, optionally with images.
+ * The command is serialized through the queue — it will wait for any prior
+ * command (new_session, abort) to fully complete before being written to stdin.
*/
async piPrompt(sessionId: string | null, message: string, images: PiImageContent[] | null) : Promise<Result<null, string>> {
try {
@@ -667,7 +677,8 @@ async piPrompt(sessionId: string | null, message: string, images: PiImageContent
}
},
/**
- * Abort current Pi operation. Waits for the Pi SDK to confirm the abort completed.
+ * Abort current Pi operation. Priority command — cancels all pending commands
+ * in the queue and sends abort directly. Waits for the SDK's done event.
*/
async piAbort(sessionId: string | null) : Promise<Result<null, string>> {
try {
@@ -679,7 +690,8 @@ async piAbort(sessionId: string | null) : Promise<Result<null, string>> {
},
/**
* Start a new Pi session (clears conversation history).
- * Waits for the Pi SDK to finish aborting any in-flight work and resetting state.
+ * Serialized through the queue — waits for any in-flight work to complete,
+ * then sends new_session and waits for the SDK's done event before returning.
*/
async piNewSession(sessionId: string | null) : Promise<Result<null, string>> {
try {
@@ -983,7 +995,7 @@ apiKey: string | null;
/**
* Max output tokens (default 4096)
*/
-maxTokens?: number;
+maxTokens?: number;
/**
* Optional system prompt from AI preset (appended to Pi's built-in system prompt)
*/
@@ -991,42 +1003,181 @@ systemPrompt?: string | null }
export type PipeSuggestionsSettings = { enabled: boolean; frequencyHours: number }
export type SettingsStore =
/**
- * Catch-all for fields added by the frontend (e.g. chatHistory, deviceId)
- * that the Rust struct doesn't know about. Without this, `save()` would
- * serialize only known fields and silently wipe frontend-only data.
+ * All recording/capture config lives here. Flattened so the JSON shape
+ * is unchanged — `disableAudio`, `port`, `fps`, etc. stay at the top level.
*/
-({ [key in string]: null | boolean | number | string | JsonValue[] | { [key in string]: JsonValue } }) & { aiPresets: AIPreset[]; deepgramApiKey: string; isLoading: boolean; userId: string;
+({
/**
- * Persistent analytics ID used for PostHog tracking (both frontend and backend)
+ * Disable all audio capture and transcription.
*/
-analyticsId: string; devMode: boolean; audioTranscriptionEngine: string; ocrEngine: string; monitorIds: string[]; audioDevices: string[];
+disableAudio: boolean;
/**
- * When true, automatically follow system default audio devices
+ * Audio transcription engine identifier.
+ * Values: "whisper-large-v3-turbo", "whisper-large-v3-turbo-quantized",
+ * "deepgram", "screenpipe-cloud", etc.
*/
-useSystemDefaultAudio?: boolean; usePiiRemoval: boolean;
+audioTranscriptionEngine: string;
/**
- * Filter music-dominant audio before transcription using spectral analysis
+ * Transcription mode: "realtime" or "batch".
+ * Previously stored in SettingsStore.extra["transcriptionMode"].
*/
-filterMusic?: boolean; port: number; dataDir: string; disableAudio: boolean; ignoredWindows: string[]; includedWindows: string[]; ignoredUrls?: string[]; fps: number; vadSensitivity: string; analyticsEnabled: boolean; audioChunkDuration: number; useChineseMirror: boolean; languages: string[]; embeddedLLM: EmbeddedLLM; autoStartEnabled: boolean; platform: string; disabledShortcuts: string[]; user: User; showScreenpipeShortcut: string; startRecordingShortcut: string; stopRecordingShortcut: string; startAudioShortcut: string; stopAudioShortcut: string; showChatShortcut: string; searchShortcut: string; lockVaultShortcut?: string; realtimeAudioTranscriptionEngine: string; disableVision: boolean;
+transcriptionMode: string;
/**
- * When true, screen capture continues but OCR text extraction is skipped.
- * Reduces CPU usage significantly while still recording video.
+ * Audio device names/IDs to capture from.
*/
-disableOcr?: boolean; useAllMonitors: boolean; adaptiveFps?: boolean; showShortcutOverlay?: boolean;
+audioDevices: string[];
/**
- * Unique device ID for AI usage tracking (generated on first launch)
+ * Automatically follow the system default audio devices.
*/
-deviceId?: string;
+useSystemDefaultAudio: boolean;
+/**
+ * Duration of each audio chunk in seconds before transcription.
+ * Stored as i32 to match existing store.bin schema (cast to u64 by engine).
+ */
+audioChunkDuration: number;
+/**
+ * Deepgram API key for cloud transcription.
+ * Empty string or "default" means not configured.
+ * Kept as String (not Option) to match existing store.bin schema.
+ */
+deepgramApiKey: string;
+/**
+ * VAD sensitivity level: "low", "medium", "high".
+ */
+vadSensitivity: string;
+/**
+ * Filter music-dominant audio before transcription using spectral analysis.
+ */
+filterMusic: boolean;
+/**
+ * Maximum batch duration in seconds for batch transcription.
+ * None = use engine-aware defaults (Deepgram=3600s, Whisper/OpenAI=600s).
+ * Previously stored in SettingsStore.extra["batchMaxDurationSecs"].
+ */
+batchMaxDurationSecs?: bigint | null;
+/**
+ * Custom vocabulary for transcription biasing and word replacement.
+ * Previously stored in SettingsStore.extra["vocabularyWords"].
+ */
+vocabularyWords?: VocabEntry[];
+/**
+ * Disable all screen capture.
+ */
+disableVision: boolean;
+/**
+ * Specific monitor IDs to capture.
+ */
+monitorIds: string[];
+/**
+ * Capture from all connected monitors.
+ */
+useAllMonitors: boolean;
+/**
+ * Target frames per second for screen capture.
+ */
+fps: number;
+/**
+ * Dynamically adjust FPS based on screen content changes.
+ */
+adaptiveFps: boolean;
+/**
+ * Video quality preset: "low", "balanced", "high", "max".
+ */
+videoQuality: string;
+/**
+ * Window titles to exclude from capture.
+ */
+ignoredWindows: string[];
+/**
+ * Window titles to exclusively capture (empty = capture all).
+ */
+includedWindows: string[];
+/**
+ * URLs to exclude from capture.
+ */
+ignoredUrls?: string[];
+/**
+ * Automatically detect and skip incognito / private browsing windows.
+ */
+ignoreIncognitoWindows: boolean;
+/**
+ * Languages for transcription (ISO 639-1 codes).
+ */
+languages: string[];
+/**
+ * Redact personally identifiable information from transcriptions.
+ */
+usePiiRemoval: boolean;
+/**
+ * Screenpipe cloud user ID. Empty string means not logged in.
+ * Kept as String (not Option) to match existing store.bin schema.
+ */
+userId: string;
+/**
+ * Display name for speaker identification.
+ * Fallback chain: this field → cloud auth name → cloud auth email.
+ * Previously stored in SettingsStore.extra["userName"].
+ */
+userName?: string | null;
+/**
+ * OpenAI-compatible transcription endpoint URL.
+ * Previously stored in SettingsStore.extra["openaiCompatibleEndpoint"].
+ */
+openaiCompatibleEndpoint?: string | null;
+/**
+ * OpenAI-compatible transcription API key.
+ * Previously stored in SettingsStore.extra["openaiCompatibleApiKey"].
+ */
+openaiCompatibleApiKey?: string | null;
+/**
+ * OpenAI-compatible transcription model name.
+ * Previously stored in SettingsStore.extra["openaiCompatibleModel"].
+ */
+openaiCompatibleModel?: string | null;
+/**
+ * HTTP server port for the screenpipe API.
+ */
+port: number;
+/**
+ * Power mode preference: "auto", "performance", "battery_saver".
+ * Previously stored in SettingsStore.extra["powerMode"].
+ */
+powerMode?: string | null;
+/**
+ * Use Chinese mirror for Hugging Face model downloads.
+ */
+useChineseMirror: boolean;
+/**
+ * Enable anonymous analytics (PostHog).
+ */
+analyticsEnabled: boolean;
+/**
+ * Persistent analytics ID (UUID, stable across sessions).
+ */
+analyticsId: string;
/**
* Enable input event capture (keyboard, mouse, clipboard).
- * Requires input monitoring permission on macOS.
*/
-enableInputCapture?: boolean;
+enableInputCapture: boolean;
/**
* Enable accessibility text capture (AX tree walker).
- * Requires accessibility permission on macOS.
*/
-enableAccessibility?: boolean;
+enableAccessibility: boolean }) &
+/**
+ * Catch-all for fields added by the frontend (e.g. chatHistory)
+ * that the Rust struct doesn't know about. Without this, `save()` would
+ * serialize only known fields and silently wipe frontend-only data.
+ */
+({ [key in string]: null | boolean | number | string | JsonValue[] | { [key in string]: JsonValue } }) & { aiPresets: AIPreset[]; isLoading: boolean; devMode: boolean; ocrEngine: string; dataDir: string; embeddedLLM: EmbeddedLLM; autoStartEnabled: boolean; platform: string; disabledShortcuts: string[]; user: User; showScreenpipeShortcut: string; startRecordingShortcut: string; stopRecordingShortcut: string; startAudioShortcut: string; stopAudioShortcut: string; showChatShortcut: string; searchShortcut: string; lockVaultShortcut?: string; realtimeAudioTranscriptionEngine: string;
+/**
+ * When true, screen capture continues but OCR text extraction is skipped.
+ * Reduces CPU usage significantly while still recording video.
+ */
+disableOcr?: boolean; showShortcutOverlay?: boolean;
+/**
+ * Unique device ID for AI usage tracking (generated on first launch)
+ */
+deviceId?: string;
/**
* Auto-install updates and restart when a new version is available.
* When disabled, users must click "update now" in the tray menu.
@@ -1042,22 +1193,15 @@ overlayMode?: string;
* Disabled by default so the overlay doesn't appear in screenpipe's own recordings.
*/
showOverlayInScreenRecording?: boolean;
-/**
- * Video quality preset controlling storage vs quality tradeoff.
- * Affects H.265 CRF during recording and JPEG quality during frame extraction.
- * Values: "low", "balanced", "high", "max". Default: "balanced".
- */
-videoQuality?: string;
/**
* When true, the chat window stays above all other windows (default: true).
*/
chatAlwaysOnTop?: boolean;
/**
- * Automatically detect and skip incognito / private browsing windows.
- * Uses localized title matching (20+ languages) and on macOS, native
- * AppleScript detection for Chromium browsers.
+ * Show restart notifications when audio/vision capture stalls.
+ * Disabled by default for now until the stall detector is more reliable.
*/
-ignoreIncognitoWindows?: boolean }
+showRestartNotifications?: boolean }
export type ShowRewindWindow = "Main" | { Home: { page: string | null } } | { Search: { query: string | null } } | "Onboarding" | "Chat" | "PermissionRecovery"
export type Suggestion = { text: string }
/**
@@ -1073,6 +1217,18 @@ export type SyncDeviceInfo = { id: string; deviceId: string; deviceName: string
*/
export type SyncStatusResponse = { enabled: boolean; isSyncing: boolean; lastSync: string | null; lastError: string | null; storageUsed: bigint | null; storageLimit: bigint | null; deviceCount: number | null; deviceLimit: number | null; syncTier: string | null; machineId: string }
export type User = { id: string | null; name: string | null; email: string | null; image: string | null; token: string | null; clerk_id: string | null; api_key: string | null; credits: Credits | null; stripe_connected: boolean | null; stripe_account_status: string | null; github_username: string | null; bio: string | null; website: string | null; contact: string | null; cloud_subscribed: boolean | null; credits_balance: number | null }
+/**
+ * Custom vocabulary entry for transcription biasing and word replacement.
+ */
+export type VocabEntry = {
+/**
+ * The word or phrase to bias toward during transcription.
+ */
+word: string;
+/**
+ * Optional replacement — if set, the transcribed `word` is replaced with this.
+ */
+replace_with?: string | null }
/** tauri-specta globals **/
diff --git a/crates/screenpipe-audio/Cargo.toml b/crates/screenpipe-audio/Cargo.toml
index f4fb9ab56..31bcfcd2c 100644
--- a/crates/screenpipe-audio/Cargo.toml
+++ b/crates/screenpipe-audio/Cargo.toml
@@ -82,7 +82,6 @@ ort = { version = "=2.0.0-rc.6", default-features = false, features = ["ndarray"
ort-sys = { version = "=2.0.0-rc.6", default-features = false }
knf-rs = "0.3.2"
futures = "0.3.31"
-deepgram = "0.6.4"
audiopipe = { git = "https://github.com/screenpipe/audiopipe.git", rev = "b199cf5b3d1e0e87604f02910240a2bc8851cf9a", default-features = false, features = ["qwen3-asr-antirez-blas"], optional = true }
bytes = { version = "1.9.0", features = ["serde"] }
rand = "0.9.0"
diff --git a/crates/screenpipe-audio/src/audio_manager/builder.rs b/crates/screenpipe-audio/src/audio_manager/builder.rs
index 4b45efdc5..341c8fa59 100644
--- a/crates/screenpipe-audio/src/audio_manager/builder.rs
+++ b/crates/screenpipe-audio/src/audio_manager/builder.rs
@@ -44,14 +44,12 @@ pub struct AudioManagerOptions {
/// Configuration for OpenAI Compatible transcription engine
pub openai_compatible_config: Option<OpenAICompatibleConfig>,
pub enable_diarization: bool,
- pub enable_realtime: bool,
pub audio_chunk_duration: Duration,
pub health_check_grace_period: u64,
pub enabled_devices: HashSet<String>,
pub use_all_devices: bool,
pub db_path: Option<String>,
pub deepgram_url: Option<String>,
- pub deepgram_websocket_url: Option<String>,
pub output_path: Option<PathBuf>,
/// Enable PII removal from audio transcriptions
pub use_pii_removal: bool,
@@ -76,7 +74,6 @@ pub struct AudioManagerOptions {
impl Default for AudioManagerOptions {
fn default() -> Self {
let deepgram_api_key = env::var("DEEPGRAM_API_KEY").ok();
- let deepgram_websocket_url = env::var("DEEPGRAM_WEBSOCKET_URL").ok();
let deepgram_url = env::var("DEEPGRAM_API_URL").ok();
let enabled_devices = HashSet::new();
Self {
@@ -87,14 +84,12 @@ impl Default for AudioManagerOptions {
deepgram_api_key,
openai_compatible_config: None,
enable_diarization: true,
- enable_realtime: false,
audio_chunk_duration: Duration::from_secs(30),
health_check_grace_period: 15,
enabled_devices,
use_all_devices: false,
db_path: None,
deepgram_url,
- deepgram_websocket_url,
use_pii_removal: false,
filter_music: false,
use_system_default_audio: true,
@@ -149,11 +144,6 @@ impl AudioManagerBuilder {
self
}
- pub fn realtime(mut self, enable_realtime: bool) -> Self {
- self.options.enable_realtime = enable_realtime;
- self
- }
-
pub fn audio_chunk_duration(mut self, audio_chunk_duration: Duration) -> Self {
self.options.audio_chunk_duration = audio_chunk_duration;
self
@@ -179,11 +169,6 @@ impl AudioManagerBuilder {
self
}
- pub fn deepgram_websocket_url(mut self, deepgram_websocket_url: Option<String>) -> Self {
- self.options.deepgram_websocket_url = deepgram_websocket_url;
- self
- }
-
pub fn use_pii_removal(mut self, use_pii_removal: bool) -> Self {
self.options.use_pii_removal = use_pii_removal;
self
@@ -263,14 +248,6 @@ impl AudioManagerBuilder {
return Err(anyhow::anyhow!("Output path is required for audio manager"));
}
- if self.options.enable_realtime
- && (self.options.deepgram_api_key.is_none() && CUSTOM_DEEPGRAM_API_TOKEN.is_empty())
- {
- return Err(anyhow::anyhow!(
- "Deepgram API key is required for realtime transcription"
- ));
- }
-
Ok(())
}
}
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index d154cd53e..dc3c58438 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -35,7 +35,6 @@ use crate::{
metrics::AudioPipelineMetrics,
segmentation::segmentation_manager::SegmentationManager,
transcription::{
- deepgram::streaming::stream_transcription_deepgram,
engine::TranscriptionEngine,
handle_new_transcript,
stt::{process_audio_input, SAMPLE_RATE},
@@ -366,54 +365,22 @@ impl AudioManager {
let recording_sender = self.recording_sender.clone();
let is_running = self.device_manager.is_running_mut(device).unwrap();
let languages = options.languages.clone();
- let deepgram_api_key = options.deepgram_api_key.clone();
- let realtime_enabled = options.enable_realtime;
let device_clone = device.clone();
let metrics = self.metrics.clone();
let recording_handle = tokio::spawn(async move {
- let record_and_transcribe_handle = tokio::spawn(record_and_transcribe(
+ let record_result = tokio::spawn(record_and_transcribe(
stream.clone(),
audio_chunk_duration,
recording_sender.clone(),
is_running.clone(),
metrics,
- ));
-
- let realtime_handle = if realtime_enabled {
- Some(tokio::spawn(stream_transcription_deepgram(
- stream,
- languages,
- is_running,
- deepgram_api_key,
- )))
- } else {
- None
- };
-
- let (record_result, realtime_result) = if let Some(handle) = realtime_handle {
- join!(record_and_transcribe_handle, handle)
- } else {
- (record_and_transcribe_handle.await, Ok(Ok(())))
- };
+ )).await;
// Check for JoinError (task panic/cancel)
- if record_result.is_err() || realtime_result.is_err() {
- let mut e = anyhow!("record_device failed");
-
- if record_result.is_err() {
- let record_error = record_result.err().unwrap();
- error!("Record and transcribe error: {}", record_error);
- e = e.context(record_error)
- }
-
- if realtime_result.is_err() {
- let realtime_error = realtime_result.err().unwrap();
- error!("Realtime recording error: {}", realtime_error);
- e = e.context(realtime_error);
- }
-
- return Err(e);
+ if let Err(ref e) = record_result {
+ error!("Record and transcribe error: {}", e);
+ return Err(anyhow!("record_device failed: {}", e));
}
// Check for inner Result errors (record_and_transcribe returned Err)
@@ -424,13 +391,6 @@ impl AudioManager {
);
return Err(anyhow!("record_device {} failed: {}", device_clone, e));
}
- if let Ok(Err(ref e)) = realtime_result {
- warn!(
- "realtime recording for device {} exited with error: {}",
- device_clone, e
- );
- return Err(anyhow!("realtime {} failed: {}", device_clone, e));
- }
warn!(
"recording handle for device {} exited unexpectedly with Ok",
diff --git a/crates/screenpipe-audio/src/core/mod.rs b/crates/screenpipe-audio/src/core/mod.rs
index bdffec34a..ecf91f4bf 100644
--- a/crates/screenpipe-audio/src/core/mod.rs
+++ b/crates/screenpipe-audio/src/core/mod.rs
@@ -8,7 +8,6 @@ pub mod engine;
pub mod pulse;
mod run_record_and_transcribe;
pub mod stream;
-use crate::transcription::deepgram::streaming::stream_transcription_deepgram;
use crate::AudioInput;
use anyhow::Result;
use dashmap::DashMap;
@@ -95,30 +94,3 @@ pub async fn record_and_transcribe(
Ok(())
}
-pub async fn start_realtime_recording(
- audio_stream: Arc<AudioStream>,
- languages: Vec<Language>,
- is_running: Arc<AtomicBool>,
- deepgram_api_key: Option<String>,
-) -> Result<()> {
- while is_running.load(Ordering::Relaxed) {
- match stream_transcription_deepgram(
- audio_stream.clone(),
- languages.clone(),
- is_running.clone(),
- deepgram_api_key.clone(),
- )
- .await
- {
- Ok(_) => break, // Normal shutdown
- Err(e) => {
- if is_normal_shutdown(&is_running) {
- break;
- }
- error!("realtime_stt error, restarting: {}", e);
- tokio::time::sleep(Duration::from_secs(1)).await;
- }
- }
- }
- Ok(())
-}
diff --git a/crates/screenpipe-audio/src/transcription/deepgram/mod.rs b/crates/screenpipe-audio/src/transcription/deepgram/mod.rs
index 4042f5cf0..5dd140f46 100644
--- a/crates/screenpipe-audio/src/transcription/deepgram/mod.rs
+++ b/crates/screenpipe-audio/src/transcription/deepgram/mod.rs
@@ -1,5 +1,4 @@
pub mod batch;
-pub mod streaming;
use lazy_static::lazy_static;
use std::env;
@@ -7,8 +6,6 @@ use std::env;
lazy_static! {
pub(crate) static ref DEEPGRAM_API_URL: String = env::var("DEEPGRAM_API_URL")
.unwrap_or_else(|_| "https://api.deepgram.com/v1/listen".to_string());
- pub(crate) static ref DEEPGRAM_WEBSOCKET_URL: String =
- env::var("DEEPGRAM_WEBSOCKET_URL").unwrap_or_else(|_| String::new());
pub(crate) static ref CUSTOM_DEEPGRAM_API_TOKEN: String =
env::var("CUSTOM_DEEPGRAM_API_TOKEN").unwrap_or_else(|_| String::new());
}
diff --git a/crates/screenpipe-audio/src/transcription/deepgram/streaming.rs b/crates/screenpipe-audio/src/transcription/deepgram/streaming.rs
deleted file mode 100644
index b846ac07a..000000000
--- a/crates/screenpipe-audio/src/transcription/deepgram/streaming.rs
+++ /dev/null
@@ -1,404 +0,0 @@
-use anyhow::Result;
-use bytes::BufMut;
-use bytes::Bytes;
-use bytes::BytesMut;
-use chrono::DateTime;
-use chrono::Utc;
-use crossbeam::channel::RecvError;
-use deepgram::common::options::Encoding;
-use deepgram::common::stream_response::StreamResponse;
-use futures::channel::mpsc::{self, Receiver as FuturesReceiver};
-use futures::{SinkExt, TryStreamExt};
-use screenpipe_core::Language;
-use screenpipe_events::send_event;
-use serde::{Deserialize, Serialize};
-use serde_json;
-use serde_json::Value;
-use std::sync::atomic::{AtomicI64, Ordering};
-use std::sync::{atomic::AtomicBool, Arc};
-use std::time::{Duration, SystemTime, UNIX_EPOCH};
-use tokio::sync::broadcast::Receiver;
-use tokio::sync::oneshot;
-use tracing::debug;
-use tracing::info;
-
-// Add this near other static/global variables
-static LAST_DISPLAY_AUDIO_ACTIVITY: AtomicI64 = AtomicI64::new(0);
-
-use crate::core::device::AudioDevice;
-use crate::core::device::DeviceType;
-use crate::core::stream::AudioStream;
-use crate::transcription::deepgram::CUSTOM_DEEPGRAM_API_TOKEN;
-use crate::transcription::deepgram::DEEPGRAM_WEBSOCKET_URL;
-
-#[derive(Serialize, Deserialize, Clone)]
-#[serde(rename_all = "camelCase")]
-pub struct RealtimeTranscriptionEvent {
- pub timestamp: DateTime<Utc>,
- pub device: String,
- pub transcription: String,
- pub is_final: bool,
- pub is_input: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub speaker: Option<String>,
-}
-
-/// Starts a Deepgram transcription stream for the given audio stream
-///
-/// # Arguments
-/// * `stream` - The audio stream to transcribe
-/// * `languages` - List of languages to transcribe (currently unused)
-/// * `is_running` - Atomic boolean to control the stream lifecycle
-/// * `deepgram_api_key` - Optional custom API key for Deepgram
-pub async fn stream_transcription_deepgram(
- stream: Arc<AudioStream>,
- _languages: Vec<Language>, // TODO impl language
- is_running: Arc<AtomicBool>,
- deepgram_api_key: Option<String>,
-) -> Result<()> {
- start_deepgram_stream(
- stream.subscribe().await,
- stream.device.clone(),
- stream.device_config.sample_rate().0,
- is_running,
- deepgram_api_key,
- )
- .await?;
-
- Ok(())
-}
-
-/// Initializes and manages a Deepgram streaming session
-pub async fn start_deepgram_stream(
- stream: Receiver<Vec<f32>>,
- device: Arc<AudioDevice>,
- sample_rate: u32,
- is_running: Arc<AtomicBool>,
- deepgram_api_key: Option<String>,
-) -> Result<()> {
- let api_key = deepgram_api_key.unwrap_or_else(|| CUSTOM_DEEPGRAM_API_TOKEN.to_string());
-
- if api_key.is_empty() {
- return Err(anyhow::anyhow!("Deepgram API key not found"));
- }
-
- // Remove the API key logging
- info!("initializing deepgram transcription service");
-
- // Log the WebSocket URL
- let ws_url = if DEEPGRAM_WEBSOCKET_URL.as_str().is_empty() {
- "default deepgram api".to_string()
- } else {
- DEEPGRAM_WEBSOCKET_URL.as_str().to_string()
- };
- debug!("connecting to deepgram at: {}", ws_url);
-
- // Log the audio configuration
- debug!(
- "audio configuration: sample_rate={}, channels=1, device={}",
- sample_rate, device
- );
-
- let (shutdown_tx, mut shutdown_rx) = oneshot::channel();
-
- // Spawn shutdown monitor
- tokio::spawn(async move {
- while is_running.load(std::sync::atomic::Ordering::SeqCst) {
- tokio::time::sleep(Duration::from_millis(100)).await;
- }
- let _ = shutdown_tx.send(()); // Ignore send errors if receiver is dropped
- });
-
- debug!("Starting deepgram stream for device: {}", device);
-
- let deepgram = match DEEPGRAM_WEBSOCKET_URL.as_str().is_empty() {
- true => deepgram::Deepgram::new(api_key)?,
- false => {
- debug!(
- "using custom deepgram websocket url: {}",
- DEEPGRAM_WEBSOCKET_URL.as_str()
- );
- deepgram::Deepgram::with_base_url_and_api_key(DEEPGRAM_WEBSOCKET_URL.as_str(), api_key)?
- }
- };
-
- let deepgram_transcription = deepgram.transcription();
-
- let options = deepgram::common::options::OptionsBuilder::new()
- .model(deepgram::common::options::Model::Nova3)
- .smart_format(true)
- .diarize(true)
- .build();
-
- debug!("deepgram options: {:?}", options);
-
- let req = deepgram_transcription
- .stream_request_with_options(options)
- .keep_alive()
- .channels(1)
- .sample_rate(sample_rate)
- .encoding(Encoding::Linear16);
-
- debug!(
- "sending deepgram request with encoding=Linear16, channels=1, sample_rate={}",
- sample_rate
- );
-
- let mut handle = req.clone().handle().await?;
- debug!("deepgram handle created successfully");
-
- let mut results = req
- .stream(get_stream(stream, device.device_type.clone()))
- .await?;
- debug!("deepgram stream started successfully");
-
- let device_clone = device.clone();
-
- // Add a sample of the expected response format for debugging
- let sample_response = r#"
- {
- "type": "Results",
- "channel_index": [0,1],
- "duration": 3.02,
- "is_final": true,
- "speech_final": true,
- "channel": {
- "alternatives": [{"transcript": "sample", "confidence": 0.9, "words": []}]
- }
- }
- "#;
-
- // Try to parse the sample to see if our expected format matches
- match serde_json::from_str::<StreamResponse>(sample_response) {
- Ok(_) => debug!("sample response format is valid"),
- Err(e) => {
- debug!("expected format example error: {}", e);
-
- // Try to parse as generic JSON to see what we can extract
- if let Ok(value) = serde_json::from_str::<Value>(sample_response) {
- debug!("sample can be parsed as generic json: {}", value["type"]);
- }
- }
- };
-
- loop {
- tokio::select! {
- Ok(()) = &mut shutdown_rx => {
- debug!("Shutting down deepgram stream for device: {}", device);
- break;
- }
- result = results.try_next() => {
- match result {
- Ok(Some(result)) => {
- handle_transcription(result, device_clone.clone()).await;
- }
- Ok(None) => break, // Stream ended
- Err(e) => {
- // Log the error
- debug!("Error in deepgram stream: {}", e);
-
- // Try to extract and process the raw JSON from the error
- if let Some(raw_data) = e.to_string().find("data:") {
- let raw_str = &e.to_string()[raw_data..];
- debug!("Raw data excerpt: {}", raw_str);
-
- // Try to extract and process the raw JSON
- if let Some(json_start) = raw_str.find('{') {
- let json_str = &raw_str[json_start..];
- if let Ok(value) = serde_json::from_str::<Value>(json_str) {
- debug!("Processing raw JSON from error: {}", value);
-
- // Try to handle as a Results type
- if value.get("type").and_then(|t| t.as_str()) == Some("Results") {
- debug!("Found Results type in error data, processing...");
- // Process the transcription data
- // ...
- }
- }
- }
- }
-
- // Don't break the loop for deserialization errors
- if e.to_string().contains("deserialization") {
- debug!("Continuing despite deserialization error");
- continue;
- } else {
- debug!("Breaking stream due to non-deserialization error");
- break;
- }
- }
- }
- }
- }
- }
-
- handle.close_stream().await?;
- Ok(())
-}
-
-fn get_stream(
- mut stream: Receiver<Vec<f32>>,
- device_type: DeviceType,
-) -> FuturesReceiver<Result<Bytes, RecvError>> {
- let (mut tx, rx) = mpsc::channel(1);
-
- tokio::spawn(async move {
- let mut packet_count = 0;
- let mut total_bytes = 0;
-
- while let Ok(data) = stream.recv().await {
- if device_type == DeviceType::Output {
- let sum_squares: f32 = data.iter().map(|&x| x * x).sum();
- let rms = (sum_squares / data.len() as f32).sqrt();
-
- if rms > 0.01 {
- LAST_DISPLAY_AUDIO_ACTIVITY.store(
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_millis() as i64,
- Ordering::SeqCst,
- );
-
- // Log display audio activity
- debug!("display audio activity detected: rms={:.6}", rms);
- }
- } else if SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_millis() as i64
- - LAST_DISPLAY_AUDIO_ACTIVITY.load(Ordering::SeqCst)
- < 100
- {
- debug!("skipping input audio due to recent display activity");
- continue;
- }
-
- let mut bytes = BytesMut::with_capacity(data.len() * 2);
- for sample in data {
- bytes.put_i16_le((sample * i16::MAX as f32) as i16);
- }
-
- packet_count += 1;
- total_bytes += bytes.len();
-
- if packet_count % 100 == 0 {
- debug!(
- "sent {} audio packets ({} bytes) to deepgram for device_type={:?}",
- packet_count, total_bytes, device_type
- );
- }
-
- if tx.send(Ok(bytes.freeze())).await.is_err() {
- debug!("stream receiver dropped, stopping audio transmission");
- break; // Stop if receiver is dropped
- }
- }
- });
-
- rx
-}
-
-async fn handle_transcription(result: StreamResponse, device: Arc<AudioDevice>) {
- // Try to handle the result as a StreamResponse enum variant first
- match result {
- StreamResponse::TranscriptResponse {
- channel, is_final, ..
- } => {
- debug!(
- "received transcription for device: {}, is_final: {}",
- device.name, is_final
- );
- let res = channel.alternatives.first().unwrap();
- let text = res.transcript.clone();
- let is_input = device.device_type == DeviceType::Input;
-
- let speaker = res
- .words
- .first()
- .and_then(|w| w.speaker)
- .map(|s| s.to_string());
-
- if !text.is_empty() {
- debug!("transcription text: {}", text);
- if let Some(speaker_id) = &speaker {
- debug!("speaker identified: {}", speaker_id);
- }
-
- let _ = send_event(
- "transcription",
- RealtimeTranscriptionEvent {
- timestamp: chrono::Utc::now(),
- device: device.to_string(),
- transcription: text.to_string(),
- is_final,
- is_input,
- speaker,
- },
- );
- }
- }
- // Add a custom handler for the "Results" type that Deepgram actually sends
- _ => {
- // Convert the StreamResponse to a JSON Value to handle it generically
- if let Ok(value) = serde_json::to_value(&result) {
- debug!("handling raw response: {}", value);
-
- // Check if this is a "Results" type response
- if value.get("type").and_then(|t| t.as_str()) == Some("Results") {
- let is_final = value
- .get("is_final")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- // Extract the transcript from the channel alternatives
- if let Some(channel) = value.get("channel") {
- if let Some(alternatives) = channel.get("alternatives") {
- if let Some(first_alt) = alternatives.get(0) {
- if let Some(transcript) =
- first_alt.get("transcript").and_then(|t| t.as_str())
- {
- if !transcript.is_empty() {
- debug!("extracted transcript from results: {}", transcript);
-
- // Extract speaker if available
- let speaker = if let Some(words) = first_alt.get("words") {
- if let Some(first_word) = words.get(0) {
- first_word
- .get("speaker")
- .and_then(|s| s.as_u64())
- .map(|s| s.to_string())
- } else {
- None
- }
- } else {
- None
- };
-
- let is_input = device.device_type == DeviceType::Input;
-
- let _ = send_event(
- "transcription",
- RealtimeTranscriptionEvent {
- timestamp: chrono::Utc::now(),
- device: device.to_string(),
- transcription: transcript.to_string(),
- is_final,
- is_input,
- speaker,
- },
- );
- }
- }
- }
- }
- }
- } else {
- debug!("unhandled response type: {:?}", value.get("type"));
- }
- } else {
- debug!("failed to convert response to json: {:?}", result);
- }
- }
- }
-}
diff --git a/crates/screenpipe-audio/tests/realtime_test.rs b/crates/screenpipe-audio/tests/realtime_test.rs
deleted file mode 100644
index a5e4163b5..000000000
--- a/crates/screenpipe-audio/tests/realtime_test.rs
+++ /dev/null
@@ -1,78 +0,0 @@
-use futures::StreamExt;
-use screenpipe_audio::core::device::AudioDevice;
-use screenpipe_audio::core::device::DeviceType;
-use screenpipe_audio::pcm_decode;
-use screenpipe_audio::transcription::deepgram::streaming::start_deepgram_stream;
-use screenpipe_audio::transcription::deepgram::streaming::RealtimeTranscriptionEvent;
-use screenpipe_events::subscribe_to_event;
-use std::{
- sync::{atomic::AtomicBool, Arc},
- time::Duration,
-};
-use tokio::sync::broadcast;
-
-/// 1. Get sample audio from test_data/accuracy1.wav
-/// 2. Stream audio from file
-/// 3. Transcribe audio
-/// 4. Assert that the transcription is correct
-#[tokio::test]
-#[ignore]
-async fn test_realtime_transcription() {
- let (samples, sample_rate) = pcm_decode("test_data/accuracy1.wav").unwrap_or_else(|e| {
- panic!("Failed to decode audio: {}", e);
- });
-
- let (stream_tx, stream_rx) = broadcast::channel(sample_rate as usize * 3);
- let device = AudioDevice::new("test".to_string(), DeviceType::Output);
- let is_running = Arc::new(AtomicBool::new(true));
-
- let deepgram_api_key = std::env::var("CUSTOM_DEEPGRAM_API_KEY").unwrap();
-
- let is_running_clone = is_running.clone();
-
- tokio::spawn(async move {
- let _ = start_deepgram_stream(
- stream_rx,
- Arc::new(device),
- sample_rate,
- is_running_clone,
- Some(deepgram_api_key),
- )
- .await;
-
- println!("Deepgram stream closed");
- });
-
- let transcription_receiver_handle = tokio::spawn(async move {
- let mut receiver = subscribe_to_event::<RealtimeTranscriptionEvent>("transcription");
- loop {
- tokio::select! {
- event = receiver.next() => {
- if let Some(event) = event {
- println!("Received event: {:?}", event.data.transcription);
- } else {
- println!("Receiver closed");
- }
- },
- _ = tokio::time::sleep(Duration::from_secs(15)) => {
- println!("Timeout");
- return;
- }
- }
- }
- });
-
- tokio::time::sleep(Duration::from_secs(10)).await;
-
- let tx = stream_tx.clone();
- let samples = samples.clone();
-
- for sample in samples.chunks(sample_rate as usize * 5) {
- tx.send(sample.to_vec()).unwrap_or_else(|e| {
- panic!("Failed to send sample: {}", e);
- });
- tokio::time::sleep(Duration::from_millis(10)).await;
- }
-
- transcription_receiver_handle.await.unwrap();
-}
diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
index 7ffa0b0e5..b0f02b320 100644
--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
@@ -443,10 +443,6 @@ async fn main() -> anyhow::Result<()> {
let mut audio_devices = Vec::new();
- // Realtime streaming is disabled — batch mode with VAD filtering is
- // more cost-effective and avoids double-billing on cloud engines.
- let enable_realtime_audio = false;
-
if !config.disable_audio {
if config.audio_devices.is_empty() {
// Use default devices
@@ -557,7 +553,7 @@ async fn main() -> anyhow::Result<()> {
PathBuf::from(output_path_clone.clone().to_string()),
audio_devices,
)
- .realtime(enable_realtime_audio);
+ ;
if let Some(ref detector) = meeting_detector {
audio_manager_builder = audio_manager_builder.meeting_detector(detector.clone());