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: Traversing UI (#631)

Matthew Diakonov72bd255a7c9c
diff --git a/screenpipe-app-tauri/components/recording-settings.tsx b/screenpipe-app-tauri/components/recording-settings.tsx
index 7aba80d9a..e25cba2a6 100644
--- a/screenpipe-app-tauri/components/recording-settings.tsx
+++ b/screenpipe-app-tauri/components/recording-settings.tsx
@@ -69,6 +69,7 @@ import { initOpenTelemetry } from "@/lib/opentelemetry";
import { Language } from "@/lib/language";
import { Command as ShellCommand } from "@tauri-apps/plugin-shell";
import { CliCommandDialog } from "./cli-command-dialog";
+import { ToastAction } from "@/components/ui/toast";
interface AudioDevice {
name: string;
@@ -559,6 +560,42 @@ export function RecordingSettings({
await invoke("show_timeline");
};
+ const handleUiMonitoringToggle = async (checked: boolean) => {
+ try {
+ if (checked) {
+ // Check accessibility permissions first
+ const hasPermission = await invoke('check_accessibility_permissions');
+ if (!hasPermission) {
+ toast({
+ title: "accessibility permission required",
+ description: "please grant accessibility permission in system preferences",
+ action: (
+ <ToastAction altText="open preferences" onClick={() => invoke('open_accessibility_preferences')}>
+ open preferences
+ </ToastAction>
+ ),
+ variant: "destructive",
+ });
+ return;
+ }
+ }
+
+ // Just update the local setting - the update button will handle the restart
+ setLocalSettings({
+ ...localSettings,
+ enableUiMonitoring: checked
+ });
+
+ } catch (error) {
+ console.error("failed to toggle ui monitoring:", error);
+ toast({
+ title: "error checking accessibility permissions",
+ description: "please try again or check the logs",
+ variant: "destructive",
+ });
+ }
+ };
+
return (
<>
<div className="relative">
@@ -1389,43 +1426,38 @@ export function RecordingSettings({
)}
</div>
</div>
- <div className="flex items-center space-x-2">
- <Switch
- id="ui-monitoring-toggle"
- checked={localSettings.enableUiMonitoring}
- onCheckedChange={(checked) =>
- setLocalSettings({
- ...localSettings,
- enableUiMonitoring: checked,
- })
- }
- />
- <Label
- htmlFor="ui-monitoring-toggle"
- className="flex items-center space-x-2"
- >
- <span>enable UI monitoring</span>
- <Badge variant="outline" className="ml-2">macOS only</Badge>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <p>
- enables monitoring of UI elements and their interactions.
- <br />
- this allows for better context in search results
- <br />
- and more accurate activity tracking.
- <br />
- (macOS only)
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </Label>
- </div>
+ {isMacOS && (
+ <div className="flex items-center space-x-2">
+ <Switch
+ id="ui-monitoring-toggle"
+ checked={localSettings.enableUiMonitoring}
+ onCheckedChange={handleUiMonitoringToggle}
+ />
+ <Label
+ htmlFor="ui-monitoring-toggle"
+ className="flex items-center space-x-2"
+ >
+ <span>enable UI monitoring</span>
+ <Badge variant="outline" className="ml-2">accessibility permissions</Badge>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ enables monitoring of UI elements and their interactions.
+ <br />
+ this allows for better context in search results
+ <br />
+ * requires accessibility permission
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ </div>
+ )}
</CardContent>
</Card>
</div>
diff --git a/screenpipe-app-tauri/components/screenpipe-status.tsx b/screenpipe-app-tauri/components/screenpipe-status.tsx
index f074b003a..d48f4b9bf 100644
--- a/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -110,20 +110,24 @@ const HealthStatus = ({ className }: { className?: string }) => {
status: string,
frameStatus: string,
audioStatus: string,
- audioDisabled: boolean
+ uiStatus: string,
+ audioDisabled: boolean,
+ uiMonitoringEnabled: boolean
) => {
if (status === "loading") return "bg-yellow-500";
const isVisionOk = frameStatus === "ok" || frameStatus === "disabled";
- const isAudioOk =
- audioStatus === "ok" || audioStatus === "disabled" || audioDisabled;
- return isVisionOk && isAudioOk ? "bg-green-500" : "bg-red-500";
+ const isAudioOk = audioStatus === "ok" || audioStatus === "disabled" || audioDisabled;
+ const isUiOk = uiStatus === "ok" || uiStatus === "disabled" || !uiMonitoringEnabled;
+ return isVisionOk && isAudioOk && isUiOk ? "bg-green-500" : "bg-red-500";
};
const getStatusMessage = (
status: string,
frameStatus: string,
audioStatus: string,
- audioDisabled: boolean
+ uiStatus: string,
+ audioDisabled: boolean,
+ uiMonitoringEnabled: boolean
) => {
if (status === "loading")
return "screenpipe is starting up. this may take a few minutes...";
@@ -133,6 +137,8 @@ const HealthStatus = ({ className }: { className?: string }) => {
issues.push("screen recording");
if (!audioDisabled && audioStatus !== "ok" && audioStatus !== "disabled")
issues.push("audio recording");
+ if (uiMonitoringEnabled && uiStatus !== "ok" && uiStatus !== "disabled")
+ issues.push("ui monitoring");
if (issues.length === 0) return "screenpipe is running smoothly";
return `there might be an issue with ${issues.join(" and ")}`;
@@ -364,13 +370,17 @@ const HealthStatus = ({ className }: { className?: string }) => {
health.status,
health.frame_status,
health.audio_status,
- settings.disableAudio
+ health.ui_status,
+ settings.disableAudio,
+ settings.enableUiMonitoring
);
const statusMessage = getStatusMessage(
health.status,
health.frame_status,
health.audio_status,
- settings.disableAudio
+ health.ui_status,
+ settings.disableAudio,
+ settings.enableUiMonitoring
);
return (
@@ -414,23 +424,33 @@ const HealthStatus = ({ className }: { className?: string }) => {
</div>
</DialogHeader>
<div className="flex-grow overflow-auto">
- <p className="text-sm mb-2 font-semibold">{statusMessage}</p>
- <div className="text-xs mb-4">
- <p>screen recording: {health.frame_status}</p>
- <p>
- audio recording:{" "}
- {settings.disableAudio ? "turned off" : health.audio_status}
- </p>
- <p>
- last screen capture:{" "}
- {formatTimestamp(health.last_frame_timestamp)}
- </p>
- <p>
- last audio capture:{" "}
- {settings.disableAudio
- ? "n/a"
- : formatTimestamp(health.last_audio_timestamp)}
- </p>
+ <p className="text-sm mb-4 font-semibold">{statusMessage}</p>
+ <div className="space-y-2 text-xs mb-4">
+ {/* Screen Recording Status */}
+ <div className="flex items-center">
+ <div className={`w-2 h-2 rounded-full ${health.frame_status === "ok" ? "bg-green-500" : "bg-red-500"} mr-2`} />
+ <span>screen recording</span>
+ <span className="text-muted-foreground ml-2">status: {health.frame_status},</span>
+ <span className="text-muted-foreground ml-2">last update: {formatTimestamp(health.last_frame_timestamp)}</span>
+ </div>
+
+ {/* Audio Recording Status */}
+ <div className="flex items-center">
+ <div className={`w-2 h-2 rounded-full ${settings.disableAudio ? "bg-gray-400" : health.audio_status === "ok" ? "bg-green-500" : "bg-red-500"} mr-2`} />
+ <span>audio recording</span>
+ <span className="text-muted-foreground ml-2">status: {settings.disableAudio ? "turned off" : health.audio_status},</span>
+ <span className="text-muted-foreground ml-2">last update: {settings.disableAudio ? "n/a" : formatTimestamp(health.last_audio_timestamp)}</span>
+ </div>
+
+ {/* UI Monitoring Status - Only show if enabled */}
+ {settings.enableUiMonitoring && (
+ <div className="flex items-center">
+ <div className={`w-2 h-2 rounded-full ${health.ui_status === "ok" ? "bg-green-500" : "bg-red-500"} mr-2`} />
+ <span>ui monitoring</span>
+ <span className="text-muted-foreground ml-2">status: {health.ui_status},</span>
+ <span className="text-muted-foreground ml-2">last update: {formatTimestamp(health.last_ui_timestamp)}</span>
+ </div>
+ )}
</div>
<Separator className="my-12" />
diff --git a/screenpipe-app-tauri/components/search-chat.tsx b/screenpipe-app-tauri/components/search-chat.tsx
index 5d78a1ee8..81da8e8d6 100644
--- a/screenpipe-app-tauri/components/search-chat.tsx
+++ b/screenpipe-app-tauri/components/search-chat.tsx
@@ -89,9 +89,6 @@ interface SearchChatProps {
searches: SearchHistory[];
}
-export function SearchChat({ currentSearchId, onAddSearch, searches }: SearchChatProps) {
-
-
interface Agent {
id: string;
name: string;
@@ -161,6 +158,42 @@ const AGENTS: Agent[] = [
},
];
+// Add this helper function to highlight keywords in text
+const highlightKeyword = (text: string, keyword: string): JSX.Element => {
+ if (!keyword || !text) return <>{text}</>;
+
+ const parts = text.split(new RegExp(`(${keyword})`, 'gi'));
+ return (
+ <>
+ {parts.map((part, i) =>
+ part.toLowerCase() === keyword.toLowerCase() ? (
+ <span key={i} className="bg-yellow-200 dark:bg-yellow-800 rounded px-0.5">{part}</span>
+ ) : (
+ part
+ )
+ )}
+ </>
+ );
+};
+
+// Update the getContextAroundKeyword function to return both text and positions
+const getContextAroundKeyword = (text: string, keyword: string, contextLength: number = 40): string => {
+ if (!keyword || !text) return text;
+
+ const index = text.toLowerCase().indexOf(keyword.toLowerCase());
+ if (index === -1) return text;
+
+ const start = Math.max(0, index - contextLength);
+ const end = Math.min(text.length, index + keyword.length + contextLength);
+
+ let result = text.slice(start, end);
+ if (start > 0) result = '...' + result;
+ if (end < text.length) result = result + '...';
+
+ return result;
+};
+
+export function SearchChat({ currentSearchId, onAddSearch, searches }: SearchChatProps) {
// Search state
const { health } = useHealthCheck();
const [query, setQuery] = useState("");
@@ -221,6 +254,38 @@ const AGENTS: Agent[] = [
const [isQueryParamsDialogOpen, setIsQueryParamsDialogOpen] = useState(false);
+ // Add state for individual content types
+ const [selectedTypes, setSelectedTypes] = useState({
+ ocr: false,
+ audio: false,
+ ui: false,
+ });
+
+ // Update content type when checkboxes change
+ const handleContentTypeChange = (type: 'ocr' | 'audio' | 'ui') => {
+ const newTypes = { ...selectedTypes, [type]: !selectedTypes[type] };
+ setSelectedTypes(newTypes);
+
+ // Convert checkbox state to content type
+ if (!newTypes.ocr && !newTypes.audio && !newTypes.ui) {
+ setContentType('all'); // fallback to all if nothing selected
+ } else if (newTypes.audio && newTypes.ui && !newTypes.ocr) {
+ setContentType('audio+ui');
+ } else if (newTypes.ocr && newTypes.ui && !newTypes.audio) {
+ setContentType('ocr+ui');
+ } else if (newTypes.audio && newTypes.ocr && !newTypes.ui) {
+ setContentType('audio+ocr');
+ } else if (newTypes.audio) {
+ setContentType('audio');
+ } else if (newTypes.ocr) {
+ setContentType('ocr');
+ } else if (newTypes.ui) {
+ setContentType('ui'); // This was missing - single UI type
+ } else {
+ setContentType('all');
+ }
+ };
+
const [selectedAgent, setSelectedAgent] = useState<Agent>(AGENTS[0]);
useEffect(() => {
@@ -595,6 +660,9 @@ const AGENTS: Agent[] = [
const response = await queryScreenpipe(searchParams);
+ // Add debug logging
+ console.log("search response:", response);
+
if (!response || !Array.isArray(response.data)) {
throw new Error("invalid response data");
}
@@ -710,21 +778,68 @@ const AGENTS: Agent[] = [
<AccordionTrigger className="flex items-center">
<div className="flex items-center w-full">
<Badge className="mr-2">{item.type}</Badge>
+ <span className="flex-grow truncate">
+ {item.type === "UI" && highlightKeyword(
+ getContextAroundKeyword(item.content.text, query),
+ query
+ )}
+ {item.type === "OCR" && highlightKeyword(
+ getContextAroundKeyword(item.content.text, query),
+ query
+ )}
+ {item.type === "Audio" && highlightKeyword(
+ getContextAroundKeyword(item.content.transcription, query),
+ query
+ )}
+ {item.type === "FTS" && highlightKeyword(
+ getContextAroundKeyword(item.content.matched_text, query),
+ query
+ )}
+ </span>
</div>
- <span className="flex-grow text-center truncate">
- {item.type === "OCR" &&
- item.content.text.substring(0, 50)}
- {item.type === "Audio" &&
- item.content.transcription.substring(0, 50)}
- {item.type === "FTS" &&
- item.content.matched_text.substring(0, 50)}
- ...
- </span>
</AccordionTrigger>
<AccordionContent>
+ {item.type === "UI" && (
+ <>
+ <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">
+ <p className="whitespace-pre-line">
+ {highlightKeyword(item.content.text, query)}
+ </p>
+ </div>
+ <div className="flex justify-center mt-4">
+ <VideoComponent filePath={item.content.file_path} />
+ </div>
+ <div className="flex flex-wrap items-center gap-2 mt-2">
+ {item.content.app_name && (
+ <Badge
+ className="text-xs cursor-pointer"
+ onClick={() =>
+ handleBadgeClick(item.content.app_name, "app")
+ }
+ >
+ {item.content.app_name}
+ </Badge>
+ )}
+ {item.content.window_name && (
+ <Badge
+ className="text-xs cursor-pointer"
+ onClick={() =>
+ handleBadgeClick(item.content.window_name, "window")
+ }
+ >
+ {item.content.window_name}
+ </Badge>
+ )}
+ </div>
+ </>
+ )}
{item.type === "OCR" && (
<>
- <p className="mt-2">{item.content.text}</p>
+ <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">
+ <p className="whitespace-pre-line">
+ {highlightKeyword(item.content.text, query)}
+ </p>
+ </div>
<div className="flex justify-center mt-4">
<VideoComponent filePath={item.content.file_path} />
</div>
@@ -752,9 +867,7 @@ const AGENTS: Agent[] = [
<HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />
</TooltipTrigger>
<TooltipContent>
- <p>
- this is the frame where the text appeared
- </p>
+ <p>this is the frame where the text appeared</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
@@ -764,7 +877,11 @@ const AGENTS: Agent[] = [
)}
{item.type === "Audio" && (
<>
- <p className="mt-2">{item.content.transcription}</p>
+ <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">
+ <p className="whitespace-pre-line">
+ {highlightKeyword(item.content.transcription, query)}
+ </p>
+ </div>
{item.content.file_path &&
item.content.file_path.trim() !== "" ? (
<div className="flex justify-center mt-4">
@@ -772,19 +889,23 @@ const AGENTS: Agent[] = [
</div>
) : (
<p className="text-gray-500 italic mt-2">
- No file path available for this audio.
+ no file path available for this audio.
</p>
)}
</>
)}
{item.type === "FTS" && (
<>
- <p className="mt-2">{item.content.matched_text}</p>
- {item.content.original_frame_text && (
- <p className="mt-2 text-sm text-gray-600">
- Original: {item.content.original_frame_text}
+ <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">
+ <p className="whitespace-pre-line">
+ {highlightKeyword(item.content.matched_text, query)}
</p>
- )}
+ {item.content.original_frame_text && (
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400 whitespace-pre-line">
+ original: {item.content.original_frame_text}
+ </p>
+ )}
+ </div>
</>
)}
</AccordionContent>
@@ -865,80 +986,158 @@ const AGENTS: Agent[] = [
return (
<div className="w-full max-w-4xl mx-auto p-4 mt-12">
- <div className="flex flex-wrap items-center gap-4 mb-4">
- <div className="flex-grow flex items-center space-x-4">
- <SqlAutocompleteInput
- id="window-name"
- type="window"
- icon={<Layers className="h-4 w-4" />}
- value={windowName}
- onChange={setWindowName}
- placeholder="filter by window name"
- className="w-3/4"
- />
- <Button
- variant="outline"
- size="icon"
- onClick={() => setIsQueryParamsDialogOpen(true)}
- >
- <Settings className="h-4 w-12" />
- </Button>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <span>
- <Button
- onClick={() => handleSearch(0)}
- disabled={
- isLoading || !health || health?.status === "error"
- }
- >
- {isLoading ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- searching...
- </>
- ) : (
- <>
- <Search className="mr-2 h-4 w-4" />
- search
- </>
- )}
- </Button>
- </span>
- </TooltipTrigger>
- {health?.status === "error" && (
+ {/* Content Type Checkboxes and Code Button */}
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center space-x-1">
+ <div className="flex items-center space-x-1">
+ <Checkbox
+ id="audio-type"
+ checked={selectedTypes.audio}
+ onCheckedChange={() => handleContentTypeChange('audio')}
+ className="h-4 w-4"
+ />
+ <Label htmlFor="audio-type" className="text-xs">speech</Label>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-3 w-3 text-muted-foreground ml-0.5" />
+ </TooltipTrigger>
<TooltipContent>
- <p>screenpipe is not running...</p>
+ <p>audio transcripts</p>
</TooltipContent>
- )}
- </Tooltip>
- </TooltipProvider>
- <Dialog open={isCurlDialogOpen} onOpenChange={setIsCurlDialogOpen}>
- <DialogTrigger asChild>
- <Button variant="outline" size="icon">
- <IconCode className="h-4 w-12" />
- </Button>
- </DialogTrigger>
- <DialogContent className="max-w-2xl">
- <DialogHeader>
- <DialogTitle>curl command</DialogTitle>
- <DialogDescription>
- you can use this curl command to make the same search request
- from the command line.
- <br />
- <br />
- <span className="text-xs text-gray-500">
- note: you need to have `jq` installed to use the command.
- </span>{" "}
- </DialogDescription>
- </DialogHeader>
- <div className="overflow-x-auto">
- <CodeBlock language="bash" value={generateCurlCommand()} />
- </div>
- </DialogContent>
- </Dialog>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ {settings.platform === "macos" && (
+ <div className="flex items-center space-x-1">
+ <Checkbox
+ id="ui-type"
+ checked={selectedTypes.ui}
+ onCheckedChange={() => handleContentTypeChange('ui')}
+ className="h-4 w-4"
+ />
+ <Label htmlFor="ui-type" className="text-xs">screen UI</Label>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-3 w-3 text-muted-foreground ml-0.5" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>text emitted directly from the source code of the desktop applications</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ )}
+ <div className="flex items-center space-x-1">
+ <Checkbox
+ id="ocr-type"
+ checked={selectedTypes.ocr}
+ onCheckedChange={() => handleContentTypeChange('ocr')}
+ className="h-4 w-4"
+ />
+ <Label htmlFor="ocr-type" className="text-xs">screen capture</Label>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-3 w-3 text-muted-foreground ml-0.5" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>recognized text from screenshots taken every 5s by default</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
</div>
+
+ <Dialog open={isCurlDialogOpen} onOpenChange={setIsCurlDialogOpen}>
+ <DialogTrigger asChild>
+ <Button variant="outline" className="text-sm">
+ <span className="flex items-center">
+ <IconCode className="h-4 w-4 mr-2" />
+ code
+ </span>
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>curl command</DialogTitle>
+ <DialogDescription>
+ you can use this curl command to make the same search request
+ from the command line.
+ <br />
+ <br />
+ <span className="text-xs text-gray-500">
+ note: you need to have `jq` installed to use the command.
+ </span>{" "}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="overflow-x-auto">
+ <CodeBlock language="bash" value={generateCurlCommand()} />
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+
+ {/* Existing search bar and other controls */}
+ <div className="flex items-center gap-4 mb-4">
+ {/* Keyword search - smaller width */}
+ <Input
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="keyword search, you may leave it blank"
+ className="w-[350px]"
+ />
+
+ {/* Window name filter - increased width */}
+ <SqlAutocompleteInput
+ id="window-name"
+ type="window"
+ value={windowName}
+ onChange={setWindowName}
+ placeholder="filter by window"
+ className="w-[300px]"
+ icon={<Layout className="h-4 w-4" />}
+ />
+
+ {/* Advanced button */}
+ <Button
+ variant="outline"
+ onClick={() => setIsQueryParamsDialogOpen(true)}
+ >
+ advanced
+ </Button>
+
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ onClick={() => handleSearch(0)}
+ disabled={isLoading || !health || health?.status === "error"}
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ searching...
+ </>
+ ) : (
+ <>
+ <Search className="mr-2 h-4 w-4" />
+ search
+ </>
+ )}
+ </Button>
+ </span>
+ </TooltipTrigger>
+ {health?.status === "error" && (
+ <TooltipContent>
+ <p>screenpipe is not running...</p>
+ </TooltipContent>
+ )}
+ </Tooltip>
+ </TooltipProvider>
</div>
<div className="flex flex-wrap items-center gap-4 mb-4">
@@ -1024,36 +1223,15 @@ const AGENTS: Agent[] = [
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
- <div className="grid grid-cols-4 items-center gap-4">
+ {/* Remove the query section */}
+ {/* <div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="query" className="text-right">
query
</Label>
- <div className="col-span-3 flex items-center">
- <Input
- id="query"
- type="text"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- className="flex-grow"
- placeholder="keyword matching audio transcription or screen text"
- />
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />
- </TooltipTrigger>
- <TooltipContent>
- <p>
- enter keywords to search your recorded data, <br />
- for example: &quot;shoes&quot; or &quot;screenpipe&quot;
- or &quot;login&quot;, this will filter out all results
- that don&apos;t contain those keywords.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </div>
+ ... query input ...
+ </div> */}
+
+ {/* Keep other advanced search options */}
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="app-name" className="text-right">
app name
@@ -1136,36 +1314,6 @@ const AGENTS: Agent[] = [
</div>
</div>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="content-type" className="text-right">
- content type
- </Label>
- <div className="col-span-3 flex items-center">
- <Select value={contentType} onValueChange={setContentType}>
- <SelectTrigger id="content-type" className="flex-grow">
- <SelectValue placeholder="content type" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">all</SelectItem>
- <SelectItem value="ocr">ocr</SelectItem>
- <SelectItem value="audio">audio</SelectItem>
- </SelectContent>
- </Select>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />
- </TooltipTrigger>
- <TooltipContent>
- <p>
- select the type of content to search. ocr is the text
- found on your screen.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </div>
<div className="grid grid-cols-4 items-center gap-4">
<Label htmlFor="limit-slider" className="text-right">
page size: {limit}
diff --git a/screenpipe-app-tauri/components/sql-autocomplete-input.tsx b/screenpipe-app-tauri/components/sql-autocomplete-input.tsx
index 0d38561b6..55807bebf 100644
--- a/screenpipe-app-tauri/components/sql-autocomplete-input.tsx
+++ b/screenpipe-app-tauri/components/sql-autocomplete-input.tsx
@@ -11,7 +11,7 @@ interface SqlAutocompleteInputProps {
value: string;
onChange: (value: string) => void;
type: "app" | "window";
- icon: React.ReactNode;
+ icon?: React.ReactNode;
className?: string;
onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
}
@@ -91,7 +91,7 @@ export function SqlAutocompleteInput({
value={inputValue}
onChange={handleInputChange}
onFocus={() => setOpen(true)}
- className="pl-10 pr-8 w-full"
+ className={cn("pr-8 w-full", icon ? "pl-7" : "pl-3")}
autoCorrect="off"
aria-autocomplete="none"
onKeyDown={onKeyDown}
diff --git a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
index e887b6449..725928958 100644
--- a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
@@ -5,8 +5,10 @@ interface HealthCheckResponse {
status_code: number;
last_frame_timestamp: string | null;
last_audio_timestamp: string | null;
+ last_ui_timestamp: string | null;
frame_status: string;
audio_status: string;
+ ui_status: string;
message: string;
}
@@ -20,8 +22,10 @@ function isHealthChanged(
oldHealth.status_code !== newHealth.status_code ||
oldHealth.last_frame_timestamp !== newHealth.last_frame_timestamp ||
oldHealth.last_audio_timestamp !== newHealth.last_audio_timestamp ||
+ oldHealth.last_ui_timestamp !== newHealth.last_ui_timestamp ||
oldHealth.frame_status !== newHealth.frame_status ||
oldHealth.audio_status !== newHealth.audio_status ||
+ oldHealth.ui_status !== newHealth.ui_status ||
oldHealth.message !== newHealth.message
);
}
@@ -53,8 +57,10 @@ export function useHealthCheck() {
const errorHealth: HealthCheckResponse = {
last_frame_timestamp: null,
last_audio_timestamp: null,
+ last_ui_timestamp: null,
frame_status: "error",
audio_status: "error",
+ ui_status: "error",
status: "error",
status_code: 500,
message: "failed to fetch health status. server might be down.",
diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 37bc2ca20..07db5e8ae 100644
--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -56,6 +56,7 @@ export interface Settings {
isFirstTimeUser: boolean;
enableFrameCache: boolean; // Add this line
enableUiMonitoring: boolean; // Add this line
+ platform: string; // Add this line
}
const defaultSettings: Settings = {
@@ -102,7 +103,8 @@ const defaultSettings: Settings = {
showScreenpipeShortcut: "Super+Alt+S",
isFirstTimeUser: true,
enableFrameCache: false, // Add this line
- enableUiMonitoring: false, // Add this line
+ enableUiMonitoring: false, // Change from true to false
+ platform: "unknown", // Add this line
};
let store: Awaited<ReturnType<typeof createStore>> | null = null;
@@ -138,13 +140,17 @@ export function useSettings() {
await initStore();
}
- const ocrModel =
- platform() === "macos"
- ? "apple-native"
- : platform() === "windows"
- ? "windows-native"
- : "tesseract";
try {
+ const currentPlatform = await platform();
+ console.log("Current platform:", currentPlatform);
+
+ const ocrModel =
+ currentPlatform === "darwin"
+ ? "apple-native"
+ : currentPlatform === "win32"
+ ? "windows-native"
+ : "tesseract";
+
console.log("loading settings", store);
// no need to call load() as it's done automatically
const savedKey = (await store!.get<string>("openaiApiKey")) || "";
@@ -193,7 +199,7 @@ export function useSettings() {
(await store!.get<number>("aiMaxContextChars")) || 30000;
const savedFps =
(await store!.get<number>("fps")) ||
- (platform() === "macos" ? 0.2 : 1);
+ (currentPlatform === "darwin" ? 0.2 : 1);
const savedVadSensitivity =
(await store!.get<VadSensitivity>("vadSensitivity")) || "high";
let savedAnalyticsEnabled = await store!.get<boolean>(
@@ -222,7 +228,6 @@ export function useSettings() {
const savedLanguages =
(await store!.get<Language[]>("languages")) || [];
- const currentPlatform = platform();
const ignoredWindowsInAllOS = [
"bit",
"VPN",
@@ -237,7 +242,7 @@ export function useSettings() {
"OBS Studio",
];
const defaultIgnoredWindows =
- currentPlatform === "macos"
+ currentPlatform === "darwin"
? [
...ignoredWindowsInAllOS,
".env",
@@ -251,7 +256,7 @@ export function useSettings() {
"Dock",
"DeepL",
]
- : currentPlatform === "windows"
+ : currentPlatform === "win32"
? [
...ignoredWindowsInAllOS,
"Nvidia",
@@ -323,6 +328,7 @@ export function useSettings() {
isFirstTimeUser: savedIsFirstTimeUser,
enableFrameCache: savedEnableFrameCache,
enableUiMonitoring: false,
+ platform: currentPlatform,
});
} catch (error) {
console.error("failed to load settings:", error);
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 442401689..053e3c991 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -3783,9 +3783,11 @@ dependencies = [
"axum",
"base64 0.22.1",
"cocoa 0.26.0",
+ "core-foundation 0.9.4",
"dirs 5.0.1",
"fix-path-env",
"http 0.2.12",
+ "libc",
"log",
"objc",
"reqwest",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index cd0043fc2..899b37183 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -86,7 +86,9 @@ tauri-plugin-global-shortcut = "2"
tauri-plugin-single-instance = "2.0.0"
tauri-plugin-updater = "2.0.0"
-[target."cfg(target_os = \"macos\")".dependencies]
+[target.'cfg(target_os = "macos")'.dependencies]
+core-foundation = "0.9.4"
+libc = "0.2.152"
cocoa = "0.26.0"
objc = "0.2.7"
base64 = "0.22.1"
diff --git a/screenpipe-app-tauri/src-tauri/Info.plist b/screenpipe-app-tauri/src-tauri/Info.plist
index 6aabf5152..c1714a03d 100644
--- a/screenpipe-app-tauri/src-tauri/Info.plist
+++ b/screenpipe-app-tauri/src-tauri/Info.plist
@@ -12,5 +12,7 @@
<string>This app requires camera access to capture video.</string>
<key>NSSystemExtensionUsageDescription</key>
<string>This app requires system extension access to capture audio output.</string>
+ <key>NSAccessibilityUsageDescription</key>
+ <string>Screenpipe needs accessibility permissions to monitor UI elements and their interactions.</string>
</dict>
</plist>
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rs
index 0f277cafd..974d4baae 100644
--- a/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -4,6 +4,14 @@ use serde_json::Value;
use tauri::Manager;
use tracing::info;
+#[cfg(target_os = "macos")]
+use core_foundation::{
+ base::TCFType,
+ boolean::CFBoolean,
+ string::CFString,
+};
+
+
#[tauri::command]
pub fn open_screen_capture_preferences() {
#[cfg(target_os = "macos")]
@@ -186,3 +194,38 @@ pub fn update_show_screenpipe_shortcut(
Ok(())
}
+
+#[tauri::command]
+pub fn open_accessibility_preferences() {
+ #[cfg(target_os = "macos")]
+ std::process::Command::new("open")
+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
+ .spawn()
+ .expect("failed to open system preferences");
+}
+
+#[tauri::command]
+pub fn check_accessibility_permissions() -> bool {
+ #[cfg(target_os = "macos")]
+ {
+ // Check if the app has accessibility permissions
+ let options = unsafe {
+ let key = CFString::new("AXTrustedCheckOptionPrompt");
+ let value = CFBoolean::false_value();
+ let pairs = &[(key, value)];
+ core_foundation::dictionary::CFDictionary::from_CFType_pairs(pairs)
+ };
+
+ let trusted = unsafe {
+ let accessibility = CFString::new("AXIsProcessTrustedWithOptions");
+ let func: extern "C" fn(*const core_foundation::dictionary::CFDictionary) -> bool =
+ std::mem::transmute(libc::dlsym(
+ libc::RTLD_DEFAULT,
+ accessibility.to_string().as_ptr() as *const _,
+ ));
+ func(options.as_concrete_TypeRef() as *const _)
+ };
+
+ trusted
+ }
+}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index 79721f431..5216d57bf 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -48,6 +48,8 @@ pub use commands::reset_all_pipes;
pub use server::spawn_server;
pub use sidecar::kill_all_sreenpipes;
pub use sidecar::spawn_screenpipe;
+pub use commands::open_accessibility_preferences;
+pub use commands::check_accessibility_permissions;
pub struct SidecarState(Arc<tokio::sync::Mutex<Option<SidecarManager>>>);
@@ -115,6 +117,8 @@ async fn main() {
llm_sidecar::stop_ollama_sidecar,
commands::update_show_screenpipe_shortcut,
commands::show_timeline,
+ commands::open_accessibility_preferences,
+ commands::check_accessibility_permissions,
icons::get_app_icon
])
.setup(|app| {
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 75b8737e9..c819fca90 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -15,7 +15,9 @@ use screenpipe_core::find_ffmpeg_path;
use screenpipe_server::{
cli::{Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, PipeCommand}, start_continuous_recording, watch_pid, DatabaseManager, PipeControl, PipeManager, ResourceMonitor, Server, highlight::{Highlight,HighlightConfig}
};
-use screenpipe_vision::monitor::list_monitors;
+use screenpipe_vision::{monitor::list_monitors};
+#[cfg(target_os = "macos")]
+use screenpipe_vision::run_ui;
use serde_json::{json, Value};
use tokio::{runtime::Runtime, signal, sync::broadcast};
use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
@@ -419,6 +421,7 @@ async fn main() -> anyhow::Result<()> {
pipe_manager.clone(),
cli.disable_vision,
cli.disable_audio,
+ cli.enable_ui_monitoring,
);
let pipe_futures = Arc::new(tokio::sync::Mutex::new(FuturesUnordered::new()));
@@ -610,6 +613,8 @@ async fn main() -> anyhow::Result<()> {
}
}
+ println!("├─────────────────────┼────────────────────────────────────┤");
+ println!("│ ui monitoring │ {:<34} │", cli.enable_ui_monitoring);
println!("└─────────────────────┴────────────────────────────────────┘");
// Add warning for cloud arguments and telemetry
@@ -719,24 +724,31 @@ async fn main() -> anyhow::Result<()> {
}
// Start the UI monitoring task
- if cfg!(target_os = "macos") {
- use screenpipe_vision::run_ui;
-
- if cli.enable_ui_monitoring {
- let shutdown_tx_clone = shutdown_tx.clone();
- tokio::spawn(async move {
- let mut shutdown_rx = shutdown_tx_clone.subscribe();
-
+ #[cfg(target_os = "macos")]
+ if cli.enable_ui_monitoring {
+ let shutdown_tx_clone = shutdown_tx.clone();
+ tokio::spawn(async move {
+ let mut shutdown_rx = shutdown_tx_clone.subscribe();
+
+ loop {
tokio::select! {
- _ = run_ui() => {
- error!("ui monitoring stopped unexpectedly");
+ result = run_ui() => {
+ match result {
+ Ok(_) => break,
+ Err(e) => {
+ error!("ui monitoring error: {}", e);
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ continue;
+ }
+ }
}
_ = shutdown_rx.recv() => {
info!("received shutdown signal, stopping ui monitoring");
+ break;
}
}
- });
- }
+ }
+ });
}
let pipe_control_future = async {
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index df6b4a923..a7f0267c7 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -69,6 +69,7 @@ pub enum SearchResult {
OCR(OCRResult),
Audio(AudioResult),
FTS(FTSSearchResult),
+ UI(UiContent),
}
// Intermediate struct for fetching data
@@ -100,13 +101,23 @@ pub struct OCRResult {
pub tags: Vec<String>,
}
-#[derive(Debug, Deserialize, PartialEq, Default, Clone, Copy)]
+#[derive(Debug, Deserialize, PartialEq, Default, Clone)]
#[serde(rename_all = "lowercase")]
pub enum ContentType {
#[default]
All,
- OCR, // TODO replace by vision and make this deprecated
+ OCR,
Audio,
+ UI,
+ #[serde(rename = "audio+ui")]
+ #[serde(alias = "audio ui")]
+ AudioAndUi,
+ #[serde(rename = "ocr+ui")]
+ #[serde(alias = "ocr ui")]
+ OcrAndUi,
+ #[serde(rename = "audio+ocr")]
+ #[serde(alias = "audio ocr")]
+ AudioAndOcr,
}
#[derive(FromRow)]
@@ -146,6 +157,22 @@ pub struct DatabaseManager {
pub pool: SqlitePool,
}
+// Add this before the DatabaseManager impl block
+#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
+pub struct UiContent {
+ pub id: i64,
+ #[sqlx(rename = "text_output")]
+ pub text: String,
+ pub timestamp: DateTime<Utc>,
+ #[sqlx(rename = "app")]
+ pub app_name: String,
+ #[sqlx(rename = "window")]
+ pub window_name: String,
+ pub initial_traversal_at: Option<DateTime<Utc>>,
+ pub file_path: String,
+ pub offset_index: i64,
+}
+
impl DatabaseManager {
pub async fn new(database_path: &str) -> Result<Self, sqlx::Error> {
debug!(
@@ -459,34 +486,70 @@ impl DatabaseManager {
) -> Result<Vec<SearchResult>, sqlx::Error> {
let mut results = Vec::new();
- if content_type == ContentType::All || content_type == ContentType::OCR {
- let ocr_results = self
- .search_ocr(
- query,
- limit,
- offset,
- start_time,
- end_time,
- app_name,
- window_name,
- min_length,
- max_length,
- )
- .await?;
- results.extend(ocr_results.into_iter().map(SearchResult::OCR));
+ match content_type {
+ ContentType::All => {
+ let ocr_results = self.search_ocr(query, limit, offset, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+ let audio_results = self.search_audio(query, limit, offset, start_time, end_time, min_length, max_length).await?;
+ let ui_results = self.search_ui_monitoring(query, app_name, window_name, start_time, end_time, limit, offset).await?;
+
+ results.extend(ocr_results.into_iter().map(SearchResult::OCR));
+ results.extend(audio_results.into_iter().map(SearchResult::Audio));
+ results.extend(ui_results.into_iter().map(SearchResult::UI));
+ },
+ ContentType::OCR => {
+ let ocr_results = self.search_ocr(query, limit, offset, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+ results.extend(ocr_results.into_iter().map(SearchResult::OCR));
+ },
+ ContentType::Audio => {
+ let audio_results = self.search_audio(query, limit, offset, start_time, end_time, min_length, max_length).await?;
+ results.extend(audio_results.into_iter().map(SearchResult::Audio));
+ },
+ ContentType::UI => {
+ let ui_results = self.search_ui_monitoring(query, app_name, window_name, start_time, end_time, limit, offset).await?;
+ results.extend(ui_results.into_iter().map(SearchResult::UI));
+ },
+ ContentType::AudioAndUi => {
+ let audio_results = self.search_audio(query, limit/2, offset, start_time, end_time, min_length, max_length).await?;
+ let ui_results = self.search_ui_monitoring(query, app_name, window_name, start_time, end_time, limit/2, offset).await?;
+
+ results.extend(audio_results.into_iter().map(SearchResult::Audio));
+ results.extend(ui_results.into_iter().map(SearchResult::UI));
+ },
+ ContentType::OcrAndUi => {
+ let ocr_results = self.search_ocr(query, limit/2, offset, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+ let ui_results = self.search_ui_monitoring(query, app_name, window_name, start_time, end_time, limit/2, offset).await?;
+
+ results.extend(ocr_results.into_iter().map(SearchResult::OCR));
+ results.extend(ui_results.into_iter().map(SearchResult::UI));
+ },
+ ContentType::AudioAndOcr => {
+ let audio_results = self.search_audio(query, limit/2, offset, start_time, end_time, min_length, max_length).await?;
+ let ocr_results = self.search_ocr(query, limit/2, offset, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+
+ results.extend(audio_results.into_iter().map(SearchResult::Audio));
+ results.extend(ocr_results.into_iter().map(SearchResult::OCR));
+ },
}
- if (content_type == ContentType::All || content_type == ContentType::Audio)
- && app_name.is_none()
- && window_name.is_none()
- {
- let audio_results = self
- .search_audio(
- query, limit, offset, start_time, end_time, min_length, max_length,
- )
- .await?;
- results.extend(audio_results.into_iter().map(SearchResult::Audio));
- }
+ // Sort results by timestamp in descending order
+ results.sort_by(|a, b| {
+ let timestamp_a = match a {
+ SearchResult::OCR(ocr) => ocr.timestamp,
+ SearchResult::Audio(audio) => audio.timestamp,
+ SearchResult::UI(ui) => ui.timestamp,
+ SearchResult::FTS(fts) => fts.frame_timestamp,
+ };
+ let timestamp_b = match b {
+ SearchResult::OCR(ocr) => ocr.timestamp,
+ SearchResult::Audio(audio) => audio.timestamp,
+ SearchResult::UI(ui) => ui.timestamp,
+ SearchResult::FTS(fts) => fts.frame_timestamp,
+ };
+ timestamp_b.cmp(&timestamp_a)
+ });
+
+ // Apply offset and limit after sorting
+ results = results.into_iter().skip(offset as usize).take(limit as usize).collect();
Ok(results)
}
@@ -702,42 +765,38 @@ impl DatabaseManager {
min_length: Option<usize>,
max_length: Option<usize>,
) -> Result<usize, sqlx::Error> {
- let mut total_count = 0;
-
- // If app_name or window_name is specified, only count OCR results
- if app_name.is_some() || window_name.is_some() {
- let ocr_count = self
- .count_ocr_results(
- query,
- start_time,
- end_time,
- app_name,
- window_name,
- min_length,
- max_length,
- )
- .await?;
- total_count += ocr_count;
- } else {
- // If no app_name or window_name is specified, proceed with normal counting
- if content_type == ContentType::All || content_type == ContentType::OCR {
- let ocr_count = self
- .count_ocr_results(
- query, start_time, end_time, None, None, min_length, max_length,
- )
- .await?;
- total_count += ocr_count;
- }
+ let mut total = 0;
- if content_type == ContentType::All || content_type == ContentType::Audio {
- let audio_count = self
- .count_audio_results(query, start_time, end_time, min_length, max_length)
- .await?;
- total_count += audio_count;
- }
+ match content_type {
+ ContentType::All => {
+ total += self.count_ocr_results(query, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+ total += self.count_audio_results(query, start_time, end_time, min_length, max_length).await?;
+ total += self.count_ui_results(query, app_name, window_name, start_time, end_time).await?;
+ },
+ ContentType::OCR => {
+ total += self.count_ocr_results(query, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+ },
+ ContentType::Audio => {
+ total += self.count_audio_results(query, start_time, end_time, min_length, max_length).await?;
+ },
+ ContentType::UI => {
+ total += self.count_ui_results(query, app_name, window_name, start_time, end_time).await?;
+ },
+ ContentType::AudioAndUi => {
+ total += self.count_audio_results(query, start_time, end_time, min_length, max_length).await?;
+ total += self.count_ui_results(query, app_name, window_name, start_time, end_time).await?;
+ },
+ ContentType::OcrAndUi => {
+ total += self.count_ocr_results(query, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+ total += self.count_ui_results(query, app_name, window_name, start_time, end_time).await?;
+ },
+ ContentType::AudioAndOcr => {
+ total += self.count_audio_results(query, start_time, end_time, min_length, max_length).await?;
+ total += self.count_ocr_results(query, start_time, end_time, app_name, window_name, min_length, max_length).await?;
+ },
}
- Ok(total_count)
+ Ok(total)
}
async fn count_ocr_results(
@@ -778,6 +837,7 @@ impl DatabaseManager {
let (count,) = query.fetch_one(&self.pool).await?;
Ok(count as usize)
}
+
async fn count_audio_results(
&self,
query: &str,
@@ -808,9 +868,41 @@ impl DatabaseManager {
let (count,) = query.fetch_one(&self.pool).await?;
Ok(count as usize)
}
+
+ async fn count_ui_results(
+ &self,
+ query: &str,
+ app_name: Option<&str>,
+ window_name: Option<&str>,
+ start_time: Option<DateTime<Utc>>,
+ end_time: Option<DateTime<Utc>>,
+ ) -> Result<usize, sqlx::Error> {
+ let sql = r#"
+ SELECT COUNT(DISTINCT ui_monitoring.id)
+ FROM ui_monitoring
+ WHERE
+ (?1 = '' OR text_output LIKE '%' || ?1 || '%')
+ AND (?2 IS NULL OR app LIKE '%' || ?2 || '%')
+ AND (?3 IS NULL OR window LIKE '%' || ?3 || '%')
+ AND (?4 IS NULL OR timestamp >= ?4)
+ AND (?5 IS NULL OR timestamp <= ?5)
+ "#;
+
+ let (count,) = sqlx::query_as::<_, (i64,)>(sql)
+ .bind(query)
+ .bind(app_name)
+ .bind(window_name)
+ .bind(start_time)
+ .bind(end_time)
+ .fetch_one(&self.pool)
+ .await?;
+
+ Ok(count as usize)
+ }
+
pub async fn get_latest_timestamps(
&self,
- ) -> Result<(Option<DateTime<Utc>>, Option<DateTime<Utc>>), sqlx::Error> {
+ ) -> Result<(Option<DateTime<Utc>>, Option<DateTime<Utc>>, Option<DateTime<Utc>>), sqlx::Error> {
let latest_frame: Option<(DateTime<Utc>,)> =
sqlx::query_as("SELECT timestamp FROM frames ORDER BY timestamp DESC LIMIT 1")
.fetch_optional(&self.pool)
@@ -821,7 +913,29 @@ impl DatabaseManager {
.fetch_optional(&self.pool)
.await?;
- Ok((latest_frame.map(|f| f.0), latest_audio.map(|a| a.0)))
+ // Check if ui_monitoring table exists first
+ let latest_ui: Option<(DateTime<Utc>,)> = match sqlx::query_scalar::<_, i32>(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='ui_monitoring'"
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ {
+ Some(_) => {
+ sqlx::query_as("SELECT timestamp FROM ui_monitoring ORDER BY timestamp DESC LIMIT 1")
+ .fetch_optional(&self.pool)
+ .await?
+ }
+ None => {
+ debug!("ui_monitoring table does not exist");
+ None
+ }
+ };
+
+ Ok((
+ latest_frame.map(|f| f.0),
+ latest_audio.map(|a| a.0),
+ latest_ui.map(|u| u.0),
+ ))
}
pub async fn get_chunked_data_since_last_request(
@@ -1256,6 +1370,97 @@ impl DatabaseManager {
end_time: end,
})
}
+
+ pub async fn search_ui_monitoring(
+ &self,
+ query: &str,
+ app_name: Option<&str>,
+ window_name: Option<&str>,
+ start_time: Option<DateTime<Utc>>,
+ end_time: Option<DateTime<Utc>>,
+ limit: u32,
+ offset: u32,
+ ) -> Result<Vec<UiContent>, sqlx::Error> {
+ let sql = r#"
+ WITH matching_frames AS (
+ SELECT
+ frames.id as frame_id,
+ frames.video_chunk_id,
+ frames.offset_index,
+ frames.timestamp as frame_timestamp,
+ ui_monitoring.id as ui_id,
+ ui_monitoring.text_output,
+ ui_monitoring.timestamp as ui_timestamp,
+ ui_monitoring.app,
+ ui_monitoring.window,
+ ui_monitoring.initial_traversal_at,
+ ABS(STRFTIME('%s', frames.timestamp) - STRFTIME('%s', ui_monitoring.timestamp)) as diff_seconds
+ FROM ui_monitoring
+ JOIN frames ON
+ ABS(STRFTIME('%s', frames.timestamp) - STRFTIME('%s', ui_monitoring.timestamp)) <= 1
+ WHERE
+ (?1 = '' OR ui_monitoring.text_output LIKE '%' || ?1 || '%')
+ AND (?2 IS NULL OR ui_monitoring.app LIKE '%' || ?2 || '%')
+ AND (?3 IS NULL OR ui_monitoring.window LIKE '%' || ?3 || '%')
+ AND (?4 IS NULL OR ui_monitoring.timestamp >= ?4)
+ AND (?5 IS NULL OR ui_monitoring.timestamp <= ?5)
+ ORDER BY ui_monitoring.timestamp DESC
+ LIMIT ?6 OFFSET ?7
+ )
+ SELECT
+ ui_id as id,
+ text_output,
+ ui_timestamp as timestamp,
+ app,
+ window,
+ initial_traversal_at,
+ video_chunks.file_path,
+ offset_index,
+ diff_seconds
+ FROM matching_frames
+ JOIN video_chunks ON matching_frames.video_chunk_id = video_chunks.id
+ ORDER BY ui_timestamp DESC
+ "#;
+
+ let query = sqlx::query_as::<_, UiContent>(sql)
+ .bind(query)
+ .bind(app_name)
+ .bind(window_name)
+ .bind(start_time)
+ .bind(end_time)
+ .bind(limit)
+ .bind(offset);
+
+ query.fetch_all(&self.pool).await
+ }
+
+ // Add tags to UI monitoring entry
+ pub async fn add_tags_to_ui_monitoring(&self, ui_monitoring_id: i64, tag_ids: &[i64]) -> Result<(), anyhow::Error> {
+ for tag_id in tag_ids {
+ sqlx::query(
+ "INSERT OR IGNORE INTO ui_monitoring_tags (ui_monitoring_id, tag_id) VALUES (?, ?)"
+ )
+ .bind(ui_monitoring_id)
+ .bind(tag_id)
+ .execute(&self.pool)
+ .await?;
+ }
+ Ok(())
+ }
+
+ // Get tags for UI monitoring entry
+ pub async fn get_ui_monitoring_tags(&self, ui_monitoring_id: i64) -> Result<Vec<String>, anyhow::Error> {
+ let tags = sqlx::query_as::<_, (String,)>(
+ "SELECT t.name FROM tags t
+ JOIN ui_monitoring_tags ut ON t.id = ut.tag_id
+ WHERE ut.ui_monitoring_id = ?"
+ )
+ .bind(ui_monitoring_id)
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(tags.into_iter().map(|t| t.0).collect())
+ }
}
#[derive(Debug, Clone)]
diff --git a/screenpipe-server/src/migrations/20241106031800_create_ui_monitoring.sql b/screenpipe-server/src/migrations/20241106031800_create_ui_monitoring.sql
new file mode 100644
index 000000000..ebf447fac
--- /dev/null
+++ b/screenpipe-server/src/migrations/20241106031800_create_ui_monitoring.sql
@@ -0,0 +1,27 @@
+CREATE TABLE IF NOT EXISTS ui_monitoring (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ text_output TEXT NOT NULL,
+ timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ app TEXT NOT NULL,
+ window TEXT NOT NULL,
+ initial_traversal_at DATETIME
+);
+
+-- Add indexes for better query performance
+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_timestamp ON ui_monitoring(timestamp);
+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_app ON ui_monitoring(app);
+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_window ON ui_monitoring(window);
+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_text_output ON ui_monitoring(text_output);
+
+-- Create junction table for UI monitoring and tags
+CREATE TABLE IF NOT EXISTS ui_monitoring_tags (
+ ui_monitoring_id INTEGER NOT NULL,
+ tag_id INTEGER NOT NULL,
+ PRIMARY KEY (ui_monitoring_id, tag_id),
+ FOREIGN KEY (ui_monitoring_id) REFERENCES ui_monitoring(id) ON DELETE CASCADE,
+ FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
+);
+
+-- Create indexes for the junction table with IF NOT EXISTS
+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_tags_ui_id ON ui_monitoring_tags(ui_monitoring_id);
+CREATE INDEX IF NOT EXISTS idx_ui_monitoring_tags_tag_id ON ui_monitoring_tags(tag_id);
\ No newline at end of file
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 9e1706b7e..fe3ecec03 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -59,6 +59,7 @@ pub struct AppState {
pub pipe_manager: Arc<PipeManager>,
pub vision_disabled: bool,
pub audio_disabled: bool,
+ pub ui_monitoring_enabled: bool,
pub frame_cache: Option<Arc<FrameCache>>,
}
@@ -124,6 +125,7 @@ pub enum ContentItem {
OCR(OCRContent),
Audio(AudioContent),
FTS(FTSContent),
+ UI(UiContent),
}
#[derive(Serialize, Deserialize, Debug)]
@@ -164,6 +166,18 @@ pub struct FTSContent {
pub tags: Vec<String>,
}
+#[derive(Serialize, Deserialize, Debug)]
+pub struct UiContent {
+ pub id: i64,
+ pub text: String,
+ pub timestamp: DateTime<Utc>,
+ pub app_name: String,
+ pub window_name: String,
+ pub initial_traversal_at: Option<DateTime<Utc>>,
+ pub file_path: String,
+ pub offset_index: i64,
+}
+
#[derive(Serialize)]
pub(crate) struct ListDeviceResponse {
name: String,
@@ -209,8 +223,10 @@ pub struct HealthCheckResponse {
pub status: String,
pub last_frame_timestamp: Option<DateTime<Utc>>,
pub last_audio_timestamp: Option<DateTime<Utc>>,
+ pub last_ui_timestamp: Option<DateTime<Utc>>,
pub frame_status: String,
pub audio_status: String,
+ pub ui_status: String,
pub message: String,
pub verbose_instructions: Option<String>,
}
@@ -243,13 +259,13 @@ pub(crate) async fn search(
let content_type = if query.app_name.is_some() || query.window_name.is_some() {
ContentType::OCR
} else {
- query.content_type
+ query.content_type.clone()
};
let (results, total) = try_join(
state.db.search(
query_str,
- content_type,
+ content_type.clone(),
query.pagination.limit,
query.pagination.offset,
query.start_time,
@@ -314,6 +330,16 @@ pub(crate) async fn search(
original_frame_text: fts.original_frame_text.clone(),
tags: fts.tags.clone(),
}),
+ SearchResult::UI(ui) => ContentItem::UI(UiContent {
+ id: ui.id,
+ text: ui.text.clone(),
+ timestamp: ui.timestamp,
+ app_name: ui.app_name.clone(),
+ window_name: ui.window_name.clone(),
+ initial_traversal_at: ui.initial_traversal_at,
+ file_path: ui.file_path.clone(),
+ offset_index: ui.offset_index,
+ }),
})
.collect();
@@ -479,11 +505,11 @@ pub(crate) async fn remove_tags(
}
pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<HealthCheckResponse> {
- let (last_frame, last_audio) = match state.db.get_latest_timestamps().await {
- Ok((frame, audio)) => (frame, audio),
+ let (last_frame, last_audio, last_ui) = match state.db.get_latest_timestamps().await {
+ Ok((frame, audio, ui)) => (frame, audio, ui),
Err(e) => {
error!("failed to get latest timestamps: {}", e);
- (None, None)
+ (None, None, None)
}
};
@@ -525,9 +551,19 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
}
};
- let (overall_status, message, verbose_instructions) = if (frame_status == "ok"
- || frame_status == "disabled")
+ let ui_status = if !state.ui_monitoring_enabled {
+ "disabled"
+ } else {
+ match last_ui {
+ Some(timestamp) if now.signed_duration_since(timestamp) < chrono::Duration::from_std(threshold).unwrap() => "ok",
+ Some(_) => "stale",
+ None => "no data"
+ }
+ };
+
+ let (overall_status, message, verbose_instructions) = if (frame_status == "ok" || frame_status == "disabled")
&& (audio_status == "ok" || audio_status == "disabled")
+ && (ui_status == "ok" || ui_status == "disabled")
{
(
"healthy",
@@ -542,11 +578,14 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
if audio_status != "ok" && audio_status != "disabled" {
unhealthy_systems.push("audio");
}
+ if ui_status != "ok" && ui_status != "disabled" {
+ unhealthy_systems.push("ui monitoring");
+ }
(
"unhealthy",
- format!("some systems are not functioning properly: {}. frame status: {}, audio status: {}",
- unhealthy_systems.join(", "), frame_status, audio_status),
+ format!("some systems are not functioning properly: {}. frame status: {}, audio status: {}, ui status: {}",
+ unhealthy_systems.join(", "), frame_status, audio_status, ui_status),
Some("if you're experiencing issues, please try the following steps:\n\
1. restart the application.\n\
2. if using a desktop app, reset your screenpipe os audio/screen recording permissions.\n\
@@ -559,8 +598,10 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
status: overall_status.to_string(),
last_frame_timestamp: last_frame,
last_audio_timestamp: last_audio,
+ last_ui_timestamp: last_ui,
frame_status: frame_status.to_string(),
audio_status: audio_status.to_string(),
+ ui_status: ui_status.to_string(),
message,
verbose_instructions,
})
@@ -706,6 +747,7 @@ pub struct Server {
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
audio_disabled: bool,
+ ui_monitoring_enabled: bool,
}
impl Server {
@@ -719,6 +761,7 @@ impl Server {
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
audio_disabled: bool,
+ ui_monitoring_enabled: bool,
) -> Self {
Server {
db,
@@ -729,6 +772,7 @@ impl Server {
pipe_manager,
vision_disabled,
audio_disabled,
+ ui_monitoring_enabled,
}
}
@@ -751,6 +795,7 @@ impl Server {
pipe_manager: self.pipe_manager,
vision_disabled: self.vision_disabled,
audio_disabled: self.audio_disabled,
+ ui_monitoring_enabled: self.ui_monitoring_enabled,
frame_cache: if enable_frame_cache {
Some(Arc::new(
FrameCache::new(self.screenpipe_dir.clone().join("data"), self.db.clone())
@@ -1398,8 +1443,6 @@ curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&include_fra
curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq
-curl "http://localhost:3030/search?limit=1&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq
-
curl "http://localhost:3030/search?limit=1&offset=0&content_type=all&include_frames=true&start_time=$(date -u -v-30M +%Y-%m-%dT%H:%M:%SZ)&end_time=$(date -u -v-25M +%Y-%m-%dT%H:%M:%SZ)" | jq -r '.data[0].content.frame' | base64 --decode > /tmp/frame.png && open /tmp/frame.png
# Search for content from the last 30 minutes
diff --git a/screenpipe-vision/src/run_ui_monitoring_macos.rs b/screenpipe-vision/src/run_ui_monitoring_macos.rs
index f121c5e08..d4daf8957 100644
--- a/screenpipe-vision/src/run_ui_monitoring_macos.rs
+++ b/screenpipe-vision/src/run_ui_monitoring_macos.rs
@@ -57,6 +57,7 @@ var currentObserver: AXObserver? {
}
var monitoringEventLoop: CFRunLoop?
var hasChanges = false
+var windowsNeedingTimestampUpdate = Set<WindowIdentifier>()
// Debounce mechanism variables
var pendingNotifications = [(startElement: AXUIElement, depth: Int)]()
var debounceTimer: DispatchSourceTimer?
@@ -241,7 +242,7 @@ func setupDatabase() {
screenPipeDb = try ScreenPipeDB()
print("database connected successfully")
- // Create table if not exists
+ // Create table if not exists (original schema)
let createTableSQL = """
CREATE TABLE IF NOT EXISTS ui_monitoring (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -257,9 +258,46 @@ func setupDatabase() {
if sqlite3_exec(screenPipeDb?.db, createTableSQL, nil, nil, nil) != SQLITE_OK {
let error = String(cString: sqlite3_errmsg(screenPipeDb?.db))
print("error creating table: \(error)")
- } else {
- print("database tables created successfully")
+ return
+ }
+
+ // Add initial_traversal_at column if it doesn't exist
+ let addColumnSQL = """
+ SELECT COUNT(*) FROM pragma_table_info('ui_monitoring')
+ WHERE name='initial_traversal_at';
+ """
+
+ var stmt: OpaquePointer?
+ var columnExists = false
+
+ if sqlite3_prepare_v2(screenPipeDb?.db, addColumnSQL, -1, &stmt, nil) == SQLITE_OK {
+ if sqlite3_step(stmt) == SQLITE_ROW {
+ columnExists = sqlite3_column_int(stmt, 0) > 0
+ }
}
+ sqlite3_finalize(stmt)
+
+ if !columnExists {
+ print("adding initial_traversal_at column...")
+ let alterTableSQL = """
+ ALTER TABLE ui_monitoring
+ ADD COLUMN initial_traversal_at TEXT;
+
+ -- Set initial_traversal_at to timestamp for existing records
+ UPDATE ui_monitoring
+ SET initial_traversal_at = timestamp
+ WHERE initial_traversal_at IS NULL;
+ """
+
+ if sqlite3_exec(screenPipeDb?.db, alterTableSQL, nil, nil, nil) != SQLITE_OK {
+ let error = String(cString: sqlite3_errmsg(screenPipeDb?.db))
+ print("error adding column: \(error)")
+ } else {
+ print("added initial_traversal_at column successfully")
+ }
+ }
+
+ print("database setup completed")
} catch {
print("error setting up database: \(error)")
exit(1)
@@ -765,6 +803,9 @@ func processPendingNotifications() {
let startElement = selectedNotification.startElement
var visitedElements = Set<AXUIElementWrapper>()
+ // Always add to timestamp update set
+ windowsNeedingTimestampUpdate.insert(WindowIdentifier(app: context.appName, window: context.windowName))
+
if updateElementAndChildren(startElement, appName: context.appName, windowName: context.windowName, visitedElements: &visitedElements) {
hasChanges = true
changedWindows.insert(WindowIdentifier(app: context.appName, window: context.windowName))
@@ -1002,7 +1043,7 @@ func buildTextOutput(from windowState: WindowState) -> String {
// Then process any orphaned elements
let orphanElements = windowState.elements.filter { !processedElements.contains($0.key) }
if !orphanElements.isEmpty {
- textOutput += "\n--- ACCESSIBILITY_NOTIFICATIONS_PROCESSING ---\n"
+ textOutput += "\n---\n"
// Sort orphans by timestamp first (oldest first), then position if timestamps are equal
let sortedOrphans = orphanElements.values.sorted { (e1, e2) -> Bool in
@@ -1053,8 +1094,9 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
.components(separatedBy: CharacterSet.controlCharacters).joined()
.trimmingCharacters(in: .whitespacesAndNewlines)
- // First, get existing text_output
+ // First, get existing text_output and check if record exists
var existingText = ""
+ var recordExists = false
let selectSQL = "SELECT text_output FROM ui_monitoring WHERE app = ? AND window = ?;"
var selectStmt: OpaquePointer?
@@ -1063,6 +1105,7 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
sqlite3_bind_text(selectStmt, 2, sanitizedWindow, -1, SQLITE_TRANSIENT)
if sqlite3_step(selectStmt) == SQLITE_ROW {
+ recordExists = true
if let text = sqlite3_column_text(selectStmt, 0) {
existingText = String(cString: text)
}
@@ -1108,7 +1151,20 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
// Skip if no unique lines or extensions found
if uniqueNewLines.isEmpty && extensionsFound == 0 {
- print("no new lines or extensions (found \(exactMatchesFound) exact matches)")
+ // Update timestamp only
+ let updateSQL = "UPDATE ui_monitoring SET timestamp = ? WHERE app = ? AND window = ?;"
+ var updateStmt: OpaquePointer?
+ if sqlite3_prepare_v2(db, updateSQL, -1, &updateStmt, nil) == SQLITE_OK {
+ sqlite3_bind_text(updateStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 2, sanitizedApp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 3, sanitizedWindow, -1, SQLITE_TRANSIENT)
+
+ if sqlite3_step(updateStmt) != SQLITE_DONE {
+ print("error updating timestamp")
+ }
+ sqlite3_finalize(updateStmt)
+ }
+ print("no new content, updated timestamp only")
return
}
@@ -1132,28 +1188,46 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
let finalText = allLines[startIndex...].joined(separator: "\n")
- // Update database
- let upsertSQL = """
- INSERT INTO ui_monitoring (
- timestamp, app, window, text_output
- ) VALUES (?, ?, ?, ?)
- ON CONFLICT(app, window) DO UPDATE SET
- timestamp = excluded.timestamp,
- text_output = excluded.text_output;
- """
-
- var upsertStmt: OpaquePointer?
- if sqlite3_prepare_v2(db, upsertSQL, -1, &upsertStmt, nil) == SQLITE_OK {
- sqlite3_bind_text(upsertStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
- sqlite3_bind_text(upsertStmt, 2, sanitizedApp, -1, SQLITE_TRANSIENT)
- sqlite3_bind_text(upsertStmt, 3, sanitizedWindow, -1, SQLITE_TRANSIENT)
- sqlite3_bind_text(upsertStmt, 4, finalText, -1, SQLITE_TRANSIENT)
+ // Update database with different SQL based on whether record exists
+ if recordExists {
+ let updateSQL = """
+ UPDATE ui_monitoring
+ SET timestamp = ?, text_output = ?
+ WHERE app = ? AND window = ?;
+ """
- if sqlite3_step(upsertStmt) != SQLITE_DONE {
- print("error updating row")
+ var updateStmt: OpaquePointer?
+ if sqlite3_prepare_v2(db, updateSQL, -1, &updateStmt, nil) == SQLITE_OK {
+ sqlite3_bind_text(updateStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 2, finalText, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 3, sanitizedApp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 4, sanitizedWindow, -1, SQLITE_TRANSIENT)
+
+ if sqlite3_step(updateStmt) != SQLITE_DONE {
+ print("error updating row")
+ }
+ sqlite3_finalize(updateStmt)
}
+ } else {
+ let insertSQL = """
+ INSERT INTO ui_monitoring (
+ timestamp, initial_traversal_at, app, window, text_output
+ ) VALUES (?, ?, ?, ?, ?);
+ """
- sqlite3_finalize(upsertStmt)
+ var insertStmt: OpaquePointer?
+ if sqlite3_prepare_v2(db, insertSQL, -1, &insertStmt, nil) == SQLITE_OK {
+ sqlite3_bind_text(insertStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(insertStmt, 2, timestamp, -1, SQLITE_TRANSIENT) // Set initial_traversal_at same as timestamp for new records
+ sqlite3_bind_text(insertStmt, 3, sanitizedApp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(insertStmt, 4, sanitizedWindow, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(insertStmt, 5, finalText, -1, SQLITE_TRANSIENT)
+
+ if sqlite3_step(insertStmt) != SQLITE_DONE {
+ print("error inserting row")
+ }
+ sqlite3_finalize(insertStmt)
+ }
}
let endTime = DispatchTime.now()
@@ -1162,13 +1236,15 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
}
func saveElementValues() {
- if !hasChanges || changedWindows.isEmpty { return }
+ // Check both sets
+ if (changedWindows.isEmpty && windowsNeedingTimestampUpdate.isEmpty) { return }
let timestamp = ISO8601DateFormatter().string(from: Date())
var totalChars = 0
sqlite3_exec(screenPipeDb?.db, "BEGIN TRANSACTION", nil, nil, nil)
+ // Process windows with content changes
for windowId in changedWindows {
guard let windowState = globalElementValues[windowId.app]?[windowId.window] else { continue }
@@ -1183,10 +1259,16 @@ func saveElementValues() {
saveToDatabase(windowId: windowId, newTextOutput: textOutput, timestamp: timestamp)
}
+ // Process windows that only need timestamp updates
+ for windowId in windowsNeedingTimestampUpdate where !changedWindows.contains(windowId) {
+ saveToDatabase(windowId: windowId, newTextOutput: "", timestamp: timestamp)
+ }
+
sqlite3_exec(screenPipeDb?.db, "COMMIT", nil, nil, nil)
// Clear the changed windows set
changedWindows.removeAll()
+ windowsNeedingTimestampUpdate.removeAll()
hasChanges = false
}
@@ -1449,11 +1531,9 @@ pub async fn run_ui() -> Result<()> {
info!("starting ui monitoring...");
debug!("running swift script from: {}", script_path.display());
- // Add error handling wrapper
match run_ui_monitoring(&script_path).await {
Ok(_) => {
- info!("ui monitoring exited normally");
- return Ok(());
+ return Err(anyhow::anyhow!("ui monitoring exited unexpectedly"));
},
Err(e) => {
error!("ui monitoring crashed: {}", e);
diff --git a/screenpipe-vision/src/ui_monitoring_macos.swift b/screenpipe-vision/src/ui_monitoring_macos.swift
index ff5cfd29f..e15f443b2 100644
--- a/screenpipe-vision/src/ui_monitoring_macos.swift
+++ b/screenpipe-vision/src/ui_monitoring_macos.swift
@@ -44,6 +44,7 @@ var currentObserver: AXObserver? {
}
var monitoringEventLoop: CFRunLoop?
var hasChanges = false
+var windowsNeedingTimestampUpdate = Set<WindowIdentifier>()
// Debounce mechanism variables
var pendingNotifications = [(startElement: AXUIElement, depth: Int)]()
var debounceTimer: DispatchSourceTimer?
@@ -228,7 +229,7 @@ func setupDatabase() {
screenPipeDb = try ScreenPipeDB()
print("database connected successfully")
- // Create table if not exists
+ // Create table if not exists (original schema)
let createTableSQL = """
CREATE TABLE IF NOT EXISTS ui_monitoring (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -244,9 +245,46 @@ func setupDatabase() {
if sqlite3_exec(screenPipeDb?.db, createTableSQL, nil, nil, nil) != SQLITE_OK {
let error = String(cString: sqlite3_errmsg(screenPipeDb?.db))
print("error creating table: \(error)")
- } else {
- print("database tables created successfully")
+ return
+ }
+
+ // Add initial_traversal_at column if it doesn't exist
+ let addColumnSQL = """
+ SELECT COUNT(*) FROM pragma_table_info('ui_monitoring')
+ WHERE name='initial_traversal_at';
+ """
+
+ var stmt: OpaquePointer?
+ var columnExists = false
+
+ if sqlite3_prepare_v2(screenPipeDb?.db, addColumnSQL, -1, &stmt, nil) == SQLITE_OK {
+ if sqlite3_step(stmt) == SQLITE_ROW {
+ columnExists = sqlite3_column_int(stmt, 0) > 0
+ }
}
+ sqlite3_finalize(stmt)
+
+ if !columnExists {
+ print("adding initial_traversal_at column...")
+ let alterTableSQL = """
+ ALTER TABLE ui_monitoring
+ ADD COLUMN initial_traversal_at TEXT;
+
+ -- Set initial_traversal_at to timestamp for existing records
+ UPDATE ui_monitoring
+ SET initial_traversal_at = timestamp
+ WHERE initial_traversal_at IS NULL;
+ """
+
+ if sqlite3_exec(screenPipeDb?.db, alterTableSQL, nil, nil, nil) != SQLITE_OK {
+ let error = String(cString: sqlite3_errmsg(screenPipeDb?.db))
+ print("error adding column: \(error)")
+ } else {
+ print("added initial_traversal_at column successfully")
+ }
+ }
+
+ print("database setup completed")
} catch {
print("error setting up database: \(error)")
exit(1)
@@ -752,6 +790,9 @@ func processPendingNotifications() {
let startElement = selectedNotification.startElement
var visitedElements = Set<AXUIElementWrapper>()
+ // Always add to timestamp update set
+ windowsNeedingTimestampUpdate.insert(WindowIdentifier(app: context.appName, window: context.windowName))
+
if updateElementAndChildren(startElement, appName: context.appName, windowName: context.windowName, visitedElements: &visitedElements) {
hasChanges = true
changedWindows.insert(WindowIdentifier(app: context.appName, window: context.windowName))
@@ -989,7 +1030,7 @@ func buildTextOutput(from windowState: WindowState) -> String {
// Then process any orphaned elements
let orphanElements = windowState.elements.filter { !processedElements.contains($0.key) }
if !orphanElements.isEmpty {
- textOutput += "\n--- ACCESSIBILITY_NOTIFICATIONS_PROCESSING ---\n"
+ textOutput += "\n---\n"
// Sort orphans by timestamp first (oldest first), then position if timestamps are equal
let sortedOrphans = orphanElements.values.sorted { (e1, e2) -> Bool in
@@ -1040,8 +1081,9 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
.components(separatedBy: CharacterSet.controlCharacters).joined()
.trimmingCharacters(in: .whitespacesAndNewlines)
- // First, get existing text_output
+ // First, get existing text_output and check if record exists
var existingText = ""
+ var recordExists = false
let selectSQL = "SELECT text_output FROM ui_monitoring WHERE app = ? AND window = ?;"
var selectStmt: OpaquePointer?
@@ -1050,6 +1092,7 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
sqlite3_bind_text(selectStmt, 2, sanitizedWindow, -1, SQLITE_TRANSIENT)
if sqlite3_step(selectStmt) == SQLITE_ROW {
+ recordExists = true
if let text = sqlite3_column_text(selectStmt, 0) {
existingText = String(cString: text)
}
@@ -1095,7 +1138,20 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
// Skip if no unique lines or extensions found
if uniqueNewLines.isEmpty && extensionsFound == 0 {
- print("no new lines or extensions (found \(exactMatchesFound) exact matches)")
+ // Update timestamp only
+ let updateSQL = "UPDATE ui_monitoring SET timestamp = ? WHERE app = ? AND window = ?;"
+ var updateStmt: OpaquePointer?
+ if sqlite3_prepare_v2(db, updateSQL, -1, &updateStmt, nil) == SQLITE_OK {
+ sqlite3_bind_text(updateStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 2, sanitizedApp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 3, sanitizedWindow, -1, SQLITE_TRANSIENT)
+
+ if sqlite3_step(updateStmt) != SQLITE_DONE {
+ print("error updating timestamp")
+ }
+ sqlite3_finalize(updateStmt)
+ }
+ print("no new content, updated timestamp only")
return
}
@@ -1119,28 +1175,46 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
let finalText = allLines[startIndex...].joined(separator: "\n")
- // Update database
- let upsertSQL = """
- INSERT INTO ui_monitoring (
- timestamp, app, window, text_output
- ) VALUES (?, ?, ?, ?)
- ON CONFLICT(app, window) DO UPDATE SET
- timestamp = excluded.timestamp,
- text_output = excluded.text_output;
- """
-
- var upsertStmt: OpaquePointer?
- if sqlite3_prepare_v2(db, upsertSQL, -1, &upsertStmt, nil) == SQLITE_OK {
- sqlite3_bind_text(upsertStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
- sqlite3_bind_text(upsertStmt, 2, sanitizedApp, -1, SQLITE_TRANSIENT)
- sqlite3_bind_text(upsertStmt, 3, sanitizedWindow, -1, SQLITE_TRANSIENT)
- sqlite3_bind_text(upsertStmt, 4, finalText, -1, SQLITE_TRANSIENT)
+ // Update database with different SQL based on whether record exists
+ if recordExists {
+ let updateSQL = """
+ UPDATE ui_monitoring
+ SET timestamp = ?, text_output = ?
+ WHERE app = ? AND window = ?;
+ """
- if sqlite3_step(upsertStmt) != SQLITE_DONE {
- print("error updating row")
+ var updateStmt: OpaquePointer?
+ if sqlite3_prepare_v2(db, updateSQL, -1, &updateStmt, nil) == SQLITE_OK {
+ sqlite3_bind_text(updateStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 2, finalText, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 3, sanitizedApp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(updateStmt, 4, sanitizedWindow, -1, SQLITE_TRANSIENT)
+
+ if sqlite3_step(updateStmt) != SQLITE_DONE {
+ print("error updating row")
+ }
+ sqlite3_finalize(updateStmt)
}
+ } else {
+ let insertSQL = """
+ INSERT INTO ui_monitoring (
+ timestamp, initial_traversal_at, app, window, text_output
+ ) VALUES (?, ?, ?, ?, ?);
+ """
- sqlite3_finalize(upsertStmt)
+ var insertStmt: OpaquePointer?
+ if sqlite3_prepare_v2(db, insertSQL, -1, &insertStmt, nil) == SQLITE_OK {
+ sqlite3_bind_text(insertStmt, 1, timestamp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(insertStmt, 2, timestamp, -1, SQLITE_TRANSIENT) // Set initial_traversal_at same as timestamp for new records
+ sqlite3_bind_text(insertStmt, 3, sanitizedApp, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(insertStmt, 4, sanitizedWindow, -1, SQLITE_TRANSIENT)
+ sqlite3_bind_text(insertStmt, 5, finalText, -1, SQLITE_TRANSIENT)
+
+ if sqlite3_step(insertStmt) != SQLITE_DONE {
+ print("error inserting row")
+ }
+ sqlite3_finalize(insertStmt)
+ }
}
let endTime = DispatchTime.now()
@@ -1149,13 +1223,15 @@ func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp
}
func saveElementValues() {
- if !hasChanges || changedWindows.isEmpty { return }
+ // Check both sets
+ if (changedWindows.isEmpty && windowsNeedingTimestampUpdate.isEmpty) { return }
let timestamp = ISO8601DateFormatter().string(from: Date())
var totalChars = 0
sqlite3_exec(screenPipeDb?.db, "BEGIN TRANSACTION", nil, nil, nil)
+ // Process windows with content changes
for windowId in changedWindows {
guard let windowState = globalElementValues[windowId.app]?[windowId.window] else { continue }
@@ -1170,10 +1246,16 @@ func saveElementValues() {
saveToDatabase(windowId: windowId, newTextOutput: textOutput, timestamp: timestamp)
}
+ // Process windows that only need timestamp updates
+ for windowId in windowsNeedingTimestampUpdate where !changedWindows.contains(windowId) {
+ saveToDatabase(windowId: windowId, newTextOutput: "", timestamp: timestamp)
+ }
+
sqlite3_exec(screenPipeDb?.db, "COMMIT", nil, nil, nil)
// Clear the changed windows set
changedWindows.removeAll()
+ windowsNeedingTimestampUpdate.removeAll()
hasChanges = false
}