YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
release-app-fix fix issue where pipe settings would be lost after disabling, also issue where backend would not properly kill the cron after deletion
Louis Beaumont91d48e56499c
diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.ymlindex 6ed9dca90..7b1360983 100644--- a/.github/workflows/release-app.yml+++ b/.github/workflows/release-app.yml@@ -466,7 +466,33 @@ jobs:tauriScript: bunx tauri -vvvretryAttempts: 3- - name: Upload Assets to CrabNebula Cloud+ - name: Download and Run CLI Manually (Windows)+ if: matrix.tauri-args == '--target x86_64-pc-windows-msvc'+ shell: pwsh+ env:+ CN_API_KEY: ${{ secrets.CN_API_KEY }}+ run: |+ # Create temp directory for CLI+ $cliDir = "cn-cli-temp"+ New-Item -ItemType Directory -Force -Path $cliDir++ # Download CLI from GitHub+ $cliUrl = "https://github.com/crabnebula-dev/cloud-releases/releases/latest/download/cloud-cli-x86_64-pc-windows-msvc.zip"+ $cliZip = "$cliDir\cli.zip"++ Write-Host "Downloading CrabNebula CLI..."+ Invoke-WebRequest -Uri $cliUrl -OutFile $cliZip++ # Extract CLI+ Expand-Archive -Path $cliZip -DestinationPath $cliDir -Force++ # Run upload command+ Write-Host "Uploading assets..."+ $env:PATH = "$PWD\$cliDir;$env:PATH"+ ./cn-cli release upload ${{ secrets.CN_APP_SLUG }} --framework tauri --path ./screenpipe-app-tauri/src-tauri --api-key ${{ secrets.CN_API_KEY }}++ - name: Upload Assets to CrabNebula Cloud (Non-Windows)+ if: matrix.tauri-args != '--target x86_64-pc-windows-msvc'uses: crabnebula-dev/[email protected]with:command: release upload ${{ secrets.CN_APP_SLUG }} --framework tauri@@ -676,33 +702,7 @@ jobs:projectPath: "./screenpipe-app-tauri"tauriScript: bunx tauri -v- - name: Download and Run CLI Manually (Windows)- if: matrix.tauri-args == '--target x86_64-pc-windows-msvc'- shell: pwsh- env:- CN_API_KEY: ${{ secrets.CN_API_KEY }}- run: |- # Create temp directory for CLI- $cliDir = "cn-cli-temp"- New-Item -ItemType Directory -Force -Path $cliDir-- # Download CLI from GitHub- $cliUrl = "https://github.com/crabnebula-dev/cloud-releases/releases/latest/download/cloud-cli-x86_64-pc-windows-msvc.zip"- $cliZip = "$cliDir\cli.zip"-- Write-Host "Downloading CrabNebula CLI..."- Invoke-WebRequest -Uri $cliUrl -OutFile $cliZip-- # Extract CLI- Expand-Archive -Path $cliZip -DestinationPath $cliDir -Force-- # Run upload command- Write-Host "Uploading assets..."- $env:PATH = "$PWD\$cliDir;$env:PATH"- ./cn-cli release upload ${{ secrets.CN_APP_SLUG }} --framework tauri --path ./screenpipe-app-tauri/src-tauri --api-key ${{ secrets.CN_API_KEY }}-- - name: Upload Assets to CrabNebula Cloud (Non-Windows)- if: matrix.tauri-args != '--target x86_64-pc-windows-msvc'+ - name: Upload Assets to CrabNebula Clouduses: crabnebula-dev/[email protected]with:command: release upload ${{ secrets.CN_APP_SLUG }} --framework tauridiff --git a/pipes/obsidian/src/app/api/settings/route.ts b/pipes/obsidian/src/app/api/settings/route.tsindex 6c560ff47..5d0b60de0 100644--- a/pipes/obsidian/src/app/api/settings/route.ts+++ b/pipes/obsidian/src/app/api/settings/route.ts@@ -8,9 +8,10 @@ import path from "path";export const runtime = "nodejs"; // Add this lineexport const dynamic = "force-dynamic";+const DEFAULT_INTERVAL_MINUTES = 5;+async function updateCronSchedule(intervalMinutes: number) {try {- // Get the .screenpipe base directory from the environment or use a defaultconst screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();const pipeConfigPath = path.join(screenpipeDir,@@ -18,10 +19,18 @@ async function updateCronSchedule(intervalMinutes: number) {"obsidian","pipe.json");+ const settingsPath = path.join(+ screenpipeDir,+ "pipes",+ "obsidian",+ "settings.json"+ );console.log(`updating cron schedule at: ${pipeConfigPath}`);+ // Load or initialize both configslet config: any = {};+ let settings: any = {};try {const content = await fs.readFile(pipeConfigPath, "utf8");@@ -33,15 +42,27 @@ async function updateCronSchedule(intervalMinutes: number) {config = { crons: [] };}- // Update or add the cron schedule+ try {+ const settingsContent = await fs.readFile(settingsPath, "utf8");+ settings = JSON.parse(settingsContent);+ } catch (err) {+ console.log(+ `no existing settings found, creating new one at ${settingsPath}`+ );+ settings = { interval: intervalMinutes * 60000 };+ }++ // Update settings+ settings.interval = intervalMinutes * 60000;+ await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));++ // Update cron configconfig.crons = [{path: "/api/log",schedule: `0 */${intervalMinutes} * * * *`,},];-- // Preserve other existing propertiesconfig.enabled = config.enabled ?? true;config.is_nextjs = config.is_nextjs ?? true;@@ -56,41 +77,48 @@ async function updateCronSchedule(intervalMinutes: number) {}export async function GET() {- const defaultSettings: Settings = {- openaiApiKey: "",- deepgramApiKey: "",- aiModel: "gpt-4",- aiUrl: "https://api.openai.com/v1",- customPrompt: "",- port: 3030,- dataDir: "default",- disableAudio: false,- ignoredWindows: [],- includedWindows: [],- aiProviderType: "openai",- embeddedLLM: {- enabled: false,- model: "llama3.2:1b-instruct-q4_K_M",- port: 11438,- },- enableFrameCache: true,- enableUiMonitoring: false,- aiMaxContextChars: 128000,- user: {- token: "",- },- };-try {const settingsManager = pipe.settings;if (!settingsManager) {throw new Error("settingsManager not found");}- const rawSettings = await settingsManager.getAll();- return NextResponse.json(rawSettings);++ // Load persisted settings if they exist+ const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();+ const settingsPath = path.join(+ screenpipeDir,+ "pipes",+ "obsidian",+ "settings.json"+ );++ try {+ const settingsContent = await fs.readFile(settingsPath, "utf8");+ const persistedSettings = JSON.parse(settingsContent);++ // Merge with current settings+ const rawSettings = await settingsManager.getAll();+ return NextResponse.json({+ ...rawSettings,+ customSettings: {+ ...rawSettings.customSettings,+ obsidian: {+ ...(rawSettings.customSettings?.obsidian || {}),+ ...persistedSettings,+ },+ },+ });+ } catch (err) {+ // If no persisted settings, return normal settings+ const rawSettings = await settingsManager.getAll();+ return NextResponse.json(rawSettings);+ }} catch (error) {console.error("failed to get settings:", error);- return NextResponse.json(defaultSettings);+ return NextResponse.json(+ { error: "failed to get settings" },+ { status: 500 }+ );}}@@ -105,9 +133,10 @@ export async function PUT(request: Request) {const { key, value, isPartialUpdate, reset, namespace } = body;// Handle obsidian namespace updates- if (namespace === "obsidian" && isPartialUpdate && value.interval) {- // Convert interval from milliseconds to minutes, ensure it's at least 1- const intervalMinutes = Math.max(1, Math.floor(value.interval / 60000));+ if (namespace === "obsidian" && isPartialUpdate) {+ // Use provided interval or default+ const intervalMs = value.interval || DEFAULT_INTERVAL_MINUTES * 60000;+ const intervalMinutes = Math.max(1, Math.floor(intervalMs / 60000));await updateCronSchedule(intervalMinutes);console.log(`setting interval to ${intervalMinutes} minutes`);}diff --git a/pipes/obsidian/src/lib/hooks/use-settings.tsx b/pipes/obsidian/src/lib/hooks/use-settings.tsxindex ea4b74b1d..4ed2066eb 100644--- a/pipes/obsidian/src/lib/hooks/use-settings.tsx+++ b/pipes/obsidian/src/lib/hooks/use-settings.tsx@@ -29,18 +29,20 @@ export function useSettings() {},};- const [settings, setSettings] = useState<Settings>(defaultSettings);- const [loading, setLoading] = useState(false);+ const [settings, setSettings] = useState<Settings | null>(null);+ const [loading, setLoading] = useState(true);const [error, setError] = useState<Error | null>(null);useEffect(() => {const loadSettings = async () => {- setLoading(true);+ if (!loading) setLoading(true);try {const response = await fetch("/api/settings");const data = await response.json();setSettings({ ...defaultSettings, ...data });} catch (err) {+ console.error("failed to load settings:", err);+ setSettings(defaultSettings);setError(err as Error);} finally {setLoading(false);@@ -68,95 +70,122 @@ export function useSettings() {value: Settings[T],namespace?: string) => {+ if (!settings) return;try {await fetch("/api/settings", {method: "PUT",body: JSON.stringify({ key, value, namespace }),});-+if (namespace) {- // Update namespace settings in state- setSettings((prev) => ({- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {- ...(prev.customSettings?.[namespace] || {}),- [key]: value,+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {+ ...(prev.customSettings?.[namespace] || {}),+ [key]: value,+ },},- },- }));+ };+ });} else {- // Update regular settings- setSettings((prev) => ({ ...prev, [key]: value }));+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return { ...prev, [key]: value };+ });}} catch (err) {setError(err as Error);}};- const updateSettings = async (newSettings: Partial<Settings>, namespace?: string) => {+ const updateSettings = async (+ newSettings: Partial<Settings>,+ namespace?: string+ ) => {+ if (!settings) return;try {await fetch("/api/settings", {method: "PUT",- body: JSON.stringify({ value: newSettings, isPartialUpdate: true, namespace }),+ body: JSON.stringify({+ value: newSettings,+ isPartialUpdate: true,+ namespace,+ }),});-+if (namespace) {- setSettings((prev) => ({- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {- ...(prev.customSettings?.[namespace] || {}),- ...newSettings,+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {+ ...(prev.customSettings?.[namespace] || {}),+ ...newSettings,+ },},- },- }));+ };+ });} else {- setSettings((prev) => ({ ...prev, ...newSettings }));+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return { ...prev, ...newSettings };+ });}} catch (err) {setError(err as Error);}};- const resetSettings = async (settingKey?: keyof Settings, namespace?: string) => {+ const resetSettings = async (+ settingKey?: keyof Settings,+ namespace?: string+ ) => {+ if (!settings) return;try {await fetch("/api/settings", {method: "PUT",body: JSON.stringify({ reset: true, key: settingKey, namespace }),});-+if (namespace) {- if (settingKey) {- // Reset single key in namespace- setSettings((prev) => ({- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {- ...(prev.customSettings?.[namespace] || {}),- [settingKey]: undefined,+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ if (settingKey) {+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {+ ...(prev.customSettings?.[namespace] || {}),+ [settingKey]: undefined,+ },},- },- }));- } else {- // Reset entire namespace- setSettings((prev) => ({- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {},- },- }));- }+ };+ } else {+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {},+ },+ };+ }+ });} else {if (settingKey) {- setSettings((prev) => ({- ...prev,- [settingKey]: defaultSettings[settingKey],- }));+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return {+ ...prev,+ [settingKey]: defaultSettings[settingKey],+ };+ });} else {setSettings(defaultSettings);}@@ -167,7 +196,7 @@ export function useSettings() {};return {- settings,+ settings: settings || defaultSettings,loading,error,updateSetting,diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 5387cd0b0..e5d2c47c7 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "0.20.8"+version = "0.20.9"description = ""authors = ["you"]license = ""diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 1c14af667..ba01caa0c 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -2,11 +2,13 @@#[cfg(feature = "pipes")]mod pipes {use regex::Regex;+ use std::collections::HashMap;use std::future::Future;use std::path::PathBuf;use std::pin::Pin;use std::time::{SystemTime, UNIX_EPOCH};use tokio::process::Command;+ use tokio::sync::watch;use reqwest::Client;use serde_json::Value;@@ -34,6 +36,19 @@ mod pipes {use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};use std::str::FromStr;+ pub struct CronHandle {+ shutdown: watch::Sender<bool>,+ }++ 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()));+// Add this function to generate a secure cron secretfn generate_cron_secret() -> String {thread_rng()@@ -138,16 +153,11 @@ mod pipes {let base_url = format!("http://localhost:{}", port);debug!("using base url: {} for cron jobs", base_url);- // Generate a CRON_SECRET if not existslet cron_secret = generate_cron_secret();debug!("generated cron secret for pipe: {}", pipe);-- // Add CRON_SECRET to environment variablesenv_vars.push(("CRON_SECRET".to_string(), cron_secret.clone()));- // Clone the crons array and screenpipe_dir before the loop- let crons = crons.to_vec();- let screenpipe_dir = screenpipe_dir.clone();+ let mut handles = Vec::new();for cron in crons {let path = cron["path"]@@ -159,35 +169,31 @@ mod pipes {.ok_or_else(|| anyhow::anyhow!("missing schedule"))?.to_string();- debug!("setting up cron job: {} with schedule: {}", path, schedule);-- // Validate cron expression- match cron::Schedule::from_str(&schedule) {- Ok(_) => {- let base_url = base_url.clone();- let pipe_clone = pipe.to_string();- let secret_clone = cron_secret.clone();- let screenpipe_dir = screenpipe_dir.clone();-- debug!("spawning cron task for path: {}", path);- tokio::spawn(async move {- run_cron_schedule(- &pipe_clone,- &base_url,- &path,- &secret_clone,- &schedule,- &screenpipe_dir,- )- .await;- });- }- Err(e) => {- error!("invalid cron expression '{}': {}", schedule, e);- anyhow::bail!("invalid cron expression '{}': {}", schedule, e);- }- }+ 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);}// Install dependencies using bun@@ -798,6 +804,7 @@ mod pipes {secret: &str,schedule: &str,screenpipe_dir: &Path,+ mut shutdown: watch::Receiver<bool>,) {let schedule = match cron::Schedule::from_str(schedule) {Ok(s) => s,@@ -869,8 +876,26 @@ mod pipes {}Err(e) => error!("failed to execute cron job: {}", e),}++ if let Ok(()) = shutdown.changed().await {+ if *shutdown.borrow() {+ info!("cron job shutdown for pipe at path: {}", path);+ break;+ }+ }}}++ 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(())+ }}#[cfg(feature = "pipes")]diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rsindex aa580a12a..3ea9017eb 100644--- a/screenpipe-server/src/pipe_manager.rs+++ b/screenpipe-server/src/pipe_manager.rs@@ -232,6 +232,9 @@ impl PipeManager {// Send kill signal and wait for confirmationhandle.kill_tx.send(()).await?;+ // Clean up any running cron jobs+ screenpipe_core::pipes::cleanup_pipe_crons(id).await?;+// Wait a bit for the process to actually terminatetokio::time::sleep(tokio::time::Duration::from_millis(100)).await;@@ -244,7 +247,9 @@ impl PipeManager {}#[cfg(windows)]{- use windows::Win32::System::Threading::{OpenProcess, PROCESS_ACCESS_RIGHTS, TerminateProcess};+ use windows::Win32::System::Threading::{+ OpenProcess, TerminateProcess, PROCESS_ACCESS_RIGHTS,+ };unsafe {if let Ok(h_process) = OpenProcess(PROCESS_ACCESS_RIGHTS(0x0001), // PROCESS_TERMINATE access right