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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: realtime pipe update, start, stop, etc. + full screen pipes
Louis Beaumont59326f5c8c85
diff --git a/examples/typescript/pipe-simple-nextjs/next.config.mjs b/examples/typescript/pipe-simple-nextjs/next.config.mjsindex 253e60e68..93cd85362 100644--- a/examples/typescript/pipe-simple-nextjs/next.config.mjs+++ b/examples/typescript/pipe-simple-nextjs/next.config.mjs@@ -3,6 +3,9 @@ const nextConfig = {images: {domains: ['screenpi.pe'],},+ experimental: {+ darkMode: false,+ },};export default nextConfig;diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 5b6ff903c..377780ba2 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -40,7 +40,7 @@ mod pipes {.to_string()}- pub async fn run_pipe(pipe: &str, screenpipe_dir: PathBuf) -> Result<Option<u16>> {+ pub async fn run_pipe(pipe: &str, screenpipe_dir: PathBuf) -> Result<tokio::process::Child> {let bun_path = find_bun_path().ok_or_else(|| anyhow::anyhow!("bun not found"))?;let pipe_dir = screenpipe_dir.join("pipes").join(pipe);let pipe_json_path = pipe_dir.join("pipe.json");@@ -56,7 +56,7 @@ mod pipes {.unwrap_or(false){debug!("pipe {} is disabled, stopping", pipe);- return Ok(None);+ anyhow::bail!("pipe is disabled");}}@@ -77,10 +77,10 @@ mod pipes {let pipe_config: Value = serde_json::from_str(&pipe_json)?;if pipe_config["is_nextjs"] == json!(true) {- info!("Running Next.js pipe: {}", pipe);+ info!("running next.js pipe: {}", pipe);// Install dependencies using bun- info!("Installing dependencies for Next.js pipe");+ info!("installing dependencies for next.js pipe");let install_output = Command::new(&bun_path).arg("install").current_dir(&pipe_dir)@@ -89,10 +89,10 @@ mod pipes {if !install_output.status.success() {error!(- "Failed to install dependencies: {}",+ "failed to install dependencies: {}",String::from_utf8_lossy(&install_output.stderr));- anyhow::bail!("Failed to install dependencies for Next.js pipe");+ anyhow::bail!("failed to install dependencies for next.js pipe");}let port = pick_unused_port().expect("No ports free");@@ -121,13 +121,12 @@ mod pipes {// Stream logsstream_logs(pipe, &mut child).await?;- return Ok(Some(port));+ return Ok(child);}}// If it's not a Next.js project, run the pipe as beforelet main_module = find_pipe_file(&pipe_dir)?;-info!("executing pipe: {:?}", main_module);// Add PIPE_FILE to environment variables for non-Next.js pipes@@ -144,10 +143,10 @@ mod pipes {.stderr(std::process::Stdio::piped()).spawn()?;- // Stream logs+ // Stream logs - don't block the main threadstream_logs(pipe, &mut child).await?;- Ok(None)+ Ok(child)}async fn stream_logs(pipe: &str, child: &mut tokio::process::Child) -> Result<()> {@@ -157,17 +156,17 @@ mod pipes {let pipe_clone = pipe.to_string();// Spawn tasks to handle stdout and stderr- let stdout_handle = tokio::spawn(async move {+ let _stdout_handle = tokio::spawn(async move {let reader = BufReader::new(stdout);let mut lines = reader.lines();while let Ok(Some(line)) = lines.next_line().await {- info!("[pipe][info][{}] {}", pipe_clone, line);+ info!("[{}] {}", pipe_clone, line);}});let pipe_clone = pipe.to_string();- let stderr_handle = tokio::spawn(async move {+ let _stderr_handle = tokio::spawn(async move {let reader = BufReader::new(stderr);let mut lines = reader.lines();while let Ok(Some(line)) = lines.next_line().await {@@ -177,23 +176,14 @@ mod pipes {|| line.contains("ready started server")|| line.contains("Local:"){- println!("[pipe][info][{}] {}", pipe_clone, line);+ info!("[{}] {}", pipe_clone, line);} else {- println!("[pipe][error][{}] {}", pipe_clone, line);+ error!("[{}] {}", pipe_clone, line);}}});- // Wait for the child process to finish- let status = child.wait().await?;-- // Wait for the output handling tasks to finish- stdout_handle.await?;- stderr_handle.await?;-- if !status.success() {- anyhow::bail!("pipe execution failed with status: {}", status);- }+ // dont' wait for the child process to finishinfo!("pipe execution completed successfully");Ok(())@@ -321,7 +311,7 @@ mod pipes {.spawn()?;// Stream logs for npm install- stream_logs("npm install", &mut install_child).await?;+ stream_logs("bun install", &mut install_child).await?;// Update pipe.json to indicate it's a Next.js projectlet mut pipe_config = if let Some(existing_json) = &existing_config {diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 1f12565fe..af9cdbfcc 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -7,13 +7,13 @@ use clap::Parser;use colored::Colorize;use crossbeam::queue::SegQueue;use dirs::home_dir;-use futures::{pin_mut, stream::FuturesUnordered, StreamExt};+use futures::pin_mut;use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices, parse_audio_device, AudioDevice, DeviceControl};use screenpipe_core::find_ffmpeg_path;use screenpipe_server::{- cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand, OutputFormat}, start_continuous_recording, watch_pid, DatabaseManager, PipeControl, PipeManager, ResourceMonitor, Server, highlight::{Highlight,HighlightConfig}+ cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand, OutputFormat}, start_continuous_recording, watch_pid, DatabaseManager, PipeManager, ResourceMonitor, Server, highlight::{Highlight,HighlightConfig}};use screenpipe_vision::monitor::list_monitors;#[cfg(target_os = "macos")]@@ -121,9 +121,7 @@ async fn main() -> anyhow::Result<()> {}).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);-+ let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));if let Some(pipe_command) = cli.command {@@ -446,8 +444,6 @@ async fn main() -> anyhow::Result<()> {cli.enable_ui_monitoring,);- let pipe_futures = Arc::new(tokio::sync::Mutex::new(FuturesUnordered::new()));- let pipe_futures_clone = pipe_futures.clone();// print screenpipe in gradientprintln!("\n\n{}", DISPLAY.truecolor(147, 112, 219).bold());@@ -680,7 +676,7 @@ async fn main() -> anyhow::Result<()> {);// Start pipes- debug!("starting pipes");+ info!("starting pipes");let pipes = pipe_manager.list_pipes().await;for pipe in pipes {debug!("pipe: {:?}", pipe.id);@@ -688,26 +684,19 @@ async fn main() -> anyhow::Result<()> {debug!("pipe {} is disabled, skipping", pipe.id);continue;}- match pipe_manager.start_pipe(&pipe.id).await {- Ok(future) => pipe_futures.lock().await.push(future),- Err(e) => eprintln!("failed to start pipe {}: {}", pipe.id, e),+ match pipe_manager.start_pipe_task(pipe.id.clone()).await {+ Ok(future) => {+ tokio::spawn(future);+ }+ Err(e) => {+ error!("failed to start pipe {}: {}", pipe.id, e);+ }}}let server_future = server.start(devices_status, api_plugin, cli.enable_frame_cache);pin_mut!(server_future);- let pipes_future = async {- loop {- if let Some(result) = pipe_futures_clone.lock().await.next().await {- info!("pipe completed: {:?}", result);- } else {- tokio::time::sleep(std::time::Duration::from_secs(1)).await;- }- }- };- pin_mut!(pipes_future);-// Add auto-destruct watcherif let Some(pid) = cli.auto_destruct_pid {info!("watching pid {} for auto-destruction", pid);@@ -779,24 +768,7 @@ async fn main() -> anyhow::Result<()> {});}- let pipe_control_future = async {- while let Some(control) = pipe_control_rx.recv().await {- match control {- PipeControl::Enable(pipe_id) => {- debug!("enabling pipe: {}", pipe_id);- match pipe_manager.start_pipe(&pipe_id).await {- Ok(future) => pipe_futures_clone.lock().await.push(future),- Err(e) => error!("failed to start pipe {}: {}", pipe_id, e),- }- }- PipeControl::Disable(pipe_id) => {- debug!("disabling pipe: {}", pipe_id);- }- }- }- };- pin_mut!(pipe_control_future);-+tokio::select! {_ = handle => info!("recording completed"),result = &mut server_future => {@@ -805,12 +777,6 @@ async fn main() -> anyhow::Result<()> {Err(e) => error!("server stopped with error: {:?}", e),}}- _ = &mut pipes_future => {- info!("all pipes completed, but server is still running");- }- _ = &mut pipe_control_future => {- info!("pipe control channel closed");- }_ = ctrl_c_future => {info!("received ctrl+c, initiating shutdown");let _ = shutdown_tx.send(());diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 5ae82aa65..373885d86 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -19,7 +19,6 @@ pub use cli::Cli;pub use core::start_continuous_recording;pub use db::{ContentSource, ContentType, DatabaseManager, SearchResult};pub use highlight::Highlight;-pub use pipe_manager::PipeControl;pub use pipe_manager::PipeManager;pub use resource_monitor::{ResourceMonitor, RestartSignal};pub use screenpipe_core::Language;diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rsindex 1bf42d60c..475da5f9d 100644--- a/screenpipe-server/src/pipe_manager.rs+++ b/screenpipe-server/src/pipe_manager.rs@@ -2,11 +2,14 @@ use anyhow::Result;use screenpipe_core::download_pipe;use serde::{Deserialize, Serialize};use serde_json::Value;+use std::collections::HashMap;use std::future::Future;use std::path::PathBuf;+use std::sync::Arc;use tokio::fs::File;use tokio::io::AsyncWriteExt;-use tokio::sync::mpsc::{self, Receiver, Sender};+use tokio::sync::mpsc::{self, Sender};+use tokio::sync::RwLock;use tracing::{debug, info};#[derive(Clone, Serialize, Deserialize, Debug)]@@ -18,52 +21,21 @@ pub struct PipeInfo {pub port: Option<u16>,}-#[derive(Debug)]-pub enum PipeControl {- Enable(String),- Disable(String),+struct PipeHandle {+ pid: i32,+ kill_tx: Sender<()>,}pub struct PipeManager {screenpipe_dir: PathBuf,- control_tx: Sender<PipeControl>,+ running_pipes: Arc<RwLock<HashMap<String, PipeHandle>>>,}impl PipeManager {- pub fn new(screenpipe_dir: PathBuf) -> (Self, Receiver<PipeControl>) {- let (control_tx, control_rx) = mpsc::channel(32);- (- PipeManager {- screenpipe_dir,- control_tx,- },- control_rx,- )- }-- pub async fn start_pipe(- &self,- id: &str,- ) -> Result<impl Future<Output = Result<Option<u16>, anyhow::Error>>> {- let pipes = self.list_pipes().await;-- if let Some(_) = pipes.iter().find(|pipe| pipe.id == id) {- let pipe_id = id.to_string();- let screenpipe_dir = self.screenpipe_dir.clone();-- let future = async move { screenpipe_core::run_pipe(&pipe_id, screenpipe_dir).await };-- self.update_config(- id,- serde_json::json!({- "enabled": true,- }),- )- .await?;-- Ok(future)- } else {- Err(anyhow::anyhow!("pipe not found"))+ pub fn new(screenpipe_dir: PathBuf) -> Self {+ PipeManager {+ screenpipe_dir,+ running_pipes: Arc::new(RwLock::new(HashMap::new())),}}@@ -88,8 +60,22 @@ impl PipeManager {})};- // Check enabled before moving new_config- let enabled = new_config.get("enabled").and_then(Value::as_bool);+ debug!("config: {}", config);++ let was_enabled = if config_path.exists() {+ let old_config: Value =+ serde_json::from_str(&tokio::fs::read_to_string(&config_path).await?)?;+ old_config+ .get("enabled")+ .and_then(Value::as_bool)+ .unwrap_or(false)+ } else {+ false+ };++ let is_enabled = new_config.get("enabled").and_then(Value::as_bool);++ debug!("is_enabled: {}", is_enabled.unwrap_or(false));if let Value::Object(existing_config) = &mut config {if let Value::Object(updates) = new_config {@@ -103,21 +89,37 @@ impl PipeManager {return Err(anyhow::anyhow!("existing configuration is not an object"));}- // Use the previously extracted enabled value- if let Some(enabled) = enabled {- let control = if enabled {- PipeControl::Enable(id.to_string())- } else {- PipeControl::Disable(id.to_string())- };- let _ = self.control_tx.send(control).await;- }-let updated_config_str = serde_json::to_string_pretty(&config)?;let mut file = File::create(&config_path).await?;file.write_all(updated_config_str.as_bytes()).await?;+ // Handle pipe state changes+ if let Some(enabled) = is_enabled {+ match (was_enabled, enabled) {+ (false, true) => {+ let future = self.start_pipe_task(id.to_string()).await?;+ tokio::spawn(future);++ info!("pipe {} enabled", id);+ }+ (true, false) => {+ self.stop_pipe(id).await?;++ info!("pipe {} disabled", id);+ }+ (true, true) => {+ self.stop_pipe(id).await?;++ let future = self.start_pipe_task(id.to_string()).await?;+ tokio::spawn(future);++ info!("pipe {} restarted", id);+ }+ (false, false) => {} // No state change needed+ }+ }+Ok(())}@@ -208,28 +210,83 @@ impl PipeManager {}pub async fn delete_pipe(&self, id: &str) -> Result<()> {- debug!("deleting pipe: {}", id);-- // First disable the pipe to stop any running instances- self.update_config(- id,- serde_json::json!({- "enabled": false,- }),- )- .await?;-- // Send control message to stop the pipe- let _ = self.control_tx.send(PipeControl::Disable(id.to_string())).await;+ // First stop the pipe if running+ self.stop_pipe(id).await?;- // Delete the pipe directory+ // Then delete the directorylet pipe_dir = self.screenpipe_dir.join("pipes").join(id);if pipe_dir.exists() {tokio::fs::remove_dir_all(pipe_dir).await?;- info!("pipe {} deleted", id);+ debug!("deleted pipe: {}", id);Ok(())} else {Err(anyhow::anyhow!("pipe '{}' does not exist", id))}}++ pub async fn stop_pipe(&self, id: &str) -> Result<()> {+ let mut pipes = self.running_pipes.write().await;+ if let Some(handle) = pipes.remove(id) {+ info!("stopping pipe: {} with pid {}", id, handle.pid);++ // Send kill signal through channel+ let _ = handle.kill_tx.send(()).await;++ info!("stopped pipe: {}", id);+ }+ Ok(())+ }++ pub async fn start_pipe_task(&self, id: String) -> Result<impl Future<Output = Result<()>>> {+ let screenpipe_dir = self.screenpipe_dir.clone();+ let running_pipes = self.running_pipes.clone();+ let id_for_map = id.clone();++ Ok(async move {+ match screenpipe_core::run_pipe(&id, screenpipe_dir.clone()).await {+ Ok(mut child) => {+ let pid = child.id().expect("Failed to get child pid") as i32;+ let (kill_tx, mut kill_rx) = mpsc::channel::<()>(1);++ running_pipes.write().await.insert(+ id_for_map.clone(),+ PipeHandle {+ pid,+ kill_tx: kill_tx.clone(),+ },+ );++ info!("started pipe: {} with pid {}", id, pid);++ tokio::select! {+ status = child.wait() => {+ match status {+ Ok(status) if !status.success() => {+ println!("pipe {} exited with status: {}", id, status);+ running_pipes.write().await.remove(&id_for_map);+ anyhow::bail!("pipe exited with non-zero status: {}", status);+ }+ Err(e) => {+ println!("error waiting for pipe {}: {}", id, e);+ running_pipes.write().await.remove(&id_for_map);+ anyhow::bail!("error waiting for pipe: {}", e);+ }+ Ok(_) => Ok(())+ }+ }+ _ = kill_rx.recv() => {+ // Kill received through channel+ let _ = child.kill().await;+ running_pipes.write().await.remove(&id_for_map);+ Ok(())+ }+ }+ }+ Err(e) => {+ println!("failed to start pipe {}: {}", id, e);+ Err(e)+ }+ }+ })+ }}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex c5470446a..8bc4ce0a4 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -662,7 +662,7 @@ async fn run_pipe_handler(State(state): State<Arc<AppState>>,JsonResponse(payload): JsonResponse<RunPipeRequest>,) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {- debug!("Starting pipe: {}", payload.pipe_id);+ debug!("starting pipe: {}", payload.pipe_id);match state.pipe_manager