Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat: implement deduplication SDK + embeddings endpoint

Louis Beaumont26703141ebc7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4711bf405..b732f55e6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -48,14 +48,9 @@ jobs:
- name: Run cargo tests
run: cargo test
- # TODO: ??
+ # todo: need to run backend ...
# - name: Run bun tests
- # env:
- # SCREENPIPE_DIR: ${{ runner.workspace }}/screenpipe
- # PIPE_ID: test
- # PIPE_FILE: pipe.ts
- # PIPE_DIR: ${{ runner.workspace }}/screenpipe/pipes/test
- # run: bun ./scripts/run_tests.js
+ # run: bun test
# working-directory: ./screenpipe-js
test-windows:
diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.yml
index 1ea922989..9fb43b82b 100644
--- a/.github/workflows/release-cli.yml
+++ b/.github/workflows/release-cli.yml
@@ -62,7 +62,7 @@ jobs:
export PKG_CONFIG_PATH="/usr/local/opt/ffmpeg/lib/pkgconfig:$PKG_CONFIG_PATH"
export PKG_CONFIG_ALLOW_CROSS=1
export RUSTFLAGS="-C link-arg=-Wl,-rpath,@executable_path/../lib -C link-arg=-Wl,-rpath,@loader_path/../lib"
- cargo build --release --features pipes,metal --target ${{ matrix.target }}
+ cargo build --release --features metal --target ${{ matrix.target }}
- name: Set version
run: |
@@ -245,7 +245,7 @@ jobs:
- name: Build CLI
run: |
- cargo build --release --features pipes --target ${{ matrix.target }}
+ cargo build --release --target ${{ matrix.target }}
- name: Set version
run: |
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3f8a49007..6753aaccf 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -241,55 +241,6 @@ before submitting a pull request, run all the tests to ensure nothing has broken
```bash
cargo test
-# on macos you need to set DYLD_LIBRARY_PATH for apple native OCR tests to run
-DYLD_LIBRARY_PATH=$(pwd)/screenpipe-vision/lib cargo test
-```
-
-you can add env var to `.vscode/settings.json`:
-
-```json
-{
- "terminal.integrated.env.osx": {
- "DYLD_LIBRARY_PATH": "$(pwd)/screenpipe-vision/lib"
- }
-}
-```
-
-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 hacks
diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.toml
index c77727656..dba450a18 100644
--- a/screenpipe-core/Cargo.toml
+++ b/screenpipe-core/Cargo.toml
@@ -14,19 +14,18 @@ which = "6.0.1"
ffmpeg-sidecar = { git = "https://github.com/nathanbabcock/ffmpeg-sidecar", branch = "main" }
log = "0.4.17"
anyhow = "1.0.86"
-candle = { workspace = true, optional = true }
-candle-nn = { workspace = true, optional = true }
-candle-transformers = { workspace = true, optional = true }
-tokenizers = { workspace = true, optional = true }
+candle = { workspace = true }
+candle-nn = { workspace = true }
+candle-transformers = { workspace = true }
+tokenizers = { workspace = true }
hf-hub = { workspace = true, features = [
"tokio",
"native-tls",
-], optional = true }
+] }
screenpipe-actions = { path = "../screenpipe-actions", optional = true }
http-cache-reqwest = "0.15.0"
reqwest = { workspace = true }
reqwest-middleware = "0.4.0"
-# pipes
tokio = { workspace = true }
# Security
@@ -53,11 +52,10 @@ zip = "0.6.2"
tokio-stream = "0.1.17"
[features]
-default = ["pipes", "security"]
-llm = ["candle", "candle-nn", "candle-transformers", "tokenizers", "hf-hub"]
-pipes = []
+default = ["security"]
security = ["dep:regex", "dep:lazy_static"]
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]
beta = ["dep:screenpipe-actions"]
+llm = []
diff --git a/screenpipe-core/examples/simple-node-api-pipe/main.rs b/screenpipe-core/examples/simple-node-api-pipe/main.rs
deleted file mode 100644
index 36290736f..000000000
--- a/screenpipe-core/examples/simple-node-api-pipe/main.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-use std::path::Path;
-use anyhow::Result;
-use dirs::home_dir;
-use screenpipe_core::{download_pipe, run_pipe};
-use tracing::info;
-use tracing_subscriber::{fmt, prelude::*, EnvFilter};
-
-// ollama run nemotron-mini:4b-instruct-q4_k_m
-// cargo run --package screenpipe-core --example simple-node-api-pipe --features metal --features pipes
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let console_layer = fmt::layer()
- .with_writer(std::io::stdout)
- .with_filter(EnvFilter::new("info"));
- tracing_subscriber::registry().with(console_layer).init();
-
- // Set up the path to the screenpipe directory
- let screenpipe_dir = home_dir().unwrap().join(".screenpipe");
-
- // The name of the pipe (folder name in examples)
- let pipe_url = "screenpipe-core/examples/simple-node-api-pipe";
- let pipe_name = Path::new(pipe_url).file_name().unwrap().to_str().unwrap();
- info!("Starting the simple Node.js API pipe...");
-
- // download the pipe
- download_pipe(pipe_url, screenpipe_dir.clone()).await?;
-
- // Run the pipe
- match run_pipe(pipe_name, screenpipe_dir).await {
- Ok(_) => println!("Pipe execution completed successfully."),
- Err(e) => eprintln!("Error executing pipe: {}", e),
- }
-
- Ok(())
-}
diff --git a/screenpipe-core/examples/simple-node-api-pipe/pipe.ts b/screenpipe-core/examples/simple-node-api-pipe/pipe.ts
deleted file mode 100644
index eb227128f..000000000
--- a/screenpipe-core/examples/simple-node-api-pipe/pipe.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-
-import { z } from "zod";
-import { streamText } from "ai";
-import { ollama } from "ollama-ai-provider";
-import * as fs from "node:fs/promises";
-
-const screenpipeQuery = z.object({
- q: z.string().optional(),
- content_type: z.enum(["ocr", "audio", "all"]).default("all"),
- limit: z.number().default(20),
- start_time: z.string().default(new Date(Date.now() - 3600000).toISOString()),
- end_time: z.string().default(new Date().toISOString()),
-});
-
-async function queryScreenpipe(params: z.infer<typeof screenpipeQuery>) {
- try {
- const queryParams = new URLSearchParams(
- Object.entries(params).filter(([_, v]) => v != null) as [string, string][]
- );
- console.log("calling screenpipe", JSON.stringify(params));
- const response = await fetch(`http://localhost:3030/search?${queryParams}`);
- if (!response.ok) {
- throw new Error(`http error! status: ${response.status}`);
- }
- return await response.json();
- } catch (error) {
- console.error("error querying screenpipe:", error);
- return null;
- }
-}
-
-const simpleOllamaChat = async () => {
- console.log(
- "starting simple ollama chat. make sure to run `ollama run nemotron-mini:4b-instruct-q4_k_m` before running this script."
- );
- const provider = ollama("nemotron-mini:4b-instruct-q4_k_m");
-
- while (true) {
- try {
- // query last 1 min of screenpipe
- const screenpipe = await queryScreenpipe({
- content_type: "all",
- limit: 10,
- start_time: new Date(Date.now() - 60000).toISOString(),
- end_time: new Date().toISOString(),
- });
- console.log(
- "got some screenpipe data of length:",
- screenpipe.data.length
- );
-
- const conversation: { role: string; content: string }[] = [
- {
- role: "user",
- content:
- "what did i do in the last minute? here is the screenpipe data: " +
- JSON.stringify(screenpipe),
- },
- ];
-
- const { textStream } = await streamText({
- model: provider,
- messages: conversation,
- maxToolRoundtrips: 3,
- });
-
- process.stdout.write("ai: ");
- for await (const chunk of textStream) {
- process.stdout.write(chunk);
- }
- console.log(); // new line after the complete response
-
- // log conversation to file
- await fs.appendFile(
- "conversation_log.txt",
- JSON.stringify(conversation) + "\n"
- );
- } catch (error) {
- console.error("error in ollama chat:", error);
- }
- }
-};
-
-const main = async () => {
- await simpleOllamaChat();
-};
-
-main();
diff --git a/screenpipe-core/examples/simple-ollama-pipe/deno.json b/screenpipe-core/examples/simple-ollama-pipe/deno.json
deleted file mode 100644
index 58f418473..000000000
--- a/screenpipe-core/examples/simple-ollama-pipe/deno.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "imports": {
- "zod": "npm:zod",
- "ai": "npm:ai",
- "ollama-ai-provider": "npm:ollama-ai-provider"
- }
-}
\ No newline at end of file
diff --git a/screenpipe-core/examples/simple-ollama-pipe/main.rs b/screenpipe-core/examples/simple-ollama-pipe/main.rs
deleted file mode 100644
index 750280d4d..000000000
--- a/screenpipe-core/examples/simple-ollama-pipe/main.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use std::path::Path;
-
-use anyhow::Result;
-use dirs::home_dir;
-use screenpipe_core::{download_pipe, run_pipe};
-use tracing::info;
-use tracing_subscriber::{fmt, prelude::*, EnvFilter};
-
-// ollama run nemotron-mini:4b-instruct-q4_k_m
-// cargo run --package screenpipe-core --example simple-ollama-pipe --features metal --features pipes
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let console_layer = fmt::layer()
- .with_writer(std::io::stdout)
- .with_filter(EnvFilter::new("info"));
- tracing_subscriber::registry().with(console_layer).init();
-
- // Set up the path to the screenpipe directory
- let screenpipe_dir = home_dir().unwrap().join(".screenpipe");
-
- // The name of the pipe (folder name in examples)
- let pipe_url = "screenpipe-core/examples/simple-ollama-pipe";
- let pipe_name = Path::new(pipe_url).file_name().unwrap().to_str().unwrap();
- info!("Starting the simple Ollama chat pipe...");
-
- // download the pipe
- download_pipe(pipe_url, screenpipe_dir.clone()).await?;
-
- // Run the pipe
- match run_pipe(pipe_name, screenpipe_dir).await {
- Ok(_) => println!("Pipe execution completed successfully."),
- Err(e) => eprintln!("Error executing pipe: {}", e),
- }
-
- Ok(())
-}
diff --git a/screenpipe-core/examples/simple-ollama-pipe/pipe.ts b/screenpipe-core/examples/simple-ollama-pipe/pipe.ts
deleted file mode 100644
index e476211d4..000000000
--- a/screenpipe-core/examples/simple-ollama-pipe/pipe.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { z } from "zod";
-import { streamText } from "ai";
-import { ollama } from "ollama-ai-provider";
-
-const screenpipeQuery = z.object({
- q: z.string().optional(),
- content_type: z.enum(["ocr", "audio", "all"]).default("all"),
- limit: z.number().default(20),
- start_time: z.string().default(new Date(Date.now() - 3600000).toISOString()),
- end_time: z.string().default(new Date().toISOString()),
-});
-
-async function queryScreenpipe(params: z.infer<typeof screenpipeQuery>) {
- try {
- const queryParams = new URLSearchParams(
- Object.entries(params).filter(([_, v]) => v != null) as [string, string][]
- );
- console.log("Calling screenpipe", JSON.stringify(params));
- const response = await fetch(`http://localhost:3030/search?${queryParams}`);
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- return await response.json();
- } catch (error) {
- console.error("Error querying screenpipe:", error);
- return null;
- }
-}
-
-const simpleOllamaChat = async () => {
- console.log(
- "Starting simple Ollama chat. Make sure to run `ollama run nemotron-mini:4b-instruct-q4_K_M` before running this script."
- );
- const provider = ollama("nemotron-mini:4b-instruct-q4_K_M");
-
- while (true) {
- try {
- // query last 1 min of screenpipe
- const screenpipe = await queryScreenpipe({
- content_type: "all",
- limit: 10,
- start_time: new Date(Date.now() - 60000).toISOString(),
- end_time: new Date().toISOString(),
- });
- console.log(
- "got some screenpipe data of length:",
- screenpipe.data.length
- );
-
- const conversation: { role: string; content: string }[] = [
- {
- role: "user",
- content:
- "What did I do in the last minute? Here is the screenpipe data: " +
- JSON.stringify(screenpipe),
- },
- ];
-
- const { textStream } = await streamText({
- model: provider,
- messages: conversation,
- maxToolRoundtrips: 3,
- });
-
- process.stdout.write("ai: ");
- for await (const chunk of textStream) {
- process.stdout.write(chunk);
- }
- console.log(); // new line after the complete response
- } catch (error) {
- console.error("error in ollama chat:", error);
- }
- }
-};
-
-const main = async () => {
- await simpleOllamaChat();
-};
-
-main();
diff --git a/screenpipe-core/examples/simple-pipe-api-pipe/main.rs b/screenpipe-core/examples/simple-pipe-api-pipe/main.rs
deleted file mode 100644
index d5b2ee4df..000000000
--- a/screenpipe-core/examples/simple-pipe-api-pipe/main.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-use std::path::Path;
-use anyhow::Result;
-use dirs::home_dir;
-use screenpipe_core::{download_pipe, run_pipe};
-use tracing::info;
-use tracing_subscriber::{fmt, prelude::*, EnvFilter};
-
-// ollama run nemotron-mini:4b-instruct-q4_k_m
-// cargo run --package screenpipe-core --example simple-pipe-api-pipe --features metal --features pipes
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let console_layer = fmt::layer()
- .with_writer(std::io::stdout)
- .with_filter(EnvFilter::new("info"));
- tracing_subscriber::registry().with(console_layer).init();
-
- // Set up the path to the screenpipe directory
- let screenpipe_dir = home_dir().unwrap().join(".screenpipe");
-
- // The name of the pipe (folder name in examples)
- let pipe_url = "screenpipe-core/examples/simple-pipe-api-pipe";
- let pipe_name = Path::new(pipe_url).file_name().unwrap().to_str().unwrap();
- info!("Starting the simple pipe API pipe...");
-
- // download the pipe
- download_pipe(pipe_url, screenpipe_dir.clone()).await?;
-
- // Run the pipe
- match run_pipe(pipe_name, screenpipe_dir).await {
- Ok(_) => println!("Pipe execution completed successfully."),
- Err(e) => eprintln!("Error executing pipe: {}", e),
- }
-
- Ok(())
-}
diff --git a/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts b/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts
deleted file mode 100644
index 41abc1ce4..000000000
--- a/screenpipe-core/examples/simple-pipe-api-pipe/pipe.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { z } from "zod";
-import { streamText } from "ai";
-import { ollama } from "ollama-ai-provider";
-import { queryScreenpipe } from "@screenpipe/js";
-
-const simpleOllamaChat = async () => {
- console.log(
- "starting simple ollama chat. make sure to run `ollama run nemotron-mini:4b-instruct-q4_k_m` before running this script."
- );
- const provider = ollama("nemotron-mini:4b-instruct-q4_k_m");
-
- while (true) {
- try {
- // query last 1 min of screenpipe
- const screenpipe = await queryScreenpipe({
- content_type: "all",
- limit: 10,
- start_time: new Date(Date.now() - 60000).toISOString(),
- end_time: new Date().toISOString(),
- });
- console.log(
- "got some screenpipe data of length:",
- screenpipe.data.length
- );
-
- const conversation: { role: string; content: string }[] = [
- {
- role: "user",
- content:
- "what did i do in the last minute? here is the screenpipe data: " +
- JSON.stringify(screenpipe),
- },
- ];
-
- const { textStream } = await streamText({
- model: provider,
- messages: conversation,
- maxToolRoundtrips: 3,
- });
-
- process.stdout.write("ai: ");
- for await (const chunk of textStream) {
- process.stdout.write(chunk);
- }
- console.log(); // new line after the complete response
- } catch (error) {
- console.error("error in ollama chat:", error);
- }
- }
-};
-
-const main = async () => {
- await simpleOllamaChat();
-};
-
-main();
diff --git a/screenpipe-core/src/embedding/mod.rs b/screenpipe-core/src/embedding/mod.rs
new file mode 100644
index 000000000..757b2013c
--- /dev/null
+++ b/screenpipe-core/src/embedding/mod.rs
@@ -0,0 +1,2 @@
+pub mod model;
+
diff --git a/screenpipe-core/src/embedding/model.rs b/screenpipe-core/src/embedding/model.rs
new file mode 100644
index 000000000..f5138a6a2
--- /dev/null
+++ b/screenpipe-core/src/embedding/model.rs
@@ -0,0 +1,139 @@
+use anyhow::Error as E;
+use candle::{DType, Device, Module, Tensor};
+use candle_nn::VarBuilder;
+use candle_transformers::models::jina_bert::{BertModel, Config, PositionEmbeddingType};
+use hf_hub::{api::sync::Api, Repo, RepoType};
+use tokenizers::Tokenizer;
+pub struct EmbeddingModel {
+ model: BertModel,
+ tokenizer: Tokenizer,
+ device: candle::Device,
+ normalize: bool,
+}
+
+impl EmbeddingModel {
+ pub fn new(model_path: Option<String>, tokenizer_path: Option<String>) -> anyhow::Result<Self> {
+ let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
+
+ // default to jina-embeddings-v2-base-en if no paths provided
+ let (model_path, tokenizer_path) = if model_path.is_none() || tokenizer_path.is_none() {
+ let api = Api::new()?;
+ let repo = api.repo(Repo::new(
+ "jinaai/jina-embeddings-v2-base-en".to_string(),
+ RepoType::Model,
+ ));
+ (repo.get("model.safetensors")?, repo.get("tokenizer.json")?)
+ } else {
+ (
+ std::path::PathBuf::from(model_path.unwrap()),
+ std::path::PathBuf::from(tokenizer_path.unwrap()),
+ )
+ };
+
+ let tokenizer = Tokenizer::from_file(tokenizer_path).map_err(E::msg)?;
+
+ let config = Config::new(
+ tokenizer.get_vocab_size(true),
+ 768,
+ 12,
+ 12,
+ 3072,
+ candle_nn::Activation::Gelu,
+ 8192,
+ 2,
+ 0.02,
+ 1e-12,
+ 0,
+ PositionEmbeddingType::Alibi,
+ );
+
+ let vb =
+ unsafe { VarBuilder::from_mmaped_safetensors(&[model_path], DType::F32, &device)? };
+ let model = BertModel::new(vb, &config)?;
+
+ Ok(Self {
+ model,
+ tokenizer,
+ device,
+ normalize: true,
+ })
+ }
+
+ fn normalize_l2(&self, v: &Tensor) -> candle::Result<Tensor> {
+ v.broadcast_div(&v.sqr()?.sum_keepdim(1)?.sqrt()?)
+ }
+
+ pub fn generate_embedding(&self, text: &str) -> anyhow::Result<Vec<f32>> {
+ let tokens = self
+ .tokenizer
+ .encode(text, true)
+ .map_err(E::msg)?
+ .get_ids()
+ .to_vec();
+
+ let token_ids = Tensor::new(&tokens[..], &self.device)?.unsqueeze(0)?;
+ let embeddings = self.model.forward(&token_ids)?;
+ let (_, n_tokens, _) = embeddings.dims3()?;
+
+ // mean pooling
+ let embeddings = (embeddings.sum(1)? / (n_tokens as f64))?;
+
+ let embeddings = if self.normalize {
+ self.normalize_l2(&embeddings)?
+ } else {
+ embeddings
+ };
+
+ // convert to vec
+ let embeddings = embeddings.squeeze(0)?;
+ let embedding_vec = embeddings.to_vec1()?;
+
+ Ok(embedding_vec)
+ }
+
+ pub fn generate_batch_embeddings(&self, texts: &[String]) -> anyhow::Result<Vec<Vec<f32>>> {
+ // configure padding
+ let mut tokenizer = self.tokenizer.clone();
+ if let Some(pp) = tokenizer.get_padding_mut() {
+ pp.strategy = tokenizers::PaddingStrategy::BatchLongest
+ } else {
+ let pp = tokenizers::PaddingParams {
+ strategy: tokenizers::PaddingStrategy::BatchLongest,
+ ..Default::default()
+ };
+ tokenizer.with_padding(Some(pp));
+ }
+
+ let tokens = tokenizer
+ .encode_batch(texts.to_vec(), true)
+ .map_err(E::msg)?;
+ let token_ids: Vec<Tensor> = tokens
+ .iter()
+ .map(|tokens| {
+ let tokens = tokens.get_ids().to_vec();
+ Tensor::new(tokens.as_slice(), &self.device)
+ })
+ .collect::<candle::Result<Vec<_>>>()?;
+
+ let token_ids = Tensor::stack(&token_ids, 0)?;
+ let embeddings = self.model.forward(&token_ids)?;
+
+ let (_, n_tokens, _) = embeddings.dims3()?;
+ let embeddings = (embeddings.sum(1)? / (n_tokens as f64))?;
+
+ let embeddings = if self.normalize {
+ self.normalize_l2(&embeddings)?
+ } else {
+ embeddings
+ };
+
+ // convert to vec of vecs
+ let mut result = Vec::new();
+ for i in 0..texts.len() {
+ let emb = embeddings.get(i)?;
+ result.push(emb.to_vec1()?);
+ }
+
+ Ok(result)
+ }
+}
diff --git a/screenpipe-core/src/lib.rs b/screenpipe-core/src/lib.rs
index bf1f1401e..ed3d699d3 100644
--- a/screenpipe-core/src/lib.rs
+++ b/screenpipe-core/src/lib.rs
@@ -20,9 +20,7 @@ pub use mistral::*;
pub mod llama;
#[cfg(feature = "llm")]
pub use llama::*;
-#[cfg(feature = "pipes")]
pub mod pipes;
-#[cfg(feature = "pipes")]
pub use pipes::*;
mod language;
#[cfg(feature = "security")]
@@ -31,7 +29,6 @@ pub mod pii_removal;
#[cfg(feature = "mkl")]
extern crate intel_mkl_src;
-
#[cfg(feature = "security")]
pub use pii_removal::*;
@@ -42,3 +39,6 @@ pub use language::{Language, TESSERACT_LANGUAGES};
pub mod devices;
pub use devices::*;
+
+pub mod embedding;
+pub use embedding::*;
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index 373544da3..e569904d7 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -1,101 +1,98 @@
-#[allow(clippy::module_inception)]
-#[cfg(feature = "pipes")]
-mod pipes {
- use dirs::home_dir;
- use regex::Regex;
- use sentry;
- use serde_json::Value;
- use std::collections::HashMap;
- use std::future::Future;
- use std::path::PathBuf;
- use std::pin::Pin;
- use std::time::{Duration, SystemTime, UNIX_EPOCH};
- use tokio::process::Command;
- use tokio::sync::watch;
-
- use anyhow::Result;
- use std::fs;
- use std::path::Path;
- use tokio::io::{AsyncBufReadExt, BufReader};
- use tracing::{debug, error, info, warn};
- use url::Url;
- use which::which;
-
- // Add these imports at the top of the file
- use serde_json::json;
- use tokio::fs::File;
- use tokio::io::AsyncWriteExt;
-
- use crate::pick_unused_port;
- use once_cell::sync::Lazy;
-
- // Add near other imports
- use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions};
- use rand::distributions::Alphanumeric;
- use rand::{thread_rng, Rng};
- use reqwest_middleware::reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
- use reqwest_middleware::reqwest::Client;
- use reqwest_middleware::ClientBuilder;
- use std::collections::HashSet;
- use std::str::FromStr;
-
- // Add at top of file with other imports
- #[cfg(windows)]
- use std::os::windows::process::CommandExt;
+use dirs::home_dir;
+use regex::Regex;
+use sentry;
+use serde_json::Value;
+use std::collections::HashMap;
+use std::future::Future;
+use std::path::PathBuf;
+use std::pin::Pin;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use tokio::process::Command;
+use tokio::sync::watch;
+
+use anyhow::Result;
+use std::fs;
+use std::path::Path;
+use tokio::io::{AsyncBufReadExt, BufReader};
+use tracing::{debug, error, info, warn};
+use url::Url;
+use which::which;
+
+// Add these imports at the top of the file
+use serde_json::json;
+use tokio::fs::File;
+use tokio::io::AsyncWriteExt;
+
+use crate::pick_unused_port;
+use once_cell::sync::Lazy;
+
+// Add near other imports
+use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions};
+use rand::distributions::Alphanumeric;
+use rand::{thread_rng, Rng};
+use reqwest_middleware::reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
+use reqwest_middleware::reqwest::Client;
+use reqwest_middleware::ClientBuilder;
+use std::collections::HashSet;
+use std::str::FromStr;
+
+// Add at top of file with other imports
+#[cfg(windows)]
+use std::os::windows::process::CommandExt;
+
+#[derive(Clone, Debug, Copy)]
+pub enum PipeState {
+ Port(u16),
+ Pid(i32),
+}
- #[derive(Clone, Debug, Copy)]
- pub enum PipeState {
- Port(u16),
- Pid(i32),
- }
+pub struct CronHandle {
+ shutdown: watch::Sender<bool>,
+}
- pub struct CronHandle {
- shutdown: watch::Sender<bool>,
- }
+#[derive(Debug, Clone)]
+pub enum BuildStatus {
+ NotStarted,
+ InProgress,
+ Success,
+ Failed(String),
+}
- #[derive(Debug, Clone)]
- pub enum BuildStatus {
- NotStarted,
- InProgress,
- Success,
- Failed(String),
- }
-
- impl CronHandle {
- pub fn stop(&self) {
- let _ = self.shutdown.send(true);
- }
+impl CronHandle {
+ pub fn stop(&self) {
+ let _ = self.shutdown.send(true);
}
+}
- static CRON_HANDLES: Lazy<tokio::sync::Mutex<HashMap<String, Vec<CronHandle>>>> =
- Lazy::new(|| tokio::sync::Mutex::new(HashMap::new()));
+static CRON_HANDLES: Lazy<tokio::sync::Mutex<HashMap<String, Vec<CronHandle>>>> =
+ Lazy::new(|| tokio::sync::Mutex::new(HashMap::new()));
- // Add this function to generate a secure cron secret
- fn generate_cron_secret() -> String {
- thread_rng()
- .sample_iter(&Alphanumeric)
- .take(32)
- .map(char::from)
- .collect()
- }
+// Add this function to generate a secure cron secret
+fn generate_cron_secret() -> String {
+ thread_rng()
+ .sample_iter(&Alphanumeric)
+ .take(32)
+ .map(char::from)
+ .collect()
+}
- // Update this function near the top of the file
- fn sanitize_pipe_name(name: &str) -> String {
- let re = Regex::new(r"[^a-zA-Z0-9_-]").unwrap();
- let sanitized = re.replace_all(name, "-").to_string();
-
- // Remove "-ref-main/" suffix if it exists
- sanitized
- .strip_suffix("-ref-main/")
- .or_else(|| sanitized.strip_suffix("-ref-main"))
- .unwrap_or(&sanitized)
- .to_string()
- }
+// Update this function near the top of the file
+fn sanitize_pipe_name(name: &str) -> String {
+ let re = Regex::new(r"[^a-zA-Z0-9_-]").unwrap();
+ let sanitized = re.replace_all(name, "-").to_string();
+
+ // Remove "-ref-main/" suffix if it exists
+ sanitized
+ .strip_suffix("-ref-main/")
+ .or_else(|| sanitized.strip_suffix("-ref-main"))
+ .unwrap_or(&sanitized)
+ .to_string()
+}
- async fn create_watchdog_script(parent_pid: u32, child_pid: u32) -> Result<PathBuf> {
- let script_content = if cfg!(windows) {
- format!(
- r#"
+async fn create_watchdog_script(parent_pid: u32, child_pid: u32) -> Result<PathBuf> {
+ let script_content = if cfg!(windows) {
+ format!(
+ r#"
$parentPid = {parent_pid}
$childPid = {child_pid}
@@ -132,10 +129,10 @@ while ($true) {{
}}
}}
"#
- )
- } else {
- format!(
- r#"#!/bin/bash
+ )
+ } else {
+ format!(
+ r#"#!/bin/bash
set -x # Enable debug mode
parent_pid={parent_pid}
child_pid={child_pid}
@@ -203,1523 +200,1511 @@ while true; do
sleep 1
done
"#
- )
- };
-
- let temp_dir = std::env::temp_dir();
- let script_name = if cfg!(windows) {
- format!("watchdog_{parent_pid}_{child_pid}.ps1")
- } else {
- format!("watchdog_{parent_pid}_{child_pid}.sh")
- };
- let script_path = temp_dir.join(script_name);
-
- tokio::fs::write(&script_path, script_content).await?;
-
- // Set executable permissions on Unix systems only
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- let mut perms = tokio::fs::metadata(&script_path).await?.permissions();
- perms.set_mode(0o755);
- tokio::fs::set_permissions(&script_path, perms).await?;
- }
-
- Ok(script_path)
+ )
+ };
+
+ let temp_dir = std::env::temp_dir();
+ let script_name = if cfg!(windows) {
+ format!("watchdog_{parent_pid}_{child_pid}.ps1")
+ } else {
+ format!("watchdog_{parent_pid}_{child_pid}.sh")
+ };
+ let script_path = temp_dir.join(script_name);
+
+ tokio::fs::write(&script_path, script_content).await?;
+
+ // Set executable permissions on Unix systems only
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut perms = tokio::fs::metadata(&script_path).await?.permissions();
+ perms.set_mode(0o755);
+ tokio::fs::set_permissions(&script_path, perms).await?;
}
- async fn spawn_watchdog(parent_pid: u32, child_pid: u32) -> Result<tokio::process::Child> {
- let script_path = create_watchdog_script(parent_pid, child_pid).await?;
-
- info!(
- "Spawning watchdog process for parent_pid={}, child_pid={}",
- parent_pid, child_pid
- );
- info!("Watchdog script path: {:?}", script_path);
-
- // Create a log file for the watchdog
- let log_path =
- std::env::temp_dir().join(format!("watchdog_{}_{}.log", parent_pid, child_pid));
+ Ok(script_path)
+}
- #[cfg(windows)]
- let child = {
- Command::new("powershell")
- .arg("-ExecutionPolicy")
- .arg("Bypass")
- .arg("-NoProfile")
- .arg("-NonInteractive")
- .arg("-WindowStyle")
- .arg("Hidden")
- .arg("-File")
- .arg(&script_path)
- .creation_flags(0x08000000)
- .stdout(std::fs::File::create(&log_path)?)
- .stderr(std::fs::File::create(&log_path)?)
- .spawn()?
- };
+async fn spawn_watchdog(parent_pid: u32, child_pid: u32) -> Result<tokio::process::Child> {
+ let script_path = create_watchdog_script(parent_pid, child_pid).await?;
- #[cfg(not(windows))]
- let child = {
- Command::new("bash")
- .arg(&script_path)
- .stdout(std::fs::File::create(&log_path)?)
- .stderr(std::fs::File::create(&log_path)?)
- .spawn()?
- };
+ info!(
+ "Spawning watchdog process for parent_pid={}, child_pid={}",
+ parent_pid, child_pid
+ );
+ info!("Watchdog script path: {:?}", script_path);
- if let Some(id) = child.id() {
- info!("Watchdog process spawned with PID: {}", id);
+ // Create a log file for the watchdog
+ let log_path = std::env::temp_dir().join(format!("watchdog_{}_{}.log", parent_pid, child_pid));
- // Modify verification for Windows
- #[cfg(windows)]
- {
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(1)).await;
- let output = Command::new("powershell")
- .arg("-NoProfile")
- .arg("-NonInteractive")
- .arg("-Command")
- .arg(format!(
- "Get-Process -Id {} -ErrorAction SilentlyContinue",
- id
- ))
- .output()
- .await;
+ #[cfg(windows)]
+ let child = {
+ Command::new("powershell")
+ .arg("-ExecutionPolicy")
+ .arg("Bypass")
+ .arg("-NoProfile")
+ .arg("-NonInteractive")
+ .arg("-WindowStyle")
+ .arg("Hidden")
+ .arg("-File")
+ .arg(&script_path)
+ .creation_flags(0x08000000)
+ .stdout(std::fs::File::create(&log_path)?)
+ .stderr(std::fs::File::create(&log_path)?)
+ .spawn()?
+ };
- match output {
- Ok(output) => {
- if output.status.success() {
- info!("Watchdog process verified running with PID: {}", id);
- } else {
- error!("Watchdog process not found after spawn! PID: {}", id);
- }
+ #[cfg(not(windows))]
+ let child = {
+ Command::new("bash")
+ .arg(&script_path)
+ .stdout(std::fs::File::create(&log_path)?)
+ .stderr(std::fs::File::create(&log_path)?)
+ .spawn()?
+ };
+
+ if let Some(id) = child.id() {
+ info!("Watchdog process spawned with PID: {}", id);
+
+ // Modify verification for Windows
+ #[cfg(windows)]
+ {
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ let output = Command::new("powershell")
+ .arg("-NoProfile")
+ .arg("-NonInteractive")
+ .arg("-Command")
+ .arg(format!(
+ "Get-Process -Id {} -ErrorAction SilentlyContinue",
+ id
+ ))
+ .output()
+ .await;
+
+ match output {
+ Ok(output) => {
+ if output.status.success() {
+ info!("Watchdog process verified running with PID: {}", id);
+ } else {
+ error!("Watchdog process not found after spawn! PID: {}", id);
}
- Err(e) => error!("Failed to verify watchdog process: {}", e),
}
- });
- }
-
- #[cfg(not(windows))]
- {
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(1)).await;
- let output = Command::new("ps")
- .args(["-p", &id.to_string()])
- .output()
- .await;
+ Err(e) => error!("Failed to verify watchdog process: {}", e),
+ }
+ });
+ }
- match output {
- Ok(output) => {
- if output.status.success() {
- info!("Watchdog process verified running with PID: {}", id);
- } else {
- error!("Watchdog process not found after spawn! PID: {}", id);
- }
+ #[cfg(not(windows))]
+ {
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ let output = Command::new("ps")
+ .args(["-p", &id.to_string()])
+ .output()
+ .await;
+
+ match output {
+ Ok(output) => {
+ if output.status.success() {
+ info!("Watchdog process verified running with PID: {}", id);
+ } else {
+ error!("Watchdog process not found after spawn! PID: {}", id);
}
- Err(e) => error!("Failed to verify watchdog process: {}", e),
}
- });
- }
+ Err(e) => error!("Failed to verify watchdog process: {}", e),
+ }
+ });
}
+ }
- // Clean up script after a delay
- let script_path_clone = script_path.clone();
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(30)).await;
- if let Err(e) = tokio::fs::remove_file(&script_path_clone).await {
- error!("Failed to remove watchdog script: {}", e);
- }
- });
+ // Clean up script after a delay
+ let script_path_clone = script_path.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(30)).await;
+ if let Err(e) = tokio::fs::remove_file(&script_path_clone).await {
+ error!("Failed to remove watchdog script: {}", e);
+ }
+ });
- Ok(child)
- }
+ Ok(child)
+}
- pub async fn run_pipe(
- pipe: &str,
- screenpipe_dir: PathBuf,
- ) -> Result<(tokio::process::Child, PipeState)> {
- let bun_path = find_bun_path().ok_or_else(|| {
- let err = anyhow::anyhow!("bun not found");
- sentry::capture_error(&err.source().unwrap());
- err
- })?;
- let pipe_dir = screenpipe_dir.join("pipes").join(pipe);
- let pipe_json_path = pipe_dir.join("pipe.json");
- let package_json_path = pipe_dir.join("package.json");
+pub async fn run_pipe(
+ pipe: &str,
+ screenpipe_dir: PathBuf,
+) -> Result<(tokio::process::Child, PipeState)> {
+ let bun_path = find_bun_path().ok_or_else(|| {
+ let err = anyhow::anyhow!("bun not found");
+ sentry::capture_error(&err.source().unwrap());
+ err
+ })?;
+ let pipe_dir = screenpipe_dir.join("pipes").join(pipe);
+ let pipe_json_path = pipe_dir.join("pipe.json");
+ let package_json_path = pipe_dir.join("package.json");
+
+ debug!(
+ "checking if pipe is a next.js project at: {:?}",
+ package_json_path
+ );
+
+ // First check if it's a Next.js project by looking at package.json
+ let is_nextjs = if package_json_path.exists() {
+ debug!("found package.json, checking for next.js dependency");
+ let package_json = tokio::fs::read_to_string(&package_json_path).await?;
+ let package_data: Value = serde_json::from_str(&package_json)?;
+ let has_next = package_data["dependencies"].get("next").is_some();
+ debug!("is next.js project: {}", has_next);
+ has_next
+ } else {
+ false
+ };
+
+ // Check if pipe is still enabled
+ if pipe_json_path.exists() {
+ debug!("checking if pipe is enabled from: {:?}", pipe_json_path);
+ let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
+ let pipe_config: Value = serde_json::from_str(&pipe_json)?;
+
+ if !pipe_config
+ .get("enabled")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+ {
+ debug!("pipe {} is disabled, stopping", pipe);
+ anyhow::bail!("pipe is disabled");
+ }
+ debug!("pipe {} is enabled, continuing", pipe);
+ }
+ // Prepare environment variables
+ debug!("preparing environment variables for pipe: {}", pipe);
+ let mut env_vars = std::env::vars().collect::<Vec<(String, String)>>();
+ env_vars.push((
+ "SCREENPIPE_DIR".to_string(),
+ screenpipe_dir.to_str().unwrap().to_string(),
+ ));
+ env_vars.push(("PIPE_ID".to_string(), pipe.to_string()));
+ env_vars.push((
+ "PIPE_DIR".to_string(),
+ pipe_dir.to_str().unwrap().to_string(),
+ ));
+
+ if is_nextjs {
debug!(
- "checking if pipe is a next.js project at: {:?}",
- package_json_path
+ "setting up next.js specific configuration for pipe: {}",
+ pipe
);
- // First check if it's a Next.js project by looking at package.json
- let is_nextjs = if package_json_path.exists() {
- debug!("found package.json, checking for next.js dependency");
- let package_json = tokio::fs::read_to_string(&package_json_path).await?;
- let package_data: Value = serde_json::from_str(&package_json)?;
- let has_next = package_data["dependencies"].get("next").is_some();
- debug!("is next.js project: {}", has_next);
- has_next
- } else {
- false
- };
+ let mut assigned_port = None;
- // Check if pipe is still enabled
+ // Handle Next.js specific setup including crons
if pipe_json_path.exists() {
- debug!("checking if pipe is enabled from: {:?}", pipe_json_path);
+ debug!("reading pipe.json for next.js configuration");
let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
let pipe_config: Value = serde_json::from_str(&pipe_json)?;
- if !pipe_config
- .get("enabled")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- debug!("pipe {} is disabled, stopping", pipe);
- anyhow::bail!("pipe is disabled");
+ // Try to use user-configured port first
+ if let Some(user_port) = pipe_config.get("port").and_then(|p| p.as_u64()) {
+ debug!("found user-configured port: {}", user_port);
+ // Verify port is available
+ if is_port_available(user_port as u16) {
+ assigned_port = Some(user_port as u16);
+ debug!("user-configured port {} is available", user_port);
+ } else {
+ debug!(
+ "user-configured port {} is in use, will assign random port",
+ user_port
+ );
+ }
}
- debug!("pipe {} is enabled, continuing", pipe);
- }
- // Prepare environment variables
- debug!("preparing environment variables for pipe: {}", pipe);
- let mut env_vars = std::env::vars().collect::<Vec<(String, String)>>();
- env_vars.push((
- "SCREENPIPE_DIR".to_string(),
- screenpipe_dir.to_str().unwrap().to_string(),
- ));
- env_vars.push(("PIPE_ID".to_string(), pipe.to_string()));
- env_vars.push((
- "PIPE_DIR".to_string(),
- pipe_dir.to_str().unwrap().to_string(),
- ));
+ // Fallback to random port if needed
+ let port = assigned_port.unwrap_or_else(|| pick_unused_port().expect("No ports free"));
+ info!("[{}] using port {} for next.js pipe", pipe, port);
- if is_nextjs {
- debug!(
- "setting up next.js specific configuration for pipe: {}",
- pipe
+ // Update pipe.json with the actual port being used
+ let mut updated_config = pipe_config.clone();
+ updated_config["port"] = json!(port);
+ let updated_pipe_json = serde_json::to_string_pretty(&updated_config)?;
+ let mut file = File::create(&pipe_json_path).await?;
+ file.write_all(updated_pipe_json.as_bytes()).await?;
+ info!(
+ "[{}] updated pipe.json with port configuration: {}",
+ pipe, updated_pipe_json
);
- let mut assigned_port = None;
+ env_vars.push(("PORT".to_string(), port.to_string()));
- // Handle Next.js specific setup including crons
- if pipe_json_path.exists() {
- debug!("reading pipe.json for next.js configuration");
- let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
- let pipe_config: Value = serde_json::from_str(&pipe_json)?;
-
- // Try to use user-configured port first
- if let Some(user_port) = pipe_config.get("port").and_then(|p| p.as_u64()) {
- debug!("found user-configured port: {}", user_port);
- // Verify port is available
- if is_port_available(user_port as u16) {
- assigned_port = Some(user_port as u16);
- debug!("user-configured port {} is available", user_port);
- } else {
- debug!(
- "user-configured port {} is in use, will assign random port",
- user_port
- );
- }
- }
-
- // Fallback to random port if needed
- let port =
- assigned_port.unwrap_or_else(|| pick_unused_port().expect("No ports free"));
- info!("[{}] using port {} for next.js pipe", pipe, port);
-
- // Update pipe.json with the actual port being used
- let mut updated_config = pipe_config.clone();
- updated_config["port"] = json!(port);
- let updated_pipe_json = serde_json::to_string_pretty(&updated_config)?;
- let mut file = File::create(&pipe_json_path).await?;
- file.write_all(updated_pipe_json.as_bytes()).await?;
+ // Handle cron jobs if they exist
+ if let Some(crons) = pipe_config.get("crons").and_then(Value::as_array) {
info!(
- "[{}] updated pipe.json with port configuration: {}",
- pipe, updated_pipe_json
+ "[{}] found {} cron jobs in configuration",
+ pipe,
+ crons.len()
);
+ let base_url = format!("http://localhost:{}", port);
+ debug!("[{}] using base url: {} for cron jobs", pipe, base_url);
+
+ let cron_secret = generate_cron_secret();
+ debug!("[{}] generated cron secret: {}", pipe, cron_secret);
+ env_vars.push(("CRON_SECRET".to_string(), cron_secret.clone()));
+
+ let mut handles = Vec::new();
+
+ for cron in crons {
+ let path = cron["path"]
+ .as_str()
+ .ok_or_else(|| anyhow::anyhow!("missing path"))?
+ .to_string();
+ let schedule = cron["schedule"]
+ .as_str()
+ .ok_or_else(|| anyhow::anyhow!("missing schedule"))?
+ .to_string();
+
+ let (tx, rx) = watch::channel(false);
+ let handle = CronHandle { shutdown: tx };
+ handles.push(handle);
+
+ let base_url = base_url.clone();
+ let pipe_clone = pipe.to_string();
+ let secret_clone = cron_secret.clone();
+ let screenpipe_dir = screenpipe_dir.clone();
+
+ tokio::spawn(async move {
+ run_cron_schedule(
+ &pipe_clone,
+ &base_url,
+ &path,
+ &secret_clone,
+ &schedule,
+ &screenpipe_dir,
+ rx,
+ )
+ .await;
+ });
+ }
- env_vars.push(("PORT".to_string(), port.to_string()));
-
- // Handle cron jobs if they exist
- if let Some(crons) = pipe_config.get("crons").and_then(Value::as_array) {
- info!(
- "[{}] found {} cron jobs in configuration",
- pipe,
- crons.len()
- );
- let base_url = format!("http://localhost:{}", port);
- debug!("[{}] using base url: {} for cron jobs", pipe, base_url);
-
- let cron_secret = generate_cron_secret();
- debug!("[{}] generated cron secret: {}", pipe, cron_secret);
- env_vars.push(("CRON_SECRET".to_string(), cron_secret.clone()));
-
- let mut handles = Vec::new();
-
- for cron in crons {
- let path = cron["path"]
- .as_str()
- .ok_or_else(|| anyhow::anyhow!("missing path"))?
- .to_string();
- let schedule = cron["schedule"]
- .as_str()
- .ok_or_else(|| anyhow::anyhow!("missing schedule"))?
- .to_string();
-
- let (tx, rx) = watch::channel(false);
- let handle = CronHandle { shutdown: tx };
- handles.push(handle);
-
- let base_url = base_url.clone();
- let pipe_clone = pipe.to_string();
- let secret_clone = cron_secret.clone();
- let screenpipe_dir = screenpipe_dir.clone();
-
- tokio::spawn(async move {
- run_cron_schedule(
- &pipe_clone,
- &base_url,
- &path,
- &secret_clone,
- &schedule,
- &screenpipe_dir,
- rx,
- )
- .await;
- });
- }
+ // Store handles for later cleanup
+ CRON_HANDLES.lock().await.insert(pipe.to_string(), handles);
+ }
- // Store handles for later cleanup
- CRON_HANDLES.lock().await.insert(pipe.to_string(), handles);
- }
+ // Install dependencies using bun
+ info!("[{}] installing dependencies for next.js pipe", pipe);
- // Install dependencies using bun
- info!("[{}] installing dependencies for next.js pipe", pipe);
+ let install_output = Command::new(&bun_path)
+ .arg("install")
+ .current_dir(&pipe_dir)
+ .env("NPM_CONFIG_REGISTRY", "https://registry.npmjs.org")
+ .env("BUN_CONFIG_REGISTRY", "https://registry.npmjs.org")
+ .output()
+ .await?;
- let install_output = Command::new(&bun_path)
- .arg("install")
- .current_dir(&pipe_dir)
- .env("NPM_CONFIG_REGISTRY", "https://registry.npmjs.org")
- .env("BUN_CONFIG_REGISTRY", "https://registry.npmjs.org")
- .output()
- .await?;
-
- if !install_output.status.success() {
- let err_msg = String::from_utf8_lossy(&install_output.stderr);
- error!("[{}] failed to install dependencies: {}", pipe, err_msg);
- let err = anyhow::anyhow!(
- "failed to install dependencies for next.js pipe: {}",
- err_msg
- );
- sentry::capture_error(&err.source().unwrap());
- anyhow::bail!(err);
- }
- info!(
- "[{}] successfully installed dependencies for next.js pipe",
- pipe
+ if !install_output.status.success() {
+ let err_msg = String::from_utf8_lossy(&install_output.stderr);
+ error!("[{}] failed to install dependencies: {}", pipe, err_msg);
+ let err = anyhow::anyhow!(
+ "failed to install dependencies for next.js pipe: {}",
+ err_msg
);
- } else {
- let port = pick_unused_port().expect("No ports free");
- info!(
- "[{}] no pipe.json found, using random port {} for next.js pipe",
- pipe, port
- );
- env_vars.push(("PORT".to_string(), port.to_string()));
+ sentry::capture_error(&err.source().unwrap());
+ anyhow::bail!(err);
}
+ info!(
+ "[{}] successfully installed dependencies for next.js pipe",
+ pipe
+ );
+ } else {
+ let port = pick_unused_port().expect("No ports free");
+ info!(
+ "[{}] no pipe.json found, using random port {} for next.js pipe",
+ pipe, port
+ );
+ env_vars.push(("PORT".to_string(), port.to_string()));
+ }
- // Try to build the Next.js project
- let build_status = try_build_nextjs(&pipe_dir, &bun_path).await?;
- let build_success = matches!(build_status, BuildStatus::Success);
-
- if pipe_json_path.exists() {
- let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
- let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
-
- pipe_config["buildStatus"] = match &build_status {
- BuildStatus::Success => json!("success"),
- BuildStatus::Failed(error) => json!({
- "status": "failed",
- "error": error
- }),
- BuildStatus::InProgress => json!("in_progress"),
- BuildStatus::NotStarted => json!("not_started"),
- };
+ // Try to build the Next.js project
+ let build_status = try_build_nextjs(&pipe_dir, &bun_path).await?;
+ let build_success = matches!(build_status, BuildStatus::Success);
- let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
- tokio::fs::write(&pipe_json_path, updated_pipe_json).await?;
- }
+ if pipe_json_path.exists() {
+ let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
+ let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
- let port = env_vars
- .iter()
- .find(|(k, _)| k == "PORT")
- .map(|(_, v)| v)
- .unwrap()
- .parse::<u16>()
- .expect("Invalid port number");
+ pipe_config["buildStatus"] = match &build_status {
+ BuildStatus::Success => json!("success"),
+ BuildStatus::Failed(error) => json!({
+ "status": "failed",
+ "error": error
+ }),
+ BuildStatus::InProgress => json!("in_progress"),
+ BuildStatus::NotStarted => json!("not_started"),
+ };
- // Run the Next.js project
- info!(
- "starting next.js project in {} mode",
- if build_success {
- "production"
- } else {
- "development"
- }
- );
+ let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
+ tokio::fs::write(&pipe_json_path, updated_pipe_json).await?;
+ }
- let mut command = Command::new(&bun_path);
- command.arg("run").arg("--bun");
+ let port = env_vars
+ .iter()
+ .find(|(k, _)| k == "PORT")
+ .map(|(_, v)| v)
+ .unwrap()
+ .parse::<u16>()
+ .expect("Invalid port number");
+ // Run the Next.js project
+ info!(
+ "starting next.js project in {} mode",
if build_success {
- command.arg("start");
+ "production"
} else {
- info!("[{}] falling back to dev mode due to build failure", pipe);
- command.arg("dev");
+ "development"
}
+ );
- command
- .arg("--port")
- .arg(port.to_string())
- .current_dir(&pipe_dir)
- .envs(env_vars)
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped());
-
- let mut child = command.spawn()?;
+ let mut command = Command::new(&bun_path);
+ command.arg("run").arg("--bun");
- debug!("[{}] streaming logs for next.js pipe", pipe);
- stream_logs(pipe, &mut child).await?;
+ if build_success {
+ command.arg("start");
+ } else {
+ info!("[{}] falling back to dev mode due to build failure", pipe);
+ command.arg("dev");
+ }
- let child_pid = child.id().expect("Failed to get child PID") as u32;
- let parent_pid = std::process::id();
+ command
+ .arg("--port")
+ .arg(port.to_string())
+ .current_dir(&pipe_dir)
+ .envs(env_vars)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
- info!("Spawned bun process with PID: {}", child_pid);
+ let mut child = command.spawn()?;
- // Spawn watchdog process
- match spawn_watchdog(parent_pid, child_pid).await {
- Ok(watchdog) => {
- debug!(
- "Watchdog process spawned successfully with PID: {:?}",
- watchdog.id()
- );
- }
- Err(e) => {
- warn!("Failed to spawn watchdog process: {}", e);
- }
- }
+ debug!("[{}] streaming logs for next.js pipe", pipe);
+ stream_logs(pipe, &mut child).await?;
- return Ok((child, PipeState::Port(port)));
- }
+ let child_pid = child.id().expect("Failed to get child PID") as u32;
+ let parent_pid = std::process::id();
- // If it's not a Next.js project, run as regular pipe
- let main_module = find_pipe_file(&pipe_dir)?;
- info!("[{}] executing pipe: {:?}", pipe, main_module);
+ info!("Spawned bun process with PID: {}", child_pid);
- env_vars.push((
- "PIPE_FILE".to_string(),
- main_module.to_str().unwrap().to_string(),
- ));
+ // Spawn watchdog process
+ match spawn_watchdog(parent_pid, child_pid).await {
+ Ok(watchdog) => {
+ debug!(
+ "Watchdog process spawned successfully with PID: {:?}",
+ watchdog.id()
+ );
+ }
+ Err(e) => {
+ warn!("Failed to spawn watchdog process: {}", e);
+ }
+ }
- let mut child = Command::new(&bun_path)
- .arg("run")
- .arg("--bun")
- .arg(&main_module)
- .envs(env_vars)
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped())
- .spawn()?;
+ return Ok((child, PipeState::Port(port)));
+ }
- // Stream logs
- stream_logs(pipe, &mut child).await?;
+ // If it's not a Next.js project, run as regular pipe
+ let main_module = find_pipe_file(&pipe_dir)?;
+ info!("[{}] executing pipe: {:?}", pipe, main_module);
+
+ env_vars.push((
+ "PIPE_FILE".to_string(),
+ main_module.to_str().unwrap().to_string(),
+ ));
+
+ let mut child = Command::new(&bun_path)
+ .arg("run")
+ .arg("--bun")
+ .arg(&main_module)
+ .envs(env_vars)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()?;
+
+ // Stream logs
+ stream_logs(pipe, &mut child).await?;
+
+ let child_id = child.id().unwrap();
+ Ok((child, PipeState::Pid(child_id as i32))) // Return 0 or handle port differently for non-Next.js projects
+}
- let child_id = child.id().unwrap();
- Ok((child, PipeState::Pid(child_id as i32))) // Return 0 or handle port differently for non-Next.js projects
- }
+async fn stream_logs(pipe: &str, child: &mut tokio::process::Child) -> Result<()> {
+ let stdout = child.stdout.take().expect("failed to get stdout");
+ let stderr = child.stderr.take().expect("failed to get stderr");
- async fn stream_logs(pipe: &str, child: &mut tokio::process::Child) -> Result<()> {
- let stdout = child.stdout.take().expect("failed to get stdout");
- let stderr = child.stderr.take().expect("failed to get stderr");
+ let pipe_clone = pipe.to_string();
- let pipe_clone = pipe.to_string();
+ // Spawn tasks to handle stdout and stderr
+ let _stdout_handle = tokio::spawn(async move {
+ let reader = BufReader::new(stdout);
+ let mut lines = reader.lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ info!("[{}] {}", pipe_clone, line);
+ }
+ });
+
+ let pipe_clone = pipe.to_string();
+
+ let _stderr_handle = tokio::spawn(async move {
+ // Create static HashMaps for efficient lookups
+ static INFO_PATTERNS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ let mut set = HashSet::new();
+ // Development related
+ set.insert("Download");
+ set.insert("Task dev");
+ set.insert("$ next dev");
+ set.insert("ready started server");
+ set.insert("Local:");
+ set.insert("Webpack is configured");
+ set.insert("See instructions");
+ set.insert("https://nextjs.org");
+ set.insert("⚠ See instructions");
+ set.insert("$ next start");
+ set.insert("[bun install]");
+ set.insert("Saved lockfile");
+ set.insert("Resolved, downloaded");
+ set.insert("Installing");
+ set.insert("Successfully installed");
+ set.insert("packages installed");
+ set.insert("Fetching");
+ set.insert("Resolving");
+ // Frontend console patterns
+ set.insert("[LOG]");
+ set.insert("console.log");
+ set.insert("] ");
+ set.insert("›");
+ set.insert("<");
+ set.insert("Warning:");
+ set.insert("render@");
+ set.insert("webpack");
+ set.insert("HMR");
+ set.insert("[HMR]");
+ set
+ });
- // Spawn tasks to handle stdout and stderr
- let _stdout_handle = tokio::spawn(async move {
- let reader = BufReader::new(stdout);
- let mut lines = reader.lines();
- while let Ok(Some(line)) = lines.next_line().await {
- info!("[{}] {}", pipe_clone, line);
- }
+ static ERROR_PATTERNS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
+ let mut set = HashSet::new();
+ set.insert("TypeError:");
+ set.insert("ReferenceError:");
+ set.insert("SyntaxError:");
+ set.insert("Error:");
+ set.insert("Uncaught");
+ set.insert("Failed to compile");
+ set.insert("ENOENT");
+ set.insert("FATAL");
+ set
});
- let pipe_clone = pipe.to_string();
-
- let _stderr_handle = tokio::spawn(async move {
- // Create static HashMaps for efficient lookups
- static INFO_PATTERNS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
- let mut set = HashSet::new();
- // Development related
- set.insert("Download");
- set.insert("Task dev");
- set.insert("$ next dev");
- set.insert("ready started server");
- set.insert("Local:");
- set.insert("Webpack is configured");
- set.insert("See instructions");
- set.insert("https://nextjs.org");
- set.insert("⚠ See instructions");
- set.insert("$ next start");
- set.insert("[bun install]");
- set.insert("Saved lockfile");
- set.insert("Resolved, downloaded");
- set.insert("Installing");
- set.insert("Successfully installed");
- set.insert("packages installed");
- set.insert("Fetching");
- set.insert("Resolving");
- // Frontend console patterns
- set.insert("[LOG]");
- set.insert("console.log");
- set.insert("] ");
- set.insert("›");
- set.insert("<");
- set.insert("Warning:");
- set.insert("render@");
- set.insert("webpack");
- set.insert("HMR");
- set.insert("[HMR]");
- set
- });
+ let reader = BufReader::new(stderr);
+ let mut lines = reader.lines();
- static ERROR_PATTERNS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
- let mut set = HashSet::new();
- set.insert("TypeError:");
- set.insert("ReferenceError:");
- set.insert("SyntaxError:");
- set.insert("Error:");
- set.insert("Uncaught");
- set.insert("Failed to compile");
- set.insert("ENOENT");
- set.insert("FATAL");
- set
- });
+ while let Ok(Some(line)) = lines.next_line().await {
+ let line_lower = line.to_lowercase(); // Convert once for case-insensitive matching
- let reader = BufReader::new(stderr);
- let mut lines = reader.lines();
+ // Quick checks first
+ if line.trim().is_empty() || line.contains("console.") {
+ info!("[{}] {}", pipe_clone, line);
+ continue;
+ }
- while let Ok(Some(line)) = lines.next_line().await {
- let line_lower = line.to_lowercase(); // Convert once for case-insensitive matching
+ // Check for error patterns first (higher priority)
+ if ERROR_PATTERNS
+ .iter()
+ .any(|&pattern| line_lower.contains(&pattern.to_lowercase()))
+ {
+ error!("[{}] {}", pipe_clone, line);
+ sentry::capture_message(
+ &format!("[{}] {}", pipe_clone, line),
+ sentry::Level::Error,
+ );
+ continue;
+ }
- // Quick checks first
- if line.trim().is_empty() || line.contains("console.") {
- info!("[{}] {}", pipe_clone, line);
- continue;
- }
+ // Then check for info patterns
+ if INFO_PATTERNS
+ .iter()
+ .any(|&pattern| line_lower.contains(&pattern.to_lowercase()))
+ {
+ info!("[{}] {}", pipe_clone, line);
+ continue;
+ }
- // Check for error patterns first (higher priority)
- if ERROR_PATTERNS
- .iter()
- .any(|&pattern| line_lower.contains(&pattern.to_lowercase()))
- {
- error!("[{}] {}", pipe_clone, line);
- sentry::capture_message(
- &format!("[{}] {}", pipe_clone, line),
- sentry::Level::Error,
- );
- continue;
- }
+ // Default to warning for unknown patterns
+ warn!("[{}] {}", pipe_clone, line);
+ }
+ });
- // Then check for info patterns
- if INFO_PATTERNS
- .iter()
- .any(|&pattern| line_lower.contains(&pattern.to_lowercase()))
- {
- info!("[{}] {}", pipe_clone, line);
- continue;
- }
+ info!("pipe execution completed successfully [{}]", pipe);
+ Ok(())
+}
- // Default to warning for unknown patterns
- warn!("[{}] {}", pipe_clone, line);
- }
- });
+// Add this helper function for retrying installations
+async fn retry_install(bun_path: &Path, dest_dir: &Path, max_retries: u32) -> Result<()> {
+ let mut attempt = 0;
+ let mut last_error = None;
- info!("pipe execution completed successfully [{}]", pipe);
- Ok(())
- }
+ while attempt < max_retries {
+ let mut install_child = Command::new(bun_path)
+ .arg("i")
+ .current_dir(dest_dir)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()?;
- // Add this helper function for retrying installations
- async fn retry_install(bun_path: &Path, dest_dir: &Path, max_retries: u32) -> Result<()> {
- let mut attempt = 0;
- let mut last_error = None;
-
- while attempt < max_retries {
- let mut install_child = Command::new(bun_path)
- .arg("i")
- .current_dir(dest_dir)
- .stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::piped())
- .spawn()?;
-
- // Stream logs for npm install
- if let Ok(()) = stream_logs("bun install", &mut install_child).await {
- let status = install_child.wait().await?;
- if status.success() {
- return Ok(());
- }
+ // Stream logs for npm install
+ if let Ok(()) = stream_logs("bun install", &mut install_child).await {
+ let status = install_child.wait().await?;
+ if status.success() {
+ return Ok(());
}
-
- attempt += 1;
- let delay = std::time::Duration::from_secs(2u64.pow(attempt)); // exponential backoff
- error!(
- "install attempt {} failed, retrying in {} seconds",
- attempt,
- delay.as_secs()
- );
- tokio::time::sleep(delay).await;
- last_error = Some(anyhow::anyhow!(
- "installation failed after {} attempts",
- attempt
- ));
}
- Err(last_error.unwrap_or_else(|| anyhow::anyhow!("installation failed")))
+ attempt += 1;
+ let delay = std::time::Duration::from_secs(2u64.pow(attempt)); // exponential backoff
+ error!(
+ "install attempt {} failed, retrying in {} seconds",
+ attempt,
+ delay.as_secs()
+ );
+ tokio::time::sleep(delay).await;
+ last_error = Some(anyhow::anyhow!(
+ "installation failed after {} attempts",
+ attempt
+ ));
}
- pub async fn download_pipe(source: &str, screenpipe_dir: PathBuf) -> anyhow::Result<PathBuf> {
- info!("Processing pipe from source: {}", source);
+ Err(last_error.unwrap_or_else(|| anyhow::anyhow!("installation failed")))
+}
+
+pub async fn download_pipe(source: &str, screenpipe_dir: PathBuf) -> anyhow::Result<PathBuf> {
+ info!("Processing pipe from source: {}", source);
- let is_local = Url::parse(source).is_err();
+ let is_local = Url::parse(source).is_err();
- let mut pipe_name =
- sanitize_pipe_name(Path::new(source).file_name().unwrap().to_str().unwrap());
+ let mut pipe_name =
+ sanitize_pipe_name(Path::new(source).file_name().unwrap().to_str().unwrap());
- // Add _local suffix for local pipes
- if is_local {
- pipe_name.push_str("_local");
- }
+ // Add _local suffix for local pipes
+ if is_local {
+ pipe_name.push_str("_local");
+ }
- let dest_dir = screenpipe_dir.join("pipes").join(&pipe_name);
+ let dest_dir = screenpipe_dir.join("pipes").join(&pipe_name);
- debug!("Destination directory: {:?}", dest_dir);
+ debug!("Destination directory: {:?}", dest_dir);
- // Save existing pipe.json content before downloading
- let pipe_json_path = dest_dir.join("pipe.json");
- let existing_config = if pipe_json_path.exists() {
- debug!("Existing pipe.json found");
- let content = tokio::fs::read_to_string(&pipe_json_path).await?;
- Some(serde_json::from_str::<Value>(&content)?)
- } else {
- debug!("No existing pipe.json found");
- None
- };
+ // Save existing pipe.json content before downloading
+ let pipe_json_path = dest_dir.join("pipe.json");
+ let existing_config = if pipe_json_path.exists() {
+ debug!("Existing pipe.json found");
+ let content = tokio::fs::read_to_string(&pipe_json_path).await?;
+ Some(serde_json::from_str::<Value>(&content)?)
+ } else {
+ debug!("No existing pipe.json found");
+ None
+ };
- // Create temp directory for download
- let temp_dir = dest_dir.with_extension("_temp");
- tokio::fs::create_dir_all(&temp_dir).await?;
+ // Create temp directory for download
+ let temp_dir = dest_dir.with_extension("_temp");
+ tokio::fs::create_dir_all(&temp_dir).await?;
- // Download to temp directory first
- let download_result = if let Ok(parsed_url) = Url::parse(source) {
- debug!("Source is a URL: {}", parsed_url);
- if parsed_url.host_str() == Some("github.com") {
- download_github_folder(&parsed_url, &temp_dir).await
- } else {
- anyhow::bail!("Unsupported URL format");
- }
+ // Download to temp directory first
+ let download_result = if let Ok(parsed_url) = Url::parse(source) {
+ debug!("Source is a URL: {}", parsed_url);
+ if parsed_url.host_str() == Some("github.com") {
+ download_github_folder(&parsed_url, &temp_dir).await
} else {
- debug!("Source is a local path");
- let source_path = Path::new(source);
- if !source_path.exists() || !source_path.is_dir() {
- anyhow::bail!("Invalid local source path");
- }
- copy_dir_all(source_path, &temp_dir).await
- };
-
- // remove temp dir if download failed
- if let Err(e) = download_result {
- tokio::fs::remove_dir_all(&temp_dir).await?;
- error!("Failed to download pipe: {}", e);
+ anyhow::bail!("Unsupported URL format");
}
-
- // If download successful, move temp dir to final location
- if dest_dir.exists() {
- tokio::fs::remove_dir_all(&dest_dir).await?;
+ } else {
+ debug!("Source is a local path");
+ let source_path = Path::new(source);
+ if !source_path.exists() || !source_path.is_dir() {
+ anyhow::bail!("Invalid local source path");
}
- tokio::fs::rename(&temp_dir, &dest_dir).await?;
+ copy_dir_all(source_path, &temp_dir).await
+ };
- // Restore or merge pipe.json if needed
- if let Some(ref existing_config) = existing_config {
- let new_config_path = dest_dir.join("pipe.json");
- if new_config_path.exists() {
- let content = tokio::fs::read_to_string(&new_config_path).await?;
- let new_json: Value = serde_json::from_str(&content)?;
+ // remove temp dir if download failed
+ if let Err(e) = download_result {
+ tokio::fs::remove_dir_all(&temp_dir).await?;
+ error!("Failed to download pipe: {}", e);
+ }
- // Create merged config
- let mut merged_config = new_json.clone(); // Start with new schema
+ // If download successful, move temp dir to final location
+ if dest_dir.exists() {
+ tokio::fs::remove_dir_all(&dest_dir).await?;
+ }
+ tokio::fs::rename(&temp_dir, &dest_dir).await?;
- // If both configs have fields array, preserve user values
- if let (Some(existing_obj), Some(new_obj)) =
- (existing_config.as_object(), merged_config.as_object_mut())
- {
- // Copy over non-fields properties from existing config
- for (key, value) in existing_obj {
- if key != "fields" {
- new_obj.insert(key.clone(), value.clone());
- }
+ // Restore or merge pipe.json if needed
+ if let Some(ref existing_config) = existing_config {
+ let new_config_path = dest_dir.join("pipe.json");
+ if new_config_path.exists() {
+ let content = tokio::fs::read_to_string(&new_config_path).await?;
+ let new_json: Value = serde_json::from_str(&content)?;
+
+ // Create merged config
+ let mut merged_config = new_json.clone(); // Start with new schema
+
+ // If both configs have fields array, preserve user values
+ if let (Some(existing_obj), Some(new_obj)) =
+ (existing_config.as_object(), merged_config.as_object_mut())
+ {
+ // Copy over non-fields properties from existing config
+ for (key, value) in existing_obj {
+ if key != "fields" {
+ new_obj.insert(key.clone(), value.clone());
}
+ }
- // For fields array, preserve user values while keeping new schema
- if let (Some(existing_fields), Some(new_fields)) = (
- existing_config["fields"].as_array(),
- new_obj.get_mut("fields").and_then(|f| f.as_array_mut()),
- ) {
- // For each field in the new schema
- for new_field in new_fields {
- if let Some(name) = new_field.get("name").and_then(Value::as_str) {
- // If this field existed in the old config, preserve its value
- if let Some(existing_field) = existing_fields
- .iter()
- .find(|f| f.get("name").and_then(Value::as_str) == Some(name))
- {
- if let Some(user_value) = existing_field.get("value") {
- if let Some(new_field_obj) = new_field.as_object_mut() {
- new_field_obj
- .insert("value".to_string(), user_value.clone());
- }
+ // For fields array, preserve user values while keeping new schema
+ if let (Some(existing_fields), Some(new_fields)) = (
+ existing_config["fields"].as_array(),
+ new_obj.get_mut("fields").and_then(|f| f.as_array_mut()),
+ ) {
+ // For each field in the new schema
+ for new_field in new_fields {
+ if let Some(name) = new_field.get("name").and_then(Value::as_str) {
+ // If this field existed in the old config, preserve its value
+ if let Some(existing_field) = existing_fields
+ .iter()
+ .find(|f| f.get("name").and_then(Value::as_str) == Some(name))
+ {
+ if let Some(user_value) = existing_field.get("value") {
+ if let Some(new_field_obj) = new_field.as_object_mut() {
+ new_field_obj
+ .insert("value".to_string(), user_value.clone());
}
}
}
}
}
}
-
- let config_str = serde_json::to_string_pretty(&merged_config)?;
- tokio::fs::write(&new_config_path, config_str).await?;
- } else {
- // If no new config exists, keep the existing one
- let config_str = serde_json::to_string_pretty(&existing_config)?;
- tokio::fs::write(&new_config_path, config_str).await?;
}
- }
-
- // After downloading/copying the pipe, check if it's a Next.js project
- let package_json_path = dest_dir.join("package.json");
- if package_json_path.exists() {
- let package_json = tokio::fs::read_to_string(&package_json_path).await?;
- let package_data: Value = serde_json::from_str(&package_json)?;
-
- let bun_path = find_bun_path().ok_or_else(|| anyhow::anyhow!("bun not found"))?;
-
- // Make bun install mandatory for all package.json pipes with retries
- retry_install(&bun_path, &dest_dir, 3).await?;
-
- if package_data["dependencies"].get("next").is_some() {
- info!("Detected Next.js project, setting up for production");
- // Update pipe.json to indicate it's a Next.js project
- let mut pipe_config = if let Some(existing_json) = &existing_config {
- existing_json.clone()
- } else if pipe_json_path.exists() {
- let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
- serde_json::from_str(&pipe_json)?
- } else {
- json!({})
- };
- pipe_config["is_nextjs"] = json!(true);
- pipe_config["buildStatus"] = json!("not_started");
- let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
- let mut file = File::create(&pipe_json_path).await?;
- file.write_all(updated_pipe_json.as_bytes()).await?;
- }
+ let config_str = serde_json::to_string_pretty(&merged_config)?;
+ tokio::fs::write(&new_config_path, config_str).await?;
+ } else {
+ // If no new config exists, keep the existing one
+ let config_str = serde_json::to_string_pretty(&existing_config)?;
+ tokio::fs::write(&new_config_path, config_str).await?;
}
-
- info!("pipe copied successfully to: {:?}", dest_dir);
- Ok(dest_dir)
}
- async fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> anyhow::Result<()> {
- let src = src.as_ref();
- let dst = dst.as_ref();
- debug!("copy_dir_all: src={:?}, dst={:?}", src, dst);
+ // After downloading/copying the pipe, check if it's a Next.js project
+ let package_json_path = dest_dir.join("package.json");
+ if package_json_path.exists() {
+ let package_json = tokio::fs::read_to_string(&package_json_path).await?;
+ let package_data: Value = serde_json::from_str(&package_json)?;
- tokio::fs::create_dir_all(&dst).await?;
- debug!("Created destination directory: {:?}", dst);
-
- let mut entries = tokio::fs::read_dir(src).await?;
- debug!("Reading source directory: {:?}", src);
-
- while let Some(entry) = entries.next_entry().await? {
- let ty = entry.file_type().await?;
- let src_path = entry.path();
- let dst_path = dst.join(entry.file_name());
+ let bun_path = find_bun_path().ok_or_else(|| anyhow::anyhow!("bun not found"))?;
- debug!("Processing entry: {:?}", src_path);
+ // Make bun install mandatory for all package.json pipes with retries
+ retry_install(&bun_path, &dest_dir, 3).await?;
- if should_ignore(&entry.file_name()) {
- debug!("Skipping ignored file/directory: {:?}", entry.file_name());
- continue;
- }
-
- if ty.is_dir() {
- debug!("Entry is a directory, recursing: {:?}", src_path);
- copy_dir_all_boxed(src_path, dst_path).await?;
+ if package_data["dependencies"].get("next").is_some() {
+ info!("Detected Next.js project, setting up for production");
+ // Update pipe.json to indicate it's a Next.js project
+ let mut pipe_config = if let Some(existing_json) = &existing_config {
+ existing_json.clone()
+ } else if pipe_json_path.exists() {
+ let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
+ serde_json::from_str(&pipe_json)?
} else {
- debug!("Copying file: {:?} to {:?}", src_path, dst_path);
- tokio::fs::copy(&src_path, &dst_path).await?;
- }
- }
+ json!({})
+ };
- debug!("Finished copying directory: {:?}", src);
- Ok(())
+ pipe_config["is_nextjs"] = json!(true);
+ pipe_config["buildStatus"] = json!("not_started");
+ let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
+ let mut file = File::create(&pipe_json_path).await?;
+ file.write_all(updated_pipe_json.as_bytes()).await?;
+ }
}
- fn copy_dir_all_boxed(
- src: impl AsRef<Path> + Send + 'static,
- dst: impl AsRef<Path> + Send + 'static,
- ) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {
- Box::pin(copy_dir_all(src, dst))
- }
+ info!("pipe copied successfully to: {:?}", dest_dir);
+ Ok(dest_dir)
+}
- fn should_ignore(file_name: &std::ffi::OsStr) -> bool {
- let ignore_list = [
- "node_modules",
- ".git",
- ".next",
- "dist",
- "build",
- ".DS_Store",
- "Thumbs.db",
- ".env",
- ".env.local",
- ".env.development.local",
- ".env.test.local",
- ".env.production.local",
- ];
-
- ignore_list.iter().any(|ignored| file_name == *ignored)
- || file_name.to_str().is_some_and(|s| s.starts_with('.'))
- }
+async fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> anyhow::Result<()> {
+ let src = src.as_ref();
+ let dst = dst.as_ref();
+ debug!("copy_dir_all: src={:?}, dst={:?}", src, dst);
- 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();
-
- Box::pin(async move {
- // Create a cached client
- let client = ClientBuilder::new(Client::new())
- .with(Cache(HttpCache {
- mode: CacheMode::Default,
- manager: CACacheManager {
- path: home_dir()
- .unwrap()
- .join(".screenpipe")
- .join(".http-cacache"),
- },
- options: HttpCacheOptions::default(),
- }))
- .build();
-
- let api_url = get_raw_github_url(url.as_str())?;
- debug!("using github api url: {}", api_url);
-
- let response = client
- .get(&api_url)
- .header("Accept", "application/vnd.github.v3+json")
- .header("User-Agent", "screenpipe")
- .send()
- .await?;
+ tokio::fs::create_dir_all(&dst).await?;
+ debug!("Created destination directory: {:?}", dst);
- debug!(
- "GitHub API cache hit: {:?}",
- response.headers().get("x-cache")
- );
+ let mut entries = tokio::fs::read_dir(src).await?;
+ debug!("Reading source directory: {:?}", src);
- let contents: Value = response.text().await?.parse()?;
- let tree = contents["tree"]
- .as_array()
- .ok_or_else(|| anyhow::anyhow!("invalid response from github api"))?;
+ while let Some(entry) = entries.next_entry().await? {
+ let ty = entry.file_type().await?;
+ let src_path = entry.path();
+ let dst_path = dst.join(entry.file_name());
- // Extract repo info from URL
- let path_segments: Vec<&str> = url.path_segments().unwrap().collect();
- let (owner, repo, _, branch) = (
- path_segments[0],
- path_segments[1],
- path_segments[2],
- path_segments[3],
- );
+ debug!("Processing entry: {:?}", src_path);
- // Extract the base path for subfolder downloads
- let base_path = url
- .path_segments()
- .and_then(|segments| {
- let segments: Vec<_> = segments.collect();
- if segments.len() >= 5 && segments[2] == "tree" {
- Some(segments[4..].join("/"))
- } else {
- None
- }
- })
- .unwrap_or_default();
+ if should_ignore(&entry.file_name()) {
+ debug!("Skipping ignored file/directory: {:?}", entry.file_name());
+ continue;
+ }
+
+ if ty.is_dir() {
+ debug!("Entry is a directory, recursing: {:?}", src_path);
+ copy_dir_all_boxed(src_path, dst_path).await?;
+ } else {
+ debug!("Copying file: {:?} to {:?}", src_path, dst_path);
+ tokio::fs::copy(&src_path, &dst_path).await?;
+ }
+ }
- debug!("base path for download: {}", base_path);
+ debug!("Finished copying directory: {:?}", src);
+ Ok(())
+}
- // Process all files in parallel
- let mut tasks = Vec::new();
+fn copy_dir_all_boxed(
+ src: impl AsRef<Path> + Send + 'static,
+ dst: impl AsRef<Path> + Send + 'static,
+) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {
+ Box::pin(copy_dir_all(src, dst))
+}
- for item in tree {
- let path = item["path"]
- .as_str()
- .ok_or_else(|| anyhow::anyhow!("missing path in github response"))?;
+fn should_ignore(file_name: &std::ffi::OsStr) -> bool {
+ let ignore_list = [
+ "node_modules",
+ ".git",
+ ".next",
+ "dist",
+ "build",
+ ".DS_Store",
+ "Thumbs.db",
+ ".env",
+ ".env.local",
+ ".env.development.local",
+ ".env.test.local",
+ ".env.production.local",
+ ];
+
+ ignore_list.iter().any(|ignored| file_name == *ignored)
+ || file_name.to_str().is_some_and(|s| s.starts_with('.'))
+}
- // Skip if file is not in the target directory
- if !path.starts_with(&base_path) {
- continue;
- }
+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();
+
+ Box::pin(async move {
+ // Create a cached client
+ let client = ClientBuilder::new(Client::new())
+ .with(Cache(HttpCache {
+ mode: CacheMode::Default,
+ manager: CACacheManager {
+ path: home_dir()
+ .unwrap()
+ .join(".screenpipe")
+ .join(".http-cacache"),
+ },
+ options: HttpCacheOptions::default(),
+ }))
+ .build();
+
+ let api_url = get_raw_github_url(url.as_str())?;
+ debug!("using github api url: {}", api_url);
+
+ let response = client
+ .get(&api_url)
+ .header("Accept", "application/vnd.github.v3+json")
+ .header("User-Agent", "screenpipe")
+ .send()
+ .await?;
- let file_name = Path::new(path)
- .file_name()
- .ok_or_else(|| anyhow::anyhow!("invalid path"))?;
+ debug!(
+ "GitHub API cache hit: {:?}",
+ response.headers().get("x-cache")
+ );
- // Skip hidden files and ignored directories
- if should_ignore(file_name) {
- debug!("skipping ignored file/directory: {}", path);
- continue;
+ let contents: Value = response.text().await?.parse()?;
+ let tree = contents["tree"]
+ .as_array()
+ .ok_or_else(|| anyhow::anyhow!("invalid response from github api"))?;
+
+ // Extract repo info from URL
+ let path_segments: Vec<&str> = url.path_segments().unwrap().collect();
+ let (owner, repo, _, branch) = (
+ path_segments[0],
+ path_segments[1],
+ path_segments[2],
+ path_segments[3],
+ );
+
+ // Extract the base path for subfolder downloads
+ let base_path = url
+ .path_segments()
+ .and_then(|segments| {
+ let segments: Vec<_> = segments.collect();
+ if segments.len() >= 5 && segments[2] == "tree" {
+ Some(segments[4..].join("/"))
+ } else {
+ None
}
+ })
+ .unwrap_or_default();
- let item_type = item["type"]
- .as_str()
- .ok_or_else(|| anyhow::anyhow!("missing type in github response"))?;
-
- if item_type == "blob" {
- // Calculate relative path from base_path
- let relative_path = if let Some(stripped) = path.strip_prefix(&base_path) {
- stripped.trim_start_matches('/')
- } else {
- path
- };
-
- let file_dest = dest_dir.join(relative_path);
- let client = client.clone();
-
- // Use raw.githubusercontent.com URL
- let raw_url = format!(
- "https://raw.githubusercontent.com/{}/{}/{}/{}",
- owner, repo, branch, path
- );
+ debug!("base path for download: {}", base_path);
- // Create task for parallel download
- tasks.push(tokio::spawn(async move {
- if let Some(parent) = file_dest.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
+ // Process all files in parallel
+ let mut tasks = Vec::new();
- let file_content = client.get(&raw_url).send().await?.bytes().await?;
- tokio::fs::write(&file_dest, &file_content).await?;
- debug!("downloaded file: {:?}", file_dest);
- Ok::<_, anyhow::Error>(())
- }));
- }
+ for item in tree {
+ let path = item["path"]
+ .as_str()
+ .ok_or_else(|| anyhow::anyhow!("missing path in github response"))?;
+
+ // Skip if file is not in the target directory
+ if !path.starts_with(&base_path) {
+ continue;
}
- // Wait for all downloads to complete
- for task in tasks {
- task.await??;
+ let file_name = Path::new(path)
+ .file_name()
+ .ok_or_else(|| anyhow::anyhow!("invalid path"))?;
+
+ // Skip hidden files and ignored directories
+ if should_ignore(file_name) {
+ debug!("skipping ignored file/directory: {}", path);
+ continue;
}
- Ok(())
- })
- }
+ let item_type = item["type"]
+ .as_str()
+ .ok_or_else(|| anyhow::anyhow!("missing type in github response"))?;
- fn get_raw_github_url(url: &str) -> anyhow::Result<String> {
- debug!("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],
- );
+ if item_type == "blob" {
+ // Calculate relative path from base_path
+ let relative_path = if let Some(stripped) = path.strip_prefix(&base_path) {
+ stripped.trim_start_matches('/')
+ } else {
+ path
+ };
+
+ let file_dest = dest_dir.join(relative_path);
+ let client = client.clone();
+
+ // Use raw.githubusercontent.com URL
let raw_url = format!(
- "https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1",
- owner, repo, branch
+ "https://raw.githubusercontent.com/{}/{}/{}/{}",
+ owner, repo, branch, path
);
- debug!("Converted to GitHub API URL: {}", raw_url);
- return Ok(raw_url);
+
+ // Create task for parallel download
+ tasks.push(tokio::spawn(async move {
+ if let Some(parent) = file_dest.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let file_content = client.get(&raw_url).send().await?.bytes().await?;
+ tokio::fs::write(&file_dest, &file_content).await?;
+ debug!("downloaded file: {:?}", file_dest);
+ Ok::<_, anyhow::Error>(())
+ }));
}
}
- anyhow::bail!("Invalid GitHub URL format")
- }
- fn find_pipe_file(pipe_dir: &Path) -> anyhow::Result<PathBuf> {
- for entry in 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 == "pipe.js" || file_name_str == "pipe.ts")
- && !is_hidden_file(&file_name)
- {
- return Ok(entry.path());
- }
+ // Wait for all downloads to complete
+ for task in tasks {
+ task.await??;
+ }
+
+ Ok(())
+ })
+}
+
+fn get_raw_github_url(url: &str) -> anyhow::Result<String> {
+ debug!("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_url = format!(
+ "https://api.github.com/repos/{}/{}/git/trees/{}?recursive=1",
+ owner, repo, branch
+ );
+ debug!("Converted to GitHub API URL: {}", raw_url);
+ return Ok(raw_url);
}
- anyhow::bail!("No pipe.js/pipe.ts found in the pipe/dist directory")
}
+ anyhow::bail!("Invalid GitHub URL format")
+}
- fn is_hidden_file(file_name: &std::ffi::OsStr) -> bool {
- file_name
- .to_str()
- .map(|s| s.starts_with('.') || s == "Thumbs.db")
- .unwrap_or(false)
+fn find_pipe_file(pipe_dir: &Path) -> anyhow::Result<PathBuf> {
+ for entry in 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 == "pipe.js" || file_name_str == "pipe.ts") && !is_hidden_file(&file_name)
+ {
+ return Ok(entry.path());
+ }
}
+ anyhow::bail!("No pipe.js/pipe.ts found in the pipe/dist directory")
+}
- #[cfg(not(windows))]
- const BUN_EXECUTABLE_NAME: &str = "bun";
+fn is_hidden_file(file_name: &std::ffi::OsStr) -> bool {
+ file_name
+ .to_str()
+ .map(|s| s.starts_with('.') || s == "Thumbs.db")
+ .unwrap_or(false)
+}
- #[cfg(windows)]
- const BUN_EXECUTABLE_NAME: &str = "bun.exe";
+#[cfg(not(windows))]
+const BUN_EXECUTABLE_NAME: &str = "bun";
- static BUN_PATH: Lazy<Option<PathBuf>> = Lazy::new(find_bun_path_internal);
+#[cfg(windows)]
+const BUN_EXECUTABLE_NAME: &str = "bun.exe";
- pub fn find_bun_path() -> Option<PathBuf> {
- BUN_PATH.as_ref().map(|p| p.clone())
- }
+static BUN_PATH: Lazy<Option<PathBuf>> = Lazy::new(find_bun_path_internal);
- fn find_bun_path_internal() -> Option<PathBuf> {
- debug!("starting search for bun executable");
-
- // Check in executable directory (eg tauri etc.)
- if let Ok(exe_path) = std::env::current_exe() {
- if let Some(exe_folder) = exe_path.parent() {
- debug!("executable folder: {:?}", exe_folder);
- let bun_in_exe_folder = exe_folder.join(BUN_EXECUTABLE_NAME);
- if bun_in_exe_folder.exists() {
- debug!("found bun in executable folder: {:?}", bun_in_exe_folder);
- return Some(bun_in_exe_folder);
- }
- debug!("bun not found in executable folder");
+pub fn find_bun_path() -> Option<PathBuf> {
+ BUN_PATH.as_ref().map(|p| p.clone())
+}
- // Platform-specific checks
- #[cfg(target_os = "macos")]
- {
- let resources_folder = exe_folder.join("../Resources");
- debug!("resources folder: {:?}", resources_folder);
- let bun_in_resources = resources_folder.join(BUN_EXECUTABLE_NAME);
- if bun_in_resources.exists() {
- debug!("found bun in resources folder: {:?}", bun_in_resources);
- return Some(bun_in_resources);
- }
- debug!("bun not found in resources folder");
- }
+fn find_bun_path_internal() -> Option<PathBuf> {
+ debug!("starting search for bun executable");
+
+ // Check in executable directory (eg tauri etc.)
+ if let Ok(exe_path) = std::env::current_exe() {
+ if let Some(exe_folder) = exe_path.parent() {
+ debug!("executable folder: {:?}", exe_folder);
+ let bun_in_exe_folder = exe_folder.join(BUN_EXECUTABLE_NAME);
+ if bun_in_exe_folder.exists() {
+ debug!("found bun in executable folder: {:?}", bun_in_exe_folder);
+ return Some(bun_in_exe_folder);
+ }
+ debug!("bun not found in executable folder");
- #[cfg(target_os = "linux")]
- {
- let lib_folder = exe_folder.join("lib");
- debug!("lib folder: {:?}", lib_folder);
- let bun_in_lib = lib_folder.join(BUN_EXECUTABLE_NAME);
- if bun_in_lib.exists() {
- debug!("found bun in lib folder: {:?}", bun_in_lib);
- return Some(bun_in_lib);
- }
- debug!("bun not found in lib folder");
+ // Platform-specific checks
+ #[cfg(target_os = "macos")]
+ {
+ let resources_folder = exe_folder.join("../Resources");
+ debug!("resources folder: {:?}", resources_folder);
+ let bun_in_resources = resources_folder.join(BUN_EXECUTABLE_NAME);
+ if bun_in_resources.exists() {
+ debug!("found bun in resources folder: {:?}", bun_in_resources);
+ return Some(bun_in_resources);
}
+ debug!("bun not found in resources folder");
}
- }
- // Check if bun is in PATH
- if let Ok(path) = which(BUN_EXECUTABLE_NAME) {
- debug!("found bun in PATH: {:?}", path);
- return Some(path);
- }
- debug!("bun not found in PATH");
-
- // Check in current working directory
- if let Ok(cwd) = std::env::current_dir() {
- debug!("current working directory: {:?}", cwd);
- let bun_in_cwd = cwd.join(BUN_EXECUTABLE_NAME);
- if bun_in_cwd.is_file() && bun_in_cwd.exists() {
- debug!("found bun in current working directory: {:?}", bun_in_cwd);
- return Some(bun_in_cwd);
+ #[cfg(target_os = "linux")]
+ {
+ let lib_folder = exe_folder.join("lib");
+ debug!("lib folder: {:?}", lib_folder);
+ let bun_in_lib = lib_folder.join(BUN_EXECUTABLE_NAME);
+ if bun_in_lib.exists() {
+ debug!("found bun in lib folder: {:?}", bun_in_lib);
+ return Some(bun_in_lib);
+ }
+ debug!("bun not found in lib folder");
}
- debug!("bun not found in current working directory");
}
-
- error!("bun not found");
- None
}
- // Add this function to handle cron state persistence
- pub async fn get_last_cron_execution(
- pipe_dir: &Path,
- path: &str,
- ) -> Result<Option<SystemTime>> {
- let state_file = pipe_dir.join(".cron_state.json");
-
- if !state_file.exists() {
- return Ok(None);
+ // Check if bun is in PATH
+ if let Ok(path) = which(BUN_EXECUTABLE_NAME) {
+ debug!("found bun in PATH: {:?}", path);
+ return Some(path);
+ }
+ debug!("bun not found in PATH");
+
+ // Check in current working directory
+ if let Ok(cwd) = std::env::current_dir() {
+ debug!("current working directory: {:?}", cwd);
+ let bun_in_cwd = cwd.join(BUN_EXECUTABLE_NAME);
+ if bun_in_cwd.is_file() && bun_in_cwd.exists() {
+ debug!("found bun in current working directory: {:?}", bun_in_cwd);
+ return Some(bun_in_cwd);
}
+ debug!("bun not found in current working directory");
+ }
- let content = tokio::fs::read_to_string(state_file).await?;
- let state: Value = serde_json::from_str(&content)?;
+ error!("bun not found");
+ None
+}
- if let Some(last_run) = state.get(path).and_then(|v| v.as_u64()) {
- Ok(Some(UNIX_EPOCH + std::time::Duration::from_secs(last_run)))
- } else {
- Ok(None)
- }
+// Add this function to handle cron state persistence
+pub async fn get_last_cron_execution(pipe_dir: &Path, path: &str) -> Result<Option<SystemTime>> {
+ let state_file = pipe_dir.join(".cron_state.json");
+
+ if !state_file.exists() {
+ return Ok(None);
}
- // Add this function to save cron execution time
- pub async fn save_cron_execution(pipe_dir: &Path, path: &str) -> Result<()> {
- let state_file = pipe_dir.join(".cron_state.json");
+ let content = tokio::fs::read_to_string(state_file).await?;
+ let state: Value = serde_json::from_str(&content)?;
- let mut state: Value = if state_file.exists() {
- let content = tokio::fs::read_to_string(&state_file).await?;
- serde_json::from_str(&content)?
- } else {
- json!({})
- };
+ if let Some(last_run) = state.get(path).and_then(|v| v.as_u64()) {
+ Ok(Some(UNIX_EPOCH + std::time::Duration::from_secs(last_run)))
+ } else {
+ Ok(None)
+ }
+}
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap()
- .as_secs();
+// Add this function to save cron execution time
+pub async fn save_cron_execution(pipe_dir: &Path, path: &str) -> Result<()> {
+ let state_file = pipe_dir.join(".cron_state.json");
- if let Some(obj) = state.as_object_mut() {
- obj.insert(path.to_string(), json!(now));
- }
+ let mut state: Value = if state_file.exists() {
+ let content = tokio::fs::read_to_string(&state_file).await?;
+ serde_json::from_str(&content)?
+ } else {
+ json!({})
+ };
- let mut file = tokio::fs::OpenOptions::new()
- .write(true)
- .create(true)
- .truncate(true)
- .open(state_file)
- .await?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
- file.write_all(serde_json::to_string_pretty(&state)?.as_bytes())
- .await?;
- Ok(())
+ if let Some(obj) = state.as_object_mut() {
+ obj.insert(path.to_string(), json!(now));
}
- // Update the run_cron_schedule function
- async fn run_cron_schedule(
- pipe: &str,
- base_url: &str,
- path: &str,
- secret: &str,
- schedule: &str,
- screenpipe_dir: &Path,
- mut shutdown: watch::Receiver<bool>,
- ) {
- let schedule = match cron::Schedule::from_str(schedule) {
- Ok(s) => s,
+ let mut file = tokio::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(state_file)
+ .await?;
+
+ file.write_all(serde_json::to_string_pretty(&state)?.as_bytes())
+ .await?;
+ Ok(())
+}
+
+// Update the run_cron_schedule function
+async fn run_cron_schedule(
+ pipe: &str,
+ base_url: &str,
+ path: &str,
+ secret: &str,
+ schedule: &str,
+ screenpipe_dir: &Path,
+ mut shutdown: watch::Receiver<bool>,
+) {
+ let schedule = match cron::Schedule::from_str(schedule) {
+ Ok(s) => s,
+ Err(e) => {
+ let err_msg = format!("invalid cron schedule: {}", e);
+ error!("{}", err_msg);
+ sentry::capture_error(&anyhow::anyhow!(err_msg).source().unwrap());
+ return;
+ }
+ };
+
+ let client = Client::new();
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ AUTHORIZATION,
+ HeaderValue::from_str(&format!("Bearer {}", secret)).unwrap(),
+ );
+
+ // Get pipe directory for state persistence
+ let pipe_dir = screenpipe_dir.join("pipes").join(pipe);
+
+ loop {
+ // Get last execution time at the start of each loop
+ let last_run = match get_last_cron_execution(&pipe_dir, path).await {
+ Ok(time) => time,
Err(e) => {
- let err_msg = format!("invalid cron schedule: {}", e);
- error!("{}", err_msg);
- sentry::capture_error(&anyhow::anyhow!(err_msg).source().unwrap());
- return;
+ error!("failed to get last cron execution: {}", e);
+ None
}
};
- let client = Client::new();
- let mut headers = HeaderMap::new();
- headers.insert(
- AUTHORIZATION,
- HeaderValue::from_str(&format!("Bearer {}", secret)).unwrap(),
- );
-
- // Get pipe directory for state persistence
- let pipe_dir = screenpipe_dir.join("pipes").join(pipe);
-
- loop {
- // Get last execution time at the start of each loop
- let last_run = match get_last_cron_execution(&pipe_dir, path).await {
- Ok(time) => time,
- Err(e) => {
- error!("failed to get last cron execution: {}", e);
- None
- }
- };
-
- let now = chrono::Local::now();
- let next = if let Some(last) = last_run {
- // Get next occurrence after the last execution
- let last_chrono = chrono::DateTime::<chrono::Local>::from(last);
- schedule.after(&last_chrono).next()
- } else {
- schedule.after(&now).next()
- };
+ let now = chrono::Local::now();
+ let next = if let Some(last) = last_run {
+ // Get next occurrence after the last execution
+ let last_chrono = chrono::DateTime::<chrono::Local>::from(last);
+ schedule.after(&last_chrono).next()
+ } else {
+ schedule.after(&now).next()
+ };
- let next = match next {
- Some(next) => next,
- None => {
- error!("no next execution time found for cron schedule");
- break;
- }
- };
+ let next = match next {
+ Some(next) => next,
+ None => {
+ error!("no next execution time found for cron schedule");
+ break;
+ }
+ };
- if next <= now {
- info!(
- "next execution time is before or equal to the current time, recalculating..."
- );
- continue;
+ if next <= now {
+ info!("next execution time is before or equal to the current time, recalculating...");
+ continue;
+ }
+ let duration = match (next - now).to_std() {
+ Ok(duration) => duration,
+ Err(e) => {
+ error!("invalid duration: {}", e);
+ continue; // falling back to minute is messing with cron schedule
}
- let duration = match (next - now).to_std() {
- Ok(duration) => duration,
- Err(e) => {
- error!("invalid duration: {}", e);
- continue; // falling back to minute is messing with cron schedule
- }
- };
+ };
- info!(
- "next cron execution for pipe {} at path {} in {} seconds",
- pipe,
- path,
- duration.as_secs()
- );
+ info!(
+ "next cron execution for pipe {} at path {} in {} seconds",
+ pipe,
+ path,
+ duration.as_secs()
+ );
- // Wait for either the next execution time or shutdown signal
- tokio::select! {
- _ = tokio::time::sleep(duration) => {
- info!("executing cron job for pipe {} at path {}", pipe, path);
- match client
- .get(format!("{}{}", base_url, path))
- .headers(headers.clone())
- .send()
- .await
- {
- Ok(res) => {
- if !res.status().is_success() {
- let err_msg = format!("cron job failed with status: {}", res.status());
- error!("{}", err_msg);
- if let Ok(text) = res.text().await {
- error!("error response: {}", text);
- sentry::capture_message(
- &format!("{}: {}", err_msg, text),
- sentry::Level::Error
- );
- } else {
- sentry::capture_message(&err_msg, sentry::Level::Error);
- }
- }
- }
- Err(e) => {
- let err_msg = format!("failed to execute cron job: {}", e);
+ // Wait for either the next execution time or shutdown signal
+ tokio::select! {
+ _ = tokio::time::sleep(duration) => {
+ info!("executing cron job for pipe {} at path {}", pipe, path);
+ match client
+ .get(format!("{}{}", base_url, path))
+ .headers(headers.clone())
+ .send()
+ .await
+ {
+ Ok(res) => {
+ if !res.status().is_success() {
+ let err_msg = format!("cron job failed with status: {}", res.status());
error!("{}", err_msg);
- sentry::capture_error(&e);
+ if let Ok(text) = res.text().await {
+ error!("error response: {}", text);
+ sentry::capture_message(
+ &format!("{}: {}", err_msg, text),
+ sentry::Level::Error
+ );
+ } else {
+ sentry::capture_message(&err_msg, sentry::Level::Error);
+ }
}
}
- }
- Ok(()) = shutdown.changed() => {
- if *shutdown.borrow() {
- info!("shutting down cron job for pipe at path: {}", path);
- break;
+ Err(e) => {
+ let err_msg = format!("failed to execute cron job: {}", e);
+ error!("{}", err_msg);
+ sentry::capture_error(&e);
}
}
}
- }
- }
-
- pub async fn cleanup_pipe_crons(pipe: &str) -> Result<()> {
- if let Some(handles) = CRON_HANDLES.lock().await.remove(pipe) {
- info!("cleaning up {} cron jobs for pipe {}", handles.len(), pipe);
- for handle in handles {
- handle.stop();
+ Ok(()) = shutdown.changed() => {
+ if *shutdown.borrow() {
+ info!("shutting down cron job for pipe at path: {}", path);
+ break;
+ }
}
- info!("stopped all cron jobs for pipe: {}", pipe);
}
- Ok(())
}
+}
- async fn try_build_nextjs(pipe_dir: &Path, bun_path: &Path) -> Result<BuildStatus> {
- info!(
- "checking if i need to build the next.js project in: {:?}",
- pipe_dir
- );
-
- // Check if build already exists and is valid
- let build_dir = pipe_dir.join(".next");
- if build_dir.exists() {
- let build_manifest = build_dir.join("build-manifest.json");
- if build_manifest.exists() {
- info!("found existing next.js build, skipping rebuild");
- return Ok(BuildStatus::Success);
- }
- // Invalid/incomplete build directory - remove it
- debug!("removing invalid next.js build directory");
- tokio::fs::remove_dir_all(&build_dir).await?;
+pub async fn cleanup_pipe_crons(pipe: &str) -> Result<()> {
+ if let Some(handles) = CRON_HANDLES.lock().await.remove(pipe) {
+ info!("cleaning up {} cron jobs for pipe {}", handles.len(), pipe);
+ for handle in handles {
+ handle.stop();
}
+ info!("stopped all cron jobs for pipe: {}", pipe);
+ }
+ Ok(())
+}
- // Update build status to InProgress in pipe.json
- let pipe_json_path = pipe_dir.join("pipe.json");
- if pipe_json_path.exists() {
- let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
- let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
- pipe_config["buildStatus"] = json!("in_progress");
- let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
- tokio::fs::write(&pipe_json_path, updated_pipe_json).await?;
- }
-
- info!("running next.js build");
- let build_output = Command::new(bun_path)
- .arg("run")
- .arg("--bun")
- .arg("build")
- .current_dir(pipe_dir)
- .output()
- .await?;
-
- if build_output.status.success() {
- info!("next.js build completed successfully");
- Ok(BuildStatus::Success)
- } else {
- let error_message = String::from_utf8_lossy(&build_output.stderr).to_string();
- error!("next.js build failed: {}", error_message);
- Ok(BuildStatus::Failed(error_message))
+async fn try_build_nextjs(pipe_dir: &Path, bun_path: &Path) -> Result<BuildStatus> {
+ info!(
+ "checking if i need to build the next.js project in: {:?}",
+ pipe_dir
+ );
+
+ // Check if build already exists and is valid
+ let build_dir = pipe_dir.join(".next");
+ if build_dir.exists() {
+ let build_manifest = build_dir.join("build-manifest.json");
+ if build_manifest.exists() {
+ info!("found existing next.js build, skipping rebuild");
+ return Ok(BuildStatus::Success);
}
+ // Invalid/incomplete build directory - remove it
+ debug!("removing invalid next.js build directory");
+ tokio::fs::remove_dir_all(&build_dir).await?;
}
- // Add this helper function to check if a port is available
- fn is_port_available(port: u16) -> bool {
- use std::net::TcpListener;
- TcpListener::bind(("127.0.0.1", port)).is_ok()
+ // Update build status to InProgress in pipe.json
+ let pipe_json_path = pipe_dir.join("pipe.json");
+ if pipe_json_path.exists() {
+ let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
+ let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
+ pipe_config["buildStatus"] = json!("in_progress");
+ let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
+ tokio::fs::write(&pipe_json_path, updated_pipe_json).await?;
}
- pub async fn download_pipe_private(
- pipe_name: &str,
- source: &str,
- screenpipe_dir: PathBuf,
- ) -> anyhow::Result<PathBuf> {
- info!("processing private pipe from zip: {}", source);
-
- let dest_dir = screenpipe_dir.join("pipes").join(&pipe_name);
- debug!("destination directory: {:?}", dest_dir);
-
- // Create temp directory for download
- let temp_dir = dest_dir.with_extension("_temp");
- tokio::fs::create_dir_all(&temp_dir).await?;
-
- // Create initial pipe.json in temp directory with download status
- let temp_pipe_json = temp_dir.join("pipe.json");
- let initial_config = json!({
- "buildStatus": {
- "status": "in_progress",
- "step": "downloading",
- }
- });
- tokio::fs::write(
- &temp_pipe_json,
- serde_json::to_string_pretty(&initial_config)?,
- )
+ info!("running next.js build");
+ let build_output = Command::new(bun_path)
+ .arg("run")
+ .arg("--bun")
+ .arg("build")
+ .current_dir(pipe_dir)
+ .output()
.await?;
- // Helper function to update build status
- async fn update_build_status(
- path: &Path,
- status: &str,
- step: &str,
- error: Option<&str>,
- ) -> anyhow::Result<()> {
- if path.exists() {
- let pipe_json = tokio::fs::read_to_string(path).await?;
- let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
- pipe_config["buildStatus"] = match error {
- Some(err) => json!({
- "status": status,
- "step": step,
- "error": err
- }),
- None => json!({
- "status": status,
- "step": step
- }),
- };
- let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
- tokio::fs::write(path, updated_pipe_json).await?;
- }
- Ok(())
- }
+ if build_output.status.success() {
+ info!("next.js build completed successfully");
+ Ok(BuildStatus::Success)
+ } else {
+ let error_message = String::from_utf8_lossy(&build_output.stderr).to_string();
+ error!("next.js build failed: {}", error_message);
+ Ok(BuildStatus::Failed(error_message))
+ }
+}
- // Cleanup function
- async fn cleanup_temp(temp_dir: &Path, temp_zip: &Path) -> anyhow::Result<()> {
- if temp_zip.exists() {
- if let Err(e) = tokio::fs::remove_file(temp_zip).await {
- warn!("Failed to remove temporary zip file: {}", e);
- }
- }
- if temp_dir.exists() {
- if let Err(e) = tokio::fs::remove_dir_all(temp_dir).await {
- warn!("Failed to remove temporary directory: {}", e);
- }
- }
- Ok(())
- }
+// Add this helper function to check if a port is available
+fn is_port_available(port: u16) -> bool {
+ use std::net::TcpListener;
+ TcpListener::bind(("127.0.0.1", port)).is_ok()
+}
- // Download zip file
- debug!("downloading zip file from: {}", source);
- let client = Client::new();
- let response = match client.get(source).send().await {
- Ok(res) => res,
- Err(e) => {
- let err_msg = format!("Failed to download zip: {}", e);
- error!("{}", err_msg);
- cleanup_temp(&temp_dir, &temp_dir.join("temp.zip")).await?;
- return Err(anyhow::anyhow!(err_msg));
- }
- };
+pub async fn download_pipe_private(
+ pipe_name: &str,
+ source: &str,
+ screenpipe_dir: PathBuf,
+) -> anyhow::Result<PathBuf> {
+ info!("processing private pipe from zip: {}", source);
+
+ let dest_dir = screenpipe_dir.join("pipes").join(&pipe_name);
+ debug!("destination directory: {:?}", dest_dir);
+
+ // Create temp directory for download
+ let temp_dir = dest_dir.with_extension("_temp");
+ tokio::fs::create_dir_all(&temp_dir).await?;
+
+ // Create initial pipe.json in temp directory with download status
+ let temp_pipe_json = temp_dir.join("pipe.json");
+ let initial_config = json!({
+ "buildStatus": {
+ "status": "in_progress",
+ "step": "downloading",
+ }
+ });
+ tokio::fs::write(
+ &temp_pipe_json,
+ serde_json::to_string_pretty(&initial_config)?,
+ )
+ .await?;
+
+ // Helper function to update build status
+ async fn update_build_status(
+ path: &Path,
+ status: &str,
+ step: &str,
+ error: Option<&str>,
+ ) -> anyhow::Result<()> {
+ if path.exists() {
+ let pipe_json = tokio::fs::read_to_string(path).await?;
+ let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
+ pipe_config["buildStatus"] = match error {
+ Some(err) => json!({
+ "status": status,
+ "step": step,
+ "error": err
+ }),
+ None => json!({
+ "status": status,
+ "step": step
+ }),
+ };
+ let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
+ tokio::fs::write(path, updated_pipe_json).await?;
+ }
+ Ok(())
+ }
- let zip_content = match response.bytes().await {
- Ok(content) => content,
- Err(e) => {
- let err_msg = format!("Failed to read zip content: {}", e);
- error!("{}", err_msg);
- cleanup_temp(&temp_dir, &temp_dir.join("temp.zip")).await?;
- return Err(anyhow::anyhow!(err_msg));
+ // Cleanup function
+ async fn cleanup_temp(temp_dir: &Path, temp_zip: &Path) -> anyhow::Result<()> {
+ if temp_zip.exists() {
+ if let Err(e) = tokio::fs::remove_file(temp_zip).await {
+ warn!("Failed to remove temporary zip file: {}", e);
}
- };
-
- // Create temporary zip file
- let temp_zip = temp_dir.join("temp.zip");
- if let Err(e) = tokio::fs::write(&temp_zip, &zip_content).await {
- let err_msg = format!("Failed to write temporary zip file: {}", e);
- error!("{}", err_msg);
- cleanup_temp(&temp_dir, &temp_zip).await?;
- return Err(anyhow::anyhow!(err_msg));
}
-
- // Update status before extraction
- let temp_pipe_json = temp_dir.join("pipe.json");
- update_build_status(&temp_pipe_json, "in_progress", "extracting", None).await?;
-
- // Unzip the file
- debug!("unzipping file to temp directory");
- let temp_zip_path = temp_zip.clone();
- let temp_dir_path = temp_dir.clone();
-
- let extraction_result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
- let zip_file = std::fs::File::open(&temp_zip_path)?;
- let mut archive = zip::ZipArchive::new(zip_file)?;
- let total_files = archive.len();
-
- for i in 0..total_files {
- let mut file = archive.by_index(i)?;
- let name = file.name().to_string();
-
- // Check for zip slip vulnerability
- if name.contains("..") {
- return Err(anyhow::anyhow!(
- "Invalid zip file: potential path traversal attack"
- ));
- }
-
- let outpath = temp_dir_path.join(&name);
- if name.ends_with('/') {
- std::fs::create_dir_all(&outpath)?;
- } else {
- if let Some(p) = outpath.parent() {
- if !p.exists() {
- std::fs::create_dir_all(p)?;
- }
- }
- let mut outfile = std::fs::File::create(&outpath)?;
- std::io::copy(&mut file, &mut outfile)?;
- }
+ if temp_dir.exists() {
+ if let Err(e) = tokio::fs::remove_dir_all(temp_dir).await {
+ warn!("Failed to remove temporary directory: {}", e);
}
- Ok(())
- })
- .await;
+ }
+ Ok(())
+ }
- // Handle extraction errors
- if let Err(e) = extraction_result {
- let err_msg = format!("Extraction task failed: {}", e);
+ // Download zip file
+ debug!("downloading zip file from: {}", source);
+ let client = Client::new();
+ let response = match client.get(source).send().await {
+ Ok(res) => res,
+ Err(e) => {
+ let err_msg = format!("Failed to download zip: {}", e);
error!("{}", err_msg);
- update_build_status(&temp_pipe_json, "error", "extracting", Some(&err_msg)).await?;
- cleanup_temp(&temp_dir, &temp_zip).await?;
+ cleanup_temp(&temp_dir, &temp_dir.join("temp.zip")).await?;
return Err(anyhow::anyhow!(err_msg));
}
+ };
- if let Err(e) = extraction_result.unwrap() {
- let err_msg = format!("Failed to extract zip: {}", e);
+ let zip_content = match response.bytes().await {
+ Ok(content) => content,
+ Err(e) => {
+ let err_msg = format!("Failed to read zip content: {}", e);
error!("{}", err_msg);
- update_build_status(&temp_pipe_json, "error", "extracting", Some(&err_msg)).await?;
- cleanup_temp(&temp_dir, &temp_zip).await?;
+ cleanup_temp(&temp_dir, &temp_dir.join("temp.zip")).await?;
return Err(anyhow::anyhow!(err_msg));
}
+ };
+
+ // Create temporary zip file
+ let temp_zip = temp_dir.join("temp.zip");
+ if let Err(e) = tokio::fs::write(&temp_zip, &zip_content).await {
+ let err_msg = format!("Failed to write temporary zip file: {}", e);
+ error!("{}", err_msg);
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
- // Remove the temporary zip file
- if let Err(e) = tokio::fs::remove_file(&temp_zip).await {
- warn!("Failed to remove temporary zip file: {}", e);
- }
+ // Update status before extraction
+ let temp_pipe_json = temp_dir.join("pipe.json");
+ update_build_status(&temp_pipe_json, "in_progress", "extracting", None).await?;
+
+ // Unzip the file
+ debug!("unzipping file to temp directory");
+ let temp_zip_path = temp_zip.clone();
+ let temp_dir_path = temp_dir.clone();
+
+ let extraction_result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
+ let zip_file = std::fs::File::open(&temp_zip_path)?;
+ let mut archive = zip::ZipArchive::new(zip_file)?;
+ let total_files = archive.len();
+
+ for i in 0..total_files {
+ let mut file = archive.by_index(i)?;
+ let name = file.name().to_string();
+
+ // Check for zip slip vulnerability
+ if name.contains("..") {
+ return Err(anyhow::anyhow!(
+ "Invalid zip file: potential path traversal attack"
+ ));
+ }
- // Move temp dir to final location
- if dest_dir.exists() {
- if let Err(e) = tokio::fs::remove_dir_all(&dest_dir).await {
- let err_msg = format!("Failed to remove existing destination directory: {}", e);
- error!("{}", err_msg);
- cleanup_temp(&temp_dir, &temp_zip).await?;
- return Err(anyhow::anyhow!(err_msg));
+ let outpath = temp_dir_path.join(&name);
+ if name.ends_with('/') {
+ std::fs::create_dir_all(&outpath)?;
+ } else {
+ if let Some(p) = outpath.parent() {
+ if !p.exists() {
+ std::fs::create_dir_all(p)?;
+ }
+ }
+ let mut outfile = std::fs::File::create(&outpath)?;
+ std::io::copy(&mut file, &mut outfile)?;
}
}
+ Ok(())
+ })
+ .await;
+
+ // Handle extraction errors
+ if let Err(e) = extraction_result {
+ let err_msg = format!("Extraction task failed: {}", e);
+ error!("{}", err_msg);
+ update_build_status(&temp_pipe_json, "error", "extracting", Some(&err_msg)).await?;
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
+
+ if let Err(e) = extraction_result.unwrap() {
+ let err_msg = format!("Failed to extract zip: {}", e);
+ error!("{}", err_msg);
+ update_build_status(&temp_pipe_json, "error", "extracting", Some(&err_msg)).await?;
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
- if let Err(e) = tokio::fs::rename(&temp_dir, &dest_dir).await {
- let err_msg = format!("Failed to move files to destination: {}", e);
+ // Remove the temporary zip file
+ if let Err(e) = tokio::fs::remove_file(&temp_zip).await {
+ warn!("Failed to remove temporary zip file: {}", e);
+ }
+
+ // Move temp dir to final location
+ if dest_dir.exists() {
+ if let Err(e) = tokio::fs::remove_dir_all(&dest_dir).await {
+ let err_msg = format!("Failed to remove existing destination directory: {}", e);
error!("{}", err_msg);
cleanup_temp(&temp_dir, &temp_zip).await?;
return Err(anyhow::anyhow!(err_msg));
}
+ }
- // Update status for installation
- let final_pipe_json = dest_dir.join("pipe.json");
- update_build_status(&final_pipe_json, "in_progress", "installing", None).await?;
-
- // Check if it's a Next.js project and handle installation
- let package_json_path = dest_dir.join("package.json");
- let is_nextjs = if package_json_path.exists() {
- let package_json = tokio::fs::read_to_string(&package_json_path).await?;
- let package_data: Value = serde_json::from_str(&package_json)?;
- package_data["dependencies"].get("next").is_some()
- } else {
- false
- };
-
- // Find bun path
- let bun_path = find_bun_path().ok_or_else(|| anyhow::anyhow!("bun not found"))?;
+ if let Err(e) = tokio::fs::rename(&temp_dir, &dest_dir).await {
+ let err_msg = format!("Failed to move files to destination: {}", e);
+ error!("{}", err_msg);
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
- // Run bun install with error handling
- info!("installing dependencies");
- if let Err(e) = retry_install(&bun_path, &dest_dir, 3).await {
- let err_msg = format!("Failed to install dependencies: {}", e);
- error!("{}", err_msg);
- update_build_status(&final_pipe_json, "error", "installing", Some(&err_msg)).await?;
- return Err(anyhow::anyhow!(err_msg));
- }
+ // Update status for installation
+ let final_pipe_json = dest_dir.join("pipe.json");
+ update_build_status(&final_pipe_json, "in_progress", "installing", None).await?;
+
+ // Check if it's a Next.js project and handle installation
+ let package_json_path = dest_dir.join("package.json");
+ let is_nextjs = if package_json_path.exists() {
+ let package_json = tokio::fs::read_to_string(&package_json_path).await?;
+ let package_data: Value = serde_json::from_str(&package_json)?;
+ package_data["dependencies"].get("next").is_some()
+ } else {
+ false
+ };
+
+ // Find bun path
+ let bun_path = find_bun_path().ok_or_else(|| anyhow::anyhow!("bun not found"))?;
+
+ // Run bun install with error handling
+ info!("installing dependencies");
+ if let Err(e) = retry_install(&bun_path, &dest_dir, 3).await {
+ let err_msg = format!("Failed to install dependencies: {}", e);
+ error!("{}", err_msg);
+ update_build_status(&final_pipe_json, "error", "installing", Some(&err_msg)).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
- if is_nextjs {
- info!("detected next.js project, updating configuration");
- if final_pipe_json.exists() {
- let pipe_json = tokio::fs::read_to_string(&final_pipe_json).await?;
- let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
- pipe_config["is_nextjs"] = json!(true);
- pipe_config["buildStatus"] = json!({
- "status": "success",
- "step": "completed"
- });
- let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
- tokio::fs::write(&final_pipe_json, updated_pipe_json).await?;
- }
- } else {
- // Update final success status for non-Next.js projects
- update_build_status(&final_pipe_json, "success", "completed", None).await?;
+ if is_nextjs {
+ info!("detected next.js project, updating configuration");
+ if final_pipe_json.exists() {
+ let pipe_json = tokio::fs::read_to_string(&final_pipe_json).await?;
+ let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
+ pipe_config["is_nextjs"] = json!(true);
+ pipe_config["buildStatus"] = json!({
+ "status": "success",
+ "step": "completed"
+ });
+ let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
+ tokio::fs::write(&final_pipe_json, updated_pipe_json).await?;
}
-
- info!("pipe downloaded and set up successfully at: {:?}", dest_dir);
- Ok(dest_dir)
+ } else {
+ // Update final success status for non-Next.js projects
+ update_build_status(&final_pipe_json, "success", "completed", None).await?;
}
-}
-#[cfg(feature = "pipes")]
-pub use pipes::*;
+ info!("pipe downloaded and set up successfully at: {:?}", dest_dir);
+ Ok(dest_dir)
+}
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 38cc97408..5c487849e 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -120,6 +120,8 @@ lru = "0.13.0"
tokio-util = { version = "0.7", features = ["io"] }
dashmap = "6.1.0"
+
+once_cell = { workspace = true }
[dev-dependencies]
env_logger = "0.10"
tempfile = "3.3.0"
@@ -144,8 +146,7 @@ default = []
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]
-pipes = ["screenpipe-core/pipes", "url"]
-llm = ["screenpipe-core/llm"]
+llm = []
beta = ["screenpipe-core/beta", "dep:screenpipe-actions"]
experimental = ["enigo"]
debug-console = ["console-subscriber"]
diff --git a/screenpipe-server/src/embedding/embedding_endpoint.rs b/screenpipe-server/src/embedding/embedding_endpoint.rs
new file mode 100644
index 000000000..83a8eb3c8
--- /dev/null
+++ b/screenpipe-server/src/embedding/embedding_endpoint.rs
@@ -0,0 +1,121 @@
+use axum::Json;
+use once_cell::sync::OnceCell;
+use screenpipe_core::model::EmbeddingModel;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use tokio::sync::Mutex;
+use tracing::info;
+
+static EMBEDDING_MODEL: OnceCell<Arc<Mutex<EmbeddingModel>>> = OnceCell::new();
+
+// OpenAI-like request/response types
+#[derive(Deserialize)]
+#[allow(dead_code)]
+pub struct EmbeddingRequest {
+ model: String,
+ input: EmbeddingInput,
+ #[serde(default = "default_encoding")]
+ encoding_format: String,
+ #[serde(default)]
+ user: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(untagged)]
+pub enum EmbeddingInput {
+ #[serde(rename = "single")]
+ Single(String),
+ #[serde(rename = "multiple")]
+ Multiple(Vec<String>),
+}
+
+#[derive(Serialize)]
+pub struct EmbeddingResponse {
+ object: String,
+ data: Vec<EmbeddingData>,
+ model: String,
+ usage: Usage,
+}
+
+#[derive(Serialize)]
+pub struct EmbeddingData {
+ object: String,
+ embedding: Vec<f32>,
+ index: usize,
+}
+
+#[derive(Serialize)]
+pub struct Usage {
+ prompt_tokens: usize,
+ total_tokens: usize,
+}
+
+fn default_encoding() -> String {
+ "float".to_string()
+}
+
+pub async fn get_or_initialize_model() -> anyhow::Result<Arc<Mutex<EmbeddingModel>>> {
+ if let Some(model) = EMBEDDING_MODEL.get() {
+ return Ok(model.clone());
+ }
+
+ let model = EmbeddingModel::new(None, None)?;
+ EMBEDDING_MODEL
+ .set(Arc::new(Mutex::new(model)))
+ .map_err(|_| anyhow::anyhow!("failed to set global embedding model"))?;
+ info!("embedding model initialized");
+
+ EMBEDDING_MODEL
+ .get()
+ .ok_or_else(|| anyhow::anyhow!("model initialization failed"))
+ .map(|model| model.clone())
+}
+
+pub async fn create_embeddings(
+ Json(request): Json<EmbeddingRequest>,
+) -> Result<Json<EmbeddingResponse>, (axum::http::StatusCode, String)> {
+ let model = get_or_initialize_model()
+ .await
+ .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
+
+ let model = model.lock().await;
+
+ let (texts, _is_single) = match request.input {
+ EmbeddingInput::Single(text) => (vec![text], true),
+ EmbeddingInput::Multiple(texts) => (texts, false),
+ };
+
+ // Generate embeddings
+ let embeddings = if texts.len() == 1 {
+ vec![model
+ .generate_embedding(&texts[0])
+ .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?]
+ } else {
+ model
+ .generate_batch_embeddings(&texts)
+ .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
+ };
+
+ // Create response
+ let data = embeddings
+ .into_iter()
+ .enumerate()
+ .map(|(i, embedding)| EmbeddingData {
+ object: "embedding".to_string(),
+ embedding,
+ index: i,
+ })
+ .collect();
+
+ let response = EmbeddingResponse {
+ object: "list".to_string(),
+ data,
+ model: request.model,
+ usage: Usage {
+ prompt_tokens: texts.iter().map(|t| t.len()).sum(),
+ total_tokens: texts.iter().map(|t| t.len()).sum(),
+ },
+ };
+
+ Ok(Json(response))
+}
diff --git a/screenpipe-server/src/embedding/mod.rs b/screenpipe-server/src/embedding/mod.rs
new file mode 100644
index 000000000..4a96329eb
--- /dev/null
+++ b/screenpipe-server/src/embedding/mod.rs
@@ -0,0 +1 @@
+pub mod embedding_endpoint;
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 329c984e8..9a1754b59 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -15,7 +15,7 @@ pub mod video_cache;
mod video_db;
pub mod video_utils;
pub mod text_embeds;
-
+pub mod embedding;
pub use auto_destruct::watch_pid;
pub use cli::Cli;
pub use core::start_continuous_recording;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 9c421b572..cfac0cc0e 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -22,6 +22,7 @@ use screenpipe_events::{send_event, subscribe_to_all_events, Event as Screenpipe
use crate::{
db_types::{ContentType, FrameData, Order, SearchMatch, SearchResult, Speaker, TagContentType},
+ embedding::embedding_endpoint::create_embeddings,
pipe_manager::PipeManager,
video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
video_cache::{AudioEntry, DeviceFrame, FrameCache, FrameMetadata, TimeSeriesFrame},
@@ -914,7 +915,6 @@ impl Server {
pub fn new(
db: Arc<DatabaseManager>,
addr: SocketAddr,
- // device_manager: Arc<DeviceManager>,
screenpipe_dir: PathBuf,
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
@@ -924,7 +924,6 @@ impl Server {
Server {
db,
addr,
- // device_manager,
screenpipe_dir,
pipe_manager,
vision_disabled,
@@ -2009,7 +2008,8 @@ pub fn create_router() -> Router<Arc<AppState>> {
axum::http::header::CACHE_CONTROL,
]); // Important for SSE
- let router = Router::new()
+ #[allow(unused_mut)]
+ let mut router = Router::new()
.route("/search", get(search))
.route("/audio/list", get(api_list_audio_devices))
.route("/vision/list", get(api_list_monitors))
@@ -2054,6 +2054,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/frames/:frame_id", get(get_frame_data))
.route("/pipes/build-status/:pipe_id", get(get_pipe_build_status))
.route("/search/keyword", get(keyword_search_handler))
+ .route("/v1/embeddings", axum::routing::post(create_embeddings))
// .route("/vision/start", post(start_vision_device))
// .route("/vision/stop", post(stop_vision_device))
// .route("/audio/restart", post(restart_audio_devices))
@@ -2064,7 +2065,6 @@ pub fn create_router() -> Router<Arc<AppState>> {
{
router = router.route("/experimental/input_control", post(input_control_handler));
}
-
router
}