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
feat: add endpoint to show window on demand
Louis Beaumont27869bf4b931
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex 49db5ce30..f0665b816 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -5289,7 +5289,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "0.36.3"+version = "0.36.4"dependencies = ["anyhow","async-stream",diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rsindex 8250e4007..271998c31 100644--- a/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -128,61 +128,8 @@ pub fn hide_main_window(app_handle: &tauri::AppHandle<tauri::Wry>) {}}-#[tauri::command]-pub fn show_meetings(app_handle: tauri::AppHandle<tauri::Wry>) {- if let Some(window) = app_handle.get_webview_window("meetings") {- #[cfg(target_os = "macos")]- let _ = app_handle.set_activation_policy(tauri::ActivationPolicy::Accessory);- // let _ = window.set_visible_on_all_workspaces(true);- // let _ = window.set_always_on_top(true);- let _ = window.set_decorations(true);- let _ = window.show();- let _ = window.set_focus();- } else {- let _window = tauri::WebviewWindowBuilder::new(- &app_handle,- "meetings",- tauri::WebviewUrl::App("meetings.html".into()),- )- .title("meetings")- .decorations(true)- .transparent(true)- // .always_on_top(true)- // .visible_on_all_workspaces(true) // Added this- .center()- .build()- .unwrap();- }-}-#[tauri::command]-pub fn show_identify_speakers(app_handle: tauri::AppHandle<tauri::Wry>) {- if let Some(window) = app_handle.get_webview_window("identify-speakers") {- #[cfg(target_os = "macos")]- let _ = app_handle.set_activation_policy(tauri::ActivationPolicy::Accessory);-- // let _ = window.set_visible_on_all_workspaces(true);- // let _ = window.set_always_on_top(true);- let _ = window.set_decorations(true);- let _ = window.show();- let _ = window.set_focus();- } else {- let _window = tauri::WebviewWindowBuilder::new(- &app_handle,- "identify-speakers",- tauri::WebviewUrl::App("identify-speakers.html".into()),- )- .title("identify-speakers")- .decorations(true)- .transparent(true)- // .always_on_top(true)- // .visible_on_all_workspaces(true) // Added this- .center()- .build()- .unwrap();- }-}const DEFAULT_SHORTCUT: &str = "Super+Alt+S";diff --git a/screenpipe-app-tauri/src-tauri/src/config.rs b/screenpipe-app-tauri/src-tauri/src/config.rsnew file mode 100644index 000000000..819e5f339--- /dev/null+++ b/screenpipe-app-tauri/src-tauri/src/config.rs@@ -0,0 +1,14 @@+use std::{fs, path::PathBuf};+use tauri::Manager;++pub fn get_base_dir(+ app: &tauri::AppHandle,+ custom_path: Option<String>,+) -> anyhow::Result<PathBuf> {+ let default_path = app.path().local_data_dir().unwrap().join("screenpipe");++ let local_data_dir = custom_path.map(PathBuf::from).unwrap_or(default_path);++ fs::create_dir_all(local_data_dir.join("data"))?;+ Ok(local_data_dir)+}diff --git a/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs b/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rsdeleted file mode 100644index 806409ace..000000000--- a/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs+++ /dev/null@@ -1,259 +0,0 @@-use anyhow::{anyhow, Result};-use serde::{Deserialize, Serialize};-use std::env;-use std::time::Duration;-use tauri::async_runtime::Receiver;-use tauri::Emitter;-use tauri::Manager;-use tauri_plugin_shell::process::CommandEvent;-use tauri_plugin_shell::ShellExt;-use tokio::time::sleep;-use tracing::{error, info};-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct EmbeddedLLMSettings {- pub enabled: bool,- pub model: String,- pub port: u16,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub enum OllamaStatus {- Idle,- Running,- Error,-}--pub struct LLMSidecar {- settings: EmbeddedLLMSettings,- status: OllamaStatus,-}--impl LLMSidecar {- pub fn new(settings: EmbeddedLLMSettings) -> Self {- Self {- settings,- status: OllamaStatus::Idle,- }- }-- pub async fn start(&mut self, app: tauri::AppHandle) -> Result<String> {- self.status = OllamaStatus::Running;- app.emit("ollama_status", &self.status)?;-- // Get the resource directory path- let resource_path = app.path().resource_dir().unwrap();-- // Append the resource path to CUDA_PATH- let cuda_path = env::var("CUDA_PATH").unwrap_or_default();- let new_cuda_path = format!("{}:{}", cuda_path, resource_path.display());-- info!("Starting Ollama serve command...");- let mut serve_command = app.shell().sidecar("ollama").unwrap();- serve_command = serve_command- .args(["serve"])- .env(- "OLLAMA_HOST",- format!("http://localhost:{}", self.settings.port),- )- .env("CUDA_PATH", &new_cuda_path);-- #[cfg(target_os = "windows")]- {- serve_command = serve_command.env("OLLAMA_ORIGINS", "*");- }-- let (mut receiver, _) = serve_command.spawn()?;-- // Stream logs for serve command- self.stream_logs("ollama-serve", &mut receiver).await?;-- info!("Waiting for Ollama server to start...");- self.wait_for_server().await?;-- // Now run the model- info!("Starting Ollama model...");- let mut model_command = app.shell().sidecar("ollama").unwrap();- model_command = model_command- .args(["run", &self.settings.model])- .env("CUDA_PATH", &new_cuda_path);-- #[cfg(target_os = "windows")]- {- model_command = model_command.env("OLLAMA_ORIGINS", "*");- }-- let (mut receiver, _) = model_command.spawn()?;-- // Stream logs for model command- self.stream_logs("ollama-model", &mut receiver).await?;-- info!("Testing Ollama model...");- let test_result = self.test_model().await?;-- Ok(test_result)- }-- async fn stream_logs(&self, prefix: &str, rx: &mut Receiver<CommandEvent>) -> Result<()> {- while let Some(event) = rx.recv().await {- match event {- CommandEvent::Stdout(line) => {- info!("[{}][stdout] {}", prefix, String::from_utf8_lossy(&line));- }- CommandEvent::Stderr(line) => {- info!("[{}][stderr] {}", prefix, String::from_utf8_lossy(&line));- }- CommandEvent::Error(e) => {- error!("[{}][error] {}", prefix, e);- }- CommandEvent::Terminated(payload) => {- info!(- "[{}][terminated] code: {:?}, signal: {:?}",- prefix, payload.code, payload.signal- );- break;- }- _ => {}- }- }- Ok(())- }-- async fn wait_for_server(&self) -> Result<()> {- let max_retries = 30;- let retry_interval = Duration::from_secs(1);-- for _ in 0..max_retries {- if let Ok(response) = reqwest::get(&format!(- "http://localhost:{}/api/version",- self.settings.port- ))- .await- {- if response.status().is_success() {- info!("Ollama server started successfully");- return Ok(());- }- }- sleep(retry_interval).await;- }-- Err(anyhow!(- "Ollama server failed to start after maximum retries"- ))- }-- async fn test_model(&self) -> Result<String> {- const MAX_RETRIES: u32 = 3;- const RETRY_DELAY: Duration = Duration::from_secs(2);-- for attempt in 1..=MAX_RETRIES {- match self.attempt_model_test().await {- Ok(result) => {- info!("model test successful on attempt {}: {}", attempt, result);- return Ok(result);- }- Err(e) => {- if attempt == MAX_RETRIES {- return Err(anyhow!(- "failed to test model after {} attempts: {}",- MAX_RETRIES,- e- ));- }- error!("model test failed on attempt {}: {}", attempt, e);- sleep(RETRY_DELAY).await;- }- }- }-- unreachable!()- }-- async fn attempt_model_test(&self) -> Result<String> {- let client = reqwest::Client::new();- let response = client- .post(format!(- "http://localhost:{}/v1/chat/completions",- self.settings.port- ))- .json(&serde_json::json!({- "model": self.settings.model,- "messages": [- {- "role": "user",- "content": "say a one sentence joke about screen recording, all lower case"- }- ],- "max_tokens": 50,- "stream": false- }))- .send()- .await?;-- if !response.status().is_success() {- return Err(anyhow!("failed to get response from model"));- }-- let data: serde_json::Value = response.json().await?;- let result = data["choices"][0]["message"]["content"]- .as_str()- .ok_or_else(|| anyhow!("unexpected response format"))?- .trim()- .to_string();-- Ok(result)- }-- pub async fn stop(&mut self, app: tauri::AppHandle) -> Result<()> {- self.status = OllamaStatus::Idle;- app.emit("ollama_status", &self.status)?;-- #[cfg(target_os = "windows")]- {- app.shell()- .command("taskkill")- .args(["/F", "/IM", "ollama.exe"])- .spawn()- .unwrap();- }-- #[cfg(not(target_os = "windows"))]- {- let output = app- .shell()- .command("pkill")- .arg("ollama")- .output()- .await- .unwrap();- info!("Ollama stopped: {:?}", output);- }-- Ok(())- }-}--#[tauri::command]-pub async fn start_ollama_sidecar(- app: tauri::AppHandle,- settings: EmbeddedLLMSettings,-) -> Result<String, String> {- let mut llm_sidecar = LLMSidecar::new(settings);- llm_sidecar- .start(app)- .await- .map_err(|e| format!("Failed to start Ollama: {}", e))-}--#[tauri::command]-pub async fn stop_ollama_sidecar(app: tauri::AppHandle) -> Result<(), String> {- let mut llm_sidecar = LLMSidecar::new(EmbeddedLLMSettings {- enabled: false,- model: String::new(),- port: 0,- });- llm_sidecar- .stop(app)- .await- .map_err(|e| format!("Failed to stop Ollama: {}", e))-}diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex 89f22123b..eaf46062b 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -7,7 +7,6 @@ use commands::save_pipe_config;use commands::show_main_window;use serde_json::json;use serde_json::Value;-use sidecar::SidecarManager;use std::env;use std::fs;use std::fs::File;@@ -35,19 +34,30 @@ use crate::analytics::start_analytics;mod commands;mod disk_usage;-mod llm_sidecar;mod permissions;mod server;mod sidecar;mod store;mod tray;mod updates;+mod window_api;++pub use server::*;++pub use sidecar::*;++pub use icons::*;+pub use store::*;++mod config;+pub use config::get_base_dir;+pub use commands::reset_all_pipes;pub use commands::set_tray_health_icon;pub use commands::set_tray_unhealth_icon;pub use server::spawn_server;-pub use sidecar::stop_screenpipe;pub use sidecar::spawn_screenpipe;+pub use sidecar::stop_screenpipe;pub use store::get_profiles_store;pub use store::get_store;@@ -62,7 +72,6 @@ use tauri_plugin_global_shortcut::{Code, Modifiers, Shortcut};use tauri_plugin_sentry::sentry;mod health;use health::start_health_check;-pub struct SidecarState(Arc<tokio::sync::Mutex<Option<SidecarManager>>>);// New struct to hold shortcut configuration#[derive(Debug, Default)]@@ -351,18 +360,6 @@ async fn get_pipe_port(pipe_id: &str) -> anyhow::Result<u16> {.ok_or_else(|| anyhow::anyhow!("no port found for pipe {}", pipe_id))}-pub fn get_base_dir(- app: &tauri::AppHandle,- custom_path: Option<String>,-) -> anyhow::Result<PathBuf> {- let default_path = app.path().local_data_dir().unwrap().join("screenpipe");-- let local_data_dir = custom_path.map(PathBuf::from).unwrap_or(default_path);-- fs::create_dir_all(local_data_dir.join("data"))?;- Ok(local_data_dir)-}-#[derive(Debug, serde::Serialize)]pub struct LogFile {name: String,@@ -451,16 +448,16 @@ use tokio::time::{sleep, Duration};#[tauri::command]async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool, String> {debug!("Starting upload for file: {}", file_path);-+// Read file contents - do this outside retry loop to avoid multiple readslet file_contents = match tokio::fs::read(file_path).await {Ok(contents) => {debug!("Successfully read file of size: {} bytes", contents.len());contents- },+ }Err(e) => {error!("Failed to read file: {}", e);- return Err(e.to_string())+ return Err(e.to_string());}};@@ -477,7 +474,7 @@ async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool, St.put(signed_url).body(file_contents.clone()).send()- .await+ .await{Ok(response) => {if response.status().is_success() {@@ -486,7 +483,7 @@ async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool, St}last_error = format!("Upload failed with status: {}", response.status());error!("{} (attempt {}/{})", last_error, attempt, max_retries);- },+ }Err(e) => {last_error = format!("Request failed: {}", e);error!("{} (attempt {}/{})", last_error, attempt, max_retries);@@ -500,7 +497,10 @@ async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool, St}}- Err(format!("Upload failed after {} attempts. Last error: {}", max_retries, last_error))+ Err(format!(+ "Upload failed after {} attempts. Last error: {}",+ max_retries, last_error+ ))}// Helper function to parse shortcut string@@ -679,11 +679,7 @@ async fn main() {reset_all_pipes,set_tray_unhealth_icon,set_tray_health_icon,- llm_sidecar::start_ollama_sidecar,- llm_sidecar::stop_ollama_sidecar,commands::update_show_screenpipe_shortcut,- commands::show_meetings,- commands::show_identify_speakers,commands::get_disk_usage,commands::open_pipe_window,get_log_files,@@ -794,13 +790,13 @@ async fn main() {.unwrap_or(Value::Bool(true)).as_bool().unwrap_or(true);-+let is_autostart_enabled = store.get("autoStartEnabled").unwrap_or(Value::Bool(true)).as_bool().unwrap_or(true);-+if is_autostart_enabled {let _ = autostart_manager.enable();} else {@@ -878,7 +874,6 @@ async fn main() {if let Err(e) = manager.spawn(&app_handle).await {error!("Failed to spawn initial sidecar: {}", e);}-});} else {debug!("Dev mode enabled, skipping sidecar spawn and restart");diff --git a/screenpipe-app-tauri/src-tauri/src/server.rs b/screenpipe-app-tauri/src-tauri/src/server.rsindex 730fe62b5..a55c9ccc0 100644--- a/screenpipe-app-tauri/src-tauri/src/server.rs+++ b/screenpipe-app-tauri/src-tauri/src/server.rs@@ -1,3 +1,4 @@+use crate::window_api::show_specific_window;use crate::{get_base_dir, get_store};use axum::body::Bytes;use axum::response::sse::{Event, Sse};@@ -23,6 +24,7 @@ use tokio::sync::mpsc;use tower_http::cors::{Any, CorsLayer};use tower_http::trace::{DefaultMakeSpan, TraceLayer};use tracing::{error, info};+#[derive(Clone, serde::Serialize, serde::Deserialize)]struct LogEntry {pipe_id: String,@@ -33,7 +35,7 @@ struct LogEntry {#[derive(Clone)]pub struct ServerState {- app_handle: tauri::AppHandle,+ pub app_handle: tauri::AppHandle,settings_tx: broadcast::Sender<String>,}@@ -162,6 +164,7 @@ pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {.route("/sse/settings", axum::routing::get(settings_stream)).route("/sidecar/start", axum::routing::post(start_sidecar)).route("/sidecar/stop", axum::routing::post(stop_sidecar))+ .route("/window", axum::routing::post(show_specific_window)).layer(cors).layer(TraceLayer::new_for_http()diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rsindex f07b94ae9..4b7186b41 100644--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs@@ -1,5 +1,4 @@use crate::get_store;-use crate::SidecarState;use serde::{Deserialize, Serialize};use serde_json::Value;use std::sync::Arc;@@ -11,6 +10,8 @@ use tauri_plugin_store::Store;use tokio::sync::Mutex;use tracing::{debug, error, info};+pub struct SidecarState(pub Arc<tokio::sync::Mutex<Option<SidecarManager>>>);+#[derive(Debug, Serialize, Deserialize, Clone)]pub struct UserCredits {#[serde(rename = "user.credits.amount")]diff --git a/screenpipe-app-tauri/src-tauri/src/window_api.rs b/screenpipe-app-tauri/src-tauri/src/window_api.rsnew file mode 100644index 000000000..e3e8d40b1--- /dev/null+++ b/screenpipe-app-tauri/src-tauri/src/window_api.rs@@ -0,0 +1,93 @@+use axum::{extract::State, http::StatusCode, Json};+use serde::{Deserialize, Serialize};+use tauri::Manager;+use tracing::{error, info};++use crate::ServerState;++#[derive(Deserialize, Debug)]+pub struct OpenLocalPathPayload {+ path: String,+ port: u16,+ title: String,+ width: f64,+ height: f64,+ x: Option<i32>,+ y: Option<i32>,+ always_on_top: Option<bool>,+ transparent: Option<bool>,+ decorations: Option<bool>,+ hidden_title: Option<bool>,+ is_focused: Option<bool>,+ visible_on_all_workspaces: Option<bool>,+}++#[derive(Serialize)]+pub struct ApiResponse {+ success: bool,+ message: String,+}++pub async fn show_specific_window(+ State(state): State<ServerState>,+ Json(payload): Json<OpenLocalPathPayload>,+) -> Result<Json<ApiResponse>, (StatusCode, String)> {+ info!("opening local path: {}", payload.path);++ // Close existing window if it exists+ if let Some(existing_window) = state.app_handle.get_webview_window(&payload.title) {+ if let Err(e) = existing_window.destroy() {+ error!("failed to close existing window: {}", e);+ }+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;+ }+ #[cfg(target_os = "macos")]+ let _ = state+ .app_handle+ .set_activation_policy(tauri::ActivationPolicy::Accessory);+ let url = format!("http://localhost:{}{}", payload.port, payload.path);+ let window = tauri::WebviewWindowBuilder::new(+ &state.app_handle,+ &payload.title,+ tauri::WebviewUrl::External(url.parse().unwrap()),+ )+ .title(&payload.title)+ .transparent(payload.transparent.unwrap_or(true))+ .decorations(payload.decorations.unwrap_or(false))+ .hidden_title(payload.hidden_title.unwrap_or(true))+ .focused(payload.is_focused.unwrap_or(true))+ .inner_size(payload.width, payload.height)+ .always_on_top(payload.always_on_top.unwrap_or(true))+ .visible_on_all_workspaces(payload.visible_on_all_workspaces.unwrap_or(true))+ .build();++ match window {+ Ok(window) => {+ // Set position if provided+ if let (Some(x), Some(y)) = (payload.x, payload.y) {+ let _ = window+ .set_position(tauri::Position::Physical(tauri::PhysicalPosition { x, y }));+ }++ if let Err(e) = window.show() {+ error!("failed to show window: {}", e);+ return Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("failed to show window: {}", e),+ ));+ }++ Ok(Json(ApiResponse {+ success: true,+ message: "window opened successfully".to_string(),+ }))+ }+ Err(e) => {+ error!("failed to create window: {}", e);+ Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("failed to create window: {}", e),+ ))+ }+ }+}