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
chore: slowly optimise pipe store focus + fixes
Louis Beaumontf58037afe811
diff --git a/Formula/screenpipe.rb b/Formula/screenpipe.rbdeleted file mode 100644index bcd7a6a99..000000000--- a/Formula/screenpipe.rb+++ /dev/null@@ -1,69 +0,0 @@-class Screenpipe < Formula- desc "Library to build personalized AI powered by what you've seen, said, or heard."- homepage "https://github.com/mediar-ai/screenpipe"- url "https://github.com/mediar-ai/screenpipe/releases/download/v0.1.98/screenpipe-0.1.98-aarch64-apple-darwin.tar.gz"- version "0.1.98"-- on_macos do- if Hardware::CPU.arm?- url "https://github.com/mediar-ai/screenpipe/releases/download/v#{version}/screenpipe-#{version}-aarch64-apple-darwin.tar.gz"- sha256 "2cb4d60689ee22bf7c639e75cbcb57d3b8f21732fc383ff57592b4044b5e4396" # arm64- else- url "https://github.com/mediar-ai/screenpipe/releases/download/v#{version}/screenpipe-#{version}-x86_64-apple-darwin.tar.gz"- sha256 "969dad8fdbf79af2fa6ea14b604ac656041d8fa0281777b70bac6893d13bd34b" # x86_64- end- end-- depends_on "ffmpeg"- # depends_on "bun" # not available on brew?-- def install- bin.install Dir["bin/*"]- lib.install Dir["lib/*"]- end-- test do- system "#{bin}/screenpipe", "-h"- end-end--# push stuff-# VERSION=0.1.35-# git tag v$VERSION-# git push origin v$VERSION-# wait linux release-# or create release-# gh release create v$VERSION --generate-notes-# then--# aarch64-apple-darwin-=begin-cargo build --release --features metal,pipes --target aarch64-apple-darwin-tar -czf screenpipe-${VERSION}-aarch64-apple-darwin.tar.gz -C target/release screenpipe-shasum -a 256 screenpipe-${VERSION}-aarch64-apple-darwin.tar.gz-gh release upload v${VERSION} screenpipe-${VERSION}-aarch64-apple-darwin.tar.gz-rm screenpipe-${VERSION}-aarch64-apple-darwin.tar.gz-=end--# x86_64-apple-darwin-=begin-export PKG_CONFIG_PATH="/usr/local/opt/ffmpeg/lib/pkgconfig:$PKG_CONFIG_PATH"-export PKG_CONFIG_ALLOW_CROSS=1-cargo build --release --features metal,pipes --target x86_64-apple-darwin-tar -czf screenpipe-${VERSION}-x86_64-apple-darwin.tar.gz -C target/release screenpipe-shasum -a 256 screenpipe-${VERSION}-x86_64-apple-darwin.tar.gz-gh release upload v${VERSION} screenpipe-${VERSION}-x86_64-apple-darwin.tar.gz-rm screenpipe-${VERSION}-x86_64-apple-darwin.tar.gz-=end--# update the ruby code above (version and sha256)-=begin-git add Formula/screenpipe.rb-git commit -m "chore: update brew to version ${VERSION}"-git push-=end--# brew tap mediar-ai/screenpipe https://github.com/mediar-ai/screenpipe.git-# brew install screenpipe--# todo automate this in the future, not urgent for now ..\ No newline at end of filediff --git a/cn b/cndeleted file mode 100755index 3791b006b..000000000Binary files a/cn and /dev/null differdiff --git a/examples/typescript/pipe-obsidian-time-logs/pipe.ts b/examples/typescript/pipe-obsidian-time-logs/pipe.tsindex c795f5b8d..2a1837810 100644--- a/examples/typescript/pipe-obsidian-time-logs/pipe.ts+++ b/examples/typescript/pipe-obsidian-time-logs/pipe.ts@@ -52,8 +52,6 @@ async function generateWorkLog(schema: workLog,});- console.log("ai answer:", response);-return response.object;}diff --git a/examples/typescript/pipe-simple-nextjs/bun.lockb b/examples/typescript/pipe-simple-nextjs/bun.lockbnew file mode 100755index 000000000..4feadb7a1Binary files /dev/null and b/examples/typescript/pipe-simple-nextjs/bun.lockb differdiff --git a/examples/typescript/pipe-simple-nextjs/components/keyword-cloud.tsx b/examples/typescript/pipe-simple-nextjs/components/keyword-cloud.tsxindex eaad4ec6b..73cce8259 100644--- a/examples/typescript/pipe-simple-nextjs/components/keyword-cloud.tsx+++ b/examples/typescript/pipe-simple-nextjs/components/keyword-cloud.tsx@@ -27,89 +27,76 @@ export const KeywordCloud: React.FC = () => {const [isLoading, setIsLoading] = useState(true);const [error, setError] = useState<string | null>(null);- const queryScreenpipe = async (params: ScreenpipeQueryParams) => {- const url = new URL("http://localhost:3030/search");- Object.entries(params).forEach(([key, value]) => {- if (value !== undefined) {- url.searchParams.append(key, value.toString());+ const processContentStreaming = async () => {+ console.log("fetching keyword stats...");+ const url = new URL("http://localhost:3030/raw_sql");++ const query = `+ WITH RECURSIVE+ split(word, str) AS (+ SELECT '', content || ' '+ FROM (+ -- Get OCR text and audio from last 12h+ SELECT text as content+ FROM ocr_text ot+ JOIN frames f ON ot.frame_id = f.id+ WHERE datetime(timestamp) >= datetime('now', '-12 hours')+ UNION ALL+ SELECT transcription as content+ FROM audio_transcriptions+ WHERE datetime(timestamp) >= datetime('now', '-12 hours')+ )+ UNION ALL+ SELECT+ LOWER(SUBSTR(str, 0, INSTR(str, ' '))),+ SUBSTR(str, INSTR(str, ' ')+1)+ FROM split WHERE str!=''+ )+ SELECT+ word,+ COUNT(*) as count+ FROM split+ WHERE length(word) > 3+ AND word NOT IN ('this', 'that', 'with', 'from', 'have', 'what', 'your', 'which', 'their', 'about')+ GROUP BY word+ HAVING count > 5+ ORDER BY count DESC+ LIMIT 50;+ `;++ try {+ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ query }),+ });++ if (!response.ok) {+ throw new Error(`http error! status: ${response.status}`);}- });- const response = await fetch(url.toString());- if (!response.ok) {- throw new Error(`http error! status: ${response.status}`);+ const result = await response.json();+ console.log("received keyword stats:", result);++ setKeywords(result.map((row: any) => ({+ word: row.word,+ count: row.count+ })));++ } catch (err) {+ console.error("failed to fetch keyword stats:", err);+ setError("error fetching keyword stats");+ } finally {+ setIsLoading(false);}- return response.json();};useEffect(() => {- const fetchKeywords = async () => {- setIsLoading(true);- setError(null);- try {- const now = new Date();- const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);-- const response = await queryScreenpipe({- content_type: "all",- start_time: yesterday.toISOString(),- end_time: now.toISOString(),- limit: 1_000_000,- });-- if (response && response.data) {- processContentStreaming(response.data);- } else {- setError("no data returned from screenpipe");- }- } catch (err) {- setError("error fetching keywords");- console.error(err);- } finally {- setIsLoading(false);- }- };-- fetchKeywords();+ processContentStreaming();}, []);- const processContentStreaming = (data: ContentItem[]) => {- const batchSize = 100;- const wordCounts: Record<string, number> = {};-- const processBatch = (startIndex: number) => {- const endIndex = Math.min(startIndex + batchSize, data.length);-- for (let i = startIndex; i < endIndex; i++) {- const item = data[i];- const text = item.type === "OCR" ? item.content.text : item.content.transcription;- if (text) {- const words = text.toLowerCase().split(/\s+/);- words.forEach((word) => {- if (word.length > 3) {- wordCounts[word] = (wordCounts[word] || 0) + 1;- }- });- }- }-- const sortedKeywords = sortKeywords(wordCounts).slice(0, 20);- setKeywords(sortedKeywords);-- if (endIndex < data.length) {- setTimeout(() => processBatch(endIndex), 0);- }- };-- processBatch(0);- };-- const sortKeywords = (wordCounts: Record<string, number>): KeywordCount[] => {- return Object.entries(wordCounts)- .map(([word, count]) => ({ word, count }))- .sort((a, b) => b.count - a.count);- };-if (isLoading) return <div>loading...</div>;if (error) return <div>error: {error}</div>;diff --git a/screenpipe-app-tauri/components/header.tsx b/screenpipe-app-tauri/components/header.tsxindex e495f87c6..14be61a4d 100644--- a/screenpipe-app-tauri/components/header.tsx+++ b/screenpipe-app-tauri/components/header.tsx@@ -38,6 +38,7 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip";+import { Calendar } from "lucide-react";export default function Header() {const [showInbox, setShowInbox] = useState(false);@@ -46,7 +47,7 @@ export default function Header() {const { settings } = useSettings();// const isLoading = !health;- const isLoading = false; // ! testing - had issue with this before+ const isLoading = false; // ! testing - had issue with this beforeuseEffect(() => {const loadMessages = async () => {@@ -124,36 +125,8 @@ export default function Header() {</div><div className="flex space-x-4 absolute top-4 right-4"><HealthStatus className="mt-3 cursor-pointer" />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <div>- <Button- variant="ghost"- size="sm"- className="cursor-pointer"- onClick={handleShowTimeline}- disabled={- !settings.enableFrameCache ||- !health ||- health.status === "error"- }- >- <Clock className="mr-2 h-4 w-4" />- timeline- </Button>- </div>- </TooltipTrigger>- {!settings.enableFrameCache && (- <TooltipContent>- <p>enable timeline in settings first</p>- </TooltipContent>- )}- </Tooltip>- </TooltipProvider>- <MeetingHistory />+ <PipeDialog /><Settings />-<Buttonvariant="ghost"size="icon"@@ -173,9 +146,18 @@ export default function Header() {<DropdownMenuContent className="mr-4" align="end"><DropdownMenuItemclassName="cursor-pointer"- onClick={(e) => e.preventDefault()}+ onClick={handleShowTimeline}+ disabled={+ !settings.enableFrameCache ||+ !health ||+ health.status === "error"+ }>- <PipeDialog />+ <Clock className="mr-2 h-4 w-4" />+ <span>timeline</span>+ </DropdownMenuItem>+ <DropdownMenuItem className="cursor-pointer p-0">+ <MeetingHistory /></DropdownMenuItem><DropdownMenuItemclassName="cursor-pointer"diff --git a/screenpipe-app-tauri/components/log-file-button.tsx b/screenpipe-app-tauri/components/log-file-button.tsxindex 833be83f2..19c869de8 100644--- a/screenpipe-app-tauri/components/log-file-button.tsx+++ b/screenpipe-app-tauri/components/log-file-button.tsx@@ -52,26 +52,6 @@ export const LogFileButton = ({}};- const handleCopyLogs = async () => {- try {- const logPath = await getLogFilePath();- const logContent = await readTextFile(logPath);- copyToClipboard(logContent);- toast({- title: "success",- description: "logs copied to clipboard.",- duration: 3000,- });- } catch (error) {- console.error("failed to copy logs:", error);- toast({- title: "error",- description: "failed to copy logs.",- variant: "destructive",- duration: 3000,- });- }- };return (<div className={cn("flex", className)}>@@ -80,9 +60,7 @@ export const LogFileButton = ({<TooltipTrigger asChild><Buttonvariant="outline"- size="sm"onClick={handleOpenLogFile}- className="mr-2"><FileText className="h-4 w-4" /></Button>@@ -92,18 +70,7 @@ export const LogFileButton = ({</TooltipContent></Tooltip></TooltipProvider>- {/* <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Button variant="outline" size="sm" onClick={handleCopyLogs}>- <Copy className="h-4 w-4" />- </Button>- </TooltipTrigger>- <TooltipContent>- <p>copy logs to clipboard</p>- </TooltipContent>- </Tooltip>- </TooltipProvider> */}+</div>);};diff --git a/screenpipe-app-tauri/components/meeting-history.tsx b/screenpipe-app-tauri/components/meeting-history.tsxindex e1098eb85..180a7b87f 100644--- a/screenpipe-app-tauri/components/meeting-history.tsx+++ b/screenpipe-app-tauri/components/meeting-history.tsx@@ -667,7 +667,7 @@ export default function MeetingHistory() {return (<Dialog open={isOpen} onOpenChange={setIsOpen}><DialogTrigger asChild>- <Button variant="ghost" onClick={() => setIsOpen(true)}>+ <Button variant="ghost" className="pl-2" onClick={() => setIsOpen(true)}><Calendar className="mr-2 h-4 w-4" />meetings</Button>diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsxindex de2fec956..09c952c10 100644--- a/screenpipe-app-tauri/components/pipe-store.tsx+++ b/screenpipe-app-tauri/components/pipe-store.tsx@@ -85,7 +85,11 @@ const corePipes: CorePipe[] = ["continuously write logs of your days in a notion table using ollama+llama3.2",url: "https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs",},-+ {+ id: "pipe-simple-nextjs",+ description: "show most used keywords",+ url: "https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-simple-nextjs",+ },];const PipeDialog: React.FC = () => {const [newRepoUrl, setNewRepoUrl] = useState("");@@ -137,15 +141,10 @@ const PipeDialog: React.FC = () => {if (!response.ok) {throw new Error("failed to fetch installed pipes");}- const data = await response.json();+ const data = (await response.json()).data;for (const pipe of data) {// read the README.md file from disk and set the fullDescription- const pathToReadme = await join(- dataDir,- "pipes",- pipe.id,- "README.md"- );+ const pathToReadme = await join(dataDir, "pipes", pipe.id, "README.md");try {const readme = await readFile(pathToReadme);const readmeString = new TextDecoder().decode(readme);@@ -351,6 +350,41 @@ const PipeDialog: React.FC = () => {}};+ const handleDeletePipe = async (pipe: Pipe) => {+ try {+ posthog.capture("delete_pipe", {+ pipe_id: pipe.id,+ });+ toast({+ title: "deleting pipe",+ description: "please wait...",+ });+ const response = await fetch(`http://localhost:3030/pipes/delete`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ pipe_id: pipe.id }),+ });+ if (!response.ok) {+ throw new Error("failed to delete pipe");+ }+ await fetchInstalledPipes();+ setSelectedPipe(null);+ toast({+ title: "pipe deleted",+ description: "the pipe has been successfully removed.",+ });+ } catch (error) {+ console.error("failed to delete pipe:", error);+ toast({+ title: "error deleting pipe",+ description: "please try again or check the logs for more information.",+ variant: "destructive",+ });+ }+ };+const renderPipeContent = () => {if (!selectedPipe) {return (@@ -423,12 +457,30 @@ const PipeDialog: React.FC = () => {support us</Button><LogFileButton />+ <Button+ onClick={() => handleDeletePipe(selectedPipe)}+ variant="outline"+ >+ <Trash2 className="mr-2 h-4 w-4" />+ delete+ </Button></div><Separator className="my-4" />{selectedPipe && selectedPipe.enabled && selectedPipe?.config?.port && (<div className="mt-4 h-[400px]">- <h3 className="text-xl font-semibold mb-2">pipe ui</h3>+ <div className="flex justify-between items-center mb-2">+ <h3 className="text-xl font-semibold">pipe ui</h3>+ <Button+ variant="outline"+ onClick={() =>+ openUrl(`http://localhost:${selectedPipe.config!.port}`)+ }+ >+ <ExternalLink className="mr-2 h-4 w-4" />+ open in browser+ </Button>+ </div><iframesrc={`http://localhost:${selectedPipe.config.port}`}className="w-full h-full border-0"@@ -704,9 +756,9 @@ const PipeDialog: React.FC = () => {return (<Dialog><DialogTrigger asChild>- <Button variant="ghost" className="h-[20px] px-0 py-0">- <Puzzle className="mr-2 h-4 w-4" />- pipe store+ <Button variant="ghost" size="icon" className="cursor-pointer">+ <Puzzle className="h-[1.2rem] w-[1.2rem]" />+ <span className="sr-only">pipe store</span></Button></DialogTrigger><DialogContent className="max-w-[90vw] w-full max-h-[90vh] h-full ">diff --git a/screenpipe-app-tauri/components/settings.tsx b/screenpipe-app-tauri/components/settings.tsxindex cfdf4dd73..f4222b46d 100644--- a/screenpipe-app-tauri/components/settings.tsx+++ b/screenpipe-app-tauri/components/settings.tsx@@ -490,7 +490,10 @@ export function Settings({ className }: { className?: string }) {</DialogTrigger><DialogContent className="max-w-[80vw] w-full max-h-[80vh] h-full overflow-y-auto"><DialogHeader>- <DialogTitle>settings</DialogTitle>+ <div className="flex items-center justify-between">+ <DialogTitle>settings</DialogTitle>+ <Badge className="mr-4">$200 cloud credits</Badge>+ </div><DialogDescription>choose your AI provider, enter necessary credentials, and more.</DialogDescription>diff --git a/screenpipe-app-tauri/package.json b/screenpipe-app-tauri/package.jsonindex 5552841e6..e2f899bad 100644--- a/screenpipe-app-tauri/package.json+++ b/screenpipe-app-tauri/package.json@@ -2,6 +2,7 @@"name": "screenpipe-app","private": true,"scripts": {+ "predev": "echo 'make sure to run cargo build --release and bun predev if you are using non dev mode in screenpipe UI'","dev": "next dev","build": "next build","prebuild": "bun scripts/pre_build.js",diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 3ba5928f3..5b6ff903c 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -171,12 +171,15 @@ mod pipes {let reader = BufReader::new(stderr);let mut lines = reader.lines();while let Ok(Some(line)) = lines.next_line().await {- if line.contains("Download") || line.starts_with("Task dev ") {- // Log download messages and task start messages as info instead of error- debug!("[pipe][info][{}] {}", pipe_clone, line);+ if line.contains("Download")+ || line.starts_with("Task dev ")+ || line.starts_with("$ next dev")+ || line.contains("ready started server")+ || line.contains("Local:")+ {+ println!("[pipe][info][{}] {}", pipe_clone, line);} else {- // Keep other messages as errors- error!("[pipe][error][{}] {}", pipe_clone, line);+ println!("[pipe][error][{}] {}", pipe_clone, line);}}});@@ -404,37 +407,69 @@ mod pipes {|| file_name.to_str().map_or(false, |s| s.starts_with('.'))}- async fn download_github_folder(url: &Url, dest_dir: &Path) -> anyhow::Result<()> {- let client = Client::new();- let api_url = get_raw_github_url(url.as_str())?;+ fn download_github_folder(+ url: &Url,+ dest_dir: &Path,+ ) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {+ let url = url.clone();+ let dest_dir = dest_dir.to_path_buf();- let response = client- .get(&api_url)- .header("Accept", "application/vnd.github.v3+json")- .header("User-Agent", "screenpipe")- .send()- .await?;+ Box::pin(async move {+ let client = Client::new();+ let api_url = get_raw_github_url(url.as_str())?;- let contents: Value = response.json().await?;+ let response = client+ .get(&api_url)+ .header("Accept", "application/vnd.github.v3+json")+ .header("User-Agent", "screenpipe")+ .send()+ .await?;- if !contents.is_array() {- anyhow::bail!("invalid response from github api");- }+ let contents: Value = response.json().await?;- for item in contents.as_array().unwrap() {- let file_name = item["name"].as_str().unwrap();- if !is_hidden_file(std::ffi::OsStr::new(file_name)) {- let download_url = item["download_url"].as_str().unwrap();- let file_content = client.get(download_url).send().await?.bytes().await?;- let file_path = dest_dir.join(file_name);- tokio::fs::write(&file_path, &file_content).await?;- info!("downloaded: {:?}", file_path);- } else {- info!("skipping hidden file: {}", file_name);+ if !contents.is_array() {+ anyhow::bail!("invalid response from github api");}- }- Ok(())+ for item in contents.as_array().unwrap() {+ let file_name = item["name"]+ .as_str()+ .ok_or_else(|| anyhow::anyhow!("missing name in github response"))?;++ if !is_hidden_file(std::ffi::OsStr::new(file_name)) {+ let file_type = item["type"]+ .as_str()+ .ok_or_else(|| anyhow::anyhow!("missing type in github response"))?;++ match file_type {+ "file" => {+ let download_url = item["download_url"].as_str().ok_or_else(|| {+ anyhow::anyhow!("missing download_url in github response")+ })?;++ let file_content =+ client.get(download_url).send().await?.bytes().await?;+ let file_path = dest_dir.join(file_name);+ tokio::fs::write(&file_path, &file_content).await?;+ debug!("downloaded file: {:?}", file_path);+ }+ "dir" => {+ let new_dest_dir = dest_dir.join(file_name);+ tokio::fs::create_dir_all(&new_dest_dir).await?;++ let new_url = format!("{}/{}", url.as_str(), file_name);+ download_github_folder(&Url::parse(&new_url)?, &new_dest_dir).await?;+ debug!("downloaded directory: {:?}", new_dest_dir);+ }+ _ => debug!("skipping unknown type: {}", file_type),+ }+ } else {+ debug!("skipping hidden file: {}", file_name);+ }+ }++ Ok(())+ })}fn get_raw_github_url(url: &str) -> anyhow::Result<String> {diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex edcfbb48f..1f12565fe 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -13,9 +13,9 @@ use screenpipe_audio::{};use screenpipe_core::find_ffmpeg_path;use screenpipe_server::{- cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, start_continuous_recording, watch_pid, DatabaseManager, PipeControl, PipeManager, ResourceMonitor, Server, highlight::{Highlight,HighlightConfig}+ cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand, OutputFormat}, start_continuous_recording, watch_pid, DatabaseManager, PipeControl, PipeManager, ResourceMonitor, Server, highlight::{Highlight,HighlightConfig}};-use screenpipe_vision::{monitor::list_monitors};+use screenpipe_vision::monitor::list_monitors;#[cfg(target_os = "macos")]use screenpipe_vision::run_ui;use serde_json::{json, Value};@@ -124,16 +124,7 @@ async fn main() -> anyhow::Result<()> {let (pipe_manager, mut pipe_control_rx) = PipeManager::new(local_data_dir_clone.clone());let pipe_manager = Arc::new(pipe_manager);- // Check if Screenpipe is present in PATH- match ensure_screenpipe_in_path().await {- Ok(_) => info!("screenpipe is available and properly set in the PATH"),- Err(e) => {- error!("screenpipe PATH check failed: {}", e);- error!("please ensure screenpipe is installed correctly and is in your PATH");- h.capture_error("please ensure screenpipe is installed correctly and is in your PATH");- // do not crash- }- }+if let Some(pipe_command) = cli.command {match pipe_command {@@ -207,6 +198,19 @@ async fn main() -> anyhow::Result<()> {}}}++ // Check if Screenpipe is present in PATH+ // TODO: likely should not force user to install in PATH (eg brew, powershell, or button in UI)+ match ensure_screenpipe_in_path().await {+ Ok(_) => info!("screenpipe is available and properly set in the PATH"),+ Err(e) => {+ error!("screenpipe PATH check failed: {}", e);+ error!("please ensure screenpipe is installed correctly and is in your PATH");+ h.capture_error("please ensure screenpipe is installed correctly and is in your PATH");+ // do not crash+ }+ }+if find_ffmpeg_path().is_none() {eprintln!("ffmpeg not found. please install ffmpeg and ensure it is in your path.");@@ -819,24 +823,56 @@ async fn main() -> anyhow::Result<()> {Ok(())}-async fn handle_pipe_command(pipe: PipeCommand, pipe_manager: &PipeManager) -> anyhow::Result<()> {- // Handle pipe subcommands- match pipe {- PipeCommand::List => {+async fn handle_pipe_command(command: PipeCommand, pipe_manager: &Arc<PipeManager>) -> anyhow::Result<()> {+ match command {+ PipeCommand::List { output } => {let pipes = pipe_manager.list_pipes().await;- println!("available pipes:");- for pipe in pipes {- println!(" id: {}, enabled: {}", pipe.id, pipe.enabled);+ match output {+ OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&json!({+ "data": pipes,+ "success": true+ }))?),+ OutputFormat::Text => {+ println!("available pipes:");+ for pipe in pipes {+ println!(" id: {}, enabled: {}", pipe.id, pipe.enabled);+ }+ }+ }+ }+ PipeCommand::Download { url, output } => {+ match pipe_manager.download_pipe(&url).await {+ Ok(pipe_id) => match output {+ OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&json!({+ "data": {+ "pipe_id": pipe_id,+ "message": "pipe downloaded successfully"+ },+ "success": true+ }))?),+ OutputFormat::Text => println!("pipe downloaded successfully. id: {}. now enable it with `screenpipe pipe enable {}`", pipe_id, pipe_id),+ },+ Err(e) => {+ let error_msg = format!("failed to download pipe: {}", e);+ match output {+ OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&json!({+ "error": error_msg,+ "success": false+ }))?),+ OutputFormat::Text => eprintln!("{}", error_msg),+ }+ }+ }+ }+ PipeCommand::Info { id, output } => {+ match pipe_manager.get_pipe_info(&id).await {+ Some(info) => match output {+ OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&info)?),+ OutputFormat::Text => println!("pipe info: {:?}", info),+ },+ None => eprintln!("pipe not found"),}}- PipeCommand::Download { url } => match pipe_manager.download_pipe(&url).await {- Ok(pipe_id) => println!("pipe downloaded successfully. id: {}. now enable it with `screenpipe pipe enable {}`", pipe_id, pipe_id),- Err(e) => eprintln!("failed to download pipe: {}", e),- },- PipeCommand::Info { id } => match pipe_manager.get_pipe_info(&id).await {- Some(info) => println!("pipe info: {:?}", info),- None => eprintln!("pipe not found"),- },PipeCommand::Enable { id } => {match pipe_manager.update_config(&id, json!({"enabled": true}))@@ -886,6 +922,23 @@ async fn handle_pipe_command(pipe: PipeCommand, pipe_manager: &PipeManager) -> a}}},+ PipeCommand::Delete { id, yes } => {+ if !yes {+ print!("are you sure you want to delete pipe '{}'? [y/N] ", id);+ std::io::stdout().flush()?;+ let mut input = String::new();+ std::io::stdin().read_line(&mut input)?;+ if !input.trim().eq_ignore_ascii_case("y") {+ println!("pipe deletion cancelled.");+ return Ok(());+ }+ }++ match pipe_manager.delete_pipe(&id).await {+ Ok(_) => println!("pipe '{}' deleted successfully", id),+ Err(e) => println!("failed to delete pipe: {}", e),+ }+ }}Ok(())}diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex 077021165..0a8efadc9 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -282,16 +282,26 @@ pub enum Command {#[derive(Subcommand)]pub enum PipeCommand {/// List all pipes- List,+ List {+ /// Output format+ #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]+ output: OutputFormat,+ },/// Download a new pipeDownload {/// URL of the pipe to downloadurl: String,+ /// Output format+ #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]+ output: OutputFormat,},/// Get info for a specific pipeInfo {/// ID of the pipeid: String,+ /// Output format+ #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]+ output: OutputFormat,},/// Enable a pipeEnable {@@ -316,4 +326,18 @@ pub enum PipeCommand {#[arg(short = 'y', long)]yes: bool,},+ /// Delete a pipe+ Delete {+ /// ID of the pipe to delete+ id: String,+ /// Automatically confirm deletion without prompting+ #[arg(short = 'y', long)]+ yes: bool,+ },+}++#[derive(Clone, Debug, ValueEnum, PartialEq)]+pub enum OutputFormat {+ Text,+ Json,}diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rsindex b57c570d9..1bf42d60c 100644--- a/screenpipe-server/src/pipe_manager.rs+++ b/screenpipe-server/src/pipe_manager.rs@@ -7,7 +7,7 @@ use std::path::PathBuf;use tokio::fs::File;use tokio::io::AsyncWriteExt;use tokio::sync::mpsc::{self, Receiver, Sender};-use tracing::{debug, info, warn};+use tracing::{debug, info};#[derive(Clone, Serialize, Deserialize, Debug)]pub struct PipeInfo {@@ -130,10 +130,7 @@ impl PipeManager {let config = tokio::fs::read_to_string(&config_path).await.and_then(|s| serde_json::from_str::<Value>(&s).map_err(Into::into))- .unwrap_or_else(|_| {- warn!("pipe {}: does not seem to have a config file", pipe_id);- Value::Null- });+ .unwrap_or_else(|_| Value::Null);PipeInfo {id: pipe_id,@@ -209,4 +206,30 @@ impl PipeManager {tokio::fs::remove_dir_all(pipe_dir).await?;Ok(())}++ pub async fn delete_pipe(&self, id: &str) -> Result<()> {+ debug!("deleting pipe: {}", id);++ // First disable the pipe to stop any running instances+ self.update_config(+ id,+ serde_json::json!({+ "enabled": false,+ }),+ )+ .await?;++ // Send control message to stop the pipe+ let _ = self.control_tx.send(PipeControl::Disable(id.to_string())).await;++ // Delete the pipe directory+ let pipe_dir = self.screenpipe_dir.join("pipes").join(id);+ if pipe_dir.exists() {+ tokio::fs::remove_dir_all(pipe_dir).await?;+ info!("pipe {} deleted", id);+ Ok(())+ } else {+ Err(anyhow::anyhow!("pipe '{}' does not exist", id))+ }+ }}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 72573d869..c5470446a 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -1,7 +1,7 @@use axum::{extract::{Json, Path, Query, State},http::StatusCode,- response::{sse::Event, Json as JsonResponse, Sse},+ response::{sse::Event, IntoResponse, Json as JsonResponse, Sse},routing::{get, post},serve, Router,};@@ -14,7 +14,7 @@ use image::ImageFormat::{self};use crate::{db::TagContentType,- pipe_manager::{PipeInfo, PipeManager},+ pipe_manager::PipeManager,video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},video_cache::{FrameCache, TimeSeriesFrame},video_utils::{merge_videos, MergeVideosRequest, MergeVideosResponse},@@ -639,14 +639,20 @@ async fn download_pipe_handler(debug!("Downloading pipe: {}", payload.url);match state.pipe_manager.download_pipe(&payload.url).await {Ok(pipe_dir) => Ok(JsonResponse(json!({- "message": format!("Pipe {} downloaded successfully", pipe_dir),- "pipe_id": pipe_dir+ "data": {+ "pipe_id": pipe_dir,+ "message": "pipe downloaded successfully"+ },+ "success": true}))),Err(e) => {error!("Failed to download pipe: {}", e);Err((StatusCode::INTERNAL_SERVER_ERROR,- JsonResponse(json!({"error": e.to_string()})),+ JsonResponse(json!({+ "error": format!("failed to download pipe: {}", e),+ "success": false+ })),))}}@@ -669,12 +675,18 @@ async fn run_pipe_handler(.await{Ok(_) => Ok(JsonResponse(json!({- "message": format!("Pipe {} started", payload.pipe_id),- "pipe_id": payload.pipe_id+ "data": {+ "pipe_id": payload.pipe_id,+ "message": "pipe started"+ },+ "success": true}))),Err(e) => Err((StatusCode::BAD_REQUEST,- JsonResponse(json!({"error": e.to_string()})),+ JsonResponse(json!({+ "error": format!("failed to start pipe: {}", e),+ "success": false+ })),)),}}@@ -695,12 +707,18 @@ async fn stop_pipe_handler(.await{Ok(_) => Ok(JsonResponse(json!({- "message": format!("Pipe {} stopped", payload.pipe_id),- "pipe_id": payload.pipe_id+ "data": {+ "pipe_id": payload.pipe_id,+ "message": "pipe stopped"+ },+ "success": true}))),Err(e) => Err((StatusCode::BAD_REQUEST,- JsonResponse(json!({"error": e.to_string()})),+ JsonResponse(json!({+ "error": format!("failed to stop pipe: {}", e),+ "success": false+ })),)),}}@@ -716,12 +734,18 @@ async fn update_pipe_config_handler(.await{Ok(_) => Ok(JsonResponse(json!({- "message": format!("Pipe {} config updated", payload.pipe_id),- "pipe_id": payload.pipe_id+ "data": {+ "pipe_id": payload.pipe_id,+ "message": "pipe config updated"+ },+ "success": true}))),Err(e) => Err((StatusCode::BAD_REQUEST,- JsonResponse(json!({"error": e.to_string()})),+ JsonResponse(json!({+ "error": format!("failed to update pipe config: {}", e),+ "success": false+ })),)),}}@@ -729,20 +753,30 @@ async fn update_pipe_config_handler(async fn get_pipe_info_handler(State(state): State<Arc<AppState>>,Path(pipe_id): Path<String>,-) -> Result<JsonResponse<PipeInfo>, (StatusCode, JsonResponse<Value>)> {+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {debug!("Getting pipe info for: {}", pipe_id);match state.pipe_manager.get_pipe_info(&pipe_id).await {- Some(info) => Ok(JsonResponse(info)),+ Some(info) => Ok(JsonResponse(json!({+ "data": info,+ "success": true+ }))),None => Err((StatusCode::NOT_FOUND,- JsonResponse(json!({"error": "Pipe not found"})),+ JsonResponse(json!({+ "error": "pipe not found",+ "success": false+ })),)),}}-async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> JsonResponse<Vec<PipeInfo>> {+async fn list_pipes_handler(State(state): State<Arc<AppState>>) -> JsonResponse<Value> {debug!("Listing pipes");- JsonResponse(state.pipe_manager.list_pipes().await)+ let pipes = state.pipe_manager.list_pipes().await;+ JsonResponse(json!({+ "data": pipes,+ "success": true+ }))}pub struct Server {@@ -1318,6 +1352,7 @@ pub fn create_router() -> Router<Arc<AppState>> {.route("/pipes/enable", post(run_pipe_handler)).route("/pipes/disable", post(stop_pipe_handler)).route("/pipes/update", post(update_pipe_config_handler))+ .route("/pipes/delete", post(delete_pipe_handler)).route("/experimental/frames/merge", post(merge_frames_handler)).route("/health", get(health_check)).route("/raw_sql", post(execute_raw_sql))@@ -1412,6 +1447,35 @@ async fn stream_frames_handler()}+// Add this new handler function+pub async fn delete_pipe_handler(+ State(state): State<Arc<AppState>>,+ Json(request): Json<DeletePipeRequest>,+) -> impl IntoResponse {+ match state.pipe_manager.delete_pipe(&request.pipe_id).await {+ Ok(_) => (+ StatusCode::OK,+ Json(json!({+ "success": true,+ "message": "pipe deleted successfully"+ })),+ ),+ Err(e) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({+ "success": false,+ "error": format!("failed to delete pipe: {}", e)+ })),+ ),+ }+}++// Add this struct for the request payload+#[derive(Debug, Deserialize)]+pub struct DeletePipeRequest {+ pipe_id: String,+}+/*Curl commands for reference: