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

feat: integrate Highlight into screenpipe (#611)

ToSevenad9b78c480a9
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 3b2a78ccd..13a1fec2c 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -42,6 +42,15 @@ anyhow = "1.0.86"
hf-hub = "0.3.2"
rand = "0.8.5"
+thiserror="1"
+
+#opentelemetry
+opentelemetry = "0.21"
+opentelemetry-appender-tracing = "0.2"
+opentelemetry-otlp = {version="0.14", features=["http-proto","reqwest-rustls","tokio","reqwest-client"]}
+opentelemetry_sdk = {version="0.21",default-features = false,features=["rt-tokio"]}
+opentelemetry-semantic-conventions = "0.13"
+
# Server
axum = "0.7.5"
async-stream = "0.3"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index d3cc3790f..d3ffa75cb 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -13,7 +13,7 @@ use screenpipe_audio::{
};
use screenpipe_core::find_ffmpeg_path;
use screenpipe_server::{
- cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, start_continuous_recording, watch_pid, DatabaseManager, PipeControl, PipeManager, ResourceMonitor, Server
+ cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, start_continuous_recording, watch_pid, DatabaseManager, PipeControl, PipeManager, ResourceMonitor, Server, highlight::{Highlight,HighlightConfig}
};
use screenpipe_vision::monitor::list_monitors;
use screenpipe_vision::run_ui;
@@ -115,6 +115,12 @@ async fn main() -> anyhow::Result<()> {
let _log_guard = setup_logging(&local_data_dir, &cli)?;
+ let h = Highlight::init(HighlightConfig {
+ project_id:String::from("7e30w91e"),
+ ..Default::default()
+ })
+ .expect("Failed to initialize Highlight.io");
+
let (pipe_manager, mut pipe_control_rx) = PipeManager::new(local_data_dir_clone.clone());
let pipe_manager = Arc::new(pipe_manager);
@@ -134,6 +140,7 @@ async fn main() -> anyhow::Result<()> {
if let Err(e) = trigger_keyboard_permission() {
error!("Failed to trigger keyboard permission: {:?}", e);
error!("Please grant keyboard permission manually in System Preferences.");
+ h.capture_error("Please grant keyboard permission manually in System Preferences.");
} else {
info!("Keyboard permission requested. Please grant permission if prompted.");
}
@@ -145,6 +152,7 @@ async fn main() -> anyhow::Result<()> {
if let Err(e) = trigger_audio_permission() {
error!("Failed to trigger audio permission: {:?}", e);
error!("Please grant microphone permission manually in System Preferences.");
+ h.capture_error("Please grant microphone permission manually in System Preferences.");
} else {
info!("Audio permission requested. Please grant permission if prompted.");
}
@@ -153,6 +161,7 @@ async fn main() -> anyhow::Result<()> {
if let Err(e) = trigger_screen_capture_permission() {
error!("Failed to trigger screen capture permission: {:?}", e);
error!("Please grant screen recording permission manually in System Preferences.");
+ h.capture_error("Please grant microphone permission manually in System Preferences.");
} else {
info!("Screen capture permission requested. Please grant permission if prompted.");
}
@@ -170,6 +179,7 @@ async fn main() -> anyhow::Result<()> {
Err(e) => {
error!("FFmpeg check failed: {}", e);
error!("Please ensure FFmpeg is installed correctly and is in your PATH");
+ h.capture_error("Please ensure FFmpeg is installed correctly and is in your PATH");
return Err(e.into());
}
}
@@ -633,6 +643,7 @@ async fn main() -> anyhow::Result<()> {
.bright_yellow()
);
} else {
+ h.shutdown();
println!(
"{}",
"telemetry is disabled. no data will be sent to external services."
@@ -768,6 +779,7 @@ async fn main() -> anyhow::Result<()> {
}
}
+ h.shutdown();
info!("shutdown complete");
Ok(())
diff --git a/screenpipe-server/src/highlight.rs b/screenpipe-server/src/highlight.rs
new file mode 100644
index 000000000..c2c290861
--- /dev/null
+++ b/screenpipe-server/src/highlight.rs
@@ -0,0 +1,210 @@
+use std::{
+ borrow::Cow, error::Error,sync::Arc, time::Duration
+};
+
+pub use opentelemetry::trace::Span as SpanTrait;
+use opentelemetry::{
+ global,
+ trace::{Status, TraceContextExt, Tracer as _},
+ KeyValue,
+};
+use opentelemetry_otlp::{
+ OtlpTracePipeline, SpanExporterBuilder, WithExportConfig,
+};
+use opentelemetry_sdk::{
+ propagation::TraceContextPropagator,
+ resource::Resource,
+ trace::{self, BatchConfig, Span, Tracer},
+};
+
+use opentelemetry_semantic_conventions::resource::{SERVICE_NAME, SERVICE_VERSION};
+
+use opentelemetry::{logs::LogError, trace::TraceError};
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum HighlightError {
+ /// Config error during setup
+ #[error("Highlight Config error: {0}")]
+ Config(String),
+
+ /// Errors from the log SDK
+ #[error(transparent)]
+ Log(LogError),
+
+ /// Errors from the trace SDK
+ #[error(transparent)]
+ Trace(TraceError),
+}
+
+
+
+impl From<TraceError> for HighlightError {
+ fn from(value: TraceError) -> Self {
+ HighlightError::Trace(value)
+ }
+}
+
+
+pub mod otel {
+ pub use opentelemetry::KeyValue;
+}
+
+pub struct HighlightConfig {
+ /// Your highlight.io Project ID
+ pub project_id: String,
+
+ /// The name of your app.
+ pub service_name: Option<String>,
+
+ /// The version of your app. We recommend setting this to the most recent deploy SHA of your app.
+ pub service_version: Option<String>,
+
+}
+
+impl Default for HighlightConfig {
+ fn default() -> Self {
+ Self {
+ project_id: Default::default(),
+ service_name: Default::default(),
+ service_version: Default::default(),
+ }
+ }
+}
+
+struct HighlightInner {
+ config: HighlightConfig,
+ tracer: Tracer,
+}
+
+#[derive(Clone)]
+pub struct Highlight(Arc<HighlightInner>);
+
+impl Highlight {
+ fn install_pipelines(
+ tracing: OtlpTracePipeline<SpanExporterBuilder>,
+ ) -> Result<Tracer, HighlightError> {
+ Ok(
+ tracing.install_batch(opentelemetry_sdk::runtime::Tokio)?,
+ )
+ }
+
+ fn get_default_resource(config: &HighlightConfig) -> Resource {
+ let mut attrs = Vec::with_capacity(2);
+ attrs.push(KeyValue::new(
+ "highlight.project_id",
+ config.project_id.clone(),
+ ));
+
+ if let Some(service_name) = &config.service_name {
+ attrs.push(KeyValue::new(SERVICE_NAME, service_name.to_owned()));
+ }
+
+ if let Some(service_version) = &config.service_version {
+ attrs.push(KeyValue::new(SERVICE_VERSION, service_version.to_owned()));
+ }
+
+ Resource::new(attrs)
+ }
+
+ fn make_install_pipelines(
+ config: &HighlightConfig,
+ ) -> Result<Tracer, HighlightError> {
+ let tracing = opentelemetry_otlp::new_pipeline()
+ .tracing()
+ .with_trace_config(
+ trace::config()
+ .with_sampler(trace::Sampler::AlwaysOn)
+ .with_resource(Self::get_default_resource(config)),
+ )
+ .with_batch_config(
+ BatchConfig::default()
+ .with_scheduled_delay(Duration::from_millis(1000))
+ .with_max_export_batch_size(128)
+ .with_max_queue_size(1024),
+ )
+ .with_exporter(
+ opentelemetry_otlp::new_exporter()
+ .http()
+ .with_endpoint("https://otel.highlight.io:4318"),
+ );
+ Self::install_pipelines(tracing)
+ }
+
+ /// Initialize Highlight.
+ pub fn init(config: HighlightConfig) -> Result<Highlight, HighlightError> {
+ if config.project_id == String::default() {
+ return Err(HighlightError::Config(
+ "You must specify a project_id in your HighlightConfig".to_string(),
+ ));
+ }
+
+ global::set_text_map_propagator(TraceContextPropagator::new());
+ let tracer = Self::make_install_pipelines(&config)?;
+
+ let h = Highlight(Arc::new(HighlightInner {
+ config,
+ tracer,
+ }));
+
+ Ok(h)
+ }
+
+
+ /// Capture an error with session info
+ ///
+ /// Like Highlight::capture_error, but also lets you provide your session_id and request_id
+ pub fn capture_error_with_session(
+ &self,
+ err: &dyn Error,
+ session_id: Option<String>,
+ request_id: Option<String>,
+ ) {
+ self.0.tracer.in_span("highlight-ctx", |cx| {
+ cx.span().record_error(err);
+
+ if let Some(session_id) = session_id {
+ cx.span()
+ .set_attribute(KeyValue::new("highlight.session_id", session_id));
+ }
+
+ if let Some(request_id) = request_id {
+ cx.span()
+ .set_attribute(KeyValue::new("highlight.trace_id", request_id));
+ }
+
+ cx.span().set_status(Status::error(format!("{:?}", err)));
+ });
+ }
+
+ /// Capture an error
+ ///
+ /// Explicitly captures any type with trait Error and sends it to Highlight.
+ pub fn capture_error(&self, err: &str) {
+ let e = std::io::Error::new(
+ std::io::ErrorKind::Other,
+ err
+ );
+ self.capture_error_with_session(&e, None, None);
+ }
+
+ /// Create a span
+ ///
+ /// Creates a span for tracing. You can end it with span.end() by importing highlightio::SpanTrait.
+ pub fn span(&self, name: impl Into<Cow<'static, str>>) -> Span {
+ self.0.tracer.start(name)
+ }
+
+ /// Returns the project ID.
+ pub fn project_id(&self) -> String {
+ self.0.config.project_id.clone()
+ }
+
+ /// Shuts down the Highlight tracer.
+ /// This allows for the traces to flush while the runtime is still around.
+ /// If this method is not called, traces that happened right before your app exits will not be transmitted to Highlight.
+ pub fn shutdown(&self) {
+ global::shutdown_tracer_provider();
+ }
+}
+
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 2b11d0d60..1ad1d8907 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -2,6 +2,7 @@ mod auto_destruct;
pub mod chunking;
pub mod cli;
pub mod core;
+pub mod highlight;
mod db;
pub mod filtering;
mod pipe_manager;
@@ -29,3 +30,6 @@ pub use server::HealthCheckResponse;
pub use server::PaginatedResponse;
pub use server::Server;
pub use video::VideoCapture;
+pub use pipe_manager::PipeControl;
+pub use highlight::Highlight;
+