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

fix: #228 and improve status state refresh

Louis Beaumontf6471ce891a5
diff --git a/screenpipe-app-tauri/components/dev-mode-settings.tsx b/screenpipe-app-tauri/components/dev-mode-settings.tsx
new file mode 100644
index 000000000..fc3fe194c
--- /dev/null
+++ b/screenpipe-app-tauri/components/dev-mode-settings.tsx
@@ -0,0 +1,342 @@
+"use client";
+import React, { useState, useEffect } from "react";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { CodeBlock } from "@/components/ui/codeblock";
+import { platform } from "@tauri-apps/plugin-os";
+import { MarkdownWithExternalLinks } from "./markdown-with-external-links";
+import { Badge } from "./ui/badge";
+import { Label } from "./ui/label";
+import { Switch } from "./ui/switch";
+import { useSettings } from "@/lib/hooks/use-settings";
+import { invoke } from "@tauri-apps/api/core";
+import { toast, useToast } from "./ui/use-toast";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "./ui/tooltip";
+import { Button } from "./ui/button";
+import { Separator } from "./ui/separator";
+import { Card, CardContent, CardFooter } from "./ui/card";
+import { useHealthCheck } from "@/lib/hooks/use-health-check";
+import { Lock, Folder, FileText, Activity, Wrench } from "lucide-react";
+import { open } from "@tauri-apps/plugin-shell";
+import { homeDir } from "@tauri-apps/api/path";
+import LogViewer from "./log-viewer-v2";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import { Command } from "@tauri-apps/plugin-shell";
+import { CliCommandDialog } from "./cli-command-dialog";
+import { LogFileButton } from "./log-file-button";
+
+const getDebuggingCommands = (os: string | null) => {
+ let cliInstructions = "";
+
+ if (os === "windows") {
+ cliInstructions =
+ "# 1. Open Command Prompt as admin (search for 'cmd' in the Start menu, right click, 'Run as admin')\n# 2. Navigate to: %LOCALAPPDATA%\\screenpipe\\\n# Type: cd %LOCALAPPDATA%\\screenpipe\n";
+ } else if (os === "macos") {
+ cliInstructions =
+ "# 1. Open Terminal\n# 2. Navigate to: /Applications/screenpipe.app/Contents/MacOS/\n# Type: cd /Applications/screenpipe.app/Contents/MacOS/\n";
+ } else if (os === "linux") {
+ cliInstructions =
+ "# 1. Open Terminal\n# 2. Navigate to: /usr/local/bin/\n# Type: cd /usr/local/bin/\n";
+ } else {
+ cliInstructions =
+ "# OS not recognized. Please check the documentation for your specific operating system.\n";
+ }
+
+ const baseInstructions = `# First, view the Screenpipe CLI arguments:
+ ${cliInstructions}
+ # 3. Run: screenpipe -h
+ # 4. Choose your preferred setup and start Screenpipe:
+ # (Replace [YOUR_ARGS] with your chosen arguments)
+ # Example: screenpipe --fps 1 `;
+
+ const dataDir =
+ os === "windows" ? "%USERPROFILE%\\.screenpipe" : "$HOME/.screenpipe";
+
+ const logPath =
+ os === "windows"
+ ? `%USERPROFILE%\\.screenpipe\\screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`
+ : `$HOME/.screenpipe/screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`;
+
+ const dbPath =
+ os === "windows"
+ ? "%USERPROFILE%\\.screenpipe\\db.sqlite"
+ : "$HOME/.screenpipe/db.sqlite";
+
+ const baseCommand =
+ baseInstructions +
+ dataDir +
+ (os === "windows"
+ ? "\n\n# We highly recommend adding --ocr-engine windows-native to your command.\n# This will use a very experimental but powerful engine to extract text from your screen instead of the default one.\n# Example: screenpipe --data-dir %USERPROFILE%\\.screenpipe --ocr-engine windows-native\n"
+ : "") +
+ "\n\n# 5. If you've already started Screenpipe, try these debugging commands:\n";
+
+ if (os === "windows") {
+ return (
+ baseCommand +
+ `# Stream the log:
+ type "${logPath}"
+
+ # Scroll the logs:
+ more "${logPath}"
+
+ # View last 10 frames:
+ sqlite3 "${dbPath}" "SELECT * FROM frames ORDER BY timestamp DESC LIMIT 10;"
+
+ # View last 10 audio transcriptions:
+ sqlite3 "${dbPath}" "SELECT * FROM audio_transcriptions ORDER BY timestamp DESC LIMIT 10;"`
+ );
+ } else if (os === "macos" || os === "linux") {
+ return (
+ baseCommand +
+ `# Stream the log:
+ tail -f "${logPath}"
+
+ # Scroll the logs:
+ less "${logPath}"
+
+ # View last 10 frames:
+ sqlite3 "${dbPath}" "SELECT * FROM frames ORDER BY timestamp DESC LIMIT 10;"
+
+ # View last 10 audio transcriptions:
+ sqlite3 "${dbPath}" "SELECT * FROM audio_transcriptions ORDER BY timestamp DESC LIMIT 10;"`
+ );
+ } else {
+ return "OS not recognized. \n\nPlease check the documentation for your specific operating system.";
+ }
+};
+
+export const DevModeSettings = () => {
+ const { settings, updateSettings } = useSettings();
+ const [localSettings, setLocalSettings] = useState(settings);
+ const handleDevModeToggle = async (checked: boolean) => {
+ try {
+ await updateSettings({ devMode: checked });
+ setLocalSettings({ ...localSettings, devMode: checked });
+ } catch (error) {
+ console.error("Failed to update dev mode:", error);
+ // Add error handling, e.g., show a toast notification
+ }
+ };
+ const [isLoading, setIsLoading] = useState(false);
+ const { toast } = useToast();
+
+ useEffect(() => {
+ setLocalSettings(settings);
+ }, [settings]);
+
+ const handleStartScreenpipe = async () => {
+ setIsLoading(true);
+ const toastId = toast({
+ title: "starting screenpipe",
+ description: "please wait...",
+ duration: Infinity,
+ });
+ try {
+ await invoke("spawn_screenpipe");
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ toastId.update({
+ id: toastId.id,
+ title: "screenpipe started",
+ description: "screenpipe is now running.",
+ duration: 3000,
+ });
+ } catch (error) {
+ console.error("failed to start screenpipe:", error);
+ toastId.update({
+ id: toastId.id,
+ title: "error",
+ description: "failed to start screenpipe.",
+ variant: "destructive",
+ duration: 3000,
+ });
+ } finally {
+ toastId.dismiss();
+ setIsLoading(false);
+ }
+ };
+
+ const handleStopScreenpipe = async () => {
+ setIsLoading(true);
+ const toastId = toast({
+ title: "stopping screenpipe",
+ description: "please wait...",
+ duration: Infinity,
+ });
+ try {
+ await invoke("kill_all_sreenpipes");
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ toastId.update({
+ id: toastId.id,
+ title: "screenpipe stopped",
+ description: "screenpipe is now stopped.",
+ duration: 3000,
+ });
+ } catch (error) {
+ console.error("failed to stop screenpipe:", error);
+ toastId.update({
+ id: toastId.id,
+ title: "error",
+ description: "failed to stop screenpipe.",
+ variant: "destructive",
+ duration: 3000,
+ });
+ } finally {
+ toastId.dismiss();
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <>
+ <div className="w-full my-4">
+ <div className="flex justify-around">
+ <Card className="p-4 relative">
+ <CardContent>
+ <div className="flex flex-col space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-2">
+ <Label htmlFor="dev-mode">enable dev mode</Label>
+ <Switch
+ id="dev-mode"
+ checked={localSettings.devMode}
+ onCheckedChange={handleDevModeToggle}
+ />
+ </div>
+ <div className="absolute top-2 right-2">
+ <CliCommandDialog localSettings={localSettings} />
+ </div>
+ </div>
+ <p className="text-sm text-muted-foreground mb-4">
+ on = use CLI for more control
+ <br />
+ in dev mode, backend won&apos;t <br />
+ auto start when starting the app
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+
+ <div className="relative">
+ <Badge className="text-xs absolute -top-3 left-1/2 transform -translate-x-1/2 z-10">
+ expert only
+ </Badge>
+ <Card className="p-4">
+ <CardContent>
+ <div className="flex items-center space-x-2">
+ <div className="flex flex-col items-center w-full">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ onClick={handleStopScreenpipe}
+ disabled={isLoading}
+ className="text-xs w-full"
+ >
+ stop
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>stop screenpipe backend</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ <div className="flex flex-col items-center w-full">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ onClick={handleStartScreenpipe}
+ disabled={isLoading}
+ className="text-xs w-full"
+ >
+ start
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>start screenpipe backend</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </div>
+ </CardContent>
+ <CardFooter className="flex flex-col items-center">
+ <p className="text-sm text-muted-foreground">
+ start or stop screenpipe backend
+ </p>
+ <p className="text-xs text-muted-foreground">
+ (auto started when dev mode is off)
+ </p>
+ </CardFooter>
+ </Card>
+ </div>
+ </div>
+ </div>
+ {/* vertical separator */}
+ <Separator orientation="vertical" />
+ {settings.devMode === true && (
+ <>
+ <p className="font-bold my-2">
+ did you run screenpipe backend? either click start on the right, or
+ thru CLI 👇
+ </p>
+ <CodeBlock language="bash" value={getDebuggingCommands(platform())} />
+
+ <div className="mt-4 text-sm text-gray-500">
+ <p>or, for more advanced queries:</p>
+ <ol className="list-decimal list-inside mt-2">
+ <li>
+ <a
+ href="https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-server/src/db.rs"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-500 hover:underline"
+ >
+ go to the database schema
+ </a>
+ </li>
+ <li>Copy the entire page (Cmd+A, Cmd+C)</li>
+ <li>Paste into ChatGPT (Cmd+V)</li>
+ <li>
+ ask: &quot;give me 10 sqlite query CLI to look up my data. My db
+ is in $HOME/.screenpipe/db.sqlite&quot;
+ </li>
+ </ol>
+ <p className="mt-2">
+ or if you prefer using curl, follow the same steps with the{" "}
+ <a
+ href="https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-server/src/server.rs"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-500 hover:underline"
+ >
+ server.rs file
+ </a>{" "}
+ and ask ChatGPT for curl commands to interact with the API.
+ </p>
+ </div>
+ </>
+ )}
+ </>
+ );
+};
diff --git a/screenpipe-app-tauri/components/log-file-button.tsx b/screenpipe-app-tauri/components/log-file-button.tsx
new file mode 100644
index 000000000..049e8feea
--- /dev/null
+++ b/screenpipe-app-tauri/components/log-file-button.tsx
@@ -0,0 +1,57 @@
+import { homeDir } from "@tauri-apps/api/path";
+import { useToast } from "./ui/use-toast";
+import { platform } from "@tauri-apps/plugin-os";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "./ui/tooltip";
+import { Button } from "./ui/button";
+import { FileText } from "lucide-react";
+import { open } from "@tauri-apps/plugin-shell";
+
+export const LogFileButton = ({ className }: { className?: string }) => {
+ const { toast } = useToast();
+ const handleOpenLogFile = async () => {
+ try {
+ const homeDirPath = await homeDir();
+ const logPath =
+ platform() === "windows"
+ ? `${homeDirPath}\\.screenpipe\\screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`
+ : `${homeDirPath}/.screenpipe/screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`;
+ await open(logPath);
+ } catch (error) {
+ console.error("failed to open log file:", error);
+ toast({
+ title: "error",
+ description: "failed to open log file.",
+ variant: "destructive",
+ duration: 3000,
+ });
+ }
+ };
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleOpenLogFile}
+ className="ml-2"
+ >
+ <FileText className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>open log file</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+};
diff --git a/screenpipe-app-tauri/components/meeting-history.tsx b/screenpipe-app-tauri/components/meeting-history.tsx
index afdb4110d..cbcf74fe4 100644
--- a/screenpipe-app-tauri/components/meeting-history.tsx
+++ b/screenpipe-app-tauri/components/meeting-history.tsx
@@ -177,9 +177,9 @@ export default function MeetingHistory() {
console.log("fetching meetings...");
setLoading(true);
try {
- // Always fetch from the last 24 hours
+ // Always fetch from the last 7x24 hours
const startTime = new Date(
- Date.now() - 24 * 60 * 60 * 1000
+ Date.now() - 7 * 24 * 60 * 60 * 1000
).toISOString();
console.log("searching from:", startTime);
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsx
index a24e85ec9..9ad2d9d03 100644
--- a/screenpipe-app-tauri/components/pipe-store.tsx
+++ b/screenpipe-app-tauri/components/pipe-store.tsx
@@ -49,7 +49,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
-import { LogFileButton } from "./screenpipe-status";
+import { LogFileButton } from "./log-file-button";
export interface Pipe {
enabled: boolean;
diff --git a/screenpipe-app-tauri/components/screenpipe-status.tsx b/screenpipe-app-tauri/components/screenpipe-status.tsx
index e16a3100b..0eb09f713 100644
--- a/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -36,309 +36,8 @@ import {
} from "@/components/ui/collapsible";
import { Command } from "@tauri-apps/plugin-shell";
import { CliCommandDialog } from "./cli-command-dialog";
-
-const getDebuggingCommands = (os: string | null) => {
- let cliInstructions = "";
-
- if (os === "windows") {
- cliInstructions =
- "# 1. Open Command Prompt as admin (search for 'cmd' in the Start menu, right click, 'Run as admin')\n# 2. Navigate to: %LOCALAPPDATA%\\screenpipe\\\n# Type: cd %LOCALAPPDATA%\\screenpipe\n";
- } else if (os === "macos") {
- cliInstructions =
- "# 1. Open Terminal\n# 2. Navigate to: /Applications/screenpipe.app/Contents/MacOS/\n# Type: cd /Applications/screenpipe.app/Contents/MacOS/\n";
- } else if (os === "linux") {
- cliInstructions =
- "# 1. Open Terminal\n# 2. Navigate to: /usr/local/bin/\n# Type: cd /usr/local/bin/\n";
- } else {
- cliInstructions =
- "# OS not recognized. Please check the documentation for your specific operating system.\n";
- }
-
- const baseInstructions = `# First, view the Screenpipe CLI arguments:
-${cliInstructions}
-# 3. Run: screenpipe -h
-# 4. Choose your preferred setup and start Screenpipe:
-# (Replace [YOUR_ARGS] with your chosen arguments)
-# Example: screenpipe --fps 1 `;
-
- const dataDir =
- os === "windows" ? "%USERPROFILE%\\.screenpipe" : "$HOME/.screenpipe";
-
- const logPath =
- os === "windows"
- ? `%USERPROFILE%\\.screenpipe\\screenpipe.${
- new Date().toISOString().split("T")[0]
- }.log`
- : `$HOME/.screenpipe/screenpipe.${
- new Date().toISOString().split("T")[0]
- }.log`;
-
- const dbPath =
- os === "windows"
- ? "%USERPROFILE%\\.screenpipe\\db.sqlite"
- : "$HOME/.screenpipe/db.sqlite";
-
- const baseCommand =
- baseInstructions +
- dataDir +
- (os === "windows"
- ? "\n\n# We highly recommend adding --ocr-engine windows-native to your command.\n# This will use a very experimental but powerful engine to extract text from your screen instead of the default one.\n# Example: screenpipe --data-dir %USERPROFILE%\\.screenpipe --ocr-engine windows-native\n"
- : "") +
- "\n\n# 5. If you've already started Screenpipe, try these debugging commands:\n";
-
- if (os === "windows") {
- return (
- baseCommand +
- `# Stream the log:
-type "${logPath}"
-
-# Scroll the logs:
-more "${logPath}"
-
-# View last 10 frames:
-sqlite3 "${dbPath}" "SELECT * FROM frames ORDER BY timestamp DESC LIMIT 10;"
-
-# View last 10 audio transcriptions:
-sqlite3 "${dbPath}" "SELECT * FROM audio_transcriptions ORDER BY timestamp DESC LIMIT 10;"`
- );
- } else if (os === "macos" || os === "linux") {
- return (
- baseCommand +
- `# Stream the log:
-tail -f "${logPath}"
-
-# Scroll the logs:
-less "${logPath}"
-
-# View last 10 frames:
-sqlite3 "${dbPath}" "SELECT * FROM frames ORDER BY timestamp DESC LIMIT 10;"
-
-# View last 10 audio transcriptions:
-sqlite3 "${dbPath}" "SELECT * FROM audio_transcriptions ORDER BY timestamp DESC LIMIT 10;"`
- );
- } else {
- return "OS not recognized. \n\nPlease check the documentation for your specific operating system.";
- }
-};
-
-const DevModeSettings = () => {
- const { settings, updateSettings } = useSettings();
- const [localSettings, setLocalSettings] = useState(settings);
- const handleDevModeToggle = async (checked: boolean) => {
- try {
- await updateSettings({ devMode: checked });
- setLocalSettings({ ...localSettings, devMode: checked });
- } catch (error) {
- console.error("Failed to update dev mode:", error);
- // Add error handling, e.g., show a toast notification
- }
- };
- const [isLoading, setIsLoading] = useState(false);
- const { toast } = useToast();
-
- useEffect(() => {
- setLocalSettings(settings);
- }, [settings]);
-
- const handleStartScreenpipe = async () => {
- setIsLoading(true);
- const toastId = toast({
- title: "starting screenpipe",
- description: "please wait...",
- duration: Infinity,
- });
- try {
- await invoke("spawn_screenpipe");
- await new Promise((resolve) => setTimeout(resolve, 2000));
- toastId.update({
- id: toastId.id,
- title: "screenpipe started",
- description: "screenpipe is now running.",
- duration: 3000,
- });
- } catch (error) {
- console.error("failed to start screenpipe:", error);
- toastId.update({
- id: toastId.id,
- title: "error",
- description: "failed to start screenpipe.",
- variant: "destructive",
- duration: 3000,
- });
- } finally {
- toastId.dismiss();
- setIsLoading(false);
- }
- };
-
- const handleStopScreenpipe = async () => {
- setIsLoading(true);
- const toastId = toast({
- title: "stopping screenpipe",
- description: "please wait...",
- duration: Infinity,
- });
- try {
- await invoke("kill_all_sreenpipes");
- await new Promise((resolve) => setTimeout(resolve, 2000));
- toastId.update({
- id: toastId.id,
- title: "screenpipe stopped",
- description: "screenpipe is now stopped.",
- duration: 3000,
- });
- } catch (error) {
- console.error("failed to stop screenpipe:", error);
- toastId.update({
- id: toastId.id,
- title: "error",
- description: "failed to stop screenpipe.",
- variant: "destructive",
- duration: 3000,
- });
- } finally {
- toastId.dismiss();
- setIsLoading(false);
- }
- };
-
- return (
- <>
- <div className="w-full my-4">
- <div className="flex justify-around">
- <Card className="p-4 relative">
- <CardContent>
- <div className="flex flex-col space-y-2">
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-2">
- <Label htmlFor="dev-mode">enable dev mode</Label>
- <Switch
- id="dev-mode"
- checked={localSettings.devMode}
- onCheckedChange={handleDevModeToggle}
- />
- </div>
- <div className="absolute top-2 right-2">
- <CliCommandDialog localSettings={localSettings} />
- </div>
- </div>
- <p className="text-sm text-muted-foreground mb-4">
- on = use CLI for more control
- <br />
- in dev mode, backend won&apos;t <br />
- auto start when starting the app
- </p>
- </div>
- </CardContent>
- </Card>
-
- <div className="relative">
- <Badge className="text-xs absolute -top-3 left-1/2 transform -translate-x-1/2 z-10">
- expert only
- </Badge>
- <Card className="p-4">
- <CardContent>
- <div className="flex items-center space-x-2">
- <div className="flex flex-col items-center w-full">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- onClick={handleStopScreenpipe}
- disabled={isLoading}
- className="text-xs w-full"
- >
- stop
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>stop screenpipe backend</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <div className="flex flex-col items-center w-full">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- onClick={handleStartScreenpipe}
- disabled={isLoading}
- className="text-xs w-full"
- >
- start
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>start screenpipe backend</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </div>
- </CardContent>
- <CardFooter className="flex flex-col items-center">
- <p className="text-sm text-muted-foreground">
- start or stop screenpipe backend
- </p>
- <p className="text-xs text-muted-foreground">
- (auto started when dev mode is off)
- </p>
- </CardFooter>
- </Card>
- </div>
- </div>
- </div>
- {/* vertical separator */}
- <Separator orientation="vertical" />
- {settings.devMode === true && (
- <>
- <p className="font-bold my-2">
- did you run screenpipe backend? either click start on the right, or
- thru CLI 👇
- </p>
- <CodeBlock language="bash" value={getDebuggingCommands(platform())} />
-
- <div className="mt-4 text-sm text-gray-500">
- <p>or, for more advanced queries:</p>
- <ol className="list-decimal list-inside mt-2">
- <li>
- <a
- href="https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-server/src/db.rs"
- target="_blank"
- rel="noopener noreferrer"
- className="text-blue-500 hover:underline"
- >
- go to the database schema
- </a>
- </li>
- <li>Copy the entire page (Cmd+A, Cmd+C)</li>
- <li>Paste into ChatGPT (Cmd+V)</li>
- <li>
- ask: &quot;give me 10 sqlite query CLI to look up my data. My db
- is in $HOME/.screenpipe/db.sqlite&quot;
- </li>
- </ol>
- <p className="mt-2">
- or if you prefer using curl, follow the same steps with the{" "}
- <a
- href="https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-server/src/server.rs"
- target="_blank"
- rel="noopener noreferrer"
- className="text-blue-500 hover:underline"
- >
- server.rs file
- </a>{" "}
- and ask ChatGPT for curl commands to interact with the API.
- </p>
- </div>
- </>
- )}
- </>
- );
-};
+import { LogFileButton } from "./log-file-button";
+import { DevModeSettings } from "./dev-mode-settings";
const HealthStatus = ({ className }: { className?: string }) => {
const { health } = useHealthCheck();
@@ -665,48 +364,4 @@ const HealthStatus = ({ className }: { className?: string }) => {
);
};
-export const LogFileButton = ({ className }: { className?: string }) => {
- const { toast } = useToast();
- const handleOpenLogFile = async () => {
- try {
- const homeDirPath = await homeDir();
- const logPath =
- platform() === "windows"
- ? `${homeDirPath}\\.screenpipe\\screenpipe.${
- new Date().toISOString().split("T")[0]
- }.log`
- : `${homeDirPath}/.screenpipe/screenpipe.${
- new Date().toISOString().split("T")[0]
- }.log`;
- await open(logPath);
- } catch (error) {
- console.error("failed to open log file:", error);
- toast({
- title: "error",
- description: "failed to open log file.",
- variant: "destructive",
- duration: 3000,
- });
- }
- };
- return (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- onClick={handleOpenLogFile}
- className="ml-2"
- >
- <FileText className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>open log file</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- );
-};
export default HealthStatus;
diff --git a/screenpipe-app-tauri/components/settings.tsx b/screenpipe-app-tauri/components/settings.tsx
index 7ad3a3576..b30977bb2 100644
--- a/screenpipe-app-tauri/components/settings.tsx
+++ b/screenpipe-app-tauri/components/settings.tsx
@@ -39,7 +39,7 @@ import {
import { RecordingSettings } from "./recording-settings";
import { Switch } from "./ui/switch";
import { Command } from "@tauri-apps/plugin-shell";
-import { LogFileButton } from "./screenpipe-status";
+import { LogFileButton } from "./log-file-button";
import { platform } from "@tauri-apps/plugin-os";
import { toast } from "@/components/ui/use-toast";
diff --git a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
index 0355394c1..e887b6449 100644
--- a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from "react";
+import { useState, useEffect, useCallback, useRef } from "react";
interface HealthCheckResponse {
status: string;
@@ -10,32 +10,47 @@ interface HealthCheckResponse {
message: string;
}
+function isHealthChanged(
+ oldHealth: HealthCheckResponse | null,
+ newHealth: HealthCheckResponse
+): boolean {
+ if (!oldHealth) return true;
+ return (
+ oldHealth.status !== newHealth.status ||
+ oldHealth.status_code !== newHealth.status_code ||
+ oldHealth.last_frame_timestamp !== newHealth.last_frame_timestamp ||
+ oldHealth.last_audio_timestamp !== newHealth.last_audio_timestamp ||
+ oldHealth.frame_status !== newHealth.frame_status ||
+ oldHealth.audio_status !== newHealth.audio_status ||
+ oldHealth.message !== newHealth.message
+ );
+}
+
export function useHealthCheck() {
const [health, setHealth] = useState<HealthCheckResponse | null>(null);
const [isServerDown, setIsServerDown] = useState(false);
- const baseCheckInterval = 5000; // 5 seconds
- const maxCheckInterval = 60000; // 1 minute
+ const pollInterval = 1000; // 1 second
+ const healthRef = useRef(health);
- const fetchHealth = async () => {
+ const fetchHealth = useCallback(async () => {
try {
- const response = await fetch("http://localhost:3030/health");
+ const response = await fetch("http://localhost:3030/health", {
+ cache: "no-store",
+ });
if (!response.ok) {
throw new Error(`http error! status: ${response.status}`);
}
const data: HealthCheckResponse = await response.json();
- if (
- !health ||
- health.status !== data.status ||
- health.status_code !== data.status_code ||
- health.message !== data.message
- ) {
+ if (isHealthChanged(healthRef.current, data)) {
setHealth(data);
+ healthRef.current = data;
}
setIsServerDown(false);
} catch (error) {
+ console.error("health check error:", error);
if (!isServerDown) {
setIsServerDown(true);
- setHealth({
+ const errorHealth: HealthCheckResponse = {
last_frame_timestamp: null,
last_audio_timestamp: null,
frame_status: "error",
@@ -43,22 +58,19 @@ export function useHealthCheck() {
status: "error",
status_code: 500,
message: "failed to fetch health status. server might be down.",
- });
+ };
+ setHealth(errorHealth);
+ healthRef.current = errorHealth;
}
}
- };
+ }, [isServerDown]);
useEffect(() => {
fetchHealth();
- const interval = setInterval(
- () => {
- fetchHealth();
- },
- isServerDown ? maxCheckInterval : baseCheckInterval
- );
+ const interval = setInterval(fetchHealth, pollInterval);
return () => clearInterval(interval);
- }, [isServerDown]);
+ }, [fetchHealth]);
- return { health, isServerDown };
-}
\ No newline at end of file
+ return { health, isServerDown, refetchHealth: fetchHealth };
+}
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 7b0281943..3c611b965 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.6.3"
+version = "0.6.4"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 592a2851f..f22d0119a 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -162,6 +162,16 @@ async fn main() -> anyhow::Result<()> {
// ! assuming silero is used
SileroVad::new().await.unwrap();
+ // Check if FFmpeg is working properly
+ match check_ffmpeg().await {
+ Ok(_) => info!("FFmpeg is working properly"),
+ Err(e) => {
+ error!("FFmpeg check failed: {}", e);
+ error!("Please ensure FFmpeg is installed correctly and is in your PATH");
+ return Err(e.into());
+ }
+ }
+
info!("screenpipe setup complete");
// TODO: ffmpeg sidecar thing here
return Ok(());
@@ -793,4 +803,21 @@ async fn handle_pipe_command(pipe: PipeCommand, pipe_manager: &PipeManager) -> a
},
}
Ok(())
-}
\ No newline at end of file
+}
+
+// Add this function near the end of the file
+async fn check_ffmpeg() -> anyhow::Result<()> {
+ // TODO: this should also check if it can properly encode mp4 etc
+ use tokio::process::Command;
+
+ let output = Command::new("ffmpeg")
+ .arg("-version")
+ .output().await?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(anyhow::anyhow!("FFmpeg check failed: {}", stderr));
+ }
+
+ Ok(())
+}
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index a94ac3743..7f97ca2b9 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -9,11 +9,12 @@ use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
+use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
-use tokio::io::{AsyncBufReadExt, BufReader};
-use tokio::process::{Child, ChildStdin, Command};
-use tokio::sync::mpsc::{channel, Receiver, Sender};
-use tokio::time::{sleep, timeout};
+use tokio::io::BufReader;
+use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};
+use tokio::sync::mpsc::channel;
+use tokio::time::sleep;
const MAX_FPS: f64 = 30.0; // Adjust based on your needs
const MAX_QUEUE_SIZE: usize = 10;
@@ -142,195 +143,6 @@ impl VideoCapture {
}
}
}
-async fn save_frames_as_video(
- frame_queue: &Arc<ArrayQueue<Arc<CaptureResult>>>,
- output_path: &str,
- fps: f64,
- new_chunk_callback: Arc<dyn Fn(&str) + Send + Sync>,
- monitor_id: u32,
- video_chunk_duration: Duration,
-) {
- debug!("Starting save_frames_as_video function");
- let frames_per_video = (fps * video_chunk_duration.as_secs_f64()).ceil() as usize;
- let mut frame_count = 0;
- let (sender, mut receiver): (Sender<Vec<u8>>, Receiver<Vec<u8>>) = channel(512);
- let sender = Arc::new(sender);
- let mut current_ffmpeg: Option<Child> = None;
- let mut current_stdin: Option<ChildStdin> = None;
-
- loop {
- if frame_count >= frames_per_video || current_ffmpeg.is_none() {
- debug!("Starting new FFmpeg process");
- // Close previous FFmpeg process if exists
- if let Some(child) = current_ffmpeg.take() {
- drop(current_stdin.take()); // Ensure stdin is closed
- let output = child
- .wait_with_output()
- .await
- .expect("ffmpeg process failed");
- debug!("FFmpeg process exited with status: {}", output.status);
- if !output.status.success() {
- error!("FFmpeg stderr: {}", String::from_utf8_lossy(&output.stderr));
- }
- }
- // Reset frame count
- frame_count = 0;
-
- // Wait for at least one frame before starting a new FFmpeg process
- let first_frame = loop {
- if let Some(result) = frame_queue.pop() {
- debug!("Got first frame for new chunk");
- break result;
- }
- tokio::time::sleep(Duration::from_millis(10)).await;
- };
-
- // Encode the first frame
- let mut buffer = Vec::new();
- first_frame
- .image
- .write_to(&mut std::io::Cursor::new(&mut buffer), ImageFormat::Png)
- .expect("Failed to encode first frame");
-
- let time = Utc::now();
- let formatted_time = time.format("%Y-%m-%d_%H-%M-%S").to_string();
- // Start new FFmpeg process with a new output file
- let output_file = PathBuf::from(output_path)
- .join(format!("monitor_{}_{}.mp4", monitor_id, formatted_time))
- .to_str()
- .expect("Failed to create valid path")
- .to_string();
-
- // Call the callback with the new video chunk file path
- new_chunk_callback(&output_file);
-
- match start_ffmpeg_process(&output_file, fps).await {
- Ok(mut child) => {
- let mut stdin = child.stdin.take().expect("Failed to open stdin");
- let stderr = child.stderr.take().expect("Failed to open stderr");
- let stdout = child.stdout.take().expect("Failed to open stdout");
-
- // Write the first frame to FFmpeg
- stdin
- .write_all(&buffer)
- .await
- .expect("Failed to write first frame to ffmpeg");
- frame_count += 1;
-
- // Spawn a task to log FFmpeg's stderr
- tokio::spawn(async move {
- let reader = BufReader::new(stderr);
- let mut lines = reader.lines();
- while let Ok(Some(line)) = lines.next_line().await {
- debug!("FFmpeg: {}", line);
- }
- });
-
- // Log FFmpeg's stdout
- tokio::spawn(async move {
- let reader = BufReader::new(stdout);
- let mut lines = reader.lines();
- while let Ok(Some(line)) = lines.next_line().await {
- debug!("FFmpeg: {}", line);
- }
- });
-
- current_ffmpeg = Some(child);
- current_stdin = Some(stdin);
- debug!("New FFmpeg process started for file: {}", output_file);
- }
- Err(e) => {
- error!("Failed to start FFmpeg process: {}", e);
- // Handle the error appropriately, maybe try to restart or exit
- }
- }
- }
-
- if let Some(result) = frame_queue.pop() {
- debug!("Processing frame in video.rs"); // {}", frame_count + 1
- let sender = Arc::clone(&sender);
-
- tokio::spawn(async move {
- let mut buffer = Vec::new();
- match result
- .image
- .write_to(&mut std::io::Cursor::new(&mut buffer), ImageFormat::Png)
- {
- Ok(_) => {
- sender
- .send(buffer)
- .await
- .expect("Failed to send encoded frame");
- }
- Err(e) => error!("Failed to encode image as PNG: {}", e),
- }
- });
- } else {
- // debug!("No frames in queue, waiting...");
- tokio::time::sleep(Duration::from_millis(10)).await;
- }
-
- const MAX_RETRIES: usize = 3;
- const RETRY_DELAY: Duration = Duration::from_millis(100);
-
- // Write encoded frames to FFmpeg
- let write_timeout = Duration::from_secs_f64(1.0 / fps);
- while let Ok(Some(buffer)) = timeout(write_timeout, receiver.recv()).await {
- if let Some(stdin) = current_stdin.as_mut() {
- let mut retries = 0;
- while retries < MAX_RETRIES {
- match stdin.write_all(&buffer).await {
- Ok(_) => {
- frame_count += 1;
- debug!("Wrote frame {} to FFmpeg", frame_count);
- break;
- }
- Err(e) => {
- retries += 1;
- if retries >= MAX_RETRIES {
- error!(
- "Failed to write frame to ffmpeg after {} retries: {}",
- MAX_RETRIES, e
- );
- // Consider breaking the outer loop or handling this failure
- break;
- } else {
- warn!(
- "Failed to write frame to ffmpeg (attempt {}): {}. Retrying...",
- retries, e
- );
- sleep(RETRY_DELAY).await;
- }
- }
- }
- }
- frame_count += 1;
- debug!("Wrote frame {} to FFmpeg", frame_count);
-
- // Calculate frames per flush based on fps
- let frames_per_flush = (fps.max(0.1) * 1.0).ceil() as usize;
-
- // Flush every calculated number of frames
- if frame_count % frames_per_flush == 0 {
- debug!("Flushing FFmpeg input after {} frames", frames_per_flush);
- if let Err(e) = stdin.flush().await {
- error!("Failed to flush FFmpeg input: {}", e);
- }
- }
- // Break the loop if we've written enough frames for this chunk
- if frame_count >= frames_per_video {
- debug!("finished writing frames for this chunk");
- break;
- }
- }
- }
-
- // Yield to other tasks periodically
- tokio::task::yield_now().await;
- }
-}
-
-use std::env;
async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child, anyhow::Error> {
// Overriding fps with max fps if over the max and warning user
@@ -388,3 +200,200 @@ async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child, anyh
Ok(child)
}
+
+async fn write_frame_to_ffmpeg(stdin: &mut ChildStdin, buffer: &[u8]) -> Result<(), anyhow::Error> {
+ stdin.write_all(buffer).await?;
+ Ok(())
+}
+
+async fn log_ffmpeg_output(stream: impl AsyncBufReadExt + Unpin, stream_name: &str) {
+ let reader = BufReader::new(stream);
+ let mut lines = reader.lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ debug!("FFmpeg {}: {}", stream_name, line);
+ }
+}
+
+async fn save_frames_as_video(
+ frame_queue: &Arc<ArrayQueue<Arc<CaptureResult>>>,
+ output_path: &str,
+ fps: f64,
+ new_chunk_callback: Arc<dyn Fn(&str) + Send + Sync>,
+ monitor_id: u32,
+ video_chunk_duration: Duration,
+) {
+ debug!("Starting save_frames_as_video function");
+ let frames_per_video = (fps * video_chunk_duration.as_secs_f64()).ceil() as usize;
+ let mut frame_count = 0;
+ let mut current_ffmpeg: Option<Child> = None;
+ let mut current_stdin: Option<ChildStdin> = None;
+
+ loop {
+ if frame_count >= frames_per_video || current_ffmpeg.is_none() {
+ if let Some(child) = current_ffmpeg.take() {
+ finish_ffmpeg_process(child, current_stdin.take()).await;
+ }
+
+ frame_count = 0;
+ let first_frame = wait_for_first_frame(frame_queue).await;
+ let buffer = encode_frame(&first_frame);
+
+ let output_file = create_output_file(output_path, monitor_id);
+ new_chunk_callback(&output_file);
+
+ match start_ffmpeg_process(&output_file, fps).await {
+ Ok(mut child) => {
+ let mut stdin = child.stdin.take().expect("Failed to open stdin");
+ spawn_ffmpeg_loggers(child.stderr.take(), child.stdout.take());
+
+ if let Err(e) = write_frame_to_ffmpeg(&mut stdin, &buffer).await {
+ error!("Failed to write first frame to ffmpeg: {}", e);
+ continue;
+ }
+ frame_count += 1;
+
+ current_ffmpeg = Some(child);
+ current_stdin = Some(stdin);
+ debug!("New FFmpeg process started for file: {}", output_file);
+ }
+ Err(e) => {
+ error!("Failed to start FFmpeg process: {}", e);
+ continue;
+ }
+ }
+ }
+
+ process_frames(
+ frame_queue,
+ &mut current_stdin,
+ &mut frame_count,
+ frames_per_video,
+ fps,
+ )
+ .await;
+
+ tokio::task::yield_now().await;
+ }
+}
+
+async fn wait_for_first_frame(
+ frame_queue: &Arc<ArrayQueue<Arc<CaptureResult>>>,
+) -> Arc<CaptureResult> {
+ loop {
+ if let Some(result) = frame_queue.pop() {
+ debug!("Got first frame for new chunk");
+ return result;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+}
+
+fn encode_frame(frame: &CaptureResult) -> Vec<u8> {
+ let mut buffer = Vec::new();
+ frame
+ .image
+ .write_to(&mut std::io::Cursor::new(&mut buffer), ImageFormat::Png)
+ .expect("Failed to encode frame");
+ buffer
+}
+
+fn create_output_file(output_path: &str, monitor_id: u32) -> String {
+ let time = Utc::now();
+ let formatted_time = time.format("%Y-%m-%d_%H-%M-%S").to_string();
+ PathBuf::from(output_path)
+ .join(format!("monitor_{}_{}.mp4", monitor_id, formatted_time))
+ .to_str()
+ .expect("Failed to create valid path")
+ .to_string()
+}
+
+fn spawn_ffmpeg_loggers(stderr: Option<ChildStderr>, stdout: Option<ChildStdout>) {
+ if let Some(stderr) = stderr {
+ tokio::spawn(log_ffmpeg_output(BufReader::new(stderr), "stderr"));
+ }
+ if let Some(stdout) = stdout {
+ tokio::spawn(log_ffmpeg_output(BufReader::new(stdout), "stdout"));
+ }
+}
+
+async fn process_frames(
+ frame_queue: &Arc<ArrayQueue<Arc<CaptureResult>>>,
+ current_stdin: &mut Option<ChildStdin>,
+ frame_count: &mut usize,
+ frames_per_video: usize,
+ fps: f64,
+) {
+ let write_timeout = Duration::from_secs_f64(1.0 / fps);
+ while *frame_count < frames_per_video {
+ if let Some(frame) = frame_queue.pop() {
+ let buffer = encode_frame(&frame);
+ if let Some(stdin) = current_stdin.as_mut() {
+ if let Err(e) = write_frame_with_retry(stdin, &buffer).await {
+ error!("Failed to write frame to ffmpeg after max retries: {}", e);
+ break;
+ }
+ *frame_count += 1;
+ debug!("Wrote frame {} to FFmpeg", frame_count);
+
+ flush_ffmpeg_input(stdin, *frame_count, fps).await;
+ }
+ } else {
+ tokio::time::sleep(write_timeout).await;
+ }
+ }
+}
+
+async fn write_frame_with_retry(
+ stdin: &mut ChildStdin,
+ buffer: &[u8],
+) -> Result<(), anyhow::Error> {
+ const MAX_RETRIES: usize = 3;
+ const RETRY_DELAY: Duration = Duration::from_millis(100);
+
+ let mut retries = 0;
+ while retries < MAX_RETRIES {
+ match stdin.write_all(buffer).await {
+ Ok(_) => return Ok(()),
+ Err(e) => {
+ retries += 1;
+ if retries >= MAX_RETRIES {
+ return Err(anyhow::anyhow!("Failed to write frame to ffmpeg: {}", e));
+ } else {
+ warn!(
+ "Failed to write frame to ffmpeg (attempt {}): {}. Retrying...",
+ retries, e
+ );
+ sleep(RETRY_DELAY).await;
+ }
+ }
+ }
+ }
+ Err(anyhow::anyhow!(
+ "Failed to write frame to ffmpeg after max retries"
+ ))
+}
+
+async fn flush_ffmpeg_input(stdin: &mut ChildStdin, frame_count: usize, fps: f64) {
+ let frames_per_flush = (fps.max(0.1) * 1.0).ceil() as usize;
+ if frame_count % frames_per_flush == 0 {
+ debug!("Flushing FFmpeg input after {} frames", frames_per_flush);
+ if let Err(e) = stdin.flush().await {
+ error!("Failed to flush FFmpeg input: {}", e);
+ }
+ }
+}
+
+async fn finish_ffmpeg_process(child: Child, stdin: Option<ChildStdin>) {
+ drop(stdin); // Ensure stdin is closed
+ match child.wait_with_output().await {
+ Ok(output) => {
+ debug!("FFmpeg process exited with status: {}", output.status);
+ if !output.status.success() {
+ error!("FFmpeg stderr: {}", String::from_utf8_lossy(&output.stderr));
+ }
+ }
+ Err(e) => error!("Failed to wait for FFmpeg process: {}", e),
+ }
+}
+
+use std::env;