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
Push all local changes from parallel agents
Louis Beaumont653f4d908d0c
diff --git a/apps/screenpipe-app-tauri/app/permission-recovery/page.tsx b/apps/screenpipe-app-tauri/app/permission-recovery/page.tsxindex f8ece14a1..84bd23234 100644--- a/apps/screenpipe-app-tauri/app/permission-recovery/page.tsx+++ b/apps/screenpipe-app-tauri/app/permission-recovery/page.tsx@@ -89,7 +89,7 @@ export default function PermissionRecoveryPage() {const interval = setInterval(() => {if (restartTriggeredRef.current) return;checkPermissions();- }, 500);+ }, 3000);return () => clearInterval(interval);}, [checkPermissions]);diff --git a/apps/screenpipe-app-tauri/components/settings/archive-settings.tsx b/apps/screenpipe-app-tauri/components/settings/archive-settings.tsxindex 2e31cfb3d..f974cf94c 100644--- a/apps/screenpipe-app-tauri/components/settings/archive-settings.tsx+++ b/apps/screenpipe-app-tauri/components/settings/archive-settings.tsx@@ -99,20 +99,12 @@ export function ArchiveSettings() {try {if (enabled) {- // Generate password if not already set- let password = settings._archiveEncryptionPassword;- if (!password) {- password = crypto.randomUUID();- await updateSettings({ _archiveEncryptionPassword: password });- }-- // Initialize archive+ // Initialize archive — encryption key is derived server-side from the tokenconst res = await fetch("http://localhost:3030/archive/init", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({token: settings.user?.token,- password,retention_days: retentionDays,}),});diff --git a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsxindex e8c0bed23..f85879a23 100644--- a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx@@ -318,10 +318,18 @@ export function PipesSection() {const fetchPipes = useCallback(async () => {try {- const res = await fetch("http://localhost:3030/pipes");+ const res = await fetch("http://localhost:3030/pipes?include_executions=true");const data = await res.json();- const fetched: PipeStatus[] = data.data || [];+ const rawItems: Array<PipeStatus & { recent_executions?: PipeExecution[] }> = data.data || [];+ const fetched: PipeStatus[] = [];+ const results: Record<string, PipeExecution[]> = {};+ for (const item of rawItems) {+ const { recent_executions, ...pipe } = item;+ fetched.push(pipe);+ results[pipe.config.name] = recent_executions || [];+ }setPipes(fetched);+ setPipeExecutions(results);// Clear drafts that match the server content (already saved)setPromptDrafts((prev) => {const next = { ...prev };@@ -334,22 +342,6 @@ export function PipesSection() {}return changed ? next : prev;});- // Fetch executions immediately (no waterfall through re-render)- if (fetched.length > 0) {- const results: Record<string, PipeExecution[]> = {};- await Promise.all(- fetched.map(async (pipe) => {- try {- const r = await fetch(`http://localhost:3030/pipes/${pipe.config.name}/executions?limit=5`);- const d = await r.json();- results[pipe.config.name] = d.data || [];- } catch {- results[pipe.config.name] = [];- }- })- );- setPipeExecutions(results);- }} catch (e) {console.error("failed to fetch pipes:", e);} finally {@@ -378,23 +370,20 @@ export function PipesSection() {return () => clearInterval(interval);}, [fetchPipes]);- const fetchAllExecutions = useCallback(async (pipeList?: PipeStatus[]) => {- const list = pipeList || pipes;- if (list.length === 0) return;- const results: Record<string, PipeExecution[]> = {};- await Promise.all(- list.map(async (pipe) => {- try {- const res = await fetch(`http://localhost:3030/pipes/${pipe.config.name}/executions?limit=5`);- const data = await res.json();- results[pipe.config.name] = data.data || [];- } catch {- results[pipe.config.name] = [];- }- })- );- setPipeExecutions(results);- }, [pipes]);+ const fetchAllExecutions = useCallback(async () => {+ try {+ const res = await fetch("http://localhost:3030/pipes?include_executions=true");+ const data = await res.json();+ const rawItems: Array<PipeStatus & { recent_executions?: PipeExecution[] }> = data.data || [];+ const results: Record<string, PipeExecution[]> = {};+ for (const item of rawItems) {+ results[item.config.name] = item.recent_executions || [];+ }+ setPipeExecutions(results);+ } catch {+ // ignore — next poll will retry+ }+ }, []);// Poll executions faster (3s) when any pipe is running, otherwise on pipe fetch (10s)useEffect(() => {diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex c80f0ed9c..7132dbad9 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -110,8 +110,6 @@ export type Settings = SettingsStore & {cloudArchiveEnabled?: boolean;/** Days to keep data locally before archiving (default: 7) */cloudArchiveRetentionDays?: number;- /** Internal: auto-generated encryption password for archive (opaque to user) */- _archiveEncryptionPassword?: string;}export function getEffectiveFilters(settings: Settings) {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex a02461438..55a4a590c 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -954,6 +954,30 @@ async fn is_server_running(app: AppHandle) -> Result<bool, String> {async fn main() {let _ = fix_path_env::fix();+ // Handle --check-arc-automation / --trigger-arc-automation flags early,+ // before any Tauri initialization. Used by the permission system to run+ // this binary via launchctl (detached from Terminal) so that macOS TCC+ // checks the binary's own identity instead of Terminal's.+ #[cfg(target_os = "macos")]+ {+ let early_args: Vec<String> = std::env::args().collect();+ let is_check = early_args.iter().any(|a| a == "--check-arc-automation");+ let is_trigger = early_args.iter().any(|a| a == "--trigger-arc-automation");+ if is_check || is_trigger {+ let result = permissions::ae_check_automation_direct(+ "company.thebrowser.Browser",+ is_trigger, // askUserIfNeeded = true for trigger+ );+ match result {+ 0 => print!("granted"),+ -1744 => print!("denied"),+ -1745 => print!("not_asked"),+ _ => print!("error"),+ }+ return;+ }+ }+// Single-instance check: if sidecar server is already listening, hand off and exit.// This covers Linux (where tauri-plugin-single-instance is disabled due to// zbus/tokio conflict) and acts as a fallback on macOS/Windows.diff --git a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rsindex e0d852d5c..82e784278 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs@@ -390,25 +390,26 @@ pub fn check_arc_installed() -> bool {}/// Check if Automation permission for Arc is already granted.-/// In production (.app bundle): uses direct FFI check against the app's own TCC entry.-/// In dev mode: always returns true — dev builds inherit Terminal's permissions and-/// the modal cannot manage Arc automation for a non-bundled binary.+/// In production (.app bundle): uses direct FFI check (correct identity, no Terminal).+/// In dev mode: runs the binary itself via launchctl (detached from Terminal) so+/// macOS TCC checks the binary's own identity, not Terminal's.#[tauri::command(async)]#[specta::specta]pub fn check_arc_automation_permission(_app: tauri::AppHandle) -> bool {#[cfg(target_os = "macos")]{- if !is_app_bundle() {- // Dev mode: can't manage Arc automation (Terminal inheritance).- // Return true to skip showing the Arc row in the modal.- return true;- }let target = "company.thebrowser.Browser";- let result = ae_check_automation_direct(target, false);- if result != 0 {- info!("arc automation check: result={} (0=granted, -1744=denied, -1745=not_asked)", result);+ if is_app_bundle() {+ // Production: direct FFI check (no Terminal inheritance)+ let result = ae_check_automation_direct(target, false);+ if result != 0 {+ info!("arc automation check (direct): result={}", result);+ }+ result == 0+ } else {+ // Dev mode: run self via launchctl to check without Terminal inheritance+ run_self_detached("--check-arc-automation")}- result == 0}#[cfg(not(target_os = "macos"))]@@ -428,8 +429,9 @@ fn is_app_bundle() -> bool {/// Call AEDeterminePermissionToAutomateTarget directly from the current process via FFI./// Returns the raw OSStatus: 0 = granted, -1744 = denied, -1745 = not yet asked./// When `ask_user` is true AND permission was not yet asked, macOS shows a system prompt.+/// Public so main.rs can call it for --check-arc-automation / --trigger-arc-automation.#[cfg(target_os = "macos")]-fn ae_check_automation_direct(target_bundle_id: &str, ask_user: bool) -> i32 {+pub fn ae_check_automation_direct(target_bundle_id: &str, ask_user: bool) -> i32 {use std::ffi::c_void;#[repr(C)]@@ -482,195 +484,117 @@ fn ae_check_automation_direct(target_bundle_id: &str, ask_user: bool) -> i32 {}}-/// Generate Swift source for the AE helper binary.-/// Supports a `request` CLI argument to trigger the permission prompt.-#[cfg(target_os = "macos")]-fn ae_helper_swift_source(target_bundle_id: &str) -> String {- format!(- r#"import Foundation; import Carbon-let b = "{target}"-let ask = CommandLine.arguments.count > 1 && CommandLine.arguments[1] == "request"-var a = AEDesc(descriptorType: 0, dataHandle: nil)-let d = b.data(using: .utf8)!-let e: OSErr = d.withUnsafeBytes {{ p in AECreateDesc(UInt32(typeApplicationBundleID), p.baseAddress!, p.count, &a) }}-if e != noErr {{ print("error"); Foundation.exit(1) }}-let r = AEDeterminePermissionToAutomateTarget(&a, typeWildCard, typeWildCard, ask)-AEDisposeDesc(&a)-switch r {{ case 0: print("granted"); case -1744: print("denied"); case -1745: print("not_asked"); default: print("error") }}-"#,- target = target_bundle_id- )-}-/// Ensure the AE helper binary is compiled and up-to-date.-/// Returns true on success.+/// Run the current binary itself via launchctl (detached from Terminal) with a flag.+/// Waits for the result and returns true if the output is "granted".+/// Used in dev mode so macOS TCC checks the binary's own identity.#[cfg(target_os = "macos")]-fn ensure_ae_helper(target_bundle_id: &str) -> bool {+fn run_self_detached(flag: &str) -> bool {use std::process::Command;+ use std::time::Duration;- let checker = "/tmp/screenpipe_ae_check";- let src_path = format!("{}.swift", checker);- let new_source = ae_helper_swift_source(target_bundle_id);-- // Check if source changed (force recompile if so)- let source_changed = std::fs::read_to_string(&src_path)- .map(|existing| existing != new_source)- .unwrap_or(true);-- if source_changed {- if std::fs::write(&src_path, &new_source).is_err() {- warn!("failed to write ae helper source");+ let exe = match std::env::current_exe() {+ Ok(p) => p,+ Err(e) => {+ warn!("failed to get current exe: {}", e);return false;}- let _ = std::fs::remove_file(checker);- }-- if !std::path::Path::new(checker).exists() {- let compile = Command::new("swiftc")- .args([&src_path, "-o", checker, "-framework", "Carbon", "-O"])- .output();- match compile {- Ok(out) if out.status.success() => {}- Ok(out) => {- warn!("swiftc failed: {}", String::from_utf8_lossy(&out.stderr));- return false;- }- Err(e) => {- warn!("failed to run swiftc: {}", e);- return false;- }- }- }+ };- true-}+ let label = format!("pe.screenpi.self-{}", flag.trim_start_matches("--"));+ let result_path = format!("/tmp/screenpipe_self_{}_result", flag.trim_start_matches("--"));-/// Run the AE helper via launchctl (detached from Terminal) and return stdout content.-/// Pass extra_args to the helper binary (e.g. &["request"] for prompt mode).-#[cfg(target_os = "macos")]-fn run_ae_helper_detached(target_bundle_id: &str, extra_args: &[&str], timeout_iters: u32) -> Option<String> {- use std::process::Command;- use std::time::Duration;+ let _ = std::fs::remove_file(&result_path);+ let _ = Command::new("launchctl").args(["remove", &label]).output();- if !ensure_ae_helper(target_bundle_id) {- return None;- }-- let checker = "/tmp/screenpipe_ae_check";- let result_path = "/tmp/screenpipe_ae_check_result";- let _ = std::fs::remove_file(result_path);- let _ = Command::new("launchctl")- .args(["remove", "pe.screenpi.ae-check"])+ let exe_str = exe.to_string_lossy().to_string();+ let submit = Command::new("launchctl")+ .args(["submit", "-l", &label, "-o", &result_path, "--", &exe_str, flag]).output();- let mut args = vec![- "submit", "-l", "pe.screenpi.ae-check",- "-o", result_path, "--", checker,- ];- args.extend_from_slice(extra_args);-- let submit = Command::new("launchctl").args(&args).output();if submit.is_err() {- warn!("failed to submit ae helper via launchctl");- return None;+ warn!("failed to submit self via launchctl with {}", flag);+ return false;}- for _ in 0..timeout_iters {+ // Wait for result (binary exits quickly for --check, so 5s is plenty)+ for _ in 0..25 {std::thread::sleep(Duration::from_millis(200));- if std::path::Path::new(result_path).exists() {- if let Ok(content) = std::fs::read_to_string(result_path) {+ if std::path::Path::new(&result_path).exists() {+ if let Ok(content) = std::fs::read_to_string(&result_path) {if !content.is_empty() {- let _ = Command::new("launchctl")- .args(["remove", "pe.screenpi.ae-check"])- .output();- return Some(content.trim().to_string());+ let _ = Command::new("launchctl").args(["remove", &label]).output();+ let result = content.trim();+ if result != "granted" {+ info!("self detached {}: {}", flag, result);+ }+ return result == "granted";}}}}- let _ = Command::new("launchctl")- .args(["remove", "pe.screenpi.ae-check"])- .output();- warn!("ae helper timed out");- None-}--/// Check AppleEvents automation permission by running a detached helper-/// process via launchctl. This avoids inheriting Terminal's permissions.-#[cfg(target_os = "macos")]-fn ae_automation_check_detached(target_bundle_id: &str) -> bool {- match run_ae_helper_detached(target_bundle_id, &[], 10) {- Some(result) => {- if result != "granted" {- info!("arc automation check (detached): {}", result);- }- result == "granted"- }- None => false,- }+ let _ = Command::new("launchctl").args(["remove", &label]).output();+ warn!("self detached {} timed out", flag);+ false}-/// Submit a detached AE helper in "request" mode to trigger the macOS permission prompt.-/// Non-blocking: returns immediately after submitting the launchctl job.-/// The prompt will appear from the detached process; polling check detects the grant.+/// Fire-and-forget: submit the binary via launchctl with a flag, don't wait for result.+/// Used for --trigger-arc-automation where the user needs to respond to a prompt.#[cfg(target_os = "macos")]-fn ae_automation_submit_request(target_bundle_id: &str) {+fn run_self_detached_fire_and_forget(flag: &str) {use std::process::Command;- if !ensure_ae_helper(target_bundle_id) {- return;- }+ let exe = match std::env::current_exe() {+ Ok(p) => p,+ Err(e) => {+ warn!("failed to get current exe: {}", e);+ return;+ }+ };- let checker = "/tmp/screenpipe_ae_check";- let result_path = "/tmp/screenpipe_ae_request_result";- let _ = std::fs::remove_file(result_path);- let _ = Command::new("launchctl")- .args(["remove", "pe.screenpi.ae-request"])- .output();+ let label = format!("pe.screenpi.self-{}", flag.trim_start_matches("--"));+ let result_path = format!("/tmp/screenpipe_self_{}_result", flag.trim_start_matches("--"));+ let _ = std::fs::remove_file(&result_path);+ let _ = Command::new("launchctl").args(["remove", &label]).output();++ let exe_str = exe.to_string_lossy().to_string();let submit = Command::new("launchctl")- .args([- "submit", "-l", "pe.screenpi.ae-request",- "-o", result_path, "--", checker, "request",- ])+ .args(["submit", "-l", &label, "-o", &result_path, "--", &exe_str, flag]).output();- if submit.is_err() {- warn!("failed to submit ae request via launchctl");- } else {- info!("submitted detached ae automation request — macOS prompt should appear");+ match submit {+ Ok(_) => info!("submitted self via launchctl with {} — prompt should appear", flag),+ Err(e) => warn!("failed to submit self via launchctl: {}", e),}}/// Request macOS Automation permission for Arc browser./// In production: triggers "screenpipe wants to control Arc" prompt via direct FFI.-/// In dev mode: submits a detached helper to trigger the prompt outside Terminal's tree.-/// Also opens System Settings > Automation as a fallback.+/// In dev mode: runs the binary itself via launchctl to trigger the prompt with+/// the correct binary identity (not Terminal's). Also opens System Settings as fallback.#[tauri::command(async)]#[specta::specta]pub fn request_arc_automation_permission(_app: tauri::AppHandle) -> bool {#[cfg(target_os = "macos")]{- let target = "company.thebrowser.Browser";-if is_app_bundle() {// Production: trigger prompt directly from the app process.- // Shows "screenpipe wants to control Arc" system dialog.info!("requesting arc automation permission via direct FFI");- let result = ae_check_automation_direct(target, true);+ let result = ae_check_automation_direct("company.thebrowser.Browser", true);info!("arc automation request (direct): result={}", result);if result != 0 {- // User denied or already denied before — open settings as fallbackopen_permission_settings(OSPermission::Automation);}result == 0} else {- // Dev mode: submit detached request (non-blocking) to trigger prompt- // outside Terminal's process tree, then open settings as fallback.- info!("requesting arc automation permission via detached helper");- ae_automation_submit_request(target);+ // Dev mode: run self via launchctl with --trigger-arc-automation.+ // This triggers the macOS prompt with the binary's own identity+ // so "screenpipe dev" appears in Automation settings.+ info!("requesting arc automation permission via detached self");open_permission_settings(OSPermission::Automation);+ run_self_detached_fire_and_forget("--trigger-arc-automation");false // Polling check will detect when granted}}diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rsindex 84e133444..e5d288caa 100644--- a/crates/screenpipe-core/src/pipes/mod.rs+++ b/crates/screenpipe-core/src/pipes/mod.rs@@ -22,6 +22,7 @@ use std::collections::{HashMap, VecDeque};use std::path::{Path, PathBuf};use std::str::FromStr;use std::sync::Arc;+use std::time::Instant;use tokio::sync::{Mutex, Semaphore};use tracing::{debug, error, info, warn};@@ -336,8 +337,8 @@ pub struct PipeManager {pipes_dir: PathBuf,/// Registered agent executors keyed by name (e.g. `"pi"`).executors: HashMap<String, Arc<dyn AgentExecutor>>,- /// Loaded pipe configs keyed by pipe name.- pipes: Arc<Mutex<HashMap<String, (PipeConfig, String)>>>, // (config, prompt_body)+ /// Loaded pipe configs keyed by pipe name: (config, prompt_body, raw_content).+ pipes: Arc<Mutex<HashMap<String, (PipeConfig, String, String)>>>,/// Recent run logs per pipe (last 50).logs: Arc<Mutex<HashMap<String, VecDeque<PipeRunLog>>>>,/// Currently running pipe PIDs.@@ -354,6 +355,8 @@ pub struct PipeManager {store: Option<Arc<dyn PipeStore>>,/// API port for prompt rendering (default 3030).api_port: u16,+ /// Timestamp of last reload_pipes() disk scan, for debouncing.+ last_reload: Arc<Mutex<Instant>>,}impl PipeManager {@@ -375,6 +378,7 @@ impl PipeManager {on_run_complete: None,store,api_port,+ last_reload: Arc::new(Mutex::new(Instant::now() - std::time::Duration::from_secs(10))),}}@@ -436,7 +440,7 @@ impl PipeManager {.to_string();config.name = dir_name.clone();info!("loaded pipe: {}", dir_name);- pipes.insert(dir_name, (config, body));+ pipes.insert(dir_name, (config, body, content));}Err(e) => {warn!("failed to parse {:?}: {}", pipe_md, e);@@ -454,7 +458,15 @@ impl PipeManager {/// Re-scan `pipes_dir` and merge: add new pipes, update configs of existing/// ones, remove pipes whose directories were deleted — but preserve runtime/// state (running flags, logs, execution IDs).+ /// Debounced: skips disk scan if last reload was < 2 seconds ago.pub async fn reload_pipes(&self) -> Result<()> {+ {+ let last = self.last_reload.lock().await;+ if last.elapsed() < std::time::Duration::from_secs(2) {+ return Ok(());+ }+ }+let mut pipes = self.pipes.lock().await;let entries = match std::fs::read_dir(&self.pipes_dir) {@@ -490,7 +502,7 @@ impl PipeManager {if !pipes.contains_key(&dir_name) {info!("discovered new pipe: {}", dir_name);}- pipes.insert(dir_name, (config, body));+ pipes.insert(dir_name, (config, body, content));}Err(e) => {warn!("failed to parse {:?}: {}", pipe_md, e);@@ -514,6 +526,9 @@ impl PipeManager {false});+ // Update debounce timestamp+ *self.last_reload.lock().await = Instant::now();+Ok(())}@@ -525,13 +540,10 @@ impl PipeManager {let exec_ids = self.running_execution_ids.lock().await;let mut result = Vec::new();- for (name, (config, body)) in pipes.iter() {+ for (name, (config, body, raw)) in pipes.iter() {let pipe_logs = logs.get(name);let last_log = pipe_logs.and_then(|l| l.back());let last_error = last_log.filter(|l| !l.success).map(|l| l.stderr.clone());- // Read raw file from disk for editing- let raw_content = std::fs::read_to_string(self.pipes_dir.join(name).join("pipe.md"))- .unwrap_or_else(|_| serialize_pipe(config, body).unwrap_or_default());let mut cfg = config.clone();cfg.name = name.clone(); // always use directory nameresult.push(PipeStatus {@@ -540,7 +552,7 @@ impl PipeManager {last_success: last_log.map(|l| l.success),is_running: running.contains_key(name),prompt_body: body.clone(),- raw_content,+ raw_content: raw.clone(),last_error,current_execution_id: exec_ids.get(name).copied(),consecutive_failures: 0,@@ -556,12 +568,10 @@ impl PipeManager {let running = self.running.lock().await;let exec_ids = self.running_execution_ids.lock().await;- pipes.get(name).map(|(config, body)| {+ pipes.get(name).map(|(config, body, raw)| {let pipe_logs = logs.get(name);let last_log = pipe_logs.and_then(|l| l.back());let last_error = last_log.filter(|l| !l.success).map(|l| l.stderr.clone());- let raw_content = std::fs::read_to_string(self.pipes_dir.join(name).join("pipe.md"))- .unwrap_or_else(|_| serialize_pipe(config, body).unwrap_or_default());let mut cfg = config.clone();cfg.name = name.to_string(); // always use directory namePipeStatus {@@ -570,7 +580,7 @@ impl PipeManager {last_success: last_log.map(|l| l.success),is_running: running.contains_key(name),prompt_body: body.clone(),- raw_content,+ raw_content: raw.clone(),last_error,current_execution_id: exec_ids.get(name).copied(),consecutive_failures: 0,@@ -595,6 +605,24 @@ impl PipeManager {}}+ /// List all pipes with status and recent executions in a single call.+ /// Avoids N+1 requests by fetching executions for all pipes at once.+ pub async fn list_pipes_with_executions(+ &self,+ exec_limit: i32,+ ) -> Vec<(PipeStatus, Vec<PipeExecution>)> {+ let statuses = self.list_pipes().await;+ let mut result = Vec::with_capacity(statuses.len());+ for status in statuses {+ let execs = self+ .get_executions(&status.config.name, exec_limit)+ .await+ .unwrap_or_default();+ result.push((status, execs));+ }+ result+ }+/// Run a pipe once (manual trigger or scheduled)./// NOTE: this blocks for the entire execution — avoid calling while/// holding the outer PipeManager mutex from an API handler.@@ -607,7 +635,7 @@ impl PipeManager {/// in a spawned tokio task. Use this from API handlers to avoid holding/// the PipeManager mutex for the entire execution duration.pub async fn start_pipe_background(&self, name: &str) -> Result<()> {- let (config, body) = {+ let (config, body, _raw) = {let pipes = self.pipes.lock().await;pipes.get(name)@@ -894,7 +922,7 @@ impl PipeManager {/// Run a pipe once with an explicit trigger type.async fn run_pipe_with_trigger(&self, name: &str, trigger: &str) -> Result<PipeRunLog> {- let (config, body) = {+ let (config, body, _raw) = {let pipes = self.pipes.lock().await;pipes.get(name)@@ -1186,12 +1214,13 @@ impl PipeManager {let (mut config, body) = parse_frontmatter(&content)?;config.enabled = enabled;let new_content = serialize_pipe(&config, &body)?;- std::fs::write(&pipe_md, new_content)?;+ std::fs::write(&pipe_md, &new_content)?;// Update in-memorylet mut pipes = self.pipes.lock().await;if let Some(entry) = pipes.get_mut(name) {entry.0.enabled = enabled;+ entry.2 = new_content;}info!(@@ -1226,6 +1255,7 @@ impl PipeManager {if let Some(entry) = pipes.get_mut(name) {entry.0 = config;entry.1 = body;+ entry.2 = raw.to_string();}return Ok(());}@@ -1281,13 +1311,14 @@ impl PipeManager {}let new_content = serialize_pipe(&config, &new_body)?;- std::fs::write(&pipe_md, new_content)?;+ std::fs::write(&pipe_md, &new_content)?;// Update in-memorylet mut pipes = self.pipes.lock().await;if let Some(entry) = pipes.get_mut(name) {entry.0 = config;entry.1 = new_body;+ entry.2 = new_content;}Ok(())@@ -1380,7 +1411,7 @@ impl PipeManager {.lock().await.get(name)- .and_then(|(c, _)| self.executors.get(&c.agent))+ .and_then(|(c, _, _)| self.executors.get(&c.agent)){let _ = executor.kill(&handle);}@@ -1414,7 +1445,7 @@ impl PipeManager {if let Some(handle) = handle {if handle.pid != 0 {let pipes = self.pipes.lock().await;- if let Some((config, _)) = pipes.get(name) {+ if let Some((config, _, _)) = pipes.get(name) {if let Some(executor) = self.executors.get(&config.agent) {executor.kill(&handle)?;}@@ -1480,7 +1511,7 @@ impl PipeManager {let pipe_snapshot: Vec<(String, PipeConfig, String)> = {let p = pipes.lock().await;p.iter()- .map(|(n, (c, b))| (n.clone(), c.clone(), b.clone()))+ .map(|(n, (c, b, _))| (n.clone(), c.clone(), b.clone())).collect()};diff --git a/crates/screenpipe-server/src/archive.rs b/crates/screenpipe-server/src/archive.rsindex 24467edbe..eefa69089 100644--- a/crates/screenpipe-server/src/archive.rs+++ b/crates/screenpipe-server/src/archive.rs@@ -88,7 +88,6 @@ impl Default for ArchiveConfig {#[derive(Debug, Deserialize)]pub struct ArchiveInitRequest {pub token: String,- pub password: String,pub retention_days: Option<u32>,}@@ -167,7 +166,14 @@ pub async fn archive_init()})?;- manager.initialize(&request.password).await.map_err(|e| {+ // Derive encryption password deterministically from the user's token.+ // Same account = same token = same key on every device. No password needed.+ let password = format!(+ "screenpipe-archive-{}",+ format!("{:x}", md5::compute(request.token.as_bytes()))+ );++ manager.initialize(&password).await.map_err(|e| {error!("archive: failed to initialize encryption: {}", e);(StatusCode::INTERNAL_SERVER_ERROR,diff --git a/crates/screenpipe-server/src/pipes_api.rs b/crates/screenpipe-server/src/pipes_api.rsindex 11f562f33..51c15724a 100644--- a/crates/screenpipe-server/src/pipes_api.rs+++ b/crates/screenpipe-server/src/pipes_api.rs@@ -44,19 +44,43 @@ pub struct ExecutionsQuery {pub limit: Option<i32>,}+#[derive(Deserialize)]+pub struct ListPipesQuery {+ pub include_executions: Option<bool>,+}+// ---------------------------------------------------------------------------// Handlers// ---------------------------------------------------------------------------/// GET /pipes — list all pipes with status./// Re-scans disk so pipes installed externally (e.g. via CLI) are picked up.-pub async fn list_pipes(State(pm): State<SharedPipeManager>) -> Json<Value> {+/// Pass `?include_executions=true` to get recent executions inline (avoids N+1 requests).+pub async fn list_pipes(+ State(pm): State<SharedPipeManager>,+ Query(query): Query<ListPipesQuery>,+) -> Json<Value> {let mgr = pm.lock().await;if let Err(e) = mgr.reload_pipes().await {tracing::warn!("failed to reload pipes from disk: {}", e);}- let pipes = mgr.list_pipes().await;- Json(json!({ "data": pipes }))+ if query.include_executions.unwrap_or(false) {+ let pipes_with_execs = mgr.list_pipes_with_executions(5).await;+ let data: Vec<Value> = pipes_with_execs+ .into_iter()+ .map(|(status, execs)| {+ let mut obj = serde_json::to_value(&status).unwrap_or(json!({}));+ if let Some(map) = obj.as_object_mut() {+ map.insert("recent_executions".to_string(), json!(execs));+ }+ obj+ })+ .collect();+ Json(json!({ "data": data }))+ } else {+ let pipes = mgr.list_pipes().await;+ Json(json!({ "data": pipes }))+ }}/// GET /pipes/:id — single pipe detail.