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: #tag search in search modal + remove activity_tags table
Louis Beaumonta4beedf9fd2c
diff --git a/apps/screenpipe-app-tauri/components/rewind/search-modal.tsx b/apps/screenpipe-app-tauri/components/rewind/search-modal.tsxindex f5a9dd367..57432614b 100644--- a/apps/screenpipe-app-tauri/components/rewind/search-modal.tsx+++ b/apps/screenpipe-app-tauri/components/rewind/search-modal.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useState, useRef, useCallback, useMemo } from "react";-import { Search, X, Loader2, Clock, MessageSquare, User, ArrowLeft, Mic, Volume2 } from "lucide-react";+import { Search, X, Loader2, Clock, MessageSquare, User, ArrowLeft, Mic, Volume2, Hash, Tag } from "lucide-react";import { useKeywordSearchStore, SearchMatch } from "@/lib/hooks/use-keyword-search-store";import { useDebounce } from "@/lib/hooks/use-debounce";import { format, isToday, isYesterday } from "date-fns";@@ -25,6 +25,13 @@ interface AudioTranscription {}+interface TaggedFrame {+ frame_id: number;+ timestamp: string;+ tag_names: string[];+ app_name: string;+}+interface SearchModalProps {isOpen: boolean;onClose: () => void;@@ -277,6 +284,12 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMoconst [isLoadingTranscriptions, setIsLoadingTranscriptions] = useState(false);const [selectedTranscriptionIndex, setSelectedTranscriptionIndex] = useState(0);+ // Tag search state+ const [tagResults, setTagResults] = useState<TaggedFrame[]>([]);+ const [allTags, setAllTags] = useState<string[]>([]); // distinct tags for autocomplete+ const [isSearchingTags, setIsSearchingTags] = useState(false);+ const isTagSearch = query.startsWith("#");+// App filterconst [appFilter, setAppFilter] = useState<string | null>(null);@@ -330,6 +343,8 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMoresetSearch();setAppFilter(null);setSpeakerResults([]);+ setTagResults([]);+ setAllTags([]);setSelectedSpeaker(null);setSpeakerTranscriptions([]);setSelectedTranscriptionIndex(0);@@ -361,11 +376,20 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMoif (!debouncedQuery.trim()) {resetSearch();setSpeakerResults([]);+ setTagResults([]);setAppFilter(null);return;}+ // Skip keyword search for #tag queries (handled by tag search effect)+ if (debouncedQuery.startsWith("#")) {+ resetSearch();+ setSpeakerResults([]);+ return;+ }+setAppFilter(null);+ setTagResults([]);setOcrOffset(0);setHasMoreOcr(true);searchKeywords(debouncedQuery, {@@ -374,6 +398,83 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMo});}, [debouncedQuery, searchKeywords, resetSearch]);+ // Search tags when query starts with #+ useEffect(() => {+ if (!debouncedQuery.startsWith("#")) {+ setTagResults([]);+ setAllTags([]);+ return;+ }++ const tagQuery = debouncedQuery.slice(1).trim().toLowerCase(); // strip #+ let cancelled = false;++ (async () => {+ setIsSearchingTags(true);+ try {+ // Fetch all distinct tags with counts from the tags + vision_tags tables+ const tagsResp = await fetch("http://localhost:3030/raw_sql", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ query: "SELECT t.name, COUNT(vt.vision_id) as count FROM tags t JOIN vision_tags vt ON t.id = vt.tag_id GROUP BY t.id, t.name ORDER BY count DESC",+ }),+ signal: AbortSignal.timeout(5000),+ });++ if (cancelled) return;+ const allDbTags: { name: string; count: number }[] = tagsResp.ok+ ? await tagsResp.json()+ : [];++ // Set autocomplete pills (filtered if user typed something after #)+ const tagNames = allDbTags.map(t => t.name);+ setAllTags(+ tagQuery.length > 0+ ? tagNames.filter(t => t.toLowerCase().includes(tagQuery))+ : tagNames+ );++ // Find tags that match the query+ const matched = tagQuery.length > 0+ ? allDbTags.filter(t => t.name.toLowerCase().includes(tagQuery))+ : allDbTags;++ if (matched.length > 0 && !cancelled) {+ // Fetch frames tagged with matching tags+ const inList = matched.map(t => `'${t.name.replace(/'/g, "''")}'`).join(",");+ const framesResp = await fetch("http://localhost:3030/raw_sql", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ query: `SELECT f.id as frame_id, f.timestamp, f.app_name, GROUP_CONCAT(DISTINCT t.name) as tag_names FROM vision_tags vt JOIN frames f ON vt.vision_id = f.id JOIN tags t ON vt.tag_id = t.id WHERE t.name IN (${inList}) GROUP BY f.id ORDER BY f.timestamp DESC LIMIT 50`,+ }),+ signal: AbortSignal.timeout(5000),+ });++ if (cancelled) return;+ if (framesResp.ok) {+ const rows: { frame_id: number; timestamp: string; tag_names: string; app_name: string }[] = await framesResp.json();+ setTagResults(rows.map(r => ({+ frame_id: r.frame_id,+ timestamp: r.timestamp,+ tag_names: r.tag_names.split(","),+ app_name: r.app_name || "",+ })));+ }+ } else {+ setTagResults([]);+ }+ } catch {+ // ignore+ } finally {+ if (!cancelled) setIsSearchingTags(false);+ }+ })();++ return () => { cancelled = true; };+ }, [debouncedQuery]);+// Search speakers in paralleluseEffect(() => {if (!debouncedQuery.trim() || debouncedQuery.length < 2 || selectedSpeaker) {@@ -649,8 +750,8 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMoif (!isOpen) return null;- const hasResults = searchResults.length > 0 || speakerResults.length > 0;- const showEmpty = !isSearching && !isSearchingSpeakers && debouncedQuery && !hasResults && !selectedSpeaker;+ const hasResults = searchResults.length > 0 || speakerResults.length > 0 || tagResults.length > 0;+ const showEmpty = !isSearching && !isSearchingSpeakers && !isSearchingTags && debouncedQuery && !hasResults && !selectedSpeaker && !isTagSearch;const activeIndex = hoveredIndex ?? selectedIndex;return (@@ -695,7 +796,7 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMosetHasMoreTranscriptions(true);}}}- placeholder="Search your memory..."+ placeholder="Search your memory... (# for tags)"className="flex-1 bg-transparent text-foreground placeholder:text-muted-foreground text-sm outline-none"autoComplete="off"autoCorrect="off"@@ -703,7 +804,7 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMospellCheck={false}autoFocus/>- {isSearching && <Loader2 className="w-4 h-4 text-muted-foreground animate-spin" />}+ {(isSearching || isSearchingTags) && <Loader2 className="w-4 h-4 text-muted-foreground animate-spin" />}{query && (<buttononClick={() => setQuery("")}@@ -815,8 +916,99 @@ export function SearchModal({ isOpen, onClose, onNavigateToTimestamp }: SearchMo</div>)}+ {/* Tag autocomplete pills */}+ {isTagSearch && allTags.length > 0 && (+ <div className="mb-4">+ <p className="text-xs text-muted-foreground mb-2 flex items-center gap-1.5">+ <Tag className="w-3 h-3" />+ tags+ </p>+ <div className="flex flex-wrap gap-1.5 mb-3">+ {allTags.map((t) => {+ const tagQuery = query.slice(1).trim().toLowerCase();+ const isActive = tagQuery === t;+ return (+ <button+ key={t}+ onClick={() => setQuery(`#${t}`)}+ className={cn(+ "inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded-full border transition-colors cursor-pointer",+ isActive+ ? "bg-foreground text-background border-foreground"+ : "border-border text-foreground/70 hover:bg-muted hover:border-foreground/30"+ )}+ >+ <Hash className="w-2.5 h-2.5" />+ {t}+ </button>+ );+ })}+ </div>+ </div>+ )}++ {/* Tag timeline entries — thumbnail grid */}+ {isTagSearch && tagResults.length > 0 && (+ <div className="grid grid-cols-4 gap-3">+ {tagResults.map((frame) => (+ <div+ key={frame.frame_id}+ onClick={() => {+ onNavigateToTimestamp(frame.timestamp);+ onClose();+ }}+ className="cursor-pointer rounded overflow-hidden border border-border hover:border-foreground/50 transition-all duration-150"+ >+ <FrameThumbnail+ frameId={frame.frame_id}+ alt={frame.tag_names.join(", ")}+ />+ <div className="p-2 bg-card">+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground mb-1">+ <Clock className="w-3 h-3" />+ <span className="font-mono">+ {formatRelativeTime(frame.timestamp)}+ </span>+ </div>+ <p className="text-xs font-medium text-foreground truncate">+ {frame.app_name || frame.tag_names[0]}+ </p>+ <div className="flex flex-wrap gap-1 mt-1">+ {frame.tag_names.map((t) => (+ <span+ key={t}+ className="px-1.5 py-0.5 text-[10px] rounded-full bg-foreground/8 text-foreground/60"+ >+ {t}+ </span>+ ))}+ </div>+ </div>+ </div>+ ))}+ </div>+ )}++ {/* Tag search loading */}+ {isTagSearch && isSearchingTags && tagResults.length === 0 && allTags.length === 0 && (+ <div className="space-y-3">+ {Array.from({ length: 4 }).map((_, i) => (+ <div key={i} className="bg-muted animate-pulse rounded p-3 h-12" />+ ))}+ </div>+ )}++ {/* Tag search empty */}+ {isTagSearch && !isSearchingTags && tagResults.length === 0 && allTags.length === 0 && (+ <div className="py-12 text-center text-sm text-muted-foreground">+ {query.slice(1).trim()+ ? <>no tags matching "{query.slice(1).trim()}"</>+ : "no tags found"}+ </div>+ )}+{/* Loading skeleton */}- {isSearching && searchResults.length === 0 && speakerResults.length === 0 && (+ {!isTagSearch && isSearching && searchResults.length === 0 && speakerResults.length === 0 && (<div className="grid grid-cols-4 gap-3">{Array.from({ length: 8 }).map((_, i) => (<div key={i} className="bg-muted animate-pulse rounded overflow-hidden">diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.ts b/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.tsindex 2cd0b6019..5e6c48717 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.ts+++ b/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.ts@@ -25,6 +25,7 @@ type ActivityMode =export function useAutoSuggestions() {const [suggestions, setSuggestions] = useState<Suggestion[]>([]);const [mode, setMode] = useState<ActivityMode>("idle");+ const [tags, setTags] = useState<string[]>([]);const [loading, setLoading] = useState(true);const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);@@ -34,6 +35,7 @@ export function useAutoSuggestions() {if (result.status === "ok") {setSuggestions(result.data.suggestions);setMode(result.data.mode as ActivityMode);+ setTags(result.data.tags || []);} else {throw new Error("failed");}@@ -45,6 +47,7 @@ export function useAutoSuggestions() {{ text: "Which apps did I use most today?" },]);setMode("idle");+ setTags([]);} finally {setLoading(false);}@@ -58,5 +61,5 @@ export function useAutoSuggestions() {};}, [refresh]);- return { suggestions, mode, loading, refresh };+ return { suggestions, mode, tags, loading, refresh };}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rs b/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rsindex a7c3d4503..37b7d48c9 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/suggestions.rs@@ -27,6 +27,7 @@ pub struct CachedSuggestions {pub generated_at: String,pub mode: String,pub ai_generated: bool,+ pub tags: Vec<String>,}// ─── Managed state ──────────────────────────────────────────────────────────@@ -59,6 +60,7 @@ pub async fn get_cached_suggestions(generated_at: chrono::Utc::now().to_rfc3339(),mode: "idle".to_string(),ai_generated: false,+ tags: vec![],}))}@@ -700,48 +702,37 @@ async fn build_activity_context(parts.join("\n")}-// ─── AI suggestion generation ───────────────────────────────────────────────--// System prompt ~250 tokens — leaves ~1200 tokens for context + ~500 for output-const AI_SYSTEM_PROMPT: &str = r#"Generate 4 chat suggestions for a screenpipe user (records screen/audio 24/7). Return ONLY a JSON array of 4 strings.--CRITICAL STYLE RULES:-- ALL LOWERCASE, no capitalization at all-- NEVER start with "Can you", "Did you", "How did", "What's the" — these sound robotic-- NEVER end with a question mark-- Start with action verbs: summarize, show, list, compare, find, what, how much-- 5-10 words, every word must add meaning-- Sound like a real person typing in a chat, not a formal question--CONTENT RULES:-- Reference SPECIFIC apps, people, topics from the activity data below-- Focus on actionable insights: summaries, time tracking, key content, patterns-- If audio mentions a person by name, use their name-- If code/terminal activity, ask about the coding session or errors--GOOD examples (notice: lowercase, no question mark, action-oriented):-- "summarize my slack conversations from today"-- "what did sarah say in the zoom call"-- "how much time in cursor vs chrome"-- "show errors from the wezterm session"-- "list topics from the standup with alex"--BAD examples (NEVER generate these):-- "Can you walk me through the code snippets?" (too formal, question mark)-- "Did you explore any new features?" (yes/no question, formal)-- "What's up with Arc notifications?" (starts with What's)-- "How did Louis discuss commercialization?" (formal, starts with How did)-- "list topics from the team meeting" (generic, doesn't reference real data)-- "show errors from the terminal session" (generic, name the actual terminal)--IMPORTANT: Do NOT copy the examples above. Use the ACTUAL app names, people, and topics from the activity data. Every suggestion must reference something specific from the context below.+// ─── AI suggestion + tag generation ─────────────────────────────────────────++// System prompt — returns both suggestions and tags in one AI call (zero extra cost)+const AI_SYSTEM_PROMPT: &str = r#"Analyze this screenpipe user's activity (records screen/audio 24/7). Return a JSON object with "suggestions" and "tags".++Format: {"suggestions":["suggestion1","suggestion2","suggestion3","suggestion4"],"tags":["tag1","tag2","tag3"]}++SUGGESTIONS — 4 natural sentences the user can click to ask about their activity:+- all lowercase plain english, NO hyphens, NO question marks+- 5-10 words, start with: summarize, show, list, compare, find, what, how much+- reference specific apps/people/topics from the data below+- example style: "summarize my slack conversations from today"++TAGS — 3-8 short hyphenated labels for search/filtering:+- lowercase with hyphens, no spaces: "coding", "rust", "debugging-auth", "meeting-with-sarah"+- include: activity type, specific apps, topics, people, projects++Output ONLY the JSON on a SINGLE LINE. Do NOT copy examples — use actual data."#;+/// Result from a single AI call that returns both suggestions and tags.+struct AiResult {+ suggestions: Vec<Suggestion>,+ tags: Vec<String>,+}+async fn generate_ai_suggestions(mode: &str,apps: &[AppActivity],windows: &[WindowActivity],-) -> Option<Vec<Suggestion>> {+) -> Option<AiResult> {if !check_ai_available().await {info!("suggestions: Apple Intelligence not available, using templates");return None;@@ -774,8 +765,8 @@ async fn generate_ai_suggestions(let content = data["choices"][0]["message"]["content"].as_str().unwrap_or("");- debug!("suggestions AI response: {}", &content[..content.len().min(200)]);- parse_ai_suggestions(content)+ debug!("suggestions AI response: {}", &content[..content.len().min(300)]);+ parse_ai_response(content)}Ok(r) => {warn!("suggestions: AI returned status {}", r.status());@@ -788,30 +779,46 @@ async fn generate_ai_suggestions(}}-fn parse_ai_suggestions(content: &str) -> Option<Vec<Suggestion>> {- // Try direct JSON parse- if let Ok(arr) = serde_json::from_str::<Vec<String>>(content) {- if !arr.is_empty() {- return Some(- arr.into_iter()- .take(4)- .map(|text| Suggestion { text })- .collect(),- );+fn parse_ai_response(content: &str) -> Option<AiResult> {+ // Try the combined format: {"suggestions":[...], "tags":[...]}+ let json_str = extract_json_object(content);+ if let Some(json_str) = json_str {+ if let Ok(obj) = serde_json::from_str::<serde_json::Value>(&json_str) {+ let suggestions = obj["suggestions"]+ .as_array()+ .map(|arr| {+ arr.iter()+ .filter_map(|v| v.as_str().map(|s| Suggestion { text: s.to_string() }))+ .take(4)+ .collect::<Vec<_>>()+ })+ .unwrap_or_default();++ let tags = obj["tags"]+ .as_array()+ .map(|arr| {+ arr.iter()+ .filter_map(|v| v.as_str().map(|s| s.to_lowercase()))+ .take(8)+ .collect::<Vec<_>>()+ })+ .unwrap_or_default();++ if !suggestions.is_empty() {+ return Some(AiResult { suggestions, tags });+ }}}- // Try extracting JSON array from wrapped text (e.g. ```json [...] ```)+ // Fallback: try parsing as a plain JSON array of strings (old format)if let Some(start) = content.find('[') {if let Some(end) = content.rfind(']') {if let Ok(arr) = serde_json::from_str::<Vec<String>>(&content[start..=end]) {if !arr.is_empty() {- return Some(- arr.into_iter()- .take(4)- .map(|text| Suggestion { text })- .collect(),- );+ return Some(AiResult {+ suggestions: arr.into_iter().take(4).map(|text| Suggestion { text }).collect(),+ tags: vec![],+ });}}}@@ -820,6 +827,29 @@ fn parse_ai_suggestions(content: &str) -> Option<Vec<Suggestion>> {None}+fn extract_json_object(content: &str) -> Option<String> {+ let content = content.trim();+ // Strip markdown code fences+ let cleaned = if content.starts_with("```") {+ content+ .lines()+ .skip(1)+ .take_while(|l| !l.starts_with("```"))+ .collect::<Vec<_>>()+ .join("\n")+ } else {+ content.to_string()+ };++ let start = cleaned.find('{')?;+ let end = cleaned.rfind('}')?;+ if end >= start {+ Some(cleaned[start..=end].to_string())+ } else {+ None+ }+}+async fn generate_suggestions() -> Result<CachedSuggestions, String> {let (apps, windows) = tokio::join!(fetch_app_activity(), fetch_window_activity());let apps = apps.unwrap_or_default();@@ -833,27 +863,103 @@ async fn generate_suggestions() -> Result<CachedSuggestions, String> {mode, apps.len(), windows.len());- // Try AI-powered suggestions first- let (suggestions, ai_generated) =+ // Try AI-powered suggestions + tags in one call+ let (suggestions, tags, ai_generated) =match generate_ai_suggestions(mode, &apps, &windows).await {- Some(s) => {- info!("suggestions: using AI-generated suggestions");- (s, true)+ Some(result) => {+ info!(+ "suggestions: AI generated {} suggestions + {} tags",+ result.suggestions.len(),+ result.tags.len()+ );+ (result.suggestions, result.tags, true)}None => {- info!("suggestions: falling back to templates (mode={})", mode);- (template_suggestions(mode, &top_apps, &windows), false)+ // Template fallback — generate basic tags from mode + top apps+ let fallback_tags = generate_heuristic_tags(mode, &top_apps);+ info!("suggestions: template fallback (mode={}, {} tags)", mode, fallback_tags.len());+ (template_suggestions(mode, &top_apps, &windows), fallback_tags, false)}};+ let now = chrono::Utc::now().to_rfc3339();++ // Store tags on recent frames (fire-and-forget, don't block suggestions)+ if !tags.is_empty() {+ let tags_clone = tags.clone();+ tokio::spawn(async move {+ if let Err(e) = store_tags(&tags_clone).await {+ warn!("suggestions: failed to store tags: {}", e);+ }+ });+ }+Ok(CachedSuggestions {suggestions: suggestions.into_iter().take(4).collect(),- generated_at: chrono::Utc::now().to_rfc3339(),+ generated_at: now,mode: mode.to_string(),ai_generated,+ tags,})}+/// Generate basic tags from heuristic mode detection when AI is unavailable.+fn generate_heuristic_tags(mode: &str, top_apps: &[String]) -> Vec<String> {+ let mut tags = vec![mode.to_string()];+ for app in top_apps.iter().take(3) {+ tags.push(app.to_lowercase().replace(' ', "-"));+ }+ tags+}++/// Store AI-generated tags on recent frames using the existing tags + vision_tags tables.+async fn store_tags(+ tags: &[String],+) -> Result<(), String> {+ let client = reqwest::Client::new();++ // Get recent frame IDs (last 10 minutes, sample up to 10)+ let resp = client+ .post(format!("{}/raw_sql", API))+ .json(&serde_json::json!({+ "query": "SELECT id FROM frames WHERE timestamp >= datetime('now', '-10 minutes') ORDER BY timestamp DESC LIMIT 10"+ }))+ .timeout(std::time::Duration::from_secs(5))+ .send()+ .await+ .map_err(|e| format!("fetch frames: {}", e))?;++ if !resp.status().is_success() {+ return Err("failed to fetch recent frames".into());+ }++ #[derive(Deserialize)]+ struct FrameRow { id: i64 }+ let frames: Vec<FrameRow> = resp.json().await.map_err(|e| format!("parse frames: {}", e))?;++ if frames.is_empty() {+ return Ok(());+ }++ // Tag frames via the existing API endpoint (POST /tags/vision/:id)+ let tag_body = serde_json::json!({ "tags": tags });+ let mut tagged = 0;+ for frame in &frames {+ let resp = client+ .post(format!("{}/tags/vision/{}", API, frame.id))+ .json(&tag_body)+ .timeout(std::time::Duration::from_secs(5))+ .send()+ .await;+ if resp.is_ok() {+ tagged += 1;+ }+ }++ info!("suggestions: tagged {}/{} frames with {} tags", tagged, frames.len(), tags.len());+ Ok(())+}+// ─── Tests ──────────────────────────────────────────────────────────────────#[cfg(test)]