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

fix: memory leak #1269, document how to use tokio-console, refactor: improve obsidian prompt to link people using obsidian syntax, refactor: improve ux to display user is logged in, refactor: make share log use the backend log instead of app by default, fix: #1202

Louis Beaumontbb5232d54018
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index acc826d53..7c58b81fe 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -321,6 +321,16 @@ run locally: https://github.com/nektos/act
### debugging memory errors
+using tokio-console:
+
+```bash
+# terminal 1
+RUST_LOG="tokio=debug,runtime=debug" RUSTFLAGS="--cfg tokio_unstable" cargo run --bin screenpipe --features debug-console
+# terminal 2
+cargo install tokio-console
+tokio-console
+```
+
```bash
RUSTFLAGS="-Z sanitizer=address" cargo run --bin screenpipe
# or
diff --git a/pipes/obsidian/src/lib/hooks/use-settings.tsx b/pipes/obsidian/src/lib/hooks/use-settings.tsx
index 495a5a091..19937b456 100644
--- a/pipes/obsidian/src/lib/hooks/use-settings.tsx
+++ b/pipes/obsidian/src/lib/hooks/use-settings.tsx
@@ -21,6 +21,7 @@ rules for the investigation:
- track project progress and blockers mentioned
style rules:
+- always put people's names in double square brackets, eg: [[John Doe]] to link to their notes, same for companies, eg: [[Google]], or projects, eg: [[Project X]]
- keep it real and conversational
- use bullet points for clarity
- include relevant timestamps
@@ -29,7 +30,10 @@ style rules:
- no corporate speak, keep it human
- for tags use hyphen between words, no spaces, eg: #my-tag not #my tag nor #myTag nor #my_tag
-remember: you're analyzing screen ocr text & audio, etc. from my computer, so focus on actual interactions and content!`,
+remember: you're analyzing screen ocr text & audio, etc. from my computer, so focus on actual interactions and content!
+you'll get chunks of 5 mins roughly of data screen & audio recordings and have to write logs.
+this data will be used later for analysis, it must contains valuable insights on what i am doing.
+if you do your job well, i'll give you a 🍺 and $1m`,
},
};
diff --git a/screenpipe-app-tauri/components/log-file-button.tsx b/screenpipe-app-tauri/components/log-file-button.tsx
index 11d883093..84a1bee56 100644
--- a/screenpipe-app-tauri/components/log-file-button.tsx
+++ b/screenpipe-app-tauri/components/log-file-button.tsx
@@ -212,9 +212,9 @@ export const LogFileButton = ({
const files = await getLogFiles();
setLogFiles(files);
- // Find most recent app log or fall back to first file
+ // Find most recent non-app log or fall back to first file
const appLog = files
- .filter((f) => f.name.toLowerCase().includes("app"))
+ .filter((f) => !f.name.toLowerCase().includes("app"))
.sort((a, b) => b.modified_at - a.modified_at)[0];
if (files.length > 0) {
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsx
index 358d9b88d..26433e9f0 100644
--- a/screenpipe-app-tauri/components/pipe-store.tsx
+++ b/screenpipe-app-tauri/components/pipe-store.tsx
@@ -165,7 +165,13 @@ export const PipeStore: React.FC = () => {
const pipeApi = await PipeApi.create(settings.user!.token!);
const response = await pipeApi.purchasePipe(pipe.id);
- if (response.data.used_credits) {
+ if (response.data.payment_successful) {
+ await handleInstallPipe(pipe);
+ toast({
+ title: "purchase & install successful",
+ description: "payment processed with saved card",
+ });
+ } else if (response.data.used_credits) {
await handleInstallPipe(pipe);
toast({
title: "purchase & install successful",
diff --git a/screenpipe-app-tauri/components/settings/account-section.tsx b/screenpipe-app-tauri/components/settings/account-section.tsx
index ed718680f..54402e73d 100644
--- a/screenpipe-app-tauri/components/settings/account-section.tsx
+++ b/screenpipe-app-tauri/components/settings/account-section.tsx
@@ -295,26 +295,56 @@ export function AccountSection() {
return (
<div className="w-full space-y-6 py-4">
<div className="flex items-center justify-between">
- <h1 className="text-2xl font-bold">account settings</h1>
+ <div className="space-y-2">
+ <h1 className="text-2xl font-bold">account settings</h1>
+ {settings.user?.email ? (
+ <p className="text-sm text-muted-foreground flex items-center gap-2">
+ <span className="inline-flex h-2 w-2 rounded-full bg-green-500" />
+ logged in as {settings.user.email}
+ </p>
+ ) : (
+ <p className="text-sm text-muted-foreground flex items-center gap-2">
+ <span className="inline-flex h-2 w-2 rounded-full bg-yellow-500" />
+ not logged in - some features will be limited
+ </p>
+ )}
+ </div>
<div className="flex gap-2">
- {settings.user?.token && (
+ {settings.user?.token ? (
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => openUrl("https://accounts.screenpi.pe/user")}
+ className="hover:bg-secondary/80"
+ >
+ manage account <UserCog className="w-4 h-4 ml-2" />
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ updateSettings({ user: { token: undefined } });
+ toast({
+ title: "logged out",
+ description: "you have been logged out",
+ });
+ }}
+ className="hover:bg-secondary/80"
+ >
+ logout <ExternalLinkIcon className="w-4 h-4 ml-2" />
+ </Button>
+ </>
+ ) : (
<Button
variant="outline"
size="sm"
- onClick={() => openUrl("https://accounts.screenpi.pe/user")}
+ onClick={() => openUrl("https://screenpi.pe/login")}
className="hover:bg-secondary/80"
>
- manage account <UserCog className="w-4 h-4 ml-2" />
+ login <ExternalLinkIcon className="w-4 h-4 ml-2" />
</Button>
)}
- <Button
- variant="outline"
- size="sm"
- onClick={() => openUrl("https://screenpi.pe/login")}
- className="hover:bg-secondary/80"
- >
- login <ExternalLinkIcon className="w-4 h-4 ml-2" />
- </Button>
</div>
</div>
diff --git a/screenpipe-app-tauri/lib/api/store/index.ts b/screenpipe-app-tauri/lib/api/store/index.ts
index 2c5be7135..b795bba8f 100644
--- a/screenpipe-app-tauri/lib/api/store/index.ts
+++ b/screenpipe-app-tauri/lib/api/store/index.ts
@@ -45,9 +45,9 @@ export interface PurchaseHistoryItem {
interface PurchaseUrlResponse {
data: {
- checkout_url: string;
- // when user had credits from previous app purchase
+ checkout_url?: string;
used_credits?: boolean;
+ payment_successful?: boolean;
};
}
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index 99b255308..75b794a63 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -124,7 +124,7 @@ pub struct TranscriptionResult {
impl TranscriptionResult {
// TODO --optimize
- pub fn cleanup_overlap(&mut self, previous_transcript: String) -> Option<(String, String)> {
+ pub fn cleanup_overlap(&mut self, previous_transcript: &String) -> Option<(String, String)> {
if let Some(transcription) = &self.transcription {
let transcription = transcription.to_string();
if let Some((prev_idx, cur_idx)) =
diff --git a/screenpipe-core/src/devices.rs b/screenpipe-core/src/devices.rs
index f3fa2da39..eabb4479c 100644
--- a/screenpipe-core/src/devices.rs
+++ b/screenpipe-core/src/devices.rs
@@ -2,7 +2,7 @@ use std::{collections::HashMap, fmt};
use anyhow::anyhow;
use serde::{Deserialize, Serialize};
-use tokio_stream::{wrappers::UnboundedReceiverStream, Stream};
+use tokio_stream::Stream;
use tracing::debug;
#[derive(Clone, Debug)]
@@ -125,7 +125,7 @@ pub struct DeviceManager {
sender: tokio::sync::broadcast::Sender<DeviceControl>,
#[allow(dead_code)]
_dummy: tokio::sync::broadcast::Receiver<DeviceControl>,
- state_sender: tokio::sync::mpsc::UnboundedSender<DeviceStateRequest>,
+ state_sender: tokio::sync::mpsc::Sender<DeviceStateRequest>,
}
impl Clone for DeviceManager {
@@ -145,7 +145,7 @@ enum DeviceStateRequest {
},
Update(DeviceControl),
Watch {
- respond_to: tokio::sync::mpsc::UnboundedSender<DeviceStateChange>,
+ respond_to: tokio::sync::mpsc::Sender<DeviceStateChange>,
},
}
@@ -158,7 +158,7 @@ pub struct DeviceStateChange {
impl DeviceManager {
pub fn default() -> Self {
let (sender, dummy_receiver) = tokio::sync::broadcast::channel(32);
- let (state_sender, state_receiver) = tokio::sync::mpsc::unbounded_channel();
+ let (state_sender, state_receiver) = tokio::sync::mpsc::channel(32);
tokio::spawn(async move {
Self::manage_state(state_receiver).await;
@@ -166,13 +166,12 @@ impl DeviceManager {
Self {
sender,
- // this ensures that even if devices go to 0 it still stays open
_dummy: dummy_receiver,
state_sender,
}
}
- async fn manage_state(mut receiver: tokio::sync::mpsc::UnboundedReceiver<DeviceStateRequest>) {
+ async fn manage_state(mut receiver: tokio::sync::mpsc::Receiver<DeviceStateRequest>) {
let mut devices = HashMap::new();
let mut watchers = Vec::new();
@@ -199,9 +198,9 @@ impl DeviceManager {
// Notify watchers of the change
watchers.retain(
- |watcher: &tokio::sync::mpsc::UnboundedSender<DeviceStateChange>| {
+ |watcher: &tokio::sync::mpsc::Sender<DeviceStateChange>| {
watcher
- .send(DeviceStateChange {
+ .try_send(DeviceStateChange {
device: device_id.clone(),
control: control.clone(),
})
@@ -220,9 +219,10 @@ impl DeviceManager {
pub async fn get_active_devices(&self) -> HashMap<String, DeviceControl> {
let (tx, rx) = tokio::sync::oneshot::channel();
- let _ = self
- .state_sender
- .send(DeviceStateRequest::Get { respond_to: tx });
+ self.state_sender
+ .send(DeviceStateRequest::Get { respond_to: tx })
+ .await
+ .expect("state manager task has terminated");
rx.await
.unwrap_or_default()
.into_iter()
@@ -231,18 +231,18 @@ impl DeviceManager {
}
pub async fn watch_devices(&self) -> impl Stream<Item = DeviceStateChange> {
- let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
- let _ = self
- .state_sender
- .send(DeviceStateRequest::Watch { respond_to: tx });
- UnboundedReceiverStream::new(rx)
+ let (tx, rx) = tokio::sync::mpsc::channel(32);
+ self.state_sender
+ .send(DeviceStateRequest::Watch { respond_to: tx })
+ .await
+ .expect("state manager task has terminated");
+ tokio_stream::wrappers::ReceiverStream::new(rx)
}
pub async fn update_device(&self, control: DeviceControl) -> anyhow::Result<()> {
- // Update state and broadcast change
- let _ = self
- .state_sender
- .send(DeviceStateRequest::Update(control.clone()));
+ self.state_sender
+ .send(DeviceStateRequest::Update(control.clone()))
+ .await?;
self.sender.send(control)?;
Ok(())
}
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 3017ddfc3..b72230dad 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -56,6 +56,7 @@ tower-http = { version = "0.5.2", features = ["cors", "trace"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
tracing-appender = { workspace = true }
+console-subscriber = { version = "0.4.1", optional = true }
# Cli ! shouldn't be required if using as lib
clap = { version = "4.3", features = ["derive", "env"] }
@@ -145,6 +146,7 @@ pipes = ["screenpipe-core/pipes", "url"]
llm = ["screenpipe-core/llm"]
beta = ["screenpipe-core/beta", "dep:screenpipe-actions"]
experimental = ["enigo"]
+debug-console = ["console-subscriber"]
[[bin]]
name = "screenpipe"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 7cf80a59d..35f5fbd86 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -29,6 +29,7 @@ use screenpipe_server::{
use screenpipe_vision::monitor::list_monitors;
#[cfg(target_os = "macos")]
use screenpipe_vision::run_ui;
+use serde::Deserialize;
use serde_json::{json, Value};
use std::{
collections::{HashMap, HashSet},
@@ -48,6 +49,14 @@ use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};
+// Add this struct to handle the server response structure
+#[derive(Debug, Deserialize)]
+#[allow(dead_code)]
+struct ApiResponse<T> {
+ data: T,
+ success: bool,
+}
+
const DISPLAY: &str = r"
_
__________________ ___ ____ ____ (_____ ___
@@ -84,6 +93,8 @@ fn setup_logging(local_data_dir: &PathBuf, cli: &Cli) -> anyhow::Result<WorkerGu
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let env_filter = EnvFilter::from_default_env()
+ .add_directive("tokio=debug".parse().unwrap()) // Add this
+ .add_directive("runtime=debug".parse().unwrap()) // Add this
.add_directive("info".parse().unwrap())
.add_directive("tokenizers=error".parse().unwrap())
.add_directive("rusty_tesseract=error".parse().unwrap())
@@ -157,7 +168,7 @@ async fn main() -> anyhow::Result<()> {
let local_data_dir = get_base_dir(&cli.data_dir)?;
let local_data_dir_clone = local_data_dir.clone();
- // Only set up logging if we're not running a pipe command with JSON output
+ // Determine initial logging state based on command
let should_log = match &cli.command {
Some(Command::Pipe { subcommand }) => {
matches!(
@@ -207,6 +218,15 @@ async fn main() -> anyhow::Result<()> {
_ => true,
};
+ // Override logging state if debug console is enabled
+ #[cfg(feature = "debug-console")]
+ let should_log = if cfg!(all(debug_assertions, feature = "debug-console")) {
+ console_subscriber::init();
+ false
+ } else {
+ should_log
+ };
+
// Store the guard in a variable that lives for the entire main function
let _log_guard = if should_log {
Some(setup_logging(&local_data_dir, &cli)?)
@@ -1439,24 +1459,24 @@ async fn handle_pipe_command(
}
PipeCommand::Info { id, output, port } => {
- let info = match client
+ let info: ApiResponse<PipeInfo> = match client
.get(format!("{}:{}/pipes/info/{}", server_url, port, id))
.send()
.await
{
Ok(response) if response.status().is_success() => response.json().await?,
- _ => {
- println!("note: server not running, showing pipe configuration");
- pipe_manager
+ _ => ApiResponse {
+ data: pipe_manager
.get_pipe_info(&id)
.await
- .ok_or_else(|| anyhow::anyhow!("pipe not found"))?
- }
+ .ok_or_else(|| anyhow::anyhow!("pipe not found"))?,
+ success: true,
+ },
};
match output {
- OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&info)?),
- OutputFormat::Text => println!("pipe info: {:?}", info),
+ OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&info.data)?),
+ OutputFormat::Text => println!("pipe info: {:?}", info.data),
}
}
PipeCommand::Enable { id, port } => {
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 90ad2f584..3faed30ed 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -19,7 +19,7 @@ use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle;
use tokio::task::JoinHandle;
-use tracing::{debug, error, info, warn};
+use tracing::{debug, error, info, instrument, warn};
#[derive(Clone)]
pub struct RecordingConfig {
@@ -68,6 +68,7 @@ pub struct VideoRecordingConfig {
pub capture_unfocused_windows: bool,
}
+#[instrument(skip(device_manager, db, recording, audio, vision))]
pub async fn start_continuous_recording(
db: Arc<DatabaseManager>,
recording: RecordingConfig,
@@ -178,6 +179,16 @@ async fn record_vision(
loop {
tokio::select! {
Some(state_change) = device_states.next() => {
+ // Clean up finished handles first
+ handles.retain(|monitor_id, handle| {
+ if handle.is_finished() {
+ info!("handle for monitor {} has finished", monitor_id);
+ false
+ } else {
+ true
+ }
+ });
+
match DeviceType::from_str(&state_change.device) {
Ok(DeviceType::Vision(monitor_id)) => {
debug!("record_vision: vision state change: {:?}", state_change);
@@ -236,15 +247,6 @@ async fn record_vision(
}
}
-
- handles.retain(|monitor_id, handle| {
- if handle.is_finished() {
- info!("handle for monitor {} has finished", monitor_id);
- false
- } else {
- true
- }
- });
}
}
@@ -398,12 +400,22 @@ async fn record_audio(
) -> 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 = String::new();
let mut previous_transcript_id: Option<i64> = None;
loop {
tokio::select! {
Some(state_change) = device_states.next() => {
+ // Handle cleanup of finished handles
+ handles.retain(|device_id, handle| {
+ if handle.is_finished() {
+ info!("handle for device {} has finished", device_id);
+ false
+ } else {
+ true
+ }
+ });
+
match DeviceType::from_str(&state_change.device) {
Ok(DeviceType::Audio(audio_device)) => {
let device_id = audio_device.to_string();
@@ -422,110 +434,101 @@ async fn record_audio(
info!("starting audio capture thread for device: {}", &audio_device);
- let whisper_sender_clone = whisper_sender.clone();
-
let audio_device = Arc::new(audio_device);
-
- let realtime_audio_devices_clone = realtime_audio_devices.clone();
- let languages_clone = languages.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();
- let handle = tokio::spawn(async move {
- info!(
- "starting audio capture thread for device: {}",
- &audio_device
- );
-
- let mut did_warn = false;
-
- let audio_device_clone = Arc::clone(&audio_device);
- let deepgram_api_key = deepgram_api_key_clone.clone();
- let is_running = Arc::new(AtomicBool::new(state_change.control.is_running));
-
- while is_running.load(Ordering::Relaxed) {
- let is_running_clone = is_running.clone();
- let device_receiver_monitor = device_receiver_clone_clone.clone();
- let device_id = audio_device_clone.to_string();
-
- // Monitor device state changes
- let mut device_states = device_receiver_monitor.watch_devices().await;
- tokio::spawn(async move {
- while let Some(state_change) = device_states.next().await {
- if state_change.device == device_id && !state_change.control.is_running {
- is_running_clone.store(false, Ordering::Relaxed);
- break;
+ let is_running = Arc::new(AtomicBool::new(true));
+
+ // Create a single clone of required values for the spawned task
+ let device_manager = Arc::clone(&device_manager);
+ let whisper_sender = whisper_sender.clone();
+ let languages = Arc::clone(&languages);
+ let deepgram_api_key = deepgram_api_key.clone();
+
+ let handle = tokio::spawn({
+ let audio_device = Arc::clone(&audio_device);
+ let is_running = Arc::clone(&is_running);
+ let realtime_devices = realtime_audio_devices.iter()
+ .map(Arc::clone)
+ .collect::<Vec<_>>();
+
+ async move {
+ info!("starting audio capture thread for device: {}", &audio_device);
+ let mut did_warn = false;
+
+ while is_running.load(Ordering::Relaxed) {
+ let device_id = audio_device.to_string();
+
+ // Monitor device state changes
+ let mut device_states = device_manager.watch_devices().await;
+ let is_running_clone = Arc::clone(&is_running);
+
+ tokio::spawn(async move {
+ while let Some(state_change) = device_states.next().await {
+ if state_change.device == device_id && !state_change.control.is_running {
+ is_running_clone.store(false, Ordering::Relaxed);
+ break;
+ }
}
- }
- });
-
- let deepgram_api_key = deepgram_api_key.clone();
- let is_running_loop = Arc::clone(&is_running);
- let audio_stream = match AudioStream::from_device(
- audio_device_clone.clone(),
- Arc::clone(&is_running_loop),
- )
- .await
- {
- Ok(stream) => stream,
- Err(e) => {
- if e.to_string().contains("audio device not found") {
- if !did_warn {
- warn!("audio device not found: {}", audio_device.name);
- did_warn = true;
+ });
+
+ let audio_stream = match AudioStream::from_device(
+ Arc::clone(&audio_device),
+ Arc::clone(&is_running),
+ ).await {
+ Ok(stream) => Arc::new(stream),
+ Err(e) => {
+ if e.to_string().contains("audio device not found") {
+ if !did_warn {
+ warn!("audio device not found: {}", audio_device.name);
+ did_warn = true;
+ }
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ continue;
+ } else {
+ error!("failed to create audio stream: {}", e);
+ return;
}
- tokio::time::sleep(Duration::from_secs(1)).await;
- continue;
- } else {
- error!("failed to create audio stream: {}", e);
- return;
}
+ };
+
+ let mut recording_handles = vec![];
+
+ // Spawn record and transcribe task
+ recording_handles.push(tokio::spawn({
+ let audio_stream = Arc::clone(&audio_stream);
+ let is_running = Arc::clone(&is_running);
+ let whisper_sender = whisper_sender.clone();
+
+ async move {
+ let _ = record_and_transcribe(
+ audio_stream,
+ chunk_duration,
+ whisper_sender,
+ is_running,
+ ).await;
+ }
+ }));
+
+ // Spawn realtime recording task if enabled
+ if realtime_audio_enabled && realtime_devices.contains(&audio_device) {
+ recording_handles.push(tokio::spawn({
+ let audio_stream = Arc::clone(&audio_stream);
+ let is_running = Arc::clone(&is_running);
+ let languages = Arc::clone(&languages);
+ let deepgram_api_key = deepgram_api_key.clone();
+
+ async move {
+ let _ = start_realtime_recording(
+ audio_stream,
+ languages,
+ is_running,
+ deepgram_api_key,
+ ).await;
+ }
+ }));
}
- };
-
- let mut recording_handles: Vec<JoinHandle<()>> = vec![];
-
- let audio_stream = Arc::new(audio_stream);
- let whisper_sender_clone = whisper_sender_clone.clone();
- let audio_stream_clone = audio_stream.clone();
- let is_running_loop_clone = is_running_loop.clone();
- let record_handle = Some(tokio::spawn(async move {
- let _ = record_and_transcribe(
- audio_stream,
- chunk_duration,
- whisper_sender_clone.clone(),
- is_running_loop_clone.clone(),
- )
- .await;
- }));
-
- if let Some(handle) = record_handle {
- 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 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);
+ join_all(recording_handles).await;
}
-
- join_all(recording_handles).await;
}
});
@@ -534,19 +537,8 @@ async fn record_audio(
_ => continue,
}
}
- _ = tokio::time::sleep(Duration::from_millis(100)) => {
-
- }
+ _ = tokio::time::sleep(Duration::from_millis(100)) => {}
}
- // Handle cleanup of finished handles
- handles.retain(|device_id, handle| {
- if handle.is_finished() {
- info!("handle for device {} has finished", device_id);
- false
- } else {
- true
- }
- });
// Process transcription results
while let Ok(mut transcription) = whisper_receiver.try_recv() {
@@ -555,42 +547,40 @@ async fn record_audio(
transcription.input.device, transcription.transcription
);
- // Insert the new transcript after fetching
- let mut current_transcript: Option<String> = transcription.transcription.clone();
- let mut processed_previous: Option<String> = None;
- if let Some((previous, current)) =
- transcription.cleanup_overlap(previous_transcript.clone())
- {
+ let mut current_transcript = transcription.transcription.clone();
+ let mut processed_previous = None;
+
+ if let Some((previous, current)) = transcription.cleanup_overlap(&previous_transcript) {
if !previous.is_empty() && !current.is_empty() {
if previous != previous_transcript {
processed_previous = Some(previous);
}
- if current_transcript.is_some()
- && current != current_transcript.clone().unwrap_or_default()
- {
+ if current_transcript.as_ref() != Some(&current) {
current_transcript = Some(current);
}
}
}
transcription.transcription = current_transcript.clone();
- if current_transcript.is_some() {
- previous_transcript = current_transcript.unwrap();
+
+ if let Some(transcript) = current_transcript {
+ previous_transcript = transcript;
} else {
continue;
}
+
// Process the audio result
match process_audio_result(
&db,
transcription,
- audio_transcription_engine.clone(),
+ Arc::clone(&audio_transcription_engine),
processed_previous,
previous_transcript_id,
)
.await
{
- Err(e) => error!("error processing audio result: {}", e),
Ok(id) => previous_transcript_id = id,
+ Err(e) => error!("error processing audio result: {}", e),
}
}
}
diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rs
index 19cff98fd..6711f2cec 100644
--- a/screenpipe-server/src/resource_monitor.rs
+++ b/screenpipe-server/src/resource_monitor.rs
@@ -12,7 +12,7 @@ use std::io::Write;
use std::sync::Arc;
use std::time::{Duration, Instant};
use sysinfo::{PidExt, ProcessExt, System, SystemExt};
-use tracing::{error, info};
+use tracing::{error, info, warn};
use uuid;
pub struct ResourceMonitor {
@@ -48,13 +48,8 @@ impl ResourceMonitor {
None
};
- // Initialize PostHog client only if telemetry is enabled
- let posthog_enabled = telemetry_enabled;
- let posthog_client = if posthog_enabled {
- Some(Client::new())
- } else {
- None
- };
+ // Create client once and reuse instead of Option
+ let posthog_client = telemetry_enabled.then(Client::new);
// Generate a unique ID for this installation
let distinct_id = uuid::Uuid::new_v4().to_string();
@@ -63,7 +58,7 @@ impl ResourceMonitor {
start_time: Instant::now(),
resource_log_file,
posthog_client,
- posthog_enabled,
+ posthog_enabled: telemetry_enabled,
distinct_id,
})
}
@@ -74,19 +69,19 @@ impl ResourceMonitor {
system_total_memory: f64,
total_cpu: f32,
) {
- if !self.posthog_enabled || self.posthog_client.is_none() {
+ let Some(client) = &self.posthog_client else {
return;
- }
+ };
- let client = self.posthog_client.as_ref().unwrap();
- let sys = System::new_all();
+ // Create System only when needed
+ let sys = System::new();
- // Prepare the PostHog event payload
+ // Avoid unnecessary cloning by using references
let payload = json!({
- "api_key": "phc_6TUWxXM2NQGPuLhkwgRHxPfXMWqhGGpXqWNIw0GRpMD", // screenpipe posthog key
+ "api_key": "phc_6TUWxXM2NQGPuLhkwgRHxPfXMWqhGGpXqWNIw0GRpMD",
"event": "resource_usage",
"properties": {
- "distinct_id": self.distinct_id,
+ "distinct_id": &self.distinct_id,
"$lib": "rust-reqwest",
"total_memory_gb": total_memory_gb,
"system_total_memory_gb": system_total_memory,
@@ -114,43 +109,57 @@ impl ResourceMonitor {
async fn log_status(&self, sys: &System) {
let pid = std::process::id();
- let main_process = sys.process(sysinfo::Pid::from_u32(pid));
+ let main_process = match sys.process(sysinfo::Pid::from_u32(pid)) {
+ Some(p) => p,
+ None => {
+ warn!("Could not find main process");
+ return;
+ }
+ };
let mut total_memory = 0.0;
let mut total_cpu = 0.0;
- if let Some(process) = main_process {
- total_memory += process.memory() as f64;
- total_cpu += process.cpu_usage();
+ total_memory += main_process.memory() as f64;
+ total_cpu += main_process.cpu_usage();
- // Iterate through all processes to find children
- for child_process in sys.processes().values() {
- if child_process.parent() == Some(sysinfo::Pid::from_u32(pid)) {
- total_memory += child_process.memory() as f64;
- total_cpu += child_process.cpu_usage();
- }
+ // Iterate through all processes to find children
+ for child_process in sys.processes().values() {
+ if child_process.parent() == Some(sysinfo::Pid::from_u32(pid)) {
+ total_memory += child_process.memory() as f64;
+ total_cpu += child_process.cpu_usage();
}
+ }
- let total_memory_gb = total_memory / 1048576000.0;
- let system_total_memory = sys.total_memory() as f64 / 1048576000.0;
- let memory_usage_percent = (total_memory_gb / system_total_memory) * 100.0;
- let runtime = self.start_time.elapsed();
-
- let log_message = format!(
- "Runtime: {}s, Total Memory: {:.0}% ({:.2} GB / {:.2} GB), Total CPU: {:.0}%",
- runtime.as_secs(),
- memory_usage_percent,
- total_memory_gb,
- system_total_memory,
- total_cpu
- );
-
- info!("{}", log_message);
+ let total_memory_gb = total_memory / 1048576000.0;
+ let system_total_memory = sys.total_memory() as f64 / 1048576000.0;
+ let memory_usage_percent = (total_memory_gb / system_total_memory) * 100.0;
+ let runtime = self.start_time.elapsed();
+
+ let log_message = format!(
+ "Runtime: {}s, Total Memory: {:.0}% ({:.2} GB / {:.2} GB), Total CPU: {:.0}%",
+ runtime.as_secs(),
+ memory_usage_percent,
+ total_memory_gb,
+ system_total_memory,
+ total_cpu
+ );
+
+ info!("{}", log_message);
+
+ if let Some(ref filename) = self.resource_log_file {
+ let file = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(filename)
+ .map_err(|e| {
+ error!("Failed to open resource log file: {}", e);
+ e
+ });
- if let Some(filename) = &self.resource_log_file {
- let now = Local::now();
+ if let Ok(mut file) = file {
let json_data = json!({
- "timestamp": now.to_rfc3339(),
+ "timestamp": Local::now().to_rfc3339(),
"runtime_seconds": runtime.as_secs(),
"total_memory_gb": total_memory_gb,
"system_total_memory_gb": system_total_memory,
@@ -158,48 +167,50 @@ impl ResourceMonitor {
"total_cpu_percent": total_cpu,
});
- if let Ok(mut file) = OpenOptions::new().read(true).write(true).open(filename) {
- let mut contents = String::new();
- if file.read_to_string(&mut contents).is_ok() {
- if let Ok(mut json_array) = serde_json::from_str::<Value>(&contents) {
- if let Some(array) = json_array.as_array_mut() {
- array.push(json_data);
- if file.set_len(0).is_ok() && file.seek(SeekFrom::Start(0)).is_ok()
- {
- if let Err(e) =
- file.write_all(json_array.to_string().as_bytes())
- {
- error!("Failed to write JSON data to file: {}", e);
- }
- } else {
- error!("Failed to truncate and seek file: {}", filename);
- }
+ // Create string buffer first
+ let mut contents = String::new();
+ file.read_to_string(&mut contents).unwrap_or_default();
+ if let Ok(mut json_array) = serde_json::from_str::<Value>(&contents) {
+ if let Some(array) = json_array.as_array_mut() {
+ array.push(json_data);
+ if file.set_len(0).is_ok() && file.seek(SeekFrom::Start(0)).is_ok() {
+ if let Err(e) = file.write_all(json_array.to_string().as_bytes()) {
+ error!("Failed to write JSON data to file: {}", e);
}
} else {
- error!("Failed to parse JSON from file: {}", filename);
+ error!("Failed to truncate and seek file: {}", filename);
}
- } else {
- error!("Failed to read JSON file: {}", filename);
}
} else {
- error!("Failed to open JSON file: {}", filename);
+ error!("Failed to parse JSON from file: {}", filename);
}
+
+ let _ = file.flush();
}
+ }
- // Send metrics to PostHog
- let total_memory_gb = total_memory_gb;
- let system_total_memory = system_total_memory;
- let total_cpu = total_cpu;
+ // Send metrics to PostHog
+ let total_memory_gb = total_memory_gb;
+ let system_total_memory = system_total_memory;
+ let total_cpu = total_cpu;
- self.send_to_posthog(total_memory_gb, system_total_memory, total_cpu)
- .await;
+ if self.posthog_enabled {
+ tokio::select! {
+ _ = self.send_to_posthog(total_memory_gb, system_total_memory, total_cpu) => {},
+ _ = tokio::time::sleep(Duration::from_secs(5)) => {
+ warn!("PostHog request timed out");
+ }
+ }
}
}
pub fn start_monitoring(self: &Arc<Self>, interval: Duration) {
+ // Clone the Arc since we need to move it into the spawned task
let monitor = Arc::clone(self);
+
tokio::spawn(async move {
let mut sys = System::new_all();
+
loop {
tokio::select! {
_ = tokio::time::sleep(interval) => {
@@ -210,4 +221,16 @@ impl ResourceMonitor {
}
});
}
+
+ pub async fn shutdown(&self) {
+ if let Some(ref file) = self.resource_log_file {
+ if let Ok(mut f) = OpenOptions::new().write(true).open(file) {
+ let _ = f.flush();
+ }
+ }
+
+ if let Some(_) = &self.posthog_client {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
}