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: stream logs & possibility to give conf to pipes
Louis Beaumont4ff7d7d4b81a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9df30c7bb..32d5f5fd0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -97,6 +97,43 @@ You can add env var to `.vscode/settings.json`:}```+This is @louis030195 whole `.vscode/settings.json` file:++```json+{+ "rust-analyzer.server.extraEnv": {+ "PKG_CONFIG_ALLOW_SYSTEM_LIBS": "1",+ "PKG_CONFIG_ALLOW_SYSTEM_CFLAGS": "1",+ "PKG_CONFIG_PATH": "/opt/homebrew/lib/pkgconfig:/opt/homebrew/share/pkgconfig",+ "PATH": "/usr/bin:/opt/homebrew/bin:${env:PATH}",+ "DYLD_LIBRARY_PATH": "${workspaceFolder}/screenpipe-vision/lib:${env:DYLD_LIBRARY_PATH}"+ },+ "rust-analyzer.cargo.extraEnv": {+ "PKG_CONFIG_ALLOW_SYSTEM_LIBS": "1",+ "PKG_CONFIG_ALLOW_SYSTEM_CFLAGS": "1",+ "PKG_CONFIG_PATH": "/opt/homebrew/lib/pkgconfig:/opt/homebrew/share/pkgconfig",+ "PATH": "/usr/bin:/opt/homebrew/bin:${env:PATH}",+ "DYLD_LIBRARY_PATH": "${workspaceFolder}/screenpipe-vision/lib:${env:DYLD_LIBRARY_PATH}"+ },+ // add env to integrated terminal+ "terminal.integrated.env.osx": {+ "DYLD_LIBRARY_PATH": "${workspaceFolder}/screenpipe-vision/lib:${env:DYLD_LIBRARY_PATH}",+ "SCREENPIPE_APP_DEV": "true",+ },+ "rust-analyzer.cargo.features": [+ "pipes"+ ],+ "rust-analyzer.cargo.runBuildScripts": true,+ "rust-analyzer.checkOnSave.command": "clippy",+ "rust-analyzer.checkOnSave.extraArgs": [+ "--features",+ "pipes"+ ],+ "rust-analyzer.cargo.allFeatures": false,+ "rust-analyzer.cargo.noDefaultFeatures": false+}+```+## Other hacksdiff --git a/examples/apps/screenpipe-app-tauri/components/pipe-logger.tsx b/examples/apps/screenpipe-app-tauri/components/pipe-logger.tsxnew file mode 100644index 000000000..eaf71a4ab--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/components/pipe-logger.tsx@@ -0,0 +1,68 @@+import React, { useState, useEffect, useRef } from "react";+import { listen } from "@tauri-apps/api/event";+import { CodeBlock } from "@/components/ui/codeblock";+import { Button } from "@/components/ui/button";+import { ChevronDown, ChevronUp } from "lucide-react";++interface LogEntry {+ pipe_id: string;+ level: string;+ message: string;+ timestamp: string;+}++interface PipeLoggerProps {+ pipeId: string;+}++const PipeLogger: React.FC<PipeLoggerProps> = ({ pipeId }) => {+ const [logs, setLogs] = useState<string[]>([]);+ const [isExpanded, setIsExpanded] = useState(false);+ const logEndRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const unlisten = listen<LogEntry>("log-message", (event) => {+ if (event.payload.pipe_id === pipeId) {+ setLogs((prevLogs) => [+ ...prevLogs,+ `[${event.payload.level}] ${event.payload.message}`,+ ]);+ }+ });++ return () => {+ unlisten.then((f) => f());+ };+ }, [pipeId]);++ useEffect(() => {+ if (isExpanded) {+ logEndRef.current?.scrollIntoView({ behavior: "smooth" });+ }+ }, [logs, isExpanded]);++ const toggleExpand = () => {+ setIsExpanded(!isExpanded);+ };++ return (+ <div className="mt-4 border rounded-md">+ <Button+ onClick={toggleExpand}+ variant="ghost"+ className="w-full flex justify-between items-center p-2"+ >+ <span>Pipe Logs</span>+ {isExpanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}+ </Button>+ {isExpanded && (+ <div className="p-2">+ <CodeBlock language="log" value={logs.join("\n")} />+ <div ref={logEndRef} />+ </div>+ )}+ </div>+ );+};++export default PipeLogger;diff --git a/examples/apps/screenpipe-app-tauri/components/pipe-store.tsx b/examples/apps/screenpipe-app-tauri/components/pipe-store.tsxindex 0834de7c3..01a783db9 100644--- a/examples/apps/screenpipe-app-tauri/components/pipe-store.tsx+++ b/examples/apps/screenpipe-app-tauri/components/pipe-store.tsx@@ -26,6 +26,7 @@ import { toast } from "./ui/use-toast";import { Input } from "./ui/input";import { Plus } from "lucide-react";import { FeatureRequestLink } from "./feature-request-link";+import PipeLogger from "./pipe-logger";const formatDate = (dateString: string) => {const date = new Date(dateString);return date.toLocaleDateString("en-US", {@@ -288,6 +289,7 @@ const PipeDialog: React.FC = () => {{selectedPipe.fullDescription.replace(/Â/g, "")}</MemoizedReactMarkdown></div>+ <PipeLogger pipeId={selectedPipe.name} /></>);};diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/commands.rsindex f367b03f9..766c03114 100644--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -13,6 +13,7 @@ pub fn open_screen_capture_preferences() {.expect("failed to open system preferences");}+#[allow(unused_imports)]#[tauri::command]pub fn open_mic_preferences() {#[cfg(target_os = "macos")]@@ -22,6 +23,7 @@ pub fn open_mic_preferences() {.expect("failed to open system preferences");}+#[allow(unused_imports)]#[tauri::command]pub fn reset_screen_permissions() {#[cfg(target_os = "macos")]diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex ef8fc6a48..2873fac5b 100755--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -16,7 +16,6 @@ use tauri::{menu::{MenuBuilder, MenuItemBuilder},tray::{MouseButton, MouseButtonState},};-use tauri_plugin_notification::NotificationExt;use tauri_plugin_autostart::MacosLauncher;use tauri_plugin_autostart::ManagerExt;#[allow(unused_imports)]diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/server.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/server.rsindex df198ac2b..26d5880ed 100644--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/server.rs+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/server.rs@@ -2,10 +2,19 @@ use axum::{extract::State, http::StatusCode, routing::post, Json, Router};use serde::{Deserialize, Serialize};use std::net::SocketAddr;use tauri::Emitter;+#[allow(unused_imports)]use tauri_plugin_notification::NotificationExt;use tokio::sync::mpsc;use tracing::{error, info};+#[derive(Clone, serde::Serialize, serde::Deserialize)]+struct LogEntry {+ pipe_id: String,+ level: String,+ message: String,+ timestamp: String,+}+#[derive(Clone)]pub struct ServerState {app_handle: tauri::AppHandle,@@ -28,6 +37,7 @@ pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {let app = Router::new().route("/notify", post(send_notification))+ .route("/log", post(log_message)).with_state(state);let addr = SocketAddr::from(([127, 0, 0, 1], port));@@ -61,6 +71,29 @@ async fn send_notification(}}+async fn log_message(+ State(state): State<ServerState>,+ Json(log_entry): Json<LogEntry>,+) -> Result<Json<ApiResponse>, (StatusCode, String)> {+ match state.app_handle.emit("log-message", &log_entry) {+ Ok(e) => {+ info!("Log message sent: {:?}", e);+ Ok(Json(ApiResponse {+ success: true,+ message: "Log message sent successfully".to_string(),+ }))+ }+ Err(e) => {+ error!("Failed to send log message: {}", e);+ Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("Failed to send log message: {}", e),+ ))+ }+ }+}++pub fn spawn_server(app_handle: tauri::AppHandle, port: u16) -> mpsc::Sender<()> {let (tx, mut rx) = mpsc::channel(1);diff --git a/examples/typescript/pipe-stream-ocr-text/main.js b/examples/typescript/pipe-stream-ocr-text/main.jsindex f9c8e43be..4b1c6a7c4 100644--- a/examples/typescript/pipe-stream-ocr-text/main.js+++ b/examples/typescript/pipe-stream-ocr-text/main.js@@ -42,6 +42,8 @@ async function runOCRTracker() {// Self-invoking async function to run the OCR tracker(async () => {try {+ console.log(pipe);+await runOCRTracker();} catch (error) {console.error("Fatal error in OCR Tracker:", error);diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.tomlindex c66635be5..0d1fcca87 100644--- a/screenpipe-core/Cargo.toml+++ b/screenpipe-core/Cargo.toml@@ -23,12 +23,17 @@ hf-hub = { workspace = true, features = ["tokio"] }reqwest = { workspace = true }tokio = { workspace = true }-deno_core = { version = "0.283.0", optional = true }+deno_core = { version = "0.307.0", optional = true }deno_ast = { version = "0.38.2", features = ["transpiling"], optional = true }-+futures = "0.3.17"# Securityregex = { version = "1.10.6", features = ["std"], optional = true }lazy_static = { version = "1.4.0", optional = true }+tempfile = "3.3.0"+url = "2.4.0"++tracing = { workspace = true }+tracing-subscriber = { workspace = true }[features]pipes = ["dep:deno_core", "dep:deno_ast"]@@ -37,4 +42,4 @@ security = ["dep:regex", "dep:lazy_static"][build-dependencies]# Move this under the same feature flag-deno_core = { version = "0.283.0", optional = true }+deno_core = { version = "0.307.0", optional = true }diff --git a/screenpipe-core/src/deno/runtime.js b/screenpipe-core/src/deno/runtime.jsindex 2b24a2a1e..b37e8c96f 100644--- a/screenpipe-core/src/deno/runtime.js+++ b/screenpipe-core/src/deno/runtime.js@@ -5,15 +5,42 @@ function argsToMessage(...args) {return args.map((arg) => JSON.stringify(arg)).join(" ");}+const sendLog = async (level, ...args) => {+ const message = argsToMessage(...args);+ const logApiUrl = process.env.SCREENPIPE_LOG_API_URL || "http://localhost:11435/log";+ const pipeId = globalThis.metadata.id || "unknown";++ try {+ await ops.op_fetch(logApiUrl, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ pipeId,+ level,+ message,+ timestamp: new Date().toISOString(),+ }),+ });+ } catch (error) {+ // core.print(`[js][error]: Failed to send log: ${error}\n`, true);+ }+};+const console = {log: (...args) => {core.print(`[js][info]: ${argsToMessage(...args)}\n`, false);+ sendLog("info", ...args);},error: (...args) => {core.print(`[js][error]: ${argsToMessage(...args)}\n`, true);+ sendLog("error", ...args);},};+globalThis.console = console;+const pipe = {readFile: (path) => {return ops.op_read_file(path);@@ -57,7 +84,20 @@ const pipe = {}},sendNotification: async ({ title, body }) => {- const response = await ops.op_fetch("http://localhost:11435/notify", {+ // try to fetch this url, if not live do try to send the notification to the server+ const notificationApiUrl = process.env.SCREENPIPE_SERVER_URL || "http://localhost:11435";++ try {+ const response = await ops.op_fetch(notificationApiUrl)+ if (!response.ok) {+ throw new Error("Failed to send notification");+ }+ } catch (error) {+ console.warn("Failed to send notification to server, is your notification server running?");+ return+ }++ const response = await ops.op_fetch(notificationApiUrl + "/notify", {headers: {"Content-Type": "application/json",},@@ -67,13 +107,28 @@ const pipe = {console.log("Notification sent:", response);return JSON.parse(response);},+ loadConfig: async () => {+ try {+ console.log("Attempting to load pipe.json");+ const configContent = await ops.op_read_file("pipe.json");+ console.log("pipe.json content:", configContent);+ const parsedConfig = JSON.parse(configContent);+ console.log("Parsed config:", parsedConfig);+ pipe.config = parsedConfig; // Set the config property+ return parsedConfig;+ } catch (error) {+ console.error("Error loading pipe.json:", error);+ pipe.config = {}; // Set an empty object if loading fails+ return {};+ }+ },};globalThis.setTimeout = (callback, delay) => {ops.op_set_timeout(delay).then(callback);};-globalThis.console = console;globalThis.pipe = pipe;+globalThis.pipe.metadata = globalThis.metadata;globalThis.fetch = pipe.fetch;-+globalThis.loadConfig = pipe.loadConfig;diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 81181fda6..30c6d13fd 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -1,3 +1,4 @@+#[allow(clippy::module_inception)]#[cfg(feature = "pipes")]mod pipes {use deno_ast::MediaType;@@ -8,17 +9,22 @@ mod pipes {use deno_core::op2;use deno_core::ModuleLoadResponse;use deno_core::ModuleSourceCode;- use log::error;use reqwest::header::HeaderMap;use reqwest::header::HeaderValue;use reqwest::header::CONTENT_TYPE;use std::collections::HashMap;use std::env;+ use std::path::PathBuf;use std::rc::Rc;use reqwest::Client;use serde_json::Value;+ use reqwest;+ use std::path::Path;+ use tracing::{error, info};+ use url::Url;+#[op2]#[string]fn op_get_env(#[string] key: String) -> Option<String> {@@ -86,8 +92,10 @@ mod pipes {#[op2(async)]#[string]async fn op_read_file(#[string] path: String) -> anyhow::Result<String> {- tokio::fs::read_to_string(&path).await.map_err(|e| {- error!("Failed to read file '{}': {}", path, e);+ let current_dir = std::env::current_dir()?;+ let full_path = current_dir.join(path);+ tokio::fs::read_to_string(&full_path).await.map_err(|e| {+ error!("Failed to read file '{}': {}", full_path.display(), e);AnyError::from(e)})}@@ -250,7 +258,7 @@ mod pipes {]}- pub async fn run_js(file_path: &str) -> anyhow::Result<()> {+ pub async fn run_js(pipe: &str, file_path: &str) -> anyhow::Result<()> {let main_module = deno_core::resolve_path(file_path, env::current_dir()?.as_path())?;let mut js_runtime = deno_core::JsRuntime::new(deno_core::RuntimeOptions {module_loader: Some(Rc::new(TsModuleLoader)),@@ -259,6 +267,11 @@ mod pipes {..Default::default()});+ // Set some metadata on the runtime+ js_runtime.execute_script("main", "globalThis.metadata = { }")?;+ // Set the pipe id+ js_runtime.execute_script("main", format!("globalThis.metadata.id = '{}'", pipe))?;+// Initialize process.envjs_runtime.execute_script("main", "globalThis.process = { env: {} }")?;@@ -293,6 +306,177 @@ mod pipes {}}}++ #[allow(clippy::manual_async_fn)]+ pub async fn run_pipe(pipe: String, screenpipe_dir: PathBuf) -> anyhow::Result<()> {+ let pipe_dir = match Url::parse(&pipe) {+ Ok(_) => {+ info!("Input appears to be a URL. Attempting to download...");+ match download_pipe(&pipe, screenpipe_dir).await {+ Ok(path) => path,+ Err(e) => {+ error!("Failed to download pipe: {}", e);+ anyhow::bail!("Failed to download pipe: {}", e);+ }+ }+ }+ Err(_) => {+ info!("Input appears to be a local path. Attempting to canonicalize...");+ match Path::new(&pipe).canonicalize() {+ Ok(path) => path,+ Err(e) => {+ error!("Failed to canonicalize path: {}", e);+ anyhow::bail!("Failed to canonicalize path: {}", e);+ }+ }+ }+ };++ info!("Pipe directory: {:?}", pipe_dir);++ let main_module = find_pipe_file(&pipe_dir)?;++ match run_js(&pipe, &main_module.to_string_lossy()).await {+ Ok(_) => info!("JS execution completed successfully"),+ Err(error) => {+ error!("Error during JS execution: {}", error);+ anyhow::bail!("Error during JS execution: {}", error);+ }+ }++ Ok(())+ }++ pub async fn download_pipe(url: &str, screenpipe_dir: PathBuf) -> anyhow::Result<PathBuf> {+ info!("Downloading pipe from URL: {}", url);++ let client = Client::new();+ let parsed_url = Url::parse(url)?;++ match parsed_url.host_str() {+ Some("github.com") => {+ let api_url = get_raw_github_url(url)?;+ download_github_folder(&client, &api_url, screenpipe_dir).await+ }+ Some("raw.githubusercontent.com") => {+ download_single_file(&client, url, screenpipe_dir).await+ }+ _ => anyhow::bail!("Unsupported URL format"),+ }+ }++ async fn download_github_folder(+ client: &Client,+ api_url: &str,+ screenpipe_dir: PathBuf,+ ) -> anyhow::Result<PathBuf> {+ let response = client+ .get(api_url)+ .header("Accept", "application/vnd.github.v3+json")+ .header("User-Agent", "screenpipe")+ .send()+ .await?;++ let contents: Value = response.json().await?;++ if !contents.is_array() {+ anyhow::bail!("Invalid response from GitHub API");+ }++ let pipe_name = Path::new(api_url)+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or("unknown_pipe")+ .to_string();++ let pipe_dir = screenpipe_dir.join("pipes").join(&pipe_name);+ tokio::fs::create_dir_all(&pipe_dir).await?;++ for item in contents.as_array().unwrap() {+ let file_name = item["name"].as_str().unwrap();+ if file_name.ends_with(".ts") || file_name.ends_with(".js") {+ if file_name.starts_with("main") || file_name.starts_with("pipe") {+ let download_url = item["download_url"].as_str().unwrap();+ let file_content = client.get(download_url).send().await?.bytes().await?;+ let file_path = pipe_dir.join(file_name);+ tokio::fs::write(&file_path, &file_content).await?;+ info!("Downloaded: {:?}", file_path);+ }+ }+ }++ info!("Pipe downloaded successfully to: {:?}", pipe_dir);+ Ok(pipe_dir)+ }++ async fn download_single_file(+ client: &Client,+ url: &str,+ screenpipe_dir: PathBuf,+ ) -> anyhow::Result<PathBuf> {+ let response = client.get(url).send().await?;+ let content = response.bytes().await?;++ let file_name = Path::new(url)+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or("pipe.js")+ .to_string();++ let pipe_name = Path::new(url)+ .parent()+ .and_then(|p| p.file_name())+ .and_then(|name| name.to_str())+ .unwrap_or("unknown_pipe")+ .to_string();++ let pipe_dir = screenpipe_dir.join("pipes").join(pipe_name);+ tokio::fs::create_dir_all(&pipe_dir).await?;++ let file_path = pipe_dir.join(file_name);+ tokio::fs::write(&file_path, &content).await?;++ info!("Downloaded single file: {:?}", file_path);+ Ok(pipe_dir)+ }++ fn get_raw_github_url(url: &str) -> anyhow::Result<String> {+ info!("Attempting to get raw GitHub URL for: {}", url);+ let parsed_url = Url::parse(url)?;+ if parsed_url.host_str() == Some("github.com") {+ let path_segments: Vec<&str> = parsed_url.path_segments().unwrap().collect();+ if path_segments.len() >= 5 && path_segments[2] == "tree" {+ let (owner, repo, _, branch) = (+ path_segments[0],+ path_segments[1],+ path_segments[2],+ path_segments[3],+ );+ let raw_path = path_segments[4..].join("/");+ let raw_url = format!(+ "https://api.github.com/repos/{}/{}/contents/{}?ref={}",+ owner, repo, raw_path, branch+ );+ info!("Converted to GitHub API URL: {}", raw_url);+ return Ok(raw_url);+ }+ }+ anyhow::bail!("Invalid GitHub URL format")+ }++ fn find_pipe_file(pipe_dir: &Path) -> anyhow::Result<PathBuf> {+ for entry in std::fs::read_dir(pipe_dir)? {+ let entry = entry?;+ let file_name = entry.file_name();+ let file_name_str = file_name.to_str().unwrap();+ if (file_name_str.starts_with("pipe") || file_name_str.starts_with("main"))+ && (file_name_str.ends_with(".ts") || file_name_str.ends_with(".js"))+ {+ return Ok(entry.path());+ }+ }+ anyhow::bail!("No pipe.ts, pipe.js, main.ts, or main.js found in the pipe directory")+ }}#[cfg(feature = "pipes")]diff --git a/screenpipe-core/tests/pipes_test.rs b/screenpipe-core/tests/pipes_test.rsindex 0e73abd36..27a6c2904 100644--- a/screenpipe-core/tests/pipes_test.rs+++ b/screenpipe-core/tests/pipes_test.rs@@ -1,14 +1,31 @@#[cfg(feature = "pipes")]#[cfg(test)]mod tests {- use screenpipe_core::run_js;+ use screenpipe_core::{download_pipe, run_js, run_pipe};+ use serde_json::json;+ use std::{path::PathBuf, sync::Once};+ use tempfile::TempDir;use tokio::{- fs::{remove_file, File},+ fs::{create_dir_all, remove_file, File},io::AsyncWriteExt,};+ use tracing::subscriber::set_global_default;+ use tracing_subscriber::fmt::Subscriber;+ static INIT: Once = Once::new();++ fn init() {+ INIT.call_once(|| {+ let subscriber = Subscriber::builder()+ .with_env_filter("debug")+ .with_test_writer()+ .finish();+ set_global_default(subscriber).expect("Failed to set tracing subscriber");+ });+ }#[tokio::test]async fn test_js_execution() {+ init();let code = r#"function add(a, b) {return a + b;@@ -25,10 +42,212 @@ mod tests {file.write_all(code.as_bytes()).await.unwrap();file.flush().await.unwrap();// Test a simple JavaScript function- let result = run_js(file_path).await;+ let result = run_js("", file_path).await;assert!(result.is_ok());println!("result: {:?}", result);remove_file(file_path).await.unwrap();}++ async fn setup_test_pipe(temp_dir: &TempDir, pipe_name: &str, code: &str) -> PathBuf {+ init();+ let pipe_dir = temp_dir.path().join(pipe_name);+ create_dir_all(&pipe_dir).await.unwrap();+ let file_path = pipe_dir.join("pipe.ts");+ tokio::fs::write(&file_path, code).await.unwrap();+ pipe_dir+ }++ #[tokio::test]+ async fn test_simple_pipe() {+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let code = r#"+ console.log("Hello from simple pipe!");+ const result = 2 + 3;+ console.log(`Result: ${result}`);+ "#;++ let pipe_dir = setup_test_pipe(&temp_dir, "simple_pipe", code).await;++ let result = run_pipe(pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;+ assert!(result.is_ok());+ }++ #[tokio::test]+ async fn test_pipe_with_http_request() {+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let code = r#"+ console.log("Fetching data from API...");+ const response = await pipe.get("https://jsonplaceholder.typicode.com/todos/1");+ console.log(JSON.stringify(response, null, 2));+ "#;++ let pipe_dir = setup_test_pipe(&temp_dir, "http_pipe", code).await;++ let result = run_pipe(pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;+ assert!(result.is_ok());+ }++ #[tokio::test]+ #[ignore] // TODO: fix this test (not implemented yet)+ async fn test_pipe_with_error() {+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let code = r#"+ console.log("This pipe will throw an error");+ throw new Error("Intentional error");+ "#;++ let pipe_dir = setup_test_pipe(&temp_dir, "error_pipe", code).await;++ let result = run_pipe(pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;+ assert!(result.is_err());+ }++ #[tokio::test]+ #[ignore] // TODO: fix this test (file operations work but not in this test for some reason)+ async fn test_pipe_with_file_operations() {+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let code = r#"+ console.log("Writing to a file...");+ await pipe.writeFile("output.txt", "Hello, Screenpipe!");+ const content = await pipe.readFile("output.txt");+ console.log(`File content: ${content}`);+ "#;++ let pipe_dir = setup_test_pipe(&temp_dir, "file_pipe", code).await;++ let result = run_pipe(pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;+ assert!(result.is_ok());++ // Verify that the file was created and contains the expected content+ let output_file = pipe_dir.join("output.txt");+ assert!(output_file.exists());+ let content = tokio::fs::read_to_string(output_file).await.unwrap();+ assert_eq!(content, "Hello, Screenpipe!");+ }++ async fn setup_test_pipe_with_config(+ temp_dir: &TempDir,+ pipe_name: &str,+ code: &str,+ config: &str,+ ) -> PathBuf {+ init();+ let pipe_dir = temp_dir.path().join(pipe_name);+ create_dir_all(&pipe_dir).await.unwrap();++ let ts_file_path = pipe_dir.join("pipe.ts");+ tokio::fs::write(&ts_file_path, code).await.unwrap();++ let json_file_path = pipe_dir.join("pipe.json");+ tokio::fs::write(&json_file_path, config).await.unwrap();++ pipe_dir+ }++ #[tokio::test]+ async fn test_pipe_with_config() {+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let code = r#"+ (async () => {+ await pipe.loadConfig();+ console.log("Pipe config test");+ console.log(`API Key: ${pipe.config.apiKey}`);+ console.log(`Endpoint: ${pipe.config.endpoint}`);+ if (pipe.config.apiKey !== "test-api-key" || pipe.config.endpoint !== "https://api.example.com") {+ throw new Error("Config not loaded correctly");+ }+ })();+ "#;++ let config = json!({+ "apiKey": "test-api-key",+ "endpoint": "https://api.example.com"+ })+ .to_string();++ let pipe_dir = setup_test_pipe_with_config(&temp_dir, "config_pipe", code, &config).await;++ // Change the working directory to the pipe directory+ std::env::set_current_dir(&pipe_dir).unwrap();++ let result = run_pipe(pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;+ assert!(result.is_ok(), "Pipe execution failed: {:?}", result);+ }++ #[tokio::test]+ async fn test_download_pipe_github_folder() {+ init();+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let github_url = "https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-stream-ocr-text";+ let result = download_pipe(github_url, screenpipe_dir.clone()).await;++ assert!(+ result.is_ok(),+ "Failed to download GitHub folder: {:?}",+ result+ );+ let pipe_dir = result.unwrap();+ assert!(pipe_dir.exists(), "Pipe directory does not exist");++ let has_main_or_pipe_file = std::fs::read_dir(&pipe_dir).unwrap().any(|entry| {+ let file_name = entry.unwrap().file_name().into_string().unwrap();+ (file_name.starts_with("main") || file_name.starts_with("pipe"))+ && (file_name.ends_with(".ts") || file_name.ends_with(".js"))+ });++ assert!(+ has_main_or_pipe_file,+ "No main.ts, main.js, pipe.ts, or pipe.js file found"+ );+ }++ #[tokio::test]+ async fn test_download_pipe_raw_file() {+ init();+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let raw_url = "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/examples/typescript/pipe-stream-ocr-text/main.js";+ let result = download_pipe(raw_url, screenpipe_dir.clone()).await;++ assert!(result.is_ok(), "Failed to download raw file: {:?}", result);+ let pipe_dir = result.unwrap();+ assert!(pipe_dir.exists(), "Pipe directory does not exist");++ let has_main_or_pipe_file = std::fs::read_dir(&pipe_dir).unwrap().any(|entry| {+ let file_name = entry.unwrap().file_name().into_string().unwrap();+ (file_name.starts_with("main") || file_name.starts_with("pipe"))+ && (file_name.ends_with(".ts") || file_name.ends_with(".js"))+ });++ assert!(+ has_main_or_pipe_file,+ "No main.ts, main.js, pipe.ts, or pipe.js file found"+ );+ }++ #[tokio::test]+ async fn test_download_pipe_invalid_url() {+ init();+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();++ let invalid_url = "https://example.com/invalid/url";+ let result = download_pipe(invalid_url, screenpipe_dir.clone()).await;++ assert!(result.is_err(), "Expected an error for invalid URL");+ }}diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 0cb2b5e95..56505e89b 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -12,15 +12,13 @@ use std::{use colored::Colorize;use crossbeam::queue::SegQueue;use dirs::home_dir;+use futures::TryFutureExt;use log::{debug, error, info, LevelFilter};use screenpipe_audio::{default_input_device, default_output_device, list_audio_devices, parse_audio_device,AudioDevice, DeviceControl,};-use screenpipe_vision::{- monitor::{get_monitor_by_id, list_monitors},- OcrEngine,-};+use screenpipe_vision::monitor::{get_monitor_by_id, list_monitors};use std::io::Write;use clap::Parser;@@ -39,7 +37,7 @@ use tokio::{fn print_devices(devices: &[AudioDevice]) {println!("Available audio devices:");- for (_, device) in devices.iter().enumerate() {+ for device in devices.iter() {println!(" {}", device);}@@ -136,7 +134,7 @@ async fn main() -> anyhow::Result<()> {let all_monitors = list_monitors().await;if cli.list_monitors {println!("Available monitors:");- for (_, monitor) in all_monitors.iter().enumerate() {+ for monitor in all_monitors.iter() {println!(" {}. {:?}", monitor.id(), monitor);}return Ok(());@@ -206,7 +204,7 @@ async fn main() -> anyhow::Result<()> {// send signal after everything startedtokio::spawn(async move {tokio::time::sleep(Duration::from_secs(15)).await;- let _ = sender_clone.push((device_clone, device_control));+ sender_clone.push((device_clone, device_control));});}}@@ -302,7 +300,7 @@ async fn main() -> anyhow::Result<()> {}}let core_ocr_engine: CoreOcrEngine = cli.ocr_engine.clone().into();- let ocr_engine = Arc::new(OcrEngine::from(core_ocr_engine));+ let ocr_engine = Arc::new(core_ocr_engine);let core_audio_transcription_engine: CoreAudioTranscriptionEngine =cli.audio_transcription_engine.clone().into();let audio_transcription_engine = Arc::new(core_audio_transcription_engine);@@ -337,6 +335,7 @@ async fn main() -> anyhow::Result<()> {}});+ let local_data_dir_clone_2 = local_data_dir_clone.clone();tokio::spawn(async move {let api_plugin = |req: &axum::http::Request<axum::body::Body>| {// Custom plugin logic here@@ -351,6 +350,7 @@ async fn main() -> anyhow::Result<()> {SocketAddr::from(([0, 0, 0, 0], cli.port)),vision_control_server_clone,audio_devices_control_server,+ local_data_dir_clone_2,);server.start(devices_status, api_plugin).await.unwrap();});@@ -428,18 +428,15 @@ async fn main() -> anyhow::Result<()> {println!("│ {:<19} │ {:<34} │", "", "No devices available");} else {let total_devices = audio_devices.len();- for (i, device) in audio_devices+ for (_, device) in audio_devices.iter().enumerate().take(MAX_DEVICES_TO_DISPLAY){let device_str = device.deref().to_string();let formatted_device = format_cell(&device_str, VALUE_WIDTH);- if i == 0 {- println!("│ {:<19} │ {:<34} │", "", formatted_device);- } else {- println!("│ {:<19} │ {:<34} │", "", formatted_device);- }++ println!("│ {:<19} │ {:<34} │", "", formatted_device);}if total_devices > MAX_DEVICES_TO_DISPLAY {println!(@@ -472,18 +469,23 @@ async fn main() -> anyhow::Result<()> {#[cfg(feature = "pipes")]if !cli.pipe.is_empty() {use futures::stream::{FuturesUnordered, StreamExt};- use screenpipe_server::pipe_runner::run_pipe;+ use screenpipe_core::run_pipe;let mut pipe_futures = FuturesUnordered::new();- for pipe in &cli.pipe {- pipe_futures.push(run_pipe(pipe));+ for pipe in cli.pipe {+ // dont crash on error+ let f = run_pipe(pipe, local_data_dir_clone.clone()).map_err(|e| {+ error!("Error running pipe runner: {:?}", e);+ });++ pipe_futures.push(f);}tokio::select! {_ = async {while let Some(result) = pipe_futures.next().await {if let Err(e) = result {- error!("Error running pipe runner: {}", e);+ error!("Error running pipe runner: {:?}", e);}}} => {diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 0dbc10936..9b90101e5 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -4,8 +4,6 @@ pub mod core;mod db;pub mod filtering;pub mod logs;-#[cfg(feature = "pipes")]-pub mod pipe_runner;mod plugin;mod resource_monitor;mod server;diff --git a/screenpipe-server/src/pipe_runner.rs b/screenpipe-server/src/pipe_runner.rsdeleted file mode 100644index 26a1db1e2..000000000--- a/screenpipe-server/src/pipe_runner.rs+++ /dev/null@@ -1,143 +0,0 @@-use futures::Future;-use log::{error, info};-use reqwest;-#[cfg(feature = "pipes")]-use screenpipe_core::run_js;-use std::io::Write;-use std::path::Path;-use tempfile::NamedTempFile;-use url::Url;--#[cfg(feature = "pipes")]-pub fn run_pipe(pipe: &str) -> impl Future<Output = anyhow::Result<()>> + '_ {- async move {- let path_to_main_module = match Url::parse(pipe) {- Ok(_) => {- info!("Input appears to be a URL. Attempting to download...");- match download_pipe(pipe).await {- Ok(path) => path,- Err(e) => {- error!("Failed to download pipe: {}", e);- anyhow::bail!("Failed to download pipe: {}", e);- }- }- }- Err(_) => {- info!("Input appears to be a local path. Attempting to canonicalize...");- match Path::new(pipe).canonicalize() {- Ok(path) => path,- Err(e) => {- error!("Failed to canonicalize path: {}", e);- anyhow::bail!("Failed to canonicalize path: {}", e);- }- }- }- };-- info!("Path to main module: {:?}", path_to_main_module);-- match run_js(&path_to_main_module.to_string_lossy()).await {- Ok(_) => info!("JS execution completed successfully"),- Err(error) => {- error!("Error during JS execution: {}", error);- anyhow::bail!("Error during JS execution: {}", error);- }- }-- Ok(())- }-}--#[cfg(feature = "pipes")]-fn get_raw_github_url(url: &str) -> Result<String, Box<dyn std::error::Error>> {- info!("Attempting to get raw GitHub URL for: {}", url);- let parsed_url = Url::parse(url)?;- if parsed_url.host_str() == Some("github.com") {- let path_segments: Vec<&str> = parsed_url.path_segments().unwrap().collect();- if path_segments.len() >= 3 {- let (owner, repo, _, branch) = (- path_segments[0],- path_segments[1],- path_segments[2],- path_segments[3],- );- let raw_path = path_segments[4..].join("/");- let raw_url = format!(- "https://raw.githubusercontent.com/{}/{}/{}/{}",- owner, repo, branch, raw_path- );- info!("Converted to raw GitHub URL: {}", raw_url);- return Ok(raw_url);- }- }- info!("URL is not a GitHub URL, returning as-is");- Ok(url.to_string())-}--#[cfg(feature = "pipes")]-async fn download_pipe(url: &str) -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {- info!("Downloading pipe from URL: {}", url);-- let raw_url = get_raw_github_url(url)?;- let parsed_url = Url::parse(&raw_url)?;- if parsed_url.host_str() != Some("raw.githubusercontent.com") {- error!("Only public GitHub URLs or raw.githubusercontent.com URLs are supported");- return Err(- "Only public GitHub URLs or raw.githubusercontent.com URLs are supported".into(),- );- }-- info!("Downloading from raw URL: {}", raw_url);- std::io::stdout().flush()?;-- let response = match reqwest::get(&raw_url).await {- Ok(resp) => resp,- Err(e) => {- error!("Failed to send GET request: {}", e);- return Err(e.into());- }- };-- let content = match response.text().await {- Ok(text) => text,- Err(e) => {- error!("Failed to get response text: {}", e);- return Err(e.into());- }- };-- info!("Downloaded content length: {} bytes", content.len());-- let mut temp_file = match NamedTempFile::new() {- Ok(file) => file,- Err(e) => {- error!("Failed to create temporary file: {}", e);- return Err(e.into());- }- };-- if let Err(e) = temp_file.write_all(content.as_bytes()) {- error!("Failed to write content to temporary file: {}", e);- return Err(e.into());- }-- // Extract the file extension from the URL- let extension = Path::new(url)- .extension()- .and_then(|ext| ext.to_str())- .unwrap_or("js"); // Default to .js if no extension is found-- info!("File extension: {}", extension);-- // Create a new temporary file with the correct extension- let temp_path = temp_file.into_temp_path();- let final_path = temp_path.with_extension(extension);- if let Err(e) = std::fs::rename(&temp_path, &final_path) {- error!("Failed to rename temporary file: {}", e);- return Err(e.into());- }-- info!("Pipe downloaded successfully to: {:?}", final_path);-- Ok(final_path)-}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex a045b73e1..5bc36a543 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -19,6 +19,7 @@ use serde_json::json;use std::{collections::HashMap,net::SocketAddr,+ path::PathBuf,sync::{atomic::AtomicBool, Arc},time::Duration,};@@ -34,6 +35,14 @@ pub struct AppState {pub audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,pub devices_status: HashMap<AudioDevice, DeviceControl>,pub app_start_time: DateTime<Utc>,+ pub screenpipe_dir: PathBuf,+}++#[cfg(feature = "pipes")]+#[derive(Serialize)]+struct PipeInfo {+ name: String,+ path: String,}// Update the SearchQuery struct@@ -454,6 +463,37 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He})}+// Add this function to list installed pipes+async fn list_installed_pipes(screenpipe_dir: PathBuf) -> anyhow::Result<Vec<PipeInfo>> {+ let pipes_dir = screenpipe_dir.join("pipes");+ let mut pipes = Vec::new();++ let mut entries = tokio::fs::read_dir(&pipes_dir).await?;+ while let Some(entry) = entries.next_entry().await? {+ if entry.file_type().await?.is_dir() {+ let name = entry.file_name().to_string_lossy().into_owned();+ let path = entry.path().to_string_lossy().into_owned();+ pipes.push(PipeInfo { name, path });+ }+ }++ Ok(pipes)+}++// Add this handler function+async fn list_pipes(+ State(state): State<Arc<AppState>>,+) -> Result<JsonResponse<Vec<PipeInfo>>, (StatusCode, String)> {+ let screenpipe_dir = state.screenpipe_dir.clone();+ match list_installed_pipes(screenpipe_dir).await {+ Ok(pipes) => Ok(JsonResponse(pipes)),+ Err(e) => {+ error!("Failed to list installed pipes: {}", e);+ Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))+ }+ }+}+// Helper functionsfn into_content_item(result: SearchResult) -> ContentItem {match result {@@ -494,6 +534,7 @@ pub struct Server {addr: SocketAddr,vision_control: Arc<AtomicBool>,audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,+ screenpipe_dir: PathBuf,}impl Server {@@ -502,12 +543,14 @@ impl Server {addr: SocketAddr,vision_control: Arc<AtomicBool>,audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,+ screenpipe_dir: PathBuf,) -> Self {Server {db,addr,vision_control,audio_devices_control,+ screenpipe_dir,}}@@ -526,6 +569,7 @@ impl Server {audio_devices_control: self.audio_devices_control,devices_status: device_status,app_start_time: Utc::now(),+ screenpipe_dir: self.screenpipe_dir,});// https://github.com/tokio-rs/console@@ -539,7 +583,6 @@ impl Server {).with_state(app_state);-match serve(TcpListener::bind(self.addr).await?, app.into_make_service()).await {Ok(_) => {info!("Server stopped gracefully");@@ -562,6 +605,7 @@ pub fn create_router() -> Router<Arc<AppState>> {"/tags/:content_type/:id",post(add_tags).delete(remove_tags),)+ .route("/pipes/list", get(list_pipes)).route("/health", get(health_check))}