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: autocomplete app and window

Louis Beaumont0ec8f9d1196e
diff --git a/content/docs/lib/utils.ts b/content/docs/lib/utils.ts
index bd0c391dd..a5ef19350 100644
--- a/content/docs/lib/utils.ts
+++ b/content/docs/lib/utils.ts
@@ -1,6 +1,6 @@
-import { clsx, type ClassValue } from "clsx"
-import { twMerge } from "tailwind-merge"
+import { clsx, type ClassValue } from "clsx";
+import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
+ return twMerge(clsx(inputs));
}
diff --git a/screenpipe-app-tauri/components/app-window-auto-complete.tsx b/screenpipe-app-tauri/components/app-window-auto-complete.tsx
new file mode 100644
index 000000000..8d4fe450a
--- /dev/null
+++ b/screenpipe-app-tauri/components/app-window-auto-complete.tsx
@@ -0,0 +1,64 @@
+import React, { useState, useEffect } from "react";
+import { Input } from "@/components/ui/input";
+import { useAppWindowHistory } from "@/lib/hooks/use-sql-autocomplete";
+import { Command } from "cmdk";
+
+interface AppWindowAutocompleteProps {
+ id: string;
+ placeholder: string;
+ value: string;
+ onChange: (value: string) => void;
+ type: "app" | "window";
+ icon: React.ReactNode;
+}
+
+export function AppWindowAutocomplete({
+ id,
+ placeholder,
+ value,
+ onChange,
+ type,
+ icon,
+}: AppWindowAutocompleteProps) {
+ const { history, isLoading, error } = useAppWindowHistory(type);
+ const [open, setOpen] = useState(false);
+
+ if (error) {
+ console.error("error fetching history:", error);
+ }
+
+ return (
+ <div className="relative">
+ {icon}
+ <Command>
+ <Input
+ id={id}
+ type="text"
+ placeholder={placeholder}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onFocus={() => setOpen(true)}
+ onBlur={() => setOpen(false)}
+ className="pl-8"
+ />
+ {open && !isLoading && (
+ <Command.List className="absolute z-10 w-full bg-white border border-gray-300 rounded-md mt-1 max-h-60 overflow-auto">
+ <Command.Input />
+ {history.map((item) => (
+ <Command.Item
+ key={item.name}
+ value={item.name}
+ onSelect={(selectedValue) => {
+ onChange(selectedValue);
+ setOpen(false);
+ }}
+ >
+ {item.name} ({item.count})
+ </Command.Item>
+ ))}
+ </Command.List>
+ )}
+ </Command>
+ </div>
+ );
+}
diff --git a/screenpipe-app-tauri/components/search-chat.tsx b/screenpipe-app-tauri/components/search-chat.tsx
index 1af62ef0e..1af7badde 100644
--- a/screenpipe-app-tauri/components/search-chat.tsx
+++ b/screenpipe-app-tauri/components/search-chat.tsx
@@ -70,6 +70,8 @@ import { Checkbox } from "@/components/ui/checkbox";
import { formatISO } from "date-fns";
import { IconCode } from "@/components/ui/icons";
import { CodeBlock } from "./ui/codeblock";
+import { SqlAutocompleteInput } from "./sql-autocomplete-input";
+import { encode } from "@/lib/utils";
export function SearchChat() {
// Search state
@@ -124,7 +126,7 @@ export function SearchChat() {
const generateCurlCommand = () => {
const baseUrl = "http://localhost:3030";
- const queryParams = new URLSearchParams({
+ const params = {
content_type: contentType,
limit: limit.toString(),
offset: offset.toString(),
@@ -132,15 +134,18 @@ export function SearchChat() {
end_time: formatISO(endDate, { representation: "complete" }),
min_length: minLength.toString(),
max_length: maxLength.toString(),
- });
+ q: query,
+ app_name: appName,
+ window_name: windowName,
+ include_frames: includeFrames ? "true" : undefined,
+ };
- if (query) queryParams.append("q", query);
- if (appName) queryParams.append("app_name", appName);
- if (windowName) queryParams.append("window_name", windowName);
- if (includeFrames) queryParams.append("include_frames", "true");
+ const queryString = Object.entries(params)
+ .filter(([_, value]) => value !== undefined && value !== "")
+ .map(([key, value]) => ` ${key}=${JSON.stringify(value)}`)
+ .join(" \\\n");
- return `curl "${baseUrl}/search?\\
-${queryParams.toString().replace(/&/g, "\\\n&")}" | jq`;
+ return `curl "${baseUrl}/search" \\\n${queryString} | jq`;
};
useEffect(() => {
@@ -706,71 +711,34 @@ ${queryParams.toString().replace(/&/g, "\\\n&")}" | jq`;
</div>
</div>
<div className="space-y-2">
- <div className="flex items-center space-x-2">
- <Label htmlFor="app-name">app name</Label>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="h-4 w-4 text-gray-400" />
- </TooltipTrigger>
- <TooltipContent>
- <p>
- enter the name of the app to search for content for example
- zoom, notion, etc. only works for ocr.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <div className="relative">
- <Laptop
- className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400"
- size={18}
- />
- <Input
- id="app-name"
- type="text"
- placeholder="app name"
- value={appName}
- onChange={(e) => setAppName(e.target.value)}
- autoCorrect="off"
- className="pl-8"
- />
- </div>
+ <SqlAutocompleteInput
+ id="app-name"
+ placeholder="app name"
+ value={appName}
+ onChange={setAppName}
+ type="app"
+ icon={
+ <Laptop
+ className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400"
+ size={18}
+ />
+ }
+ />
</div>
<div className="space-y-2">
- <div className="flex items-center space-x-2">
- <Label htmlFor="window-name">window name</Label>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="h-4 w-4 text-gray-400" />
- </TooltipTrigger>
- <TooltipContent>
- <p>
- enter the name of the window or tab to search for content.
- can be a browser tab name, app tab name, etc. only works for
- ocr.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <div className="relative">
- <Layout
- className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400"
- size={18}
- />
- <Input
- id="window-name"
- type="text"
- placeholder="window name"
- value={windowName}
- onChange={(e) => setWindowName(e.target.value)}
- autoCorrect="off"
- className="pl-8"
- />
- </div>
+ <SqlAutocompleteInput
+ id="window-name"
+ placeholder="window name"
+ value={windowName}
+ onChange={setWindowName}
+ type="window"
+ icon={
+ <Layout
+ className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400"
+ size={18}
+ />
+ }
+ />
</div>
<div className="flex items-center space-x-2">
<Switch
@@ -916,7 +884,9 @@ ${queryParams.toString().replace(/&/g, "\\\n&")}" | jq`;
</span>
</DialogDescription>
</DialogHeader>
- <CodeBlock language="bash" value={generateCurlCommand()} />
+ <div className="overflow-x-auto">
+ <CodeBlock language="bash" value={generateCurlCommand()} />
+ </div>
</DialogContent>
</Dialog>
</div>
diff --git a/screenpipe-app-tauri/components/sql-autocomplete-input.tsx b/screenpipe-app-tauri/components/sql-autocomplete-input.tsx
new file mode 100644
index 000000000..cd882eb82
--- /dev/null
+++ b/screenpipe-app-tauri/components/sql-autocomplete-input.tsx
@@ -0,0 +1,137 @@
+import React, { useState, useRef, useCallback, useEffect } from "react";
+import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";
+import { Command } from "cmdk";
+import { Input } from "@/components/ui/input";
+import { Loader2, Search, X } from "lucide-react";
+
+interface SqlAutocompleteInputProps {
+ id: string;
+ placeholder: string;
+ value: string;
+ onChange: (value: string) => void;
+ type: "app" | "window";
+ icon: React.ReactNode;
+}
+
+export function SqlAutocompleteInput({
+ id,
+ placeholder,
+ value,
+ onChange,
+ type,
+ icon,
+}: SqlAutocompleteInputProps) {
+ const { items, isLoading } = useSqlAutocomplete(type);
+ const [open, setOpen] = useState(false);
+ const [inputValue, setInputValue] = useState(value);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const commandRef = useRef<HTMLDivElement>(null);
+
+ const handleSelect = (selectedValue: string) => {
+ onChange(selectedValue);
+ setInputValue(selectedValue);
+ setOpen(false);
+ inputRef.current?.focus();
+ };
+
+ const handleInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ setInputValue(e.target.value);
+ onChange(e.target.value);
+ },
+ [onChange]
+ );
+
+ const handleClearInput = useCallback(() => {
+ setInputValue("");
+ onChange("");
+ inputRef.current?.focus();
+ }, [onChange]);
+
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (
+ commandRef.current &&
+ !commandRef.current.contains(event.target as Node)
+ ) {
+ setOpen(false);
+ }
+ };
+
+ document.addEventListener("mousedown", handleClickOutside);
+ return () => {
+ document.removeEventListener("mousedown", handleClickOutside);
+ };
+ }, []);
+
+ return (
+ <div className="relative" ref={commandRef}>
+ <div className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400 z-10 flex items-center">
+ {icon}
+ <span className="w-2" />
+ </div>
+ <Command className="relative w-full" shouldFilter={false}>
+ <div className="relative">
+ <Input
+ ref={inputRef}
+ id={id}
+ type="text"
+ placeholder={placeholder}
+ value={inputValue}
+ onChange={handleInputChange}
+ onFocus={() => setOpen(true)}
+ className="pl-10 pr-8 w-full"
+ autoCorrect="off"
+ />
+ {inputValue && (
+ <button
+ onClick={handleClearInput}
+ className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ )}
+ </div>
+ {open && (
+ <Command.List className="absolute z-20 w-full bg-white border border-gray-300 rounded-md mt-1 max-h-60 overflow-auto shadow-lg text-sm">
+ <div className="flex items-center px-3 py-2 border-b border-gray-200">
+ <Search className="mr-2 h-4 w-4 text-gray-400" />
+ <Command.Input
+ placeholder="search..."
+ value={inputValue}
+ onValueChange={setInputValue}
+ className="border-none focus:ring-0 outline-none w-full"
+ />
+ </div>
+ {isLoading ? (
+ <Command.Loading>
+ <div className="px-4 py-2 text-gray-500 flex items-center">
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ loading...
+ </div>
+ </Command.Loading>
+ ) : (
+ items
+ .filter((item) =>
+ item.name.toLowerCase().includes(inputValue.toLowerCase())
+ )
+ .map((item: any) => (
+ <Command.Item
+ key={item.name}
+ value={item.name}
+ onSelect={handleSelect}
+ className="px-4 py-2 hover:bg-gray-100 cursor-pointer border-b border-gray-200 last:border-b-0"
+ >
+ {item.name} ({item.count})
+ </Command.Item>
+ ))
+ )}
+ {!isLoading && items.length === 0 && (
+ <div className="px-4 py-2 text-gray-500">no results found</div>
+ )}
+ </Command.List>
+ )}
+ </Command>
+ </div>
+ );
+}
diff --git a/screenpipe-app-tauri/lib/hooks/use-sql-autocomplete.tsx b/screenpipe-app-tauri/lib/hooks/use-sql-autocomplete.tsx
new file mode 100644
index 000000000..7db3de855
--- /dev/null
+++ b/screenpipe-app-tauri/lib/hooks/use-sql-autocomplete.tsx
@@ -0,0 +1,61 @@
+import { useState, useEffect, useCallback } from "react";
+
+interface AutocompleteItem {
+ name: string;
+ count: number;
+}
+
+const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
+
+const cache: Record<string, { data: AutocompleteItem[]; timestamp: number }> =
+ {};
+
+export function useSqlAutocomplete(type: "app" | "window") {
+ const [items, setItems] = useState<AutocompleteItem[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+
+ const fetchItems = useCallback(async () => {
+ setIsLoading(true);
+ try {
+ const cachedData = cache[type];
+ if (cachedData && Date.now() - cachedData.timestamp < CACHE_DURATION) {
+ setItems(cachedData.data);
+ } else {
+ const query = `
+ SELECT ${
+ type === "app" ? "ocr.app_name" : "ocr.window_name"
+ } as name, COUNT(*) as count
+ FROM ocr_text ocr
+ JOIN frames f ON ocr.frame_id = f.id
+ WHERE f.timestamp > datetime('now', '-7 days')
+ GROUP BY ${type === "app" ? "ocr.app_name" : "ocr.window_name"}
+ ORDER BY count DESC
+ LIMIT 100
+ `;
+ const response = await fetch("http://localhost:3030/raw_sql", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ query }),
+ });
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ const result = await response.json();
+ setItems(result);
+ cache[type] = { data: result, timestamp: Date.now() };
+ }
+ } catch (error) {
+ console.error("failed to fetch items:", error);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [type]);
+
+ useEffect(() => {
+ fetchItems();
+ }, [fetchItems]);
+
+ return { items, isLoading };
+}
diff --git a/screenpipe-app-tauri/lib/screenpipe.ts b/screenpipe-app-tauri/lib/screenpipe.ts
index 83b98a4fa..f7789396d 100644
--- a/screenpipe-app-tauri/lib/screenpipe.ts
+++ b/screenpipe-app-tauri/lib/screenpipe.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { encode } from "./utils";
// Define types based on the server's schema
export type OCRContent = {
@@ -146,37 +147,36 @@ export async function queryScreenpipe(
try {
console.log("params", params);
- const queryParams = new URLSearchParams(
- Object.entries({
- q: params.q ? encodeURIComponent(params.q) : undefined,
- offset: params.offset.toString(),
- limit: params.limit.toString(),
- start_time: params.start_time,
- end_time: params.end_time,
- content_type: params.content_type,
- app_name: params.app_name
- ? encodeURIComponent(params.app_name)
- : undefined,
- window_name: params.window_name
- ? encodeURIComponent(params.window_name)
- : undefined,
- include_frames: params.include_frames.toString(),
- min_length: params.min_length.toString(),
- max_length: params.max_length.toString(),
- }).filter(([_, v]) => v != null) as [string, string][]
- );
- console.log("calling screenpipe", JSON.stringify(params));
- const response = await fetch(`http://localhost:3030/search?${queryParams}`);
+ const queryParams = new URLSearchParams({
+ content_type: params.content_type,
+ limit: params.limit.toString(),
+ offset: params.offset.toString(),
+ start_time: params.start_time,
+ end_time: params.end_time,
+ min_length: params.min_length.toString(),
+ max_length: params.max_length.toString(),
+ include_frames: params.include_frames.toString(),
+ });
+
+ if (params.q) queryParams.append("q", params.q);
+ if (params.app_name) queryParams.append("app_name", params.app_name);
+ if (params.window_name)
+ queryParams.append("window_name", params.window_name);
+
+ const url = `http://localhost:3030/search?${queryParams.toString()}`;
+ console.log("calling screenpipe", url);
+
+ const response = await fetch(url);
if (!response.ok) {
const text = await response.text();
- throw new Error(`HTTP error! status: ${response.status} ${text}`);
+ throw new Error(`http error! status: ${response.status} ${text}`);
}
const result = await response.json();
console.log("result", result);
console.log("result", result.data.length);
return result;
} catch (error) {
- console.error("Error querying screenpipe:", error);
+ console.error("error querying screenpipe:", error);
return null;
}
}
diff --git a/screenpipe-app-tauri/lib/utils.ts b/screenpipe-app-tauri/lib/utils.ts
index 59af118fd..474a1f1b3 100644
--- a/screenpipe-app-tauri/lib/utils.ts
+++ b/screenpipe-app-tauri/lib/utils.ts
@@ -9,16 +9,14 @@ export function stripAnsiCodes(str: string): string {
return str.replace(/\x1B\[[0-9;]*[JKmsu]/g, "");
}
export function toCamelCase(str: string): string {
- return str.replace(/([-_][a-z])/g, group =>
- group.toUpperCase()
- .replace('-', '')
- .replace('_', '')
+ return str.replace(/([-_][a-z])/g, (group) =>
+ group.toUpperCase().replace("-", "").replace("_", "")
);
}
export function keysToCamelCase<T>(obj: any): T {
if (Array.isArray(obj)) {
- return obj.map(v => keysToCamelCase<T>(v)) as any;
+ return obj.map((v) => keysToCamelCase<T>(v)) as any;
} else if (obj !== null && obj.constructor === Object) {
return Object.keys(obj).reduce(
(result, key) => ({
@@ -29,4 +27,10 @@ export function keysToCamelCase<T>(obj: any): T {
) as T;
}
return obj;
-}
\ No newline at end of file
+}
+
+export function encode(str: string): string {
+ return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
+ return "%" + c.charCodeAt(0).toString(16).toUpperCase();
+ });
+}
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index ab3b5a0bb..7652f19ac 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.2.54"
+version = "0.2.55"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index efebcda41..c1d5e07ea 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -7,17 +7,22 @@ use screenpipe_integrations::friend_wearable::FriendWearableDatabase;
use screenpipe_vision::OcrEngine;
use serde::{Deserialize, Serialize};
use sqlx::migrate::MigrateDatabase;
+use sqlx::Column;
use sqlx::Error as SqlxError;
+use sqlx::Row;
+use sqlx::TypeInfo;
+use sqlx::ValueRef;
use sqlx::{
sqlite::{SqlitePool, SqlitePoolOptions},
FromRow,
};
+
use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
-use tokio::time::{timeout, Duration as TokioDuration};
+use tokio::time::{timeout, Duration as TokioDuration};
#[derive(Debug)]
pub struct DatabaseError(String);
@@ -1421,6 +1426,43 @@ impl DatabaseManager {
tx.commit().await?;
Ok(())
}
+ pub async fn execute_raw_sql(&self, query: &str) -> Result<serde_json::Value, sqlx::Error> {
+ let rows = sqlx::query(query).fetch_all(&self.pool).await?;
+
+ let result: Vec<serde_json::Map<String, serde_json::Value>> = rows
+ .iter()
+ .map(|row| {
+ let mut map = serde_json::Map::new();
+ for (i, column) in row.columns().iter().enumerate() {
+ if let Ok(value) = row.try_get_raw(i) {
+ let json_value = match value.type_info().name() {
+ "TEXT" => {
+ let s: String = row.try_get(i).unwrap_or_default();
+ serde_json::Value::String(s)
+ }
+ "INTEGER" => {
+ let i: i64 = row.try_get(i).unwrap_or_default();
+ serde_json::Value::Number(i.into())
+ }
+ "REAL" => {
+ let f: f64 = row.try_get(i).unwrap_or_default();
+ serde_json::Value::Number(
+ serde_json::Number::from_f64(f).unwrap_or(0.into()),
+ )
+ }
+ _ => serde_json::Value::Null,
+ };
+ map.insert(column.name().to_string(), json_value);
+ }
+ }
+ map
+ })
+ .collect();
+
+ Ok(serde_json::Value::Array(
+ result.into_iter().map(serde_json::Value::Object).collect(),
+ ))
+ }
}
impl Clone for DatabaseManager {
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 8e4bd582b..fab67e1ed 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -797,6 +797,27 @@ async fn merge_frames_handler(
}
}
+#[derive(Deserialize)]
+struct RawSqlQuery {
+ query: String,
+}
+
+async fn execute_raw_sql(
+ State(state): State<Arc<AppState>>,
+ JsonResponse(payload): JsonResponse<RawSqlQuery>,
+) -> Result<JsonResponse<serde_json::Value>, (StatusCode, JsonResponse<serde_json::Value>)> {
+ match state.db.execute_raw_sql(&payload.query).await {
+ Ok(result) => Ok(JsonResponse(result)),
+ Err(e) => {
+ error!("Failed to execute raw SQL query: {}", e);
+ Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ ))
+ }
+ }
+}
+
pub fn create_router() -> Router<Arc<AppState>> {
Router::new()
.route("/search", get(search))
@@ -814,6 +835,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/pipes/update", post(update_pipe_config_handler))
.route("/experimental/frames/merge", post(merge_frames_handler))
.route("/health", get(health_check))
+ .route("/raw_sql", post(execute_raw_sql))
}
/*