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: simplify classifier to use /search API, add UI toggle + gateway routing

Louis Beaumontf725f53e186b
diff --git a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
index 025f829d8..5d57a0722 100644
--- a/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/recording-settings.tsx
@@ -1962,6 +1962,30 @@ Your screen is a pipe. Everything you see, hear, and type flows through it. Scre
{/* Text extraction — accessibility and input capture are always enabled (defaults in store.rs) */}
+ {/* Workflow event detection (cloud) */}
+ {settings.user?.cloud_subscribed && (
+ <Card className="border-border bg-card">
+ <CardContent className="px-3 py-2.5">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-2.5">
+ <Zap className="h-4 w-4 text-muted-foreground shrink-0" />
+ <div>
+ <h3 className="text-sm font-medium text-foreground flex items-center gap-1.5">
+ Workflow events
+ <span className="text-[10px] font-normal text-muted-foreground bg-muted px-1.5 py-0.5 rounded">cloud</span>
+ </h3>
+ <p className="text-xs text-muted-foreground">AI detects your workflow patterns and triggers event-based pipes</p>
+ </div>
+ </div>
+ <Switch
+ checked={settings.enableWorkflowEvents || false}
+ onCheckedChange={(checked) => handleSettingsChange({ enableWorkflowEvents: checked } as any, true)}
+ />
+ </div>
+ </CardContent>
+ </Card>
+ )}
+
</div>
{/* System */}
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 0ac75c81a..75f04cb0b 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -108,6 +108,8 @@ export type Settings = SettingsStore & {
useSystemDefaultAudio?: boolean;
enableInputCapture?: boolean;
enableAccessibility?: boolean;
+ /** Enable AI workflow event detection (cloud, triggers event-based pipes) */
+ enableWorkflowEvents?: boolean;
/** Audio transcription scheduling: "realtime" (default) or "batch" (longer chunks for quality) */
transcriptionMode?: "realtime" | "smart" | "batch";
/** User's name for speaker identification — input device audio will be labeled with this name */
@@ -166,6 +168,11 @@ export type Settings = SettingsStore & {
pipeNotifications: boolean;
mutedPipes: string[];
};
+ /** Remote devices to monitor pipes on (LAN addresses) */
+ monitorDevices?: Array<{
+ address: string;
+ label?: string;
+ }>;
}
export function getEffectiveFilters(settings: Settings) {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
index 6e4fa6c53..df9356572 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
@@ -499,13 +499,13 @@ pub async fn start_embedded_server(
if config.enable_workflow_events {
if let Some(ref token) = config.user_id {
if !token.is_empty() {
- let db_for_classifier = db.clone();
let token_for_classifier = token.clone();
+ let local_port = config.port;
tokio::spawn(async move {
screenpipe_engine::workflow_classifier::start_workflow_classifier(
- db_for_classifier,
"https://api.screenpi.pe".to_string(),
token_for_classifier,
+ local_port,
std::time::Duration::from_secs(30),
)
.await;
diff --git a/crates/screenpipe-engine/src/workflow_classifier.rs b/crates/screenpipe-engine/src/workflow_classifier.rs
index 8cc73e0c9..7152400c4 100644
--- a/crates/screenpipe-engine/src/workflow_classifier.rs
+++ b/crates/screenpipe-engine/src/workflow_classifier.rs
@@ -4,22 +4,15 @@
//! Cloud-based workflow event classifier.
//!
-//! Polls recent UI activity (app switches, window titles) and sends it to the
+//! Polls recent activity via the local `/search` API and sends it to the
//! screenpipe cloud classifier. When a high-confidence workflow event is detected,
//! emits a `WorkflowEvent` to the event bus so matching pipes can be triggered.
-//!
-//! Only runs when:
-//! - `enable_workflow_events` is true in settings
-//! - User has a cloud subscription (token present)
-//! - At least one installed pipe has a `trigger` config
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
-use std::sync::Arc;
use std::time::{Duration, Instant};
use reqwest::Client;
-use screenpipe_db::DatabaseManager;
use screenpipe_events::{ActivityEntry, ClassifierResult, WorkflowEvent};
use serde_json::json;
use tracing::{debug, info, warn};
@@ -28,20 +21,16 @@ use tracing::{debug, info, warn};
const MIN_CONFIDENCE: f32 = 0.75;
/// After emitting an event, suppress the same event type for this duration.
-/// Prevents rapid re-triggering when the user stays in the same workflow.
-const DEDUP_COOLDOWN: Duration = Duration::from_secs(300); // 5 minutes
+const DEDUP_COOLDOWN: Duration = Duration::from_secs(300);
/// System prompt for the cloud classifier.
const CLASSIFIER_SYSTEM_PROMPT: &str = r#"You are a desktop activity classifier for screenpipe. Given a sequence of app activities (timestamps, app names, window titles), identify the high-level workflow event happening. Respond with a JSON object: {"event": "event_name", "confidence": 0.0-1.0, "description": "brief explanation"}. If no specific workflow is detected, respond with {"event": "no_event", "confidence": 1.0, "description": "normal activity"}."#;
/// Start the workflow classifier polling loop.
-///
-/// This runs indefinitely, polling the DB for recent UI activity every
-/// `poll_interval` and classifying it via the cloud API.
pub async fn start_workflow_classifier(
- db: Arc<DatabaseManager>,
api_url: String,
user_token: String,
+ local_port: u16,
poll_interval: Duration,
) {
let client = Client::builder()
@@ -53,7 +42,7 @@ pub async fn start_workflow_classifier(
let mut last_activity_hash: u64 = 0;
info!(
- "workflow classifier started (poll interval: {}s, endpoint: {})",
+ "workflow classifier started (poll: {}s, cloud: {})",
poll_interval.as_secs(),
api_url
);
@@ -61,23 +50,30 @@ pub async fn start_workflow_classifier(
loop {
tokio::time::sleep(poll_interval).await;
- // 1. Get recent app switch events from DB
- let activities = match get_recent_activities(&db).await {
+ // 1. Get recent activity from local search API (all content types)
+ let activities = match get_recent_activities(&client, local_port).await {
Some(a) if !a.is_empty() => a,
_ => continue,
};
- // 2. Hash to avoid re-classifying the same activity window
+ // 2. Hash to skip re-classification of same window
let hash = hash_activities(&activities);
if hash == last_activity_hash {
continue;
}
last_activity_hash = hash;
- // 3. Format for the classifier
+ // 3. Format for classifier
let activity_text = activities
.iter()
- .map(|a| format!("[{}] {}: {}", &a.timestamp[11..19.min(a.timestamp.len())], a.app, a.window))
+ .map(|a| {
+ let ts = if a.timestamp.len() > 19 {
+ &a.timestamp[11..19]
+ } else {
+ &a.timestamp
+ };
+ format!("[{}] {}: {}", ts, a.app, a.window)
+ })
.collect::<Vec<_>>()
.join("\n");
@@ -85,94 +81,128 @@ pub async fn start_workflow_classifier(
let result = match classify(&client, &api_url, &user_token, &activity_text).await {
Ok(r) => r,
Err(e) => {
- warn!("workflow classifier error: {}", e);
+ warn!("workflow classifier: {}", e);
continue;
}
};
- // 5. Check confidence and dedup
+ // 5. Filter + dedup
if result.event == "no_event" || result.confidence < MIN_CONFIDENCE {
continue;
}
-
- // Dedup: don't emit the same event type within the cooldown window
if let Some((ref last_type, last_time)) = last_event {
if last_type == &result.event && last_time.elapsed() < DEDUP_COOLDOWN {
debug!(
- "workflow classifier: suppressing duplicate '{}' (cooldown {}s remaining)",
- result.event,
- (DEDUP_COOLDOWN - last_time.elapsed()).as_secs()
+ "workflow classifier: suppressing duplicate '{}'",
+ result.event
);
continue;
}
}
- // 6. Emit event
+ // 6. Emit
info!(
- "workflow event detected: {} ({:.0}%): {}",
+ "workflow event: {} ({:.0}%): {}",
result.event,
result.confidence * 100.0,
result.description
);
+ let _ = screenpipe_events::send_event(
+ "workflow_event",
+ WorkflowEvent {
+ event_type: result.event.clone(),
+ confidence: result.confidence,
+ description: result.description,
+ activities,
+ timestamp: chrono::Utc::now(),
+ },
+ );
+ last_event = Some((result.event, Instant::now()));
+ }
+}
- let workflow_event = WorkflowEvent {
- event_type: result.event.clone(),
- confidence: result.confidence,
- description: result.description,
- activities,
- timestamp: chrono::Utc::now(),
- };
+/// Query the local screenpipe `/search` API for recent activity across all content types.
+async fn get_recent_activities(client: &Client, port: u16) -> Option<Vec<ActivityEntry>> {
+ let now = chrono::Utc::now();
+ let five_min_ago = now - chrono::Duration::minutes(5);
- if let Err(e) = screenpipe_events::send_event("workflow_event", workflow_event) {
- warn!("failed to emit workflow event: {}", e);
- }
+ let url = format!(
+ "http://localhost:{}/search?content_type=all&limit=20&start_time={}&end_time={}",
+ port,
+ five_min_ago.to_rfc3339(),
+ now.to_rfc3339(),
+ );
- last_event = Some((result.event, Instant::now()));
+ let resp = client.get(&url).send().await.ok()?;
+ if !resp.status().is_success() {
+ return None;
}
-}
-/// Get recent user activity from ALL sources: UI events, screen content, and audio.
-/// This gives the classifier the full picture of what the user has been doing.
-async fn get_recent_activities(db: &DatabaseManager) -> Option<Vec<ActivityEntry>> {
- let since = chrono::Utc::now() - chrono::Duration::minutes(5);
+ let json: serde_json::Value = resp.json().await.ok()?;
+ let data = json.get("data")?.as_array()?;
+
let mut activities = Vec::new();
+ for item in data.iter().take(20) {
+ let content_type = item.get("type")?.as_str()?;
+ let content = item.get("content")?;
+
+ let (app, window, ts) = match content_type {
+ "OCR" | "UI" => {
+ let app = content
+ .get("app_name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let window = content
+ .get("window_name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let ts = content
+ .get("timestamp")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ (app, window, ts)
+ }
+ "Audio" => {
+ let device = content
+ .get("device_name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("mic");
+ let text = content
+ .get("transcription")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let ts = content
+ .get("timestamp")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ if text.trim().is_empty() {
+ continue;
+ }
+ let truncated: String = text.chars().take(150).collect();
+ (
+ format!("[audio:{}]", device),
+ truncated.trim().to_string(),
+ ts,
+ )
+ }
+ _ => continue,
+ };
- // 1. UI events (app switches, window focus) — the primary signal for workflow detection
- if let Ok(events) = db
- .search_ui_events(
- None, // query text
- Some("app_switch"), // event_type
- None, // app_name
- None, // window_name
- Some(since), // start_time
- None, // end_time
- 15, // limit
- 0, // offset
- )
- .await
- {
- for e in events {
- activities.push(ActivityEntry {
- app: e.app_name.unwrap_or_default(),
- window: e.window_title.unwrap_or_default(),
- timestamp: e.timestamp.to_rfc3339(),
- });
+ if !app.is_empty() || !window.is_empty() {
+ activities.push(ActivityEntry { app, window, timestamp: ts });
}
}
- // TODO: Add audio transcription context once DB has a direct query method.
- // For now, window titles provide rich context (page titles, document names, etc.)
- // and app switches are the primary signal for workflow detection.
-
- // Sort by timestamp and dedup consecutive same-app entries
- activities.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
+ // Dedup consecutive same-app+window entries
activities.dedup_by(|a, b| a.app == b.app && a.window == b.window);
if activities.is_empty() {
None
} else {
- // Cap at 20 entries to keep classifier input reasonable
- activities.truncate(20);
Some(activities)
}
}
@@ -206,31 +236,29 @@ async fn classify(
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
- return Err(format!("classifier API error {}: {}", status, text));
+ return Err(format!("API error {}: {}", status, text));
}
let json: serde_json::Value = response
.json()
.await
- .map_err(|e| format!("json parse error: {}", e))?;
+ .map_err(|e| format!("json parse: {}", e))?;
let content = json["choices"][0]["message"]["content"]
.as_str()
- .ok_or("missing content in response")?;
+ .ok_or("missing content")?;
- // Parse the classifier's JSON output
- // Handle potential <think>...</think> wrapper from Qwen3
- let clean_content = if let Some(pos) = content.find("</think>") {
+ // Handle <think>...</think> wrapper from Qwen3
+ let clean = if let Some(pos) = content.find("</think>") {
content[pos + 8..].trim()
} else {
content.trim()
};
- serde_json::from_str::<ClassifierResult>(clean_content)
- .map_err(|e| format!("failed to parse classifier output '{}': {}", clean_content, e))
+ serde_json::from_str::<ClassifierResult>(clean)
+ .map_err(|e| format!("parse '{}': {}", clean, e))
}
-/// Hash the activity window to detect changes (avoids re-classifying same state).
fn hash_activities(activities: &[ActivityEntry]) -> u64 {
let mut hasher = DefaultHasher::new();
for a in activities {
@@ -247,37 +275,20 @@ mod tests {
#[test]
fn hash_changes_with_different_activities() {
let a = vec![ActivityEntry {
- app: "Arc".to_string(),
- window: "LinkedIn".to_string(),
- timestamp: "2026-03-24T09:15:22".to_string(),
+ app: "Arc".into(),
+ window: "LinkedIn".into(),
+ timestamp: "2026-03-24T09:15:22".into(),
}];
let b = vec![ActivityEntry {
- app: "Arc".to_string(),
- window: "Salesforce".to_string(),
- timestamp: "2026-03-24T09:18:03".to_string(),
+ app: "Arc".into(),
+ window: "Salesforce".into(),
+ timestamp: "2026-03-24T09:18:03".into(),
}];
assert_ne!(hash_activities(&a), hash_activities(&b));
}
#[test]
- fn hash_stable_for_same_activities() {
- let a = vec![ActivityEntry {
- app: "Arc".to_string(),
- window: "LinkedIn".to_string(),
- timestamp: "2026-03-24T09:15:22".to_string(),
- }];
- assert_eq!(hash_activities(&a), hash_activities(&a));
- }
-
- #[test]
- fn parse_classifier_output() {
- let json = r#"{"event": "debugging_session", "confidence": 0.92, "description": "User is debugging"}"#;
- let result: ClassifierResult = serde_json::from_str(json).unwrap();
- assert_eq!(result.event, "debugging_session");
- }
-
- #[test]
- fn parse_classifier_output_with_think_wrapper() {
+ fn parse_classifier_output_with_think() {
let content = "<think>\n\n</think>\n\n{\"event\": \"no_event\", \"confidence\": 1.0, \"description\": \"normal\"}";
let clean = if let Some(pos) = content.find("</think>") {
content[pos + 8..].trim()
diff --git a/packages/ai-gateway/src/providers/index.ts b/packages/ai-gateway/src/providers/index.ts
index 2524ec29a..8e06479e1 100644
--- a/packages/ai-gateway/src/providers/index.ts
+++ b/packages/ai-gateway/src/providers/index.ts
@@ -18,6 +18,11 @@ function isOpenRouterModel(model: string): boolean {
}
export function createProvider(model: string, env: Env): AIProvider {
+ // Screenpipe event classifier — routes to self-hosted vLLM
+ if (model === 'screenpipe-event-classifier') {
+ const vllmUrl = env.EVENT_CLASSIFIER_URL || 'http://34.122.128.37:8080/v1';
+ return new OpenAIProvider('none', vllmUrl);
+ }
if (model.toLowerCase().includes('claude')) {
if (!env.ANTHROPIC_API_KEY) {
throw new Error('Anthropic API key not configured');
diff --git a/packages/ai-gateway/src/providers/openai.ts b/packages/ai-gateway/src/providers/openai.ts
index 8c1dfbbfc..9f870ac0c 100644
--- a/packages/ai-gateway/src/providers/openai.ts
+++ b/packages/ai-gateway/src/providers/openai.ts
@@ -10,8 +10,8 @@ export class OpenAIProvider implements AIProvider {
supportsJson = true;
private client: OpenAI;
- constructor(apiKey: string) {
- this.client = new OpenAI({ apiKey });
+ constructor(apiKey: string, baseURL?: string) {
+ this.client = new OpenAI({ apiKey, ...(baseURL ? { baseURL } : {}) });
}
private createJSONSchemaFormat(schema: Record<string, unknown>, name: string, description?: string): ResponseFormatJSONSchema {
diff --git a/packages/ai-gateway/src/services/cost-tracker.ts b/packages/ai-gateway/src/services/cost-tracker.ts
index 53a537c88..6fd122c98 100644
--- a/packages/ai-gateway/src/services/cost-tracker.ts
+++ b/packages/ai-gateway/src/services/cost-tracker.ts
@@ -34,6 +34,8 @@ const MODEL_PRICING: Record<string, ModelPricing> = {
'qwen3-coder': { input: 0.22, output: 1.00 },
'step-3.5-flash:free': { input: 0.00, output: 0.00 },
'step-3.5-flash': { input: 0.00, output: 0.00 },
+ // Screenpipe internal models (self-hosted, zero cost)
+ 'screenpipe-event-classifier': { input: 0.00, output: 0.00 },
// Google Gemini
'gemini-2.5-flash': { input: 0.15, output: 0.60 },
'gemini-2.5-pro': { input: 1.25, output: 10.00 },
@@ -135,6 +137,7 @@ export function inferProvider(model: string): string {
if (lower.includes('gemini')) return 'google';
if (lower.includes('glm-') || lower.includes('kimi-k')) return 'vertex-maas';
if (lower.includes('deepseek') || lower.includes('llama') || lower.includes('qwen') || lower.includes('mistral') || lower.includes('step-3.5') || lower.includes('stepfun')) return 'openrouter';
+ if (lower.includes('screenpipe-event')) return 'screenpipe-vllm';
return 'unknown';
}
diff --git a/packages/ai-gateway/src/types.ts b/packages/ai-gateway/src/types.ts
index 93ae1c01d..de935ad48 100644
--- a/packages/ai-gateway/src/types.ts
+++ b/packages/ai-gateway/src/types.ts
@@ -146,6 +146,8 @@ export interface Env {
DB: D1Database;
// Sentry error tracking
SENTRY_DSN: string;
+ // Event classifier (self-hosted vLLM)
+ EVENT_CLASSIFIER_URL: string;
// Auto-reload settings
WEBSITE_URL: string;
AUTO_RELOAD_SECRET: string;
@@ -153,9 +155,14 @@ export interface Env {
OPENROUTER_API_KEY: string;
// Admin API auth
ADMIN_SECRET: string;
- // Self-hosted Whisper A/B test
+ // Transcription A/B/C test routing
SELF_HOSTED_TRANSCRIPTION_URL?: string;
+ WHISPER_URL?: string;
+ PARAKEET_URL?: string;
+ DEEPGRAM_TRAFFIC_PCT?: string;
WHISPER_TRAFFIC_PCT?: string;
+ PARAKEET_TRAFFIC_PCT?: string;
+ DUAL_SEND_PCT?: string;
WHISPER_DUAL_SEND_PCT?: string;
// Configurable tier limits (override defaults without redeploying)
LIMIT_ANONYMOUS_DAILY?: string;