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

refactor: remove UI monitoring feature

Louis Beaumontbebb92f9c9f6
diff --git a/pipes/data-table/src/components/database-sidebar.tsx b/pipes/data-table/src/components/database-sidebar.tsx
index e215b543a..eb3292841 100644
--- a/pipes/data-table/src/components/database-sidebar.tsx
+++ b/pipes/data-table/src/components/database-sidebar.tsx
@@ -12,11 +12,6 @@ interface TableItem {
}
const allTables: TableItem[] = [
- {
- name: "ui_monitoring",
- displayName: "UI monitoring",
- icon: <Database className="h-4 w-4" />,
- },
{
name: "video_chunks",
displayName: "Video files",
@@ -46,18 +41,7 @@ export function DatabaseSidebar({
const [tables, setTables] = useState<TableItem[]>([]);
useEffect(() => {
- // detect macos
- const isMacOS =
- navigator.platform.toUpperCase().indexOf("MAC") >= 0 ||
- /Mac/.test(navigator.userAgent);
-
- // filter tables based on os
- if (isMacOS) {
- setTables(allTables);
- } else {
- // exclude ui_monitoring on non-macos
- setTables(allTables.filter((table) => table.name !== "ui_monitoring"));
- }
+ setTables(allTables);
}, []);
return (
diff --git a/pipes/data-table/src/components/page.tsx b/pipes/data-table/src/components/page.tsx
index cfd95d736..483b53782 100644
--- a/pipes/data-table/src/components/page.tsx
+++ b/pipes/data-table/src/components/page.tsx
@@ -5,7 +5,6 @@ import { DatabaseSidebar } from "./database-sidebar";
import { OcrDataTable } from "./ocr-data-table";
import { VideoChunksTable } from "./video-chunks-table";
import { AudioTranscriptionsTable } from "./audio-transcriptions-table";
-import { UiMonitoringTable } from "./ui-monitoring-table";
import { pipe } from "@screenpipe/browser";
import { SearchCommand } from "./search-command";
@@ -24,12 +23,6 @@ export default function DataPage() {
return <VideoChunksTable />;
case "audio_transcriptions":
return <AudioTranscriptionsTable />;
- case "ui_monitoring":
- return navigator.userAgent.toLowerCase().includes("mac") ? (
- <UiMonitoringTable />
- ) : (
- <div></div>
- );
default:
return <div>select a table</div>;
}
diff --git a/pipes/data-table/src/components/ui-monitoring-table.tsx b/pipes/data-table/src/components/ui-monitoring-table.tsx
deleted file mode 100644
index d0f4b3f1d..000000000
--- a/pipes/data-table/src/components/ui-monitoring-table.tsx
+++ /dev/null
@@ -1,506 +0,0 @@
-"use client";
-
-import * as React from "react";
-import {
- ColumnDef,
- SortingState,
- VisibilityState,
- flexRender,
- getCoreRowModel,
- getSortedRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import {
- AppWindow,
- ArrowUpDown,
- ChevronDown,
- ChevronLeft,
- ChevronRight,
- MoreHorizontal,
- RefreshCw,
- Search,
-} from "lucide-react";
-
-import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuCheckboxItem,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Input } from "@/components/ui/input";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
-import { Badge } from "@/components/ui/badge";
-import { SqlAutocompleteInput } from "./sql-autocomplete-input";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-
-interface UiMonitoring {
- id: number;
- text_output: string;
- timestamp: string;
- app: string;
- window: string;
- initial_traversal_at: string;
-}
-
-const columns: ColumnDef<UiMonitoring>[] = [
- {
- accessorKey: "id",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- ID
- <ArrowUpDown className="ml-2 h-4 w-4" />
- </Button>
- );
- },
- },
- {
- accessorKey: "text_output",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Text Content
- <ArrowUpDown className="ml-2 h-4 w-4" />
- </Button>
- );
- },
- cell: ({ row }) => (
- <CellContent
- value={row.getValue("text_output")}
- className="max-w-[500px] truncate font-mono"
- />
- ),
- },
- {
- accessorKey: "app",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Application
- <ArrowUpDown className="ml-2 h-4 w-4" />
- </Button>
- );
- },
- cell: ({ row }) => <Badge variant="outline">{row.getValue("app")}</Badge>,
- },
- {
- accessorKey: "window",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Window
- <ArrowUpDown className="ml-2 h-4 w-4" />
- </Button>
- );
- },
- cell: ({ row }) => (
- <CellContent
- value={row.getValue("window")}
- className="max-w-[200px] truncate"
- />
- ),
- },
- {
- accessorKey: "timestamp",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Timestamp
- <ArrowUpDown className="ml-2 h-4 w-4" />
- </Button>
- );
- },
- cell: ({ row }) => {
- const timestamp = new Date(row.getValue("timestamp"));
- return timestamp.toLocaleString();
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- const uiMonitoring = row.original;
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" className="h-8 w-8 p-0">
- <span className="sr-only">open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuLabel>actions</DropdownMenuLabel>
- <DropdownMenuItem
- onClick={() =>
- navigator.clipboard.writeText(uiMonitoring.text_output)
- }
- >
- copy text
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() =>
- navigator.clipboard.writeText(
- JSON.stringify(uiMonitoring, null, 2)
- )
- }
- >
- copy raw data
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
- },
- },
-];
-
-// Component for cell content with click support
-interface CellContentProps {
- value: string | null;
- className?: string;
-}
-
-function CellContent({ value, className }: CellContentProps) {
- const [isDialogOpen, setIsDialogOpen] = React.useState(false);
- const displayValue = value || "N/A";
-
- return (
- <>
- <div
- className={className}
- onClick={() => setIsDialogOpen(true)}
- style={{ cursor: "pointer" }}
- >
- {displayValue}
- </div>
-
- <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
- <DialogContent className="sm:max-w-[700px] max-h-[80vh]">
- <DialogHeader>
- <DialogTitle>cell content</DialogTitle>
- </DialogHeader>
- <div className="overflow-auto max-h-[60vh] font-mono p-4 border rounded-md bg-muted/50 whitespace-pre-wrap">
- {displayValue}
- </div>
- </DialogContent>
- </Dialog>
- </>
- );
-}
-
-export function UiMonitoringTable() {
- const [data, setData] = React.useState<UiMonitoring[]>([]);
- const [sorting, setSorting] = React.useState<SortingState>([]);
- const [columnVisibility, setColumnVisibility] =
- React.useState<VisibilityState>({});
- const [isLoading, setIsLoading] = React.useState(false);
- const [error, setError] = React.useState<string | null>(null);
-
- const [pageSize, setPageSize] = React.useState(9);
- const [pageIndex, setPageIndex] = React.useState(0);
- const [totalRows, setTotalRows] = React.useState(0);
-
- const [textFilter, setTextFilter] = React.useState("");
- const [appFilter, setAppFilter] = React.useState("");
-
- const fetchData = async () => {
- setIsLoading(true);
- setError(null);
- try {
- const filterClauses = [
- "text_output IS NOT NULL",
- "trim(text_output) != ''",
- textFilter
- ? `LOWER(text_output) LIKE '%${textFilter
- .toLowerCase()
- .replace(/'/g, "''")}%'`
- : null,
- appFilter
- ? `LOWER(app) LIKE '%${appFilter.toLowerCase().replace(/'/g, "''")}%'`
- : null,
- ]
- .filter(Boolean)
- .join(" AND ");
-
- const countResponse = await fetch("http://localhost:3030/raw_sql", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- query: `
- SELECT COUNT(*) as total
- FROM ui_monitoring
- WHERE ${filterClauses}
- `,
- }),
- });
-
- if (!countResponse.ok) {
- throw new Error("failed to fetch count");
- }
-
- const countResult = await countResponse.json();
- setTotalRows(countResult[0].total);
-
- const response = await fetch("http://localhost:3030/raw_sql", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- query: `
- SELECT
- id,
- text_output,
- timestamp,
- app,
- window,
- initial_traversal_at
- FROM ui_monitoring
- WHERE ${filterClauses}
- ORDER BY id DESC
- LIMIT ${pageSize}
- OFFSET ${pageIndex * pageSize}
- `,
- }),
- });
- if (!response.ok) {
- throw new Error("failed to fetch data");
- }
- const result = await response.json();
- setData(result);
- } catch (error) {
- console.error("error fetching data:", error);
- setError(
- `failed to load ui monitoring data: ${
- error instanceof Error ? error.message : "unknown error"
- }`
- );
- } finally {
- setIsLoading(false);
- }
- };
-
- React.useEffect(() => {
- const timer = setTimeout(() => {
- fetchData();
- }, 300);
-
- return () => clearTimeout(timer);
- }, [textFilter, appFilter, pageIndex, pageSize]);
-
- const table = useReactTable({
- data,
- columns,
- onSortingChange: setSorting,
- getCoreRowModel: getCoreRowModel(),
- manualPagination: true,
- manualFiltering: true,
- pageCount: Math.ceil(totalRows / pageSize),
- onPaginationChange: (updater) => {
- if (typeof updater === "function") {
- const newState = updater({
- pageIndex,
- pageSize,
- });
- setPageIndex(newState.pageIndex);
- setPageSize(newState.pageSize);
- }
- },
- getSortedRowModel: getSortedRowModel(),
- onColumnVisibilityChange: setColumnVisibility,
- state: {
- sorting,
- columnVisibility,
- pagination: {
- pageIndex,
- pageSize,
- },
- },
- });
-
- return (
- <div className="w-full">
- <div className="flex items-center justify-between py-4">
- <div className="flex items-center space-x-4">
- <div className="relative">
- <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="filter by text content..."
- value={textFilter}
- onChange={(event) => {
- setTextFilter(event.target.value);
- setPageIndex(0);
- }}
- className="max-w-sm pl-8"
- />
- </div>
- <SqlAutocompleteInput
- id="appFilter"
- type="app"
- icon={<AppWindow className="h-4 w-4" />}
- value={appFilter}
- onChange={(value) => {
- setAppFilter(value);
- setPageIndex(0);
- }}
- placeholder="filter by app..."
- className="w-[300px]"
- />
- <Button
- variant="outline"
- size="icon"
- className="w-12"
- onClick={fetchData}
- disabled={isLoading}
- >
- <RefreshCw
- className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`}
- />
- </Button>
- </div>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="outline">
- columns <ChevronDown className="ml-2 h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {table
- .getAllColumns()
- .filter((column) => column.getCanHide())
- .map((column) => {
- return (
- <DropdownMenuCheckboxItem
- key={column.id}
- className="capitalize"
- checked={column.getIsVisible()}
- onCheckedChange={(value) =>
- column.toggleVisibility(!!value)
- }
- >
- {column.id}
- </DropdownMenuCheckboxItem>
- );
- })}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- {error ? (
- <div className="text-center text-red-500 py-4">{error}</div>
- ) : (
- <div className="rounded-md border">
- <Table>
- <TableHeader>
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id}>
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext()
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {isLoading ? (
- <TableRow>
- <TableCell
- colSpan={columns.length}
- className="h-24 text-center"
- >
- loading...
- </TableCell>
- </TableRow>
- ) : table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext()
- )}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell
- colSpan={columns.length}
- className="h-24 text-center"
- >
- no results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- )}
- <div className="flex items-center justify-center space-x-2 py-4">
- <Button
- variant="outline"
- size="lg"
- className="w-32"
- onClick={() => table.previousPage()}
- disabled={!table.getCanPreviousPage()}
- >
- <ChevronLeft className="h-4 w-4" />
- previous
- </Button>
- <Button
- variant="outline"
- size="lg"
- className="w-32"
- onClick={() => table.nextPage()}
- disabled={!table.getCanNextPage()}
- >
- next
- <ChevronRight className="h-4 w-4" />
- </Button>
- </div>
- </div>
- );
-}
diff --git a/screenpipe-app-tauri/components/cli-command-dialog.tsx b/screenpipe-app-tauri/components/cli-command-dialog.tsx
index e7af0a044..8b07b01f1 100644
--- a/screenpipe-app-tauri/components/cli-command-dialog.tsx
+++ b/screenpipe-app-tauri/components/cli-command-dialog.tsx
@@ -150,10 +150,6 @@ export function CliCommandDialog({ settings }: CliCommandDialogProps) {
args.push("--enable-frame-cache");
}
- if (settings.enableUiMonitoring) {
- args.push("--enable-ui-monitoring");
- }
-
if (settings.enableRealtimeAudioTranscription) {
args.push("--enable-realtime-audio-transcription");
}
diff --git a/screenpipe-app-tauri/components/screenpipe-status.tsx b/screenpipe-app-tauri/components/screenpipe-status.tsx
index faddd70fe..5ab51f140 100644
--- a/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -93,26 +93,20 @@ const HealthStatus = ({ className }: { className?: string }) => {
status: string,
frameStatus: string,
audioStatus: string,
- uiStatus: string,
- audioDisabled: boolean,
- uiMonitoringEnabled: boolean
+ audioDisabled: boolean
) => {
if (status === "loading") return "bg-yellow-500";
const isVisionOk = frameStatus === "ok" || frameStatus === "disabled";
const isAudioOk =
audioStatus === "ok" || audioStatus === "disabled" || audioDisabled;
- const isUiOk =
- uiStatus === "ok" || uiStatus === "disabled" || !uiMonitoringEnabled;
- return isVisionOk && isAudioOk && isUiOk ? "bg-green-500" : "bg-red-500";
+ return isVisionOk && isAudioOk ? "bg-green-500" : "bg-red-500";
};
const getStatusMessage = (
status: string,
frameStatus: string,
audioStatus: string,
- uiStatus: string,
- audioDisabled: boolean,
- uiMonitoringEnabled: boolean
+ audioDisabled: boolean
) => {
if (status === "loading")
return "screenpipe is starting up. this may take a few minutes...";
@@ -122,8 +116,6 @@ 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 ")}`;
@@ -137,17 +129,13 @@ const HealthStatus = ({ className }: { className?: string }) => {
health?.status ?? "",
health?.frame_status ?? "",
health?.audio_status ?? "",
- health?.ui_status ?? "",
- settings.disableAudio,
- settings.enableUiMonitoring
+ settings.disableAudio
);
const statusMessage = getStatusMessage(
health?.status ?? "",
health?.frame_status ?? "",
health?.audio_status ?? "",
- health?.ui_status ?? "",
- settings.disableAudio ?? "",
- settings.enableUiMonitoring
+ settings.disableAudio
);
const handleOpenStatusDialog = async () => {
@@ -378,28 +366,6 @@ const HealthStatus = ({ className }: { className?: string }) => {
</div>
)}
- {/* UI Monitoring Status */}
- {settings.enableUiMonitoring && (
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <div
- className={`w-2 h-2 rounded-full ${
- health?.ui_status === "ok"
- ? "bg-green-500"
- : "bg-red-500"
- }`}
- />
- <span className="text-sm">ui monitoring</span>
- <span className="text-sm text-muted-foreground">
- status: {health?.ui_status}, last update:{" "}
- {formatTimestamp(
- health ? health.last_ui_timestamp : "error"
- )}
- </span>
- </div>
-
- </div>
- )}
</div>
</>
)}
diff --git a/screenpipe-app-tauri/components/settings/feedback-section.tsx b/screenpipe-app-tauri/components/settings/feedback-section.tsx
index b9281d372..f91123670 100644
--- a/screenpipe-app-tauri/components/settings/feedback-section.tsx
+++ b/screenpipe-app-tauri/components/settings/feedback-section.tsx
@@ -2,7 +2,8 @@
import React from "react";
import { ShareLogsButton } from "@/components/share-logs-button";
-import { MessageSquare } from "lucide-react";
+import { MessageSquare, Github } from "lucide-react";
+import { open } from "@tauri-apps/plugin-shell";
export function FeedbackSection() {
return (
@@ -41,6 +42,26 @@ export function FeedbackSection() {
No personal screen content is sent unless you explicitly attach it.
</p>
</div>
+
+ <div className="p-6 bg-card rounded-xl border border-border">
+ <div className="flex items-start gap-4">
+ <div className="p-3 bg-primary/10 rounded-lg">
+ <Github className="h-6 w-6 text-primary" />
+ </div>
+ <div>
+ <h3 className="text-lg font-semibold mb-1">GitHub Issues</h3>
+ <p className="text-sm text-muted-foreground mb-3">
+ For product ideas, bugs, suggestions, or feature requests, you can also open an issue on GitHub.
+ </p>
+ <button
+ onClick={() => open("https://github.com/mediar-ai/screenpipe/issues")}
+ className="text-sm text-primary hover:underline"
+ >
+ github.com/mediar-ai/screenpipe/issues →
+ </button>
+ </div>
+ </div>
+ </div>
</div>
</div>
);
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 559442a32..c143acce7 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -5629,7 +5629,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "screenpipe-app"
-version = "2.0.27"
+version = "2.0.28"
dependencies = [
"anyhow",
"async-stream",
diff --git a/screenpipe-js/common/types.ts b/screenpipe-js/common/types.ts
index 43717b201..3856fcd68 100644
--- a/screenpipe-js/common/types.ts
+++ b/screenpipe-js/common/types.ts
@@ -264,7 +264,6 @@ export interface Settings {
aiProviderType: AIProviderType;
embeddedLLM: EmbeddedLLMConfig;
enableFrameCache: boolean;
- enableUiMonitoring: boolean;
aiMaxContextChars: number;
analyticsEnabled: boolean;
user: User;
diff --git a/screenpipe-js/common/utils.ts b/screenpipe-js/common/utils.ts
index 433ce6ecd..e7cd513c8 100644
--- a/screenpipe-js/common/utils.ts
+++ b/screenpipe-js/common/utils.ts
@@ -91,7 +91,6 @@ function getDefaultSettings(): Settings {
port: 11434,
},
enableFrameCache: true,
- enableUiMonitoring: false,
aiMaxContextChars: 512000,
analyticsEnabled: true,
user: {
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 50d4ae232..709d51f31 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -27,8 +27,6 @@ use screenpipe_server::{
start_continuous_recording, watch_pid, PipeManager, ResourceMonitor, SCServer,
};
use screenpipe_vision::monitor::list_monitors;
-#[cfg(target_os = "macos")]
-use screenpipe_vision::run_ui;
use serde::Deserialize;
use serde_json::{json, Value};
use std::path::Path;
@@ -765,7 +763,6 @@ async fn main() -> anyhow::Result<()> {
pipe_manager.clone(),
cli.disable_vision,
cli.disable_audio,
- cli.enable_ui_monitoring,
audio_manager.clone(),
cli.enable_pipe_manager,
);
@@ -838,10 +835,6 @@ async fn main() -> anyhow::Result<()> {
"│ included windows │ {:<34} │",
format_cell(&format!("{:?}", &included_windows_clone), VALUE_WIDTH)
);
- println!(
- "│ ui monitoring │ {:<34} │",
- cli.enable_ui_monitoring
- );
println!(
"│ frame cache │ {:<34} │",
cli.enable_frame_cache
@@ -1128,34 +1121,6 @@ async fn main() -> anyhow::Result<()> {
let ctrl_c_future = signal::ctrl_c();
pin_mut!(ctrl_c_future);
- // Start the UI monitoring task
- #[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! {
- 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;
- }
- }
- }
- });
- }
-
tokio::select! {
_ = handle => info!("recording completed"),
result = &mut server_future => {
diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rs
index d06e156df..13b2ed214 100644
--- a/screenpipe-server/src/cli.rs
+++ b/screenpipe-server/src/cli.rs
@@ -278,10 +278,6 @@ pub struct Cli {
#[arg(long, default_value_t = false)]
pub enable_llm: bool,
- /// Enable UI monitoring (macOS only)
- #[arg(long, default_value_t = false)]
- pub enable_ui_monitoring: bool,
-
/// Enable experimental video frame cache (may increase CPU usage) - makes timeline UI available, frame streaming, etc.
#[arg(long, default_value_t = true)]
pub enable_frame_cache: bool,
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 34a6b2780..977305d40 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -94,7 +94,6 @@ pub struct AppState {
pub pipe_manager: Arc<PipeManager>,
pub vision_disabled: bool,
pub audio_disabled: bool,
- pub ui_monitoring_enabled: bool,
pub enable_pipe_manager: bool,
pub frame_cache: Option<Arc<FrameCache>>,
pub frame_image_cache: Option<Arc<Mutex<FrameImageCache>>>,
@@ -290,10 +289,8 @@ pub struct HealthCheckResponse {
pub status_code: u16,
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>,
pub device_status_details: Option<String>,
@@ -659,7 +656,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
};
}
- let (last_frame, audio, last_ui) = match state.db.get_latest_timestamps().await {
+ let (last_frame, 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);
@@ -722,25 +719,9 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
None
};
- 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 => "not_started",
- }
- };
-
let (overall_status, message, verbose_instructions, status_code) = if (frame_status == "ok"
|| frame_status == "disabled")
&& (audio_status == "ok" || audio_status == "disabled")
- && (ui_status == "ok" || ui_status == "disabled")
{
(
"healthy",
@@ -756,9 +737,6 @@ 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");
- }
let systems_str = unhealthy_systems.join(", ");
(
@@ -781,10 +759,8 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
} else {
None
},
- last_ui_timestamp: last_ui,
frame_status: frame_status.to_string(),
audio_status,
- ui_status: ui_status.to_string(),
message,
verbose_instructions,
device_status_details,
@@ -802,10 +778,6 @@ fn get_verbose_instructions(unhealthy_systems: &[&str]) -> String {
instructions.push_str("Audio system is not working properly. Check if microphone permissions are enabled and devices are connected.\n");
}
- if unhealthy_systems.contains(&"ui") {
- instructions.push_str("UI monitoring is not working properly. Check if accessibility permissions are enabled.\n");
- }
-
if instructions.is_empty() {
instructions =
"If you're experiencing issues, please try contacting us on Discord.".to_string();
@@ -1136,7 +1108,6 @@ pub struct SCServer {
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
audio_disabled: bool,
- ui_monitoring_enabled: bool,
enable_pipe: bool,
}
@@ -1149,7 +1120,6 @@ impl SCServer {
pipe_manager: Arc<PipeManager>,
vision_disabled: bool,
audio_disabled: bool,
- ui_monitoring_enabled: bool,
audio_manager: Arc<AudioManager>,
enable_pipe: bool,
) -> Self {
@@ -1160,7 +1130,6 @@ impl SCServer {
pipe_manager,
vision_disabled,
audio_disabled,
- ui_monitoring_enabled,
audio_manager,
enable_pipe,
}
@@ -1194,7 +1163,6 @@ impl SCServer {
pipe_manager: self.pipe_manager.clone(),
vision_disabled: self.vision_disabled,
audio_disabled: self.audio_disabled,
- ui_monitoring_enabled: self.ui_monitoring_enabled,
enable_pipe_manager: self.enable_pipe,
frame_cache: if enable_frame_cache {
Some(Arc::new(
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index b051ead7b..09baf8934 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -46,7 +46,6 @@ mod tests {
Arc::new(PipeManager::new(PathBuf::from(""))),
false,
false,
- false,
audio_manager,
true,
);
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index a7c21e72b..6221eb444 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -35,7 +35,6 @@ async fn setup_test_app() -> (Router, Arc<DatabaseManager>) {
Arc::new(PipeManager::new(PathBuf::from(""))),
false,
false,
- false,
audio_manager,
true,
);
diff --git a/screenpipe-vision/bin/ui_monitor b/screenpipe-vision/bin/ui_monitor
deleted file mode 100755
index 74bed944a..000000000
Binary files a/screenpipe-vision/bin/ui_monitor and /dev/null differ
diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin
deleted file mode 100755
index 74bed944a..000000000
Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and /dev/null differ
diff --git a/screenpipe-vision/build.rs b/screenpipe-vision/build.rs
index 3e680de75..804371429 100644
--- a/screenpipe-vision/build.rs
+++ b/screenpipe-vision/build.rs
@@ -1,58 +1,3 @@
-#[cfg(target_os = "macos")]
-use std::{env, path::PathBuf, process::Command};
-
fn main() {
- #[cfg(target_os = "macos")]
- {
- let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
- let bin_path = PathBuf::from(&manifest_dir).join("bin");
-
- // Create bin directory if it doesn't exist
- std::fs::create_dir_all(&bin_path).expect("failed to create bin directory");
-
- // Determine architecture-specific binary name
- let binary_name = if cfg!(target_arch = "aarch64") {
- "ui_monitor-aarch64-apple-darwin"
- } else {
- "ui_monitor-x86_64-apple-darwin"
- };
-
- let binary_path = bin_path.join(binary_name);
-
- println!("cargo:rerun-if-changed=src/ui_monitoring_macos.swift");
-
- let status = Command::new("swiftc")
- .args([
- "-O",
- "-whole-module-optimization",
- "-enforce-exclusivity=unchecked",
- "-num-threads",
- "8",
- "-target",
- if cfg!(target_arch = "aarch64") {
- "arm64-apple-macos11.0"
- } else {
- "x86_64-apple-macos11.0"
- },
- "-o",
- binary_path.to_str().unwrap(),
- "src/ui_monitoring_macos.swift",
- "-framework",
- "Cocoa",
- "-framework",
- "ApplicationServices",
- "-framework",
- "Foundation",
- ])
- .status()
- .expect("failed to compile Swift executable");
-
- if !status.success() {
- panic!("failed to compile ui_monitor executable");
- }
-
- let bin_path = PathBuf::from(&manifest_dir).join("bin");
- let new_path = bin_path.join("ui_monitor");
- std::fs::copy(&binary_path, &new_path).expect("failed to copy ui_monitor executable");
- }
+ // No build-time compilation needed
}
diff --git a/screenpipe-vision/src/core.rs b/screenpipe-vision/src/core.rs
index 7137ae9ca..89bbe5514 100644
--- a/screenpipe-vision/src/core.rs
+++ b/screenpipe-vision/src/core.rs
@@ -25,8 +25,6 @@ use std::{
collections::HashMap,
time::{Duration, Instant, UNIX_EPOCH},
};
-use tokio::fs::File;
-use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc::Sender;
use tracing::{debug, error, warn};
@@ -519,7 +517,6 @@ fn parse_json_output(json_output: &str) -> Vec<HashMap<String, String>> {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RealtimeVisionEvent {
Ocr(WindowOcr),
- Ui(UIFrame),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -543,41 +540,6 @@ pub struct WindowOcr {
pub browser_url: Option<String>,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct UIFrame {
- pub window: String,
- pub app: String,
- pub text_output: String,
- pub initial_traversal_at: String,
-}
-
-impl UIFrame {
- pub async fn read_from_pipe(reader: &mut BufReader<File>) -> Result<Self> {
- let window = UIFrame::read_string(reader).await?;
- let app = UIFrame::read_string(reader).await?;
- let text_output = UIFrame::read_string(reader).await?;
- let initial_traversal_at = UIFrame::read_string(reader).await?;
-
- Ok(UIFrame {
- window,
- app,
- text_output,
- initial_traversal_at,
- })
- }
-
- async fn read_string(reader: &mut BufReader<File>) -> Result<String> {
- let mut buffer = Vec::new();
- loop {
- let result = reader.read_until(b'\0', &mut buffer).await?;
- if result > 0 {
- buffer.pop(); // Remove the null terminator
- return Ok(String::from_utf8_lossy(&buffer).to_string());
- }
- }
- }
-}
-
fn get_active_browser_url_sync(
app_name: &str,
process_id: i32,
diff --git a/screenpipe-vision/src/lib.rs b/screenpipe-vision/src/lib.rs
index 131687835..e3c1bd106 100644
--- a/screenpipe-vision/src/lib.rs
+++ b/screenpipe-vision/src/lib.rs
@@ -5,20 +5,16 @@ pub mod custom_ocr;
#[cfg(target_os = "windows")]
pub mod microsoft;
pub mod monitor;
-#[cfg(target_os = "macos")]
-pub mod run_ui_monitoring_macos;
pub mod tesseract;
pub mod utils;
#[cfg(target_os = "macos")]
pub use apple::perform_ocr_apple;
-pub use core::{continuous_capture, process_ocr_task, CaptureResult, RealtimeVisionEvent, UIFrame};
+pub use core::{continuous_capture, process_ocr_task, CaptureResult, RealtimeVisionEvent};
// pub use types::CaptureResult;
pub use utils::OcrEngine;
pub mod capture_screenshot_by_window;
pub use custom_ocr::perform_ocr_custom;
#[cfg(target_os = "windows")]
pub use microsoft::perform_ocr_windows;
-#[cfg(target_os = "macos")]
-pub use run_ui_monitoring_macos::run_ui;
pub use tesseract::perform_ocr_tesseract;
pub mod browser_utils;
diff --git a/screenpipe-vision/src/run_ui_monitoring_macos.rs b/screenpipe-vision/src/run_ui_monitoring_macos.rs
deleted file mode 100644
index 96f503613..000000000
--- a/screenpipe-vision/src/run_ui_monitoring_macos.rs
+++ /dev/null
@@ -1,256 +0,0 @@
-use crate::UIFrame;
-use anyhow::Result;
-use screenpipe_events::send_event;
-use std::fs;
-use std::io;
-use std::path::PathBuf;
-use std::process::Stdio;
-use std::sync::atomic::AtomicBool;
-use std::sync::Arc;
-use tokio::fs::{File, OpenOptions};
-use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
-use tokio::process::Command;
-use tokio::signal;
-use tokio::time::{sleep, timeout, Duration};
-use tracing::{debug, error, info, warn};
-use which::which;
-
-pub async fn run_ui() -> Result<()> {
- info!("starting ui monitoring service...");
-
- let binary_name = "ui_monitor";
-
- // Try screenpipe-vision/bin first
- let bin_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("bin")
- .join(binary_name);
-
- // If not found, try current directory
- let current_dir_path = std::env::current_dir()?.join(binary_name);
-
- // Try the directory of the current executable
- let exe_dir_path = std::env::current_exe()?
- .parent()
- .unwrap_or_else(|| std::path::Path::new("."))
- .join(binary_name);
-
- // Try using which
- let which_path = which(binary_name).ok();
-
- // If not found, try tauri location
- let ui_monitor_path = if bin_path.exists() {
- bin_path
- } else if current_dir_path.exists() {
- current_dir_path
- } else if exe_dir_path.exists() {
- exe_dir_path
- } else if let Some(path) = which_path {
- path
- } else {
- PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .parent()
- .unwrap()
- .join("screenpipe-app-tauri")
- .join("src-tauri")
- .join(binary_name)
- };
-
- info!("ui_monitor path: {}", ui_monitor_path.display());
-
- let named_pipe = setup_ipc_queue().await?;
-
- let named_pipe_clone = named_pipe.clone();
- let is_running = Arc::new(AtomicBool::new(true));
- let is_running_clone = is_running.clone();
- let (is_running_sender, mut is_running_receiver) = tokio::sync::broadcast::channel(1);
- tokio::spawn(async move {
- let mut terminate_signal =
- signal::unix::signal(signal::unix::SignalKind::terminate()).unwrap();
- tokio::select! {
- _ = signal::ctrl_c() => {
- debug!("ctrl-c received");
- }
- _ = terminate_signal.recv() => {
- debug!("terminate signal received");
- }
- }
-
- if fs::metadata(&named_pipe_clone.path).is_ok() {
- if let Err(e) = fs::remove_file(&named_pipe_clone.path) {
- eprintln!("Failed to remove named pipe: {:?}", e);
- }
- }
- is_running_clone.store(false, std::sync::atomic::Ordering::Relaxed);
- let _ = is_running_sender.send(false);
- });
-
- let named_pipe_clone = named_pipe.clone();
- tokio::spawn(async move {
- // add loop and timeout for opening the file
- let mut file: Option<File> = None;
- let mut attempts = 0;
-
- while attempts < 10 {
- match timeout(Duration::from_secs(5), named_pipe_clone.open()).await {
- Ok(Ok(opened_file)) => {
- // Successfully opened the file
- file = Some(opened_file);
- break;
- }
- Ok(Err(e)) => {
- error!("failed to open named pipe: {}", e);
- attempts += 1;
- sleep(Duration::from_secs(1)).await;
- }
- Err(_) => {
- error!("timeout while trying to open named pipe");
- attempts += 1;
- sleep(Duration::from_secs(1)).await;
- }
- }
- }
-
- let file = match file {
- Some(f) => f,
- None => {
- return Err(anyhow::anyhow!(
- "failed to open named pipe after multiple attempts"
- ))
- }
- };
-
- let mut reader = BufReader::new(file);
-
- loop {
- tokio::select! {
- _ = is_running_receiver.recv() => {
- info!("ui_monitor is shutting down");
- return Ok(());
- }
- frame = UIFrame::read_from_pipe(&mut reader) => {
- match frame {
- Ok(frame) => {
- let _ = send_event("ui_frame", frame);
- }
- Err(e) => {
- if let Some(io_err) = e.downcast_ref::<io::Error>() {
- if io_err.kind() == io::ErrorKind::WouldBlock {
- // Resource temporarily unavailable, retry after a short delay
- tokio::time::sleep(Duration::from_millis(100)).await;
- } else {
- error!("failed to read line from ui_monitor: {}", e);
- }
- } else {
- error!("failed to read line from ui_monitor: {}", e);
- }
- }
- }
- }
- }
- }
- });
-
- let named_pipe_clone = named_pipe.clone();
-
- while is_running.load(std::sync::atomic::Ordering::Relaxed) {
- // Clone the PathBuf for each iteration
- let mut child = Command::new(&ui_monitor_path)
- .arg(named_pipe_clone.path.clone())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .expect("failed to start ui_monitor");
-
- info!("ui_monitor process started");
-
- // Handle stdout
- if let Some(stdout) = child.stdout.take() {
- let reader = BufReader::new(stdout);
- let mut lines = reader.lines();
-
- // Spawn a task to read lines asynchronously
- tokio::spawn(async move {
- while let Ok(Some(line)) = lines.next_line().await {
- if line.to_lowercase().contains("error") {
- error!("ui_monitor stdout: {}", line);
- } else {
- debug!("ui_monitor stdout: {}", line);
- }
- }
- });
- }
-
- // Handle stderr
- if let Some(stderr) = child.stderr.take() {
- let reader = BufReader::new(stderr);
- let mut lines = reader.lines();
-
- tokio::spawn(async move {
- while let Ok(Some(line)) = lines.next_line().await {
- error!("ui_monitor stderr: {}", line);
- }
- });
- }
-
- // Wait for the process to exit
- match child.wait().await {
- Ok(status) => {
- warn!("ui_monitor exited with status: {}", status);
- warn!("restarting ui_monitor in 5 seconds...");
- sleep(Duration::from_secs(5)).await;
- }
- Err(e) => {
- error!("failed to wait for ui_monitor process: {}", e);
- warn!("retrying ui_monitor in 5 seconds...");
- sleep(Duration::from_secs(5)).await;
- }
- }
- }
-
- Ok(())
-}
-
-async fn setup_ipc_queue() -> Result<NamedPipe> {
- // create random /dev/shm/screenpipe-ipc-queue-<random-string>
- // read 16 bytes from /dev/urandom
- let mut random_bytes = [0u8; 16];
- let mut file = File::open("/dev/urandom").await?;
- file.read_exact(&mut random_bytes).await?;
- let mut path: String = String::from("/tmp/screenpipe-ui-ipc-queue-");
- for byte in random_bytes {
- path.push_str(&format!("{:02x}", byte));
- }
-
- NamedPipe::new(path).await
-}
-
-#[derive(Debug, Clone)]
-struct NamedPipe {
- pub path: String,
-}
-
-impl NamedPipe {
- async fn new(path: String) -> Result<Self> {
- // Create the named pipe
- let c_path = std::ffi::CString::new(path.clone()).expect("CString::new failed");
- let result = unsafe { libc::mkfifo(c_path.as_ptr(), libc::S_IRUSR | libc::S_IWUSR) };
- if result != 0 {
- panic!(
- "Failed to create named pipe: {:?}",
- std::io::Error::last_os_error()
- );
- }
-
- Ok(NamedPipe { path })
- }
-
- async fn open(&self) -> Result<File> {
- let file = OpenOptions::new()
- .read(true)
- .custom_flags(libc::O_NONBLOCK) // Open in non-blocking mode
- .open(self.path.clone())
- .await?;
-
- Ok(file)
- }
-}
diff --git a/screenpipe-vision/src/ui_monitoring_macos.swift b/screenpipe-vision/src/ui_monitoring_macos.swift
deleted file mode 100644
index 6abdda6d8..000000000
--- a/screenpipe-vision/src/ui_monitoring_macos.swift
+++ /dev/null
@@ -1,1642 +0,0 @@
-import ApplicationServices
-import Cocoa
-import Foundation
-import SQLite3
-
-// Force stdout to flush immediately
-setbuf(__stdoutp, nil)
-print("swift script starting...")
-
-// Add early error handling
-func checkAccessibilityPermissions() -> Bool {
- let checkOptPrompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue()
- let options = [checkOptPrompt: true] as CFDictionary
- let trusted = AXIsProcessTrustedWithOptions(options)
- print("accessibility permissions check: \(trusted)")
- return trusted
-}
-
-// Define WindowState struct first
-struct WindowState {
- var elements: [String: ElementAttributes]
- var textOutput: String
- var timestamp: Date
-
- init() {
- self.elements = [:]
- self.textOutput = ""
- self.timestamp = Date()
- }
-}
-
-struct UIFrame {
- let window: String
- let app: String
- let text_output: String
- let initial_traversal_at: String
-}
-
-extension UIFrame {
- func toBytes() -> [UInt8] {
- var bytes = [UInt8]()
-
- // Convert each string to bytes and append to the array
- bytes.append(contentsOf: window.utf8)
- bytes.append(0) // Null-terminate the string
-
- bytes.append(contentsOf: app.utf8)
- bytes.append(0) // Null-terminate the string
-
- bytes.append(contentsOf: text_output.utf8)
- bytes.append(0) // Null-terminate the string
-
- bytes.append(contentsOf: initial_traversal_at.utf8)
- bytes.append(0) // Null-terminate the string
-
- return bytes
- }
-}
-
-// Global state
-var globalElementValues = [String: [String: WindowState]]() // [App: [Window: WindowState]]
-var currentObserver: AXObserver? {
- willSet {
- if let observer = currentObserver {
- CFRunLoopRemoveSource(
- CFRunLoopGetCurrent(),
- AXObserverGetRunLoopSource(observer),
- .defaultMode
- )
- }
- }
-}
-var monitoringEventLoop: CFRunLoop?
-var hasChanges = false
-var windowsNeedingTimestampUpdate = Set<WindowIdentifier>()
-// Debounce mechanism variables
-var pendingNotifications = [(startElement: AXUIElement, depth: Int)]()
-var debounceTimer: DispatchSourceTimer?
-
-// Add global context structure
-class MonitoringContext {
- let appName: String
- let windowName: String
-
- init(appName: String, windowName: String) {
- self.appName = appName
- self.windowName = windowName
- }
-}
-var currentContext: MonitoringContext?
-
-// Add these custom notification constants at the top of the file
-let kAXScrolledVisibleChangedNotification = "AXScrolledVisibleChanged" as CFString
-let kAXSelectedCellsChangedNotification = "AXSelectedCellsChanged" as CFString
-let kAXLayoutChangedNotification = "AXLayoutChanged" as CFString
-
-// Update notificationsToObserve array
-let notificationsToObserve: [(String, String)] = [
- ("AXValueChanged", kAXValueChangedNotification as String),
- ("AXTitleChanged", kAXTitleChangedNotification as String),
- ("AXFocusedUIElementChanged", kAXFocusedUIElementChangedNotification as String),
- ("AXFocusedWindowChanged", kAXFocusedWindowChangedNotification as String),
- ("AXMainWindowChanged", kAXMainWindowChangedNotification as String),
- ("AXSelectedTextChanged", kAXSelectedTextChangedNotification as String),
- ("AXUIElementDestroyed", kAXUIElementDestroyedNotification as String),
- ("AXSelectedChildrenChanged", kAXSelectedChildrenChangedNotification as String),
- ("AXRowCountChanged", kAXRowCountChangedNotification as String),
- ("AXSelectedRowsChanged", kAXSelectedRowsChangedNotification as String),
- ("AXScrolledVisibleChanged", kAXScrolledVisibleChangedNotification as String),
- ("AXLayoutChanged", kAXLayoutChangedNotification as String),
- ("AXSelectedCellsChanged", kAXSelectedCellsChangedNotification as String),
- ("AXWindowResized", kAXWindowResizedNotification as String),
- ("AXWindowMoved", kAXWindowMovedNotification as String),
- ("AXCreated", kAXCreatedNotification as String),
-]
-
-// Struct to hold element attributes including hierarchy and position
-struct ElementAttributes {
- var element: String
- var path: String
- var attributes: [String: String]
- var depth: Int
- var x: CGFloat
- var y: CGFloat
- var width: CGFloat
- var height: CGFloat
- var children: [ElementAttributes]
- var timestamp: Date
-
- // Add computed property for unique identifier
- var identifier: String {
- // Combine path with sorted attributes to create a stable identifier
- let attributesString = attributes.sorted { $0.key < $1.key }
- .map { "\($0.key)=\($0.value)" }
- .joined(separator: "|")
- return "\(path)#\(attributesString)"
- }
-
- init(
- element: String, path: String, attributes: [String: String], depth: Int,
- x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, children: [ElementAttributes],
- timestamp: Date = Date()
- ) {
- self.element = element
- self.path = path
- self.attributes = attributes
- self.depth = depth
- self.x = x
- self.y = y
- self.width = width
- self.height = height
- self.children = children
- self.timestamp = timestamp
- }
-}
-
-// Add traversal state management
-var isTraversing = false
-var shouldCancelTraversal = false
-let traversalQueue = DispatchQueue(label: "com.screenpipe.traversal")
-
-// Add ScreenPipeDB instance
-var screenPipeDb: ScreenPipeDB?
-
-// Replace the tuple with a struct
-struct WindowIdentifier: Hashable {
- let app: String
- let window: String
-}
-
-// Change the set declaration
-var changedWindows = Set<WindowIdentifier>()
-
-// Add synchronization queue and cleanup flag
-let synchronizationQueue = DispatchQueue(label: "com.screenpipe.synchronization")
-var isCleaningUp = false
-
-// JSON state structure
-struct UIMonitoringState: Codable {
- var ignoredApps: [String]
-
- init(ignoredApps: [String] = []) {
- self.ignoredApps = ignoredApps
- }
-}
-
-// Function to get state file path
-func getStateFilePath() -> String {
- let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
- let appSupportDir = paths[0].appendingPathComponent("screenpipe")
-
- // Create directory if it doesn't exist
- try? FileManager.default.createDirectory(at: appSupportDir, withIntermediateDirectories: true)
-
- return appSupportDir.appendingPathComponent("uiMonitoringLogs.json").path
-}
-
-// Function to load or create state
-func loadOrCreateState() -> UIMonitoringState {
- let path = getStateFilePath()
-
- if let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
- let state = try? JSONDecoder().decode(UIMonitoringState.self, from: data)
- {
- return state
- }
-
- // Create default state with TablePlus ignored
- let defaultState = UIMonitoringState(ignoredApps: ["tableplus"])
-
- // Save default state
- if let encoded = try? JSONEncoder().encode(defaultState) {
- try? encoded.write(to: URL(fileURLWithPath: path))
- }
-
- return defaultState
-}
-
-func startMonitoring() {
- print("entering startMonitoring()")
-
- // Check permissions first
- if !checkAccessibilityPermissions() {
- print("error: accessibility permissions not granted")
- exit(1)
- }
-
- // Set up signal handling
- signal(SIGINT) { _ in
- print("received SIGINT, cleaning up...")
- cleanup()
- exit(0)
- }
-
- // get args
- let args = CommandLine.arguments
- let namedPipePath = args[1]
-
- if namedPipePath.isEmpty {
- print("error: named pipe path is empty")
- exit(1)
- }
-
- // create handle
- let handle = open(namedPipePath, O_WRONLY)
- if handle == -1 {
- print("error: failed to open named pipe")
- exit(1)
- }
-
- setupDatabase()
- print("loaded ui_monitoring logs state")
-
- print("setting up application observer...")
- setupApplicationChangeObserver()
-
- print("monitoring current application...")
- monitorCurrentFrontmostApplication()
-
- Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in
- autoreleasepool {
- saveElementValues()
- }
- }
-
- monitoringEventLoop = CFRunLoopGetCurrent()
- CFRunLoopRun()
-}
-
-func setupDatabase() {
- print("setting up database connection...")
- do {
- screenPipeDb = try ScreenPipeDB()
- print("database connected successfully")
-
- // Create table if not exists (original schema)
- let createTableSQL = """
- CREATE TABLE IF NOT EXISTS ui_monitoring (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- timestamp TEXT,
- app TEXT,
- window TEXT,
- text_output TEXT
- );
- CREATE INDEX IF NOT EXISTS idx_timestamp ON ui_monitoring(timestamp);
- CREATE UNIQUE INDEX IF NOT EXISTS idx_app_window ON ui_monitoring(app, window);
- """
-
- if sqlite3_exec(screenPipeDb?.db, createTableSQL, nil, nil, nil) != SQLITE_OK {
- let error = String(cString: sqlite3_errmsg(screenPipeDb?.db))
- print("error creating table: \(error)")
- 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)
- }
-}
-
-func monitorCurrentFrontmostApplication() {
- // Cancel any in-progress traversal
- if isTraversing {
- shouldCancelTraversal = true
- // Small delay to allow cancellation
- Thread.sleep(forTimeInterval: 0.1)
- }
-
- // Stop previous monitoring if any
- if let observer = currentObserver {
- CFRunLoopRemoveSource(
- CFRunLoopGetCurrent(),
- AXObserverGetRunLoopSource(observer),
- .defaultMode
- )
- currentObserver = nil
- }
-
- // Allow the run loop to process events
- RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01))
-
- guard let app = NSWorkspace.shared.frontmostApplication else {
- print("no frontmost application found")
- return
- }
-
- // Sanitize app name by removing invisible characters and trimming
- let appName = (app.localizedName?.lowercased() ?? "unknown app")
- .components(separatedBy: CharacterSet.controlCharacters).joined()
- .trimmingCharacters(in: .whitespacesAndNewlines)
-
- // First check if app should be ignored
- let state = loadOrCreateState()
- if state.ignoredApps.contains(appName) {
- print("skipping ignored app: \(appName)")
- return
- }
-
- let pid = app.processIdentifier
- let axApp = AXUIElementCreateApplication(pid)
-
- // Get window name BEFORE initializing structures
- var windowName = "unknown window"
- var windowValue: AnyObject?
- let result = AXUIElementCopyAttributeValue(
- axApp, kAXFocusedWindowAttribute as CFString, &windowValue)
- if result == .success, let window = windowValue as! AXUIElement? {
- if let titleValue = getAttributeValue(window, forAttribute: kAXTitleAttribute) as? String {
- // Sanitize window name immediately when we get it
- windowName = titleValue.lowercased()
- .components(separatedBy: CharacterSet.controlCharacters).joined()
- .trimmingCharacters(in: .whitespacesAndNewlines)
- }
- }
-
- // Check if we already have recent data for this window
- let windowExists = globalElementValues[appName]?[windowName] != nil
- let isWindowRecent =
- globalElementValues[appName]?[windowName]?.timestamp.timeIntervalSinceNow ?? -Double
- .infinity > -300 // 5 minutes
-
- // Initialize app and window in the structure if needed
- if globalElementValues[appName] == nil {
- globalElementValues[appName] = [:]
- }
- if globalElementValues[appName]?[windowName] == nil {
- globalElementValues[appName]?[windowName] = WindowState()
- }
-
- if !windowExists || !isWindowRecent {
- // Only traverse if window doesn't exist or data is old
- print("traversing ui elements for \(appName), window: \(windowName)...")
- traverseAndStoreUIElements(axApp, appName: appName, windowName: windowName)
- hasChanges = true
- } else {
- print("reusing existing ui elements for \(appName), window: \(windowName)...")
- }
-
- // Always set up notifications
- setupAccessibilityNotifications(
- pid: pid, axApp: axApp, appName: appName, windowName: windowName)
-
- print("monitoring changes for \(appName), window: \(windowName)...")
-}
-
-func setupApplicationChangeObserver() {
- NSWorkspace.shared.notificationCenter.addObserver(
- forName: NSWorkspace.didActivateApplicationNotification,
- object: nil,
- queue: OperationQueue.main
- ) { notification in
- // Application changed, start monitoring the new frontmost app
- monitorCurrentFrontmostApplication()
- }
-
- NSWorkspace.shared.notificationCenter.addObserver(
- forName: NSWorkspace.activeSpaceDidChangeNotification,
- object: nil,
- queue: OperationQueue.main
- ) { notification in
- // Space changed, update monitoring
- monitorCurrentFrontmostApplication()
- }
-}
-
-func safeAccessibilityCall<T>(_ operation: () -> T?) -> T? {
- return autoreleasepool {
- return withoutActuallyEscaping(operation) { operation in
- return operation()
- }
- }
-}
-
-func getAttributeValue(_ element: AXUIElement, forAttribute attribute: String) -> AnyObject? {
- return safeAccessibilityCall {
- var value: AnyObject?
- let result = AXUIElementCopyAttributeValue(element, attribute as CFString, &value)
- return result == .success ? value : nil
- }
-}
-
-func traverseAndStoreUIElements(_ element: AXUIElement, appName: String, windowName: String) {
- autoreleasepool {
- if isTraversing { return }
-
- isTraversing = true
- shouldCancelTraversal = false
-
- let startTime = DispatchTime.now()
- var visitedElements = Set<AXUIElementWrapper>()
- let unwantedValues = ["0", "", "\u{200E}", "3", "\u{200F}"] // LRM and RLM marks
- let unwantedLabels = [
- "window", "application", "group", "button", "image", "text",
- "pop up button", "region", "notifications", "table", "column",
- "html content",
- ]
- let attributesToCheck = [
- "AXDescription", "AXValue", "AXLabel", "AXRoleDescription", "AXHelp",
- ]
-
- // Add character count tracking
- var totalCharacterCount = 0
-
- func traverse(_ element: AXUIElement, depth: Int) -> ElementAttributes? {
- // Add check for AXMenuBar at the start
- if let role = getAttributeValue(element, forAttribute: "AXRole") as? String,
- role == "AXMenuBar"
- {
- return nil
- }
-
- // Add depth limit check
- if depth > 100 {
- print("max depth reached: depth=\(depth), app=\(appName), window=\(windowName)")
- return nil
- }
-
- // Check for cancellation or character limit
- if shouldCancelTraversal || totalCharacterCount >= 100_000 {
- if totalCharacterCount >= 1_000_000 {
- print("hit 1mln char limit for app: \(appName), window: \(windowName)")
- }
- return nil
- }
-
- let elementWrapper = AXUIElementWrapper(element: element)
-
- guard !visitedElements.contains(elementWrapper) else { return nil }
- visitedElements.insert(elementWrapper)
-
- var attributeNames: CFArray?
- let result = AXUIElementCopyAttributeNames(element, &attributeNames)
-
- guard result == .success, let attributes = attributeNames as? [String] else {
- return nil
- }
-
- var position: CGPoint = .zero
- var size: CGSize = .zero
-
- // Get position
- if let positionValue = getAttributeValue(element, forAttribute: kAXPositionAttribute)
- as! AXValue?,
- AXValueGetType(positionValue) == .cgPoint
- {
- AXValueGetValue(positionValue, .cgPoint, &position)
- }
-
- // Get size
- if let sizeValue = getAttributeValue(element, forAttribute: kAXSizeAttribute)
- as! AXValue?,
- AXValueGetType(sizeValue) == .cgSize
- {
- AXValueGetValue(sizeValue, .cgSize, &size)
- }
-
- // Get element description
- let elementDesc =
- (getAttributeValue(element, forAttribute: "AXRole") as? String) ?? "Unknown"
-
- // Get path
- let (path, depth) = getElementPath(element)
-
- var elementAttributes = ElementAttributes(
- element: elementDesc,
- path: path,
- attributes: [:],
- depth: depth,
- x: position.x,
- y: position.y,
- width: size.width,
- height: size.height,
- children: [],
- timestamp: Date()
- )
-
- var hasRelevantValue = false
-
- for attr in attributes {
- // Check relevant attributes
- if attributesToCheck.contains(attr) {
- if let value = getAttributeValue(element, forAttribute: attr) {
- let valueStr = describeValue(value)
- if !valueStr.isEmpty && !unwantedValues.contains(valueStr)
- && valueStr.count > 1 && !unwantedLabels.contains(valueStr.lowercased())
- {
- // Store attribute and its value
- elementAttributes.attributes[attr] = valueStr
- hasRelevantValue = true
- }
- }
- }
- }
-
- // Traverse child elements
- var childrenElements: [ElementAttributes] = []
- for attr in attributes {
- if let childrenValue = getAttributeValue(element, forAttribute: attr) {
- // Check if it's an array of AXUIElements first
- if let elementArray = childrenValue as? [AXUIElement] {
- if elementArray.count > 1000 {
- print("element at path \(path) has \(elementArray.count) children")
- }
- for childElement in elementArray {
- if let childAttributes = traverse(childElement, depth: depth + 1) {
- childrenElements.append(childAttributes)
- }
- }
- } else if let childElement = childrenValue as! AXUIElement? {
- if let childAttributes = traverse(childElement, depth: depth + 1) {
- childrenElements.append(childAttributes)
- }
- }
- }
- }
- elementAttributes.children = childrenElements
-
- if hasRelevantValue || !childrenElements.isEmpty {
- // Update character count before storing
- if hasRelevantValue {
- for value in elementAttributes.attributes.values {
- totalCharacterCount += value.count
- }
- }
-
- // Store the element with its attributes using identifier as key
- globalElementValues[appName]?[windowName]?.elements[elementAttributes.identifier] =
- elementAttributes
- return elementAttributes
- } else {
- return nil
- }
- }
-
- // Run traversal in dedicated queue
- traversalQueue.async {
- _ = traverse(element, depth: 0)
-
- // Reset state after traversal
- isTraversing = false
- shouldCancelTraversal = false
-
- // Mark window as changed to ensure first scan gets saved
- hasChanges = true
- changedWindows.insert(WindowIdentifier(app: appName, window: windowName))
-
- let uiFrame = UIFrame(
- window: windowName,
- app: appName,
- text_output: "",
- initial_traversal_at: ISO8601DateFormatter().string(from: Date())
- )
- try! writeToPipe(uiFrame: uiFrame)
-
- // Update timestamp after traversal
- globalElementValues[appName]?[windowName]?.timestamp = Date()
-
- let endTime = DispatchTime.now()
- let nanoTime = endTime.uptimeNanoseconds - startTime.uptimeNanoseconds
- let timeInterval = Double(nanoTime) / 1_000_000
- print("\(String(format: "%.2f", timeInterval))ms - ui traversal")
-
- measureGlobalElementValuesSize()
- }
- }
-}
-
-func getRelevantValue(_ element: AXUIElement) -> String? {
- let attributesToCheck = ["AXDescription", "AXValue", "AXLabel", "AXRoleDescription", "AXHelp"]
- let unwantedValues = ["0", "", "\u{200E}", "3", "\u{200F}"] // LRM and RLM marks
- let unwantedLabels = [
- "window", "application", "group", "button", "image", "text",
- "pop up button", "region", "notifications", "table", "column",
- "html content",
- ]
-
- for attr in attributesToCheck {
- if let value = getAttributeValue(element, forAttribute: attr) {
- let valueStr = describeValue(value)
- if !valueStr.isEmpty && !unwantedValues.contains(valueStr) && valueStr.count > 1
- && !unwantedLabels.contains(valueStr.lowercased())
- {
- return valueStr
- }
- }
- }
-
- return nil
-}
-
-func updateElementAndChildren(
- _ element: AXUIElement,
- appName: String,
- windowName: String,
- visitedElements: inout Set<AXUIElementWrapper>
-) -> Bool {
- // Add check for AXMenuBar at the start
- if let role = getAttributeValue(element, forAttribute: "AXRole") as? String,
- role == "AXMenuBar"
- {
- return false
- }
-
- let elementWrapper = AXUIElementWrapper(element: element)
- if visitedElements.contains(elementWrapper) { return false }
- visitedElements.insert(elementWrapper)
-
- var hasUpdates = false
-
- // Get position and size
- var position: CGPoint = .zero
- var size: CGSize = .zero
-
- if let positionValue = getAttributeValue(element, forAttribute: kAXPositionAttribute)
- as! AXValue?,
- AXValueGetType(positionValue) == .cgPoint
- {
- AXValueGetValue(positionValue, .cgPoint, &position)
- }
-
- if let sizeValue = getAttributeValue(element, forAttribute: kAXSizeAttribute) as! AXValue?,
- AXValueGetType(sizeValue) == .cgSize
- {
- AXValueGetValue(sizeValue, .cgSize, &size)
- }
-
- // Get element description and full path with depth
- let elementDesc = (getAttributeValue(element, forAttribute: "AXRole") as? String) ?? "unknown"
- let (path, depth) = getElementPath(element)
-
- // Check if element has relevant value
- if let newValue = getRelevantValue(element) {
- let tempAttributes = ElementAttributes(
- element: elementDesc,
- path: path,
- attributes: ["Value": newValue],
- depth: depth,
- x: position.x,
- y: position.y,
- width: size.width,
- height: size.height,
- children: [],
- timestamp: Date()
- )
- let identifier = tempAttributes.identifier
-
- if globalElementValues[appName]?[windowName]?.elements[identifier] == nil {
- // New element - create and store it directly
- globalElementValues[appName]?[windowName]?.elements[identifier] = tempAttributes
- hasUpdates = true
- } else if globalElementValues[appName]?[windowName]?.elements[identifier]?.attributes[
- "Value"] != newValue
- {
- // Existing element with changed value
- globalElementValues[appName]?[windowName]?.elements[identifier]?.attributes["Value"] =
- newValue
- hasUpdates = true
- }
- }
-
- // Traverse children
- if let children = getAttributeValue(element, forAttribute: kAXChildrenAttribute)
- as? [AXUIElement]
- {
- if children.count > 1000 {
- let (path, _) = getElementPath(element)
- print("element at path \(path) has \(children.count) children")
- }
- for child in children {
- if updateElementAndChildren(
- child, appName: appName, windowName: windowName, visitedElements: &visitedElements)
- {
- hasUpdates = true
- }
- }
- }
-
- return hasUpdates
-}
-
-func handleFocusedWindowChange(element: AXUIElement) {
- guard let app = NSWorkspace.shared.frontmostApplication else { return }
- let appName = app.localizedName?.lowercased() ?? "unknown app"
-
- // Get the new window name
- var windowName = "unknown window"
- if let titleValue = getAttributeValue(element, forAttribute: kAXTitleAttribute) as? String {
- windowName = titleValue.lowercased()
- .components(separatedBy: CharacterSet.controlCharacters).joined()
- .trimmingCharacters(in: .whitespacesAndNewlines)
- }
-
- // Check if this is actually a new window
- let isNewWindow = currentContext?.windowName != windowName
-
- // Update the context
- currentContext = MonitoringContext(appName: appName, windowName: windowName)
-
- // Initialize window state if not present
- if globalElementValues[appName] == nil {
- globalElementValues[appName] = [:]
- }
-
- // If it's a new window, create fresh state
- if isNewWindow {
- globalElementValues[appName]?[windowName] = WindowState()
- print("new window detected: \(windowName)")
- }
-
- // Start traversing the new window
- traverseAndStoreUIElements(element, appName: appName, windowName: windowName)
- hasChanges = true
-}
-
-func axObserverCallback(
- observer: AXObserver, element: AXUIElement, notification: CFString,
- refcon: UnsafeMutableRawPointer?
-) {
- autoreleasepool {
- guard !isCleaningUp else { return }
- guard CFGetTypeID(element) == AXUIElementGetTypeID() else { return }
-
- synchronizationQueue.async {
- // Check for window-related notifications
- let notificationStr = notification as String
- if notificationStr == kAXFocusedWindowChangedNotification as String
- || notificationStr == kAXMainWindowChangedNotification as String
- || notificationStr == kAXTitleChangedNotification as String
- {
-
- // For title changes, we need to check if it's a window
- if notificationStr == kAXTitleChangedNotification as String {
- if let role = getAttributeValue(element, forAttribute: "AXRole") as? String,
- role == "AXWindow"
- {
- handleFocusedWindowChange(element: element)
- return
- }
- } else {
- handleFocusedWindowChange(element: element)
- return
- }
- }
-
- if isCleaningUp || isTraversing { return }
- if currentContext == nil { return } // Simplified check since we don't need the value yet
-
- // Get parent and grandparent
- let parent = getAttributeValue(element, forAttribute: "AXParent") as! AXUIElement?
- var grandparent: AXUIElement? = nil
- if let parent = parent {
- grandparent = getAttributeValue(parent, forAttribute: "AXParent") as! AXUIElement?
- }
-
- // Start from highest available ancestor
- let startElement = grandparent ?? parent ?? element
-
- // Get the depth of the startElement
- let (_, depth) = getElementPath(startElement)
-
- // Add to pending notifications
- pendingNotifications.append((startElement: startElement, depth: depth))
-
- // Reset debounce timer
- debounceTimer?.cancel()
- debounceTimer = nil
-
- // Start a new debounce timer
- debounceTimer = DispatchSource.makeTimerSource(queue: synchronizationQueue)
- debounceTimer?.schedule(deadline: .now() + .milliseconds(200))
- debounceTimer?.setEventHandler {
- processPendingNotifications()
- }
- debounceTimer?.resume()
- }
- }
-}
-
-func processPendingNotifications() {
- if isCleaningUp || isTraversing { return }
- guard let context = currentContext else { return }
-
- let startTime = DispatchTime.now()
-
- autoreleasepool {
- // Find the notification with the startElement of least depth
- guard let selectedNotification = pendingNotifications.min(by: { $0.depth < $1.depth })
- else {
- pendingNotifications.removeAll()
- return
- }
-
- 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))
-
- let uiFrame = UIFrame(
- window: context.windowName,
- app: context.appName,
- text_output: "",
- initial_traversal_at: ISO8601DateFormatter().string(from: Date())
- )
-
- try! writeToPipe(uiFrame: uiFrame)
- }
- }
-
- let endTime = DispatchTime.now()
- let timeInterval = Double(endTime.uptimeNanoseconds - startTime.uptimeNanoseconds) / 1_000_000
- print("\(String(format: "%.2f", timeInterval))ms - processed pending notifications")
-
- // Clear pending notifications and reset debounceTimer
- pendingNotifications.removeAll()
- debounceTimer = nil
-}
-
-func setupAccessibilityNotifications(
- pid: pid_t, axApp: AXUIElement, appName: String, windowName: String
-) {
- // Add safety check for invalid pid
- if pid <= 0 {
- print("invalid pid: \(pid)")
- return
- }
-
- synchronizationQueue.sync {
- currentContext = MonitoringContext(appName: appName, windowName: windowName)
- }
-
- // Add error handling for observer creation
- var observer: AXObserver?
- let createResult = AXObserverCreate(pid, axObserverCallback, &observer)
- if createResult != .success || observer == nil {
- print("failed to create accessibility observer: \(createResult)")
- return
- }
-
- let axObserver = observer!
-
- // Clean up previous observer if exists - no need for source nil check
- if let oldObserver = currentObserver {
- CFRunLoopRemoveSource(
- CFRunLoopGetCurrent(),
- AXObserverGetRunLoopSource(oldObserver),
- .defaultMode
- )
- }
-
- currentObserver = axObserver
-
- // Add source directly - no need for nil check
- CFRunLoopAddSource(
- CFRunLoopGetCurrent(),
- AXObserverGetRunLoopSource(axObserver),
- .defaultMode
- )
-
- // Register notifications for the app
- for (_, notification) in notificationsToObserve {
- let appResult = AXObserverAddNotification(axObserver, axApp, notification as CFString, nil)
- if appResult != .success {
- // Errors are expected for some elements, so we can silently ignore them
- }
- }
-
- // Register notifications for all windows and their elements
- if let windows = getAttributeValue(axApp, forAttribute: kAXWindowsAttribute) as? [AXUIElement] {
- for window in windows {
- registerNotificationsRecursively(element: window, observer: axObserver)
- }
- } else {
- // If we can't get windows, try to register with the main window
- if let mainWindow = getAttributeValue(axApp, forAttribute: kAXMainWindowAttribute)
- as! AXUIElement?
- {
- registerNotificationsRecursively(element: mainWindow, observer: axObserver)
- }
- }
-}
-
-// Recursive function to register notifications on elements
-func registerNotificationsRecursively(element: AXUIElement, observer: AXObserver, depth: Int = 0) {
- // Limit recursion depth to prevent infinite loops
- if depth > 5 { return }
-
- for (_, notification) in notificationsToObserve {
- let result = AXObserverAddNotification(observer, element, notification as CFString, nil)
- if result != .success {
- // Errors are expected for some elements, so we can silently ignore them
- }
- }
-
- // Get children and recursively register notifications
- if let children = getAttributeValue(element, forAttribute: kAXChildrenAttribute)
- as? [AXUIElement]
- {
- for child in children {
- registerNotificationsRecursively(element: child, observer: observer, depth: depth + 1)
- }
- }
-}
-
-func describeValue(_ value: AnyObject?) -> String {
- switch value {
- case let string as String:
- return string.replacingOccurrences(of: "\n", with: "\\n")
- case let number as NSNumber:
- return number.stringValue
- case let point as NSPoint:
- return "(\(point.x), \(point.y))"
- case let size as NSSize:
- return "w=\(size.width) h=\(size.height)"
- case let rect as NSRect:
- return "x=\(rect.origin.x) y=\(rect.origin.y) w=\(rect.size.width) h=\(rect.size.height)"
- case let range as NSRange:
- return "loc=\(range.location) len=\(range.length)"
- case let url as URL:
- return url.absoluteString
- case let array as [AnyObject]:
- return array.isEmpty ? "empty array" : "array with \(array.count) elements"
- case let axValue as AXValue:
- return describeAXValue(axValue)
- case is AXUIElement:
- return "AXUIElement"
- case .none:
- return ""
- default:
- return String(describing: value)
- }
-}
-
-func describeAXValue(_ axValue: AXValue) -> String {
- let type = AXValueGetType(axValue)
- switch type {
- case .cgPoint:
- var point = CGPoint.zero
- AXValueGetValue(axValue, .cgPoint, &point)
- return "(\(point.x), \(point.y))"
- case .cgSize:
- var size = CGSize.zero
- AXValueGetValue(axValue, .cgSize, &size)
- return "w=\(size.width) h=\(size.height)"
- case .cgRect:
- var rect = CGRect.zero
- AXValueGetValue(axValue, .cgRect, &rect)
- return "x=\(rect.origin.x) y=\(rect.origin.y) w=\(rect.size.width) h=\(rect.size.height)"
- case .cfRange:
- var range = CFRange(location: 0, length: 0)
- AXValueGetValue(axValue, .cfRange, &range)
- return "loc=\(range.location) len=\(range.length)"
- default:
- return "unknown AXValue type"
- }
-}
-
-func getElementPath(_ element: AXUIElement) -> (path: String, depth: Int) {
- var path = [String]()
- var current: AXUIElement? = element
- var depth = 0
-
- while current != nil {
- if let role = getAttributeValue(current!, forAttribute: "AXRole") as? String {
- var elementDesc = role
- if let title = getAttributeValue(current!, forAttribute: "AXTitle") as? String,
- !title.isEmpty
- {
- elementDesc += "[\(title)]"
- }
- path.append(elementDesc)
- depth += 1
- }
-
- // Get parent
- current = getAttributeValue(current!, forAttribute: "AXParent") as! AXUIElement?
- }
-
- // Reverse path but depth is already correct
- return (path.reversed().joined(separator: " -> "), depth - 1)
-}
-
-func buildTextOutput(from windowState: WindowState) -> String {
- var textOutput = ""
- var processedElements = Set<String>()
- var seenTexts = Set<String>() // Track unique text values
-
- // Helper function to process text values
- func processText(_ text: String) -> String {
- if seenTexts.contains(text) {
- return "" // Return empty string for duplicate text
- }
- seenTexts.insert(text)
- return "[\(text)]"
- }
-
- // Process hierarchical elements
- func processElement(_ elementAttributes: ElementAttributes, indentLevel: Int) {
- // One space per level
- let indentStr = String(repeating: " ", count: indentLevel)
-
- // Process each attribute value and join with spaces
- let text = elementAttributes.attributes.values
- .filter { !seenTexts.contains($0) }
- .map {
- seenTexts.insert($0)
- return "[\($0)]"
- }
- .joined(separator: " ")
-
- if !text.isEmpty {
- textOutput += "\(indentStr)\(text)\n"
- }
-
- // Mark as processed using identifier
- processedElements.insert(elementAttributes.identifier)
-
- // Recursively process children
- let sortedChildren = elementAttributes.children.sorted { (e1, e2) -> Bool in
- if abs(e1.y - e2.y) < 10 {
- return e1.x < e2.x
- }
- return e1.y < e2.y
- }
-
- for child in sortedChildren {
- processElement(child, indentLevel: indentLevel + 1)
- }
- }
-
- // Process root elements first (hierarchical)
- let rootElements = windowState.elements.values.filter { $0.depth == 0 }
- let sortedRootElements = rootElements.sorted { (e1, e2) -> Bool in
- if abs(e1.y - e2.y) < 10 {
- return e1.x < e2.x
- }
- return e1.y < e2.y
- }
-
- for rootElement in sortedRootElements {
- processElement(rootElement, indentLevel: 0)
- }
-
- // Then process any orphaned elements
- let orphanElements = windowState.elements.filter { !processedElements.contains($0.key) }
- if !orphanElements.isEmpty {
- 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
- if e1.timestamp == e2.timestamp {
- if abs(e1.y - e2.y) < 10 {
- return e1.x < e2.x
- }
- return e1.y < e2.y
- }
- return e1.timestamp < e2.timestamp
- }
-
- for element in sortedOrphans {
- // One space per depth level
- let indentStr = String(repeating: " ", count: element.depth)
- let text = element.attributes.values
- .filter { !seenTexts.contains($0) }
- .map {
- seenTexts.insert($0)
- return "[\($0)]"
- }
- .joined(separator: " ")
-
- if !text.isEmpty {
- textOutput += "\(indentStr)\(text)\n"
- }
- }
- }
-
- return textOutput
-}
-
-func saveToDatabase(windowId: WindowIdentifier, newTextOutput: String, timestamp: String) {
- guard let db = screenPipeDb?.db else {
- print("database not initialized")
- return
- }
-
- let startTime = DispatchTime.now()
- let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
- let MAX_CHARS = 300_000
-
- // Sanitize window name by removing invisible characters
- let sanitizedWindow = windowId.window
- .components(separatedBy: CharacterSet.controlCharacters).joined()
- .trimmingCharacters(in: .whitespacesAndNewlines)
- let sanitizedApp = windowId.app
- .components(separatedBy: CharacterSet.controlCharacters).joined()
- .trimmingCharacters(in: .whitespacesAndNewlines)
-
- let uiFrame = UIFrame(
- window: windowId.window,
- app: windowId.app,
- text_output: newTextOutput,
- initial_traversal_at: timestamp
- )
-
- try! writeToPipe(uiFrame: uiFrame)
-
- // 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?
-
- if sqlite3_prepare_v2(db, selectSQL, -1, &selectStmt, nil) == SQLITE_OK {
- sqlite3_bind_text(selectStmt, 1, sanitizedApp, -1, SQLITE_TRANSIENT)
- 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)
- }
- }
- sqlite3_finalize(selectStmt)
- }
-
- // Split and clean lines - only trim trailing whitespace, preserve leading
- let existingLines = existingText.components(separatedBy: "\n")
- .map { $0.trimmingCharacters(in: .whitespaces.subtracting(.init(charactersIn: " "))) }
- .filter { !$0.isEmpty }
- let newLines = newTextOutput.components(separatedBy: "\n")
- .map { $0.trimmingCharacters(in: .whitespaces.subtracting(.init(charactersIn: " "))) }
- .filter { !$0.isEmpty }
-
- var extensionsFound = 0
- var exactMatchesFound = 0
- var newCharsCount = 0
-
- let uniqueNewLines = newLines.filter { newLine in
- let strippedNewLine = newLine.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
- .trimmingCharacters(in: .whitespaces)
- return !existingLines.contains { existingLine in
- let strippedExistingLine = existingLine.trimmingCharacters(
- in: CharacterSet(charactersIn: "[]")
- )
- .trimmingCharacters(in: .whitespaces)
-
- if strippedExistingLine == strippedNewLine {
- exactMatchesFound += 1
- return true
- }
-
- if strippedExistingLine.count < strippedNewLine.count
- && strippedNewLine.contains(strippedExistingLine)
- {
- extensionsFound += 1
- // Count additional characters in the extension
- newCharsCount += (strippedNewLine.count - strippedExistingLine.count)
- return true
- }
-
- return false
- }
- }
-
- // Skip if no unique lines or extensions found
- if uniqueNewLines.isEmpty && extensionsFound == 0 {
- // 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
- }
-
- // Add characters from unique new lines
- newCharsCount += uniqueNewLines.reduce(0) { $0 + $1.count }
-
- // Process only if we have unique lines
- let allLines = existingLines + uniqueNewLines
-
- // Trim older lines if total length exceeds limit
- var totalChars = 0
- var startIndex = 0
-
- for (index, line) in allLines.enumerated().reversed() {
- totalChars += line.count + 1 // +1 for newline
- if totalChars > MAX_CHARS {
- startIndex = index + 1
- break
- }
- }
-
- let finalText = allLines[startIndex...].joined(separator: "\n")
-
- // 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 = ?;
- """
-
- 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)
-
- // comment spam
- // 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 (?, ?, ?, ?, ?);
- """
-
- 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()
- let timeInterval = Double(endTime.uptimeNanoseconds - startTime.uptimeNanoseconds) / 1_000_000
- print(
- "\(String(format: "%.2f", timeInterval))ms - saved to db for \(windowId.app)/\(String(windowId.window.prefix(30)))... (\(uniqueNewLines.count) new lines, \(extensionsFound) extensions, \(newCharsCount) new chars), skipped \(exactMatchesFound) exact matches"
- )
-}
-
-func saveElementValues() {
- // 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
- }
-
- // Build text output
- let textOutput = buildTextOutput(from: windowState)
- totalChars += textOutput.count
-
- // Store the formatted text output in the window state
- globalElementValues[windowId.app]?[windowId.window]?.textOutput = textOutput
-
- // Save to database
- 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
-}
-
-// Add proper cleanup on exit
-func cleanup() {
- // Indicate that cleanup has started
- synchronizationQueue.sync {
- isCleaningUp = true
- }
-
- close(handle)
-
- // Remove observer from run loop
- if let observer = currentObserver {
- CFRunLoopRemoveSource(
- CFRunLoopGetCurrent(),
- AXObserverGetRunLoopSource(observer),
- .defaultMode
- )
- currentObserver = nil
- }
-
- // Clear database reference
- screenPipeDb = nil
-
- // Clear global state
- globalElementValues.removeAll()
- currentContext = nil
-}
-
-func pruneGlobalState() {
- let MAX_SIZE_MB = 10.0
- let MAX_SIZE_BYTES = MAX_SIZE_MB * 1024 * 1024 / 2 // Divide by 2 since String uses 2 bytes per char
-
- var totalSize = 0
- var elementsByTimestamp: [(app: String, window: String, timestamp: Date, size: Int)] = []
-
- // Calculate sizes and collect timestamps
- for (app, windows) in globalElementValues {
- for (window, windowState) in windows {
- var windowSize = 0
- for element in windowState.elements.values {
- windowSize += element.attributes.values.reduce(0) { $0 + $1.count }
- }
- totalSize += windowSize
- elementsByTimestamp.append((app, window, windowState.timestamp, windowSize))
- }
- }
-
- // If we're under the limit, no need to prune
- if Double(totalSize) <= MAX_SIZE_BYTES {
- return
- }
-
- print(
- "pruning global state: current size \(String(format: "%.2f", Double(totalSize) * 2 / 1024 / 1024))mb"
- )
-
- // Sort by timestamp (oldest first)
- elementsByTimestamp.sort { $0.timestamp < $1.timestamp }
-
- // Remove oldest entries until we're under the limit
- var removedSize = 0
- for entry in elementsByTimestamp {
- if Double(totalSize - removedSize) <= MAX_SIZE_BYTES {
- break
- }
-
- globalElementValues[entry.app]?[entry.window] = nil
- if globalElementValues[entry.app]?.isEmpty == true {
- globalElementValues.removeValue(forKey: entry.app)
- }
-
- removedSize += entry.size
- print(
- "pruned \(entry.app)/\(entry.window): \(String(format: "%.2f", Double(entry.size) * 2 / 1024))kb"
- )
- }
-
- print(
- "pruned global state to \(String(format: "%.2f", Double(totalSize - removedSize) * 2 / 1024 / 1024))mb"
- )
-}
-
-func measureGlobalElementValuesSize() {
- var totalElements = 0
- var totalAttributes = 0
- var totalStringLength = 0
-
- for (_, windows) in globalElementValues {
- for (_, windowState) in windows {
- totalElements += windowState.elements.count
- totalAttributes += windowState.elements.values.reduce(0) { $0 + $1.attributes.count }
- totalStringLength += windowState.elements.values.reduce(0) {
- $0 + $1.attributes.values.reduce(0) { $0 + $1.count }
- }
- }
- }
-
- let mbSize = Double(totalStringLength) * 2 / 1024.0 / 1024.0
- print("global state size: \(String(format: "%.3f", mbSize))mb")
-
- // Add pruning check
- if mbSize > 10.0 {
- pruneGlobalState()
- }
-}
-
-public class UIMonitor {
- private static var shared: UIMonitor?
- private var isRunning = false
-
- public static func getInstance() -> UIMonitor {
- if shared == nil {
- shared = UIMonitor()
- }
- return shared!
- }
-
- // Start monitoring in background
- public func start() {
- if isRunning { return }
- isRunning = true
-
- DispatchQueue.global(qos: .background).async {
- startMonitoring()
- }
- }
-
- // Stop monitoring
- public func stop() {
- if !isRunning { return }
- cleanup()
- isRunning = false
- }
-
- // Get current text output for specific app/window
- public func getCurrentOutput(app: String, window: String? = nil) -> String? {
- let appName = app.lowercased()
-
- if let windowName = window?.lowercased() {
- if let windowState = globalElementValues[appName]?[windowName] {
- return buildTextOutput(from: windowState)
- }
- return nil
- }
-
- // If no window specified, return all windows' output concatenated
- var outputs: [String] = []
- if let windows = globalElementValues[appName] {
- for (windowName, windowState) in windows {
- let output = buildTextOutput(from: windowState)
- outputs.append("Window: \(windowName)\n\(output)")
- }
- }
- return outputs.isEmpty ? nil : outputs.joined(separator: "\n---\n")
- }
-
- // Get all current apps being monitored
- public func getMonitoredApps() -> [String] {
- return Array(globalElementValues.keys)
- }
-
- // Get all windows for a specific app
- public func getWindowsForApp(_ app: String) -> [String] {
- return globalElementValues[app.lowercased()]?.keys.map { $0 } ?? []
- }
-}
-
-// Wrapper for AXUIElement
-struct AXUIElementWrapper: Hashable {
- let element: AXUIElement
-
- func hash(into hasher: inout Hasher) {
- hasher.combine(CFHash(element))
- }
-
- static func == (lhs: AXUIElementWrapper, rhs: AXUIElementWrapper) -> Bool {
- return CFEqual(lhs.element, rhs.element)
- }
-}
-
-// Get the universal screenpipe database path
-func getScreenPipeDbPath() -> String {
- let homeDir = FileManager.default.homeDirectoryForCurrentUser
- return homeDir.appendingPathComponent(".screenpipe/db.sqlite").path
-}
-
-// Database connection helper
-class ScreenPipeDB {
- let db: OpaquePointer
-
- init() throws {
- var dbPointer: OpaquePointer?
- let dbPath = getScreenPipeDbPath()
-
- // Create directory if it doesn't exist
- let dbDir = (dbPath as NSString).deletingLastPathComponent
- try? FileManager.default.createDirectory(atPath: dbDir, withIntermediateDirectories: true)
-
- if sqlite3_open(dbPath, &dbPointer) != SQLITE_OK {
- throw NSError(
- domain: "db error", code: 1,
- userInfo: [NSLocalizedDescriptionKey: "failed to open database"])
- }
-
- guard let db = dbPointer else {
- throw NSError(
- domain: "db error", code: 2,
- userInfo: [NSLocalizedDescriptionKey: "database pointer is nil"])
- }
-
- self.db = db
- }
-
- deinit {
- sqlite3_close(db)
- }
-}
-
-func writeToPipe(uiFrame: UIFrame) throws {
- let message = uiFrame.toBytes()
- // let bytesWritten = message.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
- // write(handle, buffer.baseAddress, message.count)
- // }
- // if bytesWritten == -1 {
- // perror("error writing to pipe")
- // }
-
- var totalWritten = 0
- while totalWritten < message.count {
- let bytesWritten = message.withUnsafeBytes { buffer in
- write(
- handle,
- buffer.baseAddress?.advanced(by: totalWritten),
- message.count - totalWritten)
- }
- guard bytesWritten != -1 else {
- throw NSError(
- domain: "pipe error", code: 3,
- userInfo: [NSLocalizedDescriptionKey: String(cString: strerror(errno))])
- }
- totalWritten += bytesWritten
- }
-}
-
-guard CommandLine.arguments.count > 1 else {
- print("error: named pipe path not provided")
- exit(1)
-}
-
-let namedPipePath = CommandLine.arguments[1]
-
-// Check if the path is valid and is a named pipe
-var statInfo = stat()
-if stat(namedPipePath, &statInfo) != 0 || (statInfo.st_mode & S_IFMT) != S_IFIFO {
- print("error: invalid named pipe path or not a named pipe")
- exit(1)
-}
-
-let handle = open(namedPipePath, O_WRONLY)
-if handle == -1 {
- perror("error: failed to open named pipe")
- exit(1)
-}
-
-startMonitoring()