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: resource monitor not using CLI port, refactor: remove pipe runner bin shit and use hard thread instead, feat: impl dev dialog for quick settings change in dev mode of app
Louis Beaumont79e58ba50ffb
diff --git a/examples/apps/screenpipe-app-tauri/app/page.tsx b/examples/apps/screenpipe-app-tauri/app/page.tsxindex 2f482f303..13e9ee097 100644--- a/examples/apps/screenpipe-app-tauri/app/page.tsx+++ b/examples/apps/screenpipe-app-tauri/app/page.tsx@@ -21,6 +21,7 @@ import UpdateNotification from "@/components/update-notification";import { usePostHog } from "posthog-js/react";import Link from "next/link";import { useToast } from "@/components/ui/use-toast";+import { DevSettings } from "@/components/dev-dialog";export default function Home() {const { settings } = useSettings();@@ -39,6 +40,7 @@ export default function Home() {return (<main className="flex min-h-screen flex-col items-center p-8">+ {/* <DevSettings /> */}<NotificationHandler />{/* <UpdateNotification checkIntervalHours={3} /> */}{/* <ScreenpipeInstanceChecker /> */}diff --git a/examples/apps/screenpipe-app-tauri/components/dev-dialog.tsx b/examples/apps/screenpipe-app-tauri/components/dev-dialog.tsxnew file mode 100644index 000000000..19598ca74--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/components/dev-dialog.tsx@@ -0,0 +1,130 @@+import React, { useEffect, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { useSettings } from "@/lib/hooks/use-settings";+import { useToast } from "@/components/ui/use-toast";++export function DevSettings() {+ const { settings, updateSettings } = useSettings();+ const [localSettings, setLocalSettings] = React.useState(settings);+ const [isSaving, setIsSaving] = useState(false);+ const { toast } = useToast();++ useEffect(() => {+ setLocalSettings(settings);+ }, [settings]);++ const handleChange = (key: keyof typeof settings, value: any) => {+ setLocalSettings((prev) => ({ ...prev, [key]: value }));+ };++ const handleSave = async () => {+ setIsSaving(true);+ toast({+ title: "updating dev settings",+ description: "this may take a few moments...",+ });++ try {+ await updateSettings(localSettings);+ await new Promise((resolve) => setTimeout(resolve, 1000));++ toast({+ title: "dev settings updated successfully",+ description: "your changes have been saved.",+ });+ } catch (error) {+ console.error("failed to update dev settings:", error);+ toast({+ title: "error updating dev settings",+ description: "please try again or check the logs for more information.",+ variant: "destructive",+ });+ } finally {+ setIsSaving(false);+ }+ };++ return (+ <Dialog>+ <DialogTrigger asChild>+ <Button variant="outline">dev settings</Button>+ </DialogTrigger>+ <DialogContent className="max-w-[80vw] w-full max-h-[80vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>dev settings</DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ {Object.entries(localSettings).map(([key, value]) => (+ <div key={key} className="flex flex-col space-y-2">+ <Label htmlFor={key}>{key}</Label>+ {typeof value === "boolean" ? (+ <Switch+ id={key}+ checked={value}+ onCheckedChange={(checked) =>+ handleChange(key as any, checked)+ }+ />+ ) : typeof value === "string" ? (+ key === "customPrompt" ? (+ <Textarea+ id={key}+ value={value}+ onChange={(e) => handleChange(key as any, e.target.value)}+ rows={4}+ />+ ) : (+ <Input+ id={key}+ value={value}+ onChange={(e) => handleChange(key as any, e.target.value)}+ />+ )+ ) : typeof value === "number" ? (+ <Input+ id={key}+ type="number"+ value={value}+ onChange={(e) =>+ handleChange(key as any, Number(e.target.value))+ }+ />+ ) : Array.isArray(value) ? (+ <Textarea+ id={key}+ value={JSON.stringify(value)}+ onChange={(e) =>+ handleChange(key as any, JSON.parse(e.target.value))+ }+ rows={4}+ />+ ) : (+ <Input+ id={key}+ value={JSON.stringify(value)}+ onChange={(e) =>+ handleChange(key as any, JSON.parse(e.target.value))+ }+ />+ )}+ </div>+ ))}+ </div>+ <Button onClick={handleSave} className="mt-4" disabled={isSaving}>+ {isSaving ? "saving..." : "save changes"}+ </Button>+ </DialogContent>+ </Dialog>+ );+}diff --git a/examples/apps/screenpipe-app-tauri/components/pipe-store.tsx b/examples/apps/screenpipe-app-tauri/components/pipe-store.tsxindex 1bb7ebb8e..b3c505293 100644--- a/examples/apps/screenpipe-app-tauri/components/pipe-store.tsx+++ b/examples/apps/screenpipe-app-tauri/components/pipe-store.tsx@@ -90,7 +90,7 @@ const PipeDialog: React.FC = () => {});// Update installed pipes in settings- const updatedInstalledPipes = [...settings.installedPipes, pipe.mainFile!];+ const updatedInstalledPipes = [...settings.installedPipes, pipe];await updateSettings({ installedPipes: updatedInstalledPipes });// Kill existing screenpipe processes@@ -124,7 +124,7 @@ const PipeDialog: React.FC = () => {// Update installed pipes in settingsconst updatedInstalledPipes = settings.installedPipes.filter(- (p) => p !== pipe.name+ (p) => p.name !== pipe.name);await updateSettings({ installedPipes: updatedInstalledPipes });@@ -158,14 +158,9 @@ const PipeDialog: React.FC = () => {);}- if (- selectedPipe.name === "Local First Meeting Summarizer" &&- settings.installedPipes.includes(selectedPipe.name)- ) {- return <MeetingSummarizer pipe={selectedPipe} />;- }-- const isInstalled = settings.installedPipes.includes(selectedPipe.name);+ const isInstalled =+ settings.installedPipes.find((p) => p.name === selectedPipe.name) !==+ undefined;return (<>@@ -268,6 +263,7 @@ const PipeDialog: React.FC = () => {},img({ src, alt }) {return (+ /* eslint-disable @next/next/no-img-element */<imgsrc={src}alt={alt}diff --git a/examples/apps/screenpipe-app-tauri/lib/hooks/use-pipes.tsx b/examples/apps/screenpipe-app-tauri/lib/hooks/use-pipes.tsxindex 7afde212e..6ff19a44e 100644--- a/examples/apps/screenpipe-app-tauri/lib/hooks/use-pipes.tsx+++ b/examples/apps/screenpipe-app-tauri/lib/hooks/use-pipes.tsx@@ -13,21 +13,41 @@ export type Pipe = {mainFile?: string;};-const cache: { [key: string]: { data: any; timestamp: number } } = {};const CACHE_DURATION = 60 * 60 * 1000; // 1 hour in millisecondsconst fetchWithCache = async (url: string) => {- if (cache[url] && Date.now() - cache[url].timestamp < CACHE_DURATION) {- return cache[url].data;+ const cacheKey = `cache_${url}`;+ const cachedData = localStorage.getItem(cacheKey);++ if (cachedData) {+ const { data, timestamp } = JSON.parse(cachedData);+ if (Date.now() - timestamp < CACHE_DURATION) {+ return data;+ }}- const response = await fetch(url);- if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);+ try {+ const response = await fetch(url);+ if (response.status === 403) {+ throw new Error("Rate limit exceeded");+ }+ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }+ const data = await response.json();+ localStorage.setItem(+ cacheKey,+ JSON.stringify({ data, timestamp: Date.now() })+ );+ return data;+ } catch (error) {+ console.error(`Error fetching ${url}:`, error);+ if (cachedData) {+ console.log("Returning stale cached data");+ return JSON.parse(cachedData).data;+ }+ throw error;}- const data = await response.json();- cache[url] = { data, timestamp: Date.now() };- return data;};const convertHtmlToMarkdown = (html: string) => {@@ -156,7 +176,7 @@ export const usePipes = (repoUrls: string[]) => {jsFiles[0];const mainFileUrl = mainFile- ? `https://github.com/${repoFullName}/blob/${branch}/${subDir}/${mainFile.name}`+ ? `https://raw.githubusercontent.com/${repoFullName}/${branch}/${subDir}/${mainFile.name}`: undefined;return {diff --git a/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex 05eb5591b..75f232495 100644--- a/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -3,6 +3,7 @@ import { Store } from "@tauri-apps/plugin-store";import { localDataDir } from "@tauri-apps/api/path";import { join } from "@tauri-apps/api/path";import { platform } from "@tauri-apps/plugin-os";+import { Pipe } from "./use-pipes";const defaultSettings: Settings = {openaiApiKey: "",@@ -31,6 +32,8 @@ const defaultSettings: Settings = {audioDevices: ["default"],usePiiRemoval: false,restartInterval: 0,+ port: 3030,+ dataDir: "default",};export interface Settings {@@ -39,7 +42,7 @@ export interface Settings {ollamaUrl: string;isLoading: boolean;aiModel: string;- installedPipes: string[];+ installedPipes: Pipe[];userId: string;customPrompt: string;devMode: boolean;@@ -49,6 +52,8 @@ export interface Settings {audioDevices: string[];usePiiRemoval: boolean;restartInterval: number;+ port: number;+ dataDir: string;}let store: Store | null = null;@@ -96,7 +101,7 @@ export function useSettings() {const savedAiModel =((await store!.get("aiModel")) as string) || "gpt-4o";const savedInstalledPipes =- ((await store!.get("installedPipes")) as string[]) || [];+ ((await store!.get("installedPipes")) as Pipe[]) || [];const savedUserId = ((await store!.get("userId")) as string) || "";const savedCustomPrompt =((await store!.get("customPrompt")) as string) || "";@@ -117,7 +122,8 @@ export function useSettings() {((await store!.get("usePiiRemoval")) as boolean) || false;const savedRestartInterval =((await store!.get("restartInterval")) as number) || 0;-+ const savedPort = ((await store!.get("port")) as number) || 3030;+ const savedDataDir = ((await store!.get("dataDir")) as string) || "";setSettings({openaiApiKey: savedKey,useOllama: savedUseOllama,@@ -134,6 +140,8 @@ export function useSettings() {audioDevices: savedAudioDevices,usePiiRemoval: savedUsePiiRemoval,restartInterval: savedRestartInterval,+ port: savedPort,+ dataDir: savedDataDir,});} catch (error) {console.error("Failed to load settings:", error);diff --git a/examples/apps/screenpipe-app-tauri/scripts/pre_build.js b/examples/apps/screenpipe-app-tauri/scripts/pre_build.jsindex 5e366fecf..a66a34a43 100644--- a/examples/apps/screenpipe-app-tauri/scripts/pre_build.js+++ b/examples/apps/screenpipe-app-tauri/scripts/pre_build.js@@ -135,32 +135,7 @@ if (platform == 'linux') {// process.exit(1);}- // Copy screenpipe-pipe-runner binary- console.log('Copying screenpipe-pipe-runner binary for Linux...');- const pipeRunnerPotentialPaths = [- path.join(__dirname, '..', '..', '..', '..', 'target', 'release', 'screenpipe-pipe-runner'),- path.join(__dirname, '..', '..', '..', '..', 'target', 'x86_64-unknown-linux-gnu', 'release', 'screenpipe-pipe-runner'),- path.join(__dirname, '..', '..', '..', 'target', 'release', 'screenpipe-pipe-runner'),- path.join(__dirname, '..', '..', 'target', 'release', 'screenpipe-pipe-runner'),- '/home/runner/work/screenpipe/screenpipe/target/release/screenpipe-pipe-runner',- ];-- copied = false;- for (const pipeRunnerSrc of pipeRunnerPotentialPaths) {- const pipeRunnerDest = path.join(cwd, 'screenpipe-pipe-runner-x86_64-unknown-linux-gnu');- try {- await fs.copyFile(pipeRunnerSrc, pipeRunnerDest);- console.log(`Pipe runner binary copied successfully from ${pipeRunnerSrc}`);- copied = true;- break;- } catch (error) {- console.warn(`Failed to copy pipe runner binary from ${pipeRunnerSrc}:`, error);- }- }- if (!copied) {- console.error("Failed to copy pipe runner binary from any potential path.");- }}/* ########## Windows ########## */@@ -196,32 +171,6 @@ if (platform == 'windows') {// process.exit(1);}- // Copy screenpipe-pipe-runner binary- console.log('Copying screenpipe-pipe-runner binary...');- const pipeRunnerPotentialPaths = [- path.join(__dirname, '..', '..', '..', '..', 'target', 'release', 'screenpipe-pipe-runner.exe'),- path.join(__dirname, '..', '..', '..', '..', 'target', 'x86_64-pc-windows-msvc', 'release', 'screenpipe-pipe-runner.exe'),- path.join(__dirname, '..', '..', '..', 'target', 'release', 'screenpipe-pipe-runner.exe'),- path.join(__dirname, '..', '..', 'target', 'release', 'screenpipe-pipe-runner.exe'),- 'D:\\a\\screenpipe\\screenpipe\\target\\release\\screenpipe-pipe-runner.exe',- ];-- copied = false;- for (const pipeRunnerSrc of pipeRunnerPotentialPaths) {- const pipeRunnerDest = path.join(cwd, 'screenpipe-pipe-runner-x86_64-pc-windows-msvc.exe');- try {- await fs.copyFile(pipeRunnerSrc, pipeRunnerDest);- console.log(`Pipe runner binary copied successfully from ${pipeRunnerSrc}`);- copied = true;- break;- } catch (error) {- console.warn(`Failed to copy pipe runner binary from ${pipeRunnerSrc}:`, error);- }- }-- if (!copied) {- console.error("Failed to copy pipe runner binary from any potential path.");- }// Setup FFMPEGif (!(await fs.exists(config.ffmpegRealname))) {@@ -338,30 +287,6 @@ if (platform == 'macos') {console.log(`Updated dylib paths for arm64 in dev mode`);}- // Copy screenpipe-pipe-runner binary for arm64- const pipeRunnerPaths = [- "../../../../target/aarch64-apple-darwin/release/screenpipe-pipe-runner",- "../../../../target/release/screenpipe-pipe-runner"- ];-- const mostRecentPipeRunnerPath = await getMostRecentBinaryPath('arm64', pipeRunnerPaths);- if (mostRecentPipeRunnerPath) {- await $`cp ${mostRecentPipeRunnerPath} screenpipe-pipe-runner-aarch64-apple-darwin`;- console.log(`Copied most recent arm64 pipe runner binary from ${mostRecentPipeRunnerPath}`);- } else {- console.error("No suitable arm64 pipe runner binary found");- }- // if the binary exists, hard code the fucking dylib- if (await fs.exists('screenpipe-pipe-runner-aarch64-apple-darwin') && !isDevMode) {- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe_arm64.dylib @rpath/../Frameworks/libscreenpipe_arm64.dylib ./screenpipe-pipe-runner-aarch64-apple-darwin`- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe.dylib @rpath/../Frameworks/libscreenpipe.dylib ./screenpipe-pipe-runner-aarch64-apple-darwin`- console.log(`hard coded the FUCKING dylib for pipe runner`);- } else if (await fs.exists('screenpipe-pipe-runner-aarch64-apple-darwin') && isDevMode) {- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe_arm64.dylib @executable_path/target/Frameworks/libscreenpipe_arm64.dylib ./screenpipe-pipe-runner-aarch64-apple-darwin`- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe.dylib @executable_path/target/Frameworks/libscreenpipe.dylib ./screenpipe-pipe-runner-aarch64-apple-darwin`- await $`install_name_tool -add_rpath @executable_path/target/Frameworks ./screenpipe-pipe-runner-aarch64-apple-darwin`- console.log(`Updated dylib paths for arm64 pipe runner in dev mode`);- }} else if (arch === 'x86_64') {// copy screenpipe binary (more recent one)@@ -383,37 +308,8 @@ if (platform == 'macos') {await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe_x86_64.dylib @rpath/../Frameworks/libscreenpipe_x86_64.dylib ./screenpipe-x86_64-apple-darwin`await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe.dylib @rpath/../Frameworks/libscreenpipe.dylib ./screenpipe-x86_64-apple-darwin`console.log(`hard coded the FUCKING dylib`);- } else if (await fs.exists('screenpipe-x86_64-apple-darwin') && isDevMode) {- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe_x86_64.dylib @executable_path/../Frameworks/libscreenpipe_x86_64.dylib ./screenpipe-x86_64-apple-darwin`- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe.dylib @executable_path/../Frameworks/libscreenpipe.dylib ./screenpipe-x86_64-apple-darwin`- await $`install_name_tool -add_rpath @executable_path/../Frameworks ./screenpipe-x86_64-apple-darwin`- console.log(`Updated dylib paths for x86_64 in dev mode`);}- // Copy screenpipe-pipe-runner binary for x86_64- const pipeRunnerPaths = [- "../../../../target/x86_64-apple-darwin/release/screenpipe-pipe-runner",- "../../../../target/release/screenpipe-pipe-runner"- ];-- const mostRecentPipeRunnerPath = await getMostRecentBinaryPath('x86_64', pipeRunnerPaths);- if (mostRecentPipeRunnerPath) {- await $`cp ${mostRecentPipeRunnerPath} screenpipe-pipe-runner-x86_64-apple-darwin`;- console.log(`Copied most recent x86_64 pipe runner binary from ${mostRecentPipeRunnerPath}`);- } else {- console.error("No suitable x86_64 pipe runner binary found");- }- // hard code the fucking dylib for pipe runner- if (await fs.exists('screenpipe-pipe-runner-x86_64-apple-darwin') && !isDevMode) {- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe_x86_64.dylib @rpath/../Frameworks/libscreenpipe_x86_64.dylib ./screenpipe-pipe-runner-x86_64-apple-darwin`- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe.dylib @rpath/../Frameworks/libscreenpipe.dylib ./screenpipe-pipe-runner-x86_64-apple-darwin`- console.log(`hard coded the FUCKING dylib for pipe runner`);- } else if (await fs.exists('screenpipe-pipe-runner-x86_64-apple-darwin') && isDevMode) {- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe_x86_64.dylib @executable_path/../Frameworks/libscreenpipe_x86_64.dylib ./screenpipe-pipe-runner-x86_64-apple-darwin`- await $`install_name_tool -change screenpipe-vision/lib/libscreenpipe.dylib @executable_path/../Frameworks/libscreenpipe.dylib ./screenpipe-pipe-runner-x86_64-apple-darwin`- await $`install_name_tool -add_rpath @executable_path/../Frameworks ./screenpipe-pipe-runner-x86_64-apple-darwin`- console.log(`Updated dylib paths for x86_64 pipe runner in dev mode`);- }}console.log(`screenpipe for ${arch} set up successfully.`);diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 0cc815921..bc4ae05b1 100644--- a/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "0.1.68"+version = "0.1.69"description = ""authors = ["you"]license = ""diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex b33695570..31e144356 100755--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -26,10 +26,10 @@ use tauri_plugin_shell::process::CommandEvent;use tauri_plugin_shell::ShellExt;use tauri_plugin_store::{with_store, StoreCollection};use tokio::time::sleep;+use tracing::{debug, error, info};+use tracing_appender::rolling::{RollingFileAppender, Rotation};use tracing_subscriber::prelude::*;use tracing_subscriber::EnvFilter;-use tracing_appender::rolling::{RollingFileAppender, Rotation};-use tracing::{debug, error, info};use uuid::Uuid;mod analytics;@@ -184,16 +184,37 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {}).map_err(|e| e.to_string())?.unwrap_or_default();+ let port = with_store(app.clone(), stores.clone(), path.clone(), |store| {+ Ok(store+ .get("port")+ .and_then(|v| v.as_u64())+ .unwrap_or(3030))+ })+ .map_err(|e| e.to_string())?;++ let data_dir = with_store(app.clone(), stores.clone(), path.clone(), |store| {+ Ok(store+ .get("dataDir")+ .and_then(|v| v.as_str().map(String::from)))+ })+ .map_err(|e| e.to_string())?+ .unwrap_or(String::from("default"));- let _data_dir_str = base_dir.to_string_lossy();- let mut args = vec!["--port", "3030"];+ let port_str = port.to_string();+ let mut args = vec!["--port", port_str.as_str()];// if macos do --fps 0.2if cfg!(target_os = "macos") {args.push("--fps");args.push("0.2");}+ if data_dir != "default" {+ args.push("--data-dir");+ let dir = data_dir.as_str();+ args.push(dir);+ }+if audio_transcription_engine != "default" {args.push("--audio-transcription-engine");let model = audio_transcription_engine.as_str();@@ -229,13 +250,17 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {}if !pipes.is_empty() {+ let mut added_pipes = std::collections::HashSet::new();for pipe in &pipes {- args.push("--pipe");- args.push(pipe.as_str().unwrap());- debug!("adding pipe: {}", pipe.as_str().unwrap());+ if let Some(pipe_str) = pipe.as_str() {+ if added_pipes.insert(pipe_str) {+ args.push("--pipe");+ args.push(pipe_str);+ info!("adding pipe: {}", pipe_str);+ }+ }}}-// hardcode TESSDATA_PREFIX for windowsif cfg!(windows) {@@ -258,9 +283,9 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {}let command = sidecar.args(&args);-- let result = command.spawn();++ let result = command.spawn();if let Err(e) = result {error!("Failed to spawn sidecar: {}", e);return Err(e.to_string());diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.linux.conf.jsonindex b6ba34448..9669514ca 100644--- a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json+++ b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json@@ -1,8 +1,7 @@{"bundle": {"externalBin": [- "screenpipe",- "screenpipe-pipe-runner"+ "screenpipe"],"linux": {"deb": {diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.jsonindex a077277ef..f91a2e0b4 100644--- a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json+++ b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json@@ -23,8 +23,7 @@"ffmpeg/bin/*": "./"},"externalBin": [- "screenpipe",- "screenpipe-pipe-runner"+ "screenpipe"]}}\ No newline at end of filediff --git a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.windows.conf.jsonindex fdcce950e..e45ce79f8 100644--- a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json+++ b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json@@ -1,8 +1,7 @@{"bundle": {"externalBin": [- "screenpipe",- "screenpipe-pipe-runner"+ "screenpipe"],"resources": {"ffmpeg\\bin\\x64\\*": "./",diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 9d28895b3..62e099e58 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -17,7 +17,7 @@ mod pipes {#[op2(async)]#[string]- async fn op_read_file(#[string] path: String) -> Result<String, AnyError> {+ 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);AnyError::from(e)@@ -29,7 +29,7 @@ mod pipes {async fn op_write_file(#[string] path: String,#[string] contents: String,- ) -> Result<(), AnyError> {+ ) -> anyhow::Result<()> {tokio::fs::write(&path, contents).await.map_err(|e| {error!("Failed to write file '{}': {}", path, e);AnyError::from(e)@@ -38,7 +38,7 @@ mod pipes {#[op2(async)]#[string]- async fn op_fetch_get(#[string] url: String) -> Result<String, AnyError> {+ async fn op_fetch_get(#[string] url: String) -> anyhow::Result<String> {let response = reqwest::get(&url).await?;let status = response.status();let text = response.text().await?;@@ -59,7 +59,7 @@ mod pipes {async fn op_fetch_post(#[string] url: String,#[string] body: String,- ) -> Result<String, AnyError> {+ ) -> anyhow::Result<String> {let client = reqwest::Client::new();// Create a HeaderMap and add the Content-Type header@@ -83,13 +83,13 @@ mod pipes {}#[op2(async)]- async fn op_set_timeout(delay: f64) -> Result<(), AnyError> {+ async fn op_set_timeout(delay: f64) -> anyhow::Result<()> {tokio::time::sleep(std::time::Duration::from_millis(delay as u64)).await;Ok(())}#[op2(fast)]- fn op_remove_file(#[string] path: String) -> Result<(), AnyError> {+ fn op_remove_file(#[string] path: String) -> anyhow::Result<()> {std::fs::remove_file(path)?;Ok(())}@@ -180,7 +180,7 @@ mod pipes {]}- pub async fn run_js(file_path: &str) -> Result<(), AnyError> {+ pub async fn run_js(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)),diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex 140fe17c6..d9288409f 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -144,7 +144,3 @@ optional = truename = "screenpipe"path = "src/bin/screenpipe-server.rs"-[[bin]]-name = "screenpipe-pipe-runner"-path = "src/bin/screenpipe-pipe-runner.rs"-required-features = ["pipes"]diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex d51649ff4..d5fff3b9b 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -29,6 +29,7 @@ use screenpipe_core::find_ffmpeg_path;use screenpipe_server::{cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine},logs::MultiWriter,+ pipe_runner::run_pipe,start_continuous_recording, DatabaseManager, ResourceMonitor, Server,};use screenpipe_vision::utils::OcrEngine as CoreOcrEngine;@@ -69,75 +70,6 @@ fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {Ok(base_dir)}-#[cfg(feature = "pipes")]-async fn run_pipe_runner(pipes: Vec<String>) -> anyhow::Result<()> {- if pipes.len() == 0 {- ()- }-- use std::path::Path;-- use tokio::process::Command;-- // ! this is not very beautiful but it works-- let potential_paths = [- // General paths- "./screenpipe-pipe-runner",- "./target/release/screenpipe-pipe-runner",- "../target/release/screenpipe-pipe-runner",- "../../target/release/screenpipe-pipe-runner",- // Linux- "./screenpipe-pipe-runner-x86_64-unknown-linux-gnu",- // Windows- "./screenpipe-pipe-runner-x86_64-pc-windows-msvc.exe",- // macOS ARM64- "./screenpipe-pipe-runner-aarch64-apple-darwin",- // macOS x86_64- "./screenpipe-pipe-runner-x86_64-apple-darwin",- // Additional paths- "./src-tauri/screenpipe-pipe-runner",- "../src-tauri/screenpipe-pipe-runner",- "../../src-tauri/screenpipe-pipe-runner",- ];-- for path in &potential_paths {- // list stuff in parent of this path- let parent = Path::new(path).parent().unwrap();- // ls files there- let files = fs::read_dir(parent)- .ok()- .map(|entries| {- entries- .filter_map(|entry| {- entry- .ok()- .map(|e| e.file_name().to_string_lossy().into_owned())- })- .collect::<Vec<String>>()- })- .unwrap_or_default();- debug!("files: {:?}", files);- if Path::new(path).exists() {- let status = Command::new(path)- .arg("--pipe")- .args(pipes.iter().next())- .status()- .await?;-- if status.success() {- return Ok(());- } else {- eprintln!("pipe-runner process failed with status: {}", status);- // Continue to the next path if this one failed- }- }- }-- Err(anyhow::anyhow!(- "Failed to find or run screenpipe-pipe-runner"- ))-}#[tokio::main]async fn main() -> anyhow::Result<()> {let cli = Cli::parse();@@ -282,8 +214,13 @@ async fn main() -> anyhow::Result<()> {}let (restart_sender, mut restart_receiver) = channel(10);- let resource_monitor =- ResourceMonitor::new(cli.self_healing, Duration::from_secs(60), 3, restart_sender);+ let resource_monitor = ResourceMonitor::new(+ cli.self_healing,+ Duration::from_secs(60),+ 3,+ restart_sender,+ cli.port,+ );resource_monitor.start_monitoring(Duration::from_secs(10));let db = Arc::new(@@ -418,15 +355,6 @@ async fn main() -> anyhow::Result<()> {server.start(devices_status, api_plugin).await.unwrap();});- #[cfg(feature = "pipes")]- if !cli.pipe.is_empty() {- match run_pipe_runner(cli.pipe).await {- Ok(_) => info!("Pipe runner completed successfully"),- Err(e) => error!("Error running pipe runner: {}", e),- }- return Ok(());- }-// Wait for the server to startinfo!("Server started on http://localhost:{}", cli.port);@@ -540,6 +468,25 @@ async fn main() -> anyhow::Result<()> {);}+ #[cfg(feature = "pipes")]+ if !cli.pipe.is_empty() {+ let pipe_future = run_pipe(&cli.pipe[0]);+ tokio::pin!(pipe_future);++ tokio::select! {+ result = &mut pipe_future => {+ if let Err(e) = result {+ error!("Error running pipe runner: {}", e);+ }+ return Ok(());+ }+ _ = tokio::signal::ctrl_c() => {+ info!("Received Ctrl+C, shutting down...");+ return Ok(());+ }+ }+ }+// Keep the main thread runningloop {tokio::time::sleep(Duration::from_secs(1)).await;diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rsindex ff25b1b67..3359702f7 100644--- a/screenpipe-server/src/db.rs+++ b/screenpipe-server/src/db.rs@@ -214,61 +214,61 @@ impl DatabaseManager {// Commit the transaction for the full transcriptiontx.commit().await?;- // Now, let's chunk the transcription and insert into chunk tables- const CHUNKING_ENGINE: &str = "local_simple";-- let chunks = match CHUNKING_ENGINE {- "local_simple" => text_chunking_simple(transcription),- "candle_jina_bert" => text_chunking_by_similarity(transcription).await,- "unstructured" => unstructured_chunking(transcription)- .map_err(|e| anyhow::anyhow!(e))- .and_then(|chunks| Ok(chunks)),- _ => text_chunking_simple(transcription), // Default to simple chunking for unknown engines- };-- match chunks {- Ok(chunks) => {- info!(- "Successfully chunked audio transcription into {} chunks",- chunks.len()- );- for chunk in chunks.iter() {- if let Err(e) = self- .insert_chunked_text(- audio_chunk_id,- chunk,- Utc::now(),- transcription_engine,- CHUNKING_ENGINE,- ContentSource::Audio,- )- .await- {- error!("Failed to insert chunk into chunked text index: {}", e);- }- }- }- Err(e) => {- error!("Failed to chunk audio transcription: {}", e);- // Fallback to inserting the whole transcription as a single chunk- if let Err(e) = self- .insert_chunked_text(- audio_chunk_id,- transcription,- Utc::now(),- transcription_engine,- "No_Chunking",- ContentSource::Audio,- )- .await- {- error!(- "Failed to insert whole audio transcription into chunked text index: {}",- e- );- }- }- }+ // // Now, let's chunk the transcription and insert into chunk tables+ // const CHUNKING_ENGINE: &str = "local_simple";++ // let chunks = match CHUNKING_ENGINE {+ // "local_simple" => text_chunking_simple(transcription),+ // "candle_jina_bert" => text_chunking_by_similarity(transcription).await,+ // "unstructured" => unstructured_chunking(transcription)+ // .map_err(|e| anyhow::anyhow!(e))+ // .and_then(|chunks| Ok(chunks)),+ // _ => text_chunking_simple(transcription), // Default to simple chunking for unknown engines+ // };++ // match chunks {+ // Ok(chunks) => {+ // info!(+ // "Successfully chunked audio transcription into {} chunks",+ // chunks.len()+ // );+ // for chunk in chunks.iter() {+ // if let Err(e) = self+ // .insert_chunked_text(+ // audio_chunk_id,+ // chunk,+ // Utc::now(),+ // transcription_engine,+ // CHUNKING_ENGINE,+ // ContentSource::Audio,+ // )+ // .await+ // {+ // error!("Failed to insert chunk into chunked text index: {}", e);+ // }+ // }+ // }+ // Err(e) => {+ // error!("Failed to chunk audio transcription: {}", e);+ // // Fallback to inserting the whole transcription as a single chunk+ // if let Err(e) = self+ // .insert_chunked_text(+ // audio_chunk_id,+ // transcription,+ // Utc::now(),+ // transcription_engine,+ // "No_Chunking",+ // ContentSource::Audio,+ // )+ // .await+ // {+ // error!(+ // "Failed to insert whole audio transcription into chunked text index: {}",+ // e+ // );+ // }+ // }+ // }Ok(())}diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rsindex 9b90101e5..0dbc10936 100644--- a/screenpipe-server/src/lib.rs+++ b/screenpipe-server/src/lib.rs@@ -4,6 +4,8 @@ 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/bin/screenpipe-pipe-runner.rs b/screenpipe-server/src/pipe_runner.rssimilarity index 63%rename from screenpipe-server/src/bin/screenpipe-pipe-runner.rsrename to screenpipe-server/src/pipe_runner.rsindex 7da5064da..26a1db1e2 100644--- a/screenpipe-server/src/bin/screenpipe-pipe-runner.rs+++ b/screenpipe-server/src/pipe_runner.rs@@ -1,72 +1,54 @@-use clap::Parser;-use log::{error, info, warn, LevelFilter};+use futures::Future;+use log::{error, info};use reqwest;#[cfg(feature = "pipes")]use screenpipe_core::run_js;-use screenpipe_server::Cli;use std::io::Write;use std::path::Path;use tempfile::NamedTempFile;use url::Url;#[cfg(feature = "pipes")]-#[tokio::main]-async fn main() -> Result<(), Box<dyn std::error::Error>> {- let cli = Cli::parse();-- if cli.pipe.is_empty() {- error!("No pipe specified. Use --pipe to specify the pipe.");- eprintln!("No pipe specified. Use --pipe to specify the pipe.");- std::process::exit(1);- }-- let mut builder = env_logger::Builder::new();- builder- .filter(None, LevelFilter::Info)- .format_timestamp_secs()- .init();-- warn!("Warning: only 1 pipe is supported right now. This will change in the future.");-- let pipe_input = &cli.pipe[0];- info!("Attempting to process pipe input: {}", pipe_input);-- let path_to_main_module = match Url::parse(pipe_input) {- Ok(_) => {- info!("Input appears to be a URL. Attempting to download...");- match download_pipe(pipe_input).await {- Ok(path) => path,- Err(e) => {- error!("Failed to download pipe: {}", e);- return Err(e);+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_input).canonicalize() {- Ok(path) => path,- Err(e) => {- error!("Failed to canonicalize path: {}", e);- return Err(e.into());+ 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);+ 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);- return Err(error.into());+ 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(())+ 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)?;@@ -92,6 +74,7 @@ fn get_raw_github_url(url: &str) -> Result<String, Box<dyn std::error::Error>> {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);@@ -158,9 +141,3 @@ async fn download_pipe(url: &str) -> Result<std::path::PathBuf, Box<dyn std::errOk(final_path)}--#[cfg(not(feature = "pipes"))]-fn main() {- eprintln!("Pipes support is not enabled. Compile with --features pipes to enable it.");- std::process::exit(1);-}diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rsindex a4a173c79..99c428b98 100644--- a/screenpipe-server/src/resource_monitor.rs+++ b/screenpipe-server/src/resource_monitor.rs@@ -24,6 +24,7 @@ pub struct ResourceMonitor {max_health_check_failures: u32,restart_sender: Sender<RestartSignal>,resource_log_file: Option<String>, // analyse output here: https://colab.research.google.com/drive/1zELlGdzGdjChWKikSqZTHekm5XRxY-1r?usp=sharing+ port: u16,}pub enum RestartSignal {@@ -36,6 +37,7 @@ impl ResourceMonitor {health_check_interval: Duration,max_health_check_failures: u32,restart_sender: Sender<RestartSignal>,+ port: u16,) -> Arc<Self> {let resource_log_file = if env::var("SAVE_RESOURCE_USAGE").is_ok() {let now = Local::now();@@ -64,6 +66,7 @@ impl ResourceMonitor {max_health_check_failures,restart_sender,resource_log_file,+ port,})}@@ -178,7 +181,7 @@ impl ResourceMonitor {}async fn check_health(&self) {let client = reqwest::Client::new();- match client.get("http://localhost:3030/health").send().await {+ match client.get(format!("http://localhost:{}/health", self.port)).send().await {Ok(response) => {debug!("Health check response: {:?}", response);if response.status().is_success() {