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

Events (#1204)

Ezra Ellette81af30ba2cd2
diff --git a/Cargo.toml b/Cargo.toml
index c2eb608d3..8df955226 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,10 +6,9 @@ members = [
"screenpipe-server",
"screenpipe-integrations",
"screenpipe-actions",
+ "screenpipe-events",
]
-exclude = [
- "screenpipe-app-tauri/src-tauri"
-]
+exclude = ["screenpipe-app-tauri/src-tauri"]
resolver = "2"
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index dd15aaa55..d5574ff93 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -62,6 +62,7 @@ webrtc-vad = "0.4.0"
reqwest = { workspace = true }
screenpipe-core = { path = "../screenpipe-core" }
+screenpipe-events = { path = "../screenpipe-events" }
# crossbeam
crossbeam = { workspace = true }
@@ -75,7 +76,7 @@ realfft = "3.4.0"
regex = "1.11.0"
ndarray = "0.16"
ort = "=2.0.0-rc.6"
-knf-rs = { git = "https://github.com/Neptune650/knf-rs.git" }
+knf-rs = { git = "https://github.com/Neptune650/knf-rs.git", branch = "main" }
ort-sys = "=2.0.0-rc.8"
futures = "0.3.31"
deepgram = "0.6.4"
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index 6e96e1547..9ef627ae7 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -1,5 +1,5 @@
use crate::audio_processing::audio_to_mono;
-use crate::realtime::{realtime_stt, RealtimeTranscriptionEvent};
+use crate::realtime::realtime_stt;
use crate::AudioInput;
use anyhow::{anyhow, Result};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
@@ -138,14 +138,12 @@ pub async fn start_realtime_recording(
audio_stream: Arc<AudioStream>,
languages: Vec<Language>,
is_running: Arc<AtomicBool>,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
deepgram_api_key: Option<String>,
) -> Result<()> {
while is_running.load(Ordering::Relaxed) {
match realtime_stt(
audio_stream.clone(),
languages.clone(),
- realtime_transcription_sender.clone(),
is_running.clone(),
deepgram_api_key.clone(),
)
diff --git a/screenpipe-audio/src/deepgram/mod.rs b/screenpipe-audio/src/deepgram/mod.rs
index c81843cd4..62a8ee022 100644
--- a/screenpipe-audio/src/deepgram/mod.rs
+++ b/screenpipe-audio/src/deepgram/mod.rs
@@ -9,8 +9,8 @@ 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(|_| "wss://api.deepgram.com/v1/listen".to_string());
+ pub(crate) static ref DEEPGRAM_WEBSOCKET_URL: String =
+ env::var("DEEPGRAM_WEBSOCKET_URL").unwrap_or_else(|_| "".to_string());
pub(crate) static ref CUSTOM_DEEPGRAM_API_TOKEN: String =
env::var("CUSTOM_DEEPGRAM_API_TOKEN").unwrap_or_else(|_| String::new());
}
diff --git a/screenpipe-audio/src/deepgram/realtime.rs b/screenpipe-audio/src/deepgram/realtime.rs
index 430112046..c0fd3f7d2 100644
--- a/screenpipe-audio/src/deepgram/realtime.rs
+++ b/screenpipe-audio/src/deepgram/realtime.rs
@@ -1,5 +1,6 @@
use crate::{
- deepgram::CUSTOM_DEEPGRAM_API_TOKEN, realtime::RealtimeTranscriptionEvent, AudioStream,
+ deepgram::CUSTOM_DEEPGRAM_API_TOKEN, deepgram::DEEPGRAM_WEBSOCKET_URL,
+ realtime::RealtimeTranscriptionEvent, AudioStream,
};
use anyhow::Result;
use bytes::BufMut;
@@ -13,16 +14,14 @@ use futures::{SinkExt, TryStreamExt};
use screenpipe_core::AudioDevice;
use screenpipe_core::AudioDeviceType;
use screenpipe_core::Language;
+use screenpipe_events::send_event;
use std::sync::{atomic::AtomicBool, Arc};
use std::time::Duration;
use tokio::sync::broadcast::Receiver;
-use tracing::error;
-
-use super::DEEPGRAM_WEBSOCKET_URL;
+use tokio::sync::oneshot;
pub async fn stream_transcription_deepgram(
stream: Arc<AudioStream>,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
languages: Vec<Language>,
is_running: Arc<AtomicBool>,
deepgram_api_key: Option<String>,
@@ -31,7 +30,6 @@ pub async fn stream_transcription_deepgram(
stream.subscribe().await,
stream.device.clone(),
stream.device_config.sample_rate().0,
- realtime_transcription_sender,
is_running,
languages,
deepgram_api_key,
@@ -45,19 +43,36 @@ pub async fn start_deepgram_stream(
stream: Receiver<Vec<f32>>,
device: Arc<AudioDevice>,
sample_rate: u32,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
is_running: Arc<AtomicBool>,
_languages: Vec<Language>,
deepgram_api_key: Option<String>,
) -> Result<()> {
let api_key = deepgram_api_key.unwrap_or(CUSTOM_DEEPGRAM_API_TOKEN.to_string());
- let base_url = DEEPGRAM_WEBSOCKET_URL.to_string();
if api_key.is_empty() {
return Err(anyhow::anyhow!("Deepgram API key not found"));
}
- let deepgram = deepgram::Deepgram::with_base_url_and_api_key(base_url.as_str(), api_key)?;
+ // create shutdown rx from is_running
+ let (shutdown_tx, mut shutdown_rx) = oneshot::channel();
+
+ tokio::spawn(async move {
+ loop {
+ let running = is_running.load(std::sync::atomic::Ordering::SeqCst);
+ if !running {
+ shutdown_tx.send(()).unwrap();
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ });
+
+ let deepgram = match DEEPGRAM_WEBSOCKET_URL.as_str().is_empty() {
+ true => deepgram::Deepgram::new(api_key)?,
+ false => {
+ deepgram::Deepgram::with_base_url_and_api_key(DEEPGRAM_WEBSOCKET_URL.as_str(), api_key)?
+ }
+ };
let deepgram_transcription = deepgram.transcription();
@@ -75,20 +90,17 @@ pub async fn start_deepgram_stream(
let mut handle = req.clone().handle().await?;
let mut results = req.stream(get_stream(stream)).await?;
- let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
let device_clone = device.clone();
loop {
- if !is_running.load(std::sync::atomic::Ordering::SeqCst) {
- break;
- }
-
tokio::select! {
+ _ = &mut shutdown_rx => {
+ break;
+ }
result = results.try_next() => {
if let Ok(Some(result)) = result {
handle_transcription(
result,
- realtime_transcription_sender_clone.clone(),
device_clone.clone(),
).await;
}
@@ -119,11 +131,7 @@ fn get_stream(mut stream: Receiver<Vec<f32>>) -> FuturesReceiver<Result<Bytes, R
rx
}
-async fn handle_transcription(
- result: StreamResponse,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
- device: Arc<AudioDevice>,
-) {
+async fn handle_transcription(result: StreamResponse, device: Arc<AudioDevice>) {
if let StreamResponse::TranscriptResponse {
channel, is_final, ..
} = result
@@ -133,20 +141,16 @@ async fn handle_transcription(
let is_input = device.device_type == AudioDeviceType::Input;
if !text.is_empty() {
- match realtime_transcription_sender.send(RealtimeTranscriptionEvent {
- timestamp: chrono::Utc::now(),
- device: device.to_string(),
- transcription: text.to_string(),
- is_final,
- is_input,
- }) {
- Ok(_) => {}
- Err(e) => {
- if !e.to_string().contains("channel closed") {
- error!("Error sending transcription event: {}", e);
- }
- }
- }
+ let _ = send_event(
+ "transcription",
+ RealtimeTranscriptionEvent {
+ timestamp: chrono::Utc::now(),
+ device: device.to_string(),
+ transcription: text.to_string(),
+ is_final,
+ is_input,
+ },
+ );
}
}
}
diff --git a/screenpipe-audio/src/realtime.rs b/screenpipe-audio/src/realtime.rs
index 5baf1a6e8..37569d49f 100644
--- a/screenpipe-audio/src/realtime.rs
+++ b/screenpipe-audio/src/realtime.rs
@@ -2,29 +2,21 @@ use crate::{deepgram::stream_transcription_deepgram, AudioStream};
use anyhow::Result;
use chrono::{DateTime, Utc};
use screenpipe_core::Language;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use std::sync::{atomic::AtomicBool, Arc};
pub async fn realtime_stt(
stream: Arc<AudioStream>,
languages: Vec<Language>,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
is_running: Arc<AtomicBool>,
deepgram_api_key: Option<String>,
) -> Result<()> {
- stream_transcription_deepgram(
- stream,
- realtime_transcription_sender,
- languages,
- is_running,
- deepgram_api_key,
- )
- .await?;
+ stream_transcription_deepgram(stream, languages, is_running, deepgram_api_key).await?;
Ok(())
}
-#[derive(Serialize, Clone)]
+#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RealtimeTranscriptionEvent {
pub timestamp: DateTime<Utc>,
diff --git a/screenpipe-audio/tests/realtime_test.rs b/screenpipe-audio/tests/realtime_test.rs
index 3158fc8db..6785a7a01 100644
--- a/screenpipe-audio/tests/realtime_test.rs
+++ b/screenpipe-audio/tests/realtime_test.rs
@@ -1,6 +1,9 @@
+use futures::StreamExt;
use screenpipe_audio::deepgram::start_deepgram_stream;
use screenpipe_audio::pcm_decode;
+use screenpipe_audio::realtime::RealtimeTranscriptionEvent;
use screenpipe_core::{AudioDevice, AudioDeviceType};
+use screenpipe_events::subscribe_to_event;
use std::{
sync::{atomic::AtomicBool, Arc},
time::Duration,
@@ -14,7 +17,9 @@ use tokio::sync::broadcast;
#[tokio::test]
#[ignore]
async fn test_realtime_transcription() {
- let (samples, sample_rate) = pcm_decode("test_data/accuracy1.wav").unwrap();
+ 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(), AudioDeviceType::Output);
@@ -22,9 +27,6 @@ async fn test_realtime_transcription() {
let deepgram_api_key = std::env::var("CUSTOM_DEEPGRAM_API_KEY").unwrap();
- let (realtime_transcription_sender, realtime_transcription_receiver) =
- broadcast::channel(10000);
-
let is_running_clone = is_running.clone();
tokio::spawn(async move {
@@ -32,7 +34,6 @@ async fn test_realtime_transcription() {
stream_rx,
Arc::new(device),
sample_rate,
- Arc::new(realtime_transcription_sender),
is_running_clone,
vec![],
Some(deepgram_api_key),
@@ -43,17 +44,17 @@ async fn test_realtime_transcription() {
});
let transcription_receiver_handle = tokio::spawn(async move {
- let mut receiver = realtime_transcription_receiver;
+ let mut receiver = subscribe_to_event::<RealtimeTranscriptionEvent>("transcription");
loop {
tokio::select! {
- event = receiver.recv() => {
- if let Ok(event) = event {
- println!("Received event: {:?}", event.transcription);
+ event = receiver.next() => {
+ if let Some(event) = event {
+ println!("Received event: {:?}", event.data.transcription);
} else {
println!("Receiver closed");
}
},
- _ = tokio::time::sleep(Duration::from_secs(10)) => {
+ _ = tokio::time::sleep(Duration::from_secs(15)) => {
println!("Timeout");
return;
}
@@ -61,13 +62,15 @@ async fn test_realtime_transcription() {
}
});
- tokio::time::sleep(Duration::from_secs(5)).await;
+ 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();
+ tx.send(sample.to_vec()).unwrap_or_else(|e| {
+ panic!("Failed to send sample: {}", e);
+ });
tokio::time::sleep(Duration::from_millis(10)).await;
}
diff --git a/screenpipe-events/.gitignore b/screenpipe-events/.gitignore
new file mode 100644
index 000000000..21230960a
--- /dev/null
+++ b/screenpipe-events/.gitignore
@@ -0,0 +1 @@
+.cargo/
\ No newline at end of file
diff --git a/screenpipe-events/Cargo.toml b/screenpipe-events/Cargo.toml
new file mode 100644
index 000000000..0ae39f842
--- /dev/null
+++ b/screenpipe-events/Cargo.toml
@@ -0,0 +1,31 @@
+[package]
+name = "screenpipe-events"
+version.workspace = true
+authors.workspace = true
+description.workspace = true
+repository.workspace = true
+license.workspace = true
+edition.workspace = true
+
+[dependencies]
+anyhow = "1.0.95"
+futures = "0.3.31"
+lazy_static = { version = "1.4.0" }
+serde = { version = "1.0.217", features = ["derive"] }
+serde_json = "1.0.137"
+tokio.workspace = true
+tokio-stream = { version = "0.1.17", features = ["sync"] }
+once_cell = { version = "1.18" }
+tracing.workspace = true
+parking_lot = "0.12.3"
+serial_test = "3.2.0"
+ctor = "0.2"
+chrono = "0.4.39"
+
+[dev-dependencies]
+serde = { version = "1.0", features = ["derive"] }
+criterion = { version = "0.5", features = ["async_tokio"] }
+
+[[bench]]
+name = "events"
+harness = false
diff --git a/screenpipe-events/benches/events.rs b/screenpipe-events/benches/events.rs
new file mode 100644
index 000000000..78ba31907
--- /dev/null
+++ b/screenpipe-events/benches/events.rs
@@ -0,0 +1,59 @@
+use criterion::{black_box, criterion_group, criterion_main, Criterion};
+use futures::StreamExt;
+use screenpipe_events::{send_event, subscribe_to_event};
+use tokio::runtime::Runtime;
+
+fn benchmark_event_system(c: &mut Criterion) {
+ let rt = Runtime::new().unwrap();
+ let mut group = c.benchmark_group("events");
+
+ // Test with different numbers of subscribers
+ for num_subscribers in [1, 10, 50, 100] {
+ group.bench_function(
+ format!("broadcast_to_{}_subscribers", num_subscribers),
+ |b| {
+ b.to_async(&rt).iter_with_setup(
+ || {
+ // Setup phase - not timed
+ let mut receivers = Vec::new();
+ for _ in 0..num_subscribers {
+ receivers.push(subscribe_to_event::<String>("test_event"));
+ }
+ receivers
+ },
+ |mut receivers| async move {
+ // Benchmark phase - timed
+ let _ = send_event("test_event", String::from("test data"));
+ for rx in &mut receivers {
+ black_box(rx.next().await.unwrap());
+ }
+ },
+ );
+ },
+ );
+ }
+
+ // Throughput benchmark
+ group.bench_function("event_throughput", |b| {
+ b.to_async(&rt).iter(|| async {
+ const NUM_EVENTS: usize = 10_000;
+
+ let mut rx = subscribe_to_event::<u64>("counter_event");
+
+ // Send many events in sequence
+ for i in 0..NUM_EVENTS {
+ let _ = send_event("counter_event", i as u64);
+ }
+
+ // Receive all events
+ for _ in 0..NUM_EVENTS {
+ black_box(rx.next().await.unwrap());
+ }
+ });
+ });
+
+ group.finish();
+}
+
+criterion_group!(benches, benchmark_event_system);
+criterion_main!(benches);
diff --git a/screenpipe-events/src/custom_events/meetings.rs b/screenpipe-events/src/custom_events/meetings.rs
new file mode 100644
index 000000000..1c8ae45d6
--- /dev/null
+++ b/screenpipe-events/src/custom_events/meetings.rs
@@ -0,0 +1,238 @@
+use crate::{send_event, subscribe_to_all_events};
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use futures::StreamExt;
+use serde::{Deserialize, Serialize};
+use serde_json;
+use std::collections::{HashMap, HashSet};
+use std::time::{Duration, Instant};
+
+const MEETING_APPS: &[&str] = &["zoom", "teams", "meet", "webex", "skype", "slack"];
+const MEETING_KEYWORDS: &[&str] = &[
+ "meeting",
+ "call",
+ "conference",
+ "joining",
+ "started",
+ "waiting room",
+ "lobby",
+ "participant",
+ "host",
+];
+const MEETING_END_PHRASES: &[&str] = &[
+ "meeting ended",
+ "call ended",
+ "left the meeting",
+ "host has ended",
+ "meeting will end",
+ "meeting has ended",
+];
+
+pub async fn poll_meetings_events() -> Result<()> {
+ let mut subscription = subscribe_to_all_events();
+ let mut meeting_in_progress = false;
+ let mut recent_speakers = HashSet::new();
+ let mut last_activity = Instant::now();
+ let mut last_meeting_end: Option<Instant> = None;
+ const MEETING_RESTART_TIMEOUT: Duration = Duration::from_secs(10);
+
+ while let Some(event) = subscription.next().await {
+ let name = event.name;
+ let event = event.data;
+ match name.as_str() {
+ "ui_frame" => {
+ let ui_frame: UIFrame = serde_json::from_value(event).unwrap();
+ tracing::info!("ui_frame: {:?}", ui_frame.app);
+
+ let is_meeting_app = MEETING_APPS
+ .iter()
+ .any(|app| ui_frame.app.to_lowercase().contains(app));
+
+ let is_meeting_keyword = MEETING_KEYWORDS
+ .iter()
+ .any(|keyword| ui_frame.text_output.to_lowercase().contains(keyword));
+
+ if is_meeting_app
+ && !meeting_in_progress
+ && !ui_frame.window.is_empty()
+ && is_meeting_keyword
+ && last_meeting_end.map_or(true, |t| t.elapsed() >= MEETING_RESTART_TIMEOUT)
+ {
+ meeting_in_progress = true;
+ send_event(
+ "meeting_started",
+ MeetingEvent {
+ app: ui_frame.app.clone(),
+ timestamp: Utc::now(),
+ },
+ )?;
+ }
+
+ if (is_meeting_app && meeting_in_progress && ui_frame.window.is_empty())
+ || (MEETING_END_PHRASES
+ .iter()
+ .any(|phrase| ui_frame.text_output.to_lowercase().contains(phrase))
+ && meeting_in_progress)
+ {
+ meeting_in_progress = false;
+ last_meeting_end = Some(Instant::now());
+ send_event(
+ "meeting_ended",
+ MeetingEvent {
+ app: ui_frame.app.clone(),
+ timestamp: Utc::now(),
+ },
+ )?;
+ }
+ }
+ "window_ocr" => {
+ let window_ocr: WindowOcr = serde_json::from_value(event).unwrap();
+ tracing::info!("window_ocr: {:?}", window_ocr.app_name);
+
+ // Method 1: Meeting App Detection
+ let is_meeting_app = MEETING_APPS
+ .iter()
+ .any(|app| window_ocr.app_name.to_lowercase().contains(app));
+
+ // Method 2: Window Title Analysis
+ let has_meeting_keywords = MEETING_KEYWORDS
+ .iter()
+ .any(|keyword| window_ocr.window_name.to_lowercase().contains(keyword));
+
+ // Method 3: UI Element Analysis
+ let has_meeting_ui = window_ocr.text_json.iter().any(|elem| {
+ elem.values().any(|text| {
+ text.contains("Mute")
+ || text.contains("Camera")
+ || text.contains("Share Screen")
+ || text.contains("Participants")
+ || text.contains("Recording")
+ })
+ });
+
+ if (is_meeting_app && (has_meeting_keywords || has_meeting_ui))
+ && !meeting_in_progress
+ && last_meeting_end.map_or(true, |t| t.elapsed() >= MEETING_RESTART_TIMEOUT)
+ {
+ meeting_in_progress = true;
+ send_event(
+ "meeting_started",
+ MeetingEvent {
+ app: window_ocr.app_name.clone(),
+ timestamp: Utc::now(),
+ },
+ )?;
+ }
+
+ // Check for meeting end
+ let has_end_phrases = MEETING_END_PHRASES
+ .iter()
+ .any(|phrase| window_ocr.text.to_lowercase().contains(phrase));
+
+ if has_end_phrases && meeting_in_progress {
+ meeting_in_progress = false;
+ last_meeting_end = Some(Instant::now());
+ send_event(
+ "meeting_ended",
+ MeetingEvent {
+ app: window_ocr.app_name.clone(),
+ timestamp: Utc::now(),
+ },
+ )?;
+ }
+ }
+
+ "realtime_transcription" => {
+ let transcript: RealtimeTranscriptionEvent = serde_json::from_value(event).unwrap();
+ tracing::info!("realtime_transcription: {:?}", transcript.transcription);
+ // Method 4: Multiple Speaker Detection
+ if transcript.is_final {
+ recent_speakers.insert(transcript.device.clone());
+ last_activity = Instant::now();
+
+ if recent_speakers.len() >= 2
+ && !meeting_in_progress
+ && last_meeting_end.map_or(true, |t| t.elapsed() >= MEETING_RESTART_TIMEOUT)
+ {
+ meeting_in_progress = true;
+ send_event(
+ "meeting_started",
+ MeetingEvent {
+ app: "Unknown (detected via audio)".to_string(),
+ timestamp: Utc::now(),
+ },
+ )?;
+ }
+ }
+
+ // Method 5: Meeting Phrase Detection
+ let lower_transcript = transcript.transcription.to_lowercase();
+ if MEETING_KEYWORDS
+ .iter()
+ .any(|k| lower_transcript.contains(k))
+ {
+ last_activity = Instant::now();
+ }
+
+ // Clean up old speakers after inactivity
+ if last_activity.elapsed() > Duration::from_secs(300) {
+ // 5 minutes
+ recent_speakers.clear();
+ }
+
+ // Check for meeting end phrases in transcription
+ if MEETING_END_PHRASES
+ .iter()
+ .any(|phrase| lower_transcript.contains(phrase))
+ && meeting_in_progress
+ {
+ meeting_in_progress = false;
+ last_meeting_end = Some(Instant::now());
+ send_event(
+ "meeting_ended",
+ MeetingEvent {
+ app: "Unknown (detected via audio)".to_string(),
+ timestamp: Utc::now(),
+ },
+ )?;
+ }
+ }
+ _ => {}
+ }
+ }
+ Ok(())
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct MeetingEvent {
+ app: String,
+ timestamp: DateTime<Utc>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct WindowOcr {
+ pub window_name: String,
+ pub app_name: String,
+ pub text: String,
+ pub text_json: Vec<HashMap<String, String>>, // Change this line
+ pub focused: bool,
+ pub confidence: f64,
+ pub timestamp: DateTime<Utc>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct UIFrame {
+ pub window: String,
+ pub app: String,
+ pub text_output: String,
+ pub initial_traversal_at: String,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+struct RealtimeTranscriptionEvent {
+ pub timestamp: DateTime<Utc>,
+ pub device: String,
+ pub transcription: String,
+ pub is_final: bool,
+ pub is_input: bool,
+}
diff --git a/screenpipe-events/src/custom_events/mod.rs b/screenpipe-events/src/custom_events/mod.rs
new file mode 100644
index 000000000..73ca546a9
--- /dev/null
+++ b/screenpipe-events/src/custom_events/mod.rs
@@ -0,0 +1 @@
+pub mod meetings;
diff --git a/screenpipe-events/src/events_manager.rs b/screenpipe-events/src/events_manager.rs
new file mode 100644
index 000000000..d3e9a72ac
--- /dev/null
+++ b/screenpipe-events/src/events_manager.rs
@@ -0,0 +1,156 @@
+use anyhow::Result;
+use futures::Stream;
+use once_cell::sync::Lazy;
+use parking_lot::RwLock;
+use serde::Deserialize;
+use serde::{de::DeserializeOwned, Serialize};
+use serde_json::Value;
+use std::any::Any;
+use std::collections::HashMap;
+use tokio::sync::broadcast;
+use tokio_stream::wrappers::BroadcastStream;
+
+static EVENT_MANAGER: Lazy<EventManager> = Lazy::new(EventManager::new);
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct Event<T = Value> {
+ pub name: String,
+ pub data: T,
+}
+
+pub struct EventManager {
+ sender: broadcast::Sender<Event>,
+ subscriptions: RwLock<HashMap<String, Box<dyn Any + Send + Sync>>>,
+}
+
+// #[macro_export]
+// macro_rules! send_event {
+// ($name:expr, $data:expr) => {{
+// if let Err(e) = $crate::EventManager::instance().send($name, $data) {
+// tracing::error!("Failed to send event {}: {}", $name, e);
+// }
+// }};
+// }
+
+pub fn send_event<T: Serialize + 'static>(event: impl Into<String>, data: T) -> Result<()> {
+ EventManager::instance().send(event, data)
+}
+
+pub struct EventSubscription<T = Value> {
+ stream: std::pin::Pin<Box<BroadcastStream<Event>>>,
+ event_name: String,
+ _phantom: std::marker::PhantomData<T>,
+}
+
+impl<T: DeserializeOwned + Send + 'static> Clone for EventSubscription<T> {
+ fn clone(&self) -> Self {
+ let rx = EVENT_MANAGER.sender.subscribe();
+ Self {
+ stream: Box::pin(BroadcastStream::new(rx)),
+ event_name: self.event_name.clone(),
+ _phantom: std::marker::PhantomData,
+ }
+ }
+}
+
+impl<T: DeserializeOwned + Unpin + 'static> Stream for EventSubscription<T> {
+ type Item = Event<T>;
+
+ fn poll_next(
+ self: std::pin::Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<Option<Self::Item>> {
+ let me = self.get_mut();
+ loop {
+ match me.stream.as_mut().poll_next(cx) {
+ std::task::Poll::Ready(Some(Ok(event))) => {
+ if event.name == me.event_name || me.event_name.is_empty() {
+ if let Ok(data) = serde_json::from_value::<T>(event.data) {
+ return std::task::Poll::Ready(Some(Event {
+ name: event.name,
+ data,
+ }));
+ }
+ }
+ }
+ std::task::Poll::Ready(Some(_)) => continue,
+ std::task::Poll::Ready(None) => return std::task::Poll::Ready(None),
+ std::task::Poll::Pending => return std::task::Poll::Pending,
+ }
+ }
+ }
+}
+
+impl EventManager {
+ fn new() -> Self {
+ let (sender, _) = broadcast::channel(10000);
+ Self {
+ sender,
+ subscriptions: RwLock::new(HashMap::new()),
+ }
+ }
+
+ pub fn instance() -> &'static EventManager {
+ &EVENT_MANAGER
+ }
+
+ pub fn send<T: Serialize + 'static>(&self, event: impl Into<String>, data: T) -> Result<()> {
+ let event_name = event.into();
+ let value = serde_json::to_value(data)?;
+ tracing::debug!("Sending event {} with data {:?}", event_name, value);
+ match self.sender.send(Event {
+ name: event_name.clone(),
+ data: value,
+ }) {
+ Ok(_) => Ok(()),
+ Err(e) => {
+ if !e.to_string().contains("channel closed") {
+ tracing::error!("Failed to send event {}: {}", event_name, e);
+ Err(anyhow::anyhow!(
+ "Failed to send event {}: {}",
+ event_name,
+ e
+ ))
+ } else {
+ Ok(())
+ }
+ }
+ }
+ }
+
+ pub fn subscribe<T: DeserializeOwned + Unpin + Clone + Send + Sync + 'static>(
+ &self,
+ event: impl Into<String>,
+ ) -> EventSubscription<T> {
+ let event_name = event.into();
+ {
+ let subs = self.subscriptions.read();
+ if let Some(sub) = subs.get(&event_name) {
+ if let Some(typed_sub) = sub.downcast_ref::<EventSubscription<T>>() {
+ return typed_sub.clone();
+ }
+ }
+ }
+
+ let rx = self.sender.subscribe();
+ let sub = EventSubscription {
+ stream: Box::pin(BroadcastStream::new(rx)),
+ event_name: event_name.clone(),
+ _phantom: std::marker::PhantomData,
+ };
+
+ let mut subs = self.subscriptions.write();
+ subs.insert(event_name, Box::new(sub.clone()));
+ sub
+ }
+}
+
+pub fn subscribe_to_event<T: DeserializeOwned + Unpin + Clone + Send + Sync + 'static>(
+ event: impl Into<String>,
+) -> EventSubscription<T> {
+ EventManager::instance().subscribe::<T>(event)
+}
+
+pub fn subscribe_to_all_events() -> EventSubscription<serde_json::Value> {
+ EventManager::instance().subscribe::<serde_json::Value>("")
+}
diff --git a/screenpipe-events/src/lib.rs b/screenpipe-events/src/lib.rs
new file mode 100644
index 000000000..470eed5d3
--- /dev/null
+++ b/screenpipe-events/src/lib.rs
@@ -0,0 +1,7 @@
+mod events_manager;
+
+pub use events_manager::*;
+
+mod custom_events;
+
+pub use custom_events::meetings::*;
diff --git a/screenpipe-events/tests/cross_crate_events_test.rs b/screenpipe-events/tests/cross_crate_events_test.rs
new file mode 100644
index 000000000..556b29f8a
--- /dev/null
+++ b/screenpipe-events/tests/cross_crate_events_test.rs
@@ -0,0 +1,156 @@
+use futures::StreamExt;
+use screenpipe_events::{send_event, subscribe_to_event};
+use serde::{Deserialize, Serialize};
+use serial_test::serial;
+// Simulate crate A's types and events
+mod crate_a {
+ use super::*;
+
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+ pub struct UserEvent {
+ pub username: String,
+ pub action: String,
+ }
+}
+
+// Simulate crate B's types and events
+mod crate_b {
+ use super::*;
+
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+ pub struct ChatMessage {
+ pub from: String,
+ pub content: String,
+ }
+}
+
+#[tokio::test]
+#[serial]
+async fn test_cross_crate_events() {
+ // Subscribe to events from both crates
+ let mut user_stream = subscribe_to_event::<crate_a::UserEvent>("user_joined");
+ let mut chat_stream = subscribe_to_event::<crate_b::ChatMessage>("message_sent");
+
+ // Send events from crate A
+ let user_event = crate_a::UserEvent {
+ username: "Alice".to_string(),
+ action: "login".to_string(),
+ };
+
+ let _ = send_event("user_joined", user_event.clone());
+
+ // Send events from crate B
+ let chat_event = crate_b::ChatMessage {
+ from: "Alice".to_string(),
+ content: "Hello!".to_string(),
+ };
+
+ let _ = send_event("message_sent", chat_event.clone());
+
+ // Verify events are received correctly
+ assert_eq!(user_stream.next().await.unwrap().data, user_event);
+ assert_eq!(chat_stream.next().await.unwrap().data, chat_event);
+}
+
+#[tokio::test]
+#[serial]
+async fn test_cross_crate_type_safety() {
+ // Try to send wrong type to event (should not compile)
+ // EventManager::instance().send("user_joined", "wrong type").unwrap();
+
+ // Verify type safety across crate boundaries
+ let mut user_stream = subscribe_to_event::<crate_a::UserEvent>("user_joined");
+ let user_event = crate_a::UserEvent {
+ username: "Bob".to_string(),
+ action: "login".to_string(),
+ };
+ let _ = send_event("user_joined", user_event.clone());
+
+ assert_eq!(user_stream.next().await.unwrap().data, user_event);
+}
+
+#[tokio::test]
+#[serial]
+async fn test_cross_crate_multiple_subscribers() {
+ let mut stream1 = subscribe_to_event::<crate_a::UserEvent>("user_joined");
+ let mut stream2 = subscribe_to_event::<crate_a::UserEvent>("user_joined");
+
+ let event = crate_a::UserEvent {
+ username: "Charlie".to_string(),
+ action: "login".to_string(),
+ };
+
+ let _ = send_event("user_joined", event.clone());
+
+ assert_eq!(stream1.next().await.unwrap().data, event);
+ assert_eq!(stream2.next().await.unwrap().data, event);
+}
+
+#[tokio::test]
+#[serial]
+async fn test_multiple_event_types() {
+ let mut user_joined = subscribe_to_event::<crate_a::UserEvent>("user_joined");
+ let mut user_left = subscribe_to_event::<crate_a::UserEvent>("user_left");
+ let mut message_sent = subscribe_to_event::<crate_b::ChatMessage>("message_sent");
+ let mut message_edited = subscribe_to_event::<crate_b::ChatMessage>("message_edited");
+
+ // Send multiple different events
+ let join_event = crate_a::UserEvent {
+ username: "Alice".to_string(),
+ action: "login".to_string(),
+ };
+ let leave_event = crate_a::UserEvent {
+ username: "Bob".to_string(),
+ action: "logout".to_string(),
+ };
+ let msg_event = crate_b::ChatMessage {
+ from: "Alice".to_string(),
+ content: "Hello!".to_string(),
+ };
+ let edit_event = crate_b::ChatMessage {
+ from: "Alice".to_string(),
+ content: "Hello, world!".to_string(),
+ };
+
+ // Send all events
+ let _ = send_event("user_joined", join_event.clone());
+ let _ = send_event("user_left", leave_event.clone());
+ let _ = send_event("message_sent", msg_event.clone());
+ let _ = send_event("message_edited", edit_event.clone());
+
+ // Verify all events are received in order
+ assert_eq!(user_joined.next().await.unwrap().data, join_event);
+ assert_eq!(user_left.next().await.unwrap().data, leave_event);
+ assert_eq!(message_sent.next().await.unwrap().data, msg_event);
+ assert_eq!(message_edited.next().await.unwrap().data, edit_event);
+}
+
+#[tokio::test]
+#[serial]
+async fn test_stream_drop_behavior() {
+ // Create and immediately drop a stream
+ {
+ let _stream = subscribe_to_event::<crate_a::UserEvent>("user_joined");
+ }
+
+ // Send an event
+ let event = crate_a::UserEvent {
+ username: "Alice".to_string(),
+ action: "login".to_string(),
+ };
+
+ // This should not panic even though the stream was dropped
+ let _ = send_event("user_joined", event.clone());
+
+ // Create a new stream and verify it receives new events
+ let mut new_stream = subscribe_to_event::<crate_a::UserEvent>("user_joined");
+ let _ = send_event("user_joined", event.clone());
+ assert_eq!(new_stream.next().await.unwrap().data, event);
+}
+
+#[tokio::test]
+#[serial]
+async fn test_unregistered_event() {
+ // Attempt to send an event that hasn't been registered
+ let _ = send_event("nonexistent_event", "some data");
+}
diff --git a/screenpipe-events/tests/events_manager_test.rs b/screenpipe-events/tests/events_manager_test.rs
new file mode 100644
index 000000000..d010f14f5
--- /dev/null
+++ b/screenpipe-events/tests/events_manager_test.rs
@@ -0,0 +1,208 @@
+use futures::StreamExt;
+use screenpipe_events::{send_event, subscribe_to_all_events, subscribe_to_event};
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+use std::sync::{Arc, Mutex};
+use tokio::time::{sleep, Duration};
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+struct TestData {
+ message: String,
+ count: i32,
+}
+
+#[tokio::test]
+async fn test_single_subscriber() {
+ let mut stream = subscribe_to_event::<String>("test_event");
+ let _ = send_event("test_event", "hello".to_string());
+ assert_eq!(stream.next().await.unwrap().data, "hello");
+}
+
+#[tokio::test]
+async fn test_multiple_subscribers() {
+ let mut stream1 = subscribe_to_event::<String>("test_event");
+ let mut stream2 = subscribe_to_event::<String>("test_event");
+
+ let _ = send_event("test_event", "hello".to_string());
+
+ assert_eq!(stream1.next().await.unwrap().data, "hello");
+ assert_eq!(stream2.next().await.unwrap().data, "hello");
+}
+
+#[tokio::test]
+async fn test_different_events() {
+ let mut stream1 = subscribe_to_event::<i32>("event1");
+ let mut stream2 = subscribe_to_event::<String>("event2");
+
+ let _ = send_event("event1", 42);
+ let _ = send_event("event2", "hello".to_string());
+
+ assert_eq!(stream1.next().await.unwrap().data, 42);
+ assert_eq!(stream2.next().await.unwrap().data, "hello");
+}
+
+#[tokio::test]
+async fn test_complex_data() {
+ let mut stream = subscribe_to_event::<TestData>("complex");
+
+ let data = TestData {
+ message: "test".to_string(),
+ count: 123,
+ };
+
+ let _ = send_event("complex", data);
+
+ let received = stream.next().await.unwrap();
+ assert_eq!(received.data.message, "test");
+ assert_eq!(received.data.count, 123);
+}
+
+#[tokio::test]
+async fn test_dropped_events() {
+ let mut stream = subscribe_to_event::<i32>("drop_test");
+
+ for i in 0..10000 {
+ let _ = send_event("drop_test", i);
+ }
+
+ sleep(Duration::from_millis(100)).await;
+ let _ = send_event("drop_test", -1);
+
+ let last = stream.next().await.unwrap();
+ assert!(last.data == -1 || last.data >= 0);
+}
+
+#[tokio::test]
+async fn test_concurrent_senders() {
+ let mut stream = subscribe_to_event::<String>("concurrent_send");
+ let mut send_handles = vec![];
+ let expected_msgs: Arc<Mutex<HashSet<String>>> = Arc::new(Mutex::new(HashSet::new()));
+
+ for i in 0..10 {
+ let expected_msgs = expected_msgs.clone();
+ send_handles.push(tokio::spawn(async move {
+ let msg = format!("msg{}", i);
+ expected_msgs.lock().unwrap().insert(msg.clone());
+ let _ = send_event("concurrent_send", msg);
+ }));
+ }
+
+ for handle in send_handles {
+ handle.await.unwrap();
+ }
+
+ let mut received_msgs = HashSet::new();
+ for _ in 0..10 {
+ let msg = stream.next().await.unwrap();
+ received_msgs.insert(msg.data);
+ }
+
+ let expected_msgs = expected_msgs.lock().unwrap();
+ assert_eq!(&received_msgs, &*expected_msgs);
+}
+
+#[tokio::test]
+async fn test_unsubscribe() {
+ let mut stream1 = subscribe_to_event::<String>("unsubscribe_test");
+ let mut stream2 = subscribe_to_event::<String>("unsubscribe_test");
+
+ let _ = send_event("unsubscribe_test", "first".to_string());
+ assert_eq!(stream1.next().await.unwrap().data, "first");
+ assert_eq!(stream2.next().await.unwrap().data, "first");
+
+ drop(stream1);
+
+ let _ = send_event("unsubscribe_test", "second".to_string());
+ assert_eq!(stream2.next().await.unwrap().data, "second");
+}
+
+#[tokio::test]
+async fn test_send_without_subscribers() {
+ let _ = send_event("no_subscribers", "test".to_string());
+}
+
+#[tokio::test]
+async fn test_multiple_subscriptions_same_subscriber() {
+ let mut stream1 = subscribe_to_event::<String>("multi_sub");
+ let mut stream2 = subscribe_to_event::<String>("multi_sub");
+ let mut stream3 = subscribe_to_event::<String>("multi_sub");
+
+ let _ = send_event("multi_sub", "test".to_string());
+
+ assert_eq!(stream1.next().await.unwrap().data, "test");
+ assert_eq!(stream2.next().await.unwrap().data, "test");
+ assert_eq!(stream3.next().await.unwrap().data, "test");
+}
+
+#[tokio::test]
+async fn test_type_mismatch() {
+ let mut stream = subscribe_to_event::<String>("type_test");
+
+ // This should fail type checking at compile time now
+ // EventManager::instance().send("type_test", 42).unwrap();
+
+ let result = tokio::time::timeout(Duration::from_millis(100), stream.next()).await;
+ assert!(result.is_err());
+}
+
+#[tokio::test]
+async fn test_subscribe_macro_type_inference() {
+ let mut string_stream = subscribe_to_event::<String>("type_test1");
+ let _ = send_event("type_test1", "string data".to_string());
+ assert_eq!(string_stream.next().await.unwrap().data, "string data");
+
+ let mut int_stream = subscribe_to_event::<i32>("type_test2");
+ let _ = send_event("type_test2", 42);
+ assert_eq!(int_stream.next().await.unwrap().data, 42);
+
+ let mut complex_stream = subscribe_to_event::<TestData>("type_test3");
+ let test_data = TestData {
+ message: "test macro".to_string(),
+ count: 999,
+ };
+ let _ = send_event("type_test3", test_data);
+
+ let received = complex_stream.next().await.unwrap();
+ assert_eq!(received.data.message, "test macro");
+ assert_eq!(received.data.count, 999);
+}
+
+#[tokio::test]
+async fn test_macro_multiple_subscribers() {
+ let mut stream1 = subscribe_to_event::<String>("macro_multi");
+ let mut stream2 = subscribe_to_event::<String>("macro_multi");
+
+ let _ = send_event("macro_multi", "broadcast".to_string());
+
+ assert_eq!(stream1.next().await.unwrap().data, "broadcast");
+ assert_eq!(stream2.next().await.unwrap().data, "broadcast");
+}
+
+#[tokio::test]
+async fn test_subscribe_to_all_events() {
+ let mut stream = subscribe_to_all_events();
+ let _ = send_event("all_events", "test".to_string());
+ let _ = send_event("all_events2", 42);
+ let _ = send_event(
+ "all_events3",
+ TestData {
+ message: "test3".to_string(),
+ count: 999,
+ },
+ );
+
+ let mut events = vec![];
+
+ for _ in 0..3 {
+ tokio::select! {
+ event = stream.next() => {
+ events.push(event.unwrap());
+ }
+ _ = sleep(Duration::from_millis(100)) => {
+ println!("timeout");
+ }
+ }
+ }
+
+ assert_eq!(events.len(), 3);
+}
diff --git a/screenpipe-js/browser-sdk/src/index.ts b/screenpipe-js/browser-sdk/src/index.ts
index faaef7127..f58425ecd 100644
--- a/screenpipe-js/browser-sdk/src/index.ts
+++ b/screenpipe-js/browser-sdk/src/index.ts
@@ -1,4 +1,5 @@
import type {
+ EventStreamResponse,
InputAction,
InputControlResponse,
NotificationOptions,
@@ -12,6 +13,42 @@ import type {
import { toSnakeCase, convertToCamelCase } from "../../common/utils";
import { captureEvent, captureMainFeatureEvent } from "../../common/analytics";
+const WS_URL = "ws://localhost:3030/ws/events";
+
+// At the top of the file, add WebSocket instances
+let wsWithImages: WebSocket | null = null;
+let wsWithoutImages: WebSocket | null = null;
+
+// Update the wsEvents generator to accept includeImages parameter and manage connections
+async function* wsEvents(
+ includeImages: boolean = false
+): AsyncGenerator<EventStreamResponse, void, unknown> {
+ // Reuse existing connection or create new one
+ let ws = includeImages ? wsWithImages : wsWithoutImages;
+
+ if (!ws || ws.readyState === WebSocket.CLOSED) {
+ ws = new WebSocket(`${WS_URL}?images=${includeImages}`);
+ if (includeImages) {
+ wsWithImages = ws;
+ } else {
+ wsWithoutImages = ws;
+ }
+
+ // Wait for connection to establish
+ await new Promise((resolve, reject) => {
+ ws!.onopen = resolve;
+ ws!.onerror = reject;
+ });
+ }
+
+ while (true) {
+ const event: MessageEvent = await new Promise((resolve) => {
+ ws!.addEventListener("message", (ev: MessageEvent) => resolve(ev));
+ });
+ yield JSON.parse(event.data);
+ }
+}
+
async function sendInputControl(action: InputAction): Promise<boolean> {
const apiUrl = "http://localhost:3030";
try {
@@ -58,6 +95,9 @@ export interface BrowserPipe {
name: string,
properties?: Record<string, any>
) => Promise<void>;
+ streamEvents(
+ includeImages: boolean
+ ): AsyncGenerator<EventStreamResponse, void, unknown>;
}
class BrowserPipeImpl implements BrowserPipe {
@@ -230,10 +270,7 @@ class BrowserPipeImpl implements BrowserPipe {
void,
unknown
> {
- const eventSource = new EventSource(
- "http://localhost:3030/sse/transcriptions"
- );
- const { userId, email } = await this.initAnalyticsIfNeeded();
+ const { userId, email } = await this.initAnalyticsIfNeeded();\
try {
await this.captureEvent("stream_started", {
@@ -243,38 +280,29 @@ class BrowserPipeImpl implements BrowserPipe {
});
while (true) {
- const chunk: TranscriptionChunk = await new Promise(
- (resolve, reject) => {
- eventSource.onmessage = (event) => {
- if (event.data.trim() === "keep-alive-text") {
- return;
- }
- resolve(JSON.parse(event.data));
- };
- eventSource.onerror = (error) => {
- reject(error);
+ for await (const event of wsEvents()) {
+ if (event.name === "transcription") {
+ let chunk: TranscriptionChunk = event.data as TranscriptionChunk;
+ yield {
+ id: crypto.randomUUID(),
+ object: "text_completion_chunk",
+ created: Date.now(),
+ model: "screenpipe-realtime",
+ choices: [
+ {
+ text: chunk.transcription,
+ index: 0,
+ finish_reason: chunk.is_final ? "stop" : null,
+ },
+ ],
+ metadata: {
+ timestamp: chunk.timestamp,
+ device: chunk.device,
+ isInput: chunk.is_input,
+ },
};
}
- );
-
- yield {
- id: crypto.randomUUID(),
- object: "text_completion_chunk",
- created: Date.now(),
- model: "screenpipe-realtime",
- choices: [
- {
- text: chunk.transcription,
- index: 0,
- finish_reason: chunk.is_final ? "stop" : null,
- },
- ],
- metadata: {
- timestamp: chunk.timestamp,
- device: chunk.device,
- isInput: chunk.is_input,
- },
- };
+ }
}
} finally {
await this.captureEvent("stream_ended", {
@@ -282,17 +310,14 @@ class BrowserPipeImpl implements BrowserPipe {
distinct_id: userId,
email: email,
});
- eventSource.close();
}
}
async *streamVision(
includeImages: boolean = false
): AsyncGenerator<VisionStreamResponse, void, unknown> {
- const eventSource = new EventSource(
- `http://localhost:3030/sse/vision?images=${includeImages}`
- );
const { userId, email } = await this.initAnalyticsIfNeeded();
+
try {
await this.captureEvent("stream_started", {
feature: "vision",
@@ -300,20 +325,14 @@ class BrowserPipeImpl implements BrowserPipe {
email: email,
});
- while (true) {
- const event: VisionEvent = await new Promise((resolve, reject) => {
- eventSource.onmessage = (event) => {
- resolve(JSON.parse(event.data));
- };
- eventSource.onerror = (error) => {
- reject(error);
+ for await (const event of wsEvents(includeImages)) {
+ if (event.name === "ocr_result" || event.name === "ui_frame") {
+ let data: VisionEvent = event.data as VisionEvent;
+ yield {
+ type: event.name,
+ data,
};
- });
-
- yield {
- type: "vision_stream",
- data: event,
- };
+ }
}
} finally {
await this.captureEvent("stream_ended", {
@@ -321,7 +340,6 @@ class BrowserPipeImpl implements BrowserPipe {
distinct_id: userId,
email: email,
});
- eventSource.close();
}
}
@@ -342,6 +360,14 @@ class BrowserPipeImpl implements BrowserPipe {
if (!analyticsEnabled) return;
return captureMainFeatureEvent(featureName, properties);
}
+
+ public async *streamEvents(
+ includeImages: boolean = false
+ ): AsyncGenerator<EventStreamResponse, void, unknown> {
+ for await (const event of wsEvents(includeImages)) {
+ yield event;
+ }
+ }
}
const pipeImpl = new BrowserPipeImpl();
diff --git a/screenpipe-js/common/types.ts b/screenpipe-js/common/types.ts
index 58b779933..ffe3fd695 100644
--- a/screenpipe-js/common/types.ts
+++ b/screenpipe-js/common/types.ts
@@ -271,3 +271,8 @@ export interface VisionStreamResponse {
type: string;
data: VisionEvent;
}
+
+export interface EventStreamResponse {
+ name: string;
+ data: VisionEvent | TranscriptionChunk | any;
+}
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index fac91bac4..f22a81722 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -13,6 +13,7 @@ edition = { workspace = true }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
+screenpipe-events = { path = "../screenpipe-events" }
screenpipe-vision = { path = "../screenpipe-vision" }
screenpipe-audio = { path = "../screenpipe-audio" }
screenpipe-core = { path = "../screenpipe-core", features = ["security"] }
@@ -49,7 +50,7 @@ thiserror = "1"
sentry = { workspace = true }
# Server
-axum = { version = "0.7.5", features = ["ws"]}
+axum = { version = "0.7.5", features = ["ws"] }
axum-macros = "0.5.0"
async-stream = "0.3"
tokio = { version = "1.15", features = ["full", "tracing"] }
@@ -128,6 +129,7 @@ tokio-util = { version = "0.7", features = ["io"] }
[dev-dependencies]
env_logger = "0.10"
tempfile = "3.3.0"
+tokio-tungstenite = "0.19.0"
# Benches
criterion = { workspace = true }
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 9c3bd1581..33f004d9c 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -21,7 +21,7 @@ use screenpipe_server::{
AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, OutputFormat,
PipeCommand, VisionCommand,
},
- core::{AudioConfig, RealtimeConfig, RecordingConfig, VisionConfig},
+ core::{AudioConfig, RecordingConfig, VisionConfig},
handle_index_command,
pipe_manager::PipeInfo,
start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server,
@@ -217,7 +217,7 @@ async fn main() -> anyhow::Result<()> {
let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));
if let Some(Command::Completions { shell }) = &cli.command {
- cli.handle_completions(shell.clone())?;
+ cli.handle_completions(*shell)?;
return Ok(());
}
if let Some(command) = cli.command {
@@ -637,11 +637,6 @@ async fn main() -> anyhow::Result<()> {
};
let audio_chunk_duration = Duration::from_secs(cli.audio_chunk_duration);
- let (realtime_transcription_sender, _) = tokio::sync::broadcast::channel(1000);
- let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
- let (realtime_vision_sender, _) = tokio::sync::broadcast::channel(1000);
- let realtime_vision_sender = Arc::new(realtime_vision_sender.clone());
- let realtime_vision_sender_clone = realtime_vision_sender.clone();
let dm_clone = device_manager.clone();
let device_manager_clone = device_manager.clone();
@@ -673,10 +668,8 @@ async fn main() -> anyhow::Result<()> {
let runtime = &tokio::runtime::Handle::current();
runtime.spawn(async move {
loop {
- let realtime_vision_sender_clone = realtime_vision_sender.clone();
let vad_engine_clone = vad_engine.clone(); // Clone it here for each iteration
let mut shutdown_rx = shutdown_tx_clone.subscribe();
- let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
// Create the configs
let recording_config = RecordingConfig {
@@ -708,17 +701,11 @@ async fn main() -> anyhow::Result<()> {
include_windows: cli.included_windows.clone(),
};
- let realtime_config = RealtimeConfig {
- transcription_sender: Arc::new(realtime_transcription_sender_clone),
- vision_sender: realtime_vision_sender_clone,
- };
-
let recording_future = start_continuous_recording(
db_clone.clone(),
recording_config,
audio_config,
vision_config,
- realtime_config,
&vision_handle,
&audio_handle,
device_manager.clone(),
@@ -762,7 +749,6 @@ async fn main() -> anyhow::Result<()> {
}
};
- let realtime_vision_sender_clone = realtime_vision_sender_clone.clone();
let server = Server::new(
db_server,
SocketAddr::from(([127, 0, 0, 1], cli.port)),
@@ -772,9 +758,6 @@ async fn main() -> anyhow::Result<()> {
cli.disable_vision,
cli.disable_audio,
cli.enable_ui_monitoring,
- cli.enable_realtime_audio_transcription,
- realtime_transcription_sender_clone,
- realtime_vision_sender_clone.clone(),
);
tokio::spawn(async move {
@@ -1193,7 +1176,7 @@ async fn main() -> anyhow::Result<()> {
loop {
tokio::select! {
- result = run_ui(realtime_vision_sender_clone.clone()) => {
+ result = run_ui() => {
match result {
Ok(_) => break,
Err(e) => {
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 98767f837..ce22dc825 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -5,14 +5,14 @@ use anyhow::Result;
use futures::future::join_all;
use futures::StreamExt;
use log::{debug, error, info, warn};
-use screenpipe_audio::realtime::RealtimeTranscriptionEvent;
use screenpipe_audio::{
record_and_transcribe, AudioInput, AudioTranscriptionEngine, TranscriptionResult,
};
use screenpipe_audio::{start_realtime_recording, AudioStream};
use screenpipe_core::pii_removal::remove_pii;
use screenpipe_core::{AudioDevice, DeviceManager, DeviceType, Language};
-use screenpipe_vision::core::{RealtimeVisionEvent, WindowOcr};
+use screenpipe_events::{poll_meetings_events, send_event};
+use screenpipe_vision::core::WindowOcr;
use screenpipe_vision::OcrEngine;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -53,12 +53,6 @@ pub struct VisionConfig {
pub include_windows: Vec<String>,
}
-#[derive(Clone)]
-pub struct RealtimeConfig {
- pub transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
- pub vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
-}
-
#[derive(Clone)]
pub struct VideoRecordingConfig {
pub db: Arc<DatabaseManager>,
@@ -72,7 +66,6 @@ pub struct VideoRecordingConfig {
pub video_chunk_duration: Duration,
pub languages: Vec<Language>,
pub capture_unfocused_windows: bool,
- pub realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
}
pub async fn start_continuous_recording(
@@ -80,7 +73,6 @@ pub async fn start_continuous_recording(
recording: RecordingConfig,
audio: AudioConfig,
vision: VisionConfig,
- realtime: RealtimeConfig,
vision_handle: &Handle,
audio_handle: &Handle,
device_manager: Arc<DeviceManager>,
@@ -104,7 +96,6 @@ pub async fn start_continuous_recording(
recording_config.fps,
languages_clone,
recording_config.capture_unfocused_windows,
- realtime.vision_sender,
vision.ignored_windows,
vision.include_windows,
recording_config.video_chunk_duration,
@@ -123,6 +114,10 @@ pub async fn start_continuous_recording(
let whisper_receiver_clone = audio.whisper_receiver.clone();
let db_manager_audio = Arc::clone(&db);
+ tokio::spawn(async move {
+ let _ = poll_meetings_events().await;
+ });
+
let audio_task = if !audio.disabled {
audio_handle.spawn(async move {
record_audio(
@@ -135,7 +130,6 @@ pub async fn start_continuous_recording(
audio.realtime_enabled,
audio.realtime_devices,
recording_config.languages,
- realtime.transcription_sender,
audio.deepgram_api_key,
)
.await
@@ -173,7 +167,6 @@ async fn record_vision(
fps: f64,
languages: Vec<Language>,
capture_unfocused_windows: bool,
- realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
ignored_windows: Vec<String>,
include_windows: Vec<String>,
video_chunk_duration: Duration,
@@ -208,7 +201,7 @@ async fn record_vision(
let ocr_engine = Arc::clone(&ocr_engine);
let ignored_windows_video = ignored_windows.to_vec();
let include_windows_video = include_windows.to_vec();
- let realtime_vision_sender_clone = realtime_vision_sender.clone();
+
let languages = languages.clone();
let device_manager_vision_clone = device_manager.clone();
let handle = tokio::spawn(async move {
@@ -224,7 +217,6 @@ async fn record_vision(
video_chunk_duration,
languages,
capture_unfocused_windows,
- realtime_vision_sender: realtime_vision_sender_clone,
};
if let Err(e) = record_video(device_manager_vision_clone, config).await {
@@ -322,55 +314,57 @@ async fn record_video(
let text_json =
serde_json::to_string(&window_result.text_json).unwrap_or_default();
- let text = if config.use_pii_removal {
- &remove_pii(&window_result.text)
- } else {
- &window_result.text
- };
-
- let _ = config.realtime_vision_sender.send(RealtimeVisionEvent::Ocr(
- WindowOcr {
- image: Some(frame.image.clone()),
- text: text.clone(),
- text_json: window_result.text_json.clone(),
- app_name: window_result.app_name.clone(),
- window_name: window_result.window_name.clone(),
- focused: window_result.focused,
- confidence: window_result.confidence,
- timestamp: frame.timestamp,
- },
- ));
-
- if let Err(e) = config
- .db
- .insert_ocr_text(
- frame_id,
- text,
- &text_json,
- &window_result.app_name,
- &window_result.window_name,
- Arc::clone(&config.ocr_engine),
- window_result.focused,
- )
- .await
- {
- error!(
- "Failed to insert OCR text: {}, skipping window {} of frame {}",
- e, window_result.window_name, frame_id
+ let text = if config.use_pii_removal {
+ &remove_pii(&window_result.text)
+ } else {
+ &window_result.text
+ };
+
+ let _ = send_event(
+ "ocr_result",
+ WindowOcr {
+ image: Some(frame.image.clone()),
+ text: text.clone(),
+ text_json: window_result.text_json.clone(),
+ app_name: window_result.app_name.clone(),
+ window_name: window_result.window_name.clone(),
+ focused: window_result.focused,
+ confidence: window_result.confidence,
+ timestamp: frame.timestamp,
+ },
);
- continue;
+
+ if let Err(e) = config.db
+ .insert_ocr_text(
+ frame_id,
+ text,
+ &text_json,
+ &window_result.app_name,
+ &window_result.window_name,
+ Arc::clone(&config.ocr_engine),
+ window_result.focused, // Add this line
+ )
+ .await
+ {
+ error!(
+ "Failed to insert OCR text: {}, skipping window {} of frame {}",
+ e, window_result.window_name, frame_id
+ );
+ continue;
+ }
}
+
+ Err(e) => {
+ warn!("Failed to insert frame: {}", e);
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ continue;
}
- Err(e) => {
- warn!("Failed to insert frame: {}", e);
- tokio::time::sleep(Duration::from_millis(100)).await;
- continue;
+ }
+ }
+ }
}
- }
- }
- }
- }
}
+ tokio::time::sleep(Duration::from_secs_f64(1.0 / config.fps)).await;
}
}
@@ -384,14 +378,12 @@ async fn record_audio(
realtime_audio_enabled: bool,
realtime_audio_devices: Vec<Arc<AudioDevice>>,
languages: Vec<Language>,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
deepgram_api_key: Option<String>,
) -> Result<()> {
let mut handles: HashMap<String, JoinHandle<()>> = HashMap::new();
let mut device_states = device_manager.watch_devices().await;
let mut previous_transcript = "".to_string();
let mut previous_transcript_id: Option<i64> = None;
- let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
loop {
tokio::select! {
@@ -420,8 +412,6 @@ async fn record_audio(
let realtime_audio_devices_clone = realtime_audio_devices.clone();
let languages_clone = languages.clone();
- let realtime_transcription_sender_clone =
- realtime_transcription_sender_clone.clone();
let deepgram_api_key_clone = deepgram_api_key.clone();
let device_receiver_clone = device_manager.clone();
let device_receiver_clone_clone = device_receiver_clone.clone();
@@ -497,26 +487,23 @@ async fn record_audio(
recording_handles.push(handle);
}
- let audio_device_clone = audio_device_clone.clone();
- let realtime_audio_devices_clone = realtime_audio_devices_clone.clone();
- let languages_clone = languages_clone.clone();
- let is_running_loop = is_running_loop.clone();
- let realtime_transcription_sender_clone =
- realtime_transcription_sender_clone.clone();
- let live_transcription_handle = Some(tokio::spawn(async move {
- if realtime_audio_enabled
- && realtime_audio_devices_clone.contains(&audio_device_clone)
- {
- let _ = start_realtime_recording(
- audio_stream_clone,
- languages_clone.clone(),
- is_running_loop.clone(),
- realtime_transcription_sender_clone.clone(),
- deepgram_api_key.clone(),
- )
- .await;
- }
- }));
+ let audio_device_clone = audio_device_clone.clone();
+ let realtime_audio_devices_clone = realtime_audio_devices_clone.clone();
+ let languages_clone = languages_clone.clone();
+ let is_running_loop = is_running_loop.clone();
+ let live_transcription_handle = Some(tokio::spawn(async move {
+ if realtime_audio_enabled
+ && realtime_audio_devices_clone.contains(&audio_device_clone)
+ {
+ let _ = start_realtime_recording(
+ audio_stream_clone,
+ languages_clone.clone(),
+ is_running_loop.clone(),
+ deepgram_api_key.clone(),
+ )
+ .await;
+ }
+ }));
if let Some(handle) = live_transcription_handle {
recording_handles.push(handle);
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index abbfcb773..be756f124 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1,11 +1,11 @@
use axum::{
body::Body,
extract::{
- ws::{Message, WebSocket},
- Json, Path, Query, State, WebSocketUpgrade,
+ ws::{Message, WebSocket, WebSocketUpgrade},
+ Json, Path, Query, State,
},
http::StatusCode,
- response::{sse::Event, IntoResponse, Json as JsonResponse, Response, Sse},
+ response::{IntoResponse, Json as JsonResponse, Response},
routing::{get, post},
serve, Router,
};
@@ -15,10 +15,11 @@ use tokio::fs::File;
use futures::{
future::{try_join, try_join_all},
- SinkExt, Stream, StreamExt,
+ SinkExt, StreamExt,
};
use image::ImageFormat::{self};
use screenpipe_core::{AudioDevice, AudioDeviceType, DeviceControl, DeviceManager};
+use screenpipe_events::{send_event, subscribe_to_all_events, Event as ScreenpipeEvent};
use crate::{
db_types::{ContentType, FrameData, SearchResult, Speaker, TagContentType},
@@ -34,17 +35,13 @@ use crate::{
use crate::{plugin::ApiPluginLayer, video_utils::extract_frame};
use chrono::{DateTime, Utc};
use log::{debug, error, info};
-use screenpipe_audio::{
- default_input_device, default_output_device, list_audio_devices,
- realtime::RealtimeTranscriptionEvent,
-};
+use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices};
+use screenpipe_vision::monitor::list_monitors;
use screenpipe_vision::OcrEngine;
-use screenpipe_vision::{core::RealtimeVisionEvent, monitor::list_monitors};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{json, Value};
use std::{
- convert::Infallible,
net::SocketAddr,
num::NonZeroUsize,
path::PathBuf,
@@ -84,10 +81,6 @@ pub struct AppState {
pub ui_monitoring_enabled: bool,
pub frame_cache: Option<Arc<FrameCache>>,
pub frame_image_cache: Option<Arc<Mutex<LruCache<i64, (String, Instant)>>>>,
- pub realtime_transcription_enabled: bool,
- pub realtime_transcription_sender:
- Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
- pub realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
}
// Update the SearchQuery struct
@@ -863,9 +856,6 @@ pub struct Server {
vision_disabled: bool,
audio_disabled: bool,
ui_monitoring_enabled: bool,
- realtime_transcription_enabled: bool,
- realtime_transcription_sender: tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>,
- realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
}
impl Server {
@@ -879,9 +869,6 @@ impl Server {
vision_disabled: bool,
audio_disabled: bool,
ui_monitoring_enabled: bool,
- realtime_transcription_enabled: bool,
- realtime_transcription_sender: tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>,
- realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
) -> Self {
Server {
db,
@@ -892,9 +879,6 @@ impl Server {
vision_disabled,
audio_disabled,
ui_monitoring_enabled,
- realtime_transcription_enabled,
- realtime_transcription_sender,
- realtime_vision_sender,
}
}
@@ -931,9 +915,6 @@ impl Server {
} else {
None
},
- realtime_transcription_enabled: self.realtime_transcription_enabled,
- realtime_transcription_sender: Arc::new(self.realtime_transcription_sender),
- realtime_vision_sender: self.realtime_vision_sender,
});
let app = create_router()
@@ -1648,38 +1629,6 @@ async fn get_similar_speakers_handler(
Ok(JsonResponse(similar_speakers))
}
-
-async fn sse_transcription_handler(
- State(state): State<Arc<AppState>>,
-) -> Result<
- Sse<impl Stream<Item = Result<Event, Infallible>>>,
- (StatusCode, JsonResponse<serde_json::Value>),
-> {
- if !state.realtime_transcription_enabled {
- return Err((
- StatusCode::FORBIDDEN,
- JsonResponse(json!({"error": "Real-time transcription is not enabled"})),
- ));
- }
-
- // Get a new subscription - this won't affect the sender
- let rx = state.realtime_transcription_sender.subscribe();
-
- let stream = async_stream::stream! {
- let mut rx = rx; // Create a new mutable reference to the receiver
- while let Ok(event) = rx.recv().await {
- yield Ok(Event::default().data(serde_json::to_string(&event).unwrap_or_default()));
- }
- // Even if this stream ends, the sender remains active
- };
-
- Ok(Sse::new(stream).keep_alive(
- axum::response::sse::KeepAlive::new()
- .interval(Duration::from_secs(1))
- .text("keep-alive-text"),
- ))
-}
-
#[derive(Deserialize)]
pub struct AudioDeviceControlRequest {
device_name: String,
@@ -1784,53 +1733,10 @@ async fn stop_audio_device(
}
#[derive(Deserialize)]
-struct VisionSSEQuery {
+struct EventsQuery {
images: Option<bool>,
}
-async fn sse_vision_handler(
- Query(query): Query<VisionSSEQuery>,
- State(state): State<Arc<AppState>>,
-) -> Result<
- Sse<impl Stream<Item = Result<Event, Infallible>>>,
- (StatusCode, JsonResponse<serde_json::Value>),
-> {
- if state.vision_disabled {
- return Err((
- StatusCode::FORBIDDEN,
- JsonResponse(json!({"error": "Vision streaming is disabled"})),
- ));
- }
- // Get a new subscription - this won't affect the sender
- let rx = state.realtime_vision_sender.subscribe();
-
- let include_images = query.images.unwrap_or(false);
-
- let stream = async_stream::stream! {
- let mut rx = rx; // Create a new mutable reference to the receiver
- while let Ok(event) = rx.recv().await {
- match event {
- RealtimeVisionEvent::Ocr(mut frame) => {
- if !include_images {
- frame.image = None; // Remove the image data if not enabled
- }
- yield Ok(Event::default().data(serde_json::to_string(&frame).unwrap_or_default()));
- }
- _ => {
- yield Ok(Event::default().data(serde_json::to_string(&event).unwrap_or_default()));
- }
- }
- }
- // Even if this stream ends, the sender remains active
- };
-
- Ok(Sse::new(stream).keep_alive(
- axum::response::sse::KeepAlive::new()
- .interval(Duration::from_secs(1))
- .text("keep-alive-text"),
- ))
-}
-
#[derive(Debug, Deserialize)]
struct SemanticSearchQuery {
text: String,
@@ -1966,6 +1872,64 @@ async fn stop_vision_device(
}))
}
+// websocket events handler
+async fn ws_events_handler(ws: WebSocketUpgrade, query: Query<EventsQuery>) -> Response {
+ ws.on_upgrade(|socket| handle_socket(socket, query))
+}
+
+async fn handle_socket(socket: WebSocket, query: Query<EventsQuery>) {
+ let (mut sender, mut receiver) = socket.split();
+
+ let incoming = tokio::spawn(async move {
+ while let Some(Ok(msg)) = receiver.next().await {
+ if let Message::Text(t) = msg {
+ if let Ok(event) = serde_json::from_str::<ScreenpipeEvent>(&t) {
+ let _ = send_event(&event.name, event.data);
+ }
+ }
+ }
+ });
+ // Handle the WebSocket connection here
+ // You can add your logic to handle messages, upgrades, etc.
+
+ let outgoing = tokio::spawn(async move {
+ let mut stream = subscribe_to_all_events();
+ loop {
+ tokio::select! {
+ event = stream.next() => {
+ if let Some(mut event) = event {
+ if !query.images.unwrap_or(false) && (event.name == "ocr_result" || event.name == "ui_frame") {
+ if let Some(data) = event.data.as_object_mut() {
+ data.remove("image");
+ }
+ }
+ if let Err(e) = sender
+ .send(Message::Text(
+ serde_json::to_string(&event).unwrap_or_default(),
+ ))
+ .await
+ {
+ tracing::error!("Failed to send websocket message: {}", e);
+ break;
+ }
+ }
+ }
+ _ = tokio::time::sleep(Duration::from_secs(1)) => {
+ let _ = sender.send(Message::Ping(vec![])).await;
+ }
+ }
+ }
+ });
+
+ // Wait for either task to finish
+ tokio::select! {
+ _ = incoming => {}
+ _ = outgoing => {}
+ }
+
+ debug!("WebSocket connection closed");
+}
+
pub fn create_router() -> Router<Arc<AppState>> {
let cors = CorsLayer::new()
.allow_origin(Any)
@@ -2011,10 +1975,9 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/speakers/similar", get(get_similar_speakers_handler))
.route("/experimental/frames/merge", post(merge_frames_handler))
.route("/experimental/validate/media", get(validate_media_handler))
- .route("/sse/transcriptions", get(sse_transcription_handler))
.route("/audio/start", post(start_audio_device))
.route("/audio/stop", post(stop_audio_device))
- .route("/sse/vision", get(sse_vision_handler))
+ .route("/ws/events", get(ws_events_handler))
.route("/semantic-search", get(semantic_search_handler))
.route("/frames/:frame_id", get(get_frame_data))
.route("/vision/start", post(start_vision_device))
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 603d57f8c..44dac7f23 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -42,9 +42,7 @@ mod tests {
FrameCache::new(PathBuf::from(""), db).await.unwrap(),
)),
ui_monitoring_enabled: false,
- realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
- realtime_transcription_enabled: false,
- realtime_vision_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
+ frame_image_cache: None,
});
let router = create_router();
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index a9315366d..a9b9fce6c 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -36,9 +36,7 @@ async fn setup_test_app() -> (Router, Arc<AppState>) {
FrameCache::new(PathBuf::from(""), db).await.unwrap(),
)),
ui_monitoring_enabled: false,
- realtime_transcription_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
- realtime_transcription_enabled: false,
- realtime_vision_sender: Arc::new(tokio::sync::broadcast::channel(1000).0),
+ frame_image_cache: None,
});
let app = create_router().with_state(app_state.clone());
diff --git a/screenpipe-server/tests/websockets_test.rs b/screenpipe-server/tests/websockets_test.rs
new file mode 100644
index 000000000..0f3f16327
--- /dev/null
+++ b/screenpipe-server/tests/websockets_test.rs
@@ -0,0 +1,32 @@
+use futures::{SinkExt, StreamExt};
+
+#[tokio::test]
+#[ignore] // only run locally atm
+async fn send_test_event() {
+ let url = "ws://127.0.0.1:3030/ws/events";
+ let (ws_stream, _) = tokio_tungstenite::connect_async(url)
+ .await
+ .expect("Failed to connect to websocket");
+
+ let (mut write, mut read) = ws_stream.split();
+ let test_event = serde_json::json!({
+ "name": "test_event",
+ "data": 123
+ });
+
+ write
+ .send(tokio_tungstenite::tungstenite::Message::Text(
+ test_event.to_string(),
+ ))
+ .await
+ .expect("Failed to send message");
+
+ println!("waiting for event");
+
+ // Keep the connection alive while waiting for the event
+ tokio::select! {
+ ws_msg = read.next() => {
+ println!("Received websocket message: {:?}", ws_msg);
+ }
+ }
+}
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index aebc8628a..f7eb95446 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -33,6 +33,7 @@ clap = { version = "4.0", features = ["derive"] }
# Integrations
screenpipe-integrations = { path = "../screenpipe-integrations" }
+screenpipe-events = { path = "../screenpipe-events" }
# Lanuage specification
screenpipe-core = { path = "../screenpipe-core" }
diff --git a/screenpipe-vision/bin/ui_monitor b/screenpipe-vision/bin/ui_monitor
index 602bde837..c18230ba8 100755
Binary files a/screenpipe-vision/bin/ui_monitor and b/screenpipe-vision/bin/ui_monitor differ
diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin
index 602bde837..c18230ba8 100755
Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin differ
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index c7ea80ad4..14683e29b 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -21,7 +21,6 @@ use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde_json;
-use tracing::warn;
use std::sync::Arc;
use std::{
collections::HashMap,
@@ -32,6 +31,7 @@ use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc::Sender;
use tokio::sync::watch;
use tracing::info;
+use tracing::warn;
#[cfg(target_os = "macos")]
use xcap_macos::Monitor;
@@ -339,7 +339,7 @@ pub async fn process_ocr_task(
window_count += 1;
}
- window_ocr_results.push(WindowOcrResult {
+ let ocr_result = WindowOcrResult {
image: captured_window.image,
window_name: captured_window.window_name,
app_name: captured_window.app_name,
@@ -347,7 +347,9 @@ pub async fn process_ocr_task(
text_json: parse_json_output(&window_json_output),
focused: captured_window.is_focused,
confidence: confidence.unwrap_or(0.0),
- });
+ };
+
+ window_ocr_results.push(ocr_result);
}
let capture_result = CaptureResult {
diff --git a/screenpipe-vision/src/run_ui_monitoring_macos.rs b/screenpipe-vision/src/run_ui_monitoring_macos.rs
index 044a2f84c..f852840d2 100644
--- a/screenpipe-vision/src/run_ui_monitoring_macos.rs
+++ b/screenpipe-vision/src/run_ui_monitoring_macos.rs
@@ -1,5 +1,6 @@
use anyhow::Result;
use log::{debug, error, info, warn};
+use screenpipe_events::send_event;
use std::fs;
use std::io;
use std::path::PathBuf;
@@ -13,12 +14,9 @@ use tokio::signal;
use tokio::time::{sleep, timeout, Duration};
use which::which;
-use crate::core::RealtimeVisionEvent;
use crate::UIFrame;
-pub async fn run_ui(
- realtime_vision_sender: Arc<tokio::sync::broadcast::Sender<RealtimeVisionEvent>>,
-) -> Result<()> {
+pub async fn run_ui() -> Result<()> {
info!("starting ui monitoring service...");
let binary_name = "ui_monitor";
@@ -133,7 +131,7 @@ pub async fn run_ui(
frame = UIFrame::read_from_pipe(&mut reader) => {
match frame {
Ok(frame) => {
- let _ = realtime_vision_sender.send(RealtimeVisionEvent::Ui(frame));
+ let _ = send_event("ui_frame", frame);
}
Err(e) => {
if let Some(io_err) = e.downcast_ref::<io::Error>() {