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: drop pipes runtime (#1391)

tribhuwand4fd97513b7f
diff --git a/screenpipe-app-tauri/components/breaking-changes-instructions-dialog.tsx b/screenpipe-app-tauri/components/breaking-changes-instructions-dialog.tsx
index 19d210623..d3249eefb 100644
--- a/screenpipe-app-tauri/components/breaking-changes-instructions-dialog.tsx
+++ b/screenpipe-app-tauri/components/breaking-changes-instructions-dialog.tsx
@@ -45,8 +45,20 @@ export function BreakingChangesInstructionsDialog() {
const handleResetAllPipes = async () => {
setIsDeleting(true);
try {
- const cmd = Command.sidecar("screenpipe", ["pipe", "purge", "-y"]);
- await cmd.execute();
+ const response = await fetch(`http://localhost:3030/pipes/purge`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ }),
+ });
+ if(!response.ok){
+ toast({
+ title: "failed to purge pipes",
+ description: "failed to purge pipes, please try again",
+ variant: "destructive"
+ });
+ return;
+ }
toast({
title: "all pipes deleted",
description: "you can now reinstall the updated pipes from the store",
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsx
index e33dee9c6..cf4644a62 100644
--- a/screenpipe-app-tauri/components/pipe-store.tsx
+++ b/screenpipe-app-tauri/components/pipe-store.tsx
@@ -452,8 +452,20 @@ export const PipeStore: React.FC = () => {
duration: 100000,
});
- const cmd = Command.sidecar("screenpipe", ["pipe", "purge", "-y"]);
- await cmd.execute();
+ const response = await fetch(`http://localhost:3030/pipes/purge`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ }),
+ });
+ if(!response.ok){
+ toast({
+ title: "failed to purge pipes",
+ description: "failed to purge pipes, please try again",
+ variant: "destructive"
+ });
+ return;
+ }
await fetchInstalledPipes();
t.update({
diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
index b1c2b0303..44ee32b81 100644
--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs
+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
@@ -81,11 +81,14 @@ pub async fn stop_screenpipe(
) -> Result<(), String> {
debug!("Killing screenpipe");
- let mut manager = state.0.lock().await;
- if let Some(manager) = manager.as_mut() {
- if let Some(child) = manager.child.take() {
- if let Err(e) = child.kill() {
- error!("Failed to kill child process: {}", e);
+ #[cfg(not(target_os = "windows"))]
+ {
+ let mut manager = state.0.lock().await;
+ if let Some(manager) = manager.as_mut() {
+ if let Some(child) = manager.child.take() {
+ if let Err(e) = child.kill() {
+ error!("Failed to kill child process: {}", e);
+ }
}
}
}
@@ -102,11 +105,16 @@ pub async fn stop_screenpipe(
}
#[cfg(target_os = "windows")]
{
- use std::os::windows::process::CommandExt;
-
const CREATE_NO_WINDOW: u32 = 0x08000000;
- tokio::process::Command::new("taskkill")
- .args(&["/F", "/T", "/IM", "screenpipe.exe"])
+ tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
+ tokio::process::Command::new("powershell")
+ .arg("-NoProfile")
+ .arg("-WindowStyle")
+ .arg("hidden")
+ .arg("-Command")
+ .arg(format!(
+ r#"taskkill.exe /F /T /IM screenpipe.exe"#,
+ ))
.creation_flags(CREATE_NO_WINDOW)
.output()
.await
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index 4575d9eb9..d9210e630 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -84,248 +84,6 @@ mod pipes {
.to_string()
}
- async fn create_watchdog_script(parent_pid: u32, child_pid: u32) -> Result<PathBuf> {
- let script_content = if cfg!(windows) {
- format!(
- r#"
-$parentPid = {parent_pid}
-$childPid = {child_pid}
-
-function Get-ChildProcesses($ProcessId) {{
- Get-WmiObject Win32_Process | Where-Object {{ $_.ParentProcessId -eq $ProcessId }} | ForEach-Object {{
- $_.ProcessId
- Get-ChildProcesses $_.ProcessId
- }}
-}}
-
-while ($true) {{
- try {{
- $parent = Get-Process -Id $parentPid -ErrorAction Stop
- Start-Sleep -Seconds 1
- }} catch {{
- Write-Host "Parent process ($parentPid) not found, terminating child processes"
-
- # Get all child processes recursively
- $children = Get-ChildProcesses $childPid
-
- # Add the main process to the list
- $allProcesses = @($childPid) + $children
-
- foreach ($pid in $allProcesses) {{
- try {{
- Stop-Process -Id $pid -Force -ErrorAction SilentlyContinue
- Write-Host "Stopped process: $pid"
- }} catch {{
- Write-Host "Process $pid already terminated"
- }}
- }}
-
- exit
- }}
-}}
-"#
- )
- } else {
- format!(
- r#"#!/bin/bash
-set -x # Enable debug mode
-parent_pid={parent_pid}
-child_pid={child_pid}
-
-echo "[$(date)] Watchdog started - monitoring parent PID: $parent_pid, child PID: $child_pid"
-
-find_all_children() {{
- local parent=$1
- local children=$(pgrep -P $parent)
- echo $children
- for child in $children; do
- find_all_children $child
- done
-}}
-
-cleanup() {{
- echo "[$(date)] Starting cleanup..."
-
- # Get all child processes recursively
- all_children=$(find_all_children $child_pid)
- echo "[$(date)] Found child processes: $all_children"
-
- # Try to kill by process group first
- child_pgid=$(ps -o pgid= -p $child_pid 2>/dev/null | tr -d ' ')
- if [ ! -z "$child_pgid" ]; then
- echo "[$(date)] Killing process group $child_pgid"
- pkill -TERM -g $child_pgid 2>/dev/null || true
- sleep 1
- pkill -KILL -g $child_pgid 2>/dev/null || true
- fi
-
- # Kill all children individually if they still exist
- if [ ! -z "$all_children" ]; then
- echo "[$(date)] Killing all child processes: $all_children"
- kill -TERM $all_children 2>/dev/null || true
- sleep 1
- kill -KILL $all_children 2>/dev/null || true
- fi
-
- # Kill the main process if it still exists
- echo "[$(date)] Killing main process $child_pid"
- kill -TERM $child_pid 2>/dev/null || true
- sleep 1
- kill -KILL $child_pid 2>/dev/null || true
-
- # Final verification
- sleep 1
- remaining=$(ps -o pid= -g $child_pgid 2>/dev/null || true)
- if [ ! -z "$remaining" ]; then
- echo "[$(date)] WARNING: Some processes might still be running: $remaining"
- pkill -KILL -g $child_pgid 2>/dev/null || true
- fi
-
- exit 0
-}}
-
-trap cleanup SIGTERM SIGINT
-
-while true; do
- if ! ps -p $parent_pid > /dev/null 2>&1; then
- echo "[$(date)] Parent process ($parent_pid) not found, terminating child processes"
- cleanup
- exit
- fi
- sleep 1
-done
-"#
- )
- };
-
- let temp_dir = std::env::temp_dir();
- let script_name = if cfg!(windows) {
- format!("watchdog_{parent_pid}_{child_pid}.ps1")
- } else {
- format!("watchdog_{parent_pid}_{child_pid}.sh")
- };
- let script_path = temp_dir.join(script_name);
-
- tokio::fs::write(&script_path, script_content).await?;
-
- // Set executable permissions on Unix systems only
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- let mut perms = tokio::fs::metadata(&script_path).await?.permissions();
- perms.set_mode(0o755);
- tokio::fs::set_permissions(&script_path, perms).await?;
- }
-
- Ok(script_path)
- }
-
- async fn spawn_watchdog(parent_pid: u32, child_pid: u32) -> Result<tokio::process::Child> {
- let script_path = create_watchdog_script(parent_pid, child_pid).await?;
-
- info!(
- "Spawning watchdog process for parent_pid={}, child_pid={}",
- parent_pid, child_pid
- );
- info!("Watchdog script path: {:?}", script_path);
-
- // Create a log file for the watchdog
- let log_path =
- std::env::temp_dir().join(format!("watchdog_{}_{}.log", parent_pid, child_pid));
-
- #[cfg(windows)]
- let child = {
- Command::new("powershell")
- .arg("-ExecutionPolicy")
- .arg("Bypass")
- .arg("-NoProfile")
- .arg("-NonInteractive")
- .arg("-WindowStyle")
- .arg("Hidden")
- .arg("-File")
- .arg(&script_path)
- .creation_flags(0x08000000)
- .stdout(std::fs::File::create(&log_path)?)
- .stderr(std::fs::File::create(&log_path)?)
- .spawn()?
- };
-
- #[cfg(not(windows))]
- let child = {
- Command::new("bash")
- .arg(&script_path)
- .stdout(std::fs::File::create(&log_path)?)
- .stderr(std::fs::File::create(&log_path)?)
- .spawn()?
- };
-
- if let Some(id) = child.id() {
- info!("Watchdog process spawned with PID: {}", id);
-
- // Modify verification for Windows
- #[cfg(windows)]
- {
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(1)).await;
- let output = Command::new("powershell")
- .arg("-NoProfile")
- .arg("-NonInteractive")
- .arg("-Command")
- .arg(format!(
- "Get-Process -Id {} -ErrorAction SilentlyContinue",
- id
- ))
- .output()
- .await;
-
- match output {
- Ok(output) => {
- if output.status.success() {
- info!("Watchdog process verified running with PID: {}", id);
- } else {
- error!("Watchdog process not found after spawn! PID: {}", id);
- }
- }
- Err(e) => error!("Failed to verify watchdog process: {}", e),
- }
- });
- }
-
- #[cfg(not(windows))]
- {
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(1)).await;
- let output = Command::new("ps")
- .args(["-p", &id.to_string()])
- .output()
- .await;
-
- match output {
- Ok(output) => {
- if output.status.success() {
- info!("Watchdog process verified running with PID: {}", id);
- } else {
- error!("Watchdog process not found after spawn! PID: {}", id);
- }
- }
- Err(e) => error!("Failed to verify watchdog process: {}", e),
- }
- });
- }
- }
-
- // Clean up script after a delay
- let script_path_clone = script_path.clone();
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(30)).await;
- if let Err(e) = tokio::fs::remove_file(&script_path_clone).await {
- error!("Failed to remove watchdog script: {}", e);
- }
- });
-
- Ok(child)
- }
-
pub async fn run_pipe(
pipe: &str,
screenpipe_dir: PathBuf,
@@ -564,24 +322,6 @@ done
debug!("[{}] streaming logs for next.js pipe", pipe);
stream_logs(pipe, &mut child).await?;
- let child_pid = child.id().expect("Failed to get child PID") as u32;
- let parent_pid = std::process::id();
-
- info!("Spawned bun process with PID: {}", child_pid);
-
- // Spawn watchdog process
- match spawn_watchdog(parent_pid, child_pid).await {
- Ok(watchdog) => {
- debug!(
- "Watchdog process spawned successfully with PID: {:?}",
- watchdog.id()
- );
- }
- Err(e) => {
- warn!("Failed to spawn watchdog process: {}", e);
- }
- }
-
return Ok((child, PipeState::Port(port)));
}
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 86c3f2fa5..05bfea267 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -527,9 +527,11 @@ async fn main() -> anyhow::Result<()> {
let audio_runtime = Runtime::new().unwrap();
let vision_runtime = Runtime::new().unwrap();
+ let pipes_runtime = Runtime::new().unwrap();
let audio_handle = audio_runtime.handle().clone();
let vision_handle = vision_runtime.handle().clone();
+ let pipes_handle = pipes_runtime.handle().clone();
let db_clone = Arc::clone(&db);
let output_path_clone = Arc::new(local_data_dir.join("data").to_string_lossy().into_owned());
@@ -951,7 +953,7 @@ async fn main() -> anyhow::Result<()> {
}
match pipe_manager.start_pipe_task(pipe.id.clone()).await {
Ok(future) => {
- tokio::spawn(future);
+ pipes_handle.spawn(future);
}
Err(e) => {
error!("failed to start pipe {}: {}", pipe.id, e);
@@ -1073,6 +1075,7 @@ async fn main() -> anyhow::Result<()> {
}
tokio::task::block_in_place(|| {
+ drop(pipes_runtime);
drop(vision_runtime);
drop(audio_runtime);
});
diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rs
index 8d8006e23..bdd46bf60 100644
--- a/screenpipe-server/src/pipe_manager.rs
+++ b/screenpipe-server/src/pipe_manager.rs
@@ -1,7 +1,4 @@
use anyhow::Result;
-use killport::cli::Mode;
-use killport::killport::{Killport, KillportOperations};
-use killport::signal::KillportSignal;
use screenpipe_core::{download_pipe, download_pipe_private, PipeState};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -261,26 +258,60 @@ impl PipeManager {
}
pub async fn purge_pipes(&self) -> Result<()> {
- // First, get all running pipes
- let pipes = self.list_pipes().await;
-
- // Stop all running pipes
- for pipe in pipes {
- if pipe.enabled {
- debug!("stopping pipe {} before purge", pipe.id);
- self.stop_pipe(&pipe.id).await?;
+ let mut retries = 3;
+
+ loop {
+ // First, get all running pipes
+ let pipes = self.list_pipes().await;
+
+ // Stop all running pipes
+ for pipe in pipes {
+ if pipe.enabled {
+ debug!("stopping pipe [{}] before purge", pipe.id);
+ match self.stop_pipe(&pipe.id).await {
+ Ok(_) => {
+ debug!("successfully killed pipe process [{}]", &pipe.id);
+ }
+ Err(_) => {
+ debug!("failed to stop pipe [{}],", &pipe.id);
+ }
+ };
+ }
}
- }
- // Wait for all pipes to stop
- tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
-
- // Then remove the directory
- let pipe_dir = self.screenpipe_dir.join("pipes");
- tokio::fs::remove_dir_all(pipe_dir).await?;
+ // wait a little
+ tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
- debug!("all pipes purged");
- Ok(())
+ let pipe_dir = self.screenpipe_dir.join("pipes");
+ if pipe_dir.exists() {
+ match tokio::fs::remove_dir_all(&pipe_dir).await {
+ Ok(_) => {
+ debug!("all pipes purged");
+ return Ok(());
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::Other => {
+ debug!("attempting iterative deletion");
+ let mut entries = tokio::fs::read_dir(&pipe_dir).await?;
+ while let Some(entry) = entries.next_entry().await? {
+ if let Err(e) = tokio::fs::remove_file(entry.path()).await {
+ debug!("failed to remove file: {:?}", e);
+ }
+ }
+ }
+ Err(e) => {
+ if retries > 0 {
+ retries -= 1;
+ debug!("failed to purge pipes, retrying! ({} retries left)", retries);
+ } else {
+ return Err(e.into());
+ }
+ }
+ }
+ } else {
+ debug!("pipe directory does not exist");
+ return Ok(());
+ }
+ }
}
pub async fn delete_pipe(&self, id: &str) -> Result<()> {
@@ -312,28 +343,109 @@ impl PipeManager {
// Wait a bit for the process to actually terminate
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ #[cfg(unix)]
+ {
+ // try with id first
+ let command = format!(
+ "ps axuw | grep {} | grep -v grep | awk '{{print $2}}' | xargs -I {{}} kill -TERM {{}}",
+ &id.to_string()
+ );
+
+ let _ = tokio::process::Command::new("sh")
+ .arg("-c")
+ .arg(command)
+ .output()
+ .await;
+ }
+
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)
+ tokio::task::spawn(async move {
+ // killport doesn't seems working
+ #[cfg(unix)]
{
- 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
- );
+ // soft kill
+ let command = format!(
+ "lsof -i :{} | grep -E 'bun|node' | awk 'NR>1 {{print $2}}' | xargs -I {{}} kill -TERM {{}}",
+ port
+ );
+
+ let output = tokio::process::Command::new("sh")
+ .arg("-c")
+ .arg(command)
+ .output()
+ .await
+ .expect("failed to execute sh command");
+
+ if !output.status.success() {
+ // keep killport in fallback
+ use killport::cli::Mode;
+ use killport::killport::{Killport, KillportOperations};
+ use killport::signal::KillportSignal;
+
+ 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);
}
}
+
+ } else {
+ debug!(
+ "successfully killed listening on port {}",
+ port
+ );
}
- Err(e) => {
- warn!("error killing port {}: {}", port, e);
+ }
+ #[cfg(windows)]
+ {
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ let output = tokio::process::Command::new("netstat")
+ .args(&["-ano"])
+ .creation_flags(CREATE_NO_WINDOW)
+ .output()
+ .await
+ .expect("failed to execute netstat");
+
+ let output_str = std::str::from_utf8(&output.stdout)
+ .expect("failed to convert output to string");
+
+ for line in output_str.lines() {
+ // parts
+ let parts: Vec<&str> = line.split_whitespace().collect();
+ if parts.len() >= 5 {
+ // only kill local address
+ let local_address = parts[1];
+ if local_address.ends_with(&format!(":{}", port)) {
+ // extract pid
+ if let Ok(pid) = parts[4].parse::<u32>() {
+ let kill_result = tokio::process::Command::new("taskkill.exe")
+ .args(&["/F", "/T", "/PID", &pid.to_string()])
+ .creation_flags(CREATE_NO_WINDOW)
+ .output()
+ .await
+ .expect("failed to execute taskkill");
+ if kill_result.status.success() {
+ info!("successfully stopped pipe running on port: {}", port);
+ }
+ }
+ }
+ }
}
}
})
@@ -350,17 +462,15 @@ impl PipeManager {
}
#[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);
- }
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ let kill_result = tokio::process::Command::new("taskkill")
+ .args(&["/F", "/T", "/PID", &pid.to_string()])
+ .creation_flags(CREATE_NO_WINDOW)
+ .output()
+ .await
+ .expect("failed to execute taskkill");
+ if kill_result.status.success() {
+ info!("successfully stopped pipe pid: {}", pid.to_string());
}
}
}
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 8dc748e91..a1b48a0f7 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -2043,6 +2043,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/pipes/update", post(update_pipe_config_handler))
.route("/pipes/update-version", post(update_pipe_version_handler))
.route("/pipes/delete", post(delete_pipe_handler))
+ .route("/pipes/purge", post(purge_pipe_handler))
.route("/health", get(health_check))
.route("/ws/health", get(ws_health_handler))
.route("/raw_sql", post(execute_raw_sql))
@@ -2407,6 +2408,31 @@ pub async fn delete_pipe_handler(
}
}
+pub async fn purge_pipe_handler(
+ State(state): State<Arc<AppState>>,
+ Json(_request): Json<PurgePipeRequest>,
+) -> impl IntoResponse {
+ match state.pipe_manager.purge_pipes().await {
+ Ok(_) => (
+ StatusCode::OK,
+ Json(json!({
+ "success": true,
+ "message": "pipes purged successfully"
+ })),
+ ),
+ Err(e) => {
+ error!("failed to purge pipes: {}", e);
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({
+ "success": false,
+ "error": format!("failed to purge pipes: {}", e)
+ })),
+ )
+ }
+ }
+}
+
// Add this struct for the request payload
#[derive(Debug, Deserialize)]
pub struct DeletePipeRequest {
@@ -2426,6 +2452,10 @@ pub struct RestartAudioDevicesResponse {
restarted_devices: Vec<String>,
}
+#[derive(Debug, Deserialize)]
+pub struct PurgePipeRequest {
+}
+
// async fn restart_audio_devices(
// State(state): State<Arc<AppState>>,
// ) -> Result<JsonResponse<RestartAudioDevicesResponse>, (StatusCode, JsonResponse<Value>)> {