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
fix killing pipes (#1130)
neo773734f809645cd
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsxindex df1832a49..ffd5875c0 100644--- a/screenpipe-app-tauri/components/pipe-store.tsx+++ b/screenpipe-app-tauri/components/pipe-store.tsx@@ -542,19 +542,6 @@ const PipeStore: React.FC = () => {}};- const reloadPipeConfig = async (pipe: Pipe) => {- await fetchInstalledPipes();-- const freshPipe = pipes.find(- (p) => normalizeId(p.id) === normalizeId(pipe.id)- );- if (freshPipe) {- console.log("freshPipe", freshPipe);-- setSelectedPipe(freshPipe);- }- };-const handleToggleEnabled = async (pipe: Pipe) => {try {// Reset broken state when manually toggling@@ -801,6 +788,7 @@ const PipeStore: React.FC = () => {const handleConfigSave = async (config: Record<string, any>) => {if (selectedPipe) {try {+ setIsEnabling(true);const response = await fetch("http://localhost:3030/pipes/update", {method: "POST",headers: {@@ -822,7 +810,9 @@ const PipeStore: React.FC = () => {description: "The pipe configuration has been updated.",});- await setSelectedPipe({ ...selectedPipe, config: config });+ await setSelectedPipe({...selectedPipe, config: config});+ setIsEnabling(false);+} catch (error) {console.error("Failed to save config:", error);toast({@@ -831,6 +821,7 @@ const PipeStore: React.FC = () => {"please try again or check the logs for more information.",variant: "destructive",});+ setIsEnabling(false);}}};@@ -1054,8 +1045,7 @@ const PipeStore: React.FC = () => {// Add this effect to periodically check running pipesuseEffect(() => {- const interval = setInterval(checkRunningPipes, 2000);- return () => clearInterval(interval);+ checkRunningPipes();}, [pipes]);const updateBrokenPipes = async (pipeId: string, isBroken: boolean) => {diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex 230855071..54f96129a 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -307,6 +307,19 @@ async fn get_pipe_port(pipe_id: &str) -> anyhow::Result<u16> {.ok_or_else(|| anyhow::anyhow!("no port found for pipe {}", pipe_id))}+async fn list_pipes() -> anyhow::Result<Value> {+ let client = reqwest::Client::new();+ let response = client+ .get("http://localhost:3030/pipes/list")+ .send()+ .await?+ .json::<Value>()+ .await?;++ Ok(response)+}++fn get_base_dir(app: &tauri::AppHandle, custom_path: Option<String>) -> anyhow::Result<PathBuf> {let default_path = app.path().local_data_dir().unwrap().join("screenpipe");@@ -648,10 +661,30 @@ async fn main() {}"quit" => {debug!("Quit requested");- // First try to stop any running recordings- let state = app_handle.state::<SidecarState>();- tauri::async_runtime::block_on(async {- if let Err(e) = kill_all_sreenpipes(state, app_handle.clone()).await {+ // Kill all pipes before quitting+ let app_handle_clone = app_handle.clone();+ tauri::async_runtime::spawn(async move {+ if let Ok(response) = list_pipes().await {+ if let Some(pipes) = response["data"].as_array() {+ for pipe in pipes {+ if pipe["enabled"].as_bool().unwrap_or(false) {+ if let Some(id) = pipe["id"].as_str() {+ let _ = reqwest::Client::new()+ .post(format!("http://localhost:3030/pipes/disable"))+ .json(&serde_json::json!({+ "pipe_id": id+ }))+ .send()+ .await;+ }+ }+ }+ }+ }++ // Stop any running recordings+ let state = app_handle_clone.state::<SidecarState>();+ if let Err(e) = kill_all_sreenpipes(state, app_handle_clone.clone()).await {error!("Error stopping recordings during quit: {}", e);}});diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 2540012b9..9737f96ff 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -38,6 +38,13 @@ mod pipes {use reqwest_middleware::ClientBuilder;use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions};+ #[derive(Clone, Debug, Copy)]+ pub enum PipeState {+ Port(u16),+ Pid(i32),+ }++pub struct CronHandle {shutdown: watch::Sender<bool>,}@@ -73,7 +80,7 @@ mod pipes {.to_string()}- pub async fn run_pipe(pipe: &str, screenpipe_dir: PathBuf) -> Result<tokio::process::Child> {+ pub async fn run_pipe(pipe: &str, screenpipe_dir: PathBuf) -> Result<(tokio::process::Child, PipeState)> {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");@@ -245,7 +252,8 @@ mod pipes {.find(|(k, _)| k == "PORT").map(|(_, v)| v).unwrap()- .clone();+ .parse::<u16>()+ .expect("Invalid port number");// Run the Next.js projectinfo!(@@ -267,7 +275,7 @@ mod pipes {command.arg("--port")- .arg(port)+ .arg(port.to_string()).current_dir(&pipe_dir).envs(env_vars).stdout(std::process::Stdio::piped())@@ -278,7 +286,7 @@ mod pipes {debug!("streaming logs for next.js pipe");stream_logs(pipe, &mut child).await?;- return Ok(child);+ return Ok((child, PipeState::Port(port)));}// If it's not a Next.js project, run as regular pipe@@ -302,7 +310,8 @@ mod pipes {// Stream logsstream_logs(pipe, &mut child).await?;- Ok(child)+ let child_id = child.id().unwrap();+ Ok((child, PipeState::Pid(child_id as i32))) // Return 0 or handle port differently for non-Next.js projects}async fn stream_logs(pipe: &str, child: &mut tokio::process::Child) -> Result<()> {diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 99523fe38..393814336 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -17,6 +17,7 @@ screenpipe-vision = { path = "../screenpipe-vision" }screenpipe-audio = { path = "../screenpipe-audio" }screenpipe-core = { path = "../screenpipe-core", features = ["security"] }screenpipe-actions = { path = "../screenpipe-actions", optional = true }+killport = { version = "1.1.0" }# Image processingimage = { workspace = true }diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rsindex ed35915f4..95681d93d 100644--- a/screenpipe-server/src/pipe_manager.rs+++ b/screenpipe-server/src/pipe_manager.rs@@ -1,5 +1,8 @@use anyhow::Result;-use screenpipe_core::download_pipe;+use killport::cli::Mode;+use killport::killport::{Killport, KillportOperations};+use killport::signal::KillportSignal;+use screenpipe_core::{download_pipe, PipeState};use serde::{Deserialize, Serialize};use serde_json::Value;use std::collections::HashMap;@@ -10,7 +13,7 @@ use tokio::fs::File;use tokio::io::AsyncWriteExt;use tokio::sync::mpsc::{self, Sender};use tokio::sync::RwLock;-use tracing::{debug, info};+use tracing::{debug, info, warn};#[derive(Clone, Serialize, Deserialize, Debug)]pub struct PipeInfo {@@ -22,7 +25,7 @@ pub struct PipeInfo {}struct PipeHandle {- pid: i32,+ state: PipeState,kill_tx: Sender<()>,}@@ -236,7 +239,7 @@ impl PipeManager {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);+ info!("stopping pipe: {}", id);// Send kill signal and wait for confirmationhandle.kill_tx.send(()).await?;@@ -247,29 +250,60 @@ impl PipeManager {// Wait a bit for the process to actually terminatetokio::time::sleep(tokio::time::Duration::from_millis(100)).await;- // Force kill the process if it's still running- #[cfg(unix)]- {- use nix::sys::signal::{kill, Signal};- use nix::unistd::Pid;- let _ = kill(Pid::from_raw(handle.pid), Signal::SIGKILL);- }- #[cfg(windows)]- {- use windows::Win32::System::Threading::{- OpenProcess, TerminateProcess, PROCESS_ACCESS_RIGHTS,- };- unsafe {- if let Ok(h_process) = OpenProcess(- PROCESS_ACCESS_RIGHTS(0x0001), // PROCESS_TERMINATE access right- false,- handle.pid as u32,- ) {- let _ = TerminateProcess(h_process, 1);+ match handle.state {+ PipeState::Port(port) => {+ tokio::task::spawn_blocking(move || {+ let killport = Killport;+ let signal: KillportSignal = "SIGKILL".parse().unwrap();++ match killport.kill_service_by_port(port, signal.clone(), Mode::Auto, false) {+ Ok(killed_services) => {+ if killed_services.is_empty() {+ debug!("no services found using port {}", port);+ } else {+ for (killable_type, name) in killed_services {+ debug!(+ "successfully killed {} '{}' listening on port {}",+ killable_type, name, port+ );+ }+ }+ }+ Err(e) => {+ warn!("error killing port {}: {}", port, e);+ }+ }+ }).await.map_err(|e| anyhow::anyhow!("Failed to kill port: {}", e))?;+ }+ PipeState::Pid(pid) => {+ // Force kill the process if it's still running+ #[cfg(unix)]+ {+ use nix::sys::signal::{kill, Signal};+ use nix::unistd::Pid;+ let _ = kill(Pid::from_raw(pid), Signal::SIGKILL);+ }+ #[cfg(windows)]+ {+ use windows::Win32::System::Threading::{+ OpenProcess, TerminateProcess, PROCESS_ACCESS_RIGHTS,+ };+ unsafe {+ if let Ok(h_process) = OpenProcess(+ PROCESS_ACCESS_RIGHTS(0x0001), // PROCESS_TERMINATE access right+ false,+ pid as u32,+ ) {+ let _ = TerminateProcess(h_process, 1);+ }+ }}}}+ // Clean up cron jobs+ screenpipe_core::pipes::cleanup_pipe_crons(id).await?;+info!("stopped pipe: {}", id);}Ok(())@@ -282,19 +316,25 @@ impl PipeManager {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;+ Ok((mut child, pipe_state)) => {let (kill_tx, mut kill_rx) = mpsc::channel::<()>(1);running_pipes.write().await.insert(id_for_map.clone(),PipeHandle {- pid,+ state: pipe_state,kill_tx: kill_tx.clone(),},);- info!("started pipe: {} with pid {}", id, pid);+ match pipe_state {+ PipeState::Port(port) => {+ info!("started pipe: {} on port {}", id, port);+ }+ PipeState::Pid(pid) => {+ info!("started pipe: {} on pid {}", id, pid);+ }+ }tokio::select! {status = child.wait() => {