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: screenpipe action in beta

Louis Beaumont46fc0479a973
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 837156f97..37cd51feb 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -158,6 +158,20 @@ this is @louis030195 whole `.vscode/settings.json` file:
## other hacks
+### running dev + prod in the same time
+
+one command i keep using to avoid having to kill my main "production" process is:
+
+```bash
+./target/release/screenpipe --port 3035 --data-dir /tmp/sp
+```
+
+it will avoid conflicts with the port and avoid conflicts with the data dir
+
+especially useful if you've done new database migrations and want to avoid breaking your previous months of data :)
+
+on macos the /tmp dir keeps being cleaned up by the system fyi
+
### debugging github action
ssh into the runner:
diff --git a/screenpipe-actions/Cargo.toml b/screenpipe-actions/Cargo.toml
index 00a91b523..447801f85 100644
--- a/screenpipe-actions/Cargo.toml
+++ b/screenpipe-actions/Cargo.toml
@@ -19,18 +19,10 @@ path = "src/main.rs"
anyhow = "1.0"
reqwest = { version = "0.11", features = ["json"] }
serde_json = "1.0"
-xcap = "0.0.13"
-base64 = "0.21" # Add this line
-image = "0.25" # Add this line
tokio = { version = "1.26", features = ["full"] }
rdev = "0.5.3"
enigo = "0.1.3"
-chrono = "0.4"
tempfile = "3.2"
-url = "2.4.0"
-once_cell = "1.18.0"
serde = { version = "1.0", features = ["derive"] }
-log = "0.4"
-env_logger = "0.10"
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
\ No newline at end of file
diff --git a/screenpipe-actions/src/monitor_keystroke_commands.rs b/screenpipe-actions/src/monitor_keystroke_commands.rs
index 90865c8b5..9f61173cb 100644
--- a/screenpipe-actions/src/monitor_keystroke_commands.rs
+++ b/screenpipe-actions/src/monitor_keystroke_commands.rs
@@ -1,37 +1,40 @@
use rdev::{listen, Event, EventType, Key};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
-use tokio::sync::mpsc;
-use tokio::sync::Mutex;
+use tokio::sync::{mpsc, Mutex};
use tracing::error;
pub enum KeystrokeCommand {
DoubleSlash,
+ Stop,
// Add other commands as needed
}
-#[allow(dead_code)]
pub struct KeystrokeMonitor {
tx: mpsc::Sender<KeystrokeCommand>,
last_slash: Arc<Mutex<Option<std::time::Instant>>>,
+ shift_pressed: Arc<AtomicBool>,
+ ctrl_pressed: Arc<AtomicBool>,
}
impl KeystrokeMonitor {
- #[allow(dead_code)]
pub fn new(tx: mpsc::Sender<KeystrokeCommand>) -> Self {
KeystrokeMonitor {
tx,
last_slash: Arc::new(Mutex::new(None)),
+ shift_pressed: Arc::new(AtomicBool::new(false)),
+ ctrl_pressed: Arc::new(AtomicBool::new(false)),
}
}
- #[allow(dead_code)]
pub async fn start_monitoring(&self) -> anyhow::Result<()> {
let tx = self.tx.clone();
let last_slash = self.last_slash.clone();
-
+ let shift_pressed = self.shift_pressed.clone();
+ let ctrl_pressed = self.ctrl_pressed.clone();
tokio::task::spawn_blocking(move || {
if let Err(error) = listen(move |event| {
- let _ = handle_event(event, &tx, &last_slash);
+ let _ = handle_event(event, &tx, &last_slash, &shift_pressed, &ctrl_pressed);
}) {
error!("error: {:?}", error)
}
@@ -41,43 +44,56 @@ impl KeystrokeMonitor {
}
}
-#[allow(dead_code)]
fn handle_event(
event: Event,
tx: &mpsc::Sender<KeystrokeCommand>,
last_slash: &Arc<Mutex<Option<std::time::Instant>>>,
+ shift_pressed: &Arc<AtomicBool>,
+ ctrl_pressed: &Arc<AtomicBool>,
) -> anyhow::Result<()> {
- static mut SHIFT_PRESSED: bool = false;
-
match event.event_type {
EventType::KeyPress(key) => {
- if key == Key::ShiftLeft || key == Key::ShiftRight {
- unsafe { SHIFT_PRESSED = true; }
- } else if key == Key::Slash || (unsafe { SHIFT_PRESSED } && key == Key::Num7) {
- // Monitoring for slash (/) or Shift+7 combination
- let mut last_slash_guard = last_slash.blocking_lock();
- let now = std::time::Instant::now();
- if let Some(last) = *last_slash_guard {
- if now.duration_since(last).as_millis() < 500 {
- tx.blocking_send(KeystrokeCommand::DoubleSlash)?;
- *last_slash_guard = None;
- return Ok(());
+ match key {
+ Key::ShiftLeft | Key::ShiftRight => {
+ shift_pressed.store(true, Ordering::SeqCst);
+ }
+ Key::ControlLeft | Key::ControlRight => {
+ ctrl_pressed.store(true, Ordering::SeqCst);
+ }
+ Key::KeyQ => {
+ tx.blocking_send(KeystrokeCommand::Stop)?;
+ return Ok(());
+ }
+ Key::Slash | Key::Num7 if shift_pressed.load(Ordering::SeqCst) => {
+ // Monitoring for slash (/) or Shift+7 combination
+ let mut last_slash_guard = last_slash.blocking_lock();
+ let now = std::time::Instant::now();
+ if let Some(last) = *last_slash_guard {
+ if now.duration_since(last).as_millis() < 500 {
+ tx.blocking_send(KeystrokeCommand::DoubleSlash)?;
+ *last_slash_guard = None;
+ return Ok(());
+ }
}
+ *last_slash_guard = Some(now);
}
- *last_slash_guard = Some(now);
+ _ => {}
}
- },
- EventType::KeyRelease(key) => {
- if key == Key::ShiftLeft || key == Key::ShiftRight {
- unsafe { SHIFT_PRESSED = false; }
+ }
+ EventType::KeyRelease(key) => match key {
+ Key::ShiftLeft | Key::ShiftRight => {
+ shift_pressed.store(false, Ordering::SeqCst);
+ }
+ Key::ControlLeft | Key::ControlRight => {
+ ctrl_pressed.store(false, Ordering::SeqCst);
}
+ _ => {}
},
_ => {}
}
Ok(())
}
-#[allow(dead_code)]
pub async fn run_keystroke_monitor(tx: mpsc::Sender<KeystrokeCommand>) -> anyhow::Result<()> {
let monitor = KeystrokeMonitor::new(tx);
monitor.start_monitoring().await?;
diff --git a/screenpipe-actions/src/run.rs b/screenpipe-actions/src/run.rs
index 0e28db3a0..7e119a878 100644
--- a/screenpipe-actions/src/run.rs
+++ b/screenpipe-actions/src/run.rs
@@ -1,16 +1,19 @@
use crate::type_and_animate::{delete_characters, type_slowly, EnigoCommand};
use crate::{call_ai, run_keystroke_monitor, KeystrokeCommand};
use reqwest;
+use std::string::ToString;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
use tempfile::NamedTempFile;
use tokio::process::Command;
use tokio::sync::mpsc;
use tokio::task;
use tokio::time::Instant;
use tracing::{error, info};
-use std::string::ToString;
+// TODO: make this function not prevent ctrl+c in the future
pub async fn run() -> anyhow::Result<()> {
- info!("starting keystroke monitor. press '//' to print attributes for the current app and call openai.");
+ info!("starting keystroke monitor. press '//' to print attributes for the current app and call openai. press 'ctrl+q' to stop.");
let (tx, mut rx) = mpsc::channel(100);
let (_enigo_tx, mut enigo_rx) = mpsc::channel(100);
@@ -31,7 +34,7 @@ pub async fn run() -> anyhow::Result<()> {
enigo.key_click(enigo::Key::Backspace);
}
EnigoCommand::Shutdown => {
- println!("Shutting down Enigo thread.");
+ info!("Shutting down Enigo thread.");
break;
}
}
@@ -46,21 +49,28 @@ pub async fn run() -> anyhow::Result<()> {
}
});
- while let Some(command) = rx.recv().await {
- match command {
- KeystrokeCommand::DoubleSlash => {
- info!("double slash detected. calling ai...");
+ let stop_signal = Arc::new(AtomicBool::new(false));
+
+ loop {
+ tokio::select! {
+ Some(command) = rx.recv() => {
+ match command {
+ KeystrokeCommand::DoubleSlash => {
+ // Reset the stop signal at the start of a new action
+ stop_signal.store(false, Ordering::SeqCst);
- type_slowly("thinking".to_string()).await?;
- let swift_output = run_swift_script().await?;
+ info!("double slash detected. calling ai...");
- // Use swift_output directly here
- // For example, pass it to the LLM or process it further
+ type_slowly("thinking".to_string(), stop_signal.clone()).await?;
+ let swift_output = run_swift_script().await?;
- info!("swift output: {}", swift_output);
+ // Use swift_output directly here
+ // For example, pass it to the LLM or process it further
- let prompt = format!(
- r#"Based on the following Swift output,
+ info!("swift output: {}", swift_output);
+
+ let prompt = format!(
+ r#"Based on the following Swift output,
you need to continue where the "//" is.
Output your response in JSON format as follows:
{{
@@ -75,32 +85,46 @@ pub async fn run() -> anyhow::Result<()> {
swift_output
);
- let start = Instant::now();
- match call_ai(prompt, String::new(), true).await {
- Ok(response) => {
- let duration = start.elapsed();
- info!("{:.1?} - first call_ai", duration);
- delete_characters("thinking".len()).await?;
- delete_characters(2).await?; // Delete the double slash
- info!("ai response: {}", response);
- type_slowly("[GENERIC_RESPONSE]".to_string()).await?;
- type_slowly("\n".to_string()).await?;
- type_slowly(response).await?;
- }
- Err(e) => {
- let duration = start.elapsed();
- error!("{:.1?} - failed first call_ai", duration);
- delete_characters("thinking".len()).await?;
- error!("failed to get response from ai: {}", e);
- continue; // skip the rest of the loop iteration
- }
- }
- type_slowly("\n".to_string()).await?;
- type_slowly("\n".to_string()).await?;
- type_slowly("[RESPONSE_WITH_CONTEXT]".to_string()).await?;
+ let start = Instant::now();
+ let stop_signal_clone = stop_signal.clone();
+ match call_ai(prompt, String::new(), true).await {
+ Ok(response) => {
+ let duration = start.elapsed();
+ info!("{:.1?} - first call_ai", duration);
+ delete_characters("thinking".len()).await?;
+ delete_characters(2).await?; // Delete the double slash
+ info!("ai response: {}", response);
- let context = format!("Swift output: {}", swift_output);
- let prompt = r#"Based on the following Swift output, find double slash '//' to see where users curor is,
+ // Spawn a new task for typing
+ let typing_task = task::spawn(async move {
+ let _ = type_slowly("[GENERIC_RESPONSE]".to_string(), stop_signal_clone.clone()).await;
+ let _ = type_slowly("\n".to_string(), stop_signal_clone.clone()).await;
+ let _ = type_slowly(response, stop_signal_clone).await;
+ });
+
+ // Wait for the typing task to complete or be interrupted
+ tokio::select! {
+ _ = typing_task => {},
+ _ = rx.recv() => {
+ // If we receive any command while typing, stop the typing
+ stop_signal.store(true, Ordering::SeqCst);
+ }
+ }
+ }
+ Err(e) => {
+ let duration = start.elapsed();
+ error!("{:.1?} - failed first call_ai", duration);
+ delete_characters("thinking".len()).await?;
+ error!("failed to get response from ai: {}", e);
+ continue; // skip the rest of the loop iteration
+ }
+ }
+ type_slowly("\n".to_string(), stop_signal.clone()).await?;
+ type_slowly("\n".to_string(), stop_signal.clone()).await?;
+ type_slowly("[RESPONSE_WITH_CONTEXT]".to_string(), stop_signal.clone()).await?;
+
+ let context = format!("Swift output: {}", swift_output);
+ let prompt = r#"Based on the following Swift output, find double slash '//' to see where users curor is,
Now, provide 3 search queries to find relevant context in user files to continue the conversation. follow these guidelines:
1. focus on specificity, avoid generic words
@@ -121,93 +145,278 @@ pub async fn run() -> anyhow::Result<()> {
]
}"#.to_string();
- let start = Instant::now();
- match call_ai(prompt, context, true).await {
- Ok(response) => {
- let duration = start.elapsed();
- info!("{:.1?} - second call_ai", duration);
- // println!("ai response: {}", response);
-
- // Split the response by newlines to get individual queries
- let queries: Vec<String> = response
- .split('\n')
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())
- .collect();
-
- let mut search_results = Vec::new();
-
- for query in &queries {
- match search_localhost(query).await {
- // used to be &query
- Ok(search_result) => {
- let truncated_result =
- search_result.chars().take(100).collect::<String>();
- let capitalized_query = query.to_uppercase();
- type_slowly(format!("[{}] ", capitalized_query)).await?;
- info!("search result for '{}': {}", query, truncated_result);
- search_results.push(search_result);
- }
- Err(e) => {
- error!("error searching localhost for '{}': {:?}", query, e)
+ let start = Instant::now();
+ match call_ai(prompt, context, true).await {
+ Ok(response) => {
+ let duration = start.elapsed();
+ info!("{:.1?} - second call_ai", duration);
+ // println!("ai response: {}", response);
+
+ // Split the response by newlines to get individual queries
+ let queries: Vec<String> = response
+ .split('\n')
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect();
+
+ let mut search_results = Vec::new();
+
+ for query in &queries {
+ match search_localhost(query).await {
+ // used to be &query
+ Ok(search_result) => {
+ let truncated_result =
+ search_result.chars().take(100).collect::<String>();
+ let capitalized_query = query.to_uppercase();
+ type_slowly(format!("[{}] ", capitalized_query), stop_signal.clone()).await?;
+ info!("search result for '{}': {}", query, truncated_result);
+ search_results.push(search_result);
+ }
+ Err(e) => {
+ error!("error searching localhost for '{}': {:?}", query, e)
+ }
+ }
}
- }
- }
- type_slowly("\n".to_string()).await?;
- type_slowly("analyzing".to_string()).await?;
-
- // Final LLM call
- let final_prompt = r#"Based on the desktop text and search results of my computer, draft a concise response.
- Provide the most relevant message
- Also provide who your message is addressed to ("TO_YOU" or "ON_YOUR_BEHALF")
- You might be writing: a response, a follow-up, a suggestion, a clarification, or you might be puzzled
- Output your response in JSON format as follows:
- {
- "response": "[ADDRESSED TO] Your response text here"
- }
- Ensure the response matches the length and tone of the message we are responding to.
- Make the response concise and to the point.
- The response should be casual, social media style.
- It should not look like it was written by AI.
- "#.to_string();
- let final_context = format!(
- "swift output: {}\nfirst llm response: {}\nsearch results: {}",
- swift_output,
- response,
- search_results.join("\n")
- );
+ type_slowly("\n".to_string(), stop_signal.clone()).await?;
+ type_slowly("analyzing".to_string(), stop_signal.clone()).await?;
- let start = Instant::now();
- match call_ai(final_prompt, final_context, true).await {
- Ok(final_response) => {
- let duration = start.elapsed();
- info!("{:.1?} - final call_ai", duration);
- delete_characters("analyzing".len()).await?;
- info!("<<<llm final response>>>: {}", final_response);
- type_slowly(final_response).await?;
+ // Final LLM call
+ let final_prompt = r#"Based on the desktop text and search results of my computer, draft a concise response.
+ Provide the most relevant message
+ Also provide who your message is addressed to ("TO_YOU" or "ON_YOUR_BEHALF")
+ You might be writing: a response, a follow-up, a suggestion, a clarification, or you might be puzzled
+ Output your response in JSON format as follows:
+ {
+ "response": "[ADDRESSED TO] Your response text here"
+ }
+ Ensure the response matches the length and tone of the message we are responding to.
+ Make the response concise and to the point.
+ The response should be casual, social media style.
+ It should not look like it was written by AI.
+ "#.to_string();
+ let final_context = format!(
+ "swift output: {}\nfirst llm response: {}\nsearch results: {}",
+ swift_output,
+ response,
+ search_results.join("\n")
+ );
+
+ let start = Instant::now();
+ match call_ai(final_prompt, final_context, true).await {
+ Ok(final_response) => {
+ let duration = start.elapsed();
+ info!("{:.1?} - final call_ai", duration);
+ delete_characters("analyzing".len()).await?;
+ info!("<<<llm final response>>>: {}", final_response);
+ type_slowly(final_response, stop_signal.clone()).await?;
+ }
+ Err(e) => {
+ error!("error in final openai call: {:?}", e);
+ continue;
+ }
+ }
}
Err(e) => {
- error!("error in final openai call: {:?}", e);
+ error!("error in second openai call: {}", e);
continue;
}
}
- }
- Err(e) => {
- error!("error in second openai call: {}", e);
- continue;
+ },
+ KeystrokeCommand::Stop => {
+ info!("stop command received. stopping current action...");
+ stop_signal.store(true, Ordering::SeqCst);
}
}
- }
+ },
+ else => break,
}
}
+
+ // Cleanup code
+ info!("shutting down enigo thread...");
+ if let Err(e) = _enigo_tx.send(EnigoCommand::Shutdown).await {
+ error!("failed to send shutdown command to enigo thread: {:?}", e);
+ }
+
Ok(())
}
async fn run_swift_script() -> anyhow::Result<String> {
let start = Instant::now();
- let script_content = include_str!("print_all_attributes.swift");
+ let script_content = r#"
+import Cocoa
+import ApplicationServices
+import Foundation
+
+class QueueElement {
+ let element: AXUIElement
+ let depth: Int
+
+ init(_ element: AXUIElement, depth: Int) {
+ self.element = element
+ self.depth = depth
+ }
+}
+
+func printAllAttributeValues(_ startElement: AXUIElement) {
+ var elements: [(CGPoint, CGSize, String)] = []
+ var visitedElements = Set<AXUIElement>()
+ let unwantedValues = ["0", "", "", "3", ""]
+ let unwantedLabels = [
+ "window", "application", "group", "button", "image", "text",
+ "pop up button", "region", "notifications", "table", "column",
+ "html content"
+ ]
+
+ func traverseHierarchy(_ element: AXUIElement, depth: Int) {
+ guard !visitedElements.contains(element) else { return }
+ visitedElements.insert(element)
+
+ var attributeNames: CFArray?
+ let result = AXUIElementCopyAttributeNames(element, &attributeNames)
+
+ guard result == .success, let attributes = attributeNames as? [String] else { return }
+
+ var position: CGPoint = .zero
+ var size: CGSize = .zero
+
+ // Get position
+ if let positionValue = getAttributeValue(element, forAttribute: kAXPositionAttribute) as! AXValue?,
+ AXValueGetType(positionValue) == .cgPoint {
+ AXValueGetValue(positionValue, .cgPoint, &position)
+ }
+
+ // Get size
+ if let sizeValue = getAttributeValue(element, forAttribute: kAXSizeAttribute) as! AXValue?,
+ AXValueGetType(sizeValue) == .cgSize {
+ AXValueGetValue(sizeValue, .cgSize, &size)
+ }
+
+ for attr in attributes {
+ if ["AXDescription", "AXValue", "AXLabel", "AXRoleDescription", "AXHelp"].contains(attr) {
+ if let value = getAttributeValue(element, forAttribute: attr) {
+ let valueStr = describeValue(value)
+ if !valueStr.isEmpty && !unwantedValues.contains(valueStr) && valueStr.count > 1 &&
+ !unwantedLabels.contains(valueStr.lowercased()) {
+ elements.append((position, size, valueStr))
+ }
+ }
+ }
+
+ // Traverse child elements
+ if let childrenValue = getAttributeValue(element, forAttribute: attr) {
+ if let elementArray = childrenValue as? [AXUIElement] {
+ for childElement in elementArray {
+ traverseHierarchy(childElement, depth: depth + 1)
+ }
+ } else if let childElement = childrenValue as! AXUIElement? {
+ traverseHierarchy(childElement, depth: depth + 1)
+ }
+ }
+ }
+ }
+
+ traverseHierarchy(startElement, depth: 0)
+
+ // Sort elements from top to bottom, then left to right
+ elements.sort { (a, b) in
+ if a.0.y != b.0.y {
+ return a.0.y < b.0.y
+ } else {
+ return a.0.x < b.0.x
+ }
+ }
+
+ // Deduplicate and print sorted elements to stdout, excluding coordinates
+ var uniqueValues = Set<String>()
+ for (_, _, valueStr) in elements {
+ if uniqueValues.insert(valueStr).inserted {
+ print(valueStr)
+ }
+ }
+}
+
+func formatCoordinates(_ position: CGPoint, _ size: CGSize) -> String {
+ return String(format: "(x:%.0f,y:%.0f,w:%.0f,h:%.0f)", position.x, position.y, size.width, size.height)
+}
+
+func describeValue(_ value: AnyObject?) -> String {
+ switch value {
+ case let string as String:
+ return string
+ case let number as NSNumber:
+ return number.stringValue
+ case let point as NSPoint:
+ return "(\(point.x), \(point.y))"
+ case let size as NSSize:
+ return "w=\(size.width) h=\(size.height)"
+ case let rect as NSRect:
+ return "x=\(rect.origin.x) y=\(rect.origin.y) w=\(rect.size.width) h=\(rect.size.height)"
+ case let range as NSRange:
+ return "loc=\(range.location) len=\(range.length)"
+ case let url as URL:
+ return url.absoluteString
+ case let array as [AnyObject]:
+ return array.isEmpty ? "Empty array" : "Array with \(array.count) elements"
+ case let axValue as AXValue:
+ return describeAXValue(axValue)
+ case is AXUIElement:
+ return "AXUIElement"
+ case .none:
+ return "None"
+ default:
+ return String(describing: value)
+ }
+}
+
+func describeAXValue(_ axValue: AXValue) -> String {
+ let type = AXValueGetType(axValue)
+ switch type {
+ case .cgPoint:
+ var point = CGPoint.zero
+ AXValueGetValue(axValue, .cgPoint, &point)
+ return "(\(point.x), \(point.y))"
+ case .cgSize:
+ var size = CGSize.zero
+ AXValueGetValue(axValue, .cgSize, &size)
+ return "w=\(size.width) h=\(size.height)"
+ case .cgRect:
+ var rect = CGRect.zero
+ AXValueGetValue(axValue, .cgRect, &rect)
+ return "x=\(rect.origin.x) y=\(rect.origin.y) w=\(rect.size.width) h=\(rect.size.height)"
+ case .cfRange:
+ var range = CFRange(location: 0, length: 0)
+ AXValueGetValue(axValue, .cfRange, &range)
+ return "loc=\(range.location) len=\(range.length)"
+ default:
+ return "Unknown AXValue type"
+ }
+}
+
+func getAttributeValue(_ element: AXUIElement, forAttribute attr: String) -> AnyObject? {
+ var value: AnyObject?
+ let result = AXUIElementCopyAttributeValue(element, attr as CFString, &value)
+ return result == .success ? value : nil
+}
+
+func printAllAttributeValuesForCurrentApp() {
+ guard let app = NSWorkspace.shared.frontmostApplication else {
+ return
+ }
+
+ let pid = app.processIdentifier
+ let axApp = AXUIElementCreateApplication(pid)
+
+ print("attribute values for \(app.localizedName ?? "unknown app"):")
+ printAllAttributeValues(axApp)
+}
+
+// usage
+printAllAttributeValuesForCurrentApp()
+"#;
+
let temp_file = NamedTempFile::new()?;
tokio::fs::write(temp_file.path(), script_content).await?;
diff --git a/screenpipe-actions/src/type_and_animate.rs b/screenpipe-actions/src/type_and_animate.rs
index a15f0bfe7..5fd7a4d39 100644
--- a/screenpipe-actions/src/type_and_animate.rs
+++ b/screenpipe-actions/src/type_and_animate.rs
@@ -1,8 +1,10 @@
use anyhow::Result;
-use tokio::time::{sleep, Duration};
-use std::cell::RefCell;
use enigo::{Enigo, Key, KeyboardControllable};
use serde::Serialize;
+use std::cell::RefCell;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use tokio::time::{sleep, Duration};
#[allow(dead_code)]
#[derive(Debug)]
@@ -46,23 +48,35 @@ pub async fn delete_characters(count: usize) -> Result<()> {
Ok(())
}
-pub async fn type_slowly(text: String) -> Result<()> {
+pub async fn type_slowly(text: String, stop_signal: Arc<AtomicBool>) -> Result<()> {
let text_len = text.len();
- tokio::task::spawn_blocking(move || {
- with_enigo(|enigo| {
- for line in text.split('\n') {
- if !line.is_empty() {
- enigo.key_sequence(line);
+ for line in text.split('\n') {
+ if !line.is_empty() {
+ for char in line.chars() {
+ if stop_signal.load(Ordering::SeqCst) {
+ return Ok(());
}
- if text.contains('\n') {
+ tokio::task::spawn_blocking(move || {
+ with_enigo(|enigo| {
+ enigo.key_sequence(&char.to_string());
+ });
+ }).await?;
+ sleep(Duration::from_millis(50)).await;
+ }
+ }
+ if text.contains('\n') {
+ if stop_signal.load(Ordering::SeqCst) {
+ return Ok(());
+ }
+ tokio::task::spawn_blocking(move || {
+ with_enigo(|enigo| {
enigo.key_down(Key::Shift);
enigo.key_click(Key::Return);
enigo.key_up(Key::Shift);
- }
- }
- });
- })
- .await?;
+ });
+ }).await?;
+ }
+ }
sleep(Duration::from_millis(text_len as u64)).await;
Ok(())
}
diff --git a/screenpipe-app-tauri/components/recording-settings.tsx b/screenpipe-app-tauri/components/recording-settings.tsx
index 4e43f1ab1..c41312383 100644
--- a/screenpipe-app-tauri/components/recording-settings.tsx
+++ b/screenpipe-app-tauri/components/recording-settings.tsx
@@ -15,7 +15,8 @@ import {
Check,
ChevronsUpDown,
Eye,
- HelpCircle, Languages,
+ HelpCircle,
+ Languages,
Mic,
Monitor,
X,
@@ -102,6 +103,15 @@ export function RecordingSettings({
const isDisabled = health?.status_code === 500;
const [isCopyDialogOpen, setIsCopyDialogOpen] = useState(false);
const { copyToClipboard } = useCopyToClipboard({ timeout: 2000 });
+ const [isMacOS, setIsMacOS] = useState(false);
+
+ useEffect(() => {
+ const checkPlatform = async () => {
+ const currentPlatform = await platform();
+ setIsMacOS(currentPlatform === "macos");
+ };
+ checkPlatform();
+ }, []);
useEffect(() => {
const loadDevices = async () => {
@@ -309,11 +319,11 @@ export function RecordingSettings({
const handleLanguageChange = (currentValue: Language) => {
const updatedLanguages = localSettings.languages.includes(currentValue)
- ? localSettings.languages.filter((id) => id !== currentValue)
- : [...localSettings.languages, currentValue];
+ ? localSettings.languages.filter((id) => id !== currentValue)
+ : [...localSettings.languages, currentValue];
setLocalSettings({ ...localSettings, languages: updatedLanguages });
- }
+ };
const handleAudioDeviceChange = (currentValue: string) => {
const updatedDevices = localSettings.audioDevices.includes(currentValue)
@@ -385,9 +395,7 @@ export function RecordingSettings({
) {
localSettings.monitorIds.forEach((id) => args.push(`--monitor-id ${id}`));
}
- if (
- localSettings.languages.length > 0
- ) {
+ if (localSettings.languages.length > 0) {
localSettings.languages.forEach((id) => args.push(`--language ${id}`));
}
if (
@@ -425,7 +433,7 @@ export function RecordingSettings({
if (localSettings.vadSensitivity !== "high") {
args.push(`--vad-sensitivity ${localSettings.vadSensitivity}`);
}
-
+
if (!localSettings.analyticsEnabled) {
args.push("--disable-telemetry");
}
@@ -433,7 +441,7 @@ export function RecordingSettings({
args.push(`--audio-chunk-duration ${localSettings.audioChunkDuration}`);
}
- if(localSettings.languages.length > 0) {
+ if (localSettings.languages.length > 0) {
localSettings.languages.forEach((id) => args.push(`--language ${id}`));
}
@@ -481,6 +489,10 @@ export function RecordingSettings({
setLocalSettings({ ...localSettings, useChineseMirror: checked });
};
+ const handleEnableBetaToggle = (checked: boolean) => {
+ setLocalSettings({ ...localSettings, enableBeta: checked });
+ };
+
return (
<>
<div className="relative">
@@ -530,18 +542,18 @@ export function RecordingSettings({
<CardContent className="space-y-4">
<div className="flex flex-col space-y-2">
<Label
- htmlFor="audioTranscriptionModel"
- className="flex items-center space-x-2"
+ htmlFor="audioTranscriptionModel"
+ className="flex items-center space-x-2"
>
- <Mic className="h-4 w-4"/>
+ <Mic className="h-4 w-4" />
<span>audio transcription model</span>
</Label>
<Select
- onValueChange={handleAudioTranscriptionModelChange}
- defaultValue={localSettings.audioTranscriptionEngine}
+ onValueChange={handleAudioTranscriptionModelChange}
+ defaultValue={localSettings.audioTranscriptionEngine}
>
<SelectTrigger>
- <SelectValue placeholder="select audio transcription engine"/>
+ <SelectValue placeholder="select audio transcription engine" />
</SelectTrigger>
<SelectContent>
<SelectItem value="deepgram">
@@ -561,15 +573,15 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<Label htmlFor="ocrModel" className="flex items-center space-x-2">
- <Eye className="h-4 w-4"/>
+ <Eye className="h-4 w-4" />
<span>ocr model</span>
</Label>
<Select
- onValueChange={handleOcrModelChange}
- defaultValue={localSettings.ocrEngine}
+ onValueChange={handleOcrModelChange}
+ defaultValue={localSettings.ocrEngine}
>
<SelectTrigger>
- <SelectValue placeholder="select ocr engine"/>
+ <SelectValue placeholder="select ocr engine" />
</SelectTrigger>
<SelectContent>{renderOcrEngineOptions()}</SelectContent>
</Select>
@@ -577,66 +589,66 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<Label
- htmlFor="monitorIds"
- className="flex items-center space-x-2"
+ htmlFor="monitorIds"
+ className="flex items-center space-x-2"
>
- <Monitor className="h-4 w-4"/>
+ <Monitor className="h-4 w-4" />
<span>monitors</span>
</Label>
<Popover open={openMonitors} onOpenChange={setOpenMonitors}>
<PopoverTrigger asChild>
<Button
- variant="outline"
- role="combobox"
- aria-expanded={openMonitors}
- className="w-full justify-between"
+ variant="outline"
+ role="combobox"
+ aria-expanded={openMonitors}
+ className="w-full justify-between"
>
{localSettings.monitorIds.length > 0
- ? `${localSettings.monitorIds.length} monitor(s) selected`
- : "select monitors"}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50"/>
+ ? `${localSettings.monitorIds.length} monitor(s) selected`
+ : "select monitors"}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
- <CommandInput placeholder="search monitors..."/>
+ <CommandInput placeholder="search monitors..." />
<CommandList>
<CommandEmpty>no monitor found.</CommandEmpty>
<CommandGroup>
{availableMonitors.map((monitor) => (
- <CommandItem
- key={monitor.id}
- value={monitor.id}
- onSelect={() =>
- handleMonitorChange(monitor.id.toString())
- }
- >
- <div className="flex items-center">
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- localSettings.monitorIds.includes(
- monitor.id.toString()
- )
- ? "opacity-100"
- : "opacity-0"
- )}
- />
- {/* not selectable */}
- <span
- style={{
- userSelect: "none",
- WebkitUserSelect: "none",
- MozUserSelect: "none",
- msUserSelect: "none",
- }}
- >
+ <CommandItem
+ key={monitor.id}
+ value={monitor.id}
+ onSelect={() =>
+ handleMonitorChange(monitor.id.toString())
+ }
+ >
+ <div className="flex items-center">
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ localSettings.monitorIds.includes(
+ monitor.id.toString()
+ )
+ ? "opacity-100"
+ : "opacity-0"
+ )}
+ />
+ {/* not selectable */}
+ <span
+ style={{
+ userSelect: "none",
+ WebkitUserSelect: "none",
+ MozUserSelect: "none",
+ msUserSelect: "none",
+ }}
+ >
{monitor.id}. {monitor.name}{" "}
- {monitor.is_default ? "(default)" : ""} -{" "}
- {monitor.width}x{monitor.height}
+ {monitor.is_default ? "(default)" : ""} -{" "}
+ {monitor.width}x{monitor.height}
</span>
- </div>
- </CommandItem>
+ </div>
+ </CommandItem>
))}
</CommandGroup>
</CommandList>
@@ -646,65 +658,65 @@ export function RecordingSettings({
</div>
<div className="flex flex-col space-y-2">
<Label
- htmlFor="audioDevices"
- className="flex items-center space-x-2"
+ htmlFor="audioDevices"
+ className="flex items-center space-x-2"
>
- <Mic className="h-4 w-4"/>
+ <Mic className="h-4 w-4" />
<span>audio devices</span>
</Label>
<Popover
- open={openAudioDevices}
- onOpenChange={setOpenAudioDevices}
+ open={openAudioDevices}
+ onOpenChange={setOpenAudioDevices}
>
<PopoverTrigger asChild>
<Button
- variant="outline"
- role="combobox"
- aria-expanded={openAudioDevices}
- className="w-full justify-between"
+ variant="outline"
+ role="combobox"
+ aria-expanded={openAudioDevices}
+ className="w-full justify-between"
>
{localSettings.audioDevices.length > 0
- ? `${localSettings.audioDevices.length} device(s) selected`
- : "select audio devices"}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50"/>
+ ? `${localSettings.audioDevices.length} device(s) selected`
+ : "select audio devices"}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
- <CommandInput placeholder="search audio devices..."/>
+ <CommandInput placeholder="search audio devices..." />
<CommandList>
<CommandEmpty>no audio device found.</CommandEmpty>
<CommandGroup>
{availableAudioDevices.map((device) => (
- <CommandItem
- key={device.name}
- value={device.name}
- onSelect={handleAudioDeviceChange}
- >
- <div className="flex items-center">
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- localSettings.audioDevices.includes(
- device.name
- )
- ? "opacity-100"
- : "opacity-0"
- )}
- />
- <span
- style={{
- userSelect: "none",
- WebkitUserSelect: "none",
- MozUserSelect: "none",
- msUserSelect: "none",
- }}
- >
+ <CommandItem
+ key={device.name}
+ value={device.name}
+ onSelect={handleAudioDeviceChange}
+ >
+ <div className="flex items-center">
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ localSettings.audioDevices.includes(
+ device.name
+ )
+ ? "opacity-100"
+ : "opacity-0"
+ )}
+ />
+ <span
+ style={{
+ userSelect: "none",
+ WebkitUserSelect: "none",
+ MozUserSelect: "none",
+ msUserSelect: "none",
+ }}
+ >
{device.name}{" "}
- {device.is_default ? "(default)" : ""}
+ {device.is_default ? "(default)" : ""}
</span>
- </div>
- </CommandItem>
+ </div>
+ </CommandItem>
))}
</CommandGroup>
</CommandList>
@@ -715,64 +727,60 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<Label
- htmlFor="languages"
- className="flex items-center space-x-2"
+ htmlFor="languages"
+ className="flex items-center space-x-2"
>
- <Languages className="h-4 w-4"/>
+ <Languages className="h-4 w-4" />
<span>languages</span>
</Label>
<Popover open={openLanguages} onOpenChange={setOpenLanguages}>
<PopoverTrigger asChild>
<Button
- variant="outline"
- role="combobox"
- aria-expanded={openLanguages}
- className="w-full justify-between"
+ variant="outline"
+ role="combobox"
+ aria-expanded={openLanguages}
+ className="w-full justify-between"
>
{localSettings.languages.length > 0
- ? `${localSettings.languages.join(", ")}`
- : "select languages"}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50"/>
+ ? `${localSettings.languages.join(", ")}`
+ : "select languages"}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
- <CommandInput placeholder="search languages..."/>
+ <CommandInput placeholder="search languages..." />
<CommandList>
<CommandEmpty>no language found.</CommandEmpty>
<CommandGroup>
{Object.entries(Language).map(([language, id]) => (
- <CommandItem
- key={language}
- value={language}
- onSelect={() =>
- handleLanguageChange(id)
- }
- >
- <div className="flex items-center">
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- localSettings.languages.includes(
- id
- )
- ? "opacity-100"
- : "opacity-0"
- )}
- />
- {/* not selectable */}
- <span
- style={{
- userSelect: "none",
- WebkitUserSelect: "none",
- MozUserSelect: "none",
- msUserSelect: "none",
- }}
- >
+ <CommandItem
+ key={language}
+ value={language}
+ onSelect={() => handleLanguageChange(id)}
+ >
+ <div className="flex items-center">
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ localSettings.languages.includes(id)
+ ? "opacity-100"
+ : "opacity-0"
+ )}
+ />
+ {/* not selectable */}
+ <span
+ style={{
+ userSelect: "none",
+ WebkitUserSelect: "none",
+ MozUserSelect: "none",
+ msUserSelect: "none",
+ }}
+ >
{language}
</span>
- </div>
- </CommandItem>
+ </div>
+ </CommandItem>
))}
</CommandGroup>
</CommandList>
@@ -784,13 +792,13 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<div className="flex items-center space-x-2">
<Switch
- id="piiRemoval"
- checked={localSettings.usePiiRemoval}
- onCheckedChange={handlePiiRemovalChange}
+ id="piiRemoval"
+ checked={localSettings.usePiiRemoval}
+ onCheckedChange={handlePiiRemovalChange}
/>
<Label
- htmlFor="piiRemoval"
- className="flex items-center space-x-2"
+ htmlFor="piiRemoval"
+ className="flex items-center space-x-2"
>
<span>remove personal information (PII)</span>
<Badge variant="outline" className="ml-2">
@@ -799,13 +807,13 @@ export function RecordingSettings({
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent>
<p>
removes sensitive information like credit card
numbers, emails, and phone numbers from OCR text
- <br/>
+ <br />
before saving to the database or returning in search
results
</p>
@@ -817,8 +825,8 @@ export function RecordingSettings({
</div>
<div className="flex flex-col space-y-2">
<Label
- htmlFor="restartInterval"
- className="flex items-center space-x-2"
+ htmlFor="restartInterval"
+ className="flex items-center space-x-2"
>
<span>restart interval (minutes)</span>
<Badge variant="outline" className="ml-2">
@@ -827,14 +835,14 @@ export function RecordingSettings({
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent>
<p>
set how often the recording process should restart.
- <br/>
+ <br />
0 means no automatic restart.
- <br/>
+ <br />
this can help mitigate potential memory leaks or other
issues.
</p>
@@ -843,32 +851,32 @@ export function RecordingSettings({
</TooltipProvider>
</Label>
<Input
- id="restartInterval"
- type="number"
- min="0"
- value={localSettings.restartInterval}
- onChange={handleRestartIntervalChange}
- className="w-full"
- placeholder="Enter restart interval in minutes (0 to disable)"
+ id="restartInterval"
+ type="number"
+ min="0"
+ value={localSettings.restartInterval}
+ onChange={handleRestartIntervalChange}
+ className="w-full"
+ placeholder="Enter restart interval in minutes (0 to disable)"
/>
</div>
<div className="flex flex-col space-y-2">
<div className="flex items-center space-x-2">
<Switch
- id="disableAudio"
- checked={localSettings.disableAudio}
- onCheckedChange={handleDisableAudioChange}
+ id="disableAudio"
+ checked={localSettings.disableAudio}
+ onCheckedChange={handleDisableAudioChange}
/>
<Label
- htmlFor="disableAudio"
- className="flex items-center space-x-2"
+ htmlFor="disableAudio"
+ className="flex items-center space-x-2"
>
<span>disable audio recording</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent>
<p>
@@ -884,23 +892,23 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<Label
- htmlFor="ignoredWindows"
- className="flex items-center space-x-2"
+ htmlFor="ignoredWindows"
+ className="flex items-center space-x-2"
>
<span>ignored windows</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent side="right">
<p>
windows to ignore during screen recording
(case-insensitive), example:
- <br/>
+ <br />
- &quot;bit&quot; will ignore &quot;Bitwarden&quot; and
&quot;bittorrent&quot;
- <br/>- &quot;incognito&quot; will ignore tabs, windows
+ <br />- &quot;incognito&quot; will ignore tabs, windows
that contains the word &quot;incognito&quot;
</p>
</TooltipContent>
@@ -909,38 +917,38 @@ export function RecordingSettings({
</Label>
<div className="flex flex-wrap gap-2 mb-2">
{localSettings.ignoredWindows.map((window) => (
- <Badge
- key={window}
- variant="secondary"
- className="flex items-center gap-1"
- >
- {window}
- <X
- className="h-3 w-3 cursor-pointer"
- onClick={() => handleRemoveIgnoredWindow(window)}
- />
- </Badge>
+ <Badge
+ key={window}
+ variant="secondary"
+ className="flex items-center gap-1"
+ >
+ {window}
+ <X
+ className="h-3 w-3 cursor-pointer"
+ onClick={() => handleRemoveIgnoredWindow(window)}
+ />
+ </Badge>
))}
</div>
<div className="flex gap-2">
<Input
- id="ignoredWindows"
- placeholder="add window to ignore"
- onKeyPress={(e) => {
- if (e.key === "Enter") {
- handleAddIgnoredWindow(e.currentTarget.value);
- e.currentTarget.value = "";
- }
- }}
+ id="ignoredWindows"
+ placeholder="add window to ignore"
+ onKeyPress={(e) => {
+ if (e.key === "Enter") {
+ handleAddIgnoredWindow(e.currentTarget.value);
+ e.currentTarget.value = "";
+ }
+ }}
/>
<Button
- onClick={() => {
- const input = document.getElementById(
- "ignoredWindows"
- ) as HTMLInputElement;
- handleAddIgnoredWindow(input.value);
- input.value = "";
- }}
+ onClick={() => {
+ const input = document.getElementById(
+ "ignoredWindows"
+ ) as HTMLInputElement;
+ handleAddIgnoredWindow(input.value);
+ input.value = "";
+ }}
>
add
</Button>
@@ -949,23 +957,23 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<Label
- htmlFor="includedWindows"
- className="flex items-center space-x-2"
+ htmlFor="includedWindows"
+ className="flex items-center space-x-2"
>
<span>included windows</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent side="right">
<p>
windows to include during screen recording
(case-insensitive), example:
- <br/>
+ <br />
- &quot;chrome&quot; will match &quot;Google
Chrome&quot;
- <br/>- &quot;bitwarden&quot; will match
+ <br />- &quot;bitwarden&quot; will match
&quot;Bitwarden&quot; and &quot;bittorrent&quot;
</p>
</TooltipContent>
@@ -974,38 +982,38 @@ export function RecordingSettings({
</Label>
<div className="flex flex-wrap gap-2 mb-2">
{localSettings.includedWindows.map((window) => (
- <Badge
- key={window}
- variant="secondary"
- className="flex items-center gap-1"
- >
- {window}
- <X
- className="h-3 w-3 cursor-pointer"
- onClick={() => handleRemoveIncludedWindow(window)}
- />
- </Badge>
+ <Badge
+ key={window}
+ variant="secondary"
+ className="flex items-center gap-1"
+ >
+ {window}
+ <X
+ className="h-3 w-3 cursor-pointer"
+ onClick={() => handleRemoveIncludedWindow(window)}
+ />
+ </Badge>
))}
</div>
<div className="flex gap-2">
<Input
- id="includedWindows"
- placeholder="add window to include"
- onKeyPress={(e) => {
- if (e.key === "Enter") {
- handleAddIncludedWindow(e.currentTarget.value);
- e.currentTarget.value = "";
- }
- }}
+ id="includedWindows"
+ placeholder="add window to include"
+ onKeyPress={(e) => {
+ if (e.key === "Enter") {
+ handleAddIncludedWindow(e.currentTarget.value);
+ e.currentTarget.value = "";
+ }
+ }}
/>
<Button
- onClick={() => {
- const input = document.getElementById(
- "includedWindows"
- ) as HTMLInputElement;
- handleAddIncludedWindow(input.value);
- input.value = "";
- }}
+ onClick={() => {
+ const input = document.getElementById(
+ "includedWindows"
+ ) as HTMLInputElement;
+ handleAddIncludedWindow(input.value);
+ input.value = "";
+ }}
>
add
</Button>
@@ -1018,15 +1026,15 @@ export function RecordingSettings({
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent side="right">
<p>
adjust the recording frame rate. lower values save
- <br/>
+ <br />
resources, higher values provide smoother recordings,
less likely to miss activity.
- <br/>
+ <br />
(we do not use resources if your screen does not change
much)
</p>
@@ -1036,13 +1044,13 @@ export function RecordingSettings({
</Label>
<div className="flex items-center space-x-4">
<Slider
- id="fps"
- min={0.1}
- max={10}
- step={0.1}
- value={[localSettings.fps]}
- onValueChange={handleFpsChange}
- className="flex-grow"
+ id="fps"
+ min={0.1}
+ max={10}
+ step={0.1}
+ value={[localSettings.fps]}
+ onValueChange={handleFpsChange}
+ className="flex-grow"
/>
<span className="w-12 text-right">
{localSettings.fps.toFixed(1)}
@@ -1052,24 +1060,24 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<Label
- htmlFor="vadSensitivity"
- className="flex items-center space-x-2"
+ htmlFor="vadSensitivity"
+ className="flex items-center space-x-2"
>
<span>vad sensitivity</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent side="right">
<p>
adjust the voice activity detection sensitivity.
- <br/>
+ <br />
low: more sensitive, catches most speech but may have
more false positives.
- <br/>
+ <br />
medium: balanced sensitivity.
- <br/>
+ <br />
high (recommended): less sensitive, may miss some speech
but reduces false positives.
</p>
@@ -1079,13 +1087,13 @@ export function RecordingSettings({
</Label>
<div className="flex items-center space-x-4">
<Slider
- id="vadSensitivity"
- min={0}
- max={2}
- step={1}
- value={[vadSensitivityToNumber(localSettings.vadSensitivity)]}
- onValueChange={handleVadSensitivityChange}
- className="flex-grow"
+ id="vadSensitivity"
+ min={0}
+ max={2}
+ step={1}
+ value={[vadSensitivityToNumber(localSettings.vadSensitivity)]}
+ onValueChange={handleVadSensitivityChange}
+ className="flex-grow"
/>
<span className="w-16 text-right">
{localSettings.vadSensitivity}
@@ -1100,24 +1108,24 @@ export function RecordingSettings({
<div className="flex flex-col space-y-2">
<Label
- htmlFor="audioChunkDuration"
- className="flex items-center space-x-2"
+ htmlFor="audioChunkDuration"
+ className="flex items-center space-x-2"
>
<span>audio chunk duration (seconds)</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent side="right">
<p>
adjust the duration of each audio chunk.
- <br/>
+ <br />
shorter durations may lower resource usage spikes,
- <br/>
+ <br />
while longer durations may increase transcription
quality.
- <br/>
+ <br />
deepgram in general works better than whisper if you
want higher quality transcription.
</p>
@@ -1127,13 +1135,13 @@ export function RecordingSettings({
</Label>
<div className="flex items-center space-x-4">
<Slider
- id="audioChunkDuration"
- min={5}
- max={3000}
- step={1}
- value={[localSettings.audioChunkDuration]}
- onValueChange={handleAudioChunkDurationChange}
- className="flex-grow"
+ id="audioChunkDuration"
+ min={5}
+ max={3000}
+ step={1}
+ value={[localSettings.audioChunkDuration]}
+ onValueChange={handleAudioChunkDurationChange}
+ className="flex-grow"
/>
<span className="w-12 text-right">
{localSettings.audioChunkDuration} s
@@ -1142,39 +1150,39 @@ export function RecordingSettings({
</div>
<div className="flex items-center space-x-2">
<Switch
- id="analytics-toggle"
- checked={localSettings.analyticsEnabled}
- onCheckedChange={handleAnalyticsToggle}
+ id="analytics-toggle"
+ checked={localSettings.analyticsEnabled}
+ onCheckedChange={handleAnalyticsToggle}
/>
<Label
- htmlFor="analytics-toggle"
- className="flex items-center space-x-2"
+ htmlFor="analytics-toggle"
+ className="flex items-center space-x-2"
>
<span>enable telemetry</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent side="right">
<p>
telemetry helps us improve screenpipe.
- <br/>
+ <br />
when enabled, we collect anonymous usage data such as
button clicks.
- <br/>
+ <br />
we do not collect any screen data, microphone, query
data.
- <br/>
+ <br />
do not collect any screen data, microphone, query data.
- <br/>
+ <br />
read more on our data privacy policy at
- <br/>
+ <br />
<a
- href="https://screenpi.pe/privacy"
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary hover:underline"
+ href="https://screenpi.pe/privacy"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-primary hover:underline"
>
https://screenpi.pe/privacy
</a>
@@ -1186,28 +1194,28 @@ export function RecordingSettings({
</div>
<div className="flex items-center space-x-2">
<Switch
- id="chinese-mirror-toggle"
- checked={localSettings.useChineseMirror}
- onCheckedChange={handleChineseMirrorToggle}
+ id="chinese-mirror-toggle"
+ checked={localSettings.useChineseMirror}
+ onCheckedChange={handleChineseMirrorToggle}
/>
<Label
- htmlFor="chinese-mirror-toggle"
- className="flex items-center space-x-2"
+ htmlFor="chinese-mirror-toggle"
+ className="flex items-center space-x-2"
>
<span>use chinese mirror for model downloads</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default"/>
+ <HelpCircle className="h-4 w-4 cursor-default" />
</TooltipTrigger>
<TooltipContent side="right">
<p>
enable this option to use a chinese mirror for
- <br/>
+ <br />
downloading Hugging Face models
- <br/>
+ <br />
(e.g. Whisper, embedded Llama, etc.)
- <br/>
+ <br />
which are blocked in mainland China.
</p>
</TooltipContent>
@@ -1215,6 +1223,46 @@ export function RecordingSettings({
</TooltipProvider>
</Label>
</div>
+ {isMacOS && (
+ <div className="flex items-center space-x-2">
+ <Switch
+ id="enable-beta-toggle"
+ checked={localSettings.enableBeta}
+ onCheckedChange={handleEnableBetaToggle}
+ />
+ <Label
+ htmlFor="enable-beta-toggle"
+ className="flex items-center space-x-2"
+ >
+ <span>enable beta features</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ ⚠️ uses our hosted AI service (powered by OpenAI) ⚠️
+ <br />
+ • we provide free ChatGPT credits
+ <br />
+ • may have privacy implications (data sent to our
+ servers)
+ <br />
+ enables experimental features like double slash
+ <br />
+ which you can use to autocomplete anywhere
+ <br />
+ by pressing twice on slash or stop it with pressing q
+ <br />
+ (only tested on US or German qwertz keyboards)
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ </div>
+ )}
</CardContent>
</Card>
</div>
@@ -1228,7 +1276,7 @@ export function RecordingSettings({
</DialogDescription>
</DialogHeader>
<div className="overflow-x-auto">
- <CodeBlock language="bash" value={generateCliCommand()}/>
+ <CodeBlock language="bash" value={generateCliCommand()} />
</div>
<DialogFooter>
<Button onClick={handleCopyCliCommand}>Copy to Clipboard</Button>
diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 43f5be188..453e66db4 100644
--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -41,7 +41,8 @@ export interface Settings {
audioChunkDuration: number; // new field
useChineseMirror: boolean; // Add this line
embeddedLLM: EmbeddedLLMConfig;
- languages: Language[],
+ languages: Language[];
+ enableBeta: boolean;
}
const defaultSettings: Settings = {
@@ -83,6 +84,7 @@ const defaultSettings: Settings = {
model: "llama3.2:1b-instruct-q4_K_M",
port: 11438,
},
+ enableBeta: false,
};
let store: Awaited<ReturnType<typeof createStore>> | null = null;
@@ -212,6 +214,8 @@ export function useSettings() {
? savedIgnoredWindows
: defaultIgnoredWindows;
+ const savedEnableBeta = (await store!.get<boolean>("enableBeta")) || false;
+
setSettings({
openaiApiKey: savedKey,
deepgramApiKey: savedDeepgramKey,
@@ -241,6 +245,7 @@ export function useSettings() {
useChineseMirror: savedUseChineseMirror,
embeddedLLM: savedEmbeddedLLM,
languages: savedLanguages,
+ enableBeta: savedEnableBeta,
});
} catch (error) {
console.error("failed to load settings:", error);
diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
index ba909baad..9ce643846 100644
--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs
+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
@@ -167,6 +167,11 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {
.and_then(|v| v.as_array().cloned())
.unwrap_or_default();
+ let enable_beta = store
+ .get("enableBeta")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
println!("audio_chunk_duration: {}", audio_chunk_duration);
let port_str = port.to_string();
@@ -266,6 +271,10 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {
args.push("--disable-telemetry");
}
+ if enable_beta {
+ args.push("--enable-beta");
+ }
+
// args.push("--debug");
// macos /Applications/screenpipe.app/Contents/MacOS/
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index 1669ed756..bb9ad9296 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -15,7 +15,7 @@ mod pipes {
use std::path::Path;
use std::pin::Pin;
use tokio::io::{AsyncBufReadExt, BufReader};
- use tracing::{error, info};
+ use tracing::{debug, error, info};
use url::Url;
// Update this function near the top of the file
@@ -105,7 +105,7 @@ mod pipes {
if let Some(line) = line {
if line.contains("Download") {
// Log download messages as info instead of error
- info!("[pipe][download][{}] {}", pipe_clone, line);
+ debug!("[pipe][download][{}] {}", pipe_clone, line);
} else {
// Keep other messages as errors
error!("[pipe][error][{}] {}", pipe_clone, line);
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 94f4bb96c..3c6a94691 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -91,9 +91,6 @@ uuid = "1.5.0"
tempfile = { version = "3.3.0", optional = true }
url = { version = "2.2.0", optional = true }
-# Telemetry
-highlightio = { version = "1.0.2", features = ["tokio"] }
-
[dev-dependencies]
tempfile = "3.3.0"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 0c95cc23d..f16636d0f 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -393,7 +393,7 @@ async fn main() -> anyhow::Result<()> {
"open source | runs locally | developer friendly".bright_green()
);
- println!("┌─────────────────────┬──────────────���─────���───────────────┐");
+ println!("┌─────────────────────┬────────────────────────────────────┐");
println!("│ setting │ value │");
println!("├─────────────────────┼────────────────────────────────────┤");
println!("│ fps │ {:<34} │", cli.fps);
@@ -634,18 +634,30 @@ async fn main() -> anyhow::Result<()> {
let ctrl_c_future = signal::ctrl_c();
pin_mut!(ctrl_c_future);
+ // only in beta and on macos
#[cfg(feature = "beta")]
{
- use screenpipe_actions::run; // Ensure this import is present
+ if cli.enable_beta && cfg!(target_os = "macos") {
+ use screenpipe_actions::run;
- info!("beta feature enabled, starting screenpipe actions");
+ info!("beta feature enabled, starting screenpipe actions");
- // Spawn the run function in a blocking task to avoid affecting the async runtime
- tokio::spawn(async {
- if let Err(e) = run().await {
- eprintln!("Error running screenpipe actions: {}", e);
- }
- });
+ let shutdown_tx_clone = shutdown_tx.clone();
+ tokio::spawn(async move {
+ let mut shutdown_rx = shutdown_tx_clone.subscribe();
+
+ tokio::select! {
+ result = run() => {
+ if let Err(e) = result {
+ error!("Error running screenpipe actions: {}", e);
+ }
+ }
+ _ = shutdown_rx.recv() => {
+ info!("Received shutdown signal, stopping screenpipe actions");
+ }
+ }
+ });
+ }
}
tokio::select! {
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index 2c759ecf8..2e85308a3 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -230,6 +230,10 @@ pub struct Cli {
#[arg(long, default_value_t = false)]
pub enable_llm: bool,
+ /// Enable beta features
+ #[arg(long, default_value_t = false)]
+ pub enable_beta: bool,
+
#[command(subcommand)]
pub command: Option<Command>,