YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix: use dedicated runtime for embedded server to reduce CPU contention
Louis Beaumonte742afac21b0
diff --git a/screenpipe-app-tauri/components/global-chat.tsx b/screenpipe-app-tauri/components/global-chat.tsxindex b0c068f9e..c370f8d68 100644--- a/screenpipe-app-tauri/components/global-chat.tsx+++ b/screenpipe-app-tauri/components/global-chat.tsx@@ -568,7 +568,8 @@ export function GlobalChat() {const [piInfo, setPiInfo] = useState<{ running: boolean; projectDir: string | null; pid: number | null } | null>(null);const [piProjectDir, setPiProjectDir] = useState<string>("");const [piStarting, setPiStarting] = useState(false);- const [piStreamingText, setPiStreamingText] = useState<string>("");+ const piStreamingTextRef = useRef<string>("");+ const piMessageIdRef = useRef<string | null>(null);// Chat history stateconst [conversationId, setConversationId] = useState<string | null>(null);@@ -1057,22 +1058,17 @@ export function GlobalChat() {const isPi = activePreset?.provider === "pi";const hasValidModel = isPi || (activePreset?.model && activePreset.model.trim() !== "");const needsLogin = (activePreset?.provider === "screenpipe-cloud" || isPi) && !settings.user?.token;- const needsProjectDir = isPi && !piProjectDir;- const piReady = isPi ? (piInfo?.running && !needsProjectDir) : true;- const canChat = hasPresets && hasValidModel && !needsLogin && piReady;+ const piReady = isPi ? piInfo?.running : true;+ const canChat = hasPresets && hasValidModel && !needsLogin && (isPi ? piReady : true);- // Load Pi project dir from localStorage+ // Auto-set Pi project dir to temp locationuseEffect(() => {- const saved = localStorage.getItem("pi_project_dir");- if (saved) setPiProjectDir(saved);- }, []);-- // Save Pi project dir- useEffect(() => {- if (piProjectDir) {- localStorage.setItem("pi_project_dir", piProjectDir);+ if (isPi && !piProjectDir) {+ // Use a default temp directory for Pi+ const defaultDir = "/tmp/screenpipe-pi-chat";+ setPiProjectDir(defaultDir);}- }, [piProjectDir]);+ }, [isPi, piProjectDir]);// Start Pi when neededuseEffect(() => {@@ -1080,13 +1076,18 @@ export function GlobalChat() {const startPi = async () => {setPiStarting(true);+ console.log("[Pi] Starting with dir:", piProjectDir);try {const result = await commands.piStart(piProjectDir, settings.user?.token ?? null);+ console.log("[Pi] Start result:", result);if (result.status === "ok") {setPiInfo(result.data);} else {+ console.error("[Pi] Start failed:", result.error);toast({ title: "Failed to start Pi", description: result.error, variant: "destructive" });}+ } catch (e) {+ console.error("[Pi] Start exception:", e);} finally {setPiStarting(false);}@@ -1098,29 +1099,105 @@ export function GlobalChat() {useEffect(() => {if (!isPi) return;- const unlistenEvent = listen<any>("pi_event", (event) => {- const data = event.payload;- console.log("[Pi Event]", data);-- // Handle different event types- if (data.type === "message_update" && data.assistantMessageEvent) {- const evt = data.assistantMessageEvent;- if (evt.type === "text_delta" && evt.delta) {- setPiStreamingText(prev => prev + evt.delta);+ let unlistenEvent: (() => void) | null = null;+ let unlistenTerminated: (() => void) | null = null;+ let unlistenOutput: (() => void) | null = null;+ let mounted = true;++ const setup = async () => {+ unlistenEvent = await listen<any>("pi_event", (event) => {+ if (!mounted) return;+ const data = event.payload;+ console.log("[Pi Event]", data.type, data);++ // Handle different event types+ if (data.type === "message_update" && data.assistantMessageEvent) {+ const evt = data.assistantMessageEvent;+ if (evt.type === "text_delta" && evt.delta) {+ piStreamingTextRef.current += evt.delta;+ // Update the message if we have an active message ID+ if (piMessageIdRef.current) {+ const msgId = piMessageIdRef.current;+ const content = piStreamingTextRef.current;+ setMessages((prev) =>+ prev.map((m) => m.id === msgId ? { ...m, content } : m)+ );+ }+ }+ } else if (data.type === "tool_execution_start") {+ // Tool started - show what's happening+ console.log("[Pi] Tool started:", data.toolName, data.args);+ if (piMessageIdRef.current) {+ const msgId = piMessageIdRef.current;+ const currentText = piStreamingTextRef.current;+ const toolInfo = `\n\n*Running ${data.toolName}...*`;+ setMessages((prev) =>+ prev.map((m) => m.id === msgId ? { ...m, content: currentText + toolInfo } : m)+ );+ }+ } else if (data.type === "tool_execution_update") {+ // Tool progress+ console.log("[Pi] Tool update:", data.toolName, data.partialResult);+ } else if (data.type === "tool_execution_end") {+ // Tool finished+ console.log("[Pi] Tool ended:", data.toolName, data.isError);+ if (piMessageIdRef.current) {+ const msgId = piMessageIdRef.current;+ const content = piStreamingTextRef.current;+ setMessages((prev) =>+ prev.map((m) => m.id === msgId ? { ...m, content } : m)+ );+ }+ } else if (data.type === "agent_end") {+ // Agent finished - final update+ console.log("[Pi] Agent ended");+ if (piMessageIdRef.current) {+ const msgId = piMessageIdRef.current;+ const content = piStreamingTextRef.current || "Done";+ setMessages((prev) =>+ prev.map((m) => m.id === msgId ? { ...m, content } : m)+ );+ }+ piStreamingTextRef.current = "";+ piMessageIdRef.current = null;+ setIsLoading(false);+ setIsStreaming(false);+ } else if (data.type === "response" && data.success === false) {+ // Error response+ console.error("[Pi] Error:", data.error);+ if (piMessageIdRef.current) {+ const msgId = piMessageIdRef.current;+ setMessages((prev) =>+ prev.map((m) => m.id === msgId ? { ...m, content: `Error: ${data.error}` } : m)+ );+ }+ piStreamingTextRef.current = "";+ piMessageIdRef.current = null;+ setIsLoading(false);+ setIsStreaming(false);}- } else if (data.type === "agent_end") {- // Agent finished- setPiStreamingText("");- }- });+ });- const unlistenTerminated = listen("pi_terminated", () => {- setPiInfo(null);- });+ unlistenTerminated = await listen("pi_terminated", () => {+ if (!mounted) return;+ console.log("[Pi] Process terminated");+ setPiInfo(null);+ });++ // Also listen for raw output for debugging+ unlistenOutput = await listen<string>("pi_output", (event) => {+ if (!mounted) return;+ console.log("[Pi Raw]", event.payload);+ });+ };++ setup();return () => {- unlistenEvent.then(fn => fn());- unlistenTerminated.then(fn => fn());+ mounted = false;+ unlistenEvent?.();+ unlistenTerminated?.();+ unlistenOutput?.();};}, [isPi]);@@ -1147,26 +1224,12 @@ export function GlobalChat() {if (!activePreset) return "No preset selected";if (!hasValidModel) return `No model selected in "${activePreset.id}" preset - click edit to add one`;if (needsLogin) return "Login required";- if (isPi && needsProjectDir) return "Select a project folder for Pi";if (isPi && piStarting) return "Starting Pi agent...";if (isPi && !piReady) return "Connecting to Pi agent...";return null;};const disabledReason = getDisabledReason();- // Pi project folder picker- const selectPiProject = async () => {- const { open: openDialog } = await import("@tauri-apps/plugin-dialog");- const selected = await openDialog({- directory: true,- multiple: false,- title: "Select Project Folder for Pi Agent",- });- if (selected) {- setPiProjectDir(selected as string);- }- };-// Listen for Rust-level open-chat event (Cmd+L / Ctrl+L global shortcut)useEffect(() => {const unlisten = listen("open-chat", () => {@@ -1368,23 +1431,49 @@ export function GlobalChat() {};const assistantMessageId = (Date.now() + 1).toString();++ // Set up refs for event handler to use+ piStreamingTextRef.current = "";+ piMessageIdRef.current = assistantMessageId;+setMessages((prev) => [...prev, newUserMessage]);setInput("");setIsLoading(true);setIsStreaming(true);- setPiStreamingText("");++ // Timeout failsafe - if no agent_end after 3 minutes, stop loading+ const timeoutId = setTimeout(() => {+ if (piMessageIdRef.current === assistantMessageId) {+ console.warn("[Pi] Timeout waiting for response");+ piMessageIdRef.current = null;+ setIsLoading(false);+ setIsStreaming(false);+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId && m.content === "Processing..."+ ? { ...m, content: "Request timed out. Check if Pi is running correctly." }+ : m+ )+ );+ }+ }, 180000);try {// Add placeholder for responsesetMessages((prev) => [...prev,- { id: assistantMessageId, role: "assistant", content: "", timestamp: Date.now() },+ { id: assistantMessageId, role: "assistant", content: "Processing...", timestamp: Date.now() },]);- // Send prompt to Pi+ console.log("[Pi] Sending prompt:", userMessage);++ // Send prompt to Pi - the pi_event listener in useEffect handles the restconst result = await commands.piPrompt(userMessage);+ console.log("[Pi] Prompt result:", result);if (result.status === "error") {+ clearTimeout(timeoutId);+ piMessageIdRef.current = null;setMessages((prev) =>prev.map((m) =>m.id === assistantMessageId@@ -1397,48 +1486,13 @@ export function GlobalChat() {return;}- // Wait for Pi events to update the message- // The pi_event listener will update piStreamingText- // We need to watch for changes and update the message- const checkInterval = setInterval(() => {- setMessages((prev) =>- prev.map((m) =>- m.id === assistantMessageId- ? { ...m, content: piStreamingText || "Processing..." }- : m- )- );- }, 100);-- // Wait for agent_end or timeout- const timeout = setTimeout(() => {- clearInterval(checkInterval);- setIsLoading(false);- setIsStreaming(false);- }, 120000); // 2 minute timeout-- // Listen for agent_end to stop- const unlistenEnd = await listen("pi_event", (event: any) => {- if (event.payload?.type === "agent_end") {- clearInterval(checkInterval);- clearTimeout(timeout);- unlistenEnd();-- // Final update with accumulated text- setMessages((prev) =>- prev.map((m) =>- m.id === assistantMessageId- ? { ...m, content: piStreamingText || "Done" }- : m- )- );- setIsLoading(false);- setIsStreaming(false);- }- });+ // The pi_event listener will handle streaming updates and completion+ // Clear timeout when agent_end is received (handled in the listener)} catch (error) {+ clearTimeout(timeoutId);console.error("Pi error:", error);+ piMessageIdRef.current = null;setMessages((prev) =>prev.map((m) =>m.id === assistantMessageId@@ -2093,12 +2147,10 @@ export function GlobalChat() {</div><div className="flex-1 min-w-0"><h2 className="font-semibold text-sm tracking-tight">- {isPi ? "Pi Agent" : "Pipe AI"}+ Pipe AI</h2><p className="text-[10px] text-muted-foreground font-mono uppercase tracking-wider truncate">- {isPi && piProjectDir- ? piProjectDir.split("/").pop() || piProjectDir- : "Screen Activity Assistant"}+ Screen Activity Assistant</p></div><Button@@ -2229,7 +2281,7 @@ export function GlobalChat() {<div className="relative flex flex-col items-center justify-center py-12 space-y-4"><div className={cn("relative p-6 rounded-2xl border",- needsLogin || needsProjectDir+ needsLogin || piStarting? "bg-muted/50 border-border/50": "bg-destructive/5 border-destructive/20")}>@@ -2239,9 +2291,7 @@ export function GlobalChat() {<div className="absolute bottom-0 left-0 w-4 h-4 border-l-2 border-b-2 border-current opacity-20 rounded-bl" /><div className="absolute bottom-0 right-0 w-4 h-4 border-r-2 border-b-2 border-current opacity-20 rounded-br" />- {needsProjectDir ? (- <Settings className="h-12 w-12 text-muted-foreground" />- ) : needsLogin ? (+ {needsLogin ? (<PipeAIIconLarge size={48} className="text-muted-foreground" />) : piStarting ? (<Loader2 className="h-12 w-12 text-muted-foreground animate-spin" />@@ -2251,23 +2301,13 @@ export function GlobalChat() {</div><div className="text-center space-y-2"><h3 className="font-semibold tracking-tight">- {needsProjectDir ? "Select Project Folder" : !hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : piStarting ? "Starting Pi..." : "Login Required"}+ {!hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : piStarting ? "Starting Pi..." : "Login Required"}</h3><p className="text-sm text-muted-foreground max-w-sm">{disabledReason}</p></div>- {needsProjectDir && (- <Button- variant="default"- onClick={selectPiProject}- className="gap-2 font-medium bg-foreground text-background hover:bg-foreground/90"- >- <Settings className="h-4 w-4" />- Select Folder- </Button>- )}- {needsLogin && !needsProjectDir && (+ {needsLogin && (<Buttonvariant="default"onClick={() => openUrl("https://screenpi.pe/login")}@@ -2277,7 +2317,7 @@ export function GlobalChat() {Login</Button>)}- {!hasPresets && !needsProjectDir && (+ {!hasPresets && (<Buttonvariant="outline"onClick={async () => {@@ -2290,7 +2330,7 @@ export function GlobalChat() {Go to Settings</Button>)}- {hasPresets && !hasValidModel && !needsProjectDir && (+ {hasPresets && !hasValidModel && (<p className="text-xs text-muted-foreground font-mono">Use the preset selector below to configure a model</p>diff --git a/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsxindex 35e5ebe27..017223dc7 100644--- a/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx+++ b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx@@ -429,13 +429,47 @@ export function ObsidianSyncCard() {const openObsidian = async () => {if (!settings.vaultPath) return;- // Use path-based deep link (don't encode - Obsidian expects raw path)- const deepLink = `obsidian://open?path=${settings.vaultPath}`;-try {- // Use the 'open' command on macOS to handle custom URL schemes+ // Read Obsidian's vault registry to find the correct vault name+ const { homeDir } = await import("@tauri-apps/api/path");+ const { readTextFile } = await import("@tauri-apps/plugin-fs");++ const home = await homeDir();+ const obsidianConfigPath = `${home}Library/Application Support/obsidian/obsidian.json`;++ let vaultName: string | null = null;++ try {+ const configContent = await readTextFile(obsidianConfigPath);+ const config = JSON.parse(configContent);++ // Find vault that matches our path+ for (const [_id, vault] of Object.entries(config.vaults || {})) {+ const v = vault as { path: string };+ if (v.path === settings.vaultPath) {+ // Extract vault name from path+ vaultName = settings.vaultPath.split("/").pop() || null;+ break;+ }+ }+ } catch (e) {+ console.warn("Could not read Obsidian config:", e);+ }++ // Use vault name if found, otherwise just open Obsidian app+ const deepLink = vaultName+ ? `obsidian://open?vault=${encodeURIComponent(vaultName)}`+ : "obsidian://";+const command = Command.create("open", [deepLink]);await command.execute();++ if (!vaultName) {+ toast({+ title: "Opened Obsidian",+ description: "Vault not found in Obsidian registry. You may need to open it manually.",+ });+ }} catch (e) {console.error("Failed to open Obsidian:", e);toast({diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex 717b86a23..3e9a9c25b 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -703,6 +703,7 @@ pub fn parse_shortcut(shortcut_str: &str) -> Result<Shortcut, String> {// check if the server is running#[tauri::command]#[specta::specta]+#[allow(dead_code)]async fn is_server_running(app: AppHandle) -> Result<bool, String> {let store = app.state::<store::SettingsStore>();let port = store.port;@@ -1140,7 +1141,6 @@ async fn main() {// Get app handle once for all initializationslet app_handle = app.handle().clone();- let server_running = is_server_running(app_handle.clone());// Initialize server first (core service)let server_shutdown_tx = spawn_server(app_handle.clone(), 11435);@@ -1151,48 +1151,83 @@ async fn main() {info!("use_dev_mode: {}", use_dev_mode);// Start embedded server in non-dev mode+ // Use a dedicated thread with its own tokio runtime to avoid competing with Tauri's UI runtimeif !use_dev_mode {let store_clone = store.clone();let base_dir_clone = base_dir.clone();let sidecar_state = app_handle.state::<SidecarState>();let sidecar_state_inner = sidecar_state.0.clone();- tauri::async_runtime::spawn(async move {- if server_running.await.unwrap_or(false) {- info!("Server already running, skipping embedded server start");- return;- }-- // Check permissions before starting- let permissions_check = permissions::do_permissions_check(false);- let disable_audio = store_clone.disable_audio;-- if !permissions_check.screen_recording.permitted() {- warn!("Screen recording permission not granted: {:?}. Server will not start.", permissions_check.screen_recording);- return;- }-- if !disable_audio && !permissions_check.microphone.permitted() {- warn!("Microphone permission not granted: {:?}. Audio recording will not work.", permissions_check.microphone);- }-- info!("Starting embedded screenpipe server...");- let config = embedded_server::EmbeddedServerConfig::from_store(- &store_clone,- base_dir_clone,- );-- match embedded_server::start_embedded_server(config).await {- Ok(handle) => {- info!("Embedded screenpipe server started successfully");- // Store handle in state so it can be stopped/restarted later- let mut guard = sidecar_state_inner.lock().await;- *guard = Some(handle);- }- Err(e) => {- error!("Failed to start embedded server: {}", e);- }- }- });++ // Spawn a dedicated thread for the server with its own runtime+ // This prevents CPU contention between UI and recording workloads+ std::thread::Builder::new()+ .name("screenpipe-server".to_string())+ .spawn(move || {+ // Create a dedicated multi-threaded runtime for the server+ let server_runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(4)+ .thread_name("screenpipe-worker")+ .enable_all()+ .build()+ .expect("Failed to create server runtime");++ server_runtime.block_on(async move {+ // Check if server already running (with timeout)+ let server_running = tokio::time::timeout(+ std::time::Duration::from_secs(2),+ async {+ reqwest::Client::new()+ .get("http://localhost:3030/health")+ .timeout(std::time::Duration::from_secs(1))+ .send()+ .await+ .is_ok()+ }+ ).await.unwrap_or(false);++ if server_running {+ info!("Server already running, skipping embedded server start");+ return;+ }++ // Check permissions before starting+ let permissions_check = permissions::do_permissions_check(false);+ let disable_audio = store_clone.disable_audio;++ if !permissions_check.screen_recording.permitted() {+ warn!("Screen recording permission not granted: {:?}. Server will not start.", permissions_check.screen_recording);+ return;+ }++ if !disable_audio && !permissions_check.microphone.permitted() {+ warn!("Microphone permission not granted: {:?}. Audio recording will not work.", permissions_check.microphone);+ }++ info!("Starting embedded screenpipe server on dedicated runtime...");+ let config = embedded_server::EmbeddedServerConfig::from_store(+ &store_clone,+ base_dir_clone,+ );++ match embedded_server::start_embedded_server(config).await {+ Ok(handle) => {+ info!("Embedded screenpipe server started successfully on dedicated runtime");+ // Store handle in state so it can be stopped/restarted later+ let mut guard = sidecar_state_inner.blocking_lock();+ *guard = Some(handle);++ // Keep the runtime alive+ loop {+ tokio::time::sleep(std::time::Duration::from_secs(60)).await;+ }+ }+ Err(e) => {+ error!("Failed to start embedded server: {}", e);+ }+ }+ });+ })+ .expect("Failed to spawn server thread");} else {debug!("Skipping server start: dev_mode enabled");}diff --git a/screenpipe-app-tauri/src-tauri/src/pi.rs b/screenpipe-app-tauri/src-tauri/src/pi.rsindex 85401918b..75b07efc5 100644--- a/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -10,7 +10,7 @@ use std::path::PathBuf;use std::process::{Child, ChildStdin, Command, Stdio};use std::sync::Arc;use tauri::Emitter;-use tauri::{AppHandle, Manager, State};+use tauri::{AppHandle, State};use tokio::sync::Mutex;use tracing::{debug, error, info, warn};@@ -49,6 +49,7 @@ pub struct PiCheckResult {/// RPC Response from Pi#[derive(Debug, Deserialize)]+#[allow(dead_code)]struct RpcResponse {#[serde(rename = "type")]response_type: String,@@ -59,6 +60,7 @@ struct RpcResponse {id: Option<String>,}+#[allow(dead_code)]pub struct PiManager {child: Option<Child>,stdin: Option<ChildStdin>,@@ -343,15 +345,27 @@ pub async fn pi_start(let app_handle = app.clone();std::thread::spawn(move || {let reader = BufReader::new(stdout);+ info!("Pi stdout reader started");for line in reader.lines() {match line {Ok(line) => {- debug!("Pi stdout: {}", line);+ // Log all output at info level for debugging+ info!("Pi stdout: {}", line);// Try to parse as JSON and emit event- if let Ok(event) = serde_json::from_str::<Value>(&line) {- let _ = app_handle.emit("pi_event", &event);+ match serde_json::from_str::<Value>(&line) {+ Ok(event) => {+ info!("Pi event type: {:?}", event.get("type"));+ if let Err(e) = app_handle.emit("pi_event", &event) {+ error!("Failed to emit pi_event: {}", e);+ }+ }+ Err(e) => {+ warn!("Pi stdout not JSON: {} (line: {})", e, &line[..line.len().min(100)]);+ }+ }+ if let Err(e) = app_handle.emit("pi_output", &line) {+ error!("Failed to emit pi_output: {}", e);}- let _ = app_handle.emit("pi_output", &line);}Err(e) => {error!("Error reading pi stdout: {}", e);@@ -368,19 +382,18 @@ pub async fn pi_start(let app_handle = app.clone();std::thread::spawn(move || {let reader = BufReader::new(stderr);+ info!("Pi stderr reader started");for line in reader.lines() {match line {Ok(line) => {- if line.to_lowercase().contains("error") {- error!("Pi stderr: {}", line);- } else {- debug!("Pi stderr: {}", line);- }+ // Log all stderr at info level for debugging+ info!("Pi stderr: {}", line);let _ = app_handle.emit("pi_log", &line);}Err(_) => break,}}+ info!("Pi stderr reader ended");});}