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 global shortcut for standalone AI chat window
Louis Beaumontc70da3040f36
diff --git a/screenpipe-app-tauri/app/chat/page.tsx b/screenpipe-app-tauri/app/chat/page.tsxnew file mode 100644index 000000000..1165c85d7--- /dev/null+++ b/screenpipe-app-tauri/app/chat/page.tsx@@ -0,0 +1,7 @@+"use client";++import { StandaloneChat } from "@/components/standalone-chat";++export default function ChatPage() {+ return <StandaloneChat />;+}diff --git a/screenpipe-app-tauri/components/onboarding/status.tsx b/screenpipe-app-tauri/components/onboarding/status.tsxindex 60c6037c9..ba28b6d9d 100644--- a/screenpipe-app-tauri/components/onboarding/status.tsx+++ b/screenpipe-app-tauri/components/onboarding/status.tsx@@ -559,9 +559,9 @@ const OnboardingStatus: React.FC<OnboardingStatusProps> = ({</span><span><span className="font-semibold text-foreground">- {formatShortcut(settings.showSearchShortcut, isMacOS)}+ {formatShortcut(settings.showChatShortcut, isMacOS)}</span>{" "}- search+ ai chat</span></div></div>diff --git a/screenpipe-app-tauri/components/standalone-chat.tsx b/screenpipe-app-tauri/components/standalone-chat.tsxnew file mode 100644index 000000000..fb059d71d--- /dev/null+++ b/screenpipe-app-tauri/components/standalone-chat.tsx@@ -0,0 +1,976 @@+"use client";++import * as React from "react";+import { useState, useRef, useEffect } from "react";+import { listen } from "@tauri-apps/api/event";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { useSettings } from "@/lib/hooks/use-settings";+import { cn } from "@/lib/utils";+import { Loader2, Send, Square, User, Settings, ExternalLink } from "lucide-react";+import { toast } from "@/components/ui/use-toast";+import { motion, AnimatePresence } from "framer-motion";+import { PipeAIIcon, PipeAIIconLarge } from "@/components/pipe-ai-icon";+import { MemoizedReactMarkdown } from "@/components/markdown";+import { VideoComponent } from "@/components/rewind/video";+import { AIPresetsSelector } from "@/components/rewind/ai-presets-selector";+import { AIPreset } from "@/lib/utils/tauri";+import remarkGfm from "remark-gfm";+import OpenAI from "openai";+import { ChatCompletionTool } from "openai/resources/chat/completions";+import { open as openUrl } from "@tauri-apps/plugin-shell";+import { usePlatform } from "@/lib/hooks/use-platform";+import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";+import { commands } from "@/lib/utils/tauri";+import { UpgradeDialog } from "@/components/upgrade-dialog";+import {+ parseMentions,+ buildAppMentionSuggestions,+ normalizeAppTag,+} from "@/components/global-chat";++const SCREENPIPE_API = "http://localhost:3030";++interface MentionSuggestion {+ tag: string;+ description: string;+ category: "time" | "content" | "app" | "speaker";+ appName?: string;+}++const APP_SUGGESTION_LIMIT = 10;++interface Speaker {+ id: number;+ name: string;+ metadata?: string;+}++const STATIC_MENTION_SUGGESTIONS: MentionSuggestion[] = [+ { tag: "@today", description: "today's activity", category: "time" },+ { tag: "@yesterday", description: "yesterday", category: "time" },+ { tag: "@last-week", description: "past 7 days", category: "time" },+ { tag: "@last-hour", description: "past hour", category: "time" },+ { tag: "@audio", description: "audio/meetings only", category: "content" },+ { tag: "@screen", description: "screen text only", category: "content" },+];++const TOOLS: ChatCompletionTool[] = [+ {+ type: "function",+ function: {+ name: "search_content",+ description: `Search screenpipe's recorded content: screen text (OCR), audio transcriptions, and UI elements.++**MANDATORY**: start_time is REQUIRED for every search. Database has 600k+ entries - searches without time bounds WILL timeout.++RULES:+- ALWAYS include start_time (required) - default to 1-2 hours ago+- Use app_name filter whenever user mentions an app+- Keep limit=5-10, never higher initially+- If query times out, retry with shorter time range (30 mins)`,+ parameters: {+ type: "object",+ properties: {+ q: { type: "string", description: "Search keywords. Be specific. Optional but recommended." },+ content_type: { type: "string", enum: ["all", "ocr", "audio", "ui"], description: "Filter by type." },+ limit: { type: "integer", description: "Max results (1-20). Default: 10" },+ start_time: { type: "string", description: "ISO 8601 UTC start time. REQUIRED." },+ end_time: { type: "string", description: "ISO 8601 UTC end time." },+ app_name: { type: "string", description: "Filter by app name." },+ window_name: { type: "string", description: "Filter by window title." },+ speaker_name: { type: "string", description: "Filter audio by speaker name." },+ },+ },+ },+ },+];++const SYSTEM_PROMPT = `You are a helpful AI assistant that can search through the user's Screenpipe data - their screen recordings, audio transcriptions, and UI interactions.++CRITICAL SEARCH RULES (database has 600k+ entries - ALWAYS use time filters):+1. ALWAYS include start_time in EVERY search - NEVER search without a time range+2. Default time range: last 1-2 hours. Expand ONLY if no results found+3. ALWAYS use app_name filter when user mentions ANY app+4. Keep limit=5-10 initially++Rules for showing videos/audio:+- Show videos by putting .mp4 file paths in inline code blocks: \`/path/to/video.mp4\`+- Use the exact, absolute file_path from search results++Be concise. Cite timestamps when relevant.++Current time: ${new Date().toISOString()}`;++interface SearchResult {+ type: "OCR" | "Audio" | "UI";+ content: {+ text?: string;+ transcription?: string;+ timestamp: string;+ app_name?: string;+ window_name?: string;+ device_name?: string;+ file_path?: string;+ audio_file_path?: string;+ };+}++interface Message {+ id: string;+ role: "user" | "assistant";+ content: string;+}++export function StandaloneChat() {+ const { settings } = useSettings();+ const { isMac } = usePlatform();+ const { items: appItems } = useSqlAutocomplete("app");++ const [input, setInput] = useState("");+ const [messages, setMessages] = useState<Message[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [isStreaming, setIsStreaming] = useState(false);+ const [activePreset, setActivePreset] = useState<AIPreset | undefined>();+ const [showMentionDropdown, setShowMentionDropdown] = useState(false);+ const [mentionFilter, setMentionFilter] = useState("");+ const [selectedMentionIndex, setSelectedMentionIndex] = useState(0);+ const [speakerSuggestions, setSpeakerSuggestions] = useState<MentionSuggestion[]>([]);+ const [isLoadingSpeakers, setIsLoadingSpeakers] = useState(false);+ const abortControllerRef = useRef<AbortController | null>(null);+ const messagesEndRef = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const dropdownRef = useRef<HTMLDivElement>(null);++ const [showUpgradeDialog, setShowUpgradeDialog] = useState(false);+ const [upgradeReason, setUpgradeReason] = useState<"daily_limit" | "model_not_allowed">("daily_limit");+ const [upgradeResetsAt, setUpgradeResetsAt] = useState<string | undefined>();++ const appMentionSuggestions = React.useMemo(+ () => buildAppMentionSuggestions(appItems, APP_SUGGESTION_LIMIT),+ [appItems]+ );++ const appTagMap = React.useMemo(() => {+ const map: Record<string, string> = {};+ for (const suggestion of appMentionSuggestions) {+ if (suggestion.appName) {+ map[suggestion.tag.slice(1).toLowerCase()] = suggestion.appName;+ }+ }+ return map;+ }, [appMentionSuggestions]);++ const baseMentionSuggestions = React.useMemo(+ () => [...STATIC_MENTION_SUGGESTIONS, ...appMentionSuggestions],+ [appMentionSuggestions]+ );++ // Fetch speakers dynamically+ useEffect(() => {+ if (!mentionFilter || mentionFilter.length < 1) {+ setSpeakerSuggestions([]);+ return;+ }++ const matchesBase = baseMentionSuggestions.some(+ s => s.tag.toLowerCase().includes(`@${mentionFilter.toLowerCase()}`)+ );+ if (matchesBase && mentionFilter.length < 3) {+ setSpeakerSuggestions([]);+ return;+ }++ const searchSpeakers = async () => {+ setIsLoadingSpeakers(true);+ try {+ const response = await fetch(+ `${SCREENPIPE_API}/speakers/search?name=${encodeURIComponent(mentionFilter)}`+ );+ if (response.ok) {+ const speakers: Speaker[] = await response.json();+ const suggestions: MentionSuggestion[] = speakers+ .filter(s => s.name)+ .slice(0, 5)+ .map(s => ({+ tag: s.name.includes(" ") ? `@"${s.name}"` : `@${s.name}`,+ description: `speaker`,+ category: "speaker" as const,+ }));+ setSpeakerSuggestions(suggestions);+ }+ } catch (error) {+ console.error("Error searching speakers:", error);+ } finally {+ setIsLoadingSpeakers(false);+ }+ };++ const debounceTimeout = setTimeout(searchSpeakers, 300);+ return () => clearTimeout(debounceTimeout);+ }, [mentionFilter, baseMentionSuggestions]);++ const filteredMentions = React.useMemo(() => {+ const suggestions = !mentionFilter+ ? baseMentionSuggestions+ : baseMentionSuggestions.filter(+ s => s.tag.toLowerCase().includes(mentionFilter.toLowerCase()) ||+ s.description.toLowerCase().includes(mentionFilter.toLowerCase())+ );+ return [...suggestions, ...speakerSuggestions];+ }, [mentionFilter, speakerSuggestions, baseMentionSuggestions]);++ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const value = e.target.value;+ setInput(value);++ const cursorPos = e.target.selectionStart || 0;+ const textBeforeCursor = value.slice(0, cursorPos);+ const atMatch = textBeforeCursor.match(/@(\w*)$/);++ if (atMatch) {+ setShowMentionDropdown(true);+ setMentionFilter(atMatch[1]);+ setSelectedMentionIndex(0);+ } else {+ setShowMentionDropdown(false);+ setMentionFilter("");+ }+ };++ const insertMention = (tag: string) => {+ const cursorPos = inputRef.current?.selectionStart || input.length;+ const textBeforeCursor = input.slice(0, cursorPos);+ const textAfterCursor = input.slice(cursorPos);++ const atIndex = textBeforeCursor.lastIndexOf("@");+ if (atIndex !== -1) {+ const newValue = textBeforeCursor.slice(0, atIndex) + tag + " " + textAfterCursor;+ setInput(newValue);+ }++ setShowMentionDropdown(false);+ setMentionFilter("");+ inputRef.current?.focus();+ };++ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (!showMentionDropdown) return;++ if (e.key === "ArrowDown") {+ e.preventDefault();+ setSelectedMentionIndex(i => Math.min(i + 1, filteredMentions.length - 1));+ } else if (e.key === "ArrowUp") {+ e.preventDefault();+ setSelectedMentionIndex(i => Math.max(i - 1, 0));+ } else if (e.key === "Enter" && filteredMentions.length > 0) {+ e.preventDefault();+ insertMention(filteredMentions[selectedMentionIndex].tag);+ } else if (e.key === "Escape") {+ setShowMentionDropdown(false);+ } else if (e.key === "Tab" && filteredMentions.length > 0) {+ e.preventDefault();+ insertMention(filteredMentions[selectedMentionIndex].tag);+ }+ };++ useEffect(() => {+ const defaultPreset = settings.aiPresets?.find((p) => p.defaultPreset);+ setActivePreset(defaultPreset || settings.aiPresets?.[0]);+ }, [settings.aiPresets]);++ const hasPresets = settings.aiPresets && settings.aiPresets.length > 0;+ const hasValidModel = activePreset?.model && activePreset.model.trim() !== "";+ const needsLogin = activePreset?.provider === "screenpipe-cloud" && !settings.user?.token;+ const canChat = hasPresets && hasValidModel && !needsLogin;++ const getDisabledReason = (): string | null => {+ if (!hasPresets) return "No AI presets configured";+ if (!activePreset) return "No preset selected";+ if (!hasValidModel) return `No model selected in "${activePreset.id}" preset`;+ if (needsLogin) return "Login required for Screenpipe Cloud";+ return null;+ };+ const disabledReason = getDisabledReason();++ // Focus input on mount+ useEffect(() => {+ setTimeout(() => inputRef.current?.focus(), 100);+ }, []);++ // Escape key to close window+ useEffect(() => {+ const handleEscape = (e: KeyboardEvent) => {+ if (e.key === "Escape" && !showMentionDropdown) {+ commands.closeWindow("Chat");+ }+ };+ window.addEventListener("keydown", handleEscape);+ return () => window.removeEventListener("keydown", handleEscape);+ }, [showMentionDropdown]);++ useEffect(() => {+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });+ }, [messages]);++ async function executeSearchTool(args: Record<string, unknown>): Promise<string> {+ const MAX_LIMIT = 10;+ const MAX_RESPONSE_CHARS = 4000;+ const MAX_TEXT_PER_RESULT = 300;++ try {+ const params = new URLSearchParams();+ if (args.q) params.append("q", String(args.q));+ if (args.content_type && args.content_type !== "all") {+ params.append("content_type", String(args.content_type));+ }++ const requestedLimit = args.limit ? Number(args.limit) : 10;+ const limit = Math.min(requestedLimit, MAX_LIMIT);+ params.append("limit", String(limit));++ if (args.start_time) params.append("start_time", String(args.start_time));+ if (args.end_time) params.append("end_time", String(args.end_time));+ if (args.app_name) params.append("app_name", String(args.app_name));+ if (args.window_name) params.append("window_name", String(args.window_name));+ if (args.speaker_name) params.append("speaker_name", String(args.speaker_name));++ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 30000);++ const response = await fetch(`${SCREENPIPE_API}/search?${params.toString()}`, {+ signal: controller.signal,+ });+ clearTimeout(timeoutId);++ if (!response.ok) throw new Error(`Search failed: ${response.status}`);++ const data = await response.json();++ if (data.error) {+ return `Search failed: ${data.error}`;+ }++ const searchResults = data.data || [];++ if (searchResults.length === 0) {+ return "No results found. Try broader search terms or wider time range.";+ }++ const formatted = searchResults.map((result: SearchResult) => {+ const content = result.content;+ if (!content) return null;++ const truncateText = (text: string | undefined) => {+ if (!text) return "";+ if (text.length > MAX_TEXT_PER_RESULT) {+ return text.substring(0, MAX_TEXT_PER_RESULT) + "...";+ }+ return text;+ };++ if (result.type === "OCR") {+ const filePath = content.file_path ? `\nfile_path: ${content.file_path}` : "";+ return `[OCR] ${content.app_name || "?"} | ${content.window_name || "?"}\n${content.timestamp}${filePath}\n${truncateText(content.text)}`;+ } else if (result.type === "Audio") {+ const audioPath = content.audio_file_path ? `\naudio_file_path: ${content.audio_file_path}` : "";+ return `[Audio] ${content.device_name || "?"}\n${content.timestamp}${audioPath}\n${truncateText(content.transcription)}`;+ } else if (result.type === "UI") {+ const filePath = content.file_path ? `\nfile_path: ${content.file_path}` : "";+ return `[UI] ${content.app_name || "?"} | ${content.window_name || "?"}\n${content.timestamp}${filePath}\n${truncateText(content.text)}`;+ }+ return null;+ }).filter(Boolean);++ const result = formatted.join("\n---\n");++ if (result.length > MAX_RESPONSE_CHARS) {+ return `Search returned too much data. Try a narrower time range.`;+ }++ return `Found ${searchResults.length} results:\n\n${result}`;+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ return "Search timed out. Retry with narrower time range and start_time within last 30-60 minutes.";+ }+ return `Search failed: ${error instanceof Error ? error.message : "Unknown error"}`;+ }+ }++ function getOpenAIClient(): OpenAI | null {+ if (!activePreset) return null;++ const apiKey =+ activePreset.provider === "screenpipe-cloud"+ ? settings.user?.token || "anonymous"+ : "apiKey" in activePreset+ ? (activePreset.apiKey as string) || ""+ : "";++ const baseURL =+ activePreset.provider === "screenpipe-cloud"+ ? "https://api.screenpi.pe/v1"+ : activePreset.url;++ const defaultHeaders: Record<string, string> = {};+ if (activePreset.provider === "screenpipe-cloud" && settings.deviceId) {+ defaultHeaders["X-Device-Id"] = settings.deviceId;+ }++ return new OpenAI({+ apiKey,+ baseURL,+ dangerouslyAllowBrowser: true,+ defaultHeaders,+ });+ }++ async function sendMessage(userMessage: string) {+ if (!canChat || !activePreset) return;++ const openai = getOpenAIClient();+ if (!openai) return;++ const mentions = parseMentions(userMessage, { appTagMap });+ const displayMessage = userMessage;+ const processedMessage = mentions.cleanedInput || userMessage;++ const newUserMessage: Message = {+ id: Date.now().toString(),+ role: "user",+ content: displayMessage,+ };++ const assistantMessageId = (Date.now() + 1).toString();+ setMessages((prev) => [...prev, newUserMessage]);+ setInput("");+ setIsLoading(true);+ setIsStreaming(true);++ abortControllerRef.current = new AbortController();++ try {+ let systemPrompt = SYSTEM_PROMPT;++ const mentionContext: string[] = [];++ if (mentions.timeRanges.length > 0) {+ const timeContext = mentions.timeRanges.map(t =>+ `- ${t.label}: from ${t.start.toISOString()} to ${t.end.toISOString()}`+ ).join("\n");+ mentionContext.push(`TIME FILTER:\n${timeContext}`);+ }++ if (mentions.contentType) {+ mentionContext.push(`CONTENT TYPE FILTER: ${mentions.contentType}`);+ }++ if (mentions.appName) {+ mentionContext.push(`APP FILTER: ${mentions.appName}`);+ }++ if (mentions.speakerName) {+ mentionContext.push(`SPEAKER FILTER: ${mentions.speakerName}`);+ }++ if (mentionContext.length > 0) {+ systemPrompt += `\n\nUser specified filters via @mentions:\n${mentionContext.join("\n\n")}`;+ }++ const MAX_HISTORY = 10;+ const recentMessages = messages.slice(-MAX_HISTORY);+ const conversationMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [+ { role: "system", content: systemPrompt },+ ...recentMessages.map((m) => ({+ role: m.role as "user" | "assistant",+ content: m.content,+ })),+ { role: "user", content: processedMessage },+ ];++ setMessages((prev) => [+ ...prev,+ { id: assistantMessageId, role: "assistant", content: "" },+ ]);++ let accumulatedText = "";+ let toolCalls: any[] = [];++ const stream = await openai.chat.completions.create(+ {+ model: activePreset.model || "gpt-4",+ messages: conversationMessages,+ tools: TOOLS,+ stream: true,+ },+ { signal: abortControllerRef.current.signal }+ );++ for await (const chunk of stream) {+ const delta = chunk.choices[0]?.delta;++ if (delta?.content) {+ accumulatedText += delta.content;+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: accumulatedText }+ : m+ )+ );+ }++ if (delta?.tool_calls) {+ for (const toolCall of delta.tool_calls) {+ const index = toolCall.index;+ if (!toolCalls[index]) {+ toolCalls[index] = {+ id: toolCall.id || "",+ function: { name: "", arguments: "" },+ };+ }+ if (toolCall.id) toolCalls[index].id = toolCall.id;+ if (toolCall.function?.name) toolCalls[index].function.name = toolCall.function.name;+ if (toolCall.function?.arguments) toolCalls[index].function.arguments += toolCall.function.arguments;+ }+ }+ }++ if (toolCalls.length > 0) {+ const searchArgs = toolCalls[0]?.function?.arguments;+ let searchInfo = "Searching...";+ try {+ const args = JSON.parse(searchArgs || "{}");+ const parts = [];+ if (args.app_name) parts.push(args.app_name);+ if (args.start_time) parts.push(`from ${args.start_time}`);+ if (args.q) parts.push(`"${args.q}"`);+ if (parts.length > 0) searchInfo = `Searching ${parts.join(", ")}...`;+ } catch {}++ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: accumulatedText + `\n\n*${searchInfo}*` }+ : m+ )+ );++ const toolResults: OpenAI.Chat.ChatCompletionMessageParam[] = [];++ toolResults.push({+ role: "assistant",+ content: accumulatedText || null,+ tool_calls: toolCalls.map((tc) => ({+ id: tc.id,+ type: "function" as const,+ function: {+ name: tc.function.name,+ arguments: tc.function.arguments,+ },+ })),+ });++ for (const toolCall of toolCalls) {+ if (toolCall.function.name === "search_content") {+ try {+ const args = JSON.parse(toolCall.function.arguments || "{}");+ const result = await executeSearchTool(args);+ toolResults.push({+ role: "tool",+ tool_call_id: toolCall.id,+ content: result,+ });+ } catch (e) {+ toolResults.push({+ role: "tool",+ tool_call_id: toolCall.id,+ content: `Error parsing tool arguments: ${e}`,+ });+ }+ }+ }++ accumulatedText = "";+ const continueStream = await openai.chat.completions.create(+ {+ model: activePreset.model || "gpt-4",+ messages: [...conversationMessages, ...toolResults],+ stream: true,+ },+ { signal: abortControllerRef.current?.signal }+ );++ for await (const chunk of continueStream) {+ const content = chunk.choices[0]?.delta?.content;+ if (content) {+ accumulatedText += content;+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: accumulatedText }+ : m+ )+ );+ }+ }+ }++ if (!accumulatedText && toolCalls.length === 0) {+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: "I couldn't generate a response." }+ : m+ )+ );+ }+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ return;+ }+ console.error("Chat error:", error);++ let errorMessage = error instanceof Error ? error.message : "Something went wrong";++ if (errorMessage.includes("daily_limit_exceeded")) {+ try {+ const match = errorMessage.match(/"resets_at":\s*"([^"]+)"/);+ if (match) setUpgradeResetsAt(match[1]);+ } catch {}+ setUpgradeReason("daily_limit");+ setShowUpgradeDialog(true);+ errorMessage = "You've used all your free queries for today.";+ } else if (errorMessage.includes("model_not_allowed")) {+ setUpgradeReason("model_not_allowed");+ setShowUpgradeDialog(true);+ errorMessage = "This model requires an upgrade.";+ } else if (errorMessage.includes("401") || errorMessage.includes("Unauthorized")) {+ errorMessage = "Invalid API key. Please check your preset configuration.";+ } else if (errorMessage.includes("429")) {+ errorMessage = "Rate limit exceeded. Please wait and try again.";+ } else if (errorMessage.includes("Failed to fetch") || errorMessage.includes("NetworkError")) {+ errorMessage = "Network error. Check your connection.";+ } else if (+ errorMessage.includes("context") ||+ errorMessage.includes("token") ||+ errorMessage.includes("too large")+ ) {+ errorMessage = "Response too large. Try a more specific search.";+ setMessages([]);+ }++ setMessages((prev) => {+ const filtered = prev.filter((m) => m.id !== assistantMessageId || m.content);+ return [+ ...filtered,+ {+ id: Date.now().toString(),+ role: "assistant",+ content: `Error: ${errorMessage}`,+ },+ ];+ });+ } finally {+ setIsLoading(false);+ setIsStreaming(false);+ abortControllerRef.current = null;+ }+ }++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ if (!input.trim() || isLoading) return;+ sendMessage(input.trim());+ };++ const handleStop = () => {+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ setIsLoading(false);+ setIsStreaming(false);+ }+ };++ return (+ <div className="flex flex-col h-screen bg-background">+ {/* Header */}+ <div className="relative flex items-center gap-3 px-4 py-3 border-b border-border/50 bg-gradient-to-r from-background to-muted/30">+ <div className="absolute top-0 left-0 w-8 h-8 border-l-2 border-t-2 border-foreground/10 rounded-tl-lg" />+ <div className="relative z-10 p-1.5 rounded-lg bg-foreground/5 border border-border/50">+ <PipeAIIcon size={18} animated={false} className="text-foreground" />+ </div>+ <div className="flex-1">+ <h2 className="font-semibold text-sm tracking-tight">Pipe AI</h2>+ <p className="text-[10px] text-muted-foreground font-mono uppercase tracking-wider">Screen Activity Assistant</p>+ </div>+ <kbd className="hidden sm:inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-mono text-muted-foreground bg-muted/50 border border-border/50 rounded">+ {isMac ? "⌘⌥" : "Alt+"}L+ </kbd>+ </div>++ {/* Messages */}+ <div className="relative flex-1 overflow-y-auto p-4 space-y-4">+ {messages.length === 0 && disabledReason && (+ <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+ ? "bg-muted/50 border-border/50"+ : "bg-destructive/5 border-destructive/20"+ )}>+ {needsLogin ? (+ <PipeAIIconLarge size={48} className="text-muted-foreground" />+ ) : (+ <Settings className="h-12 w-12 text-destructive/70" />+ )}+ </div>+ <div className="text-center space-y-2">+ <h3 className="font-semibold tracking-tight">+ {!hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : "Login Required"}+ </h3>+ <p className="text-sm text-muted-foreground max-w-sm">+ {disabledReason}+ </p>+ </div>+ {needsLogin && (+ <Button+ variant="default"+ onClick={() => openUrl("https://screenpi.pe/login")}+ className="gap-2 font-medium bg-foreground text-background hover:bg-foreground/90"+ >+ <ExternalLink className="h-4 w-4" />+ Login+ </Button>+ )}+ {!hasPresets && (+ <Button+ variant="outline"+ onClick={async () => {+ await commands.showWindow({ Settings: { page: null } });+ }}+ className="gap-2"+ >+ <Settings className="h-4 w-4" />+ Go to Settings+ </Button>+ )}+ </div>+ )}+ {messages.length === 0 && canChat && (+ <div className="relative text-center py-12">+ <div className="relative mx-auto mb-6 w-fit">+ <div className="absolute -inset-4 border border-dashed border-border/50 rounded-xl" />+ <div className="absolute -inset-2 border border-border/30 rounded-lg" />+ <PipeAIIconLarge size={56} thinking={false} className="relative text-foreground/80" />+ </div>+ <h3 className="text-base font-medium mb-2 text-foreground">Ask about your screen activity</h3>+ <p className="text-sm text-muted-foreground mb-6">+ Search your recordings, transcriptions, and interactions+ </p>+ <div className="flex flex-wrap gap-2 justify-center max-w-sm mx-auto text-xs text-muted-foreground">+ <span className="px-2 py-1 bg-muted/30 rounded border border-border/30 font-mono">"What did I do in the last hour?"</span>+ <span className="px-2 py-1 bg-muted/30 rounded border border-border/30 font-mono">"Find my Slack messages"</span>+ </div>+ </div>+ )}+ <AnimatePresence mode="popLayout">+ {messages.map((message) => (+ <motion.div+ key={message.id}+ initial={{ opacity: 0, y: 10 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -10 }}+ transition={{ duration: 0.2 }}+ className={cn(+ "relative flex gap-3",+ message.role === "user" ? "flex-row-reverse" : "flex-row"+ )}+ >+ <div+ className={cn(+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition-colors",+ message.role === "user"+ ? "bg-foreground text-background border-foreground"+ : "bg-muted/50 text-foreground border-border/50"+ )}+ >+ {message.role === "user" ? (+ <User className="h-4 w-4" />+ ) : (+ <PipeAIIcon size={16} animated={false} />+ )}+ </div>+ <div+ className={cn(+ "relative flex-1 rounded-xl px-4 py-3 text-sm border",+ message.role === "user"+ ? "bg-foreground text-background border-foreground"+ : "bg-muted/30 border-border/50"+ )}+ >+ <MemoizedReactMarkdown+ className={cn(+ "prose prose-sm max-w-none",+ message.role === "user" ? "prose-invert" : "dark:prose-invert"+ )}+ remarkPlugins={[remarkGfm]}+ components={{+ p({ children }) {+ return <p className="mb-2 last:mb-0 leading-relaxed">{children}</p>;+ },+ a({ href, children, ...props }) {+ const isMediaLink = href?.toLowerCase().match(/\.(mp4|mp3|wav|webm)$/);+ if (isMediaLink && href) {+ return <VideoComponent filePath={href} className="my-2" />;+ }+ return (+ <a href={href} target="_blank" rel="noopener noreferrer" className="underline underline-offset-2" {...props}>+ {children}+ </a>+ );+ },+ code({ className, children, ...props }) {+ const content = String(children).replace(/\n$/, "");+ const isMedia = content.trim().toLowerCase().match(/\.(mp4|mp3|wav|webm)$/);++ if (isMedia) {+ return <VideoComponent filePath={content.trim()} className="my-2" />;+ }++ return (+ <code className="px-1.5 py-0.5 rounded bg-background/50 border border-border/50 font-mono text-xs" {...props}>+ {content}+ </code>+ );+ },+ }}+ >+ {message.content}+ </MemoizedReactMarkdown>+ </div>+ </motion.div>+ ))}+ </AnimatePresence>+ {isLoading && !messages.find(m => m.content.includes("Searching")) && (+ <motion.div+ initial={{ opacity: 0, y: 5 }}+ animate={{ opacity: 1, y: 0 }}+ className="flex items-center gap-3 px-4 py-3 bg-muted/30 rounded-xl border border-border/50 w-fit"+ >+ <PipeAIIcon size={18} thinking={true} className="text-foreground/70" />+ <span className="text-sm text-muted-foreground font-medium">Processing...</span>+ </motion.div>+ )}+ <div ref={messagesEndRef} />+ </div>++ {/* Input */}+ <div className="relative border-t border-border/50 bg-gradient-to-t from-muted/20 to-transparent">+ <div className="p-2 border-b border-border/30">+ <AIPresetsSelector+ onPresetChange={setActivePreset}+ showLoginCta={false}+ />+ </div>+ <form onSubmit={handleSubmit} className="p-3">+ <div className="flex gap-2">+ <div className="relative flex-1">+ <Input+ ref={inputRef}+ value={input}+ onChange={handleInputChange}+ onKeyDown={handleKeyDown}+ placeholder={+ disabledReason+ ? disabledReason+ : "Ask about your screen... (type @ for filters)"+ }+ disabled={isLoading || !canChat}+ className={cn(+ "flex-1 bg-background/50 border-border/50 focus:border-foreground/30 focus:ring-foreground/10 transition-colors",+ disabledReason && "border-destructive/50"+ )}+ />++ <AnimatePresence>+ {showMentionDropdown && filteredMentions.length > 0 && (+ <motion.div+ ref={dropdownRef}+ initial={{ opacity: 0, y: 4 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: 4 }}+ transition={{ duration: 0.1 }}+ className="absolute bottom-full left-0 right-0 mb-1 bg-background border border-border rounded-lg shadow-lg overflow-hidden z-50 max-h-[240px] overflow-y-auto"+ >+ {["time", "content", "app", "speaker"].map(category => {+ const items = filteredMentions.filter(m => m.category === category);+ if (items.length === 0) return null;+ return (+ <div key={category}>+ <div className="px-2 py-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground bg-muted/30 border-b border-border/50">+ {category === "time" ? "time" : category === "content" ? "content type" : category === "speaker" ? "speakers" : "apps"}+ </div>+ {items.map((suggestion) => {+ const globalIndex = filteredMentions.indexOf(suggestion);+ return (+ <button+ key={suggestion.tag}+ type="button"+ onClick={() => insertMention(suggestion.tag)}+ className={cn(+ "w-full px-3 py-1.5 text-left text-sm flex items-center justify-between gap-2 transition-colors",+ globalIndex === selectedMentionIndex+ ? "bg-muted text-foreground"+ : "hover:bg-muted/50"+ )}+ >+ <span className="font-mono text-xs">{suggestion.tag}</span>+ <span className="text-[10px] text-muted-foreground truncate">{suggestion.description}</span>+ </button>+ );+ })}+ </div>+ );+ })}+ {isLoadingSpeakers && (+ <div className="px-3 py-2 text-[10px] text-muted-foreground flex items-center gap-2">+ <Loader2 className="h-3 w-3 animate-spin" />+ <span>Searching speakers...</span>+ </div>+ )}+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ <Button+ type={isStreaming ? "button" : "submit"}+ size="icon"+ disabled={(!input.trim() && !isStreaming) || !canChat}+ onClick={isStreaming ? handleStop : undefined}+ className={cn(+ "shrink-0 transition-all duration-200",+ isStreaming+ ? "bg-destructive hover:bg-destructive/90"+ : "bg-foreground hover:bg-foreground/90 text-background"+ )}+ >+ {isStreaming ? (+ <Square className="h-4 w-4" />+ ) : (+ <Send className="h-4 w-4" />+ )}+ </Button>+ </div>+ </form>+ </div>++ <UpgradeDialog+ open={showUpgradeDialog}+ onOpenChange={setShowUpgradeDialog}+ reason={upgradeReason}+ resetsAt={upgradeResetsAt}+ />+ </div>+ );+}diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex 9368394c4..ae8072c2d 100644--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -174,7 +174,7 @@ let DEFAULT_SETTINGS: Settings = {stopRecordingShortcut: "Super+Alt+X",startAudioShortcut: "",stopAudioShortcut: "",- showSearchShortcut: "Super+Alt+K",+ showChatShortcut: "Super+Alt+L",enableRealtimeAudioTranscription: false,realtimeAudioTranscriptionEngine: "deepgram",disableVision: false,@@ -192,7 +192,7 @@ export function createDefaultSettingsObject(): Settings {DEFAULT_SETTINGS.ocrEngine = p === "macos" ? "apple-native" : p === "windows" ? "windows-native" : "tesseract";DEFAULT_SETTINGS.fps = p === "macos" ? 0.5 : 1;DEFAULT_SETTINGS.showScreenpipeShortcut = p === "windows" ? "Alt+S" : "Super+Alt+S";- DEFAULT_SETTINGS.showSearchShortcut = p === "windows" ? "Alt+K" : "Super+Alt+K";+ DEFAULT_SETTINGS.showChatShortcut = p === "windows" ? "Alt+L" : "Super+Alt+L";return DEFAULT_SETTINGS;} catch (e) {diff --git a/screenpipe-app-tauri/lib/utils/tauri.ts b/screenpipe-app-tauri/lib/utils/tauri.tsindex 484233f71..dca88e331 100644--- a/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/screenpipe-app-tauri/lib/utils/tauri.ts@@ -252,12 +252,12 @@ export type SettingsStore = { aiPresets: AIPreset[]; deepgramApiKey: string; isL/*** Persistent analytics ID used for PostHog tracking (both frontend and backend)*/-analyticsId: string; devMode: boolean; audioTranscriptionEngine: string; ocrEngine: string; monitorIds: string[]; audioDevices: string[]; usePiiRemoval: boolean; restartInterval: number; port: number; dataDir: string; disableAudio: boolean; ignoredWindows: string[]; includedWindows: string[]; fps: number; vadSensitivity: string; analyticsEnabled: boolean; audioChunkDuration: number; useChineseMirror: boolean; languages: string[]; embeddedLLM: EmbeddedLLM; enableBeta: boolean; isFirstTimeUser: boolean; autoStartEnabled: boolean; enableFrameCache: boolean; platform: string; disabledShortcuts: string[]; user: User; showScreenpipeShortcut: string; startRecordingShortcut: string; stopRecordingShortcut: string; startAudioShortcut: string; stopAudioShortcut: string; showSearchShortcut: string; enableRealtimeAudioTranscription: boolean; realtimeAudioTranscriptionEngine: string; disableVision: boolean; useAllMonitors: boolean; enableRealtimeVision: boolean; showShortcutOverlay?: boolean;+analyticsId: string; devMode: boolean; audioTranscriptionEngine: string; ocrEngine: string; monitorIds: string[]; audioDevices: string[]; usePiiRemoval: boolean; restartInterval: number; port: number; dataDir: string; disableAudio: boolean; ignoredWindows: string[]; includedWindows: string[]; fps: number; vadSensitivity: string; analyticsEnabled: boolean; audioChunkDuration: number; useChineseMirror: boolean; languages: string[]; embeddedLLM: EmbeddedLLM; enableBeta: boolean; isFirstTimeUser: boolean; autoStartEnabled: boolean; enableFrameCache: boolean; platform: string; disabledShortcuts: string[]; user: User; showScreenpipeShortcut: string; startRecordingShortcut: string; stopRecordingShortcut: string; startAudioShortcut: string; stopAudioShortcut: string; showChatShortcut: string; enableRealtimeAudioTranscription: boolean; realtimeAudioTranscriptionEngine: string; disableVision: boolean; useAllMonitors: boolean; enableRealtimeVision: boolean; showShortcutOverlay?: boolean;/*** Unique device ID for AI usage tracking (generated on first launch)*/deviceId?: string }-export type ShowRewindWindow = "Main" | { Settings: { page: string | null } } | { Search: { query: string | null } } | "Onboarding"+export type ShowRewindWindow = "Main" | { Settings: { page: string | null } } | { Search: { query: string | null } } | "Onboarding" | "Chat"export type User = { id: string | null; name: string | null; email: string | null; image: string | null; token: string | null; clerk_id: string | null; api_key: string | null; credits: Credits | null; stripe_connected: boolean | null; stripe_account_status: string | null; github_username: string | null; bio: string | null; website: string | null; contact: string | null; cloud_subscribed: boolean | null }/** tauri-specta globals **/diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex 742ce9b45..d7faac0b2 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -48,6 +48,8 @@ mod updates;mod window_api;#[cfg(target_os = "windows")]mod windows_overlay;+#[cfg(target_os = "macos")]+mod space_monitor;pub use server::*;@@ -285,21 +287,21 @@ async fn apply_shortcuts(app: &AppHandle, config: &ShortcutConfig) -> Result<(),).await?;- // Register show search shortcut (global - shows main window + opens search dialog)+ // Register show chat shortcut (global - toggles standalone AI chat window)register_shortcut(app,- &config.show_search,- config.is_disabled("show_search"),+ &config.show_chat,+ config.is_disabled("show_chat"),|app| {- info!("show search shortcut triggered");- // First show the main window- show_main_window(app, false);- // Then emit event to open search dialog (with small delay for window to be ready)- let app_clone = app.clone();- std::thread::spawn(move || {- std::thread::sleep(std::time::Duration::from_millis(100));- let _ = app_clone.emit("open-search", ());- });+ info!("show chat shortcut triggered");+ // Toggle the chat window - close if visible, show if not+ if let Some(window) = app.get_webview_window("chat") {+ if window.is_visible().unwrap_or(false) {+ let _ = window.close();+ return;+ }+ }+ let _ = ShowRewindWindow::Chat.show(app);},).await?;@@ -879,6 +881,9 @@ async fn main() {let _ = ShowRewindWindow::Settings { page: None }.show(app_handle);}});++ // Set up Space change listener to hide overlay when switching Spaces+ space_monitor::setup_space_listener(app.handle().clone());}// Logging setupdiff --git a/screenpipe-app-tauri/src-tauri/src/window_api.rs b/screenpipe-app-tauri/src-tauri/src/window_api.rsindex f5047ea94..38a14e8f9 100644--- a/screenpipe-app-tauri/src-tauri/src/window_api.rs+++ b/screenpipe-app-tauri/src-tauri/src/window_api.rs@@ -142,6 +142,7 @@ pub enum RewindWindowId {Settings,Search,Onboarding,+ Chat,}impl FromStr for RewindWindowId {@@ -153,6 +154,7 @@ impl FromStr for RewindWindowId {"settings" => Ok(RewindWindowId::Settings),"search" => Ok(RewindWindowId::Search),"onboarding" => Ok(RewindWindowId::Onboarding),+ "chat" => Ok(RewindWindowId::Chat),_ => Ok(RewindWindowId::Main),}}@@ -165,6 +167,7 @@ impl std::fmt::Display for RewindWindowId {RewindWindowId::Settings => write!(f, "settings"),RewindWindowId::Search => write!(f, "search"),RewindWindowId::Onboarding => write!(f, "onboarding"),+ RewindWindowId::Chat => write!(f, "chat"),}}}@@ -176,6 +179,7 @@ impl RewindWindowId {RewindWindowId::Settings => "settings",RewindWindowId::Search => "search",RewindWindowId::Onboarding => "onboarding",+ RewindWindowId::Chat => "chat",}}@@ -185,6 +189,7 @@ impl RewindWindowId {RewindWindowId::Settings => "settings",RewindWindowId::Search => "search",RewindWindowId::Onboarding => "onboarding",+ RewindWindowId::Chat => "ai chat",}}@@ -194,6 +199,7 @@ impl RewindWindowId {RewindWindowId::Settings => (1200.0, 850.0),RewindWindowId::Search => (1200.0, 850.0),RewindWindowId::Onboarding => (900.0, 800.0),+ RewindWindowId::Chat => (500.0, 600.0),})}@@ -209,6 +215,7 @@ pub enum ShowRewindWindow {Settings { page: Option<String> },Search { query: Option<String> },Onboarding,+ Chat,}impl ShowRewindWindow {@@ -254,6 +261,7 @@ impl ShowRewindWindow {ShowRewindWindow::Settings { page: _ } => RewindWindowId::Settings,ShowRewindWindow::Search { query: _ } => RewindWindowId::Search,ShowRewindWindow::Onboarding => RewindWindowId::Onboarding,+ ShowRewindWindow::Chat => RewindWindowId::Chat,}}@@ -263,6 +271,7 @@ impl ShowRewindWindow {ShowRewindWindow::Settings { page: _ } => None,ShowRewindWindow::Search { query } => Some(query.clone().unwrap_or_default().to_string()),ShowRewindWindow::Onboarding => None,+ ShowRewindWindow::Chat => None,}}@@ -640,6 +649,17 @@ impl ShowRewindWindow {window}+ ShowRewindWindow::Chat => {+ let builder = self.window_builder(app, "/chat")+ .inner_size(500.0, 650.0)+ .min_inner_size(400.0, 500.0)+ .focused(true)+ .always_on_top(true);+ #[cfg(target_os = "macos")]+ let builder = builder.hidden_title(true);+ let window = builder.build()?;+ window+ }};