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

improve flow, onboarding ux, settings, give app more native feel

shaik-zeeshan6a7143e96b6b
diff --git a/openrewind/app/layout.tsx b/openrewind/app/layout.tsx
index 5f0cafa14..6f4fdb3b5 100644
--- a/openrewind/app/layout.tsx
+++ b/openrewind/app/layout.tsx
@@ -4,6 +4,7 @@ import "./globals.css";
import { Providers } from "./providers";
import { Toaster } from "@/components/ui/toaster";
import { useEffect } from "react";
+import { DeeplinkHandler } from "@/components/deeplink-handler";
const inter = Inter({ subsets: ["latin"] });
@@ -64,6 +65,7 @@ export default function RootLayout({
<html lang="en" suppressHydrationWarning>
<Providers>
<body className={`${inter.className} scrollbar-hide`}>
+ <DeeplinkHandler />
{children}
<Toaster />
</body>
diff --git a/openrewind/app/onboarding/page.tsx b/openrewind/app/onboarding/page.tsx
new file mode 100644
index 000000000..e062320c3
--- /dev/null
+++ b/openrewind/app/onboarding/page.tsx
@@ -0,0 +1,340 @@
+"use client";
+
+import React, { useState, useEffect } from "react";
+import { useToast } from "@/components/ui/use-toast";
+import OnboardingStatus from "@/components/onboarding/status";
+import OnboardingIntro from "@/components/onboarding/introduction";
+import OnboardingAPISetup from "@/components/onboarding/api-setup";
+import OnboardingInstructions from "@/components/onboarding/explain-instructions";
+import OnboardingLogin from "@/components/onboarding/login";
+import { useOnboarding } from "@/lib/hooks/use-onboarding";
+import posthog from "posthog-js";
+import { commands } from "@/lib/utils/tauri";
+
+type SlideKey =
+ | "intro"
+ | "status"
+ | "login"
+ | "apiSetup"
+ | "instructions";
+
+// Window size configurations for each slide
+const SLIDE_WINDOW_SIZES: Record<SlideKey, { width: number; height: number }> = {
+ intro: { width: 1100, height: 850 }, // Increased for demo content
+ status: { width: 1100, height: 850 }, // Good for status checks
+ login: { width: 1100, height: 680 }, // Compact for login form
+ apiSetup: { width: 1100, height: 1000 }, // Taller for AI presets configuration
+ instructions: { width: 1100, height: 1050 }, // Largest for the final comprehensive instructions
+};
+
+// Simplified flow - linear progression
+const getNextSlide = (currentSlide: SlideKey): SlideKey | null => {
+ switch (currentSlide) {
+ case "intro":
+ return "status";
+ case "status":
+ return "login";
+ case "login":
+ return "apiSetup";
+ case "apiSetup":
+ return "instructions";
+ case "instructions":
+ return null;
+ default:
+ return null;
+ }
+};
+
+const getPrevSlide = (currentSlide: SlideKey): SlideKey | null => {
+ switch (currentSlide) {
+ case "intro":
+ return null;
+ case "status":
+ return "intro";
+ case "login":
+ return "status";
+ case "apiSetup":
+ return "login";
+ case "instructions":
+ return "apiSetup";
+ default:
+ return null;
+ }
+};
+
+const trackOnboardingStep = (
+ step: SlideKey | "completed",
+ properties?: Record<string, any>
+) => {
+ posthog.capture("onboarding_step", {
+ step,
+ ...properties,
+ });
+};
+
+// Function to set window size for current slide
+const setWindowSizeForSlide = async (slide: SlideKey) => {
+ try {
+ const { width, height } = SLIDE_WINDOW_SIZES[slide];
+ await commands.setWindowSize("Onboarding", width, height);
+ console.log(`✅ Set window size for ${slide}: ${width}x${height}`);
+ } catch (error) {
+ console.warn(`⚠️ Failed to set window size for ${slide}:`, error);
+ // Don't show error toast for window sizing issues as it's not critical
+ // The window will just maintain its current size
+ }
+};
+
+export default function OnboardingPage() {
+ const { toast } = useToast();
+ const [currentSlide, setCurrentSlide] = useState<SlideKey>("intro");
+ const [error, setError] = useState<string | null>(null);
+ const [isVisible, setIsVisible] = useState(false);
+ const [isTransitioning, setIsTransitioning] = useState(false);
+ const [completedSteps, setCompletedSteps] = useState<SlideKey[]>(["intro"]);
+ const {
+ onboardingData,
+ completeOnboarding,
+ isLoading
+ } = useOnboarding();
+
+ // Load onboarding status on mount
+ useEffect(() => {
+ const { loadOnboardingStatus } = useOnboarding.getState();
+ loadOnboardingStatus();
+ }, []);
+
+ // Set window size when slide changes
+ useEffect(() => {
+ setWindowSizeForSlide(currentSlide);
+ setIsVisible(true);
+ }, [currentSlide]);
+
+ useEffect(() => {
+ if (error) {
+ toast({
+ title: "Error",
+ description: error,
+ variant: "destructive",
+ });
+ }
+ }, [error, toast]);
+
+ // Handle redirect if already completed
+ useEffect(() => {
+ if (onboardingData.isCompleted) {
+ const redirectToMain = async () => {
+ try {
+ await commands.showWindow("Main");
+ if (typeof window !== 'undefined' && 'close' in window) {
+ window.close();
+ }
+ } catch (error) {
+ console.error("Error redirecting to main window:", error);
+ }
+ };
+ redirectToMain();
+ }
+ }, [onboardingData.isCompleted]);
+
+ const showSuccessToast = (message: string) => {
+ toast({
+ title: "Success",
+ description: message,
+ variant: "default",
+ });
+ };
+
+ const showErrorToast = (message: string) => {
+ toast({
+ title: "Error",
+ description: message,
+ variant: "destructive",
+ });
+ };
+
+ const handleNextSlide = async () => {
+ if (isTransitioning) return;
+
+ setIsTransitioning(true);
+ const nextSlide = getNextSlide(currentSlide);
+
+ try {
+ trackOnboardingStep(currentSlide, {
+ direction: "next",
+ });
+
+ // Mark current step as completed
+ if (!completedSteps.includes(currentSlide)) {
+ setCompletedSteps(prev => [...prev, currentSlide]);
+ }
+
+ if (nextSlide) {
+ setIsVisible(false);
+ setTimeout(async () => {
+ setCurrentSlide(nextSlide);
+ setError(null);
+ setIsTransitioning(false);
+ }, 300);
+ } else {
+ await handleEnd();
+ }
+ } catch (error) {
+ console.error("Error in handleNextSlide:", error);
+ showErrorToast("Failed to proceed to next step");
+ setIsTransitioning(false);
+ }
+ };
+
+ const handlePrevSlide = async () => {
+ if (isTransitioning) return;
+
+ setIsTransitioning(true);
+
+ try {
+ trackOnboardingStep(currentSlide, {
+ direction: "back",
+ });
+
+ setIsVisible(false);
+
+ setTimeout(async () => {
+ let prevSlide = getPrevSlide(currentSlide);
+
+ if (prevSlide) {
+ setError(null);
+ setCurrentSlide(prevSlide);
+ }
+ setIsTransitioning(false);
+ }, 300);
+ } catch (error) {
+ console.error("Error in handlePrevSlide:", error);
+ showErrorToast("Failed to go back");
+ setIsTransitioning(false);
+ }
+ };
+
+ const handleSkip = async () => {
+ if (isTransitioning) return;
+
+ try {
+ setIsTransitioning(true);
+ trackOnboardingStep("completed", { skipped: true });
+
+ // Removed success toast to avoid spam
+ await handleEnd();
+ } catch (error) {
+ console.error("Error skipping onboarding:", error);
+ showErrorToast("Failed to skip onboarding");
+ setIsTransitioning(false);
+ }
+ };
+
+ const handleEnd = async () => {
+ try {
+ setIsTransitioning(true);
+ trackOnboardingStep("completed");
+
+ // Complete onboarding in backend (only store completion status)
+ await completeOnboarding();
+
+ showSuccessToast("Onboarding completed successfully!");
+
+ // // Small delay for user to see success message
+ // setTimeout(async () => {
+ // try {
+ // // Show main window and close onboarding window
+ // await commands.closeWindow("Onboarding");
+ // await commands.showWindow("Main");
+ // } catch (windowError) {
+ // console.error("Error managing windows:", windowError);
+ // showErrorToast("Onboarding completed but failed to switch windows");
+ // }
+ // }, 1500);
+
+ } catch (error) {
+ console.error("Error completing onboarding:", error);
+ showErrorToast("Failed to complete onboarding");
+ setIsTransitioning(false);
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="flex items-center justify-center min-h-screen bg-background">
+ <div className="text-center">
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
+ <p className="text-muted-foreground">Loading onboarding...</p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col w-full h-screen overflow-hidden bg-background">
+ {/* Progress indicator with drag region */}
+ <div className="w-full bg-secondary p-4" data-tauri-drag-region>
+ <div className="flex items-center justify-between max-w-4xl mx-auto">
+ <div className="flex items-center space-x-2">
+ <span className="text-sm font-medium">Progress:</span>
+ <div className="text-sm text-muted-foreground">
+ Step {["intro", "status", "login", "apiSetup", "instructions"].indexOf(currentSlide) + 1} of 5
+ </div>
+ </div>
+ <button
+ onClick={handleSkip}
+ disabled={isTransitioning}
+ className="text-sm text-muted-foreground hover:text-foreground disabled:opacity-50"
+ >
+ Skip onboarding
+ </button>
+ </div>
+ </div>
+
+ {/* Main content container - centered and properly sized */}
+ <div className="flex-1 flex items-center justify-center p-6 overflow-auto">
+ <div className="w-full max-w-4xl mx-auto h-full flex items-center justify-center">
+ {currentSlide === "intro" && (
+ <OnboardingIntro
+ className={`transition-opacity duration-300 w-full
+ ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
+ handleNextSlide={handleNextSlide}
+ />
+ )}
+ {currentSlide === "status" && (
+ <OnboardingStatus
+ className={`transition-opacity duration-300 w-full
+ ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
+ handlePrevSlide={handlePrevSlide}
+ handleNextSlide={handleNextSlide}
+ />
+ )}
+ {currentSlide === "login" && (
+ <OnboardingLogin
+ className={`transition-opacity duration-300 w-full
+ ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
+ handleNextSlide={handleNextSlide}
+ handlePrevSlide={handlePrevSlide}
+ />
+ )}
+ {currentSlide === "apiSetup" && (
+ <OnboardingAPISetup
+ className={`transition-opacity duration-300 ease-in-out w-full
+ ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
+ handleNextSlide={handleNextSlide}
+ handlePrevSlide={handlePrevSlide}
+ />
+ )}
+ {currentSlide === "instructions" && (
+ <OnboardingInstructions
+ className={`transition-opacity duration-300 ease-in-out w-full
+ ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
+ handleNextSlide={handleEnd}
+ handlePrevSlide={handlePrevSlide}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/openrewind/app/page.tsx b/openrewind/app/page.tsx
index ad8297381..7cf2c1bf7 100644
--- a/openrewind/app/page.tsx
+++ b/openrewind/app/page.tsx
@@ -4,52 +4,47 @@ import { getStore, useSettings } from "@/lib/hooks/use-settings";
import React, { useEffect, useState, useRef } from "react";
import NotificationHandler from "@/components/notification-handler";
-import Header from "@/components/header";
import { useToast } from "@/components/ui/use-toast";
-import Onboarding from "@/components/onboarding";
import { useOnboarding } from "@/lib/hooks/use-onboarding";
import { ChangelogDialog } from "@/components/changelog-dialog";
import { BreakingChangesInstructionsDialog } from "@/components/breaking-changes-instructions-dialog";
-import { useChangelogDialog } from "@/lib/hooks/use-changelog-dialog";
-import { useStatusDialog } from "@/lib/hooks/use-status-dialog";
-import { useSettingsDialog } from "@/lib/hooks/use-settings-dialog";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
-import { invoke } from "@tauri-apps/api/core";
-import { listen } from "@tauri-apps/api/event";
-import { useProfiles } from "@/lib/hooks/use-profiles";
-import { relaunch } from "@tauri-apps/plugin-process";
-import { PipeApi } from "@/lib/api";
+import { commands } from "@/lib/utils/tauri";
import localforage from "localforage";
-import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
import { LoginDialog } from "../components/login-dialog";
import { ModelDownloadTracker } from "../components/model-download-tracker";
import Timeline from "@/components/rewind/timeline";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
-import { RefreshCw, AlertTriangle, Settings } from "lucide-react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { RefreshCw, AlertTriangle, Settings, Mail } from "lucide-react";
import { PermissionButtons } from "@/components/status/permission-buttons";
import { usePlatform } from "@/lib/hooks/use-platform";
import SplashScreen from "@/components/splash-screen";
+import { openSettingsWindow } from "@/lib/utils/window";
+import HealthStatus from "@/components/screenpipe-status";
+import { ShareLogsButton } from "@/components/share-logs-button";
export default function Home() {
const { settings, updateSettings, loadUser, reloadStore, isSettingsLoaded, loadingError } = useSettings();
- const { setActiveProfile } = useProfiles();
const { toast } = useToast();
- const { showOnboarding, setShowOnboarding, initialized } = useOnboarding();
- const { setShowChangelogDialog } = useChangelogDialog();
- const { open: openStatusDialog } = useStatusDialog();
- const { setIsOpen: setSettingsOpen } = useSettingsDialog();
+ const { onboardingData } = useOnboarding();
const { isServerDown } = useHealthCheck();
const { isMac } = usePlatform();
const [isRestarting, setIsRestarting] = useState(false);
+ const [isFeedbackOpen, setIsFeedbackOpen] = useState(false);
const isProcessingRef = useRef(false);
+ // Load onboarding status on mount
useEffect(() => {
- if (settings.user?.token) {
- loadUser(settings.user.token);
- }
- }, [settings.user.token]);
+ const { loadOnboardingStatus } = useOnboarding.getState();
+ loadOnboardingStatus();
+ }, []);
useEffect(() => {
const getAudioDevices = async () => {
@@ -58,96 +53,9 @@ export default function Home() {
return devices;
};
- const setupDeepLink = async () => {
- const unsubscribeDeepLink = await onOpenUrl(async (urls) => {
- console.log("received deep link urls:", urls);
- for (const url of urls) {
- const parsedUrl = new URL(url);
-
- // Handle API key auth
- if (url.includes("api_key=")) {
- const apiKey = parsedUrl.searchParams.get("api_key");
- if (apiKey) {
- updateSettings({ user: { token: apiKey } });
- toast({
- title: "logged in!",
- description: "you have been logged in",
- });
- }
- }
-
- if (url.includes("settings")) {
- setSettingsOpen(true);
- }
-
- if (url.includes("changelog")) {
- setShowChangelogDialog(true);
- }
-
- if (url.includes("onboarding")) {
- setShowOnboarding(true);
- }
-
- if (url.includes("status")) {
- openStatusDialog();
- }
- }
- });
- return unsubscribeDeepLink;
- };
-
- let deepLinkUnsubscribe: (() => void) | undefined;
-
- setupDeepLink().then((unsubscribe) => {
- deepLinkUnsubscribe = unsubscribe;
- });
-
- const unlisten = Promise.all([
- listen("shortcut-start-recording", async () => {
- await invoke("spawn_screenpipe");
-
- toast({
- title: "recording started",
- description: "screen recording has been initiated",
- });
- }),
-
- listen("shortcut-stop-recording", async () => {
- await invoke("stop_screenpipe");
-
- toast({
- title: "recording stopped",
- description: "screen recording has been stopped",
- });
- }),
-
- listen<string>("switch-profile", async (event) => {
- const profile = event.payload;
- setActiveProfile(profile);
-
- toast({
- title: "profile switched",
- description: `switched to ${profile} profile, restarting screenpipe now`,
- });
-
- await invoke("stop_screenpipe");
-
- await new Promise((resolve) => setTimeout(resolve, 1000));
-
- await invoke("spawn_screenpipe");
-
- await new Promise((resolve) => setTimeout(resolve, 1000));
- relaunch();
- })
- ]);
-
+ // Cleanup function placeholder if needed
return () => {
- if (deepLinkUnsubscribe) {
- deepLinkUnsubscribe();
- }
- unlisten.then((unsubscribes) => {
- unsubscribes.forEach((unsubscribe) => unsubscribe());
- });
+ // Any cleanup logic can go here
};
}, []);
@@ -159,26 +67,19 @@ export default function Home() {
if (restartPending) {
// Clear the restart pending flag
await localforage.removeItem("screenPermissionRestartPending");
- setShowOnboarding(true);
+ try {
+ await commands.showWindow("Onboarding");
+ } catch (error) {
+ console.error("Failed to show onboarding window:", error);
+ }
}
};
- // Only check after onboarding is initialized
- if (initialized) {
+ // Always call this effect, but only execute logic when onboarding data is loaded
+ if (onboardingData.isCompleted !== undefined) {
checkScreenPermissionRestart();
}
- }, [setShowOnboarding, initialized]);
-
- useEffect(() => {
- const unlisten = listen("cli-login", async (event) => {
- console.log("received cli-login event:", event);
- await reloadStore();
- });
-
- return () => {
- unlisten.then((unlistenFn) => unlistenFn());
- };
- }, []);
+ }, [onboardingData.isCompleted]);
const handleRestartServer = async () => {
setIsRestarting(true);
@@ -190,7 +91,7 @@ export default function Home() {
});
// Stop the server first
- await invoke("stop_screenpipe");
+ await commands.stopScreenpipe();
// Wait for proper cleanup
await new Promise(resolve => setTimeout(resolve, 2000));
@@ -202,7 +103,7 @@ export default function Home() {
});
// Start the server
- await invoke("spawn_screenpipe");
+ await commands.spawnScreenpipe(null);
toast({
title: "server restarted",
@@ -224,95 +125,116 @@ export default function Home() {
return (
<div className="flex flex-col items-center flex-1 mx-auto relative scrollbar-hide">
- <LoginDialog />
- <ModelDownloadTracker />
+ {/* Transparent titlebar area */}
+ <div className="h-8 bg-transparent w-full" data-tauri-drag-region>
+ <div className="flex items-center justify-between gap-2">
+ <div/>
+ <h1 className="text-xs font-bold">OpenRewind</h1>
+ <div className="flex items-center gap-2">
+ <HealthStatus className="cursor-pointer" />
+ <Popover open={isFeedbackOpen} onOpenChange={setIsFeedbackOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <Mail className="h-4 w-4" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-100 rounded-2xl">
+ <ShareLogsButton
+ showShareLink={false}
+ onComplete={() => setIsFeedbackOpen(false)}
+ />
+ </PopoverContent>
+ </Popover>
+ <Button variant="ghost" size="icon" onClick={() => openSettingsWindow()}>
+ <Settings className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ </div>
+
<NotificationHandler />
- {/* Only render content after both onboarding and settings are initialized */}
- {initialized && isSettingsLoaded ? (
+ {/* Only render content after settings are loaded */}
+ {isSettingsLoaded ? (
<>
- {showOnboarding ? (
- <Onboarding />
+ <ChangelogDialog />
+ <BreakingChangesInstructionsDialog />
+ <LoginDialog />
+ <ModelDownloadTracker />
+ {!isServerDown ? (
+ <div className="w-full scrollbar-hide">
+ <Timeline />
+ </div>
) : (
- <>
- <ChangelogDialog />
- {/* <BreakingChangesInstructionsDialog /> */}
- {!isServerDown ? (
- <div className="w-full scrollbar-hide">
- <Timeline />
+ <div className="flex items-center justify-center h-screen p-4">
+ <div className="max-w-lg w-full space-y-6">
+ {/* Header */}
+ <div className="text-center space-y-4">
+ <div className="flex flex-col items-center gap-3">
+ <div className="w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center">
+ <AlertTriangle className="w-8 h-8 text-destructive" />
+ </div>
+ <div>
+ <h2 className="text-2xl font-bold">Server Not Active</h2>
+ <p className="text-muted-foreground mt-2">
+ The screenpipe server is not running. Start the server or check permissions to continue.
+ </p>
+ </div>
+ </div>
</div>
- ) : (
- <div className="flex items-center justify-center h-screen p-4">
- <div className="max-w-lg w-full space-y-6">
- {/* Header */}
- <div className="text-center space-y-4">
- <div className="flex flex-col items-center gap-3">
- <div className="w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center">
- <AlertTriangle className="w-8 h-8 text-destructive" />
- </div>
- <div>
- <h2 className="text-2xl font-bold">Server Not Active</h2>
- <p className="text-muted-foreground mt-2">
- The screenpipe server is not running. Start the server or check permissions to continue.
- </p>
- </div>
+
+ {/* Actions Card */}
+ <div className="bg-card border rounded-lg p-6 space-y-6">
+ {/* Server Control */}
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <h3 className="font-semibold">Server Control</h3>
+ <p className="text-sm text-muted-foreground">
+ Start or restart the screenpipe server
+ </p>
</div>
+ <Button
+ onClick={handleRestartServer}
+ disabled={isRestarting}
+ className="flex items-center gap-2"
+ >
+ <RefreshCw className={`h-4 w-4 ${isRestarting ? 'animate-spin' : ''}`} />
+ {isRestarting ? "Starting..." : "Start Server"}
+ </Button>
</div>
+ </div>
- {/* Actions Card */}
- <div className="bg-card border rounded-lg p-6 space-y-6">
- {/* Server Control */}
+ {/* Permissions Section - Only show on Mac */}
+ {isMac && (
+ <>
+ <Separator />
<div className="space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <h3 className="font-semibold">Server Control</h3>
- <p className="text-sm text-muted-foreground">
- Start or restart the screenpipe server
- </p>
+ <div>
+ <h3 className="font-semibold">System Permissions</h3>
+ <p className="text-sm text-muted-foreground">
+ Ensure screenpipe has the necessary permissions to function properly
+ </p>
+ </div>
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Screen Recording</span>
+ <PermissionButtons type="screen" />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Audio Recording</span>
+ <PermissionButtons type="audio" />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Accessibility</span>
+ <PermissionButtons type="accessibility" />
</div>
- <Button
- onClick={handleRestartServer}
- disabled={isRestarting}
- className="flex items-center gap-2"
- >
- <RefreshCw className={`h-4 w-4 ${isRestarting ? 'animate-spin' : ''}`} />
- {isRestarting ? "Starting..." : "Start Server"}
- </Button>
</div>
</div>
-
- {/* Permissions Section - Only show on Mac */}
- {isMac && (
- <>
- <Separator />
- <div className="space-y-4">
- <div>
- <h3 className="font-semibold">System Permissions</h3>
- <p className="text-sm text-muted-foreground">
- Ensure screenpipe has the necessary permissions to function properly
- </p>
- </div>
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium">Screen Recording</span>
- <PermissionButtons type="screen" />
- </div>
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium">Audio Recording</span>
- <PermissionButtons type="audio" />
- </div>
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium">Accessibility</span>
- <PermissionButtons type="accessibility" />
- </div>
- </div>
- </div>
- </>
- )}
- </div>
- </div>
+ </>
+ )}
</div>
- )}
- </>
+ </div>
+ </div>
)}
</>
) : (
diff --git a/openrewind/app/providers.tsx b/openrewind/app/providers.tsx
index 7153c1188..a8ac89521 100644
--- a/openrewind/app/providers.tsx
+++ b/openrewind/app/providers.tsx
@@ -4,9 +4,9 @@ import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { useEffect } from "react";
import { ChangelogDialogProvider } from "@/lib/hooks/use-changelog-dialog";
+import { SettingsProvider } from "@/lib/hooks/use-settings";
import { forwardRef } from "react";
-import { store as SettingsStore, useSettings } from "@/lib/hooks/use-settings";
-import { profilesStore as ProfilesStore } from "@/lib/hooks/use-profiles";
+import { NuqsAdapter } from "nuqs/adapters/next/app";
export const Providers = forwardRef<
HTMLDivElement,
@@ -25,13 +25,13 @@ export const Providers = forwardRef<
}, []);
return (
- <SettingsStore.Provider>
- <ProfilesStore.Provider>
+ <NuqsAdapter>
+ <SettingsProvider>
<ChangelogDialogProvider>
<PostHogProvider client={posthog}>{children}</PostHogProvider>
</ChangelogDialogProvider>
- </ProfilesStore.Provider>
- </SettingsStore.Provider>
+ </SettingsProvider>
+ </NuqsAdapter>
);
});
diff --git a/openrewind/app/settings/page.tsx b/openrewind/app/settings/page.tsx
new file mode 100644
index 000000000..93e8eb6a8
--- /dev/null
+++ b/openrewind/app/settings/page.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import React, { useEffect, useState, Suspense } from "react";
+import { useSettings } from "@/lib/hooks/use-settings";
+import {
+ Brain,
+ Video,
+ Keyboard,
+ User,
+ Settings as SettingsIcon,
+ HardDrive,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+import { AccountSection } from "@/components/settings/account-section";
+import ShortcutSection from "@/components/settings/shortcut-section";
+import { AIPresets } from "@/components/settings/ai-presets";
+import { RecordingSettings } from "@/components/settings/recording-settings";
+import GeneralSettings from "@/components/settings/general-settings";
+import { DiskUsageSection } from "@/components/settings/disk-usage-section";
+import { useRouter } from "next/navigation";
+import { useQueryState } from "nuqs";
+import { listen } from "@tauri-apps/api/event";
+
+type SettingsSection =
+ | "general"
+ | "ai"
+ | "shortcuts"
+ | "recording"
+ | "account"
+ | "disk-usage";
+
+function SettingsPageContent() {
+ const router = useRouter();
+ const [activeSection, setActiveSection] = useQueryState("section", {
+ defaultValue: "general" as SettingsSection,
+ parse: (value) => {
+ if (["general", "ai", "shortcuts", "recording", "account", "disk-usage"].includes(value)) {
+ return value as SettingsSection;
+ }
+ return "general" as SettingsSection;
+ },
+ serialize: (value) => value,
+ });
+
+ const { settings } = useSettings();
+
+ const renderSection = () => {
+ switch (activeSection) {
+ case "general":
+ return <GeneralSettings />;
+ case "ai":
+ return <AIPresets />;
+ case "account":
+ return <AccountSection />;
+ case "recording":
+ return <RecordingSettings />;
+ case "shortcuts":
+ return <ShortcutSection />;
+ case "disk-usage":
+ return <DiskUsageSection />;
+ }
+ };
+
+ const settingsSections = [
+ {
+ id: "general",
+ label: "General",
+ icon: <SettingsIcon className="h-4 w-4" />,
+ description: "Basic app settings and preferences",
+ },
+ {
+ id: "account",
+ label: "Account",
+ icon: <User className="h-4 w-4" />,
+ description: "User account and authentication",
+ },
+ {
+ id: "recording",
+ label: "Recording",
+ icon: <Video className="h-4 w-4" />,
+ description: "Screen and audio recording settings",
+ },
+ {
+ id: "ai",
+ label: "AI Settings",
+ icon: <Brain className="h-4 w-4" />,
+ description: "AI models and processing options",
+ },
+ {
+ id: "shortcuts",
+ label: "Shortcuts",
+ icon: <Keyboard className="h-4 w-4" />,
+ description: "Keyboard shortcuts and hotkeys",
+ },
+ {
+ id: "disk-usage",
+ label: "Disk Usage",
+ icon: <HardDrive className="h-4 w-4" />,
+ description: "Monitor storage usage for Screenpipe data",
+ },
+ ];
+
+ // Listen for navigation events from other windows
+ useEffect(() => {
+ const unlisten = listen<{ url: string }>("navigate", (event) => {
+ const url = new URL(event.payload.url, window.location.origin);
+ const section = url.searchParams.get("section");
+ if (section && ["general", "ai", "shortcuts", "recording", "account", "disk-usage"].includes(section)) {
+ setActiveSection(section as SettingsSection);
+ }
+ });
+
+ return () => {
+ unlisten.then((unlistenFn) => unlistenFn());
+ };
+ }, [setActiveSection]);
+
+ return (
+ <div className="min-h-screen bg-background">
+ {/* Transparent titlebar area */}
+ <div className="h-8 bg-transparent" data-tauri-drag-region></div>
+
+ <div className="max-w-7xl mx-auto px-4">
+ <div className="flex h-[calc(100vh-2rem)] min-h-0">
+ {/* Sidebar */}
+ <div className="w-80 border-r bg-background flex flex-col min-h-0 rounded-tl-lg">
+ <div className="p-6 border-b">
+ <div className="space-y-3">
+ <h1 className="text-2xl font-bold text-foreground">
+ Settings
+ </h1>
+ </div>
+ </div>
+
+ {/* Navigation */}
+ <div className="p-4 space-y-2 flex-1 overflow-y-auto">
+ {settingsSections.map((section) => (
+ <button
+ key={section.id}
+ onClick={() =>
+ setActiveSection(section.id as SettingsSection)
+ }
+ className={cn(
+ "w-full flex items-start space-x-3 px-4 py-3 rounded-xl transition-all duration-200 text-left group",
+ activeSection === section.id
+ ? "bg-card shadow-sm border border-border text-foreground"
+ : "hover:bg-card/50 text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <div className={cn(
+ "mt-0.5 transition-colors",
+ activeSection === section.id
+ ? "text-primary"
+ : "text-muted-foreground group-hover:text-foreground"
+ )}>
+ {section.icon}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="font-medium text-sm">{section.label}</div>
+ <div className="text-xs text-muted-foreground mt-0.5 leading-relaxed">
+ {section.description}
+ </div>
+ </div>
+ </button>
+ ))}
+ </div>
+
+ {/* Footer */}
+ <div className="p-4 border-t border-border flex-shrink-0">
+ <div className="text-xs text-muted-foreground text-center">
+ OpenRewind Settings
+ </div>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 flex flex-col h-full bg-background min-h-0 rounded-tr-lg">
+ <div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
+ <div className="p-8 pb-16 max-w-4xl mx-auto">
+ {renderSection()}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default function SettingsPage() {
+ return (
+ <Suspense fallback={<div className="min-h-screen bg-background flex items-center justify-center">
+ <div className="text-muted-foreground">Loading settings...</div>
+ </div>}>
+ <SettingsPageContent />
+ </Suspense>
+ );
+}
\ No newline at end of file
diff --git a/openrewind/components/breaking-changes-instructions-dialog.tsx b/openrewind/components/breaking-changes-instructions-dialog.tsx
index 93284a954..104b2ce3e 100644
--- a/openrewind/components/breaking-changes-instructions-dialog.tsx
+++ b/openrewind/components/breaking-changes-instructions-dialog.tsx
@@ -26,7 +26,7 @@ export function BreakingChangesInstructionsDialog() {
try {
const response = await fetch("http://localhost:3030/pipes/list");
const data = await response.json();
- setHasPipes(data.data.length > 0);
+ setHasPipes(data?.data?.length > 0);
} catch (error) {
console.error("failed to check pipes:", error);
}
diff --git a/openrewind/components/cli-command-dialog.tsx b/openrewind/components/cli-command-dialog.tsx
index 56969d631..e7af0a044 100644
--- a/openrewind/components/cli-command-dialog.tsx
+++ b/openrewind/components/cli-command-dialog.tsx
@@ -12,13 +12,13 @@ import { CodeBlock } from "./ui/codeblock";
import { useCopyToClipboard } from "@/lib/hooks/use-copy-to-clipboard";
import { useToast } from "@/components/ui/use-toast";
import { IconCode } from "./ui/icons";
-import { Settings } from "@/lib/hooks/use-settings";
import { getCliPath } from "@/lib/utils";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { platform } from "@tauri-apps/plugin-os";
+import { SettingsStore } from "@/lib/utils/tauri";
interface CliCommandDialogProps {
- settings: Settings;
+ settings: SettingsStore;
}
export function CliCommandDialog({ settings }: CliCommandDialogProps) {
diff --git a/openrewind/components/deeplink-handler.tsx b/openrewind/components/deeplink-handler.tsx
new file mode 100644
index 000000000..ccaf54425
--- /dev/null
+++ b/openrewind/components/deeplink-handler.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import { useEffect } from "react";
+import { useToast } from "@/components/ui/use-toast";
+import { useChangelogDialog } from "@/lib/hooks/use-changelog-dialog";
+import { useStatusDialog } from "@/lib/hooks/use-status-dialog";
+import { useSettings } from "@/lib/hooks/use-settings";
+import { commands } from "@/lib/utils/tauri";
+import { listen } from "@tauri-apps/api/event";
+import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
+import { openSettingsWindow } from "@/lib/utils/window";
+
+export function DeeplinkHandler() {
+ const { toast } = useToast();
+ const { setShowChangelogDialog } = useChangelogDialog();
+ const { open: openStatusDialog } = useStatusDialog();
+ const { loadUser, reloadStore } = useSettings();
+
+ useEffect(() => {
+ const setupDeepLink = async () => {
+ const unsubscribeDeepLink = await onOpenUrl(async (urls) => {
+ console.log("received deep link urls:", urls);
+ for (const url of urls) {
+ const parsedUrl = new URL(url);
+
+ // Handle API key auth
+ if (url.includes("api_key=")) {
+ const apiKey = parsedUrl.searchParams.get("api_key");
+ if (apiKey) {
+ try {
+ await loadUser(apiKey);
+ toast({
+ title: "logged in!",
+ description: "you have been logged in",
+ });
+
+ } catch (error) {
+ console.error("failed to load user:", error);
+ toast({
+ title: "failed to load user",
+ description: "failed to load user",
+ });
+ }
+ }
+ }
+
+ if (url.includes("settings")) {
+ await openSettingsWindow();
+ }
+
+ if (url.includes("changelog")) {
+ setShowChangelogDialog(true);
+ }
+
+ if (url.includes("onboarding")) {
+ try {
+ await commands.showWindow("Onboarding");
+ } catch (error) {
+ console.error("Failed to show onboarding window:", error);
+ }
+ }
+
+ if (url.includes("status")) {
+ openStatusDialog();
+ }
+ }
+ });
+ return unsubscribeDeepLink;
+ };
+
+ let deepLinkUnsubscribe: (() => void) | undefined;
+
+ setupDeepLink().then((unsubscribe) => {
+ deepLinkUnsubscribe = unsubscribe;
+ });
+
+ const unlisten = Promise.all([
+ listen("shortcut-start-recording", async () => {
+ await commands.spawnScreenpipe(null);
+
+ toast({
+ title: "recording started",
+ description: "screen recording has been initiated",
+ });
+ }),
+
+ listen("shortcut-stop-recording", async () => {
+ await commands.stopScreenpipe();
+
+ toast({
+ title: "recording stopped",
+ description: "screen recording has been stopped",
+ });
+ }),
+
+ listen("cli-login", async (event) => {
+ console.log("received cli-login event:", event);
+ await reloadStore();
+ }),
+ ]);
+
+ return () => {
+ if (deepLinkUnsubscribe) {
+ deepLinkUnsubscribe();
+ }
+ unlisten.then((unsubscribes) => {
+ unsubscribes.forEach((unsubscribe) => unsubscribe());
+ });
+ };
+ }, [toast, setShowChangelogDialog, openStatusDialog, loadUser, reloadStore]);
+
+ return null; // This component doesn't render anything
+}
\ No newline at end of file
diff --git a/openrewind/components/dev-mode-settings.tsx b/openrewind/components/dev-mode-settings.tsx
index 912376b73..d592eb3d9 100644
--- a/openrewind/components/dev-mode-settings.tsx
+++ b/openrewind/components/dev-mode-settings.tsx
@@ -175,6 +175,10 @@ export const DevModeSettings = ({ localDataDir }: { localDataDir: string }) => {
}
};
+ if (!settings) {
+ return null;
+ }
+
return (
<>
<div className="w-full my-4 flex justify-center">
diff --git a/openrewind/components/header.tsx b/openrewind/components/header.tsx
index 5b73903de..793e85ac8 100644
--- a/openrewind/components/header.tsx
+++ b/openrewind/components/header.tsx
@@ -1,6 +1,5 @@
"use client";
import { Button } from "@/components/ui/button";
-import { Settings } from "@/components/settings";
import HealthStatus from "@/components/screenpipe-status";
import React from "react";
@@ -32,13 +31,13 @@ import {
Message,
} from "@/components/inbox-messages";
import { useState, useEffect } from "react";
-import { useOnboarding } from "@/lib/hooks/use-onboarding";
import { listen } from "@tauri-apps/api/event";
import localforage from "localforage";
import { useChangelogDialog } from "@/lib/hooks/use-changelog-dialog";
-import { useSettingsDialog } from "@/lib/hooks/use-settings-dialog";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { ShareLogsButton } from "./share-logs-button";
+import { openSettingsWindow } from "@/lib/utils/window";
+import { commands } from "@/lib/utils/tauri";
export default function Header() {
const [showInbox, setShowInbox] = useState(false);
@@ -104,11 +103,17 @@ export default function Header() {
await localforage.setItem("inboxMessages", []);
};
- const { setShowOnboarding } = useOnboarding();
const { setShowChangelogDialog } = useChangelogDialog();
- const { setIsOpen: setSettingsOpen } = useSettingsDialog();
const [isFeedbackOpen, setIsFeedbackOpen] = useState(false);
+ const handleShowOnboarding = async () => {
+ try {
+ await commands.showWindow("Onboarding");
+ } catch (error) {
+ console.error("Failed to show onboarding window:", error);
+ }
+ };
+
return (
<div>
<div className="relative z-[-1] flex flex-col items-center">
@@ -129,7 +134,6 @@ export default function Header() {
</PopoverContent>
</Popover>
<HealthStatus className="mt-3 cursor-pointer" />
- <Settings />
{/* <Button
variant="ghost"
@@ -156,9 +160,9 @@ export default function Header() {
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem
- onSelect={(e) => {
+ onSelect={async (e) => {
e.preventDefault();
- setSettingsOpen(true);
+ await openSettingsWindow();
}}
className="cursor-pointer p-1.5"
>
@@ -191,7 +195,7 @@ export default function Header() {
<DropdownMenuGroup>
<DropdownMenuItem
className="cursor-pointer"
- onClick={() => setShowOnboarding(true)}
+ onClick={() => handleShowOnboarding()}
>
<Play className="mr-2 h-4 w-4" />
<span>show onboarding</span>
diff --git a/openrewind/components/log-file-button.tsx b/openrewind/components/log-file-button.tsx
index f41189d2a..d984c854b 100644
--- a/openrewind/components/log-file-button.tsx
+++ b/openrewind/components/log-file-button.tsx
@@ -20,7 +20,7 @@ import {
} from "./ui/dialog";
import { useState, useEffect } from "react";
import { ScrollArea } from "./ui/scroll-area";
-import { invoke } from "@tauri-apps/api/core";
+import { commands, LogFile } from "@/lib/utils/tauri";
import React from "react";
import { LogViewer, LogViewerSearch } from "@patternfly/react-log-viewer";
import { Toolbar, ToolbarContent, ToolbarItem } from "@patternfly/react-core";
@@ -105,15 +105,15 @@ export const LogFileButton = ({
const [logContent, setLogContent] = useState("");
const [logFiles, setLogFiles] = useState<LogFile[]>([]);
- interface LogFile {
- name: string;
- path: string;
- modified_at: number;
- }
const getLogFiles = async () => {
try {
- const logFiles = await invoke("get_log_files");
- return logFiles as LogFile[];
+ const result = await commands.getLogFiles();
+ if (result.status === "ok") {
+ return result.data;
+ } else {
+ console.error("failed to get log files:", result.error);
+ return [];
+ }
} catch (error) {
console.error("failed to get log files:", error);
return [];
@@ -144,7 +144,7 @@ export const LogFileButton = ({
// Find most recent non-app log or fall back to first file
const appLog = files
.filter((f) => !f.name.toLowerCase().includes("app"))
- .sort((a, b) => b.modified_at - a.modified_at)[0];
+ .sort((a, b) => Number(b.modified_at - a.modified_at))[0];
if (files.length > 0) {
await loadLogContent(appLog?.path || files[0].path);
diff --git a/openrewind/components/onboarding.tsx b/openrewind/components/onboarding.tsx
deleted file mode 100644
index 77f6c175b..000000000
--- a/openrewind/components/onboarding.tsx
+++ /dev/null
@@ -1,203 +0,0 @@
-import localforage from "localforage";
-import React, { useState, useEffect } from "react";
-import { useToast } from "@/components/ui/use-toast";
-import { Dialog, DialogContent } from "@/components/ui/dialog";
-import OnboardingStatus from "@/components/onboarding/status";
-import OnboardingIntro from "@/components/onboarding/introduction";
-import OnboardingAPISetup from "@/components/onboarding/api-setup";
-import OnboardingInstructions from "@/components/onboarding/explain-instructions";
-import { useOnboarding } from "@/lib/hooks/use-onboarding";
-import { useSettings } from "@/lib/hooks/use-settings";
-import OnboardingLogin from "./onboarding/login";
-import posthog from "posthog-js";
-
-type SlideKey =
- | "intro"
- | "status"
- | "login"
- | "apiSetup"
- | "instructions";
-
-// Simplified flow - linear progression
-const getNextSlide = (currentSlide: SlideKey): SlideKey | null => {
- switch (currentSlide) {
- case "intro":
- return "status";
- case "status":
- return "login";
- case "login":
- return "apiSetup";
- case "apiSetup":
- return "instructions";
- case "instructions":
- return null;
- default:
- return null;
- }
-};
-
-const getPrevSlide = (currentSlide: SlideKey): SlideKey | null => {
- switch (currentSlide) {
- case "intro":
- return null;
- case "status":
- return "intro";
- case "login":
- return "status";
- case "apiSetup":
- return "login";
- case "instructions":
- return "apiSetup";
- default:
- return null;
- }
-};
-
-const trackOnboardingStep = (
- step: SlideKey | "completed",
- properties?: Record<string, any>
-) => {
- posthog.capture("onboarding_step", {
- step,
- ...properties,
- });
-};
-
-const Onboarding: React.FC = () => {
- const { toast } = useToast();
- const [currentSlide, setCurrentSlide] = useState<SlideKey>("intro");
- const [error, setError] = useState<string | null>(null);
- const [isVisible, setIsVisible] = useState(false);
- const [visitedSlides, setVisitedSlides] = useState<SlideKey[]>(["intro"]);
- const { showOnboarding, setShowOnboarding } = useOnboarding();
-
- useEffect(() => {
- setIsVisible(true);
- }, [currentSlide]);
-
- useEffect(() => {
- if (showOnboarding) {
- const hideCloseButton = () => {
- const closeButton = document.querySelector(".lucide-x");
- if (closeButton) {
- (closeButton as HTMLElement).classList.add("hidden");
- }
- };
- setTimeout(hideCloseButton, 100);
- }
- }, [showOnboarding]);
-
- useEffect(() => {
- if (error) {
- toast({
- title: "Error",
- description: error,
- variant: "destructive",
- });
- }
- }, [error, toast]);
-
- const handleNextSlide = () => {
- const nextSlide = getNextSlide(currentSlide);
-
- trackOnboardingStep(currentSlide, {
- direction: "next",
- });
-
- if (nextSlide) {
- setIsVisible(false);
- setTimeout(() => {
- setCurrentSlide(nextSlide);
- setVisitedSlides(prev => [...prev, nextSlide]);
- setError(null);
- }, 300);
- } else {
- handleEnd();
- }
- };
-
- const handlePrevSlide = () => {
- setIsVisible(false);
-
- trackOnboardingStep(currentSlide, {
- direction: "back",
- });
-
- setTimeout(() => {
- let prevSlide = getPrevSlide(currentSlide);
-
- if (prevSlide) {
- setError(null);
- setCurrentSlide(prevSlide);
- }
- }, 300);
- };
-
- const handleDialogClose = (open: boolean) => {
- if (!open && currentSlide) {
- setShowOnboarding(open);
- }
- };
-
- const handleEnd = async () => {
- trackOnboardingStep("completed");
-
- // Save user preferences
- await localforage.setItem("user_preferences", {
- completedAt: new Date().toISOString(),
- });
-
- // This will automatically set onboarding_completed to true
- setShowOnboarding(false);
- };
-
- return (
- <Dialog open={showOnboarding} onOpenChange={handleDialogClose}>
- <DialogContent className="max-w-5xl min-w-[1000px] min-h-[640px] max-h-[calc(100vh-100px)] overflow-hidden">
- <div className="flex flex-col w-full h-full overflow-hidden">
- {currentSlide === "intro" && (
- <OnboardingIntro
- className={`transition-opacity duration-300
- ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
- handleNextSlide={handleNextSlide}
- />
- )}
- {currentSlide === "status" && (
- <OnboardingStatus
- className={`transition-opacity duration-300
- ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
- handlePrevSlide={handlePrevSlide}
- handleNextSlide={handleNextSlide}
- />
- )}
- {currentSlide === "login" && (
- <OnboardingLogin
- className={`transition-opacity duration-300
- ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
- handleNextSlide={handleNextSlide}
- handlePrevSlide={handlePrevSlide}
- />
- )}
- {currentSlide === "apiSetup" && (
- <OnboardingAPISetup
- className={`transition-opacity duration-300 ease-in-out
- ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
- handleNextSlide={handleNextSlide}
- handlePrevSlide={handlePrevSlide}
- />
- )}
- {currentSlide === "instructions" && (
- <OnboardingInstructions
- className={`transition-opacity duration-300 ease-in-out
- ${isVisible ? "opacity-100 ease-out" : "opacity-0 ease-in"}`}
- handleNextSlide={handleEnd}
- handlePrevSlide={handlePrevSlide}
- />
- )}
- </div>
- </DialogContent>
- </Dialog>
- );
-};
-
-export default Onboarding;
diff --git a/openrewind/components/onboarding/api-setup.tsx b/openrewind/components/onboarding/api-setup.tsx
index 536a0b646..e28fcf8ce 100644
--- a/openrewind/components/onboarding/api-setup.tsx
+++ b/openrewind/components/onboarding/api-setup.tsx
@@ -3,7 +3,6 @@ import { useToast } from "@/components/ui/use-toast";
import { useSettings } from "@/lib/hooks/use-settings";
import { CardContent } from "@/components/ui/card";
import { ArrowUpRight } from "lucide-react";
-import { DialogTitle } from "@/components/ui/dialog";
import { open } from "@tauri-apps/plugin-shell";
import OnboardingNavigation from "@/components/onboarding/navigation";
@@ -37,10 +36,10 @@ const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({
// Check if at least one preset exists and has required fields
const hasValidPreset = React.useMemo(() => {
- if (!settings.aiPresets || settings.aiPresets.length === 0) return false;
+ if (!settings?.aiPresets || settings?.aiPresets.length === 0) return false;
// Find the default preset or the first one if no default is set
- const defaultPreset = settings.aiPresets.find(p => p.defaultPreset) || settings.aiPresets[0];
+ const defaultPreset = settings?.aiPresets.find(p => p.defaultPreset) || settings?.aiPresets[0];
if (!defaultPreset) return false;
@@ -59,14 +58,14 @@ const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({
return url?.trim() !== "" &&
model?.trim() !== "" &&
hasRequiredApiKey;
- }, [settings.aiPresets]);
+ }, [settings?.aiPresets]);
const handleValidationMoveNextSlide = async () => {
setIsValidating(true);
try {
// Find the default preset or the first one
- const defaultPreset = settings.aiPresets.find(p => p.defaultPreset) || settings.aiPresets[0];
+ const defaultPreset = settings?.aiPresets.find(p => p.defaultPreset) || settings?.aiPresets[0];
if (!defaultPreset) {
toast({
@@ -84,7 +83,7 @@ const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({
const apiKey = (provider === "openai" || provider === "custom") && "apiKey" in defaultPreset
? defaultPreset.apiKey
: provider === "screenpipe-cloud"
- ? settings.user.token
+ ? settings?.user?.token
: "";
const t = toast({
@@ -154,9 +153,9 @@ const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({
src="/128x128.png"
alt="screenpipe-logo"
/>
- <DialogTitle className="text-center text-2xl">
+ <h1 className="text-center text-2xl">
setup your ai settings
- </DialogTitle>
+ </h1>
</div>
<div className="mt-4 h-full w-full">
<CardContent className="flex flex-col items-center space-y-4 h-full">
diff --git a/openrewind/components/onboarding/dev-or-non-dev.tsx b/openrewind/components/onboarding/dev-or-non-dev.tsx
index a38c3756b..87b780714 100644
--- a/openrewind/components/onboarding/dev-or-non-dev.tsx
+++ b/openrewind/components/onboarding/dev-or-non-dev.tsx
@@ -7,6 +7,7 @@ import { Card, CardContent } from "@/components/ui/card";
import { DialogHeader, DialogTitle } from "@/components/ui/dialog";
import OnboardingNavigation from "@/components/onboarding/navigation";
import { invoke } from "@tauri-apps/api/core";
+import { SettingsStore } from "@/lib/utils/tauri";
interface OnboardingDevOrNonDevProps {
className?: string;
@@ -75,7 +76,7 @@ const OnboardingDevOrNonDev: React.FC<OnboardingDevOrNonDevProps> = ({
try {
if (option === "devMode") {
await updateSettings({ devMode: true });
- setLocalSettings({ ...localSettings, devMode: true });
+ setLocalSettings({ ...localSettings, devMode: true } as SettingsStore);
toast({
title: "success",
description: "dev mode enabled successfully",
@@ -83,7 +84,7 @@ const OnboardingDevOrNonDev: React.FC<OnboardingDevOrNonDevProps> = ({
});
} else if (option === "nonDevMode") {
await updateSettings({ devMode: false });
- setLocalSettings({ ...localSettings, devMode: false });
+ setLocalSettings({ ...localSettings, devMode: false } as SettingsStore);
toast({
title: "success",
description: "screenpipe backend is in standard mode",
diff --git a/openrewind/components/onboarding/explain-instructions.tsx b/openrewind/components/onboarding/explain-instructions.tsx
index df68246a4..6885ae6e8 100644
--- a/openrewind/components/onboarding/explain-instructions.tsx
+++ b/openrewind/components/onboarding/explain-instructions.tsx
@@ -1,17 +1,19 @@
import React from "react";
-import { DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { RainbowButton } from "../ui/rainbow-button";
-import {
- CheckCircle,
- Play,
- Search,
- MessageSquare,
- ArrowRight,
- Sparkles,
+import {
+ ArrowLeft,
+ ArrowRight,
+ Video,
+ Mic,
+ Search,
+ Clock,
+ Settings,
+ Bot,
+ MonitorSpeaker
} from "lucide-react";
-import OnboardingNavigation from "@/components/onboarding/navigation";
import { motion } from "framer-motion";
+import { Card, CardContent } from "@/components/ui/card";
interface OnboardingInstructionsProps {
className?: string;
@@ -20,69 +22,66 @@ interface OnboardingInstructionsProps {
}
const OnboardingInstructions: React.FC<OnboardingInstructionsProps> = ({
- className,
+ className = "",
handleNextSlide,
handlePrevSlide,
}) => {
- const features = [
+ const steps = [
{
- icon: Play,
- title: "Recording Started",
- description: "OpenRewind is now capturing your screen and audio",
- status: "active"
+ icon: MonitorSpeaker,
+ title: "Background Recording",
+ description: "OpenRewind runs quietly in the background, capturing your screen and audio activities without interruption.",
+ color: "text-blue-500"
+ },
+ {
+ icon: Clock,
+ title: "Timeline View",
+ description: "Access your timeline to see a visual representation of your day's activities, organized chronologically.",
+ color: "text-green-500"
},
{
icon: Search,
- title: "Timeline Ready",
- description: "View and navigate through your recorded activities",
- status: "ready"
+ title: "AI Search",
+ description: "Use natural language to search through your recorded data. Ask questions like 'What did I work on yesterday?'",
+ color: "text-purple-500"
},
{
- icon: MessageSquare,
- title: "AI Assistant",
- description: "Ask questions about your recorded data",
- status: "ready"
+ icon: Settings,
+ title: "Customize Settings",
+ description: "Adjust recording preferences, privacy settings, and AI configurations to match your workflow.",
+ color: "text-orange-500"
}
];
- const quickTips = [
- "Use the timeline at the bottom to navigate through your day",
- "Scroll through your screen recordings with your mouse wheel",
- "Click the AI panel to ask questions about what you've recorded",
- "Audio transcriptions will appear automatically for meetings and calls"
+ const shortcuts = [
+ { key: "⌘ + ⌥ + S", description: "Show/Hide OpenRewind" },
+ { key: "⌘ + ⌥ + U", description: "Start Recording" },
+ { key: "⌘ + ⌥ + X", description: "Stop Recording" },
];
return (
- <div className={`${className} flex flex-col h-full`}>
- <DialogHeader className="flex flex-col px-2 justify-center items-center mb-6">
+ <div className={`flex justify-center items-center flex-col space-y-6 p-8 ${className}`}>
+ <div className="flex flex-col px-2 justify-center items-center mb-6">
<motion.div
+ className="w-16 h-16 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mb-4"
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 0.5 }}
- className="relative"
>
- <img
- className="w-20 h-20 justify-center mb-4"
- src="/128x128.png"
- alt="openrewind-logo"
- />
- <div className="absolute -top-2 -right-2">
- <CheckCircle className="w-8 h-8 text-green-500 bg-white rounded-full" />
- </div>
+ <Bot className="w-8 h-8 text-white" />
</motion.div>
-
- <DialogTitle className="text-center text-2xl font-bold">
- You&apos;re all set! 🎉
- </DialogTitle>
- <p className="text-center text-muted-foreground mt-2 max-w-md">
- OpenRewind is ready to help you remember, find, and understand everything you do on your computer.
+ <h1 className="text-center text-2xl font-bold mb-2">
+ You&apos;re All Set! 🎉
+ </h1>
+ <p className="text-center text-muted-foreground max-w-md">
+ OpenRewind is now configured and ready to help you remember everything. Here&apos;s how to get the most out of it.
</p>
- </DialogHeader>
+ </div>
<div className="flex-1 flex flex-col items-center justify-center space-y-6">
{/* Status Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-w-4xl">
- {features.map((feature, index) => (
+ {steps.map((step, index) => (
<motion.div
key={index}
initial={{ opacity: 0, y: 20 }}
@@ -91,13 +90,10 @@ const OnboardingInstructions: React.FC<OnboardingInstructionsProps> = ({
className="bg-card border rounded-xl p-4 text-center"
>
<div className="flex items-center justify-center mb-3">
- <feature.icon className="w-8 h-8 text-primary" />
- {feature.status === "active" && (
- <div className="ml-2 w-2 h-2 bg-green-500 rounded-full animate-pulse" />
- )}
+ <step.icon className={`w-8 h-8 ${step.color}`} />
</div>
- <h3 className="font-semibold text-sm mb-1">{feature.title}</h3>
- <p className="text-xs text-muted-foreground">{feature.description}</p>
+ <h3 className="font-semibold text-sm mb-1">{step.title}</h3>
+ <p className="text-xs text-muted-foreground">{step.description}</p>
</motion.div>
))}
</div>
@@ -110,14 +106,14 @@ const OnboardingInstructions: React.FC<OnboardingInstructionsProps> = ({
className="bg-gradient-to-r from-blue-50 to-purple-50 dark:from-blue-950/20 dark:to-purple-950/20 rounded-xl p-6 max-w-2xl"
>
<div className="flex items-center justify-center mb-4">
- <Sparkles className="w-5 h-5 text-orange-500 mr-2" />
+ <Settings className="w-5 h-5 text-orange-500 mr-2" />
<h3 className="text-lg font-semibold">Quick Tips</h3>
</div>
<ul className="space-y-2 text-sm">
- {quickTips.map((tip, index) => (
+ {shortcuts.map((shortcut, index) => (
<li key={index} className="flex items-start">
<div className="w-2 h-2 bg-primary rounded-full mt-2 mr-3 flex-shrink-0" />
- <span className="text-muted-foreground">{tip}</span>
+ <span className="text-muted-foreground">{shortcut.key} - {shortcut.description}</span>
</li>
))}
</ul>
diff --git a/openrewind/components/onboarding/introduction.tsx b/openrewind/components/onboarding/introduction.tsx
index b24de68d8..e3da4d9db 100644
--- a/openrewind/components/onboarding/introduction.tsx
+++ b/openrewind/components/onboarding/introduction.tsx
@@ -1,5 +1,4 @@
import React, { useState } from "react";
-import { DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { RainbowButton } from "../ui/rainbow-button";
import { ArrowRight, Video, Mic, Brain, Clock, Play } from "lucide-react";
@@ -7,6 +6,7 @@ import { useSettings } from "@/lib/hooks/use-settings";
import posthog from "posthog-js";
import { useOnboarding } from "@/lib/hooks/use-onboarding";
import { motion } from "framer-motion";
+import { commands } from "@/lib/utils/tauri";
interface OnboardingIntroProps {
className?: string;
@@ -17,13 +17,25 @@ const OnboardingIntro: React.FC<OnboardingIntroProps> = ({
className = "",
handleNextSlide,
}) => {
- const { setShowOnboarding } = useOnboarding();
+ const { completeOnboarding } = useOnboarding();
const [currentStep, setCurrentStep] = useState(0);
const [showDemo, setShowDemo] = useState(false);
- const handleSkip = () => {
- setShowOnboarding(false);
- posthog.capture("onboarding_skipped");
+ const handleSkip = async () => {
+ try {
+ await completeOnboarding();
+ posthog.capture("onboarding_skipped");
+
+ // Show main window and close onboarding window
+ await commands.showWindow("Main");
+
+ // Close the onboarding window
+ if (typeof window !== 'undefined' && 'close' in window) {
+ window.close();
+ }
+ } catch (error) {
+ console.error("Error skipping onboarding:", error);
+ }
};
const features = [
@@ -62,7 +74,7 @@ const OnboardingIntro: React.FC<OnboardingIntroProps> = ({
return (
<div className={`flex justify-center items-center flex-col space-y-6 ${className}`}>
- <DialogHeader className="flex flex-col px-2 justify-center items-center">
+ <div className="flex flex-col px-2 justify-center items-center">
<motion.img
className="w-24 h-24 justify-center"
src="/128x128.png"
@@ -71,13 +83,13 @@ const OnboardingIntro: React.FC<OnboardingIntroProps> = ({
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 0.5 }}
/>
- <DialogTitle className="text-center text-3xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
+ <h1 className="text-center text-3xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
Welcome to OpenRewind
- </DialogTitle>
+ </h1>
<p className="text-center text-lg text-muted-foreground mt-2">
Your AI-powered digital memory assistant
</p>
- </DialogHeader>
+ </div>
{!showDemo ? (
<>
diff --git a/openrewind/components/onboarding/login.tsx b/openrewind/components/onboarding/login.tsx
index 7190b13fa..52b31a697 100644
--- a/openrewind/components/onboarding/login.tsx
+++ b/openrewind/components/onboarding/login.tsx
@@ -23,7 +23,7 @@ const OnboardingLogin: React.FC<OnboardingLoginProps> = ({
<div className="w-full h-full flex flex-col items-center justify-center space-y-6 py-4">
<div className="w-full max-w-md space-y-6">
<div className="text-center space-y-2 mb-8">
- <h1 className="text-3xl font-bold">login to screenpipe</h1>
+ <h1 className="text-3xl font-bold">login to openrewind</h1>
<p className="text-sm text-muted-foreground">
connect your account to unlock all features
</p>
@@ -31,10 +31,10 @@ const OnboardingLogin: React.FC<OnboardingLoginProps> = ({
<div className="p-6 border border-border/50 rounded-lg bg-background/50">
<div className="space-y-4">
- {settings.user?.token ? (
+ {settings?.user?.token ? (
<p className="text-sm text-muted-foreground flex items-center justify-center gap-2">
<span className="inline-flex h-2 w-2 rounded-full bg-green-500" />
- logged in as {settings.user.email}
+ logged in as {settings?.user?.email}
</p>
) : (
<p className="text-sm text-muted-foreground flex items-center justify-center gap-2">
@@ -44,7 +44,7 @@ const OnboardingLogin: React.FC<OnboardingLoginProps> = ({
)}
<div className="flex flex-col gap-2">
- {settings.user?.token ? (
+ {settings?.user?.token ? (
<>
<Button
variant="outline"
@@ -58,7 +58,7 @@ const OnboardingLogin: React.FC<OnboardingLoginProps> = ({
variant="outline"
size="sm"
onClick={() => {
- updateSettings({ user: { token: undefined } });
+ updateSettings({ user: undefined });
toast({
title: "logged out",
description: "you have been logged out",
diff --git a/openrewind/components/onboarding/status.tsx b/openrewind/components/onboarding/status.tsx
index f0fb46dc7..804159eb9 100644
--- a/openrewind/components/onboarding/status.tsx
+++ b/openrewind/components/onboarding/status.tsx
@@ -1,6 +1,5 @@
import React, { useState, useEffect, useRef } from "react";
import { Check, HelpCircle, Video, ChevronDown } from "lucide-react";
-import { DialogHeader, DialogTitle } from "@/components/ui/dialog";
import OnboardingNavigation from "@/components/onboarding/navigation";
import { Button } from "../ui/button";
import { Switch } from "../ui/switch";
@@ -250,9 +249,9 @@ const OnboardingStatus: React.FC<OnboardingStatusProps> = ({
<div className="w-32 h-32 flex items-center justify-center">
<img className="w-32 h-32" src="/128x128.png" alt="screenpipe-logo" />
</div>
- <DialogTitle className="text-center text-2xl">
+ <h1 className="text-center text-2xl">
setting up screenpipe
- </DialogTitle>
+ </h1>
<p className="text-sm text-muted-foreground pt-2">
100% local-first • your data never leaves your device
</p>
diff --git a/openrewind/components/rewind/ai-presets-selector.tsx b/openrewind/components/rewind/ai-presets-selector.tsx
index 4411cc332..c798d9fa2 100644
--- a/openrewind/components/rewind/ai-presets-selector.tsx
+++ b/openrewind/components/rewind/ai-presets-selector.tsx
@@ -51,6 +51,7 @@ import {
} from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Slider } from "./ui/slider";
+import { AIPreset } from "@/lib/utils/tauri";
export const Icons = {
openai: (props: any) => (
@@ -69,32 +70,6 @@ export const Icons = {
spinner: Loader2,
};
-interface BaseAIPreset {
- id: string;
- maxContextChars: number;
- url: string;
- model: string;
- defaultPreset: boolean;
- prompt: string;
-}
-
-type AIPreset = BaseAIPreset &
- (
- | {
- provider: "openai";
- apiKey: string;
- }
- | {
- provider: "native-ollama";
- }
- | {
- provider: "screenpipe-cloud";
- }
- | {
- provider: "custom";
- apiKey?: string;
- }
- );
interface BaseRecommendedPreset {
id: string;
@@ -117,28 +92,9 @@ type RecommendedPreset = BaseRecommendedPreset &
);
interface AIProviderConfigProps {
- onSubmit: (data: AIProviderData) => void;
- defaultPreset?: {
- provider: "openai" | "native-ollama" | "custom" | "screenpipe-cloud";
- apiKey?: string;
- baseUrl?: string;
- modelName?: string;
- maxContextChars?: number;
- prompt?: string;
- id?: string;
- };
+ onSubmit: (data: AIPreset) => void;
+ defaultPreset?: AIPreset;
}
-
-interface AIProviderData {
- provider: "openai" | "native-ollama" | "custom" | "screenpipe-cloud";
- apiKey?: string;
- baseUrl?: string;
- modelName?: string;
- maxContextChars?: number;
- prompt?: string;
- id?: string;
-}
-
interface OpenAIModel {
id: string;
created?: number;
@@ -157,7 +113,7 @@ export function AIProviderConfig({
defaultPreset,
}: AIProviderConfigProps) {
const [selectedProvider, setSelectedProvider] = useState<
- AIProviderData["provider"]
+ AIPreset["provider"]
>(defaultPreset?.provider || "openai");
const { settings } = useSettings();
const [isLoading, setIsLoading] = useState(false);
@@ -165,14 +121,15 @@ export function AIProviderConfig({
const [isLoadingModels, setIsLoadingModels] = useState(false);
const [idError, setIdError] = useState<string | null>(null);
const [showApiKey, setShowApiKey] = useState(false);
- const [formData, setFormData] = useState<AIProviderData>({
+ const [formData, setFormData] = useState<AIPreset>({
provider: defaultPreset?.provider || "openai",
apiKey: defaultPreset?.apiKey || "",
- baseUrl: defaultPreset?.baseUrl || "",
- modelName: defaultPreset?.modelName || "",
+ url: defaultPreset?.url || "",
+ model: defaultPreset?.model || "",
maxContextChars: defaultPreset?.maxContextChars || 512000,
prompt: defaultPreset?.prompt || DEFAULT_PROMPT,
id: defaultPreset?.id || "",
+ defaultPreset: defaultPreset?.defaultPreset || false,
});
const validateId = (id: string | undefined): boolean => {
@@ -272,12 +229,12 @@ export function AIProviderConfig({
);
} else if (
selectedProvider === "custom" &&
- formData.baseUrl &&
+ formData.url &&
formData.apiKey
) {
- fetchOpenAIModels(formData.baseUrl, formData.apiKey);
+ fetchOpenAIModels(formData.url, formData.apiKey);
}
- }, [selectedProvider, formData.apiKey, formData.baseUrl]);
+ }, [selectedProvider, formData.apiKey, formData.url]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -365,7 +322,7 @@ export function AIProviderConfig({
setFormData({
...formData,
provider: "native-ollama",
- baseUrl: "http://localhost:11434/v1",
+ url: "http://localhost:11434/v1",
});
}}
>
@@ -385,7 +342,7 @@ export function AIProviderConfig({
setFormData({
...formData,
provider: "screenpipe-cloud",
- baseUrl: "https://ai-proxy.i-f9f.workers.dev/v1",
+ url: "https://ai-proxy.i-f9f.workers.dev/v1",
});
}}
>
@@ -407,7 +364,7 @@ export function AIProviderConfig({
setFormData({
...formData,
provider: "custom",
- baseUrl: "http://localhost:11434/v1",
+ url: "http://localhost:11434/v1",
});
}}
>
@@ -449,9 +406,9 @@ export function AIProviderConfig({
<div className="space-y-2">
<Label htmlFor="model">model</Label>
<Select
- value={formData.modelName}
+ value={formData.model}
onValueChange={(value) =>
- setFormData({ ...formData, modelName: value })
+ setFormData({ ...formData, model: value })
}
>
<SelectTrigger>
@@ -487,18 +444,18 @@ export function AIProviderConfig({
id="baseUrl"
type="text"
placeholder="http://localhost:11434"
- value={formData.baseUrl || ""}
+ value={formData.url || ""}
onChange={(e) =>
- setFormData({ ...formData, baseUrl: e.target.value })
+ setFormData({ ...formData, url: e.target.value })
}
/>
</div>
<div className="space-y-2">
<Label htmlFor="model">model</Label>
<Select
- value={formData.modelName}
+ value={formData.model}
onValueChange={(value) =>
- setFormData({ ...formData, modelName: value })
+ setFormData({ ...formData, model: value })
}
>
<SelectTrigger>
@@ -531,9 +488,9 @@ export function AIProviderConfig({
<div className="space-y-2">
<Label htmlFor="model">model</Label>
<Select
- value={formData.modelName}
+ value={formData.model}
onValueChange={(value) =>
- setFormData({ ...formData, modelName: value })
+ setFormData({ ...formData, model: value })
}
>
<SelectTrigger>
@@ -569,9 +526,9 @@ export function AIProviderConfig({
id="baseUrl"
type="text"
placeholder="https://api.example.com/v1"
- value={formData.baseUrl || ""}
+ value={formData.url || ""}
onChange={(e) =>
- setFormData({ ...formData, baseUrl: e.target.value })
+ setFormData({ ...formData, url: e.target.value })
}
/>
</div>
@@ -606,9 +563,9 @@ export function AIProviderConfig({
<div className="space-y-2">
<Label htmlFor="model">model</Label>
<Select
- value={formData.modelName}
+ value={formData.model}
onValueChange={(value) =>
- setFormData({ ...formData, modelName: value })
+ setFormData({ ...formData, model: value })
}
>
<SelectTrigger>
@@ -693,7 +650,7 @@ export function AIProviderConfig({
className="w-full"
disabled={
isLoading ||
- Boolean(!formData.id?.length && !formData.modelName?.length)
+ Boolean(!formData.id?.length && !formData.model?.length)
}
>
{isLoading ? (
@@ -751,9 +708,12 @@ export const AIPresetDialog = ({
? {
id: preset.id,
provider: preset.provider,
- baseUrl: preset.url,
- modelName: preset.model,
- ...("apiKey" in preset ? { apiKey: preset.apiKey } : {}),
+ url: preset.url,
+ model: preset.model,
+ maxContextChars: preset.maxContextChars,
+ prompt: preset.prompt,
+ defaultPreset: preset.defaultPreset,
+ apiKey: preset.apiKey || null,
}
: undefined;
@@ -828,14 +788,6 @@ export const AIPresetsSelector = ({
updateSettings({
aiPresets: updatedPresets,
- aiModel: nextPreset.model,
- aiProviderType: nextPreset.provider,
- customPrompt: nextPreset.prompt,
- aiMaxContextChars: nextPreset.maxContextChars,
- aiUrl: nextPreset.url,
- ...("apiKey" in nextPreset && {
- openaiApiKey: nextPreset.apiKey,
- }),
});
toast.success("Preset changed", {
@@ -909,14 +861,6 @@ export const AIPresetsSelector = ({
if (isEditingDefaultPreset) {
updateSettings({
aiPresets: updatedPresets,
- aiModel: preset.model,
- aiProviderType: preset.provider,
- customPrompt: preset.prompt,
- aiMaxContextChars: preset.maxContextChars,
- aiUrl: preset.url,
- ...("apiKey" in preset && {
- openaiApiKey: preset.apiKey,
- }),
});
} else {
updateSettings({
@@ -950,14 +894,7 @@ export const AIPresetsSelector = ({
updateSettings({
aiPresets: [newPreset],
- aiModel: newPreset.model,
- aiProviderType: newPreset.provider,
- customPrompt: newPreset.prompt,
- aiMaxContextChars: newPreset.maxContextChars,
- aiUrl: newPreset.url,
- ...("apiKey" in newPreset && {
- openaiApiKey: newPreset.apiKey,
- }),
+
});
} else {
// Adding a new preset
@@ -1006,14 +943,6 @@ export const AIPresetsSelector = ({
updateSettings({
aiPresets: updatedPresets,
- aiModel: preset.model,
- aiProviderType: preset.provider,
- customPrompt: preset.prompt,
- aiMaxContextChars: preset.maxContextChars,
- aiUrl: preset.url,
- ...("apiKey" in preset && {
- openaiApiKey: preset.apiKey,
- }),
});
toast.success("Default preset updated", {
@@ -1196,14 +1125,6 @@ export const AIPresetsSelector = ({
updateSettings({
aiPresets: updatedPresets,
- aiModel: selectedPresetObj.model,
- aiProviderType: selectedPresetObj.provider,
- customPrompt: selectedPresetObj.prompt,
- aiMaxContextChars: selectedPresetObj.maxContextChars,
- aiUrl: selectedPresetObj.url,
- ...("apiKey" in selectedPresetObj && {
- openaiApiKey: selectedPresetObj.apiKey,
- }),
});
toast.success("Preset selected", {
diff --git a/openrewind/components/rewind/timeline.tsx b/openrewind/components/rewind/timeline.tsx
index cdd4af46f..7e7d1b06e 100644
--- a/openrewind/components/rewind/timeline.tsx
+++ b/openrewind/components/rewind/timeline.tsx
@@ -326,7 +326,7 @@ export default function Timeline() {
ref={containerRef}
className="inset-0 flex flex-col bg-background text-foreground relative"
style={{
- height: "100vh",
+ height: "calc(100vh - 2rem)",
overscrollBehavior: "none",
WebkitUserSelect: "none",
userSelect: "none",
@@ -350,9 +350,9 @@ export default function Timeline() {
</div>
</div>
- <div className="flex-1 relative min-h-0">
+ <div className="flex-1 relative min-h-0 pt-4">
{isLoading && (
- <div className="absolute inset-0 flex items-center justify-center backdrop-blur-sm">
+ <div className="absolute inset-0 top-4 flex items-center justify-center backdrop-blur-sm">
<div className="bg-background/95 p-6 border rounded-xl shadow-lg text-center space-y-3 max-w-md mx-4">
<h3 className="font-medium">Loading Timeline</h3>
<p className="text-sm text-muted-foreground">
diff --git a/openrewind/components/rewind/timeline/ai-panel.tsx b/openrewind/components/rewind/timeline/ai-panel.tsx
index 0ad3a3e6e..af0a95040 100644
--- a/openrewind/components/rewind/timeline/ai-panel.tsx
+++ b/openrewind/components/rewind/timeline/ai-panel.tsx
@@ -5,7 +5,7 @@ import { ChatMessage } from "@/components/rewind/chat-message";
import { useToast } from "@/components/ui/use-toast";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
-import { Loader2, Send, Square, X, GripHorizontal, Bot, Terminal } from "lucide-react";
+import { Loader2, Send, Square, X, GripHorizontal, Bot } from "lucide-react";
import { StreamTimeSeriesResponse } from "@/components/rewind/timeline";
import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";
import { Agent } from "./agents";
@@ -15,11 +15,11 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
-import { AIPreset, useSettings } from "@/lib/hooks/use-settings";
+import { useSettings } from "@/lib/hooks/use-settings";
import { ExportButton } from "../export-button";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import Image from "next/image";
import { AIPresetsSelector } from "../ai-presets-selector";
+import { AIPreset } from "@/lib/utils/tauri";
const providerIcons = {
openai: <Image src="/images/openai.png" alt="OpenAI" width={16} height={16} />,
diff --git a/openrewind/components/rewind/timeline/timeline-controls.tsx b/openrewind/components/rewind/timeline/timeline-controls.tsx
index 7af993e4b..cba080f4d 100644
--- a/openrewind/components/rewind/timeline/timeline-controls.tsx
+++ b/openrewind/components/rewind/timeline/timeline-controls.tsx
@@ -28,11 +28,11 @@ import {
} from "@/components/ui/dropdown-menu";
import { open } from "@tauri-apps/plugin-shell";
import HealthStatus from "@/components/screenpipe-status";
-import { Settings } from "@/components/settings";
import { ShareLogsButton } from "@/components/share-logs-button";
import { useOnboarding } from "@/lib/hooks/use-onboarding";
import { useChangelogDialog } from "@/lib/hooks/use-changelog-dialog";
-import { useSettingsDialog } from "@/lib/hooks/use-settings-dialog";
+import { openSettingsWindow } from "@/lib/utils/window";
+import { commands } from "@/lib/utils/tauri";
import { CommandShortcut } from "@/components/ui/command";
@@ -63,8 +63,6 @@ interface TimelineControlsProps {
className?: string;
}
-
-
export function TimelineControls({
startAndEndDates,
currentDate,
@@ -74,9 +72,15 @@ export function TimelineControls({
}: TimelineControlsProps) {
const [isFeedbackOpen, setIsFeedbackOpen] = useState(false);
- const { setShowOnboarding } = useOnboarding();
const { setShowChangelogDialog } = useChangelogDialog();
- const { setIsOpen: setSettingsOpen } = useSettingsDialog();
+
+ const handleShowOnboarding = async () => {
+ try {
+ await commands.showWindow("Onboarding");
+ } catch (error) {
+ console.error("Failed to show onboarding window:", error);
+ }
+ };
const jumpDay = async (days: number) => {
const today = new Date();
@@ -194,9 +198,6 @@ export function TimelineControls({
</PopoverContent>
</Popover>
- <HealthStatus className="cursor-pointer" />
- <Settings />
-
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
@@ -213,9 +214,9 @@ export function TimelineControls({
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem
- onSelect={(e) => {
+ onSelect={async (e) => {
e.preventDefault();
- setSettingsOpen(true);
+ await openSettingsWindow();
}}
className="cursor-pointer p-1.5"
>
@@ -248,7 +249,7 @@ export function TimelineControls({
<DropdownMenuGroup>
<DropdownMenuItem
className="cursor-pointer"
- onClick={() => setShowOnboarding(true)}
+ onClick={() => handleShowOnboarding()}
>
<Play className="mr-2 h-4 w-4" />
<span>show onboarding</span>
diff --git a/openrewind/components/rewind/timeline/timeline-search.tsx b/openrewind/components/rewind/timeline/timeline-search.tsx
index 1030562e3..356567b25 100644
--- a/openrewind/components/rewind/timeline/timeline-search.tsx
+++ b/openrewind/components/rewind/timeline/timeline-search.tsx
@@ -547,7 +547,8 @@ prioritize precision over recall - better to return no match than a wrong match.
}, [appStats]);
const loadSuggestionsIfNeeded = useCallback(() => {
- if (!settings?.aiModel) {
+ const defaultPreset = settings?.aiPresets?.find(p => p.defaultPreset) || settings?.aiPresets?.[0];
+ if (!defaultPreset?.model) {
setSuggestions([]);
return;
}
@@ -561,16 +562,16 @@ prioritize precision over recall - better to return no match than a wrong match.
const openai = new OpenAI({
apiKey:
- settings?.aiProviderType === "screenpipe-cloud"
+ (defaultPreset.provider === "screenpipe-cloud"
? settings?.user?.token
- : settings?.openaiApiKey,
- baseURL: settings?.aiUrl,
+ : defaultPreset.apiKey) || undefined,
+ baseURL: defaultPreset.url,
dangerouslyAllowBrowser: true,
});
getCachedOrGenerateSuggestions(
openai,
- settings?.aiModel,
+ defaultPreset.model,
getSystemPrompt(),
appStats,
)
@@ -609,12 +610,14 @@ prioritize precision over recall - better to return no match than a wrong match.
setIsSearching(true);
setSearchStatus("");
+ const defaultPreset = settings?.aiPresets?.find(p => p.defaultPreset) || settings?.aiPresets?.[0];
+
const openai = new OpenAI({
apiKey:
- settings?.aiProviderType === "screenpipe-cloud"
+ (defaultPreset?.provider === "screenpipe-cloud"
? settings?.user?.token
- : settings?.openaiApiKey,
- baseURL: settings?.aiUrl,
+ : defaultPreset?.apiKey) || undefined,
+ baseURL: defaultPreset?.url,
dangerouslyAllowBrowser: true,
});
@@ -625,7 +628,7 @@ prioritize precision over recall - better to return no match than a wrong match.
query,
frames,
openai,
- settings?.aiModel || "mistral",
+ defaultPreset?.model || "mistral",
(status) => setSearchStatus(status),
systemPrompt,
0,
@@ -656,12 +659,14 @@ prioritize precision over recall - better to return no match than a wrong match.
const regenerateSuggestions = useCallback(async () => {
setIsLoadingSuggestions(true);
+ const defaultPreset = settings?.aiPresets?.find(p => p.defaultPreset) || settings?.aiPresets?.[0];
+
const openai = new OpenAI({
apiKey:
- settings?.aiProviderType === "screenpipe-cloud"
+ (defaultPreset?.provider === "screenpipe-cloud"
? settings?.user?.token
- : settings?.openaiApiKey,
- baseURL: settings?.aiUrl,
+ : defaultPreset?.apiKey) || undefined,
+ baseURL: defaultPreset?.url,
dangerouslyAllowBrowser: true,
});
@@ -671,7 +676,7 @@ prioritize precision over recall - better to return no match than a wrong match.
const newSuggestions = await generateSuggestions(
openai,
- settings?.aiModel || "mistral",
+ defaultPreset?.model || "mistral",
getSystemPrompt(),
appStats,
);
diff --git a/openrewind/components/screenpipe-status.tsx b/openrewind/components/screenpipe-status.tsx
index 35cc4b29b..c6d65b033 100644
--- a/openrewind/components/screenpipe-status.tsx
+++ b/openrewind/components/screenpipe-status.tsx
@@ -14,7 +14,7 @@ import { Separator } from "./ui/separator";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { Folder, Activity, Mic, RefreshCw, AlertTriangle } from "lucide-react";
import { open as openUrl } from "@tauri-apps/plugin-shell";
-import { invoke } from "@tauri-apps/api/core";
+import { commands } from "@/lib/utils/tauri";
import { LogFileButton } from "./log-file-button";
import { DevModeSettings } from "./dev-mode-settings";
@@ -57,7 +57,7 @@ const HealthStatus = ({ className }: { className?: string }) => {
});
// Stop the server first
- await invoke("stop_screenpipe");
+ await commands.stopScreenpipe();
// Wait a moment for cleanup
await new Promise(resolve => setTimeout(resolve, 2000));
@@ -69,7 +69,7 @@ const HealthStatus = ({ className }: { className?: string }) => {
});
// Start the server
- await invoke("spawn_screenpipe");
+ await commands.spawnScreenpipe(null);
toast({
title: "server restarted",
@@ -168,21 +168,23 @@ const HealthStatus = ({ className }: { className?: string }) => {
return (
<>
- <Badge
+ <Button
variant="default"
className={cn(
- "cursor-pointer bg-transparent text-foreground hover:bg-accent hover:text-accent-foreground"
+ "cursor-pointer bg-transparent text-foreground hover:bg-transparent hover:text-foreground group"
)}
onClick={handleOpenStatusDialog}
>
{/* <Power className="mr-2 h-4 w-4" /> */}
- <Activity className="mr-2 h-4 w-4" />
+ <Badge variant={"secondary"} className="group-hover:bg-transparent group-hover:text-foreground">
+ status
+ </Badge>
<span
className={`ml-1 w-2 h-2 rounded-full ${statusColor} inline-block ${
statusColor === "bg-red-500" ? "animate-pulse" : ""
}`}
/>
- </Badge>
+ </Button>
<Dialog open={isOpen} onOpenChange={close}>
<DialogContent
className="max-w-4xl max-h-[90vh] flex flex-col p-8"
diff --git a/openrewind/components/settings.tsx b/openrewind/components/settings.tsx
deleted file mode 100644
index 281817d74..000000000
--- a/openrewind/components/settings.tsx
+++ /dev/null
@@ -1,329 +0,0 @@
-"use client";
-
-import React, { useEffect, useState } from "react";
-import { useSettings } from "@/lib/hooks/use-settings";
-import {
- Brain,
- Video,
- Keyboard,
- User,
- ChevronDown,
- Plus,
- Trash2,
- Check,
- Settings as SettingsIcon,
- X,
- HardDrive,
-} from "lucide-react";
-import { DialogHeader, DialogTitle } from "./ui/dialog";
-import { cn } from "@/lib/utils";
-import { AccountSection } from "./settings/account-section";
-import ShortcutSection from "./settings/shortcut-section";
-import AISection from "./settings/ai-section";
-import { AIPresets } from "./settings/ai-presets";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "./ui/dropdown-menu";
-import { Input } from "./ui/input";
-import { Button } from "./ui/button";
-import { relaunch } from "@tauri-apps/plugin-process";
-import { invoke } from "@tauri-apps/api/core";
-import { useProfiles } from "@/lib/hooks/use-profiles";
-import { toast } from "./ui/use-toast";
-import { Dialog, DialogContent } from "./ui/dialog";
-import { useSettingsDialog } from "@/lib/hooks/use-settings-dialog";
-import { RecordingSettings } from "./settings/recording-settings";
-import GeneralSettings from "./settings/general-settings";
-import { DiskUsageSection } from "./settings/disk-usage-section";
-
-type SettingsSection =
- | "general"
- | "ai"
- | "shortcuts"
- | "recording"
- | "account"
- | "disk-usage";
-
-export function Settings() {
- const { isOpen, setIsOpen: setSettingsOpen } = useSettingsDialog();
- const {
- profiles,
- activeProfile,
- createProfile,
- deleteProfile,
- setActiveProfile,
- } = useProfiles();
- const [activeSection, setActiveSection] =
- useState<SettingsSection>("general");
- const [isCreatingProfile, setIsCreatingProfile] = useState(false);
- const [newProfileName, setNewProfileName] = useState("");
- const { settings } = useSettings();
-
- const handleProfileChange = async () => {
- toast({
- title: "Restarting Screenpipe",
- description: "Please wait while we restart Screenpipe",
- });
- await invoke("stop_screenpipe");
-
- await new Promise((resolve) => setTimeout(resolve, 1000));
-
- await invoke("spawn_screenpipe");
-
- await new Promise((resolve) => setTimeout(resolve, 1000));
- relaunch();
- };
-
- const handleCreateProfile = async () => {
- if (newProfileName.trim() === "default") {
- toast({
- title: "Profile name not allowed",
- description: "Please choose a different name for your profile",
- variant: "destructive",
- });
- return;
- }
- if (newProfileName.trim()) {
- console.log("creating profile", newProfileName.trim());
- createProfile({
- profileName: newProfileName.trim(),
- currentSettings: settings,
- });
- setActiveProfile(newProfileName.trim());
- setNewProfileName("");
- setIsCreatingProfile(false);
- handleProfileChange();
- }
- };
-
- const handleSwitchProfile = async (profileName: string) => {
- setActiveProfile(profileName);
- handleProfileChange();
- };
-
- const renderSection = () => {
- switch (activeSection) {
- case "general":
- return <GeneralSettings />;
- case "ai":
- return <AIPresets />;
- case "account":
- return <AccountSection />;
- case "recording":
- return <RecordingSettings />;
- case "shortcuts":
- return <ShortcutSection />;
- case "disk-usage":
- return <DiskUsageSection />;
- }
- };
-
- const settingsSections = [
- {
- id: "general",
- label: "General",
- icon: <SettingsIcon className="h-4 w-4" />,
- description: "Basic app settings and preferences",
- },
- {
- id: "account",
- label: "Account",
- icon: <User className="h-4 w-4" />,
- description: "User account and authentication",
- },
- {
- id: "recording",
- label: "Recording",
- icon: <Video className="h-4 w-4" />,
- description: "Screen and audio recording settings",
- },
- {
- id: "ai",
- label: "AI Settings",
- icon: <Brain className="h-4 w-4" />,
- description: "AI models and processing options",
- },
- {
- id: "shortcuts",
- label: "Shortcuts",
- icon: <Keyboard className="h-4 w-4" />,
- description: "Keyboard shortcuts and hotkeys",
- },
- {
- id: "disk-usage",
- label: "Disk Usage",
- icon: <HardDrive className="h-4 w-4" />,
- description: "Monitor storage usage for Screenpipe data",
- },
- ];
-
- useEffect(() => {
- console.log(profiles, "profiles");
- }, [profiles]);
-
- return (
- <Dialog modal={true} open={isOpen} onOpenChange={setSettingsOpen}>
- <DialogContent
- className="max-w-7xl w-full max-h-[90vh] h-[90vh] overflow-hidden p-0 border-slate-200 dark:border-slate-700"
- onClick={(e) => e.stopPropagation()}
- >
- <div className="flex h-full min-h-0">
- {/* Sidebar */}
- <div className="w-80 border-r bg-gradient-to-b from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800 flex flex-col min-h-0">
- <div className="p-6 border-b">
- <DialogHeader className="space-y-3">
- <div className="flex items-center justify-between">
- <DialogTitle className="text-2xl font-bold text-slate-900 dark:text-slate-100">
- Settings
- </DialogTitle>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setSettingsOpen(false)}
- className="h-8 w-8 p-0"
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
-
- {/* Profile Selector */}
- <div className="space-y-2">
- <label className="text-sm font-medium text-slate-700 dark:text-slate-300">
- Profile
- </label>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="outline"
- className="w-full justify-between font-mono text-sm bg-white dark:bg-slate-800"
- >
- {activeProfile}
- <ChevronDown className="h-4 w-4 opacity-50" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-72">
- {profiles?.map((profile) => (
- <DropdownMenuItem
- key={profile}
- className="justify-between"
- onSelect={() => handleSwitchProfile(profile)}
- >
- <span className="font-mono">{profile}</span>
- <div className="flex items-center gap-2">
- {activeProfile === profile && (
- <Check className="h-4 w-4 text-green-600" />
- )}
- {profile !== "default" && (
- <Trash2
- className="h-4 w-4 opacity-50 hover:opacity-100 text-red-500"
- onClick={(e) => {
- e.stopPropagation();
- deleteProfile(profile);
- }}
- />
- )}
- </div>
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- {isCreatingProfile ? (
- <div className="p-2">
- <form
- onSubmit={(e) => {
- e.preventDefault();
- handleCreateProfile();
- }}
- className="flex gap-2"
- >
- <Input
- value={newProfileName}
- onChange={(e) => setNewProfileName(e.target.value)}
- placeholder="Profile name"
- className="h-8 font-mono"
- autoFocus
- />
- <Button
- type="submit"
- size="sm"
- disabled={!newProfileName.trim()}
- >
- <Check className="h-4 w-4" />
- </Button>
- </form>
- </div>
- ) : (
- <DropdownMenuItem
- onSelect={(e) => {
- e.preventDefault();
- setIsCreatingProfile(true);
- }}
- className="gap-2"
- >
- <Plus className="h-4 w-4" />
- <span>New profile</span>
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </DialogHeader>
- </div>
-
- {/* Navigation */}
- <div className="p-4 space-y-2 flex-1 overflow-y-auto">
- {settingsSections.map((section) => (
- <button
- key={section.id}
- onClick={() =>
- setActiveSection(section.id as SettingsSection)
- }
- className={cn(
- "w-full flex items-start space-x-3 px-4 py-3 rounded-xl transition-all duration-200 text-left group",
- activeSection === section.id
- ? "bg-white dark:bg-slate-800 shadow-sm border border-slate-200 dark:border-slate-700 text-slate-900 dark:text-slate-100"
- : "hover:bg-white/50 dark:hover:bg-slate-800/50 text-slate-700 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100",
- )}
- >
- <div className={cn(
- "mt-0.5 transition-colors",
- activeSection === section.id
- ? "text-blue-600 dark:text-blue-400"
- : "text-slate-500 group-hover:text-slate-700 dark:group-hover:text-slate-300"
- )}>
- {section.icon}
- </div>
- <div className="flex-1 min-w-0">
- <div className="font-medium text-sm">{section.label}</div>
- <div className="text-xs text-slate-500 dark:text-slate-400 mt-0.5 leading-relaxed">
- {section.description}
- </div>
- </div>
- </button>
- ))}
- </div>
-
- {/* Footer */}
- <div className="p-4 border-t border-slate-200 dark:border-slate-700 flex-shrink-0">
- <div className="text-xs text-slate-500 dark:text-slate-400 text-center">
- OpenRewind Settings
- </div>
- </div>
- </div>
-
- {/* Content */}
- <div className="flex-1 flex flex-col h-full bg-slate-50 dark:bg-slate-900 min-h-0">
- <div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
- <div className="p-8 pb-16 max-w-4xl mx-auto">
- {renderSection()}
- </div>
- </div>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/openrewind/components/settings/account-section.tsx b/openrewind/components/settings/account-section.tsx
index 96c7e960a..dc0bc5939 100644
--- a/openrewind/components/settings/account-section.tsx
+++ b/openrewind/components/settings/account-section.tsx
@@ -215,11 +215,11 @@ export function AccountSection() {
return (
<div className="space-y-8">
<div className="space-y-3">
- <h1 className="text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">
+ <h1 className="text-3xl font-bold tracking-tight text-foreground">
Account Settings
</h1>
- <p className="text-slate-600 dark:text-slate-400 text-lg">
- Manage your account, subscription, and profile information
+ <p className="text-muted-foreground text-lg">
+ Manage your account and authentication settings
</p>
</div>
@@ -252,7 +252,7 @@ export function AccountSection() {
variant="outline"
size="sm"
onClick={() => {
- updateSettings({ user: { token: undefined } });
+ updateSettings({ user: undefined });
toast({
title: "logged out",
description: "you have been logged out",
diff --git a/openrewind/components/settings/ai-presets.tsx b/openrewind/components/settings/ai-presets.tsx
index 0c6dec916..9f10da5d1 100644
--- a/openrewind/components/settings/ai-presets.tsx
+++ b/openrewind/components/settings/ai-presets.tsx
@@ -1,13 +1,12 @@
-import { useEffect, useMemo, useState } from "react";
+import { useState, useEffect, useMemo, useCallback } from "react";
import { Button } from "../ui/button";
import {
- AIPreset,
DEFAULT_PROMPT,
useSettings,
} from "@/lib/hooks/use-settings";
-import { AIModel, AIProviderCard, OllamaModel } from "./ai-section";
import { Label } from "../ui/label";
-import { Input } from "../ui/input";
+import { ValidatedInput } from "../ui/validated-input";
+import { ValidatedTextarea } from "../ui/validated-textarea";
import {
ArrowLeft,
ChevronsUpDown,
@@ -20,6 +19,8 @@ import {
Settings2,
Trash2,
XIcon,
+ CheckCircle2,
+ AlertCircle,
} from "lucide-react";
import { Textarea } from "../ui/textarea";
import {
@@ -40,7 +41,7 @@ import {
} from "../ui/command";
import { Badge } from "../ui/badge";
import { toast } from "../ui/use-toast";
-import { Card } from "../ui/card";
+import { Card, CardContent } from "../ui/card";
import { AIProviderType } from "@screenpipe/browser";
import {
AlertDialog,
@@ -54,6 +55,83 @@ import {
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { cn } from "@/lib/utils";
+import { AIPreset } from "@/lib/utils/tauri";
+import {
+ validatePresetName,
+ validateUrl,
+ validateApiKey,
+ validateContextLength,
+ debounce,
+ FieldValidationResult
+} from "@/lib/utils/validation";
+
+export interface AIProviderCardProps {
+ type: "screenpipe-cloud" | "openai" | "native-ollama" | "custom" | "embedded";
+ title: string;
+ description: string;
+ imageSrc: string;
+ selected: boolean;
+ onClick: () => void;
+ disabled?: boolean;
+ warningText?: string;
+ imageClassName?: string;
+}
+
+export interface OllamaModel {
+ name: string;
+ size: number;
+ digest: string;
+ modified_at: string;
+}
+
+export interface AIModel {
+ id: string;
+ name: string;
+ provider: string;
+}
+
+export const AIProviderCard = ({
+ type,
+ title,
+ description,
+ imageSrc,
+ selected,
+ onClick,
+ disabled,
+ warningText,
+ imageClassName,
+}: AIProviderCardProps) => {
+ return (
+ <Card
+ onClick={onClick}
+ className={cn(
+ "flex py-4 px-4 rounded-lg hover:bg-accent transition-colors h-[145px] w-full cursor-pointer",
+ selected ? "border-black/60 border-[1.5px]" : "",
+ disabled && "opacity-50 cursor-not-allowed",
+ )}
+ >
+ <CardContent className="flex flex-col p-0 w-full">
+ <div className="flex items-center gap-2 mb-2">
+ <img
+ src={imageSrc}
+ alt={title}
+ className={cn(
+ "rounded-lg shrink-0 size-8",
+ type === "native-ollama" &&
+ "outline outline-gray-300 outline-1 outline-offset-2",
+ imageClassName,
+ )}
+ />
+ <span className="text-lg font-medium truncate">{title}</span>
+ </div>
+ <p className="text-sm text-muted-foreground line-clamp-3">
+ {description}
+ </p>
+ {warningText && <Badge className="w-fit mt-2">{warningText}</Badge>}
+ </CardContent>
+ </Card>
+ );
+};
const AISection = ({
preset,
@@ -70,45 +148,89 @@ const AISection = ({
>(preset);
const [isLoading, setIsLoading] = useState(false);
const [showApiKey, setShowApiKey] = useState(false);
- const [nameError, setNameError] = useState<string | null>(null);
+ const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
- const validateName = (name: string) => {
- if (!name) {
- setNameError("name is required");
- return false;
- }
- if (name.trim().toLowerCase().endsWith("copy")) {
- setNameError("name cannot end with 'copy'");
- return false;
- }
- if (
- settings.aiPresets.find(
- (p) => p.id.toLowerCase() === name.toLowerCase() && p.id !== preset?.id
- )
- ) {
- setNameError("name already exists");
- return false;
+ // Optimized validation with debouncing
+ const debouncedValidatePreset = useMemo(
+ () => debounce((presetData: Partial<AIPreset>) => {
+ const errors: Record<string, string> = {};
+
+ // Validate name
+ if (presetData.id) {
+ const nameValidation = validatePresetName(
+ presetData.id,
+ settings.aiPresets,
+ preset?.id
+ );
+ if (!nameValidation.isValid && nameValidation.error) {
+ errors.id = nameValidation.error;
+ }
+ }
+
+ // Validate URL
+ if (presetData.url) {
+ const urlValidation = validateUrl(presetData.url);
+ if (!urlValidation.isValid && urlValidation.error) {
+ errors.url = urlValidation.error;
+ }
+ }
+
+ // Validate API key
+ if (presetData.apiKey && presetData.provider) {
+ const apiKeyValidation = validateApiKey(presetData.apiKey, presetData.provider);
+ if (!apiKeyValidation.isValid && apiKeyValidation.error) {
+ errors.apiKey = apiKeyValidation.error;
+ }
+ }
+
+ // Validate context length
+ if (presetData.maxContextChars && presetData.model) {
+ const contextValidation = validateContextLength(presetData.maxContextChars, presetData.model);
+ if (!contextValidation.isValid && contextValidation.error) {
+ errors.maxContextChars = contextValidation.error;
+ }
+ }
+
+ setValidationErrors(errors);
+ }, 300),
+ [settings.aiPresets, preset?.id]
+ );
+
+ // Update validation when preset changes
+ useEffect(() => {
+ if (settingsPreset) {
+ debouncedValidatePreset(settingsPreset);
}
- setNameError(null);
- return true;
- };
+ }, [settingsPreset, debouncedValidatePreset]);
+
+ const isFormValid = useMemo(() => {
+ return Object.keys(validationErrors).length === 0 &&
+ settingsPreset?.id &&
+ settingsPreset?.provider &&
+ settingsPreset?.model;
+ }, [validationErrors, settingsPreset]);
const updateStoreSettings = async () => {
+ if (!isFormValid) {
+ toast({
+ title: "Validation errors",
+ description: "Please fix all validation errors before saving",
+ variant: "destructive",
+ });
+ return;
+ }
+
setIsLoading(true);
try {
if (!settingsPreset?.id) {
toast({
- title: "please enter a name",
- description: "name is required",
+ title: "Please enter a name",
+ description: "Name is required",
variant: "destructive",
});
return;
}
- if (!validateName(settingsPreset.id)) {
- return;
- }
-
// If this is the first preset, make it default
if (!settings.aiPresets.length) {
const defaultPreset = {
@@ -119,20 +241,12 @@ const AISection = ({
} as AIPreset;
await updateSettings({
- aiModel: defaultPreset?.model,
- aiProviderType: defaultPreset?.provider,
- customPrompt: defaultPreset?.prompt,
- aiMaxContextChars: defaultPreset?.maxContextChars,
- aiUrl: defaultPreset?.url,
- ...("apiKey" in defaultPreset && {
- openaiApiKey: defaultPreset.apiKey,
- }),
aiPresets: [defaultPreset],
});
toast({
- title: "preset created",
- description: "default preset has been created",
+ title: "Preset created",
+ description: "Default preset has been created successfully",
});
setDialog(false);
@@ -153,14 +267,7 @@ const AISection = ({
// If this is the default preset, update global settings too
if (p.defaultPreset) {
updateSettings({
- aiModel: updatedPreset.model,
- aiProviderType: updatedPreset.provider,
- customPrompt: updatedPreset.prompt,
- aiMaxContextChars: updatedPreset.maxContextChars,
- aiUrl: updatedPreset.url,
- ...("apiKey" in updatedPreset && {
- openaiApiKey: updatedPreset.apiKey,
- }),
+ aiPresets: updatedPresets,
});
}
@@ -174,8 +281,8 @@ const AISection = ({
});
toast({
- title: "preset updated",
- description: "changes have been saved",
+ title: "Preset updated",
+ description: "Changes have been saved successfully",
});
} else {
// Handle create case (new preset or duplicate)
@@ -191,18 +298,18 @@ const AISection = ({
});
toast({
- title: isDuplicating ? "preset duplicated" : "preset created",
+ title: isDuplicating ? "Preset duplicated" : "Preset created",
description: isDuplicating
- ? "duplicate has been saved"
- : "new preset has been added",
+ ? "Duplicate has been saved successfully"
+ : "New preset has been added successfully",
});
}
setDialog(false);
} catch (error) {
toast({
- title: "error saving preset",
- description: "something went wrong while saving the preset",
+ title: "Error saving preset",
+ description: "Something went wrong while saving the preset",
variant: "destructive",
});
} finally {
@@ -210,38 +317,27 @@ const AISection = ({
}
};
- const updateSettingsPreset = (presetsObject: Partial<AIPreset>) => {
- setSettingsPreset({ ...settingsPreset, ...presetsObject });
- };
+ const updateSettingsPreset = useCallback((presetsObject: Partial<AIPreset>) => {
+ setSettingsPreset(prev => ({ ...prev, ...presetsObject }));
+ }, []);
- const handleApiKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const value = e.target.value;
- updateSettingsPreset({
- apiKey: value,
- });
- };
+ const handleApiKeyChange = useCallback((value: string, isValid: boolean) => {
+ updateSettingsPreset({ apiKey: value });
+ }, [updateSettingsPreset]);
- const handleMaxContextCharsChange = (value: number[]) => {
- updateSettingsPreset({
- maxContextChars: value[0],
- });
- };
+ const handleMaxContextCharsChange = useCallback((value: number[]) => {
+ updateSettingsPreset({ maxContextChars: value[0] });
+ }, [updateSettingsPreset]);
- const handleCustomPromptChange = (
- e: React.ChangeEvent<HTMLTextAreaElement>
- ) => {
- updateSettingsPreset({
- prompt: e.target.value ?? DEFAULT_PROMPT,
- });
- };
+ const handleCustomPromptChange = useCallback((value: string, isValid: boolean) => {
+ updateSettingsPreset({ prompt: value });
+ }, [updateSettingsPreset]);
- const handleResetCustomPrompt = () => {
- updateSettingsPreset({
- prompt: DEFAULT_PROMPT,
- });
- };
+ const handleResetCustomPrompt = useCallback(() => {
+ updateSettingsPreset({ prompt: DEFAULT_PROMPT });
+ }, [updateSettingsPreset]);
- const handleAiProviderChange = (newValue: AIPreset["provider"]) => {
+ const handleAiProviderChange = useCallback((newValue: AIPreset["provider"]) => {
let newUrl = "";
let newModel = settingsPreset?.model;
@@ -265,7 +361,7 @@ const AISection = ({
url: newUrl,
model: newModel,
});
- };
+ }, [settingsPreset?.url, settingsPreset?.model, updateSettingsPreset]);
const isApiKeyRequired =
settingsPreset?.url !== "https://ai-proxy.i-f9f.workers.dev/v1" &&
@@ -275,9 +371,8 @@ const AISection = ({
const [models, setModels] = useState<AIModel[]>([]);
const [isLoadingModels, setIsLoadingModels] = useState(false);
- const fetchModels = async () => {
+ const fetchModels = useCallback(async () => {
setIsLoadingModels(true);
- console.log(settingsPreset);
try {
switch (settingsPreset?.provider) {
case "screenpipe-cloud":
@@ -317,16 +412,14 @@ const AISection = ({
},
});
if (!r.ok) {
- // TODO better UX for this
toast({
- title: "error fetching models",
- description: "please check your api key",
+ title: "Error fetching models",
+ description: "Please check your API key",
variant: "destructive",
});
return;
}
const d = await r.json();
- console.log(d);
const models = d.data.map((model: { id: string }) => ({
id: model.id,
name: model.id,
@@ -349,7 +442,6 @@ const AISection = ({
return;
}
const customData = await customResponse.json();
- console.log(customData);
setModels(
(customData.data || []).map((model: { id: string }) => ({
id: model.id,
@@ -378,7 +470,7 @@ const AISection = ({
} finally {
setIsLoadingModels(false);
}
- };
+ }, [settingsPreset?.provider, settingsPreset?.url, settingsPreset?.apiKey, settings.user?.id]);
const apiKey = useMemo(() => {
if (settingsPreset && "apiKey" in settingsPreset) {
@@ -388,7 +480,6 @@ const AISection = ({
}, [settingsPreset]);
useEffect(() => {
- console.log("hello");
if (
(settingsPreset?.provider === "openai" ||
settingsPreset?.provider === "custom") &&
@@ -396,7 +487,7 @@ const AISection = ({
)
return;
fetchModels();
- }, [settingsPreset?.provider, settingsPreset?.url, apiKey]);
+ }, [fetchModels]);
return (
<div className="w-full space-y-6 py-4">
@@ -409,20 +500,21 @@ const AISection = ({
<ArrowLeft className="w-4 h-4" /> back
</Button>
<h1 className="text-2xl font-bold">
- {preset ? "update preset" : "create preset"}
+ {preset ? "Update preset" : "Create preset"}
</h1>
</div>
+
<div className="w-full">
<div className="flex flex-col gap-2">
<Label htmlFor="aiUrl" className="min-w-[80px]">
- ai provider
+ AI provider
</Label>
</div>
<div className="grid grid-cols-2 gap-4 mb-4 mt-4">
<AIProviderCard
type="openai"
- title="openai"
- description="use your own openai api key for gpt-4 and other models"
+ title="OpenAI"
+ description="Use your own OpenAI API key for GPT-4 and other models"
imageSrc="/images/openai.png"
selected={settingsPreset?.provider === "openai"}
onClick={() => handleAiProviderChange("openai")}
@@ -430,25 +522,25 @@ const AISection = ({
<AIProviderCard
type="screenpipe-cloud"
- title="screenpipe cloud"
- description="use openai, anthropic and google models without worrying about api keys or usage"
+ title="Screenpipe Cloud"
+ description="Use OpenAI, Anthropic and Google models without worrying about API keys or usage"
imageSrc="/images/screenpipe.png"
selected={settingsPreset?.provider === "screenpipe-cloud"}
onClick={() => handleAiProviderChange("screenpipe-cloud")}
disabled={!settings.user}
warningText={
!settings.user
- ? "login required"
+ ? "Login required"
: !settings.user?.credits?.amount
- ? "requires credits"
+ ? "Requires credits"
: undefined
}
/>
<AIProviderCard
type="native-ollama"
- title="ollama"
- description="run ai models locally using your existing ollama installation"
+ title="Ollama"
+ description="Run AI models locally using your existing Ollama installation"
imageSrc="/images/ollama.png"
selected={settingsPreset?.provider === "native-ollama"}
onClick={() => handleAiProviderChange("native-ollama")}
@@ -456,84 +548,62 @@ const AISection = ({
<AIProviderCard
type="custom"
- title="custom"
- description="connect to your own ai provider or self-hosted models"
+ title="Custom"
+ description="Connect to your own AI provider or self-hosted models"
imageSrc="/images/custom.png"
selected={settingsPreset?.provider === "custom"}
onClick={() => handleAiProviderChange("custom")}
/>
</div>
</div>
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4">
- <Label htmlFor="preset_id" className="flex items-center gap-2">
- name
- {nameError && (
- <span className="text-xs text-destructive font-normal">
- {nameError}
- </span>
- )}
- </Label>
- <Input
- id="preset_id"
- value={settingsPreset?.id}
- onChange={(e) => {
- const namePreset = e.target.value;
- validateName(namePreset);
- updateSettingsPreset({ id: namePreset });
- }}
- className={cn(
- "flex-grow",
- nameError && "border-destructive focus-visible:ring-destructive"
- )}
- placeholder="enter name"
- autoCorrect="off"
- autoCapitalize="off"
- autoComplete="off"
- type="text"
- disabled={!!preset && !isDuplicating && preset.id !== undefined}
- />
- </div>
- </div>
+
+ <ValidatedInput
+ id="preset_id"
+ label="Preset Name"
+ value={settingsPreset?.id || ""}
+ onChange={(value, isValid) => updateSettingsPreset({ id: value })}
+ validation={(value) => validatePresetName(value, settings.aiPresets, preset?.id)}
+ placeholder="Enter preset name"
+ required={true}
+ disabled={!!preset && !isDuplicating && preset.id !== undefined}
+ helperText="Only letters, numbers, spaces, hyphens, and underscores allowed"
+ />
{settingsPreset?.provider === "custom" && (
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4">
- <Label htmlFor="customAiUrl">custom url</Label>
- <Input
- id="customAiUrl"
- value={settingsPreset?.url}
- onChange={(e) => {
- const newUrl = e.target.value;
- updateSettingsPreset({ url: newUrl });
- }}
- className="flex-grow"
- placeholder="enter custom ai url"
- autoCorrect="off"
- autoCapitalize="off"
- autoComplete="off"
- type="text"
- />
- </div>
- </div>
+ <ValidatedInput
+ id="customAiUrl"
+ label="Custom URL"
+ value={settingsPreset?.url || ""}
+ onChange={(value, isValid) => updateSettingsPreset({ url: value })}
+ validation={validateUrl}
+ placeholder="Enter custom AI URL"
+ required={true}
+ helperText="Enter the base URL for your custom AI provider"
+ />
)}
+
{isApiKeyRequired &&
(settingsPreset?.provider === "openai" ||
settingsPreset?.provider === "custom") && (
<div className="w-full">
<div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="aiApiKey">API Key</Label>
+ <Label htmlFor="aiApiKey" className="flex items-center gap-1">
+ API Key
+ <span className="text-destructive">*</span>
+ {validationErrors.apiKey && (
+ <AlertCircle className="h-4 w-4 text-destructive ml-1" />
+ )}
+ </Label>
<div className="flex-grow relative">
- <Input
+ <ValidatedInput
id="aiApiKey"
type={showApiKey ? "text" : "password"}
- value={settingsPreset?.apiKey}
+ value={settingsPreset?.apiKey || ""}
onChange={handleApiKeyChange}
+ validation={(value) => validateApiKey(value, settingsPreset?.provider || "openai")}
+ placeholder="Enter your AI API key"
+ required={true}
className="pr-10"
- placeholder="enter your ai api key"
- autoCorrect="off"
- autoCapitalize="off"
- autoComplete="off"
/>
<Button
type="button"
@@ -555,13 +625,19 @@ const AISection = ({
<div className="w-full">
<div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="aiModel">ai model</Label>
+ <Label htmlFor="aiModel" className="flex items-center gap-1">
+ AI Model
+ <span className="text-destructive">*</span>
+ </Label>
<Popover modal={true}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
- className="w-full justify-between"
+ className={cn(
+ "w-full justify-between",
+ !settingsPreset?.model && "text-muted-foreground"
+ )}
disabled={
(settingsPreset?.provider === "openai" &&
!settingsPreset?.apiKey) ||
@@ -572,26 +648,26 @@ const AISection = ({
>
{settingsPreset?.provider === "openai" &&
!settingsPreset?.apiKey
- ? "api key required to fetch models"
+ ? "API key required to fetch models"
: settingsPreset?.provider === "screenpipe-cloud" &&
(!settings.user || settings.user.cloud_subscribed === false)
- ? "subscription required to access models"
- : settingsPreset?.model || "select model..."}
+ ? "Subscription required to access models"
+ : settingsPreset?.model || "Select model..."}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
- <CommandInput placeholder="select or type model name" />
+ <CommandInput placeholder="Select or type model name" />
<CommandList>
<CommandEmpty>
- press enter to use &quot;{settingsPreset?.model}&quot;
+ Press enter to use &quot;{settingsPreset?.model}&quot;
</CommandEmpty>
- <CommandGroup heading="Suggestions">
+ <CommandGroup heading="Available Models">
{isLoadingModels ? (
<CommandItem value="loading" disabled>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
- loading models...
+ Loading models...
</CommandItem>
) : (
models?.map((model) => (
@@ -602,10 +678,12 @@ const AISection = ({
updateSettingsPreset({ model: model.id });
}}
>
- {model.name}
- <Badge variant="outline" className="ml-2">
- {model.provider}
- </Badge>
+ <div className="flex items-center justify-between w-full">
+ <span>{model.name}</span>
+ <Badge variant="outline" className="ml-2">
+ {model.provider}
+ </Badge>
+ </div>
</CommandItem>
))
)}
@@ -616,35 +694,30 @@ const AISection = ({
</Popover>
</div>
</div>
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="customPrompt">prompt</Label>
- <div className="flex-grow relative">
- <Textarea
- id="customPrompt"
- value={settingsPreset?.prompt || DEFAULT_PROMPT}
- onChange={handleCustomPromptChange}
- className="min-h-[100px]"
- placeholder="enter your custom prompt here"
- />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="absolute right-2 top-2"
- onClick={handleResetCustomPrompt}
- >
- <RefreshCw className="h-4 w-4 mr-2" />
- reset
- </Button>
- </div>
- </div>
- </div>
+
+ <ValidatedTextarea
+ id="customPrompt"
+ label="Custom Prompt"
+ value={settingsPreset?.prompt || DEFAULT_PROMPT}
+ onChange={handleCustomPromptChange}
+ validation={(value) => {
+ if (value.length < 10) {
+ return { isValid: false, error: "Prompt must be at least 10 characters" };
+ }
+ return { isValid: true };
+ }}
+ placeholder="Enter your custom prompt here"
+ required={true}
+ minLength={10}
+ maxLength={5000}
+ className="min-h-[100px] resize-none"
+ helperText="This prompt will be used to guide the AI's responses"
+ />
<div className="w-full">
<div className="flex flex-col gap-4 mb-4 w-full">
<Label htmlFor="aiMaxContextChars" className="flex items-center">
- max context{" "}
+ Max Context Characters{" "}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
@@ -652,22 +725,25 @@ const AISection = ({
</TooltipTrigger>
<TooltipContent side="left">
<p>
- maximum number of characters (think 4 characters per token)
- to send to the ai model. <br />
- usually, openai models support up to 200k tokens, which is
- roughly 1m characters. <br />
- we&apos;ll use this for UI purposes to show you how much you
+ Maximum number of characters (think 4 characters per token)
+ to send to the AI model. <br />
+ Usually, OpenAI models support up to 200k tokens, which is
+ roughly 1M characters. <br />
+ We&apos;ll use this for UI purposes to show you how much you
can send.
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
+ {validationErrors.maxContextChars && (
+ <AlertCircle className="h-4 w-4 text-destructive ml-1" />
+ )}
</Label>
<div className="flex-grow flex items-center">
<Slider
id="aiMaxContextChars"
- min={10000}
- max={1000000}
+ min={1000}
+ max={2000000}
step={10000}
value={
settingsPreset?.maxContextChars
@@ -677,16 +753,37 @@ const AISection = ({
onValueChange={handleMaxContextCharsChange}
className="flex-grow"
/>
- <span className="ml-2 min-w-[60px] text-right">
- {settingsPreset?.maxContextChars?.toLocaleString() ?? 512000}
+ <span className="ml-2 min-w-[80px] text-right">
+ {(settingsPreset?.maxContextChars ?? 512000).toLocaleString()}
</span>
</div>
+ {validationErrors.maxContextChars && (
+ <p className="text-sm text-destructive">{validationErrors.maxContextChars}</p>
+ )}
</div>
</div>
- <div className="flex justify-end">
- <Button onClick={() => updateStoreSettings()} disabled={isLoading}>
- {isLoading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
- {preset ? "update preset" : "create preset"}
+
+ <div className="flex justify-end gap-2">
+ <Button
+ variant="outline"
+ onClick={() => setDialog(false)}
+ disabled={isLoading}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={updateStoreSettings}
+ disabled={isLoading || !isFormValid}
+ className="flex items-center gap-2"
+ >
+ {isLoading ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : isFormValid ? (
+ <CheckCircle2 className="w-4 h-4" />
+ ) : (
+ <AlertCircle className="w-4 h-4" />
+ )}
+ {preset ? "Update preset" : "Create preset"}
</Button>
</div>
</div>
@@ -736,8 +833,8 @@ export const AIPresets = () => {
if (checkIfDefault) {
toast({
- title: "cannot delete default preset",
- description: "please set another preset as default first",
+ title: "Cannot delete default preset",
+ description: "Please set another preset as default first",
variant: "destructive",
});
return;
@@ -749,8 +846,8 @@ export const AIPresets = () => {
if (!checkIfIDPresent) {
toast({
- title: "preset not found",
- description: "the preset you're trying to delete doesn't exist",
+ title: "Preset not found",
+ description: "The preset you're trying to delete doesn't exist",
variant: "destructive",
});
return;
@@ -765,13 +862,13 @@ export const AIPresets = () => {
});
toast({
- title: "preset deleted",
- description: "the preset has been removed successfully",
+ title: "Preset deleted",
+ description: "The preset has been removed successfully",
});
} catch (error) {
toast({
- title: "error deleting preset",
- description: "something went wrong while deleting the preset",
+ title: "Error deleting preset",
+ description: "Something went wrong while deleting the preset",
variant: "destructive",
});
} finally {
@@ -807,13 +904,13 @@ export const AIPresets = () => {
await updateSettings(updateData);
toast({
- title: "default preset updated",
- description: "the preset has been set as default",
+ title: "Default preset updated",
+ description: "The preset has been set as default",
});
} catch (error) {
toast({
- title: "error updating default preset",
- description: "something went wrong while updating the default preset",
+ title: "Error updating default preset",
+ description: "Something went wrong while updating the default preset",
variant: "destructive",
});
} finally {
@@ -841,10 +938,10 @@ export const AIPresets = () => {
return (
<div className="space-y-8">
<div className="space-y-3">
- <h1 className="text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">
+ <h1 className="text-3xl font-bold tracking-tight text-foreground">
AI Settings
</h1>
- <p className="text-slate-600 dark:text-slate-400 text-lg">
+ <p className="text-muted-foreground text-lg">
Configure AI models, prompts, and processing preferences
</p>
</div>
@@ -854,12 +951,13 @@ export const AIPresets = () => {
<h2 className="text-xl font-medium text-muted-foreground">
No AI presets yet
</h2>
- <p className="text-sm text-muted-foreground">
- Create your first AI preset to get started with intelligent features
+ <p className="text-sm text-muted-foreground text-center max-w-md">
+ Create your first AI preset to get started with intelligent features.
+ Presets allow you to quickly switch between different AI configurations.
</p>
- <Button onClick={() => setCreatePresentDialog(true)}>
+ <Button onClick={() => setCreatePresentDialog(true)} size="lg">
<Plus className="w-4 h-4 mr-2" />
- Create Preset
+ Create Your First Preset
</Button>
</div>
</div>
@@ -869,103 +967,153 @@ export const AIPresets = () => {
return (
<div className="space-y-8">
<div className="space-y-3">
- <h1 className="text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">
+ <h1 className="text-3xl font-bold tracking-tight text-foreground">
AI Settings
</h1>
- <p className="text-slate-600 dark:text-slate-400 text-lg">
+ <p className="text-muted-foreground text-lg">
Configure AI models, prompts, and processing preferences
</p>
</div>
<div className="flex items-center justify-between">
- <div></div>
+ <div className="flex items-center gap-4">
+ <Badge variant="outline" className="px-3 py-1">
+ {settings.aiPresets.length} preset{settings.aiPresets.length !== 1 ? 's' : ''}
+ </Badge>
+ {settings.aiPresets.some(p => p.defaultPreset) && (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <CheckCircle2 className="h-4 w-4 text-green-500" />
+ Default preset configured
+ </div>
+ )}
+ </div>
<Button onClick={() => setCreatePresentDialog(true)}>
<Plus className="w-4 h-4 mr-2" />
Create Preset
</Button>
</div>
+
<div className="w-full grid grid-cols-1 md:grid-cols-2 gap-6">
{settings.aiPresets.map((preset) => {
const isDefault = preset.defaultPreset;
+ const hasValidation = preset.provider && preset.model && preset.url;
+
return (
<Card
key={preset.id}
- className="p-6 relative group transition-all hover:shadow-lg border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
+ className={cn(
+ "p-6 relative group transition-all hover:shadow-lg border-border bg-card cursor-pointer",
+ isDefault && "ring-2 ring-primary/20"
+ )}
+ onClick={() => {
+ setSelectedPreset(preset);
+ setIsDuplicating(false);
+ setCreatePresentDialog(true);
+ }}
>
- <div
- className="flex justify-between items-start cursor-pointer"
- onClick={() => {
- setSelectedPreset(preset);
- setIsDuplicating(false);
- setCreatePresentDialog(true);
- }}
- >
- <div className="space-y-2">
- <div className="text-lg font-semibold text-foreground flex items-center gap-2">
- {preset.id}
- {isDefault && (
- <Badge variant="secondary" className="font-normal">
- default
- </Badge>
- )}
- </div>
- <div className="text-sm text-muted-foreground space-y-1">
+ <div className="space-y-4">
+ <div className="flex justify-between items-start">
+ <div className="space-y-2 flex-1">
<div className="flex items-center gap-2">
- <span>model:</span>
- <span className="font-medium">{preset.model}</span>
+ <h3 className="text-lg font-semibold text-foreground truncate">
+ {preset.id}
+ </h3>
+ {isDefault && (
+ <Badge variant="default" className="text-xs">
+ default
+ </Badge>
+ )}
+ {!hasValidation && (
+ <AlertCircle className="h-4 w-4 text-destructive" />
+ )}
</div>
- <div className="flex items-center gap-2">
- <span>context:</span>
- <span className="font-medium">
- {preset.maxContextChars?.toLocaleString()}
- </span>
+
+ <div className="space-y-1 text-sm text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <span className="font-medium">Provider:</span>
+ <span className="capitalize">{preset.provider.replace('-', ' ')}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="font-medium">Model:</span>
+ <span className="font-mono text-xs bg-muted px-2 py-1 rounded">
+ {preset.model || 'Not set'}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="font-medium">Context:</span>
+ <span>
+ {preset.maxContextChars?.toLocaleString() || '512,000'} chars
+ </span>
+ </div>
</div>
</div>
+
+ <div className="flex items-start gap-2">
+ <img
+ src={providerImageSrc[preset.provider]}
+ alt={`${preset.provider} logo`}
+ className="w-10 h-10 opacity-80 group-hover:opacity-100 transition-opacity rounded"
+ />
+ {hasValidation ? (
+ <CheckCircle2 className="h-5 w-5 text-green-500" />
+ ) : (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <AlertCircle className="h-5 w-5 text-destructive" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Configuration incomplete</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )}
+ </div>
+ </div>
+
+ <div className="flex justify-between items-center pt-2 border-t border-border">
+ <div className="flex gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ duplicatePreset(preset.id);
+ }}
+ disabled={isLoading}
+ className="text-xs"
+ >
+ Duplicate
+ </Button>
+
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setPresetToSetDefault(preset.id);
+ }}
+ disabled={isLoading || isDefault}
+ className="text-xs"
+ >
+ {isDefault ? "Current default" : "Set as default"}
+ </Button>
+ </div>
+
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={(e) => {
+ e.stopPropagation();
+ setPresetToDelete(preset.id);
+ }}
+ disabled={isLoading || isDefault}
+ className="text-xs text-destructive hover:text-destructive"
+ >
+ <Trash2 className="w-3 h-3 mr-1" />
+ Remove
+ </Button>
</div>
- <img
- src={providerImageSrc[preset.provider]}
- alt={`${preset.provider} logo`}
- className="w-10 h-10 opacity-80 group-hover:opacity-100 transition-opacity"
- />
- </div>
- <div className="flex justify-end gap-2 mt-4">
- <Button
- className="text-xs"
- variant="ghost"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- duplicatePreset(preset.id);
- }}
- disabled={isLoading}
- >
- duplicate
- </Button>
- <Button
- className="text-xs"
- variant="ghost"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- setPresetToSetDefault(preset.id);
- }}
- disabled={isLoading || isDefault}
- >
- {isDefault ? "current default" : "set as default"}
- </Button>
- <Button
- className="text-xs text-destructive"
- variant="ghost"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- setPresetToDelete(preset.id);
- }}
- disabled={isLoading || isDefault}
- >
- <Trash2 className="w-3 h-3 mr-1" />
- remove
- </Button>
</div>
</Card>
);
@@ -978,14 +1126,14 @@ export const AIPresets = () => {
>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>are you sure?</AlertDialogTitle>
+ <AlertDialogTitle>Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
- this action cannot be undone. this will permanently delete the
- preset.
+ This action cannot be undone. This will permanently delete the
+ preset &quot;{presetToDelete}&quot;.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel>cancel</AlertDialogCancel>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => presetToDelete && removePreset(presetToDelete)}
@@ -993,7 +1141,7 @@ export const AIPresets = () => {
{isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
- "delete"
+ "Delete"
)}
</AlertDialogAction>
</AlertDialogFooter>
@@ -1006,13 +1154,14 @@ export const AIPresets = () => {
>
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>change default preset?</AlertDialogTitle>
+ <AlertDialogTitle>Change default preset?</AlertDialogTitle>
<AlertDialogDescription>
- this will set this preset as the default and apply its settings.
+ This will set &quot;{presetToSetDefault}&quot; as the default preset and apply its settings.
+ The current default preset will remain but will no longer be the default.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
- <AlertDialogCancel>cancel</AlertDialogCancel>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() =>
presetToSetDefault && setDefaultPreset(presetToSetDefault)
@@ -1021,7 +1170,7 @@ export const AIPresets = () => {
{isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
- "continue"
+ "Continue"
)}
</AlertDialogAction>
</AlertDialogFooter>
diff --git a/openrewind/components/settings/ai-section.tsx b/openrewind/components/settings/ai-section.tsx
deleted file mode 100644
index 7d69ca2f1..000000000
--- a/openrewind/components/settings/ai-section.tsx
+++ /dev/null
@@ -1,493 +0,0 @@
-/* eslint-disable @next/next/no-img-element */
-import { AIProviderType, useSettings } from "@/lib/hooks/use-settings";
-import { Label } from "@/components/ui/label";
-import { Separator } from "@/components/ui/separator";
-import { Slider } from "@/components/ui/slider";
-import { Switch } from "@/components/ui/switch";
-import {
- TooltipProvider,
- Tooltip,
- TooltipTrigger,
- TooltipContent,
-} from "@/components/ui/tooltip";
-import {
- HelpCircle,
- EyeOff,
- Eye,
- RefreshCw,
- Loader2,
- ChevronsUpDown,
-} from "lucide-react";
-import { Badge } from "@/components/ui/badge";
-import React, { useState, useEffect } from "react";
-import { Input } from "../ui/input";
-import { Textarea } from "../ui/textarea";
-import { Button } from "../ui/button";
-import { cn } from "@/lib/utils";
-import { Card, CardContent } from "../ui/card";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
- CommandSeparator,
-} from "@/components/ui/command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
-
-export interface AIProviderCardProps {
- type: "screenpipe-cloud" | "openai" | "native-ollama" | "custom" | "embedded";
- title: string;
- description: string;
- imageSrc: string;
- selected: boolean;
- onClick: () => void;
- disabled?: boolean;
- warningText?: string;
- imageClassName?: string;
-}
-
-export interface OllamaModel {
- name: string;
- size: number;
- digest: string;
- modified_at: string;
-}
-
-export interface AIModel {
- id: string;
- name: string;
- provider: string;
-}
-
-export const AIProviderCard = ({
- type,
- title,
- description,
- imageSrc,
- selected,
- onClick,
- disabled,
- warningText,
- imageClassName,
-}: AIProviderCardProps) => {
- return (
- <Card
- onClick={onClick}
- className={cn(
- "flex py-4 px-4 rounded-lg hover:bg-accent transition-colors h-[145px] w-full cursor-pointer",
- selected ? "border-black/60 border-[1.5px]" : "",
- disabled && "opacity-50 cursor-not-allowed",
- )}
- >
- <CardContent className="flex flex-col p-0 w-full">
- <div className="flex items-center gap-2 mb-2">
- <img
- src={imageSrc}
- alt={title}
- className={cn(
- "rounded-lg shrink-0 size-8",
- type === "native-ollama" &&
- "outline outline-gray-300 outline-1 outline-offset-2",
- imageClassName,
- )}
- />
- <span className="text-lg font-medium truncate">{title}</span>
- </div>
- <p className="text-sm text-muted-foreground line-clamp-3">
- {description}
- </p>
- {warningText && <Badge className="w-fit mt-2">{warningText}</Badge>}
- </CardContent>
- </Card>
- );
-};
-
-const AISection = () => {
- const { settings, updateSettings, resetSetting } = useSettings();
-
- const [showApiKey, setShowApiKey] = React.useState(false);
-
- const handleApiKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- updateSettings({ openaiApiKey: e.target.value });
- };
-
- const handleMaxContextCharsChange = (value: number[]) => {
- updateSettings({ aiMaxContextChars: value[0] });
- };
-
- const handleCustomPromptChange = (
- e: React.ChangeEvent<HTMLTextAreaElement>,
- ) => {
- updateSettings({ customPrompt: e.target.value });
- };
-
- const handleResetCustomPrompt = () => {
- resetSetting("customPrompt");
- };
-
- const handleAiProviderChange = (newValue: AIProviderType) => {
- let newUrl = "";
- let newModel = settings.aiModel;
-
- switch (newValue) {
- case "openai":
- newUrl = "https://api.openai.com/v1";
- break;
- case "native-ollama":
- newUrl = "http://localhost:11434/v1";
- break;
- case "embedded":
- newUrl = `http://localhost:${settings.embeddedLLM.port}/v1`;
- newModel = settings.embeddedLLM.model;
- break;
- case "screenpipe-cloud":
- newUrl = "https://ai-proxy.i-f9f.workers.dev/v1";
- break;
- case "custom":
- newUrl = settings.aiUrl;
- break;
- }
-
- updateSettings({
- aiProviderType: newValue,
- aiUrl: newUrl,
- aiModel: newModel,
- });
- };
-
- const isApiKeyRequired =
- settings.aiUrl !== "https://ai-proxy.i-f9f.workers.dev/v1" &&
- settings.aiUrl !== "http://localhost:11434/v1" &&
- settings.aiUrl !== "embedded";
-
- const [models, setModels] = useState<AIModel[]>([]);
- const [isLoadingModels, setIsLoadingModels] = useState(false);
-
- const fetchModels = async () => {
- setIsLoadingModels(true);
- console.log(settings.aiProviderType, settings.openaiApiKey, settings.aiUrl);
- try {
- switch (settings.aiProviderType) {
- case "screenpipe-cloud":
- const response = await fetch(
- "https://ai-proxy.i-f9f.workers.dev/v1/models",
- {
- headers: {
- Authorization: `Bearer ${settings.user?.id || ""}`,
- },
- },
- );
- if (!response.ok) throw new Error("Failed to fetch models");
- const data = await response.json();
- setModels(data.models);
- break;
-
- case "native-ollama":
- const ollamaResponse = await fetch("http://localhost:11434/api/tags");
- if (!ollamaResponse.ok)
- throw new Error("Failed to fetch Ollama models");
- const ollamaData = (await ollamaResponse.json()) as {
- models: OllamaModel[];
- };
- setModels(
- (ollamaData.models || []).map((model) => ({
- id: model.name,
- name: model.name,
- provider: "ollama",
- })),
- );
- break;
-
- case "openai":
- setModels([
- { id: "gpt-4", name: "gpt-4", provider: "openai" },
- { id: "gpt-3.5-turbo", name: "gpt-3.5-turbo", provider: "openai" },
- ]);
- break;
-
- case "custom":
- try {
- const customResponse = await fetch(`${settings.aiUrl}/models`, {
- headers: settings.openaiApiKey
- ? { Authorization: `Bearer ${settings.openaiApiKey}` }
- : {},
- });
- if (!customResponse.ok)
- throw new Error("Failed to fetch custom models");
- const customData = await customResponse.json();
- console.log(customData);
- setModels(
- (customData.data || []).map((model: { id: string }) => ({
- id: model.id,
- name: model.id,
- provider: "custom",
- })),
- );
- } catch (error) {
- console.error(
- "Failed to fetch custom models, allowing manual input:",
- error,
- );
- setModels([]);
- }
- break;
-
- default:
- setModels([]);
- }
- } catch (error) {
- console.error(
- `Failed to fetch models for ${settings.aiProviderType}:`,
- error,
- );
- setModels([]);
- } finally {
- setIsLoadingModels(false);
- }
- };
-
- useEffect(() => {
- fetchModels();
- }, [settings.aiProviderType, settings.openaiApiKey, settings.aiUrl]);
-
- return (
- <div className="w-full space-y-6 py-4">
- <h1 className="text-2xl font-bold">ai settings</h1>
- <div className="w-full">
- <Label htmlFor="aiUrl" className="min-w-[80px]">
- ai provider
- </Label>
- <div className="grid grid-cols-2 gap-4 mb-4 mt-4">
- <AIProviderCard
- type="openai"
- title="openai"
- description="use your own openai api key for gpt-4 and other models"
- imageSrc="/images/openai.png"
- selected={settings.aiProviderType === "openai"}
- onClick={() => handleAiProviderChange("openai")}
- />
-
- <AIProviderCard
- type="screenpipe-cloud"
- title="screenpipe cloud"
- description="use openai, anthropic and google models without worrying about api keys or usage"
- imageSrc="/images/screenpipe.png"
- selected={settings.aiProviderType === "screenpipe-cloud"}
- onClick={() => handleAiProviderChange("screenpipe-cloud")}
- disabled={!settings.user}
- warningText={
- !settings.user
- ? "login required"
- : !settings.user?.credits?.amount
- ? "requires credits"
- : undefined
- }
- />
-
- <AIProviderCard
- type="native-ollama"
- title="ollama"
- description="run ai models locally using your existing ollama installation"
- imageSrc="/images/ollama.png"
- selected={settings.aiProviderType === "native-ollama"}
- onClick={() => handleAiProviderChange("native-ollama")}
- />
-
- <AIProviderCard
- type="custom"
- title="custom"
- description="connect to your own ai provider or self-hosted models"
- imageSrc="/images/custom.png"
- selected={settings.aiProviderType === "custom"}
- onClick={() => handleAiProviderChange("custom")}
- />
- </div>
- </div>
- {settings.aiProviderType === "custom" && (
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4">
- <Label htmlFor="customAiUrl">custom url</Label>
- <Input
- id="customAiUrl"
- value={settings.aiUrl}
- onChange={(e) => {
- const newUrl = e.target.value;
- updateSettings({ aiUrl: newUrl });
- }}
- className="flex-grow"
- placeholder="enter custom ai url"
- autoCorrect="off"
- autoCapitalize="off"
- autoComplete="off"
- type="text"
- />
- </div>
- </div>
- )}
- {isApiKeyRequired && (
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="aiApiKey">API Key</Label>
- <div className="flex-grow relative">
- <Input
- id="aiApiKey"
- type={showApiKey ? "text" : "password"}
- value={settings.openaiApiKey}
- onChange={handleApiKeyChange}
- className="pr-10"
- placeholder="enter your ai api key"
- autoCorrect="off"
- autoCapitalize="off"
- autoComplete="off"
- />
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="absolute right-0 top-0 h-full"
- onClick={() => setShowApiKey(!showApiKey)}
- >
- {showApiKey ? (
- <EyeOff className="h-4 w-4" />
- ) : (
- <Eye className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
- </div>
- )}
- {settings.aiProviderType !== "embedded" && (
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="aiModel">ai model</Label>
- <Popover modal={true}>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- className="w-full justify-between"
- >
- {settings.aiModel || "select model..."}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-full p-0">
- <Command>
- <CommandInput
- placeholder="select or type model name"
- onValueChange={(value) => {
- if (value) {
- updateSettings({ aiModel: value });
- }
- }}
- />
- <CommandList>
- <CommandEmpty>
- press enter to use &quot;{settings.aiModel}&quot;
- </CommandEmpty>
- <CommandGroup heading="Suggestions">
- {isLoadingModels ? (
- <CommandItem value="loading" disabled>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- loading models...
- </CommandItem>
- ) : (
- models.map((model) => (
- <CommandItem
- key={model.id}
- value={model.id}
- onSelect={() => {
- updateSettings({ aiModel: model.id });
- }}
- >
- {model.name}
- <Badge variant="outline" className="ml-2">
- {model.provider}
- </Badge>
- </CommandItem>
- ))
- )}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- </div>
- </div>
- )}
-
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="customPrompt">prompt</Label>
- <div className="flex-grow relative">
- <Textarea
- id="customPrompt"
- value={settings.customPrompt}
- onChange={handleCustomPromptChange}
- className="min-h-[100px]"
- placeholder="enter your custom prompt here"
- />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="absolute right-2 top-2"
- onClick={handleResetCustomPrompt}
- >
- <RefreshCw className="h-4 w-4 mr-2" />
- reset
- </Button>
- </div>
- </div>
- </div>
-
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="aiMaxContextChars" className="flex items-center">
- max context{" "}
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="ml-2 h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="left">
- <p>
- maximum number of characters (think 4 characters per token)
- to send to the ai model. <br />
- usually, openai models support up to 200k tokens, which is
- roughly 1m characters. <br />
- we&apos;ll use this for UI purposes to show you how much you
- can send.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </Label>
- <div className="flex-grow flex items-center">
- <Slider
- id="aiMaxContextChars"
- min={10000}
- max={1000000}
- step={10000}
- value={[settings.aiMaxContextChars]}
- onValueChange={handleMaxContextCharsChange}
- className="flex-grow"
- />
- <span className="ml-2 min-w-[60px] text-right">
- {settings.aiMaxContextChars.toLocaleString()}
- </span>
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default AISection;
diff --git a/openrewind/components/settings/disk-usage-section.tsx b/openrewind/components/settings/disk-usage-section.tsx
index eabdc70d9..4676c9e49 100644
--- a/openrewind/components/settings/disk-usage-section.tsx
+++ b/openrewind/components/settings/disk-usage-section.tsx
@@ -6,8 +6,9 @@ import { Button } from "../ui/button";
import { Separator } from "../ui/separator";
import { Badge } from "../ui/badge";
import { useDiskUsage } from "@/lib/hooks/use-disk-usage";
-import { RefreshCw, HardDrive, Folder, Video, Mic, Database } from "lucide-react";
+import { RefreshCw, HardDrive, Folder, Video, Mic, Database, Calculator } from "lucide-react";
import { Skeleton } from "../ui/skeleton";
+import { Progress } from "../ui/progress";
export function DiskUsageSection() {
const { diskUsage, isLoading, error, refetch } = useDiskUsage();
@@ -56,69 +57,102 @@ export function DiskUsageSection() {
disabled={isLoading}
>
<RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`} />
- Refresh
+ {isLoading ? "Calculating..." : "Refresh"}
</Button>
</div>
+ {/* Loading Progress Indicator */}
+ {isLoading && (
+ <Card className="border-blue-200 bg-blue-50/50">
+ <CardContent className="pt-6">
+ <div className="flex items-center space-x-3">
+ <Calculator className="h-5 w-5 text-blue-600 animate-pulse" />
+ <div className="flex-1">
+ <p className="text-sm font-medium text-blue-900">Calculating disk usage...</p>
+ <p className="text-xs text-blue-700 mt-1">
+ Scanning directories and analyzing file sizes. This may take a moment for large datasets.
+ </p>
+ <Progress value={undefined} className="mt-3 h-2" />
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ )}
+
{/* Overview Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
- <Card>
+ <Card className={isLoading ? "opacity-75" : ""}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Data Size</CardTitle>
- <Database className="h-4 w-4 text-muted-foreground" />
+ <Database className={`h-4 w-4 text-muted-foreground ${isLoading ? "animate-pulse" : ""}`} />
</CardHeader>
<CardContent>
{isLoading ? (
- <Skeleton className="h-8 w-20" />
+ <div className="space-y-2">
+ <Skeleton className="h-8 w-24" />
+ <Skeleton className="h-3 w-20" />
+ </div>
) : (
- <div className="text-2xl font-bold">{diskUsage?.total_data_size || "---"}</div>
+ <>
+ <div className="text-2xl font-bold">{diskUsage?.total_data_size || "0 KB"}</div>
+ <p className="text-xs text-muted-foreground">
+ All Screenpipe data
+ </p>
+ </>
)}
- <p className="text-xs text-muted-foreground">
- All Screenpipe data
- </p>
</CardContent>
</Card>
- <Card>
+ <Card className={isLoading ? "opacity-75" : ""}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Cache Size</CardTitle>
- <Folder className="h-4 w-4 text-muted-foreground" />
+ <Folder className={`h-4 w-4 text-muted-foreground ${isLoading ? "animate-pulse" : ""}`} />
</CardHeader>
<CardContent>
{isLoading ? (
- <Skeleton className="h-8 w-20" />
+ <div className="space-y-2">
+ <Skeleton className="h-8 w-24" />
+ <Skeleton className="h-3 w-20" />
+ </div>
) : (
- <div className="text-2xl font-bold">{diskUsage?.total_cache_size || "---"}</div>
+ <>
+ <div className="text-2xl font-bold">{diskUsage?.total_cache_size || "0 KB"}</div>
+ <p className="text-xs text-muted-foreground">
+ Temporary files
+ </p>
+ </>
)}
- <p className="text-xs text-muted-foreground">
- Temporary files
- </p>
</CardContent>
</Card>
- <Card>
+ <Card className={isLoading ? "opacity-75" : ""}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Available Space</CardTitle>
- <HardDrive className="h-4 w-4 text-muted-foreground" />
+ <HardDrive className={`h-4 w-4 text-muted-foreground ${isLoading ? "animate-pulse" : ""}`} />
</CardHeader>
<CardContent>
{isLoading ? (
- <Skeleton className="h-8 w-20" />
+ <div className="space-y-2">
+ <Skeleton className="h-8 w-24" />
+ <Skeleton className="h-3 w-20" />
+ </div>
) : (
- <div className="text-2xl font-bold text-green-600">{diskUsage?.avaiable_space || "---"}</div>
+ <>
+ <div className="text-2xl font-bold text-green-600">{diskUsage?.available_space || "Unknown"}</div>
+ <p className="text-xs text-muted-foreground">
+ Free disk space
+ </p>
+ </>
)}
- <p className="text-xs text-muted-foreground">
- Free disk space
- </p>
</CardContent>
</Card>
</div>
{/* Media Breakdown */}
- <Card>
+ <Card className={isLoading ? "opacity-75" : ""}>
<CardHeader>
<CardTitle className="flex items-center gap-2">
- <Video className="h-5 w-5" />
+ <Video className={`h-5 w-5 ${isLoading ? "animate-pulse" : ""}`} />
Media Files
</CardTitle>
<CardDescription>
@@ -127,10 +161,32 @@ export function DiskUsageSection() {
</CardHeader>
<CardContent className="space-y-4">
{isLoading ? (
- <div className="space-y-3">
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-full" />
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-4 w-4 rounded" />
+ <Skeleton className="h-4 w-20" />
+ </div>
+ <Skeleton className="h-6 w-16 rounded-full" />
+ </div>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-4 w-4 rounded" />
+ <Skeleton className="h-4 w-20" />
+ </div>
+ <Skeleton className="h-6 w-16 rounded-full" />
+ </div>
+ <Skeleton className="h-px w-full" />
+ <div className="flex items-center justify-between">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-6 w-20 rounded-full" />
+ </div>
+ <div className="mt-3 p-3 bg-muted/50 rounded-lg">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Calculator className="h-4 w-4 animate-pulse" />
+ <span>Analyzing media files recursively...</span>
+ </div>
+ </div>
</div>
) : (
<>
@@ -139,26 +195,31 @@ export function DiskUsageSection() {
<Video className="h-4 w-4 text-blue-500" />
<span className="text-sm font-medium">Video Files</span>
</div>
- <Badge variant="secondary">{diskUsage?.media.videos_size || "---"}</Badge>
+ <Badge variant="secondary">{diskUsage?.media.videos_size || "0 KB"}</Badge>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Mic className="h-4 w-4 text-green-500" />
<span className="text-sm font-medium">Audio Files</span>
</div>
- <Badge variant="secondary">{diskUsage?.media.audios_size || "---"}</Badge>
+ <Badge variant="secondary">{diskUsage?.media.audios_size || "0 KB"}</Badge>
</div>
<Separator />
<div className="flex items-center justify-between font-medium">
<span>Total Media Size</span>
- <Badge>{diskUsage?.media.total_media_size || "---"}</Badge>
+ <Badge className="bg-primary">{diskUsage?.media.total_media_size || "0 KB"}</Badge>
</div>
+ {diskUsage && (
+ <div className="mt-3 p-3 bg-muted/50 rounded-lg">
+ <p className="text-xs text-muted-foreground">
+ ✓ Values calculated from recursive directory scan including all subdirectories
+ </p>
+ </div>
+ )}
</>
)}
</CardContent>
</Card>
-
-
</div>
);
}
\ No newline at end of file
diff --git a/openrewind/components/settings/general-settings.tsx b/openrewind/components/settings/general-settings.tsx
index faa64a76d..907e6c16c 100644
--- a/openrewind/components/settings/general-settings.tsx
+++ b/openrewind/components/settings/general-settings.tsx
@@ -6,38 +6,40 @@ import { Switch } from "@/components/ui/switch";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Rocket } from "lucide-react";
+import { SettingsStore } from "@/lib/utils/tauri";
export default function GeneralSettings() {
const { settings, updateSettings } = useSettings();
-
- const handleSettingsChange = (newSettings: Partial<typeof settings>) => {
- updateSettings(newSettings);
+ const handleSettingsChange = (newSettings: Partial<SettingsStore>) => {
+ if (settings) {
+ updateSettings(newSettings);
+ }
};
return (
<div className="space-y-8">
<div className="space-y-3">
- <h1 className="text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">
+ <h1 className="text-3xl font-bold tracking-tight text-foreground">
General Settings
</h1>
- <p className="text-slate-600 dark:text-slate-400 text-lg">
+ <p className="text-muted-foreground text-lg">
Configure basic application preferences and behavior
</p>
</div>
<div className="space-y-6">
- <Card className="border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 shadow-sm">
+ <Card className="border-border bg-card shadow-sm">
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div className="flex items-start space-x-4">
- <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
- <Rocket className="h-5 w-5 text-blue-600 dark:text-blue-400" />
+ <div className="p-2 bg-primary/10 rounded-lg">
+ <Rocket className="h-5 w-5 text-primary" />
</div>
<div className="space-y-1 flex-1">
- <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
+ <h3 className="text-lg font-semibold text-foreground">
Auto-start Application
</h3>
- <p className="text-sm text-slate-600 dark:text-slate-400 leading-relaxed">
+ <p className="text-sm text-muted-foreground leading-relaxed">
Automatically launch OpenRewind when your computer starts up.
This ensures you never miss capturing important moments.
</p>
@@ -45,7 +47,7 @@ export default function GeneralSettings() {
</div>
<Switch
id="auto-start-toggle"
- checked={settings.autoStartEnabled}
+ checked={settings?.autoStartEnabled ?? false}
onCheckedChange={(checked) =>
handleSettingsChange({ autoStartEnabled: checked })
}
@@ -59,8 +61,8 @@ export default function GeneralSettings() {
</div>
<div className="pt-4">
- <div className="p-4 bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg">
- <p className="text-sm text-blue-800 dark:text-blue-200">
+ <div className="p-4 bg-primary/5 border border-primary/20 rounded-lg">
+ <p className="text-sm text-primary">
💡 <strong>Tip:</strong> Auto-start ensures continuous recording so you never miss capturing important moments.
</p>
</div>
diff --git a/openrewind/components/settings/recording-settings.tsx b/openrewind/components/settings/recording-settings.tsx
index 85c882e22..94149671c 100644
--- a/openrewind/components/settings/recording-settings.tsx
+++ b/openrewind/components/settings/recording-settings.tsx
@@ -1,6 +1,6 @@
"use client";
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useState, useMemo, useCallback } from "react";
import { Label } from "@/components/ui/label";
import {
Select,
@@ -29,6 +29,9 @@ import {
Key,
Terminal,
Asterisk,
+ AlertCircle,
+ RefreshCw,
+ Loader2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
@@ -40,15 +43,14 @@ import {
CommandItem,
} from "@/components/ui/command";
import { Command as TauriCommand } from "@tauri-apps/plugin-shell";
+import { commands, SettingsStore } from "@/lib/utils/tauri";
import {
- Settings,
useSettings,
VadSensitivity,
} from "@/lib/hooks/use-settings";
import { useToast } from "@/components/ui/use-toast";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
-import { invoke } from "@tauri-apps/api/core";
import { Badge } from "@/components/ui/badge";
import {
Tooltip,
@@ -73,6 +75,14 @@ import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";
import * as Sentry from "@sentry/react";
import { defaultOptions } from "tauri-plugin-sentry-api";
import { useLoginDialog } from "../login-dialog";
+import { ValidatedInput } from "../ui/validated-input";
+import {
+ validateField,
+ sanitizeValue,
+ debounce,
+ validateUrl,
+ FieldValidationResult
+} from "@/lib/utils/validation";
type PermissionsStatus = {
screenRecording: string;
@@ -125,6 +135,10 @@ export function RecordingSettings() {
const [clickTimeout, setClickTimeout] = useState<ReturnType<
typeof setTimeout
> | null>(null);
+
+ // Add validation state
+ const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
+ const [pendingChanges, setPendingChanges] = useState<Partial<SettingsStore>>({});
const { items: windowItems, isLoading: isWindowItemsLoading } =
useSqlAutocomplete("window");
@@ -146,51 +160,75 @@ export function RecordingSettings() {
// Add new state to track if settings have changed
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
- // Modify setLocalSettings to track changes
- const handleSettingsChange = (
- newSettings: Partial<Settings>,
+ // Optimized debounced validation
+ const debouncedValidateSettings = useMemo(
+ () => debounce((newSettings: Partial<SettingsStore>) => {
+ const errors: Record<string, string> = {};
+
+ // Validate numeric fields
+ if (newSettings.fps !== undefined) {
+ const fpsValidation = validateField("fps", newSettings.fps);
+ if (!fpsValidation.isValid && fpsValidation.error) {
+ errors.fps = fpsValidation.error;
+ }
+ }
+
+ if (newSettings.audioChunkDuration !== undefined) {
+ const durationValidation = validateField("audioChunkDuration", newSettings.audioChunkDuration);
+ if (!durationValidation.isValid && durationValidation.error) {
+ errors.audioChunkDuration = durationValidation.error;
+ }
+ }
+
+ if (newSettings.port !== undefined) {
+ const portValidation = validateField("port", newSettings.port);
+ if (!portValidation.isValid && portValidation.error) {
+ errors.port = portValidation.error;
+ }
+ }
+
+ if (newSettings.dataDir !== undefined) {
+ const dataDirValidation = validateField("dataDir", newSettings.dataDir);
+ if (!dataDirValidation.isValid && dataDirValidation.error) {
+ errors.dataDir = dataDirValidation.error;
+ }
+ }
+
+ if (newSettings.deepgramApiKey !== undefined && newSettings.deepgramApiKey.trim()) {
+ if (newSettings.deepgramApiKey.length < 10) {
+ errors.deepgramApiKey = "API key seems too short";
+ }
+ }
+
+ setValidationErrors(errors);
+ }, 300),
+ []
+ );
+
+ // Enhanced settings change handler with validation
+ const handleSettingsChange = useCallback((
+ newSettings: Partial<SettingsStore>,
restart: boolean = true
) => {
- updateSettings(newSettings);
+ // Sanitize values
+ const sanitizedSettings: Partial<SettingsStore> = {};
+ for (const [key, value] of Object.entries(newSettings)) {
+ sanitizedSettings[key as keyof SettingsStore] = sanitizeValue(key as keyof SettingsStore, value);
+ }
+
+ // Update pending changes
+ setPendingChanges(prev => ({ ...prev, ...sanitizedSettings }));
+
+ // Validate new settings
+ debouncedValidateSettings({ ...settings, ...sanitizedSettings });
+
+ // Update settings
+ updateSettings(sanitizedSettings);
+
if (restart) {
setHasUnsavedChanges(true);
}
- };
-
- // Show toast when settings change
- useEffect(() => {
- if (hasUnsavedChanges) {
- toast({
- title: "settings changed",
- description: "restart required to apply changes",
- action: (
- <ToastAction
- altText="restart now"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- // Wrap in setTimeout to ensure event handling is complete
- setTimeout(() => {
- handleUpdate();
- }, 0);
- return false;
- }}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- onMouseUp={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- >
- restart now
- </ToastAction>
- ),
- duration: 50000,
- });
- }
- }, [hasUnsavedChanges]);
+ }, [settings, updateSettings, debouncedValidateSettings]);
useEffect(() => {
const checkPlatform = async () => {
@@ -299,25 +337,77 @@ export function RecordingSettings() {
loadDevices();
}, []);
+ // Enhanced validation for specific fields
+ const validateDeepgramApiKey = useCallback((apiKey: string): FieldValidationResult => {
+ if (!apiKey.trim()) {
+ return { isValid: false, error: "API key is required" };
+ }
+ if (apiKey.length < 10) {
+ return { isValid: false, error: "API key seems too short" };
+ }
+ return { isValid: true };
+ }, []);
+
+ const validateDataDirectory = useCallback((path: string): FieldValidationResult => {
+ if (!path.trim()) {
+ return { isValid: false, error: "Data directory path is required" };
+ }
+ // Add more validation as needed
+ return { isValid: true };
+ }, []);
+
+ // Enhanced FPS change handler with validation
+ const handleFpsChange = useCallback((value: number[]) => {
+ const fps = Math.max(0.1, Math.min(60, value[0]));
+ handleSettingsChange({ fps }, true);
+ }, [handleSettingsChange]);
+
+ // Enhanced audio chunk duration handler
+ const handleAudioChunkDurationChange = useCallback((value: number[]) => {
+ const duration = Math.max(5, Math.min(3600, value[0]));
+ handleSettingsChange({ audioChunkDuration: duration }, true);
+ }, [handleSettingsChange]);
+
+ // Enhanced Deepgram API key handler
+ const handleDeepgramApiKeyChange = useCallback((value: string, isValid: boolean) => {
+ handleSettingsChange({ deepgramApiKey: value }, true);
+ }, [handleSettingsChange]);
+
+ // Enhanced data directory change with validation
+ const handleDataDirInputChange = useCallback((value: string, isValid: boolean) => {
+ handleSettingsChange({ dataDir: value }, true);
+ }, [handleSettingsChange]);
+
+ // Optimized update function with better error handling
const handleUpdate = async () => {
+ // Check for validation errors
+ if (Object.keys(validationErrors).length > 0) {
+ toast({
+ title: "Validation errors",
+ description: "Please fix all validation errors before applying changes",
+ variant: "destructive",
+ });
+ return;
+ }
+
setIsUpdating(true);
+ setHasUnsavedChanges(false);
+
toast({
- title: "updating screenpipe recording settings",
- description: "this may take a few moments...",
+ title: "Updating recording settings",
+ description: "This may take a few moments...",
});
try {
- console.log("settings", settings);
+ console.log("Applying settings:", settings);
if (!settings.analyticsEnabled) {
posthog.capture("telemetry", {
enabled: false,
});
- // disable opentelemetry
posthog.opt_out_capturing();
- // disable sentry
Sentry.close();
- console.log("telemetry disabled");
+ console.log("Telemetry disabled");
} else {
const isDebug = process.env.TAURI_ENV_DEBUG === "true";
if (!isDebug) {
@@ -325,44 +415,56 @@ export function RecordingSettings() {
posthog.capture("telemetry", {
enabled: true,
});
-
- // enable opentelemetry
- console.log("telemetry enabled");
-
- // enable sentry
+ console.log("Telemetry enabled");
Sentry.init({
...defaultOptions,
});
}
}
- await invoke("stop_screenpipe");
-
+ await commands.stopScreenpipe();
await new Promise((resolve) => setTimeout(resolve, 1000));
- // Start a new instance with updated settings
- await invoke("spawn_screenpipe");
-
+ await commands.spawnScreenpipe(null);
await new Promise((resolve) => setTimeout(resolve, 2000));
- // await relaunch();
- // toast({
- // title: "settings updated successfully",
- // description: "screenpipe has been restarted with new settings.",
- // });
-
- // window.location.reload();
+ toast({
+ title: "Settings updated successfully",
+ description: "Screenpipe has been restarted with new settings",
+ });
} catch (error) {
- console.error("failed to update settings:", error);
+ console.error("Failed to update settings:", error);
toast({
- title: "error updating settings",
- description: "please try again or check the logs for more information.",
+ title: "Error updating settings",
+ description: "Please try again or check the logs for more information",
variant: "destructive",
});
+ setHasUnsavedChanges(true);
} finally {
setIsUpdating(false);
}
};
+ // Show validation status in the UI
+ const getValidationStatus = () => {
+ const errorCount = Object.keys(validationErrors).length;
+ if (errorCount > 0) {
+ return {
+ variant: "destructive" as const,
+ message: `${errorCount} validation error${errorCount > 1 ? 's' : ''} found`,
+ };
+ }
+ if (hasUnsavedChanges) {
+ return {
+ variant: "secondary" as const,
+ message: "Unsaved changes - restart required",
+ };
+ }
+ return {
+ variant: "default" as const,
+ message: "All settings valid",
+ };
+ };
+
const handleAudioTranscriptionModelChange = (
value: string,
realtime = false
@@ -420,10 +522,6 @@ export function RecordingSettings() {
handleSettingsChange({ disableAudio: checked }, true);
};
- const handleFpsChange = (value: number[]) => {
- handleSettingsChange({ fps: value[0] }, true);
- };
-
const handleVadSensitivityChange = (value: number[]) => {
const sensitivityMap: { [key: number]: VadSensitivity } = {
2: "high",
@@ -447,27 +545,6 @@ export function RecordingSettings() {
return sensitivityMap[sensitivity];
};
- const handleAudioChunkDurationChange = (value: number[]) => {
- handleSettingsChange({ audioChunkDuration: value[0] }, true);
- };
-
- const renderOcrEngineOptions = () => {
- const currentPlatform = platform();
- return (
- <>
- {currentPlatform === "linux" && (
- <SelectItem value="tesseract">tesseract</SelectItem>
- )}
- {currentPlatform === "windows" && (
- <SelectItem value="windows-native">windows native</SelectItem>
- )}
- {currentPlatform === "macos" && (
- <SelectItem value="apple-native">apple native</SelectItem>
- )}
- </>
- );
- };
-
const handleAnalyticsToggle = (checked: boolean) => {
const newValue = checked;
handleSettingsChange({ analyticsEnabled: newValue }, true);
@@ -520,13 +597,6 @@ export function RecordingSettings() {
}
};
- const handleDataDirInputChange = async (
- e: React.ChangeEvent<HTMLInputElement>
- ) => {
- const newValue = e.target.value;
- handleSettingsChange({ dataDir: newValue }, true);
- };
-
const handleDataDirInputBlur = () => {
console.log("wcw blur");
setDataDirInputVisible(false);
@@ -572,9 +642,7 @@ export function RecordingSettings() {
try {
if (checked) {
// Check accessibility permissions first
- const perms = await invoke<PermissionsStatus>("do_permissions_check", {
- initialCheck: false,
- });
+ const perms = await commands.doPermissionsCheck(false);
if (!perms.accessibility) {
toast({
title: "accessibility permission required",
@@ -583,7 +651,7 @@ export function RecordingSettings() {
action: (
<ToastAction
altText="open preferences"
- onClick={() => invoke("open_accessibility_preferences")}
+ onClick={() => commands.openPermissionSettings("accessibility")}
>
open preferences
</ToastAction>
@@ -694,827 +762,969 @@ export function RecordingSettings() {
return (
<div className="space-y-8">
<div className="space-y-3">
- <h1 className="text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">
+ <h1 className="text-3xl font-bold tracking-tight text-foreground">
Recording Settings
</h1>
- <p className="text-slate-600 dark:text-slate-400 text-lg">
+ <p className="text-muted-foreground text-lg">
Configure screen and audio recording preferences
</p>
</div>
+
+ {/* Validation and Status Alert */}
+ {(Object.keys(validationErrors).length > 0 || hasUnsavedChanges) && (
+ <Alert>
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>Configuration Status</AlertTitle>
+ <AlertDescription className="flex items-center justify-between">
+ <span>{getValidationStatus().message}</span>
+ {hasUnsavedChanges && Object.keys(validationErrors).length === 0 && (
+ <Button
+ onClick={handleUpdate}
+ disabled={isUpdating}
+ size="sm"
+ variant="outline"
+ >
+ {isUpdating ? (
+ <Loader2 className="h-4 w-4 animate-spin mr-2" />
+ ) : (
+ <RefreshCw className="h-4 w-4 mr-2" />
+ )}
+ Apply Changes
+ </Button>
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
+
{settings.devMode || (!isUpdating && isDisabled) ? (
<Alert>
<Terminal className="h-4 w-4" />
- <AlertTitle>heads up!</AlertTitle>
+ <AlertTitle>Development Mode</AlertTitle>
<AlertDescription>
- make sure to turn off dev mode and start screenpipe recorder first
- (go to status)
+ Make sure to turn off dev mode and start screenpipe recorder first (go to status)
</AlertDescription>
</Alert>
- ) : (
- <></>
+ ) : null}
+
+ {/* Enhanced Deepgram API Key Section */}
+ {settings.audioTranscriptionEngine === "deepgram" && (
+ <div className="space-y-4">
+ <h4 className="text-lg font-semibold">Deepgram Configuration</h4>
+
+ <ValidatedInput
+ id="deepgramApiKey"
+ label="Deepgram API Key"
+ type={showApiKey ? "text" : "password"}
+ value={settings.deepgramApiKey || ""}
+ onChange={handleDeepgramApiKeyChange}
+ validation={validateDeepgramApiKey}
+ placeholder="Enter your Deepgram API key"
+ required={true}
+ helperText="Don&apos;t have an API key? Get one from Deepgram&apos;s website or use screenpipe cloud"
+ className="pr-10"
+ />
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="absolute right-0 top-0 h-full"
+ onClick={() => setShowApiKey(!showApiKey)}
+ >
+ {showApiKey ? (
+ <EyeOff className="h-4 w-4" />
+ ) : (
+ <Eye className="h-4 w-4" />
+ )}
+ </Button>
+ </div>
)}
- <div
- // className={cn(
- // isDisabled && "opacity-50 pointer-events-none cursor-not-allowed"
- // )}
- >
- <h4 className="text-lg font-semibold my-4">video</h4>
- <div className="space-y-6">
+
+ {/* Enhanced Data Directory Section */}
+ <div className="space-y-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Folder className="h-5 w-5" />
+ <h3 className="text-lg font-semibold">Data Directory</h3>
+ </div>
+
+ {dataDirInputVisible ? (
+ <ValidatedInput
+ id="dataDir"
+ label="Data Directory Path"
+ value={settings.dataDir || ""}
+ onChange={handleDataDirInputChange}
+ validation={validateDataDirectory}
+ onBlur={() => {
+ setDataDirInputVisible(false);
+ validateDataDirInput();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ setDataDirInputVisible(false);
+ validateDataDirInput();
+ }
+ }}
+ placeholder="Enter data directory path"
+ autoFocus={true}
+ required={true}
+ />
+ ) : (
+ <Button
+ variant="outline"
+ role="combobox"
+ className="w-full justify-between"
+ onClick={handleDataDirChange}
+ >
+ <div className="flex gap-4">
+ {settings.dataDir ? "Change directory" : "Select directory"}
+ <span className="text-muted-foreground">
+ {settings.dataDir || "Default directory"}
+ </span>
+ </div>
+ <ChevronsUpDown className="h-4 w-4 opacity-50" />
+ </Button>
+ )}
+ </div>
+
+ {/* Rest of the existing UI sections remain the same but with improved validation feedback */}
+
+ {/* Enhanced FPS Section */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="fps" className="flex items-center space-x-2">
+ <span>Frames per second (FPS)</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Adjust the recording frame rate. Lower values save resources,
+ higher values provide smoother recordings and are less likely to miss activity.
+ We optimize resource usage when your screen doesn&apos;t change much.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ {validationErrors.fps && (
+ <AlertCircle className="h-4 w-4 text-destructive" />
+ )}
+ </Label>
+ <div className="flex items-center space-x-4">
+ <Slider
+ id="fps"
+ min={0.1}
+ max={10}
+ step={0.1}
+ value={[settings.fps]}
+ onValueChange={handleFpsChange}
+ className="flex-grow"
+ />
+ <span className="w-12 text-right">
+ {settings.fps.toFixed(1)}
+ </span>
+ </div>
+ {validationErrors.fps && (
+ <p className="text-sm text-destructive">{validationErrors.fps}</p>
+ )}
+ </div>
+
+ {/* Enhanced Audio Chunk Duration Section */}
+ <div className="flex flex-col space-y-2">
+ <Label
+ htmlFor="audioChunkDuration"
+ className="flex items-center space-x-2"
+ >
+ <span>Audio chunk duration (seconds)</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Adjust the duration of each audio chunk. Shorter durations may lower
+ resource usage spikes, while longer durations may increase transcription
+ quality. Deepgram generally works better than Whisper for higher quality transcription.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ {validationErrors.audioChunkDuration && (
+ <AlertCircle className="h-4 w-4 text-destructive" />
+ )}
+ </Label>
+ <div className="flex items-center space-x-4">
+ <Slider
+ id="audioChunkDuration"
+ min={5}
+ max={3000}
+ step={1}
+ value={[settings.audioChunkDuration]}
+ onValueChange={handleAudioChunkDurationChange}
+ className="flex-grow"
+ />
+ <span className="w-12 text-right">
+ {settings.audioChunkDuration} s
+ </span>
+ </div>
+ {validationErrors.audioChunkDuration && (
+ <p className="text-sm text-destructive">{validationErrors.audioChunkDuration}</p>
+ )}
+ </div>
+
+ <Separator />
+
+ {/* Audio Transcription Engine */}
+ <div className="flex flex-col space-y-2">
+ <div className="flex items-center gap-2 mb-2">
+ <Mic className="h-5 w-5" />
+ <h3 className="text-lg font-semibold">Audio Transcription</h3>
+ </div>
+ <div className="space-y-4">
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="audioTranscriptionEngine" className="flex items-center space-x-2">
+ <span>Audio transcription engine</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Choose the transcription engine. Deepgram provides higher quality but requires an API key or screenpipe cloud.
+ Whisper runs locally but may be slower.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <Select
+ value={settings.audioTranscriptionEngine}
+ onValueChange={(value) => handleAudioTranscriptionModelChange(value)}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select transcription engine" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="whisper-tiny">Whisper Tiny</SelectItem>
+ <SelectItem value="whisper-tiny-quantized">Whisper Tiny Quantized</SelectItem>
+ <SelectItem value="whisper-large">Whisper Large V3</SelectItem>
+ <SelectItem value="whisper-large-quantized">Whisper Large V3 Quantized</SelectItem>
+ <SelectItem value="whisper-large-v3-turbo">Whisper Large V3 Turbo</SelectItem>
+ <SelectItem value="whisper-large-v3-turbo-quantized">Whisper Large V3 Turbo Quantized</SelectItem>
+ <SelectItem value="deepgram">Deepgram</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Realtime Transcription */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="realtimeAudioTranscriptionEngine" className="flex items-center space-x-2">
+ <span>Realtime audio transcription engine</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Engine used for real-time transcription. This can be different from the main transcription engine.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <Select
+ value={settings.realtimeAudioTranscriptionEngine}
+ onValueChange={(value) => handleAudioTranscriptionModelChange(value, true)}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select realtime transcription engine" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="whisper-tiny">Whisper Tiny</SelectItem>
+ <SelectItem value="whisper-tiny-quantized">Whisper Tiny Quantized</SelectItem>
+ <SelectItem value="whisper-large">Whisper Large V3</SelectItem>
+ <SelectItem value="whisper-large-quantized">Whisper Large V3 Quantized</SelectItem>
+ <SelectItem value="whisper-large-v3-turbo">Whisper Large V3 Turbo</SelectItem>
+ <SelectItem value="whisper-large-v3-turbo-quantized">Whisper Large V3 Turbo Quantized</SelectItem>
+ <SelectItem value="deepgram">Deepgram</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {/* Enable Realtime Transcription */}
<div className="flex items-center justify-between">
<div className="space-y-1">
- <h4 className="font-medium">disable video recording</h4>
+ <Label htmlFor="enableRealtimeAudioTranscription">Enable realtime audio transcription</Label>
<p className="text-sm text-muted-foreground">
- useful if you don&apos;t need screen recording or if you have
- memory/cpu issues
+ Transcribe audio in real-time for immediate processing
</p>
</div>
<Switch
- id="disableVision"
- checked={settings.disableVision}
+ id="enableRealtimeAudioTranscription"
+ checked={settings.enableRealtimeAudioTranscription}
onCheckedChange={(checked) =>
- handleSettingsChange({ disableVision: checked }, true)
+ handleSettingsChange({ enableRealtimeAudioTranscription: checked }, true)
}
/>
</div>
+ </div>
+ </div>
- {!settings.disableVision && (
- <>
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h4 className="font-medium">
- enable realtime vision processing
- </h4>
- <p className="text-sm text-muted-foreground">
- stream screen content in real-time (dev preview) -{" "}
- <a
- href="https://github.com/mediar-ai/screenpipe/tree/main/screenpipe-js/examples/stream-screenshots"
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary hover:underline"
+ <Separator />
+
+ {/* Audio Devices */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="audioDevices" className="flex items-center space-x-2">
+ <span>Audio devices</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Select which audio devices to record from. You can select multiple devices.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <Popover open={openAudioDevices} onOpenChange={setOpenAudioDevices}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={openAudioDevices}
+ className="w-full justify-between"
+ >
+ {settings.audioDevices.length > 0
+ ? `${settings.audioDevices.length} device(s) selected`
+ : "Select audio devices..."}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-full p-0">
+ <Command>
+ <CommandInput placeholder="Search audio devices..." />
+ <CommandList>
+ <CommandEmpty>No audio devices found.</CommandEmpty>
+ <CommandGroup>
+ {availableAudioDevices.map((device) => (
+ <CommandItem
+ key={device.name}
+ value={device.name}
+ onSelect={() => handleAudioDeviceChange(device.name)}
>
- view example
- </a>
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Switch
- id="enableRealtimeVision"
- checked={settings.enableRealtimeVision}
- onCheckedChange={(checked) =>
- handleSettingsChange(
- {
- enableRealtimeVision: checked,
- },
- true
- )
- }
- />
- </div>
- </div>
-
- <div className="flex flex-col space-y-6">
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="monitorIds"
- className="flex items-center space-x-2"
- >
- <Monitor className="h-4 w-4" />
- <span>monitors</span>
- </Label>
- <MultiSelect
- options={availableMonitors.map((monitor) => ({
- value: monitor.id.toString(),
- label: `${monitor.id}. ${monitor.name} - ${
- monitor.width
- }x${monitor.height} ${
- monitor.is_default ? "(default)" : ""
- }`,
- }))}
- defaultValue={settings.monitorIds}
- onValueChange={(values) =>
- values.length === 0
- ? handleSettingsChange({ disableVision: true }, true)
- : handleSettingsChange({ monitorIds: values }, true)
- }
- placeholder={
- settings.useAllMonitors
- ? "all monitors will be used"
- : "select monitors"
- }
- variant="default"
- modalPopover={true}
- animation={2}
- // disabled={settings.useAllMonitors}
- />
- </div>
-
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="ocrModel"
- className="flex items-center space-x-2"
- >
- <Eye className="h-4 w-4" />
- <span>ocr model</span>
- </Label>
- <Select
- onValueChange={handleOcrModelChange}
- defaultValue={settings.ocrEngine}
- >
- <SelectTrigger>
- <SelectValue
- className="capitalize"
- placeholder="select ocr engine"
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ settings.audioDevices.includes(device.name)
+ ? "opacity-100"
+ : "opacity-0"
+ )}
/>
- </SelectTrigger>
- <SelectContent className="capitalize">
- {renderOcrEngineOptions()}
- </SelectContent>
- </Select>
- </div>
- <div className="flex flex-col space-y-2">
- <Label htmlFor="fps" className="flex items-center space-x-2">
- <span>frames per second (fps)</span>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <p>
- adjust the recording frame rate. lower values save
- <br />
- resources, higher values provide smoother
- recordings, less likely to miss activity.
- <br />
- (we do not use resources if your screen does not
- change much)
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </Label>
- <div className="flex items-center space-x-4">
- <Slider
- id="fps"
- min={0.1}
- max={10}
- step={0.1}
- value={[settings.fps]}
- onValueChange={handleFpsChange}
- className="flex-grow"
- />
- <span className="w-12 text-right">
- {settings.fps.toFixed(1)}
- </span>
- </div>
- </div>
- <div className="space-y-6">
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="ignoredWindows"
- className="flex items-center space-x-2"
- >
- <span>ignored windows</span>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <p>
- windows to ignore during screen recording
- (case-insensitive), example:
- <br />
- - &quot;bit&quot; will ignore
- &quot;Bitwarden&quot; and &quot;bittorrent&quot;
- <br />- &quot;incognito&quot; will ignore tabs,
- windows that contains the word
- &quot;incognito&quot;
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </Label>
- <MultiSelect
- options={createWindowOptions(
- windowItems,
- settings.ignoredWindows
+ {device.name}
+ {device.is_default && (
+ <Badge variant="secondary" className="ml-2">
+ Default
+ </Badge>
)}
- defaultValue={settings.ignoredWindows}
- onValueChange={handleIgnoredWindowsChange}
- placeholder="add windows to ignore"
- variant="default"
- modalPopover={true}
- animation={2}
- allowCustomValues={true}
- validateCustomValue={(value) => value.length >= 2}
- />
- </div>
-
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="includedWindows"
- className="flex items-center space-x-2"
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ </div>
+
+ {/* Languages */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="languages" className="flex items-center space-x-2">
+ <Languages className="h-4 w-4" />
+ <span>Languages</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Select languages for audio transcription. Multiple languages can be selected.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <Popover open={openLanguages} onOpenChange={setOpenLanguages}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={openLanguages}
+ className="w-full justify-between"
+ >
+ {settings.languages.length > 0
+ ? `${settings.languages.length} language(s) selected`
+ : "Select languages..."}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-full p-0">
+ <Command>
+ <CommandInput placeholder="Search languages..." />
+ <CommandList>
+ <CommandEmpty>No languages found.</CommandEmpty>
+ <CommandGroup>
+ {[
+ { code: "english", name: "English" },
+ { code: "spanish", name: "Spanish" },
+ { code: "french", name: "French" },
+ { code: "german", name: "German" },
+ { code: "italian", name: "Italian" },
+ { code: "portuguese", name: "Portuguese" },
+ { code: "russian", name: "Russian" },
+ { code: "japanese", name: "Japanese" },
+ { code: "korean", name: "Korean" },
+ { code: "chinese", name: "Chinese" },
+ { code: "arabic", name: "Arabic" },
+ { code: "hindi", name: "Hindi" },
+ { code: "dutch", name: "Dutch" },
+ { code: "swedish", name: "Swedish" },
+ { code: "indonesian", name: "Indonesian" },
+ { code: "finnish", name: "Finnish" },
+ { code: "hebrew", name: "Hebrew" },
+ { code: "ukrainian", name: "Ukrainian" },
+ { code: "greek", name: "Greek" },
+ { code: "malay", name: "Malay" },
+ { code: "czech", name: "Czech" },
+ { code: "romanian", name: "Romanian" },
+ { code: "danish", name: "Danish" },
+ { code: "hungarian", name: "Hungarian" },
+ { code: "norwegian", name: "Norwegian" },
+ { code: "thai", name: "Thai" },
+ { code: "urdu", name: "Urdu" },
+ { code: "croatian", name: "Croatian" },
+ { code: "bulgarian", name: "Bulgarian" },
+ { code: "lithuanian", name: "Lithuanian" },
+ { code: "latin", name: "Latin" },
+ { code: "welsh", name: "Welsh" },
+ { code: "slovak", name: "Slovak" },
+ { code: "persian", name: "Persian" },
+ { code: "latvian", name: "Latvian" },
+ { code: "bengali", name: "Bengali" },
+ { code: "serbian", name: "Serbian" },
+ { code: "azerbaijani", name: "Azerbaijani" },
+ { code: "slovenian", name: "Slovenian" },
+ { code: "estonian", name: "Estonian" },
+ { code: "macedonian", name: "Macedonian" },
+ { code: "nepali", name: "Nepali" },
+ { code: "mongolian", name: "Mongolian" },
+ { code: "bosnian", name: "Bosnian" },
+ { code: "kazakh", name: "Kazakh" },
+ { code: "albanian", name: "Albanian" },
+ { code: "swahili", name: "Swahili" },
+ { code: "galician", name: "Galician" },
+ { code: "marathi", name: "Marathi" },
+ { code: "punjabi", name: "Punjabi" },
+ { code: "sinhala", name: "Sinhala" },
+ { code: "khmer", name: "Khmer" },
+ { code: "afrikaans", name: "Afrikaans" },
+ { code: "belarusian", name: "Belarusian" },
+ { code: "gujarati", name: "Gujarati" },
+ { code: "amharic", name: "Amharic" },
+ { code: "yiddish", name: "Yiddish" },
+ { code: "lao", name: "Lao" },
+ { code: "uzbek", name: "Uzbek" },
+ { code: "faroese", name: "Faroese" },
+ { code: "pashto", name: "Pashto" },
+ { code: "maltese", name: "Maltese" },
+ { code: "sanskrit", name: "Sanskrit" },
+ { code: "luxembourgish", name: "Luxembourgish" },
+ { code: "myanmar", name: "Myanmar" },
+ { code: "tibetan", name: "Tibetan" },
+ { code: "tagalog", name: "Tagalog" },
+ { code: "assamese", name: "Assamese" },
+ { code: "tatar", name: "Tatar" },
+ { code: "hausa", name: "Hausa" },
+ { code: "javanese", name: "Javanese" },
+ { code: "turkish", name: "Turkish" },
+ { code: "polish", name: "Polish" },
+ { code: "catalan", name: "Catalan" },
+ { code: "malayalam", name: "Malayalam" },
+ ].map((language) => (
+ <CommandItem
+ key={language.code}
+ value={language.code}
+ onSelect={() => handleLanguageChange(language.code as Language)}
>
- <span>included windows</span>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <p>
- windows to include during screen recording
- (case-insensitive), example:
- <br />
- - &quot;chrome&quot; will match &quot;Google
- Chrome&quot;
- <br />- &quot;bitwarden&quot; will match
- &quot;Bitwarden&quot; and &quot;bittorrent&quot;
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </Label>
- <MultiSelect
- options={createWindowOptions(
- windowItems,
- settings.includedWindows
- )}
- defaultValue={settings.includedWindows}
- onValueChange={handleIncludedWindowsChange}
- placeholder="add window to include"
- variant="default"
- modalPopover={true}
- animation={2}
- allowCustomValues={true}
- validateCustomValue={(value) => value.length >= 2}
- />
- </div>
- </div>
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ settings.languages.includes(language.code as Language)
+ ? "opacity-100"
+ : "opacity-0"
+ )}
+ />
+ {language.name}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ </div>
+
+ {/* Audio Settings Toggles */}
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="disableAudio">Disable audio recording</Label>
+ <p className="text-sm text-muted-foreground">
+ Turn off audio recording completely
+ </p>
+ </div>
+ <Switch
+ id="disableAudio"
+ checked={settings.disableAudio}
+ onCheckedChange={handleDisableAudioChange}
+ />
+ </div>
+
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="usePiiRemoval">PII removal</Label>
+ <p className="text-sm text-muted-foreground">
+ Remove personally identifiable information from transcriptions
+ </p>
+ </div>
+ <Switch
+ id="usePiiRemoval"
+ checked={settings.usePiiRemoval}
+ onCheckedChange={handlePiiRemovalChange}
+ />
+ </div>
+ </div>
- {/* */}
+ {/* VAD Sensitivity */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="vadSensitivity" className="flex items-center space-x-2">
+ <span>Voice activity detection sensitivity</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Adjust how sensitive the voice activity detection is. Higher sensitivity
+ may capture more audio but also more background noise.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <div className="flex items-center space-x-4">
+ <Slider
+ id="vadSensitivity"
+ min={0}
+ max={2}
+ step={1}
+ value={[vadSensitivityToNumber(settings.vadSensitivity as VadSensitivity)]}
+ onValueChange={handleVadSensitivityChange}
+ className="flex-grow"
+ />
+ <span className="w-16 text-right capitalize">
+ {settings.vadSensitivity}
+ </span>
+ </div>
+ </div>
+
+ <Separator />
+
+ {/* Video Settings */}
+ <div className="flex flex-col space-y-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Monitor className="h-5 w-5" />
+ <h3 className="text-lg font-semibold">Video Recording</h3>
+ </div>
+
+ {/* Monitor Selection */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="monitors" className="flex items-center space-x-2">
+ <span>Monitors</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Select which monitors to record from. Multiple monitors can be selected.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ {availableMonitors.map((monitor) => (
+ <div
+ key={monitor.id}
+ className={cn(
+ "flex items-center space-x-3 rounded-lg border p-3 cursor-pointer transition-colors",
+ settings.monitorIds.includes(monitor.id.toString())
+ ? "border-primary bg-primary/5"
+ : "border-border hover:bg-accent"
+ )}
+ onClick={() => {
+ const currentIds = settings.monitorIds;
+ const monitorId = monitor.id.toString();
+ const updatedIds = currentIds.includes(monitorId)
+ ? currentIds.filter(id => id !== monitorId)
+ : [...currentIds, monitorId];
+
+ handleSettingsChange({ monitorIds: updatedIds }, true);
+ }}
+ >
+ <div className="flex-1">
+ <p className="font-medium">{monitor.name}</p>
+ <p className="text-sm text-muted-foreground">
+ {monitor.width}x{monitor.height}
+ {monitor.is_default && " (Default)"}
+ </p>
+ </div>
+ <Check
+ className={cn(
+ "h-4 w-4",
+ settings.monitorIds.includes(monitor.id.toString())
+ ? "opacity-100"
+ : "opacity-0"
+ )}
+ />
</div>
- <Separator className="my-6" />
- </>
- )}
+ ))}
+ </div>
</div>
- <h4 className="text-lg font-semibold my-4">audio</h4>
+ {/* OCR Engine */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="ocrEngine" className="flex items-center space-x-2">
+ <span>OCR engine</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ OCR (Optical Character Recognition) engine for extracting text from images.
+ Platform-optimized engine is automatically selected.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <Select
+ value={settings.ocrEngine}
+ onValueChange={handleOcrModelChange}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select OCR engine" />
+ </SelectTrigger>
+ <SelectContent>
+ {isMacOS && <SelectItem value="apple-native">Apple Native</SelectItem>}
+ {!isMacOS && platform() === "windows" && <SelectItem value="windows-native">Windows Native</SelectItem>}
+ {!isMacOS && platform() !== "windows" && <SelectItem value="tesseract">Tesseract</SelectItem>}
+ </SelectContent>
+ </Select>
+ </div>
- <div className="space-y-6">
+ {/* Video Settings Toggles */}
+ <div className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-1">
- <h4 className="font-medium">disable audio recording</h4>
+ <Label htmlFor="disableVision">Disable screen recording</Label>
<p className="text-sm text-muted-foreground">
- useful if you don&apos;t need audio or if you have memory/cpu
- issues
+ Turn off screen recording completely
</p>
</div>
<Switch
- id="disableAudio"
- checked={settings.disableAudio}
- onCheckedChange={handleDisableAudioChange}
+ id="disableVision"
+ checked={settings.disableVision}
+ onCheckedChange={(checked) =>
+ handleSettingsChange({ disableVision: checked }, true)
+ }
/>
</div>
- {!settings.disableAudio && (
- <>
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h4 className="font-medium">
- enable realtime audio transcription
- </h4>
- <p className="text-sm text-muted-foreground">
- transcribe audio in real-time as you speak (dev preview) -{" "}
- <a
- href="https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-js/examples/basic-transcription/index.ts"
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary hover:underline"
- >
- view example
- </a>
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Switch
- id="enableRealtimeAudio"
- checked={settings.enableRealtimeAudioTranscription}
- onCheckedChange={(checked) =>
- handleSettingsChange(
- {
- enableRealtimeAudioTranscription: checked,
- },
- true
- )
- }
- />
- </div>
- </div>
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="useAllMonitors">Use all monitors</Label>
+ <p className="text-sm text-muted-foreground">
+ Automatically record from all available monitors
+ </p>
+ </div>
+ <Switch
+ id="useAllMonitors"
+ checked={settings.useAllMonitors}
+ onCheckedChange={(checked) =>
+ handleSettingsChange({ useAllMonitors: checked }, true)
+ }
+ />
+ </div>
- {settings.enableRealtimeAudioTranscription && (
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="realtimeAudioTranscriptionEngine"
- className="flex items-center space-x-2"
- >
- <Mic className="h-4 w-4" />
- <span>realtime transcription model</span>
- </Label>
- <Select
- onValueChange={(value) =>
- handleAudioTranscriptionModelChange(value, true)
- }
- value={settings.realtimeAudioTranscriptionEngine}
- >
- <SelectTrigger>
- <SelectValue placeholder="select realtime transcription engine" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="screenpipe-cloud">
- <div className="flex items-center justify-between w-full space-x-2">
- <span>screenpipe cloud</span>
- <div className="flex items-center gap-2">
- <Badge variant="secondary">cloud</Badge>
- {!settings.user?.cloud_subscribed && (
- <Badge variant="outline" className="text-xs">
- get screenpipe cloud
- </Badge>
- )}
- </div>
- </div>
- </SelectItem>
- <SelectItem value="deepgram">
- <div className="flex items-center justify-between w-full space-x-2">
- <span>deepgram</span>
- <Badge variant="secondary">cloud</Badge>
- </div>
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
- )}
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="enableRealtimeVision">Enable realtime vision</Label>
+ <p className="text-sm text-muted-foreground">
+ Process screen content in real-time for immediate analysis
+ </p>
+ </div>
+ <Switch
+ id="enableRealtimeVision"
+ checked={settings.enableRealtimeVision}
+ onCheckedChange={(checked) =>
+ handleSettingsChange({ enableRealtimeVision: checked }, true)
+ }
+ />
+ </div>
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="audioTranscriptionModel"
- className="flex items-center space-x-2"
- >
- <Mic className="h-4 w-4" />
- <span>audio transcription model</span>
- </Label>
- <Select
- onValueChange={handleAudioTranscriptionModelChange}
- value={settings.audioTranscriptionEngine}
- >
- <SelectTrigger>
- <SelectValue placeholder="select audio transcription engine" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="screenpipe-cloud">
- <div className="flex items-center justify-between w-full space-x-2">
- <span>screenpipe cloud</span>
- <div className="flex items-center gap-2">
- <Badge variant="secondary">cloud</Badge>
- {!settings.user?.cloud_subscribed && (
- <Badge variant="outline" className="text-xs">
- get screenpipe cloud
- </Badge>
- )}
- </div>
- </div>
- </SelectItem>
- <SelectItem value="deepgram">
- <div className="flex items-center justify-between w-full space-x-2">
- <span>deepgram</span>
- <Badge variant="secondary">cloud</Badge>
- </div>
- </SelectItem>
- <SelectItem value="whisper-tiny">whisper-tiny</SelectItem>
- <SelectItem value="whisper-tiny-quantized">
- whisper-tiny-quantized
- </SelectItem>
- <SelectItem value="whisper-large">whisper-large</SelectItem>
- <SelectItem value="whisper-large-quantized">
- whisper-large-quantized
- </SelectItem>
- <SelectItem value="whisper-large-v3-turbo">
- whisper-large-turbo
- </SelectItem>
- <SelectItem value="whisper-large-v3-turbo-quantized">
- whisper-large-turbo-quantized
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="enableFrameCache">Enable frame cache</Label>
+ <p className="text-sm text-muted-foreground">
+ Cache frames to improve performance and reduce resource usage
+ </p>
+ </div>
+ <Switch
+ id="enableFrameCache"
+ checked={settings.enableFrameCache}
+ onCheckedChange={handleFrameCacheToggle}
+ />
+ </div>
- {settings.audioTranscriptionEngine === "deepgram" && (
- <div className="mt-2">
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="deepgramApiKey"
- className="flex items-center gap-2"
- >
- <Key className="h-4 w-4" />
- <span>api key</span>
- </Label>
- <div className="flex-grow relative">
- <Input
- id="deepgramApiKey"
- type={showApiKey ? "text" : "password"}
- value={settings.deepgramApiKey}
- onChange={(e) => {
- const newValue = e.target.value;
- handleSettingsChange(
- {
- deepgramApiKey: newValue,
- },
- true
- );
- }}
- className="pr-10 w-full"
- placeholder="enter your Deepgram API key"
- autoCorrect="off"
- autoCapitalize="off"
- autoComplete="off"
- />
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="absolute right-0 top-0 h-full"
- onClick={() => setShowApiKey(!showApiKey)}
- >
- {showApiKey ? (
- <EyeOff className="h-4 w-4" />
- ) : (
- <Eye className="h-4 w-4" />
- )}
- </Button>
- </div>
- </div>
- <p className="text-sm text-muted-foreground text-left mt-1">
- don&apos;t have an api key? get one from{" "}
- <a
- href="https://console.deepgram.com/"
- target="_blank"
- rel="noopener noreferrer"
- className="text-primary hover:underline"
- >
- deepgram&apos;s website
- </a>{" "}
- or use screenpipe cloud
- </p>
- </div>
- )}
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="enableUiMonitoring">Enable UI monitoring</Label>
+ <p className="text-sm text-muted-foreground">
+ Monitor UI elements and interactions (requires accessibility permission)
+ </p>
+ </div>
+ <Switch
+ id="enableUiMonitoring"
+ checked={settings.enableUiMonitoring}
+ onCheckedChange={handleUiMonitoringToggle}
+ />
+ </div>
+ </div>
+ </div>
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="audioDevices"
- className="flex items-center space-x-2"
- >
- <Mic className="h-4 w-4" />
- <span>audio devices</span>
- </Label>
- <Popover
- open={openAudioDevices}
- onOpenChange={setOpenAudioDevices}
- modal={true}
- >
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- aria-expanded={openAudioDevices}
- className="w-full justify-between"
- >
- {settings.audioDevices.length > 0
- ? `${settings.audioDevices.length} device(s) selected`
- : "select audio devices"}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-full p-0">
- <Command>
- <CommandInput placeholder="search audio devices..." />
- <CommandList>
- <CommandEmpty>no audio device found.</CommandEmpty>
- <CommandGroup>
- {availableAudioDevices.map((device) => (
- <CommandItem
- key={device.name}
- value={device.name}
- onSelect={() =>
- handleAudioDeviceChange(device.name)
- }
- >
- <div className="flex items-center">
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- settings.audioDevices.includes(device.name)
- ? "opacity-100"
- : "opacity-0"
- )}
- />
- <span
- style={{
- userSelect: "none",
- WebkitUserSelect: "none",
- MozUserSelect: "none",
- msUserSelect: "none",
- }}
- >
- {device.name}{" "}
- {device.is_default ? "(default)" : ""}
- </span>
- </div>
- </CommandItem>
- ))}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- </div>
+ <Separator />
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="languages"
- className="flex items-center space-x-2"
- >
- <Languages className="h-4 w-4" />
- <span>languages</span>
- </Label>
- <Popover open={openLanguages} onOpenChange={setOpenLanguages}>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- aria-expanded={openLanguages}
- className="w-full justify-between"
- >
- {settings.languages.length > 0
- ? `${settings.languages.join(", ")}`
- : "select languages"}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-full p-0">
- <Command>
- <CommandInput placeholder="search languages..." />
- <CommandList>
- <CommandEmpty>no language found.</CommandEmpty>
- <CommandGroup>
- {Object.entries(Language).map(([language, id]) => (
- <CommandItem
- key={language}
- value={language}
- onSelect={() => handleLanguageChange(id)}
- >
- <div className="flex items-center">
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- settings.languages.includes(id)
- ? "opacity-100"
- : "opacity-0"
- )}
- />
- {/* not selectable */}
- <span
- style={{
- userSelect: "none",
- WebkitUserSelect: "none",
- MozUserSelect: "none",
- msUserSelect: "none",
- }}
- >
- {language}
- </span>
- </div>
- </CommandItem>
- ))}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- </div>
+ {/* Window Filtering */}
+ <div className="space-y-4">
+ <div className="flex items-center gap-2 mb-2">
+ <AppWindowMac className="h-5 w-5" />
+ <h3 className="text-lg font-semibold">Window Filtering</h3>
+ </div>
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="vadSensitivity"
- className="flex items-center space-x-2"
- >
- <span>voice activity detection sensitivity</span>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <p>
- adjust the voice activity detection sensitivity.
- <br />
- low: more sensitive, catches most speech but may have
- more false positives.
- <br />
- medium: balanced sensitivity.
- <br />
- high (recommended): less sensitive, may miss some
- speech but reduces false positives.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </Label>
- <div className="flex items-center space-x-4">
- <Slider
- id="vadSensitivity"
- min={0}
- max={2}
- step={1}
- value={[vadSensitivityToNumber(settings.vadSensitivity)]}
- onValueChange={handleVadSensitivityChange}
- className="flex-grow"
- />
- <span className="w-16 text-right">
- {settings.vadSensitivity}
- </span>
- </div>
- <div className="flex justify-between text-xs text-gray-500">
- <span>low</span>
- <span>medium</span>
- <span>high</span>
- </div>
- </div>
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="ignoredWindows" className="flex items-center space-x-2">
+ <span>Ignored windows</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Windows that will be excluded from recording. Useful for privacy or reducing noise.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <MultiSelect
+ options={createWindowOptions(windowItems || [], settings.ignoredWindows)}
+ value={settings.ignoredWindows}
+ onValueChange={handleIgnoredWindowsChange}
+ placeholder="Select windows to ignore..."
+ />
+ </div>
- <div className="flex flex-col space-y-2">
- <Label
- htmlFor="audioChunkDuration"
- className="flex items-center space-x-2"
- >
- <span>audio chunk duration (seconds)</span>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger>
- <HelpCircle className="h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="right">
- <p>
- adjust the duration of each audio chunk.
- <br />
- shorter durations may lower resource usage spikes,
- <br />
- while longer durations may increase transcription
- quality.
- <br />
- deepgram in general works better than whisper if you
- want higher quality transcription.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </Label>
- <div className="flex items-center space-x-4">
- <Slider
- id="audioChunkDuration"
- min={5}
- max={3000}
- step={1}
- value={[settings.audioChunkDuration]}
- onValueChange={handleAudioChunkDurationChange}
- className="flex-grow"
- />
- <span className="w-12 text-right">
- {settings.audioChunkDuration} s
- </span>
- </div>
- </div>
- </>
- )}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="includedWindows" className="flex items-center space-x-2">
+ <span>Included windows (whitelist)</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Only these windows will be recorded. Leave empty to record all windows except ignored ones.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <MultiSelect
+ options={createWindowOptions(windowItems || [], settings.includedWindows)}
+ value={settings.includedWindows}
+ onValueChange={handleIncludedWindowsChange}
+ placeholder="Select windows to include (optional)..."
+ />
</div>
+ </div>
- <Separator className="my-6" />
+ <Separator />
- <h4 className="text-lg font-semibold my-4">misc</h4>
+ {/* System Settings */}
+ <div className="space-y-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Terminal className="h-5 w-5" />
+ <h3 className="text-lg font-semibold">System Settings</h3>
+ </div>
- <div className="space-y-8 py-4">
- <div className="space-y-6">
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h4 className="font-medium">
- remove personal information (pii)
- </h4>
- <p className="text-sm text-muted-foreground">
- removes sensitive data like credit cards, emails, and phone
- numbers from ocr text
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Badge variant="secondary">experimental</Badge>
- <Switch
- id="piiRemoval"
- checked={settings.usePiiRemoval}
- onCheckedChange={handlePiiRemovalChange}
- />
- </div>
- </div>
+ {/* Port Configuration */}
+ <ValidatedInput
+ id="port"
+ label="Server Port"
+ type="number"
+ value={settings.port.toString()}
+ onChange={(value, isValid) => {
+ const portValue = parseInt(value) || 3030;
+ handleSettingsChange({ port: portValue }, true);
+ }}
+ validation={(value) => validateField("port", parseInt(value) || 0)}
+ placeholder="Enter server port"
+ required={true}
+ helperText="Port for the Screenpipe server (requires restart)"
+ />
+
+ {/* Restart Interval */}
+ <div className="flex flex-col space-y-2">
+ <Label htmlFor="restartInterval" className="flex items-center space-x-2">
+ <span>Restart interval (minutes)</span>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>
+ <HelpCircle className="h-4 w-4 cursor-default" />
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ <p>
+ Automatically restart the recording process at this interval. Set to 0 to disable.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </Label>
+ <div className="flex items-center space-x-4">
+ <Slider
+ id="restartInterval"
+ min={0}
+ max={1440}
+ step={15}
+ value={[settings.restartInterval]}
+ onValueChange={(value) =>
+ handleSettingsChange({ restartInterval: value[0] }, true)
+ }
+ className="flex-grow"
+ />
+ <span className="w-16 text-right">
+ {settings.restartInterval === 0 ? "Disabled" : `${settings.restartInterval}m`}
+ </span>
+ </div>
+ </div>
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h4 className="font-medium">enable telemetry</h4>
- <p className="text-sm text-muted-foreground">
- help improve screenpipe with anonymous usage data
- </p>
- </div>
- <Switch
- id="analytics-toggle"
- checked={settings.analyticsEnabled}
- onCheckedChange={handleAnalyticsToggle}
- />
+ {/* System Toggles */}
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="analyticsEnabled">Enable analytics</Label>
+ <p className="text-sm text-muted-foreground">
+ Help improve Screenpipe by sharing anonymous usage data
+ </p>
</div>
+ <Switch
+ id="analyticsEnabled"
+ checked={settings.analyticsEnabled}
+ onCheckedChange={handleAnalyticsToggle}
+ />
+ </div>
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h4 className="font-medium">use chinese mirror</h4>
- <p className="text-sm text-muted-foreground">
- alternative download source for hugging face models in
- mainland china
- </p>
- </div>
- <Switch
- id="chinese-mirror-toggle"
- checked={settings.useChineseMirror}
- onCheckedChange={handleChineseMirrorToggle}
- />
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="useChineseMirror">Use Chinese mirror</Label>
+ <p className="text-sm text-muted-foreground">
+ Use Chinese mirror for downloads (for users in China)
+ </p>
</div>
+ <Switch
+ id="useChineseMirror"
+ checked={settings.useChineseMirror}
+ onCheckedChange={handleChineseMirrorToggle}
+ />
+ </div>
- {isMacOS && (
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h4 className="font-medium">enable ui monitoring</h4>
- <p className="text-sm text-muted-foreground">
- monitor ui elements for better search context (requires
- accessibility permission)
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Switch
- id="ui-monitoring-toggle"
- checked={settings.enableUiMonitoring}
- onCheckedChange={handleUiMonitoringToggle}
- />
- </div>
- </div>
- )}
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="devMode">Developer mode</Label>
+ <p className="text-sm text-muted-foreground">
+ Enable developer features and debug logging
+ </p>
+ </div>
+ <Switch
+ id="devMode"
+ checked={settings.devMode}
+ onCheckedChange={(checked) =>
+ handleSettingsChange({ devMode: checked }, false)
+ }
+ />
+ </div>
- <div className="space-y-2">
- <div className="flex items-center gap-2 mb-2">
- <Folder className="h-5 w-5" />
- <h3 className="text-lg font-semibold">data directory</h3>
- </div>
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Label htmlFor="enableBeta">Enable beta features</Label>
+ <p className="text-sm text-muted-foreground">
+ Access experimental features (may be unstable)
+ </p>
+ </div>
+ <Switch
+ id="enableBeta"
+ checked={settings.enableBeta}
+ onCheckedChange={(checked) =>
+ handleSettingsChange({ enableBeta: checked }, false)
+ }
+ />
+ </div>
+ </div>
+ </div>
- {!dataDirInputVisible ? (
- <Button
- variant="outline"
- role="combobox"
- className="w-full justify-between"
- onClick={handleDataDirChange}
- >
- <div className="flex gap-4">
- {!!settings.dataDir
- ? "change directory"
- : "select directory"}
- <span className="text-muted-foreground">
- {settings.dataDir === settings.dataDir
- ? `current at: ${
- settings.dataDir || "default directory"
- }`
- : `change to: ${
- settings.dataDir || "default directory"
- }`}
- </span>
- </div>
- <ChevronsUpDown className="h-4 w-4 opacity-50" />
- </Button>
+ {/* Action Buttons */}
+ <div className="flex items-center justify-between pt-6 border-t">
+ <div className="text-sm text-muted-foreground">
+ {hasUnsavedChanges && "Changes require restart to take effect"}
+ </div>
+ <div className="flex gap-2">
+ {hasUnsavedChanges && (
+ <Button
+ onClick={handleUpdate}
+ disabled={isUpdating || Object.keys(validationErrors).length > 0}
+ className="flex items-center gap-2"
+ >
+ {isUpdating ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
) : (
- <Input
- id="dataDir"
- type="text"
- autoFocus={true}
- value={settings.dataDir}
- onChange={handleDataDirInputChange}
- onBlur={handleDataDirInputBlur}
- onKeyDown={handleDataDirInputKeyDown}
- />
+ <RefreshCw className="h-4 w-4" />
)}
- </div>
-
- {/* */}
- </div>
+ Apply Changes
+ </Button>
+ )}
</div>
</div>
</div>
diff --git a/openrewind/components/settings/shortcut-row.tsx b/openrewind/components/settings/shortcut-row.tsx
index 682da4529..bff82efb4 100644
--- a/openrewind/components/settings/shortcut-row.tsx
+++ b/openrewind/components/settings/shortcut-row.tsx
@@ -1,19 +1,18 @@
import React, { useEffect, useState } from "react";
import { Settings, Shortcut, useSettings } from "@/lib/hooks/use-settings";
-import { useProfiles } from "@/lib/hooks/use-profiles";
import { parseKeyboardShortcut } from "@/lib/utils";
import { Switch } from "@/components/ui/switch";
import { toast } from "@/components/ui/use-toast";
import { cn } from "@/lib/utils";
import { Pencil } from "lucide-react";
-import { invoke } from "@tauri-apps/api/core";
+import { commands } from "@/lib/utils/tauri";
import hotkeys from "hotkeys-js";
interface ShortcutRowProps {
shortcut: string;
title: string;
description: string;
- type: "global" | "profile" | "pipe";
+ type: "global" | "pipe";
value?: string;
}
@@ -32,7 +31,6 @@ const ShortcutRow = ({
}: ShortcutRowProps) => {
const [isRecording, setIsRecording] = useState(false);
const { settings, updateSettings } = useSettings();
- const { profileShortcuts, updateProfileShortcut } = useProfiles();
useEffect(() => {
if (!isRecording) return;
@@ -91,7 +89,6 @@ const ShortcutRow = ({
stopRecordingShortcut: string;
startAudioShortcut: string;
stopAudioShortcut: string;
- profileShortcuts: Record<string, string>;
pipeShortcuts: Record<string, string>;
}) => {
console.log("syncing shortcuts:", {
@@ -100,20 +97,18 @@ const ShortcutRow = ({
stopShortcut: updatedShortcuts.stopRecordingShortcut,
startAudioShortcut: updatedShortcuts.startAudioShortcut,
stopAudioShortcut: updatedShortcuts.stopAudioShortcut,
- profileShortcuts: updatedShortcuts.profileShortcuts,
pipeShortcuts: updatedShortcuts.pipeShortcuts,
});
// wait 1 second
await new Promise((resolve) => setTimeout(resolve, 1000));
- await invoke("update_global_shortcuts", {
- showShortcut: updatedShortcuts.showScreenpipeShortcut,
- startShortcut: updatedShortcuts.startRecordingShortcut,
- stopShortcut: updatedShortcuts.stopRecordingShortcut,
- startAudioShortcut: updatedShortcuts.startAudioShortcut,
- stopAudioShortcut: updatedShortcuts.stopAudioShortcut,
- profileShortcuts: updatedShortcuts.profileShortcuts,
- pipeShortcuts: updatedShortcuts.pipeShortcuts,
- });
+ await commands.updateGlobalShortcuts(
+ updatedShortcuts.showScreenpipeShortcut,
+ updatedShortcuts.startRecordingShortcut,
+ updatedShortcuts.stopRecordingShortcut,
+ updatedShortcuts.startAudioShortcut,
+ updatedShortcuts.stopAudioShortcut,
+ updatedShortcuts.pipeShortcuts
+ );
return true;
};
@@ -136,26 +131,14 @@ const ShortcutRow = ({
case "global":
updateSettings({ [shortcut]: keys });
await syncShortcuts({
- ...settings,
+ showScreenpipeShortcut: settings.showScreenpipeShortcut,
+ startRecordingShortcut: settings.startRecordingShortcut,
+ stopRecordingShortcut: settings.stopRecordingShortcut,
+ startAudioShortcut: settings.startAudioShortcut,
+ stopAudioShortcut: settings.stopAudioShortcut,
[shortcut]: keys,
- profileShortcuts,
pipeShortcuts: settings.pipeShortcuts,
- });
- break;
- case "profile":
- const profileId = shortcut.replace("profile_", "");
- updateProfileShortcut({
- profile: profileId,
- shortcut: keys,
- });
- await syncShortcuts({
- ...settings,
- profileShortcuts: {
- ...profileShortcuts,
- [profileId]: keys,
- },
- pipeShortcuts: settings.pipeShortcuts,
- });
+ } as any);
break;
case "pipe":
const pipeId = shortcut.replace("pipe_", "");
@@ -166,8 +149,11 @@ const ShortcutRow = ({
},
});
await syncShortcuts({
- ...settings,
- profileShortcuts,
+ showScreenpipeShortcut: settings.showScreenpipeShortcut,
+ startRecordingShortcut: settings.startRecordingShortcut,
+ stopRecordingShortcut: settings.stopRecordingShortcut,
+ startAudioShortcut: settings.startAudioShortcut,
+ stopAudioShortcut: settings.stopAudioShortcut,
pipeShortcuts: {
...settings.pipeShortcuts,
[pipeId]: keys,
@@ -198,8 +184,11 @@ const ShortcutRow = ({
});
await syncShortcuts({
- ...settings,
- profileShortcuts,
+ showScreenpipeShortcut: settings.showScreenpipeShortcut,
+ startRecordingShortcut: settings.startRecordingShortcut,
+ stopRecordingShortcut: settings.stopRecordingShortcut,
+ startAudioShortcut: settings.startAudioShortcut,
+ stopAudioShortcut: settings.stopAudioShortcut,
pipeShortcuts: settings.pipeShortcuts,
});
};
diff --git a/openrewind/components/settings/shortcut-section.tsx b/openrewind/components/settings/shortcut-section.tsx
index 97090ac86..04a23f9b3 100644
--- a/openrewind/components/settings/shortcut-section.tsx
+++ b/openrewind/components/settings/shortcut-section.tsx
@@ -1,6 +1,5 @@
import React, { useEffect, useState } from "react";
import { useSettings } from "@/lib/hooks/use-settings";
-import { useProfiles } from "@/lib/hooks/use-profiles";
import { PipeApi } from "@/lib/api";
import ShortcutRow from "./shortcut-row";
@@ -9,7 +8,6 @@ const ShortcutSection = () => {
{ id: string; source: string; enabled: boolean }[]
>([]);
const { settings } = useSettings();
- const { profiles, profileShortcuts } = useProfiles();
useEffect(() => {
const loadPipes = async () => {
@@ -33,11 +31,11 @@ const ShortcutSection = () => {
return (
<div className="space-y-8">
<div className="space-y-3">
- <h1 className="text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">
+ <h1 className="text-3xl font-bold tracking-tight text-foreground">
Shortcuts
</h1>
- <p className="text-slate-600 dark:text-slate-400 text-lg">
- Configure keyboard shortcuts for quick access to features
+ <p className="text-muted-foreground text-lg">
+ Keyboard shortcuts and hotkeys
</p>
</div>
@@ -82,28 +80,6 @@ const ShortcutSection = () => {
value={settings.stopAudioShortcut}
/>
- {profiles.length > 1 && (
- <>
- <div className="mt-8 mb-4">
- <h2 className="text-lg font-semibold">profile shortcuts</h2>
- <p className="text-sm text-muted-foreground">
- assign shortcuts to quickly switch between profiles
- </p>
- </div>
-
- {profiles.map((profile) => (
- <ShortcutRow
- key={profile}
- type="profile"
- shortcut={`profile_${profile}`}
- title={`switch to ${profile}`}
- description={`activate ${profile} profile`}
- value={profileShortcuts[profile]}
- />
- ))}
- </>
- )}
-
{pipes.filter((p) => p.enabled).length > 0 && (
<>
<div className="mt-8 mb-4">
diff --git a/openrewind/components/share-logs-button.tsx b/openrewind/components/share-logs-button.tsx
index a53254f43..087e101b3 100644
--- a/openrewind/components/share-logs-button.tsx
+++ b/openrewind/components/share-logs-button.tsx
@@ -2,7 +2,7 @@ import { Button } from "./ui/button";
import { useToast } from "./ui/use-toast";
import { Upload, Loader, Copy, X, Camera, Video } from "lucide-react";
import { readTextFile } from "@tauri-apps/plugin-fs";
-import { invoke } from "@tauri-apps/api/core";
+import { commands, LogFile } from "@/lib/utils/tauri";
import { useState, useEffect } from "react";
import { useCopyToClipboard } from "@/lib/hooks/use-copy-to-clipboard";
import { useSettings } from "@/lib/hooks/use-settings";
@@ -20,12 +20,6 @@ import {
} from "./ui/tooltip";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
-interface LogFile {
- name: string;
- path: string;
- modified_at: number;
-}
-
interface VideoChunk {
device_name: string;
file_path: string;
@@ -104,8 +98,17 @@ export const ShareLogsButton = ({
const getLogFiles = async () => {
try {
- const logFiles = await invoke("get_log_files");
- return logFiles as LogFile[];
+ const result = await commands.getLogFiles();
+ if (result.status === "ok") {
+ return result.data.map(file => ({
+ name: file.name,
+ path: file.path,
+ modified_at: Number(file.modified_at)
+ }));
+ } else {
+ console.error("failed to get log files:", result.error);
+ return [];
+ }
} catch (error) {
console.error("failed to get log files:", error);
return [];
@@ -250,11 +253,11 @@ export const ShareLogsButton = ({
signedUrl: signedUrlVideo,
});
- const videoUploaded = await invoke("upload_file_to_s3", {
- filePath: mergedVideoPath,
- signedUrl: signedUrlVideo,
- });
- if (!videoUploaded) throw new Error("Failed to upload video");
+ const videoResult = await commands.uploadFileToS3(
+ mergedVideoPath,
+ signedUrlVideo
+ );
+ if (videoResult.status !== "ok") throw new Error("Failed to upload video");
}
const os = osPlatform();
diff --git a/openrewind/components/status/permission-buttons.tsx b/openrewind/components/status/permission-buttons.tsx
index b092eaeab..ed813bad3 100644
--- a/openrewind/components/status/permission-buttons.tsx
+++ b/openrewind/components/status/permission-buttons.tsx
@@ -2,25 +2,11 @@ import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Check, Lock, Settings, X } from "lucide-react";
import { toast } from "@/components/ui/use-toast";
-import { invoke } from "@tauri-apps/api/core";
+import { commands, OSPermissionsCheck, OSPermissionStatus } from "@/lib/utils/tauri";
import { usePlatform } from "@/lib/hooks/use-platform";
import { useSettings } from "@/lib/hooks/use-settings";
import localforage from "localforage";
-// You can add this to a types.ts file in your lib directory
-export enum OSPermissionStatus {
- NotNeeded = "notNeeded",
- Empty = "empty",
- Granted = "granted",
- Denied = "denied",
-}
-
-export interface OSPermissionsCheck {
- screenRecording: OSPermissionStatus;
- microphone: OSPermissionStatus;
- accessibility: OSPermissionStatus;
-}
-
interface PermissionButtonsProps {
type: "screen" | "audio" | "accessibility";
}
@@ -38,12 +24,7 @@ export const PermissionButtons: React.FC<PermissionButtonsProps> = ({
const checkPermissions = async () => {
if (isMacOS) {
try {
- const perms = await invoke<OSPermissionsCheck>(
- "do_permissions_check",
- {
- initialCheck: true,
- }
- );
+ const perms = await commands.doPermissionsCheck(true);
setPermissions(perms);
} catch (error) {
console.error("Failed to check permissions:", error);
@@ -72,14 +53,10 @@ export const PermissionButtons: React.FC<PermissionButtonsProps> = ({
? "microphone"
: "accessibility";
- await invoke("request_permission", {
- permission: permissionType,
- });
+ await commands.requestPermission(permissionType);
// Refresh permissions after request
- const perms = await invoke<OSPermissionsCheck>("do_permissions_check", {
- initialCheck: false,
- });
+ const perms = await commands.doPermissionsCheck(false);
setPermissions(perms);
// If screen recording permission was requested, set flag and prompt for restart
@@ -113,9 +90,7 @@ export const PermissionButtons: React.FC<PermissionButtonsProps> = ({
? "microphone"
: "accessibility";
- await invoke("open_permission_settings", {
- permission: permissionType,
- });
+ await commands.openPermissionSettings(permissionType);
} catch (error) {
console.error(`failed to open ${type} permission settings:`, error);
toast({
@@ -130,8 +105,7 @@ export const PermissionButtons: React.FC<PermissionButtonsProps> = ({
if (!isMacOS) return null;
const isPermitted = (status: OSPermissionStatus) =>
- status === OSPermissionStatus.Granted ||
- status === OSPermissionStatus.NotNeeded;
+ status === "granted" || status === "notNeeded";
const permissionStatus =
type === "screen"
@@ -146,7 +120,7 @@ export const PermissionButtons: React.FC<PermissionButtonsProps> = ({
<div className="flex items-center gap-2">
{permissions && (
<span>
- {isPermitted(permissionStatus ?? OSPermissionStatus.Empty) ? (
+ {isPermitted(permissionStatus ?? "empty") ? (
<Check className="h-4 w-4 text-green-500" />
) : (
<X className="h-4 w-4 text-red-500" />
diff --git a/openrewind/components/ui/validated-input.tsx b/openrewind/components/ui/validated-input.tsx
new file mode 100644
index 000000000..db5b91339
--- /dev/null
+++ b/openrewind/components/ui/validated-input.tsx
@@ -0,0 +1,181 @@
+import React, { useState, useCallback, useMemo } from "react";
+import { Input, InputProps } from "./input";
+import { Label } from "./label";
+import { cn } from "@/lib/utils";
+import { AlertCircle, CheckCircle2, Info } from "lucide-react";
+import { debounce, FieldValidationResult } from "@/lib/utils/validation";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "./tooltip";
+
+export interface ValidatedInputProps extends Omit<InputProps, "onChange"> {
+ label?: string;
+ helperText?: string;
+ validation?: (value: string) => FieldValidationResult;
+ onChange?: (value: string, isValid: boolean) => void;
+ debounceMs?: number;
+ showValidationIcon?: boolean;
+ required?: boolean;
+ maxLength?: number;
+ minLength?: number;
+}
+
+export const ValidatedInput = React.forwardRef<HTMLInputElement, ValidatedInputProps>(
+ ({
+ label,
+ helperText,
+ validation,
+ onChange,
+ debounceMs = 300,
+ showValidationIcon = true,
+ required = false,
+ maxLength,
+ minLength,
+ className,
+ ...props
+ }, ref) => {
+ const [value, setValue] = useState(props.value?.toString() || "");
+ const [validationResult, setValidationResult] = useState<FieldValidationResult>({ isValid: true });
+ const [isTouched, setIsTouched] = useState(false);
+
+ // Debounced validation function
+ const debouncedValidation = useMemo(
+ () => debounce((val: string) => {
+ if (validation) {
+ const result = validation(val);
+ setValidationResult(result);
+ onChange?.(val, result.isValid);
+ } else {
+ onChange?.(val, true);
+ }
+ }, debounceMs),
+ [validation, onChange, debounceMs]
+ );
+
+ const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ const newValue = e.target.value;
+ setValue(newValue);
+ setIsTouched(true);
+
+ // Immediate validation for basic checks
+ if (required && !newValue.trim()) {
+ setValidationResult({ isValid: false, error: `${label || "Field"} is required` });
+ } else if (minLength && newValue.length < minLength) {
+ setValidationResult({ isValid: false, error: `Minimum ${minLength} characters required` });
+ } else if (maxLength && newValue.length > maxLength) {
+ setValidationResult({ isValid: false, error: `Maximum ${maxLength} characters allowed` });
+ } else {
+ // Clear immediate errors for debounced validation
+ setValidationResult({ isValid: true });
+ }
+
+ debouncedValidation(newValue);
+ }, [required, minLength, maxLength, label, debouncedValidation]);
+
+ const getValidationIcon = () => {
+ if (!showValidationIcon || !isTouched) return null;
+
+ if (!validationResult.isValid) {
+ return <AlertCircle className="h-4 w-4 text-destructive" />;
+ }
+
+ if (validationResult.warning) {
+ return <Info className="h-4 w-4 text-warning" />;
+ }
+
+ if (validation && value) {
+ return <CheckCircle2 className="h-4 w-4 text-success" />;
+ }
+
+ return null;
+ };
+
+ const getInputVariant = () => {
+ if (!isTouched) return "";
+
+ if (!validationResult.isValid) {
+ return "border-destructive focus-visible:ring-destructive";
+ }
+
+ if (validationResult.warning) {
+ return "border-warning focus-visible:ring-warning";
+ }
+
+ if (validation && value) {
+ return "border-success focus-visible:ring-success";
+ }
+
+ return "";
+ };
+
+ const getMessage = () => {
+ if (!isTouched) return helperText;
+ return validationResult.error || validationResult.warning || helperText;
+ };
+
+ const getMessageColor = () => {
+ if (!isTouched) return "text-muted-foreground";
+ if (!validationResult.isValid) return "text-destructive";
+ if (validationResult.warning) return "text-warning";
+ return "text-muted-foreground";
+ };
+
+ return (
+ <div className="space-y-2">
+ {label && (
+ <Label htmlFor={props.id} className="flex items-center gap-1">
+ {label}
+ {required && <span className="text-destructive">*</span>}
+ </Label>
+ )}
+
+ <div className="relative">
+ <Input
+ ref={ref}
+ {...props}
+ value={value}
+ onChange={handleChange}
+ onBlur={() => setIsTouched(true)}
+ className={cn(
+ getInputVariant(),
+ showValidationIcon && "pr-10",
+ className
+ )}
+ maxLength={maxLength}
+ />
+
+ {showValidationIcon && (
+ <div className="absolute right-3 top-1/2 -translate-y-1/2">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>{getValidationIcon()}</div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{validationResult.error || validationResult.warning || "Valid"}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ )}
+ </div>
+
+ {getMessage() && (
+ <p className={cn("text-sm", getMessageColor())}>
+ {getMessage()}
+ {maxLength && (
+ <span className="float-right text-muted-foreground">
+ {value.length}/{maxLength}
+ </span>
+ )}
+ </p>
+ )}
+ </div>
+ );
+ }
+);
+
+ValidatedInput.displayName = "ValidatedInput";
\ No newline at end of file
diff --git a/openrewind/components/ui/validated-textarea.tsx b/openrewind/components/ui/validated-textarea.tsx
new file mode 100644
index 000000000..f10b81352
--- /dev/null
+++ b/openrewind/components/ui/validated-textarea.tsx
@@ -0,0 +1,181 @@
+import React, { useState, useCallback, useMemo } from "react";
+import { Textarea, TextareaProps } from "./textarea";
+import { Label } from "./label";
+import { cn } from "@/lib/utils";
+import { AlertCircle, CheckCircle2, Info } from "lucide-react";
+import { debounce, FieldValidationResult } from "@/lib/utils/validation";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "./tooltip";
+
+export interface ValidatedTextareaProps extends Omit<TextareaProps, "onChange"> {
+ label?: string;
+ helperText?: string;
+ validation?: (value: string) => FieldValidationResult;
+ onChange?: (value: string, isValid: boolean) => void;
+ debounceMs?: number;
+ showValidationIcon?: boolean;
+ required?: boolean;
+ maxLength?: number;
+ minLength?: number;
+}
+
+export const ValidatedTextarea = React.forwardRef<HTMLTextAreaElement, ValidatedTextareaProps>(
+ ({
+ label,
+ helperText,
+ validation,
+ onChange,
+ debounceMs = 300,
+ showValidationIcon = true,
+ required = false,
+ maxLength,
+ minLength,
+ className,
+ ...props
+ }, ref) => {
+ const [value, setValue] = useState(props.value?.toString() || "");
+ const [validationResult, setValidationResult] = useState<FieldValidationResult>({ isValid: true });
+ const [isTouched, setIsTouched] = useState(false);
+
+ // Debounced validation function
+ const debouncedValidation = useMemo(
+ () => debounce((val: string) => {
+ if (validation) {
+ const result = validation(val);
+ setValidationResult(result);
+ onChange?.(val, result.isValid);
+ } else {
+ onChange?.(val, true);
+ }
+ }, debounceMs),
+ [validation, onChange, debounceMs]
+ );
+
+ const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
+ const newValue = e.target.value;
+ setValue(newValue);
+ setIsTouched(true);
+
+ // Immediate validation for basic checks
+ if (required && !newValue.trim()) {
+ setValidationResult({ isValid: false, error: `${label || "Field"} is required` });
+ } else if (minLength && newValue.length < minLength) {
+ setValidationResult({ isValid: false, error: `Minimum ${minLength} characters required` });
+ } else if (maxLength && newValue.length > maxLength) {
+ setValidationResult({ isValid: false, error: `Maximum ${maxLength} characters allowed` });
+ } else {
+ // Clear immediate errors for debounced validation
+ setValidationResult({ isValid: true });
+ }
+
+ debouncedValidation(newValue);
+ }, [required, minLength, maxLength, label, debouncedValidation]);
+
+ const getValidationIcon = () => {
+ if (!showValidationIcon || !isTouched) return null;
+
+ if (!validationResult.isValid) {
+ return <AlertCircle className="h-4 w-4 text-destructive" />;
+ }
+
+ if (validationResult.warning) {
+ return <Info className="h-4 w-4 text-warning" />;
+ }
+
+ if (validation && value) {
+ return <CheckCircle2 className="h-4 w-4 text-success" />;
+ }
+
+ return null;
+ };
+
+ const getTextareaVariant = () => {
+ if (!isTouched) return "";
+
+ if (!validationResult.isValid) {
+ return "border-destructive focus-visible:ring-destructive";
+ }
+
+ if (validationResult.warning) {
+ return "border-warning focus-visible:ring-warning";
+ }
+
+ if (validation && value) {
+ return "border-success focus-visible:ring-success";
+ }
+
+ return "";
+ };
+
+ const getMessage = () => {
+ if (!isTouched) return helperText;
+ return validationResult.error || validationResult.warning || helperText;
+ };
+
+ const getMessageColor = () => {
+ if (!isTouched) return "text-muted-foreground";
+ if (!validationResult.isValid) return "text-destructive";
+ if (validationResult.warning) return "text-warning";
+ return "text-muted-foreground";
+ };
+
+ return (
+ <div className="space-y-2">
+ {label && (
+ <Label htmlFor={props.id} className="flex items-center gap-1">
+ {label}
+ {required && <span className="text-destructive">*</span>}
+ </Label>
+ )}
+
+ <div className="relative">
+ <Textarea
+ ref={ref}
+ {...props}
+ value={value}
+ onChange={handleChange}
+ onBlur={() => setIsTouched(true)}
+ className={cn(
+ getTextareaVariant(),
+ showValidationIcon && "pr-10",
+ className
+ )}
+ maxLength={maxLength}
+ />
+
+ {showValidationIcon && (
+ <div className="absolute right-3 top-3">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>{getValidationIcon()}</div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{validationResult.error || validationResult.warning || "Valid"}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ )}
+ </div>
+
+ {getMessage() && (
+ <p className={cn("text-sm", getMessageColor())}>
+ {getMessage()}
+ {maxLength && (
+ <span className="float-right text-muted-foreground">
+ {value.length}/{maxLength}
+ </span>
+ )}
+ </p>
+ )}
+ </div>
+ );
+ }
+);
+
+ValidatedTextarea.displayName = "ValidatedTextarea";
\ No newline at end of file
diff --git a/openrewind/lib/api/store/index.ts b/openrewind/lib/api/store/index.ts
index f1b04db63..57f4d4756 100644
--- a/openrewind/lib/api/store/index.ts
+++ b/openrewind/lib/api/store/index.ts
@@ -1,4 +1,4 @@
-import { invoke } from "@tauri-apps/api/core";
+import { commands } from "../../utils/tauri";
import localforage from "localforage";
export interface PipeStorePlugin {
@@ -109,7 +109,7 @@ export class PipeApi {
private async init(authToken: string) {
try {
- const BASE_URL = await invoke("get_env", { name: "BASE_URL_PRIVATE" });
+ const BASE_URL = await commands.getEnv("BASE_URL_PRIVATE");
if (BASE_URL) {
this.baseUrl = BASE_URL as string;
}
diff --git a/openrewind/lib/hooks/use-disk-usage.tsx b/openrewind/lib/hooks/use-disk-usage.tsx
index 568556170..1bd40000c 100644
--- a/openrewind/lib/hooks/use-disk-usage.tsx
+++ b/openrewind/lib/hooks/use-disk-usage.tsx
@@ -3,11 +3,6 @@
import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
-export interface DiskUsedByPipes {
- pipes: [string, string][];
- total_pipes_size: string;
-}
-
export interface DiskUsedByMedia {
videos_size: string;
audios_size: string;
@@ -15,11 +10,10 @@ export interface DiskUsedByMedia {
}
export interface DiskUsage {
- pipes: DiskUsedByPipes;
media: DiskUsedByMedia;
total_data_size: string;
total_cache_size: string;
- avaiable_space: string;
+ available_space: string;
}
export function useDiskUsage() {
@@ -31,11 +25,37 @@ export function useDiskUsage() {
try {
setIsLoading(true);
setError(null);
- const result = await invoke<DiskUsage>("get_disk_usage");
+
+ // Add a small delay to show loading state for very fast calculations
+ const [result] = await Promise.all([
+ invoke<DiskUsage>("get_disk_usage"),
+ new Promise(resolve => setTimeout(resolve, 500)) // Minimum 500ms loading
+ ]);
+
setDiskUsage(result);
} catch (err) {
console.error("Failed to fetch disk usage:", err);
- setError(err as string);
+
+ // Provide more user-friendly error messages
+ let errorMessage = "Unknown error occurred";
+ if (typeof err === "string") {
+ errorMessage = err;
+ } else if (err instanceof Error) {
+ errorMessage = err.message;
+ } else if (err && typeof err === "object" && "message" in err) {
+ errorMessage = String(err.message);
+ }
+
+ // Handle common error scenarios
+ if (errorMessage.includes("permission") || errorMessage.includes("access")) {
+ errorMessage = "Permission denied. Please check file access permissions.";
+ } else if (errorMessage.includes("not found") || errorMessage.includes("directory")) {
+ errorMessage = "Screenpipe data directory not found. Make sure Screenpipe has been initialized.";
+ } else if (errorMessage.includes("timeout")) {
+ errorMessage = "Calculation timed out. Try again or check for very large datasets.";
+ }
+
+ setError(errorMessage);
} finally {
setIsLoading(false);
}
diff --git a/openrewind/lib/hooks/use-onboarding.tsx b/openrewind/lib/hooks/use-onboarding.tsx
index 03d6cf28a..8923ab5ef 100644
--- a/openrewind/lib/hooks/use-onboarding.tsx
+++ b/openrewind/lib/hooks/use-onboarding.tsx
@@ -1,116 +1,109 @@
-import { useSettings } from "./use-settings";
-import localforage from "localforage";
import { create } from "zustand";
+import { commands, OnboardingStore } from "@/lib/utils/tauri";
import { useEffect } from "react";
-// Define the store state type
interface OnboardingState {
- showOnboarding: boolean;
- setShowOnboarding: (show: boolean) => void;
- initialized: boolean;
- setInitialized: (initialized: boolean) => void;
+ onboardingData: OnboardingStore;
+ isLoading: boolean;
+ error: string | null;
+
+ // Actions
+ loadOnboardingStatus: () => Promise<void>;
+ completeOnboarding: () => Promise<void>;
+ resetOnboarding: () => Promise<void>;
}
-// Create the Zustand store
-export const useOnboardingStore = create<OnboardingState>((set) => ({
- showOnboarding: false,
- initialized: false,
- setShowOnboarding: (show: boolean) => {
- set({ showOnboarding: show });
- // Only persist when explicitly setting to false (completed)
- if (!show) {
- localforage.setItem("onboarding_completed", true);
- }
+export const useOnboarding = create<OnboardingState>((set, get) => ({
+ onboardingData: {
+ isCompleted: false,
+ completedAt: null,
},
- setInitialized: (initialized: boolean) => set({ initialized }),
-}));
+ isLoading: false,
+ error: null,
-// Initialize the store with persisted data
-const initializeOnboarding = async () => {
- const state = useOnboardingStore.getState();
-
- // Only initialize once
- if (state.initialized) {
- return;
- }
-
- try {
- // Add timeout to prevent hanging on localforage operations
- const timeoutPromise = new Promise((_, reject) => {
- setTimeout(() => reject(new Error("Initialization timeout")), 1000);
- });
-
- const initPromise = (async () => {
- // Check if onboarding was completed before
- const onboardingCompleted = await localforage.getItem("onboarding_completed");
-
- // Check if this is a first-time user (no user preferences stored)
- const userPreferences = await localforage.getItem("user_preferences");
+ loadOnboardingStatus: async () => {
+ try {
+ set({ isLoading: true, error: null });
+ const result = await commands.getOnboardingStatus();
- // Show onboarding if:
- // 1. Onboarding was never completed AND
- // 2. No user preferences exist (first-time user)
- const shouldShowOnboarding = !onboardingCompleted && !userPreferences;
-
- return { onboardingCompleted, userPreferences, shouldShowOnboarding };
- })();
-
- const result = await Promise.race([
- initPromise,
- timeoutPromise
- ]) as { onboardingCompleted: any, userPreferences: any, shouldShowOnboarding: boolean };
-
- const { onboardingCompleted, userPreferences, shouldShowOnboarding } = result;
-
- useOnboardingStore.setState({
- showOnboarding: shouldShowOnboarding,
- initialized: true,
- });
-
- console.log("Onboarding initialized:", {
- onboardingCompleted,
- userPreferences: !!userPreferences,
- shouldShowOnboarding
- });
- } catch (error) {
- console.error("Failed to initialize onboarding:", error);
- // Default to not showing onboarding on error to prevent getting stuck
- useOnboardingStore.setState({
- showOnboarding: false,
- initialized: true,
- });
- }
-};
-
-// Custom hook that combines store with initialization logic
-export const useOnboarding = () => {
- const { showOnboarding, setShowOnboarding, initialized } = useOnboardingStore();
- const { settings } = useSettings();
+ if (result.status === "ok") {
+ set({ onboardingData: result.data, isLoading: false });
+ } else {
+ throw new Error(result.error);
+ }
+ } catch (error) {
+ console.error("Error loading onboarding status:", error);
+ set({
+ error: error instanceof Error ? error.message : "Failed to load onboarding status",
+ isLoading: false
+ });
+ }
+ },
- useEffect(() => {
- // Initialize immediately when hook is first called, don't wait for settings
- if (!initialized) {
- // Start initialization immediately
- initializeOnboarding();
+ completeOnboarding: async () => {
+ try {
+ set({ isLoading: true, error: null });
+ const result = await commands.completeOnboarding();
- // Also set a shorter fallback timeout for better UX
- const fallbackTimeout = setTimeout(() => {
- console.warn("Fallback initialization triggered after 2 seconds");
- useOnboardingStore.setState({
- showOnboarding: false,
- initialized: true,
- });
- }, 2000);
+ if (result.status === "ok") {
+ // Update local state
+ set(state => ({
+ onboardingData: {
+ ...state.onboardingData,
+ isCompleted: true,
+ completedAt: new Date().toISOString(),
+ },
+ isLoading: false
+ }));
+ } else {
+ throw new Error(result.error);
+ }
+ } catch (error) {
+ console.error("Error completing onboarding:", error);
+ set({
+ error: error instanceof Error ? error.message : "Failed to complete onboarding",
+ isLoading: false
+ });
+ throw error;
+ }
+ },
- return () => clearTimeout(fallbackTimeout);
+ resetOnboarding: async () => {
+ try {
+ set({ isLoading: true, error: null });
+ const result = await commands.resetOnboarding();
+
+ if (result.status === "ok") {
+ // Update local state
+ set(state => ({
+ onboardingData: {
+ ...state.onboardingData,
+ isCompleted: false,
+ completedAt: null,
+ },
+ isLoading: false
+ }));
+ } else {
+ throw new Error(result.error);
+ }
+ } catch (error) {
+ console.error("Error resetting onboarding:", error);
+ set({
+ error: error instanceof Error ? error.message : "Failed to reset onboarding",
+ isLoading: false
+ });
+ throw error;
}
- }, [initialized]);
+ },
+}));
- return {
- showOnboarding,
- setShowOnboarding,
- initialized
- };
+// Hook to automatically load onboarding status on mount
+export const useOnboardingWithLoader = () => {
+ const store = useOnboarding();
+
+ useEffect(() => {
+ store.loadOnboardingStatus();
+ }, []);
+
+ return store;
};
-
-// No longer need the OnboardingProvider component
diff --git a/openrewind/lib/hooks/use-profiles.tsx b/openrewind/lib/hooks/use-profiles.tsx
deleted file mode 100644
index 524ff64ec..000000000
--- a/openrewind/lib/hooks/use-profiles.tsx
+++ /dev/null
@@ -1,236 +0,0 @@
-import { Action, action, persist } from "easy-peasy";
-import { LazyStore } from "@tauri-apps/plugin-store";
-import { localDataDir } from "@tauri-apps/api/path";
-import { flattenObject, FlattenObjectKeys, unflattenObject } from "../utils";
-import { createContextStore } from "easy-peasy";
-import { createDefaultSettingsObject, Settings } from "./use-settings";
-import { remove } from "@tauri-apps/plugin-fs";
-export interface ProfilesModel {
- activeProfile: string;
- profiles: string[];
- shortcuts: {
- [profileName: string]: string;
- };
- setActiveProfile: Action<ProfilesModel, string>;
- createProfile: Action<
- ProfilesModel,
- {
- profileName: string;
- currentSettings: Settings;
- }
- >;
- deleteProfile: Action<ProfilesModel, string>;
- updateShortcut: Action<ProfilesModel, { profile: string; shortcut: string }>;
-}
-
-let profilesStorePromise: Promise<LazyStore> | null = null;
-
-/**
- * @warning Do not change autoSave to true, it causes race conditions
- */
-const getProfilesStore = async () => {
- if (!profilesStorePromise) {
- profilesStorePromise = (async () => {
- const dir = await localDataDir();
- console.log(dir, "dir");
- return new LazyStore(`${dir}/screenpipe/profiles.bin`, {
- autoSave: false,
- });
- })();
- }
- return profilesStorePromise;
-};
-
-const profilesStorage = {
- getItem: async (_key: string) => {
- await new Promise((resolve) => setTimeout(resolve, 2000));
- const tauriStore = await getProfilesStore();
- const allKeys = await tauriStore.keys();
- const values: Record<string, any> = {};
-
- for (const k of allKeys) {
- values[k] = await tauriStore.get(k);
- }
-
- return unflattenObject(values);
- },
-
- setItem: async (_key: string, value: any) => {
- const tauriStore = await getProfilesStore();
- const flattenedValue = flattenObject(value);
-
- const existingKeys = await tauriStore.keys();
- for (const key of existingKeys) {
- await tauriStore.delete(key);
- }
-
- for (const [key, val] of Object.entries(flattenedValue)) {
- await tauriStore.set(key, val);
- }
-
- await tauriStore.save();
- },
- removeItem: async (_key: string) => {
- const tauriStore = await getProfilesStore();
- const keys = await tauriStore.keys();
- for (const key of keys) {
- await tauriStore.delete(key);
- }
- await tauriStore.save();
- },
-};
-
-const copyProfileSettings = async (
- profileName: string,
- currentSettings: Settings
-) => {
- try {
- const dir = await localDataDir();
- const fileName = `store-${profileName}.bin`;
-
- console.log(`copying profile settings to ${fileName}`);
-
- const store = new LazyStore(`${dir}/screenpipe/${fileName}`, {
- autoSave: false,
- });
-
- // Start with default settings
- const defaultSettings = createDefaultSettingsObject();
- const flattenedDefaults = flattenObject(defaultSettings);
-
- // Define keys to copy from current settings
- const keysToCopy: FlattenObjectKeys<Settings>[] = [
- // Account related
- "user.token",
- "user.id",
- "user.email",
- "user.name",
- "user.image",
- "user.clerk_id",
- "user.credits.amount",
-
- // AI related
- "aiProviderType",
- "aiUrl",
- "aiModel",
- "aiMaxContextChars",
- "openaiApiKey",
-
- // Shortcuts
- "showScreenpipeShortcut",
- "startRecordingShortcut",
- "stopRecordingShortcut",
- "disabledShortcuts",
- ] as const;
-
- // Copy specific keys from current settings
- const flattenedCurrentSettings = flattenObject(currentSettings);
- for (const key of keysToCopy) {
- const value = flattenedCurrentSettings[key];
- if (value !== undefined) {
- await store.set(key, value);
- }
- }
-
- // Set all other keys to defaults
- for (const [key, value] of Object.entries(flattenedDefaults)) {
- if (!keysToCopy.includes(key as FlattenObjectKeys<Settings>)) {
- await store.set(key, value);
- }
- }
-
- await store.save();
- console.log(`successfully copied profile settings to ${fileName}`);
- } catch (err) {
- console.error(`failed to copy profile settings: ${err}`);
- throw new Error(`failed to copy profile settings: ${err}`);
- }
-};
-
-const deleteProfileFile = async (profile: string) => {
- try {
- const dir = await localDataDir();
- const file = profile === "default" ? "store.bin" : `store-${profile}.bin`;
- await remove(`${dir}/screenpipe/${file}`);
- } catch (err) {
- console.error(`failed to delete profile file: ${err}`);
- throw new Error(`failed to delete profile file: ${err}`);
- }
-};
-
-export const profilesStore = createContextStore<ProfilesModel>(
- persist(
- {
- activeProfile: "default",
- profiles: ["default"],
- shortcuts: {},
- setActiveProfile: action((state, payload) => {
- state.activeProfile = payload;
- }),
- updateShortcut: action((state, { profile, shortcut }) => {
- if (shortcut === '') {
- delete state.shortcuts[profile];
- } else {
- state.shortcuts[profile] = shortcut;
- }
- }),
- createProfile: action((state, payload) => {
- state.profiles.push(payload.profileName);
- copyProfileSettings(payload.profileName, payload.currentSettings).catch(
- (err) =>
- console.error(
- `failed to create profile ${payload.profileName}: ${err}`
- )
- );
- }),
- deleteProfile: action((state, payload) => {
- if (payload === "default") {
- console.error("cannot delete default profile");
- return;
- }
- state.profiles = state.profiles.filter(
- (profile) => profile !== payload
- );
- deleteProfileFile(payload).catch((err) =>
- console.error(`failed to delete profile ${payload}: ${err}`)
- );
- }),
- },
- {
- storage: profilesStorage,
- }
- )
-);
-
-export const useProfiles = () => {
- const { profiles, activeProfile, shortcuts } = profilesStore.useStoreState(
- (state) => ({
- activeProfile: state.activeProfile,
- profiles: state.profiles,
- shortcuts: state.shortcuts,
- })
- );
-
- const setActiveProfile = profilesStore.useStoreActions(
- (actions) => actions.setActiveProfile
- );
- const createProfile = profilesStore.useStoreActions(
- (actions) => actions.createProfile
- );
- const deleteProfile = profilesStore.useStoreActions(
- (actions) => actions.deleteProfile
- );
- const updateShortcut = profilesStore.useStoreActions(
- (actions) => actions.updateShortcut
- );
-
- return {
- profiles,
- activeProfile,
- profileShortcuts: shortcuts,
- setActiveProfile,
- createProfile,
- deleteProfile,
- updateProfileShortcut: updateShortcut,
- };
-};
diff --git a/openrewind/lib/hooks/use-settings-dialog.ts b/openrewind/lib/hooks/use-settings-dialog.ts
deleted file mode 100644
index 3fe4484eb..000000000
--- a/openrewind/lib/hooks/use-settings-dialog.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { create } from "zustand";
-
-interface SettingsDialogStore {
- isOpen: boolean;
- setIsOpen: (open: boolean) => void;
-}
-
-export const useSettingsDialog = create<SettingsDialogStore>((set) => ({
- isOpen: false,
- setIsOpen: (open) => set({ isOpen: open }),
-}));
diff --git a/openrewind/lib/hooks/use-settings.tsx b/openrewind/lib/hooks/use-settings.tsx
index 9cbd6d551..3701a9c67 100644
--- a/openrewind/lib/hooks/use-settings.tsx
+++ b/openrewind/lib/hooks/use-settings.tsx
@@ -1,21 +1,14 @@
import { homeDir } from "@tauri-apps/api/path";
import { platform } from "@tauri-apps/plugin-os";
-import { Pipe } from "./use-pipes";
-import { Language } from "@/lib/language";
-import {
- action,
- Action,
- persist,
- PersistStorage,
- createContextStore,
-} from "easy-peasy";
-import { LazyStore, LazyStore as TauriStore } from "@tauri-apps/plugin-store";
+import { Store } from "@tauri-apps/plugin-store";
import { localDataDir } from "@tauri-apps/api/path";
-import { flattenObject, unflattenObject } from "../utils";
-import { useEffect, useState } from "react";
+import React, { createContext, useContext, useEffect, useState } from "react";
import posthog from "posthog-js";
import localforage from "localforage";
-
+import { User } from "../utils/tauri";
+import { Pipe } from "./use-pipes";
+import { Language } from "@/lib/language";
+import { SettingsStore } from "../utils/tauri";
export type VadSensitivity = "low" | "medium" | "high";
export type AIProviderType =
@@ -37,26 +30,6 @@ export enum Shortcut {
STOP_RECORDING = "stop_recording",
}
-export type User = {
- id?: string;
- email?: string;
- name?: string;
- image?: string;
- token?: string;
- clerk_id?: string;
- api_key?: string;
- credits?: {
- amount: number;
- };
- stripe_connected?: boolean;
- stripe_account_status?: "active" | "pending";
- github_username?: string;
- bio?: string;
- website?: string;
- contact?: string;
- cloud_subscribed?: boolean;
-};
-
export type AIPreset = {
id: string;
maxContextChars: number;
@@ -64,7 +37,6 @@ export type AIPreset = {
model: string;
defaultPreset: boolean;
prompt: string;
- //provider: AIProviderType;
} & (
| {
provider: "openai";
@@ -82,57 +54,7 @@ export type AIPreset = {
}
);
-export type Settings = {
- openaiApiKey: string;
- deepgramApiKey: string;
- isLoading: boolean;
- aiModel: string;
- installedPipes: Pipe[];
- userId: string;
- customPrompt: string;
- devMode: boolean;
- audioTranscriptionEngine: string;
- ocrEngine: string;
- monitorIds: string[];
- audioDevices: string[];
- usePiiRemoval: boolean;
- restartInterval: number;
- port: number;
- dataDir: string;
- disableAudio: boolean;
- ignoredWindows: string[];
- includedWindows: string[];
- aiProviderType: AIProviderType;
- aiUrl: string;
- aiMaxContextChars: number;
- fps: number;
- vadSensitivity: VadSensitivity;
- analyticsEnabled: boolean;
- audioChunkDuration: number; // new field
- useChineseMirror: boolean; // Add this line
- embeddedLLM: EmbeddedLLMConfig;
- languages: Language[];
- enableBeta: boolean;
- isFirstTimeUser: boolean;
- autoStartEnabled: boolean;
- enableFrameCache: boolean; // Add this line
- enableUiMonitoring: boolean; // Add this line
- platform: string; // Add this line
- disabledShortcuts: Shortcut[];
- user: User;
- showScreenpipeShortcut: string;
- startRecordingShortcut: string;
- stopRecordingShortcut: string;
- startAudioShortcut: string;
- stopAudioShortcut: string;
- pipeShortcuts: Record<string, string>;
- enableRealtimeAudioTranscription: boolean;
- realtimeAudioTranscriptionEngine: string;
- disableVision: boolean;
- useAllMonitors: boolean;
- aiPresets: AIPreset[];
- enableRealtimeVision: boolean;
-};
+export type Settings = SettingsStore
export const DEFAULT_PROMPT = `Rules:
- You can analyze/view/show/access videos to the user by putting .mp4 files in a code block (we'll render it) like this: \`/users/video.mp4\`, use the exact, absolute, file path from file_path property
@@ -141,67 +63,6 @@ export const DEFAULT_PROMPT = `Rules:
- Always answer my question/intent, do not make up things
`;
-const DEFAULT_SETTINGS: Settings = {
- aiPresets: [],
- openaiApiKey: "",
- deepgramApiKey: "", // for now we hardcode our key (dw about using it, we have bunch of credits)
- isLoading: false,
- aiModel: "gpt-4o",
- installedPipes: [],
- userId: "",
- customPrompt: `Rules:
-- You can analyze/view/show/access videos to the user by putting .mp4 files in a code block (we'll render it) like this: \`/users/video.mp4\`, use the exact, absolute, file path from file_path property
-- Do not try to embed video in links (e.g. [](.mp4) or https://.mp4) instead put the file_path in a code block using backticks
-- Do not put video in multiline code block it will not render the video (e.g. \`\`\`bash\n.mp4\`\`\` IS WRONG) instead using inline code block with single backtick
-- Always answer my question/intent, do not make up things
-`,
- devMode: false,
- audioTranscriptionEngine: "whisper-large-v3-turbo",
- ocrEngine: "default",
- monitorIds: ["default"],
- audioDevices: ["default"],
- usePiiRemoval: false,
- restartInterval: 0,
- port: 3030,
- dataDir: "default",
- disableAudio: false,
- ignoredWindows: [],
- includedWindows: [],
- aiProviderType: "openai",
- aiUrl: "https://api.openai.com/v1",
- aiMaxContextChars: 512000,
- fps: 0.5,
- vadSensitivity: "high",
- analyticsEnabled: true,
- audioChunkDuration: 30, // default to 10 seconds
- useChineseMirror: false, // Add this line
- languages: [],
- embeddedLLM: {
- enabled: false,
- model: "llama3.2:1b-instruct-q4_K_M",
- port: 11434,
- },
- enableBeta: false,
- isFirstTimeUser: true,
- autoStartEnabled: true,
- enableFrameCache: true, // Add this line
- enableUiMonitoring: false, // Change from true to false
- platform: "unknown", // Add this line
- disabledShortcuts: [],
- user: {},
- showScreenpipeShortcut: "Super+Alt+S",
- startRecordingShortcut: "Super+Alt+U", // Super+Alt+R is used on windows by Xbox Game Bar
- stopRecordingShortcut: "Super+Alt+X",
- startAudioShortcut: "",
- stopAudioShortcut: "",
- pipeShortcuts: {},
- enableRealtimeAudioTranscription: false,
- realtimeAudioTranscriptionEngine: "deepgram",
- disableVision: false,
- useAllMonitors: false,
- enableRealtimeVision: true,
-};
-
const DEFAULT_IGNORED_WINDOWS_IN_ALL_OS = [
"bit",
"VPN",
@@ -235,313 +96,230 @@ const DEFAULT_IGNORED_WINDOWS_PER_OS: Record<string, string[]> = {
linux: ["Info center", "Discover", "Parted"],
};
-// Model definition
-export interface StoreModel {
- settings: Settings;
- setSettings: Action<StoreModel, Partial<Settings>>;
- resetSettings: Action<StoreModel>;
- resetSetting: Action<StoreModel, keyof Settings>;
-}
-
-// Validate and sanitize settings to prevent corruption
-function validateSettings(settings: any): Settings {
- const defaultSettings = createDefaultSettingsObject();
-
- // Ensure all required fields exist with proper types
- const validatedSettings: Settings = {
- ...defaultSettings,
- ...settings,
- };
-
- // Validate specific fields that are critical
- if (!Array.isArray(validatedSettings.monitorIds)) {
- validatedSettings.monitorIds = defaultSettings.monitorIds;
- }
-
- if (!Array.isArray(validatedSettings.audioDevices)) {
- validatedSettings.audioDevices = defaultSettings.audioDevices;
- }
-
- if (!Array.isArray(validatedSettings.ignoredWindows)) {
- validatedSettings.ignoredWindows = defaultSettings.ignoredWindows;
- }
-
- if (!Array.isArray(validatedSettings.includedWindows)) {
- validatedSettings.includedWindows = defaultSettings.includedWindows;
- }
-
- if (!Array.isArray(validatedSettings.aiPresets)) {
- validatedSettings.aiPresets = defaultSettings.aiPresets;
- }
-
- // Validate numeric fields
- if (typeof validatedSettings.fps !== 'number' || validatedSettings.fps < 0) {
- validatedSettings.fps = defaultSettings.fps;
- }
-
- if (typeof validatedSettings.port !== 'number' || validatedSettings.port < 1000) {
- validatedSettings.port = defaultSettings.port;
- }
-
- return validatedSettings;
-}
+let DEFAULT_SETTINGS: Settings = {
+ aiPresets: [],
+ deepgramApiKey: "",
+ isLoading: false,
+ installedPipes: [],
+ userId: "",
+ devMode: false,
+ audioTranscriptionEngine: "whisper-large-v3-turbo",
+ ocrEngine: "default",
+ monitorIds: ["default"],
+ audioDevices: ["default"],
+ usePiiRemoval: false,
+ restartInterval: 0,
+ port: 3030,
+ dataDir: "default",
+ disableAudio: false,
+ ignoredWindows: [
+ ],
+ includedWindows: [],
+
+ fps: 0.5,
+ vadSensitivity: "high",
+ analyticsEnabled: true,
+ audioChunkDuration: 30,
+ useChineseMirror: false,
+ languages: [],
+ embeddedLLM: {
+ enabled: false,
+ model: "llama3.2:1b-instruct-q4_K_M",
+ port: 11434,
+ },
+ enableBeta: false,
+ isFirstTimeUser: true,
+ autoStartEnabled: true,
+ enableFrameCache: true,
+ enableUiMonitoring: false,
+ platform: "unknown",
+ disabledShortcuts: [],
+ user: {
+ id: null,
+ name: null,
+ email: null,
+ image: null,
+ token: null,
+ clerk_id: null,
+ api_key: null,
+ credits: null,
+ stripe_connected: null,
+ stripe_account_status: null,
+ github_username: null,
+ bio: null,
+ website: null,
+ contact: null,
+ cloud_subscribed: null
+ },
+ showScreenpipeShortcut: "Super+Alt+S",
+ startRecordingShortcut: "Super+Alt+U",
+ stopRecordingShortcut: "Super+Alt+X",
+ startAudioShortcut: "",
+ stopAudioShortcut: "",
+ pipeShortcuts: {},
+ enableRealtimeAudioTranscription: false,
+ realtimeAudioTranscriptionEngine: "deepgram",
+ disableVision: false,
+ useAllMonitors: false,
+ enableRealtimeVision: true,
+ };;
export function createDefaultSettingsObject(): Settings {
- let defaultSettings = { ...DEFAULT_SETTINGS };
try {
- const currentPlatform = platform();
-
- const ocrModel =
- currentPlatform === "macos"
- ? "apple-native"
- : currentPlatform === "windows"
- ? "windows-native"
- : "tesseract";
-
- defaultSettings.ocrEngine = ocrModel;
- defaultSettings.fps = currentPlatform === "macos" ? 0.5 : 1;
- defaultSettings.platform = currentPlatform;
-
- defaultSettings.ignoredWindows = [
- ...DEFAULT_IGNORED_WINDOWS_IN_ALL_OS,
- ...(DEFAULT_IGNORED_WINDOWS_PER_OS[currentPlatform] ?? []),
- ];
+ const p = platform();
+ DEFAULT_SETTINGS.platform = p;
+ DEFAULT_SETTINGS.disabledShortcuts = DEFAULT_IGNORED_WINDOWS_IN_ALL_OS;
+ DEFAULT_SETTINGS.disabledShortcuts.push(...(DEFAULT_IGNORED_WINDOWS_PER_OS[p] ?? []));
+ DEFAULT_SETTINGS.ocrEngine = p === "macos" ? "apple-native" : p === "windows" ? "windows-native" : "tesseract";
+ DEFAULT_SETTINGS.fps = p === "macos" ? 0.5 : 1;
- return defaultSettings;
+ return DEFAULT_SETTINGS;
} catch (e) {
+ // Fallback if platform detection fails
return DEFAULT_SETTINGS;
}
}
-// Create a singleton store instance
-let storePromise: Promise<LazyStore> | null = null;
-
-// Debounce mechanism for saving settings
-let saveTimeout: NodeJS.Timeout | null = null;
-const SAVE_DEBOUNCE_MS = 500;
-
-// Track if settings have been loaded from storage at least once
-let hasLoadedFromStorage = false;
-
-// Helper function to check if settings are ready to use
-export const areSettingsReady = () => hasLoadedFromStorage;
+// Store singleton
+let _store: Promise<Store> | undefined;
-/**
- * @warning Do not change autoSave to true, it causes race conditions
- */
export const getStore = async () => {
- if (!storePromise) {
- storePromise = (async () => {
- const dir = await localDataDir();
- const profilesStore = new TauriStore(`${dir}/openrewind/profiles.bin`, {
- autoSave: false,
- });
- const activeProfile =
- (await profilesStore.get("activeProfile")) || "default";
- const file =
- activeProfile === "default"
- ? `store.bin`
- : `store-${activeProfile}.bin`;
- console.log("activeProfile", activeProfile, file);
- return new TauriStore(`${dir}/openrewind/${file}`, {
- autoSave: false,
- });
- })();
+ if (!_store) {
+ const dir = await localDataDir();
+ _store = Store.load(`${dir}/openrewind/store.bin`, {
+ autoSave: false,
+ });
}
- return storePromise;
+ return _store;
};
-const tauriStorage: PersistStorage = {
- getItem: async (_key: string) => {
- try {
- const tauriStore = await getStore();
- const allKeys = await tauriStore.keys();
- const values: Record<string, any> = {};
-
- for (const k of allKeys) {
- try {
- values[k] = await tauriStore.get(k);
- } catch (error) {
- console.warn(`Failed to get key ${k}:`, error);
- // Continue with other keys if one fails
- }
- }
+// Store utilities similar to Cap's implementation
+function createSettingsStore() {
+ const get = async (): Promise<Settings> => {
+ const store = await getStore();
+ const settings = await store.get<Settings>("settings");
+ return settings || createDefaultSettingsObject();
+ };
- const settings = unflattenObject(values);
-
- // Validate and sanitize the loaded settings
- const validatedSettings = validateSettings(settings);
-
- // Mark that we've successfully loaded from storage
- hasLoadedFromStorage = true;
-
- return { settings: validatedSettings };
- } catch (error) {
- console.error("Failed to load settings, using defaults:", error);
- // Return default settings if loading fails completely
- return { settings: createDefaultSettingsObject() };
- }
- },
- setItem: async (_key: string, value: any) => {
- const tauriStore = await getStore();
+ const set = async (value: Partial<Settings>) => {
+ const store = await getStore();
+ const current = await get();
+ const newSettings = { ...current, ...value };
+ await store.set("settings", newSettings);
+ await store.save();
+ };
- try {
- delete value.settings.customSettings;
-
- // Validate settings before saving
- const validatedSettings = validateSettings(value.settings);
- const flattenedValue = flattenObject(validatedSettings);
-
- // Get existing keys to know what to clean up
- const existingKeys = await tauriStore.keys();
-
- // Set new flattened values first
- for (const [key, val] of Object.entries(flattenedValue)) {
- if (!key || !key.length) continue;
- const defaultValue =
- key in DEFAULT_SETTINGS ? DEFAULT_SETTINGS[key as keyof Settings] : "";
- await tauriStore.set(key, val === undefined ? defaultValue : val);
- }
+ const reset = async () => {
+ const store = await getStore();
+ await store.set("settings", createDefaultSettingsObject());
+ await store.save();
+ };
- // Only delete keys that are no longer in the new settings
- const newKeys = Object.keys(flattenedValue);
- for (const existingKey of existingKeys) {
- if (!newKeys.includes(existingKey)) {
- await tauriStore.delete(existingKey);
- }
- }
+ const resetSetting = async <K extends keyof Settings>(key: K) => {
+ const current = await get();
+ const defaultValue = createDefaultSettingsObject()[key];
+ await set({ [key]: defaultValue } as Partial<Settings>);
+ };
- // Debounce the save operation to prevent race conditions
- if (saveTimeout) {
- clearTimeout(saveTimeout);
- }
-
- saveTimeout = setTimeout(async () => {
- try {
- await tauriStore.save();
- } catch (error) {
- console.error("Failed to save store:", error);
- }
- }, SAVE_DEBOUNCE_MS);
- } catch (error) {
- console.error("Failed to save settings:", error);
- // Don't throw to prevent breaking the app, but log the error
- }
- },
- removeItem: async (_key: string) => {
- const tauriStore = await getStore();
- const keys = await tauriStore.keys();
- for (const key of keys) {
- await tauriStore.delete(key);
- }
- await tauriStore.save();
- },
-};
+ const listen = (callback: (settings: Settings) => void) => {
+ return getStore().then((store) => {
+ return store.onKeyChange("settings", (newValue: Settings | null | undefined) => {
+ callback(newValue || createDefaultSettingsObject());
+ });
+ });
+ };
-export const store = createContextStore<StoreModel>(
- persist(
- {
- settings: createDefaultSettingsObject(),
- setSettings: action((state, payload) => {
- console.log(state, payload);
- state.settings = {
- ...state.settings,
- ...payload,
- };
- }),
- resetSettings: action((state) => {
- state.settings = createDefaultSettingsObject();
- }),
- resetSetting: action((state, key) => {
- const defaultValue = createDefaultSettingsObject()[key];
- (state.settings as any)[key] = defaultValue;
- }),
- },
- {
- storage: tauriStorage,
- mergeStrategy: "mergeDeep",
- },
- ),
-);
+ return {
+ get,
+ set,
+ reset,
+ resetSetting,
+ listen,
+ };
+}
-export function useSettings() {
- const settings = store.useStoreState((state) => state.settings);
- const setSettings = store.useStoreActions((actions) => actions.setSettings);
- const resetSettings = store.useStoreActions(
- (actions) => actions.resetSettings,
- );
- const resetSetting = store.useStoreActions((actions) => actions.resetSetting);
+const settingsStore = createSettingsStore();
- // Track if settings have been loaded from storage
+// Context for React
+interface SettingsContextType {
+ settings: Settings;
+ updateSettings: (updates: Partial<Settings>) => Promise<void>;
+ resetSettings: () => Promise<void>;
+ resetSetting: <K extends keyof Settings>(key: K) => Promise<void>;
+ reloadStore: () => Promise<void>;
+ loadUser: (token: string, forceReload?: boolean) => Promise<void>;
+ getDataDir: () => Promise<string>;
+ isSettingsLoaded: boolean;
+ loadingError: string | null;
+}
+
+const SettingsContext = createContext<SettingsContextType | undefined>(undefined);
+
+export const SettingsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const [settings, setSettings] = useState<Settings>(createDefaultSettingsObject());
const [isSettingsLoaded, setIsSettingsLoaded] = useState(false);
const [loadingError, setLoadingError] = useState<string | null>(null);
- // Initialize settings loading on mount
+ // Load settings on mount
useEffect(() => {
- const initializeSettings = async () => {
+ const loadSettings = async () => {
try {
- // Add timeout to prevent hanging
- const timeoutPromise = new Promise((_, reject) => {
- setTimeout(() => reject(new Error("Settings loading timeout")), 5000);
- });
-
- const loadPromise = (async () => {
- // Force a reload from storage to ensure we have the latest settings
- const store = await getStore();
- const allKeys = await store.keys();
-
- if (allKeys.length > 0) {
- // Settings exist in storage, load them
- const values: Record<string, any> = {};
- for (const k of allKeys) {
- try {
- values[k] = await store.get(k);
- } catch (error) {
- console.warn(`Failed to get key ${k}:`, error);
- }
- }
-
- const loadedSettings = unflattenObject(values);
- const validatedSettings = validateSettings(loadedSettings);
-
- // Only update if the loaded settings are different from current
- if (JSON.stringify(validatedSettings) !== JSON.stringify(settings)) {
- setSettings(validatedSettings);
- }
- } else {
- console.log("No existing settings found, using defaults");
- }
- })();
-
- await Promise.race([loadPromise, timeoutPromise]);
-
+ const loadedSettings = await settingsStore.get();
+ setSettings(loadedSettings);
setIsSettingsLoaded(true);
setLoadingError(null);
} catch (error) {
- console.error("Failed to initialize settings:", error);
+ console.error("Failed to load settings:", error);
setLoadingError(error instanceof Error ? error.message : "Unknown error");
- setIsSettingsLoaded(true); // Still mark as loaded to prevent infinite loading
+ setIsSettingsLoaded(true);
}
};
- // Only initialize if not already loaded
- if (!isSettingsLoaded) {
- initializeSettings();
- }
- }, [isSettingsLoaded, setSettings]);
+ loadSettings();
+
+ // Listen for changes
+ const unsubscribe = settingsStore.listen((newSettings) => {
+ setSettings(newSettings);
+ });
+
+ return () => {
+ unsubscribe.then((unsub) => unsub());
+ };
+ }, []);
+ // Track user changes for posthog
useEffect(() => {
- if (settings.user?.id) {
- posthog.identify(settings.user?.id, {
- email: settings.user?.email,
- name: settings.user?.name,
- github_username: settings.user?.github_username,
- website: settings.user?.website,
- contact: settings.user?.contact,
+ if (settings.user && settings.user.id) {
+ posthog.identify(settings.user.id, {
+ email: settings.user.email,
+ name: settings.user.name,
+ github_username: settings.user.github_username,
+ website: settings.user.website,
+ contact: settings.user.contact,
});
}
}, [settings.user?.id]);
+ const updateSettings = async (updates: Partial<Settings>) => {
+ await settingsStore.set(updates);
+ // Settings will be updated via the listener
+ };
+
+ const resetSettings = async () => {
+ await settingsStore.reset();
+ // Settings will be updated via the listener
+ };
+
+ const resetSetting = async <K extends keyof Settings>(key: K) => {
+ await settingsStore.resetSetting(key);
+ // Settings will be updated via the listener
+ };
+
+ const reloadStore = async () => {
+ const freshSettings = await settingsStore.get();
+ setSettings(freshSettings);
+ };
+
const getDataDir = async () => {
const homeDirPath = await homeDir();
@@ -552,14 +330,7 @@ export function useSettings() {
)
return settings.dataDir;
- let p = "macos";
- try {
- p = platform();
- } catch (e) {}
-
- return p === "macos" || p === "linux"
- ? `${homeDirPath}/.screenpipe`
- : `${homeDirPath}\\.screenpipe`;
+ return `${homeDirPath}/.openrewind`;
};
const loadUser = async (token: string, forceReload = false) => {
@@ -574,9 +345,7 @@ export function useSettings() {
// use cache if less than 30s old
if (cached && Date.now() - cached.timestamp < 30000) {
- setSettings({
- user: cached.data,
- });
+ await updateSettings({ user: cached.data });
return;
}
}
@@ -596,6 +365,7 @@ export function useSettings() {
const data = await response.json();
const userData = {
...data.user,
+ token
} as User;
// if user was not logged in, send posthog event app_login with email
@@ -611,38 +381,36 @@ export function useSettings() {
timestamp: Date.now(),
});
- setSettings({
- user: userData,
- });
+ await updateSettings({ user: userData });
} catch (err) {
console.error("failed to load user:", err);
throw err;
}
};
- const reloadStore = async () => {
- const store = await getStore();
- await store.reload();
-
- const allKeys = await store.keys();
- const values: Record<string, any> = {};
-
- for (const k of allKeys) {
- values[k] = await store.get(k);
- }
-
- setSettings(unflattenObject(values));
- };
-
- return {
+ const value: SettingsContextType = {
settings,
- updateSettings: setSettings,
+ updateSettings,
resetSettings,
+ resetSetting,
reloadStore,
loadUser,
- resetSetting,
getDataDir,
isSettingsLoaded,
loadingError,
};
+
+ return (
+ <SettingsContext.Provider value={value}>
+ {children}
+ </SettingsContext.Provider>
+ );
+};
+
+export function useSettings(): SettingsContextType {
+ const context = useContext(SettingsContext);
+ if (context === undefined) {
+ throw new Error("useSettings must be used within a SettingsProvider");
+ }
+ return context;
}
diff --git a/openrewind/lib/shortcuts.ts b/openrewind/lib/shortcuts.ts
index 17434ab7d..734fc5e92 100644
--- a/openrewind/lib/shortcuts.ts
+++ b/openrewind/lib/shortcuts.ts
@@ -1,4 +1,4 @@
-import { invoke } from "@tauri-apps/api/core";
+import { commands } from "./utils/tauri";
import { Shortcut } from "./hooks/use-settings";
export async function registerShortcuts({
@@ -8,8 +8,8 @@ export async function registerShortcuts({
showScreenpipeShortcut: string;
disabledShortcuts: Shortcut[];
}) {
- invoke("update_show_screenpipe_shortcut", {
- new_shortcut: showScreenpipeShortcut,
- enabled: !disabledShortcuts.includes(Shortcut.SHOW_SCREENPIPE),
- });
+ commands.updateShowScreenpipeShortcut(
+ showScreenpipeShortcut,
+ !disabledShortcuts.includes(Shortcut.SHOW_SCREENPIPE)
+ );
}
diff --git a/openrewind/lib/utils/tauri.ts b/openrewind/lib/utils/tauri.ts
new file mode 100644
index 000000000..e18d23e83
--- /dev/null
+++ b/openrewind/lib/utils/tauri.ts
@@ -0,0 +1,239 @@
+
+// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
+
+/** user-defined commands **/
+
+
+export const commands = {
+async openPermissionSettings(permission: OSPermission) : Promise<void> {
+ await TAURI_INVOKE("open_permission_settings", { permission });
+},
+async requestPermission(permission: OSPermission) : Promise<void> {
+ await TAURI_INVOKE("request_permission", { permission });
+},
+async doPermissionsCheck(initialCheck: boolean) : Promise<OSPermissionsCheck> {
+ return await TAURI_INVOKE("do_permissions_check", { initialCheck });
+},
+async getEnv(name: string) : Promise<string> {
+ return await TAURI_INVOKE("get_env", { name });
+},
+async getLogFiles() : Promise<Result<LogFile[], string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("get_log_files") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async getMediaFile(filePath: string) : Promise<Result<JsonValue, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("get_media_file", { filePath }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async uploadFileToS3(filePath: string, signedUrl: string) : Promise<Result<boolean, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("upload_file_to_s3", { filePath, signedUrl }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async updateGlobalShortcuts(showShortcut: string, startShortcut: string, stopShortcut: string, startAudioShortcut: string, stopAudioShortcut: string, profileShortcuts: { [key in string]: string }) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("update_global_shortcuts", { showShortcut, startShortcut, stopShortcut, startAudioShortcut, stopAudioShortcut, profileShortcuts }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async spawnScreenpipe(overrideArgs: string[] | null) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("spawn_screenpipe", { overrideArgs }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async stopScreenpipe() : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("stop_screenpipe") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async getDiskUsage() : Promise<Result<JsonValue, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("get_disk_usage") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async openPipeWindow(port: number, title: string) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("open_pipe_window", { port, title }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async updateShowScreenpipeShortcut(newShortcut: string, enabled: boolean) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("update_show_screenpipe_shortcut", { newShortcut, enabled }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async showWindow(window: ShowRewindWindow) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("show_window", { window }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async closeWindow(window: ShowRewindWindow) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("close_window", { window }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async setWindowSize(window: ShowRewindWindow, width: number, height: number) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("set_window_size", { window, width, height }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async getOnboardingStatus() : Promise<Result<OnboardingStore, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("get_onboarding_status") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async completeOnboarding() : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("complete_onboarding") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async resetOnboarding() : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("reset_onboarding") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async showOnboardingWindow() : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("show_onboarding_window") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async setTrayUnhealthIcon() : Promise<void> {
+ await TAURI_INVOKE("set_tray_unhealth_icon");
+},
+async setTrayHealthIcon() : Promise<void> {
+ await TAURI_INVOKE("set_tray_health_icon");
+}
+}
+
+/** user-defined events **/
+
+
+
+/** user-defined constants **/
+
+
+
+/** user-defined types **/
+
+export type AIPreset = { id: string; prompt: string; provider: AIProviderType; url: string; model: string; defaultPreset: boolean; apiKey: string | null; maxContextChars: number }
+export type AIProviderType = "openai" | "native-ollama" | "custom" | "screenpipe-cloud"
+export type Credits = { amount: number }
+export type EmbeddedLLM = { enabled: boolean; model: string; port: number }
+export type JsonValue = null | boolean | number | string | JsonValue[] | { [key in string]: JsonValue }
+export type LogFile = { name: string; path: string; modified_at: bigint }
+export type OSPermission = "screenRecording" | "microphone" | "accessibility"
+export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
+export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; accessibility: OSPermissionStatus }
+export type OnboardingStore = { isCompleted: boolean; completedAt: string | null }
+export type Pipe = { id: string; name: string; description: string; version: string; author: string; authorLink: string; repository: string; lastUpdate: string; fullDescription: string; downloads: number; mainFile: string; config: { [key in string]: string } }
+export type SettingsStore = { aiPresets: AIPreset[]; deepgramApiKey: string; isLoading: boolean; installedPipes: Pipe[]; userId: string; devMode: boolean; audioTranscriptionEngine: string; ocrEngine: string; monitorIds: string[]; audioDevices: string[]; usePiiRemoval: boolean; restartInterval: number; port: number; dataDir: string; disableAudio: boolean; ignoredWindows: string[]; includedWindows: string[]; fps: number; vadSensitivity: string; analyticsEnabled: boolean; audioChunkDuration: number; useChineseMirror: boolean; languages: string[]; embeddedLLM: EmbeddedLLM; enableBeta: boolean; isFirstTimeUser: boolean; autoStartEnabled: boolean; enableFrameCache: boolean; enableUiMonitoring: boolean; platform: string; disabledShortcuts: string[]; user: User; showScreenpipeShortcut: string; startRecordingShortcut: string; stopRecordingShortcut: string; startAudioShortcut: string; stopAudioShortcut: string; pipeShortcuts: { [key in string]: string }; enableRealtimeAudioTranscription: boolean; realtimeAudioTranscriptionEngine: string; disableVision: boolean; useAllMonitors: boolean; enableRealtimeVision: boolean }
+export type ShowRewindWindow = "Main" | { Settings: { page: string | null } } | "Search" | "Onboarding"
+export type User = { id: string | null; name: string | null; email: string | null; image: string | null; token: string | null; clerk_id: string | null; api_key: string | null; credits: Credits | null; stripe_connected: boolean | null; stripe_account_status: string | null; github_username: string | null; bio: string | null; website: string | null; contact: string | null; cloud_subscribed: boolean | null }
+
+/** tauri-specta globals **/
+
+import {
+ invoke as TAURI_INVOKE,
+ Channel as TAURI_CHANNEL,
+} from "@tauri-apps/api/core";
+import * as TAURI_API_EVENT from "@tauri-apps/api/event";
+import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow";
+
+type __EventObj__<T> = {
+ listen: (
+ cb: TAURI_API_EVENT.EventCallback<T>,
+ ) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
+ once: (
+ cb: TAURI_API_EVENT.EventCallback<T>,
+ ) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
+ emit: null extends T
+ ? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
+ : (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
+};
+
+export type Result<T, E> =
+ | { status: "ok"; data: T }
+ | { status: "error"; error: E };
+
+function __makeEvents__<T extends Record<string, any>>(
+ mappings: Record<keyof T, string>,
+) {
+ return new Proxy(
+ {} as unknown as {
+ [K in keyof T]: __EventObj__<T[K]> & {
+ (handle: __WebviewWindow__): __EventObj__<T[K]>;
+ };
+ },
+ {
+ get: (_, event) => {
+ const name = mappings[event as keyof T];
+
+ return new Proxy((() => {}) as any, {
+ apply: (_, __, [window]: [__WebviewWindow__]) => ({
+ listen: (arg: any) => window.listen(name, arg),
+ once: (arg: any) => window.once(name, arg),
+ emit: (arg: any) => window.emit(name, arg),
+ }),
+ get: (_, command: keyof __EventObj__<any>) => {
+ switch (command) {
+ case "listen":
+ return (arg: any) => TAURI_API_EVENT.listen(name, arg);
+ case "once":
+ return (arg: any) => TAURI_API_EVENT.once(name, arg);
+ case "emit":
+ return (arg: any) => TAURI_API_EVENT.emit(name, arg);
+ }
+ },
+ });
+ },
+ },
+ );
+}
diff --git a/openrewind/lib/utils/validation.ts b/openrewind/lib/utils/validation.ts
new file mode 100644
index 000000000..c9ca6b92c
--- /dev/null
+++ b/openrewind/lib/utils/validation.ts
@@ -0,0 +1,317 @@
+import { z } from "zod";
+import { SettingsStore, AIPreset, AIProviderType, EmbeddedLLM, User, Credits } from "./tauri";
+
+// Zod schemas for validation
+export const creditsSchema = z.object({
+ amount: z.number().min(0, "Credits amount cannot be negative"),
+});
+
+export const embeddedLLMSchema = z.object({
+ enabled: z.boolean(),
+ model: z.string().min(1, "Model name is required"),
+ port: z.number().int().min(1024).max(65535, "Port must be between 1024-65535"),
+});
+
+export const userSchema = z.object({
+ id: z.string().nullable(),
+ name: z.string().nullable(),
+ email: z.string().email("Invalid email format").nullable(),
+ image: z.string().url("Invalid image URL").nullable(),
+ token: z.string().nullable(),
+ clerk_id: z.string().nullable(),
+ api_key: z.string().nullable(),
+ credits: creditsSchema.nullable(),
+ stripe_connected: z.boolean().nullable(),
+ stripe_account_status: z.string().nullable(),
+ github_username: z.string().nullable(),
+ bio: z.string().nullable(),
+ website: z.string().url("Invalid website URL").nullable(),
+ contact: z.string().nullable(),
+ cloud_subscribed: z.boolean().nullable(),
+});
+
+export const aiProviderTypeSchema = z.enum(["openai", "native-ollama", "custom", "screenpipe-cloud"]);
+
+export const aiPresetSchema = z.object({
+ id: z.string().min(1, "Preset name is required").regex(/^[a-zA-Z0-9\s\-_]+$/, "Only letters, numbers, spaces, hyphens, and underscores allowed").refine(
+ (val) => !val.trim().toLowerCase().endsWith("copy"),
+ "Preset name cannot end with 'copy'"
+ ),
+ prompt: z.string().min(10, "Prompt must be at least 10 characters"),
+ provider: aiProviderTypeSchema,
+ url: z.string().url("Invalid URL format"),
+ model: z.string().min(1, "Model is required"),
+ defaultPreset: z.boolean(),
+ apiKey: z.string().nullable(),
+ maxContextChars: z.number().int().min(1000, "Must be at least 1,000 characters").max(2000000, "Cannot exceed 2,000,000 characters"),
+});
+
+export const settingsStoreSchema = z.object({
+ // AI Settings
+ aiPresets: z.array(aiPresetSchema),
+ openaiApiKey: z.string(),
+ deepgramApiKey: z.string(),
+ aiModel: z.string().min(1, "AI model is required"),
+ customPrompt: z.string().min(10, "Custom prompt must be at least 10 characters"),
+ aiProviderType: aiProviderTypeSchema,
+ aiUrl: z.string().url("Invalid AI URL format"),
+ aiMaxContextChars: z.number().int().min(1000).max(2000000),
+
+ // Audio Settings
+ audioTranscriptionEngine: z.string().min(1, "Audio transcription engine is required"),
+ realtimeAudioTranscriptionEngine: z.string(),
+ enableRealtimeAudioTranscription: z.boolean(),
+ audioDevices: z.array(z.string()),
+ disableAudio: z.boolean(),
+ vadSensitivity: z.enum(["low", "medium", "high"]),
+ audioChunkDuration: z.number().int().min(5, "Must be at least 5 seconds").max(3600, "Cannot exceed 1 hour"),
+ languages: z.array(z.string()),
+
+ // Video Settings
+ ocrEngine: z.string().min(1, "OCR engine is required"),
+ monitorIds: z.array(z.string()),
+ ignoredWindows: z.array(z.string()),
+ includedWindows: z.array(z.string()),
+ disableVision: z.boolean(),
+ useAllMonitors: z.boolean(),
+ enableRealtimeVision: z.boolean(),
+ fps: z.number().min(0.1, "FPS must be at least 0.1").max(60, "FPS cannot exceed 60"),
+ enableFrameCache: z.boolean(),
+ enableUiMonitoring: z.boolean(),
+
+ // System Settings
+ dataDir: z.string().min(1, "Data directory is required"),
+ port: z.number().int().min(1024, "Port must be at least 1024").max(65535, "Port cannot exceed 65535"),
+ restartInterval: z.number().int().min(0, "Restart interval cannot be negative"),
+ analyticsEnabled: z.boolean(),
+ useChineseMirror: z.boolean(),
+ usePiiRemoval: z.boolean(),
+ devMode: z.boolean(),
+ enableBeta: z.boolean(),
+ isFirstTimeUser: z.boolean(),
+ autoStartEnabled: z.boolean(),
+ platform: z.string(),
+
+ // Shortcuts
+ disabledShortcuts: z.array(z.string()),
+ showScreenpipeShortcut: z.string(),
+ startRecordingShortcut: z.string(),
+ stopRecordingShortcut: z.string(),
+ startAudioShortcut: z.string(),
+ stopAudioShortcut: z.string(),
+ pipeShortcuts: z.record(z.string()),
+
+ // Other
+ isLoading: z.boolean(),
+ installedPipes: z.array(z.any()), // Define proper pipe schema if needed
+ userId: z.string(),
+ embeddedLLM: embeddedLLMSchema,
+ user: userSchema,
+});
+
+// Validation results
+export interface ValidationResult {
+ isValid: boolean;
+ errors: Record<string, string[]>;
+ warnings: Record<string, string[]>;
+}
+
+export interface FieldValidationResult {
+ isValid: boolean;
+ error?: string;
+ warning?: string;
+}
+
+// Field-specific validators
+export const validateField = (
+ field: keyof SettingsStore,
+ value: any
+): FieldValidationResult => {
+ try {
+ const fieldSchema = settingsStoreSchema.shape[field];
+ if (!fieldSchema) {
+ return { isValid: false, error: "Unknown field" };
+ }
+
+ fieldSchema.parse(value);
+ return { isValid: true };
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ return {
+ isValid: false,
+ error: error.errors[0]?.message || "Invalid value",
+ };
+ }
+ return { isValid: false, error: "Validation failed" };
+ }
+};
+
+// Validate entire settings object
+export const validateSettings = (settings: Partial<SettingsStore>): ValidationResult => {
+ const result: ValidationResult = {
+ isValid: true,
+ errors: {},
+ warnings: {},
+ };
+
+ for (const [field, value] of Object.entries(settings)) {
+ const fieldResult = validateField(field as keyof SettingsStore, value);
+ if (!fieldResult.isValid && fieldResult.error) {
+ result.isValid = false;
+ result.errors[field] = [fieldResult.error];
+ }
+ if (fieldResult.warning) {
+ result.warnings[field] = [fieldResult.warning];
+ }
+ }
+
+ return result;
+};
+
+// Sanitize input values
+export const sanitizeValue = (field: keyof SettingsStore, value: any): any => {
+ switch (field) {
+ case "port":
+ case "restartInterval":
+ case "audioChunkDuration":
+ return Math.max(0, parseInt(String(value)) || 0);
+
+ case "fps":
+ return Math.max(0.1, Math.min(60, parseFloat(String(value)) || 1));
+
+ case "dataDir":
+ return String(value).trim();
+
+ case "ignoredWindows":
+ case "includedWindows":
+ case "audioDevices":
+ case "monitorIds":
+ case "languages":
+ return Array.isArray(value) ? value.filter(Boolean) : [];
+
+ default:
+ return value;
+ }
+};
+
+// Performance optimization helpers
+export const debounce = <T extends (...args: any[]) => any>(
+ func: T,
+ wait: number
+): ((...args: Parameters<T>) => void) => {
+ let timeout: NodeJS.Timeout;
+ return (...args: Parameters<T>) => {
+ clearTimeout(timeout);
+ timeout = setTimeout(() => func(...args), wait);
+ };
+};
+
+export const throttle = <T extends (...args: any[]) => any>(
+ func: T,
+ limit: number
+): ((...args: Parameters<T>) => void) => {
+ let inThrottle: boolean;
+ return (...args: Parameters<T>) => {
+ if (!inThrottle) {
+ func(...args);
+ inThrottle = true;
+ setTimeout(() => (inThrottle = false), limit);
+ }
+ };
+};
+
+// UI feedback helpers
+export const getFieldVariant = (field: keyof SettingsStore, settings: any) => {
+ const validation = validateField(field, settings[field]);
+ if (!validation.isValid) return "destructive";
+ if (validation.warning) return "secondary";
+ return "default";
+};
+
+export const getFieldHelperText = (field: keyof SettingsStore, settings: any) => {
+ const validation = validateField(field, settings[field]);
+ return validation.error || validation.warning || "";
+};
+
+// Preset validation
+export const validatePresetName = (name: string, existingPresets: AIPreset[], currentId?: string): FieldValidationResult => {
+ if (!name.trim()) {
+ return { isValid: false, error: "Preset name is required" };
+ }
+
+ if (name.trim().toLowerCase().endsWith("copy")) {
+ return { isValid: false, error: "Preset name cannot end with 'copy'" };
+ }
+
+ const exists = existingPresets.some(
+ preset => preset.id.toLowerCase() === name.toLowerCase() && preset.id !== currentId
+ );
+
+ if (exists) {
+ return { isValid: false, error: "A preset with this name already exists" };
+ }
+
+ if (!/^[a-zA-Z0-9\s\-_]+$/.test(name)) {
+ return { isValid: false, error: "Only letters, numbers, spaces, hyphens, and underscores are allowed" };
+ }
+
+ return { isValid: true };
+};
+
+// URL validation
+export const validateUrl = (url: string): FieldValidationResult => {
+ if (!url.trim()) {
+ return { isValid: false, error: "URL is required" };
+ }
+
+ try {
+ new URL(url);
+ return { isValid: true };
+ } catch {
+ return { isValid: false, error: "Please enter a valid URL" };
+ }
+};
+
+// API key validation
+export const validateApiKey = (apiKey: string, provider: AIProviderType): FieldValidationResult => {
+ if (!apiKey.trim()) {
+ return { isValid: false, error: "API key is required" };
+ }
+
+ switch (provider) {
+ case "openai":
+ if (!apiKey.startsWith("sk-")) {
+ return { isValid: false, error: "OpenAI API keys should start with 'sk-'" };
+ }
+ break;
+ case "custom":
+ if (apiKey.length < 10) {
+ return { isValid: false, error: "API key seems too short" };
+ }
+ break;
+ }
+
+ return { isValid: true };
+};
+
+// Context length validation
+export const validateContextLength = (length: number, model: string): FieldValidationResult => {
+ if (length < 1000) {
+ return { isValid: false, error: "Context length must be at least 1,000 characters" };
+ }
+
+ if (length > 2000000) {
+ return { isValid: false, error: "Context length cannot exceed 2,000,000 characters" };
+ }
+
+ // Model-specific warnings
+ if (model.includes("gpt-4") && length > 128000 * 4) {
+ return { isValid: true, warning: "This context length exceeds GPT-4's recommended limit" };
+ }
+
+ if (model.includes("gpt-3.5") && length > 16000 * 4) {
+ return { isValid: true, warning: "This context length exceeds GPT-3.5's limit" };
+ }
+
+ return { isValid: true };
+};
\ No newline at end of file
diff --git a/openrewind/lib/utils/window.ts b/openrewind/lib/utils/window.ts
new file mode 100644
index 000000000..21d2c4416
--- /dev/null
+++ b/openrewind/lib/utils/window.ts
@@ -0,0 +1,14 @@
+import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
+import { commands } from "./tauri";
+
+export async function openSettingsWindow(section?: string) {
+ await commands.showWindow({ Settings: { page: section ?? null } });
+}
+
+export async function openSearchWindow() {
+ await commands.showWindow("Search");
+}
+
+export async function openMainWindow() {
+ await commands.showWindow("Main");
+}
\ No newline at end of file
diff --git a/openrewind/src-tauri/Cargo.lock b/openrewind/src-tauri/Cargo.lock
index 390e4a869..745d66a88 100755
--- a/openrewind/src-tauri/Cargo.lock
+++ b/openrewind/src-tauri/Cargo.lock
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "Inflector"
+version = "0.11.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"
+
[[package]]
name = "addr2line"
version = "0.22.0"
@@ -4118,6 +4124,8 @@ dependencies = [
"serde",
"serde_derive",
"serde_json",
+ "specta",
+ "specta-typescript",
"sysinfo",
"tauri",
"tauri-build",
@@ -4138,6 +4146,7 @@ dependencies = [
"tauri-plugin-single-instance",
"tauri-plugin-store",
"tauri-plugin-updater",
+ "tauri-specta",
"tauri-utils",
"tokio",
"tower-http",
@@ -5771,6 +5780,52 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "specta"
+version = "2.0.0-rc.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ccbb212565d2dc177bc15ecb7b039d66c4490da892436a4eee5b394d620c9bc"
+dependencies = [
+ "paste",
+ "serde_json",
+ "specta-macros",
+ "thiserror 1.0.69",
+ "uuid",
+]
+
+[[package]]
+name = "specta-macros"
+version = "2.0.0-rc.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68999d29816965eb9e5201f60aec02a76512139811661a7e8e653abc810b8f72"
+dependencies = [
+ "Inflector",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.90",
+]
+
+[[package]]
+name = "specta-serde"
+version = "0.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12260cbb21abb2e83a0375b1521867910e3aed8a7afa782206150ce552cd2e5a"
+dependencies = [
+ "specta",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "specta-typescript"
+version = "0.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e4472229365ceb6395487e3a60d921ad8e21f9ad06eaecc396f098902c9adc"
+dependencies = [
+ "specta",
+ "specta-serde",
+ "thiserror 1.0.69",
+]
+
[[package]]
name = "spin"
version = "0.9.8"
@@ -6058,6 +6113,7 @@ dependencies = [
"serde_json",
"serde_repr",
"serialize-to-javascript",
+ "specta",
"swift-rs",
"tauri-build",
"tauri-macros",
@@ -6510,6 +6566,34 @@ dependencies = [
"wry",
]
+[[package]]
+name = "tauri-specta"
+version = "2.0.0-rc.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d06336a2fa3ead0c8d08719e78cbc1fb73650845789605bd2ab908cbde72815"
+dependencies = [
+ "heck 0.5.0",
+ "serde",
+ "serde_json",
+ "specta",
+ "specta-typescript",
+ "tauri",
+ "tauri-specta-macros",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "tauri-specta-macros"
+version = "2.0.0-rc.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a4aa93823e07859546aa796b8a5d608190cd8037a3a5dce3eb63d491c34bda8"
+dependencies = [
+ "heck 0.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.90",
+]
+
[[package]]
name = "tauri-utils"
version = "2.1.0"
diff --git a/openrewind/src-tauri/Cargo.toml b/openrewind/src-tauri/Cargo.toml
index a169cad30..692418be0 100644
--- a/openrewind/src-tauri/Cargo.toml
+++ b/openrewind/src-tauri/Cargo.toml
@@ -43,6 +43,15 @@ serde_json = "1.0"
tower-http = { version = "0.4.0", features = ["cors", "trace"] }
http = "0.2"
+# TypeScript bindings
+specta = { version = "=2.0.0-rc.20", features = [
+ "derive",
+ "serde_json",
+ "uuid",
+] }
+tauri-specta = { version = "=2.0.0-rc.20", features = ["derive", "typescript"] }
+specta-typescript = "0.0.7"
+
# Logging
log = "0.4.17"
diff --git a/openrewind/src-tauri/capabilities/main.json b/openrewind/src-tauri/capabilities/main.json
index f02b5a8eb..7a30222e0 100644
--- a/openrewind/src-tauri/capabilities/main.json
+++ b/openrewind/src-tauri/capabilities/main.json
@@ -48,6 +48,8 @@
"core:window:default",
"core:window:allow-get-all-windows",
"core:window:allow-close",
+ "core:window:allow-destroy",
+ "core:window:allow-start-dragging",
{
"identifier": "fs:scope",
"allow": [
@@ -160,6 +162,7 @@
"core:path:default",
"process:default",
"core:webview:allow-internal-toggle-devtools",
+ "core:webview:allow-create-webview-window",
{
"identifier": "shell:allow-execute",
"allow": [
diff --git a/openrewind/src-tauri/gen/schemas/capabilities.json b/openrewind/src-tauri/gen/schemas/capabilities.json
index 075391b31..e9b78cd0b 100644
--- a/openrewind/src-tauri/gen/schemas/capabilities.json
+++ b/openrewind/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","remote":{"urls":["http://localhost:*"]},"local":true,"windows":["*"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","shell:allow-open","store:default","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default","sentry:default","opener:allow-open-url","core:window:default","core:window:allow-get-all-windows","core:window:allow-close",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.openrewind/**","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.openrewind/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":true,"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","core:webview:allow-internal-toggle-devtools",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]},{"identifier":"http:default","allow":[{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"http://**/*"},{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"https://**/*"}]},"deep-link:default","fs:allow-write-text-file",{"identifier":"fs:scope","allow":[{"path":"$APPLOCALDATA"},{"path":"$APPLOCALDATA/**"}]},"opener:default","opener:default"]}}
\ No newline at end of file
+{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","remote":{"urls":["http://localhost:*"]},"local":true,"windows":["*"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","shell:allow-open","store:default","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default","sentry:default","opener:allow-open-url","core:window:default","core:window:allow-get-all-windows","core:window:allow-close","core:window:allow-destroy","core:window:allow-start-dragging",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.openrewind/**","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.openrewind/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":true,"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","core:webview:allow-internal-toggle-devtools","core:webview:allow-create-webview-window",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]},{"identifier":"http:default","allow":[{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"http://**/*"},{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"https://**/*"}]},"deep-link:default","fs:allow-write-text-file",{"identifier":"fs:scope","allow":[{"path":"$APPLOCALDATA"},{"path":"$APPLOCALDATA/**"}]},"opener:default","opener:default"]}}
\ No newline at end of file
diff --git a/openrewind/src-tauri/src/analytics.rs b/openrewind/src-tauri/src/analytics.rs
index b984281ca..86e257903 100755
--- a/openrewind/src-tauri/src/analytics.rs
+++ b/openrewind/src-tauri/src/analytics.rs
@@ -80,10 +80,9 @@ impl AnalyticsManager {
let disk_data = json!({
"disk_total_data_size": disk_usage.total_data_size,
"disk_total_cache_size": disk_usage.total_cache_size,
- "disk_available_space": disk_usage.avaiable_space,
+ "disk_available_space": disk_usage.available_space,
"disk_media_videos_size": disk_usage.media.videos_size,
"disk_media_audios_size": disk_usage.media.audios_size,
- "disk_total_pipes_size": disk_usage.pipes.total_pipes_size,
});
payload_props.extend(disk_data.as_object().unwrap().clone());
}
diff --git a/openrewind/src-tauri/src/commands.rs b/openrewind/src-tauri/src/commands.rs
index d8d3eb1ca..c06117418 100644
--- a/openrewind/src-tauri/src/commands.rs
+++ b/openrewind/src-tauri/src/commands.rs
@@ -1,10 +1,13 @@
-use crate::get_data_dir;
+use crate::{get_data_dir, window_api::{RewindWindowId, ShowRewindWindow}, store::{OnboardingStore, SettingsStore}};
use serde::Serialize;
+use specta::Type;
use tauri::Manager;
use tracing::{error, info};
+use std::{fs, path::Path};
#[tauri::command]
-pub fn set_tray_unhealth_icon(app_handle: tauri::AppHandle<tauri::Wry>) {
+#[specta::specta]
+pub fn set_tray_unhealth_icon(app_handle: tauri::AppHandle) {
if let Some(main_tray) = app_handle.tray_by_id("screenpipe_main") {
let _ = main_tray.set_icon(Some(
tauri::image::Image::from_path("icons/screenpipe-logo-tray-failed.png").unwrap(),
@@ -13,7 +16,8 @@ pub fn set_tray_unhealth_icon(app_handle: tauri::AppHandle<tauri::Wry>) {
}
#[tauri::command]
-pub fn set_tray_health_icon(app_handle: tauri::AppHandle<tauri::Wry>) {
+#[specta::specta]
+pub fn set_tray_health_icon(app_handle: tauri::AppHandle) {
if let Some(main_tray) = app_handle.tray_by_id("screenpipe_main") {
let _ = main_tray.set_icon(Some(
tauri::image::Image::from_path("icons/screenpipe-logo-tray-black.png").unwrap(),
@@ -22,7 +26,8 @@ pub fn set_tray_health_icon(app_handle: tauri::AppHandle<tauri::Wry>) {
}
#[tauri::command]
-pub fn show_main_window(app_handle: &tauri::AppHandle<tauri::Wry>, overlay: bool) {
+#[specta::specta]
+pub fn show_main_window(app_handle: &tauri::AppHandle, overlay: bool) {
if let Some(window) = app_handle.get_webview_window("main") {
#[cfg(target_os = "macos")]
if overlay {
@@ -61,7 +66,8 @@ pub fn show_main_window(app_handle: &tauri::AppHandle<tauri::Wry>, overlay: bool
}
#[tauri::command]
-pub fn hide_main_window(app_handle: &tauri::AppHandle<tauri::Wry>) {
+#[specta::specta]
+pub fn hide_main_window(app_handle: &tauri::AppHandle) {
if let Some(window) = app_handle.get_webview_window("main") {
let _ = window.close();
}
@@ -70,8 +76,9 @@ pub fn hide_main_window(app_handle: &tauri::AppHandle<tauri::Wry>) {
const DEFAULT_SHORTCUT: &str = "Super+Alt+S";
#[tauri::command(rename_all = "snake_case")]
+#[specta::specta]
pub fn update_show_screenpipe_shortcut(
- app_handle: tauri::AppHandle<tauri::Wry>,
+ app_handle: tauri::AppHandle,
new_shortcut: String,
enabled: bool,
) -> Result<(), String> {
@@ -137,15 +144,16 @@ pub fn update_show_screenpipe_shortcut(
}
// Add these new structs
-#[derive(Debug, Serialize)]
+#[derive(Debug, Serialize, Type)]
pub struct AuthStatus {
authenticated: bool,
message: Option<String>,
}
#[tauri::command]
+#[specta::specta]
pub async fn open_pipe_window(
- app_handle: tauri::AppHandle<tauri::Wry>,
+ app_handle: tauri::AppHandle,
port: u16,
title: String,
) -> Result<(), String> {
@@ -215,11 +223,12 @@ pub async fn open_pipe_window(
}
#[tauri::command]
+#[specta::specta]
pub async fn get_disk_usage(
- app_handle: tauri::AppHandle<tauri::Wry>,
+ app_handle: tauri::AppHandle,
) -> Result<serde_json::Value, String> {
- let screenpipe_dir_path =
- get_data_dir(&app_handle).unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe"));
+ let screenpipe_dir_path = get_data_dir(&app_handle)
+ .unwrap_or_else(|_| dirs::home_dir().unwrap().join(".openrewind"));
match crate::disk_usage::disk_usage(&screenpipe_dir_path).await {
Ok(Some(disk_usage)) => match serde_json::to_value(&disk_usage) {
Ok(json_value) => Ok(json_value),
@@ -235,3 +244,75 @@ pub async fn get_disk_usage(
}
}
}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn show_window(
+ app_handle: tauri::AppHandle,
+ window: ShowRewindWindow,
+) -> Result<(), String> {
+ window.show(&app_handle).map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn close_window(
+ app_handle: tauri::AppHandle,
+ window: ShowRewindWindow,
+) -> Result<(), String> {
+ let window_id = match window {
+ ShowRewindWindow::Main => RewindWindowId::Main,
+ ShowRewindWindow::Settings { .. } => RewindWindowId::Settings,
+ ShowRewindWindow::Onboarding => RewindWindowId::Onboarding,
+ ShowRewindWindow::Search => RewindWindowId::Search,
+ };
+
+ if let Some(window) = window_id.get(&app_handle) {
+ window.close().map_err(|e| e.to_string())
+ } else {
+ Err(format!("Window {} not found", window_id.label()))
+ }
+}
+
+// Onboarding commands
+#[tauri::command]
+#[specta::specta]
+pub async fn get_onboarding_status(app_handle: tauri::AppHandle) -> Result<OnboardingStore, String> {
+ OnboardingStore::get(&app_handle).map(|o| o.unwrap_or_default())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn complete_onboarding(app_handle: tauri::AppHandle) -> Result<(), String> {
+ // wait until onboarding is updated
+ OnboardingStore::update(&app_handle, |onboarding| {
+ onboarding.complete();
+ }).map_err(|e| e.to_string())?;
+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
+ show_window(app_handle.clone(), ShowRewindWindow::Main).await?;
+ close_window(app_handle.clone(), ShowRewindWindow::Onboarding).await?;
+ Ok(())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn reset_onboarding(app_handle: tauri::AppHandle) -> Result<(), String> {
+ OnboardingStore::update(&app_handle, |onboarding| {
+ onboarding.reset();
+ })
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn show_onboarding_window(app_handle: tauri::AppHandle) -> Result<(), String> {
+ ShowRewindWindow::Onboarding.show(&app_handle).map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+#[tauri::command]
+#[specta::specta]
+pub async fn set_window_size(app_handle: tauri::AppHandle, window: ShowRewindWindow, width: f64, height: f64) -> Result<(), String> {
+ window.set_size(&app_handle, width, height).map_err(|e| e.to_string())?;
+ Ok(())
+}
\ No newline at end of file
diff --git a/openrewind/src-tauri/src/disk_usage.rs b/openrewind/src-tauri/src/disk_usage.rs
index f670e0cca..cd5cc72ef 100644
--- a/openrewind/src-tauri/src/disk_usage.rs
+++ b/openrewind/src-tauri/src/disk_usage.rs
@@ -9,17 +9,10 @@ use tracing::{info, warn};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DiskUsage {
- pub pipes: DiskUsedByPipes,
pub media: DiskUsedByMedia,
pub total_data_size: String,
pub total_cache_size: String,
- pub avaiable_space: String,
-}
-
-#[derive(Debug, Serialize, Deserialize, Clone)]
-pub struct DiskUsedByPipes {
- pub pipes: Vec<(String, String)>, // why not pipes' size??
- pub total_pipes_size: String,
+ pub available_space: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -58,14 +51,22 @@ pub fn directory_size(path: &Path) -> io::Result<Option<u64>> {
}
pub fn readable(size: u64) -> String {
- let units = ["KB", "MB", "GB"];
- let mut size = size as f64 / 1024.0;
+ if size == 0 {
+ return "0 KB".to_string();
+ }
+
+ let units = ["B", "KB", "MB", "GB", "TB"];
+ let mut size = size as f64;
let mut unit = 0;
+
while size >= 1024.0 && unit < units.len() - 1 {
size /= 1024.0;
unit += 1;
}
- if units[unit] == "GB" {
+
+ if unit == 0 {
+ format!("{:.0} {}", size, units[unit])
+ } else if units[unit] == "GB" || units[unit] == "TB" {
format!("{:.2} {}", size, units[unit])
} else {
format!("{:.1} {}", size, units[unit])
@@ -73,7 +74,7 @@ pub fn readable(size: u64) -> String {
}
pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, String> {
- let pipes_dir = screenpipe_dir.join("pipes");
+ info!("Calculating disk usage for directory: {}", screenpipe_dir.display());
let data_dir = screenpipe_dir.join("data");
let cache_dir = match get_cache_dir()? {
@@ -87,118 +88,146 @@ pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, S
if let Ok(content) = fs::read_to_string(&cache_file) {
warn!("disk cache file found: {}", cache_file.to_string_lossy());
if content.contains("---") {
- info!("possibly some values in disk usgae haven't calculated, recalculating...");
+ info!("possibly some values in disk usage haven't calculated, recalculating...");
} else {
if let Ok(cached) = serde_json::from_str::<CachedDiskUsage>(&content) {
let now = chrono::Local::now().timestamp();
let two_days = 2 * 24 * 60 * 60; // 2 days in seconds
if now - cached.timestamp < two_days {
+ info!("Using cached disk usage data");
return Ok(Some(cached.usage));
}
}
}
}
- let mut pipes = Vec::new();
- let mut total_video_size: Option<u64> = Some(0);
- let mut total_audio_size: Option<u64> = Some(0);
-
- if pipes_dir.exists() {
- for entry in fs::read_dir(&pipes_dir).map_err(|e| e.to_string())? {
- let entry = entry.map_err(|e| e.to_string())?;
- let path = entry.path();
- if path.is_dir() {
- let size = directory_size(&path).map_err(|e| e.to_string())?;
- let size_str = match size {
- Some(s) => readable(s),
- None => "---".to_string(),
- };
- pipes.push((
- path.file_name().unwrap().to_string_lossy().to_string(),
- size_str,
- ));
- }
- }
- } else {
- warn!("there are no pipes to calculate sizes");
- }
+ let mut total_video_size: u64 = 0;
+ let mut total_audio_size: u64 = 0;
+ // Calculate total data size
+ info!("Calculating total data size for: {}", screenpipe_dir.display());
let total_data_size = match directory_size(screenpipe_dir).map_err(|e| e.to_string())? {
- Some(size) => readable(size),
- None => "---".to_string(),
- };
- let total_media_size = match directory_size(&data_dir).map_err(|e| e.to_string())? {
- Some(size) => readable(size),
- None => "---".to_string(),
- };
- let total_pipes_size = match directory_size(&pipes_dir).map_err(|e| e.to_string())? {
- Some(size) => readable(size),
- None => "---".to_string(),
+ Some(size) => {
+ info!("Total data size: {} bytes", size);
+ readable(size)
+ },
+ None => {
+ warn!("Could not calculate total data size");
+ "---".to_string()
+ },
};
+
+ // Calculate cache size
+ info!("Calculating cache size for: {}", cache_dir.display());
let total_cache_size = match directory_size(&cache_dir).map_err(|e| e.to_string())? {
- Some(size) => readable(size),
- None => "---".to_string(),
+ Some(size) => {
+ info!("Total cache size: {} bytes", size);
+ readable(size)
+ },
+ None => {
+ warn!("Could not calculate cache size");
+ "---".to_string()
+ },
};
+ // Calculate individual media file sizes recursively
if data_dir.exists() {
- for entry in fs::read_dir(&data_dir).map_err(|e| e.to_string())? {
- let entry = entry.map_err(|e| e.to_string())?;
- let path = entry.path();
- if path.is_file() {
- let size = entry.metadata().map_err(|e| e.to_string())?.len();
- let file_name = path.file_name().unwrap().to_string_lossy().to_string();
- if file_name.contains("input") || file_name.contains("output") {
- total_audio_size = total_audio_size.map(|s| s + size);
- } else {
- total_video_size = total_video_size.map(|s| s + size);
+ info!("Scanning data directory recursively for media files");
+ fn scan_media_files(dir: &Path, video_size: &mut u64, audio_size: &mut u64) -> io::Result<()> {
+ for entry in fs::read_dir(dir)? {
+ let entry = entry?;
+ let path = entry.path();
+ if path.is_dir() {
+ // Recursively scan subdirectories
+ scan_media_files(&path, video_size, audio_size)?;
+ } else if path.is_file() {
+ let size = entry.metadata()?.len();
+ let file_name = path.file_name().unwrap().to_string_lossy().to_string();
+
+ // Classify files based on extension and name patterns
+ let extension = path.extension()
+ .and_then(|ext| ext.to_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ match extension.as_str() {
+ // Audio file extensions
+ "mp3" | "wav" | "flac" | "aac" | "ogg" | "m4a" | "wma" => {
+ *audio_size += size;
+ },
+ // Video file extensions
+ "mp4" | "avi" | "mkv" | "mov" | "wmv" | "flv" | "webm" | "m4v" => {
+ *video_size += size;
+ },
+ // Fallback to filename patterns for files without clear extensions
+ _ => {
+ if file_name.contains("input") || file_name.contains("output") || file_name.contains("audio") {
+ *audio_size += size;
+ } else if file_name.contains("video") || file_name.contains("screen") {
+ *video_size += size;
+ } else {
+ // Default to video for unknown media files
+ *video_size += size;
+ }
+ }
+ }
}
}
+ Ok(())
+ }
+
+ if let Err(e) = scan_media_files(&data_dir, &mut total_video_size, &mut total_audio_size) {
+ warn!("Error scanning media files: {}", e);
}
+
+ info!("Video files total: {} bytes, Audio files total: {} bytes", total_video_size, total_audio_size);
} else {
- warn!("no data dir to calculate disk usage");
- total_audio_size = None;
- total_video_size = None;
+ warn!("Data directory does not exist: {}", data_dir.display());
}
- let videos_size_str = total_video_size.map_or("---".to_string(), |s| readable(s));
- let audios_size_str = total_audio_size.map_or("---".to_string(), |s| readable(s));
+ let videos_size_str = readable(total_video_size);
+ let audios_size_str = readable(total_audio_size);
+ let total_media_size_calculated = total_video_size + total_audio_size;
+ let total_media_size_str = readable(total_media_size_calculated);
- let avaiable_space = {
+ // Calculate available space
+ info!("Calculating available disk space");
+ let available_space = {
let mut sys = System::new();
sys.refresh_disks_list();
let path_obj = Path::new(&screenpipe_dir);
- sys.disks()
+ let available = sys.disks()
.iter()
.find(|disk| path_obj.starts_with(disk.mount_point()))
.map(|disk| disk.available_space())
- .unwrap_or(0)
+ .unwrap_or(0);
+ info!("Available disk space: {} bytes", available);
+ available
};
let disk_usage = DiskUsage {
- pipes: DiskUsedByPipes {
- pipes,
- total_pipes_size,
- },
media: DiskUsedByMedia {
videos_size: videos_size_str,
audios_size: audios_size_str,
- total_media_size,
+ total_media_size: total_media_size_str,
},
total_data_size,
total_cache_size,
- avaiable_space: readable(avaiable_space),
+ available_space: readable(available_space),
};
+ info!("Disk usage calculation completed: {:?}", disk_usage);
+
// Cache the result
let cached = CachedDiskUsage {
timestamp: chrono::Local::now().timestamp(),
usage: disk_usage.clone(),
};
- info!("writing disk usage cache file: {}", cache_file.to_string_lossy());
+ info!("Writing disk usage cache file: {}", cache_file.to_string_lossy());
if let Err(e) = fs::write(&cache_file, serde_json::to_string_pretty(&cached).unwrap()) {
- info!("Failed to write cache file: {}", e);
+ warn!("Failed to write cache file: {}", e);
}
Ok(Some(disk_usage))
diff --git a/openrewind/src-tauri/src/main.rs b/openrewind/src-tauri/src/main.rs
index ef8d4c267..3f848127c 100755
--- a/openrewind/src-tauri/src/main.rs
+++ b/openrewind/src-tauri/src/main.rs
@@ -8,6 +8,7 @@ use serde_json::Value;
use std::env;
use std::fs::File;
use std::path::PathBuf;
+use std::str::FromStr;
use std::sync::Arc;
use tauri::Config;
use tauri::Emitter;
@@ -25,6 +26,14 @@ use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
use updates::start_update_check;
+use window_api::ShowRewindWindow;
+
+// TypeScript bindings generation imports (only in debug builds)
+#[cfg(debug_assertions)]
+use specta_typescript::Typescript;
+#[cfg(debug_assertions)]
+use tauri_specta::{collect_commands, Builder};
+
mod analytics;
mod icons;
use crate::analytics::start_analytics;
@@ -44,7 +53,7 @@ pub use server::*;
pub use sidecar::*;
pub use icons::*;
-pub use store::*;
+pub use store::get_store;
mod config;
pub use config::get_base_dir;
@@ -54,21 +63,21 @@ pub use commands::set_tray_unhealth_icon;
pub use server::spawn_server;
pub use sidecar::spawn_screenpipe;
pub use sidecar::stop_screenpipe;
-pub use store::get_profiles_store;
-pub use store::get_store;
+// Removed: pub use store::get_profiles_store; // Profile functionality has been removed
use crate::commands::hide_main_window;
pub use permissions::do_permissions_check;
pub use permissions::open_permission_settings;
pub use permissions::request_permission;
use std::collections::HashMap;
-use tauri::AppHandle;
+use tauri::{AppHandle, WebviewUrl, WebviewWindow};
use tauri_plugin_global_shortcut::GlobalShortcutExt;
use tauri_plugin_global_shortcut::{Code, Modifiers, Shortcut};
use tauri_plugin_sentry::sentry;
mod health;
-use health::start_health_check;
use base64::Engine;
+use health::start_health_check;
+use window_api::RewindWindowId;
// New struct to hold shortcut configuration
#[derive(Debug, Default)]
@@ -78,7 +87,6 @@ struct ShortcutConfig {
stop: String,
start_audio: String,
stop_audio: String,
- profile_shortcuts: HashMap<String, String>,
disabled: Vec<String>,
}
@@ -86,26 +94,6 @@ impl ShortcutConfig {
async fn from_store(app: &AppHandle) -> Result<Self, String> {
let store = get_store(app, None).map_err(|e| e.to_string())?;
- let profile_shortcuts = match get_profiles_store(app) {
- Ok(profiles_store) => {
- let profiles = profiles_store
- .get("profiles")
- .and_then(|v| serde_json::from_value::<Vec<String>>(v.clone()).ok())
- .unwrap_or_default();
-
- profiles
- .into_iter()
- .filter_map(|profile| {
- profiles_store
- .get(format!("shortcuts.{}", profile))
- .and_then(|v| v.as_str().map(String::from))
- .map(|shortcut| (profile, shortcut))
- })
- .collect()
- }
- Err(_) => HashMap::new(),
- };
-
Ok(Self {
show: store
.get("showOpenRewindShortcut")
@@ -127,7 +115,6 @@ impl ShortcutConfig {
.get("stopAudioShortcut")
.and_then(|v| v.as_str().map(String::from))
.unwrap_or_default(),
- profile_shortcuts,
disabled: store
.get("disabledShortcuts")
.and_then(|v| serde_json::from_value(v.clone()).ok())
@@ -166,7 +153,7 @@ async fn register_shortcut(
}
#[tauri::command]
-#[allow(clippy::too_many_arguments)]
+#[specta::specta]
async fn update_global_shortcuts(
app: AppHandle,
show_shortcut: String,
@@ -174,7 +161,7 @@ async fn update_global_shortcuts(
stop_shortcut: String,
start_audio_shortcut: String,
stop_audio_shortcut: String,
- profile_shortcuts: HashMap<String, String>,
+ _profile_shortcuts: HashMap<String, String>, // Keep for API compatibility but ignore
) -> Result<(), String> {
let config = ShortcutConfig {
show: show_shortcut,
@@ -182,7 +169,6 @@ async fn update_global_shortcuts(
stop: stop_shortcut,
start_audio: start_audio_shortcut,
stop_audio: stop_audio_shortcut,
- profile_shortcuts,
disabled: ShortcutConfig::from_store(&app).await?.disabled,
};
apply_shortcuts(&app, &config).await
@@ -241,18 +227,6 @@ async fn apply_shortcuts(app: &AppHandle, config: &ShortcutConfig) -> Result<(),
)
.await?;
- // Register profile shortcuts
- for (profile, shortcut) in &config.profile_shortcuts {
- if !shortcut.is_empty() {
- let profile = profile.clone();
- register_shortcut(app, shortcut, false, move |app| {
- info!("switch-profile shortcut triggered for profile: {}", profile);
- let _ = app.emit("switch-profile", profile.clone());
- })
- .await?;
- }
- }
-
// Register start audio shortcut
register_shortcut(
app,
@@ -287,11 +261,12 @@ async fn apply_shortcuts(app: &AppHandle, config: &ShortcutConfig) -> Result<(),
}
#[tauri::command]
+#[specta::specta]
fn get_env(name: &str) -> String {
std::env::var(String::from(name)).unwrap_or(String::from(""))
}
-#[derive(Debug, serde::Serialize)]
+#[derive(Debug, serde::Serialize, specta::Type)]
pub struct LogFile {
name: String,
path: String,
@@ -299,6 +274,7 @@ pub struct LogFile {
}
#[tauri::command]
+#[specta::specta]
async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
let data_dir = get_data_dir(&app).map_err(|e| e.to_string())?;
let mut log_files = Vec::new();
@@ -377,16 +353,17 @@ fn get_data_dir(app: &tauri::AppHandle) -> anyhow::Result<PathBuf> {
use tokio::time::{sleep, Duration};
#[tauri::command]
+#[specta::specta]
async fn get_media_file(file_path: &str) -> Result<serde_json::Value, String> {
use std::path::Path;
-
+
debug!("Reading media file: {}", file_path);
-
+
let path = Path::new(file_path);
if !path.exists() {
return Err(format!("File does not exist: {}", file_path));
}
-
+
// Read file contents
let file_contents = match tokio::fs::read(path).await {
Ok(contents) => {
@@ -398,13 +375,13 @@ async fn get_media_file(file_path: &str) -> Result<serde_json::Value, String> {
return Err(format!("Failed to read file: {}", e));
}
};
-
+
// Convert to base64
let data = base64::prelude::BASE64_STANDARD.encode(&file_contents);
-
+
// Determine MIME type
let mime_type = get_mime_type(file_path);
-
+
Ok(serde_json::json!({
"data": data,
"mimeType": mime_type
@@ -414,18 +391,25 @@ async fn get_media_file(file_path: &str) -> Result<serde_json::Value, String> {
fn get_mime_type(path: &str) -> String {
let ext = path.split('.').last().unwrap_or("").to_lowercase();
let is_audio = path.to_lowercase().contains("input") || path.to_lowercase().contains("output");
-
+
match ext.as_str() {
"mp4" => "video/mp4".to_string(),
"webm" => "video/webm".to_string(),
"ogg" => "video/ogg".to_string(),
"mp3" => "audio/mpeg".to_string(),
"wav" => "audio/wav".to_string(),
- _ => if is_audio { "audio/mpeg".to_string() } else { "video/mp4".to_string() }
+ _ => {
+ if is_audio {
+ "audio/mpeg".to_string()
+ } else {
+ "video/mp4".to_string()
+ }
+ }
}
}
#[tauri::command]
+#[specta::specta]
async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool, String> {
debug!("Starting upload for file: {}", file_path);
@@ -604,6 +588,53 @@ async fn main() {
}
}
+ // Generate TypeScript bindings in debug mode
+ #[cfg(debug_assertions)]
+ {
+ use crate::store::{SettingsStore, OnboardingStore};
+
+ info!("Generating TypeScript bindings...");
+ let builder = Builder::new()
+ .commands(collect_commands![
+ // Commands from permissions.rs
+ permissions::open_permission_settings,
+ permissions::request_permission,
+ permissions::do_permissions_check,
+ // Commands from main.rs
+ get_env,
+ get_log_files,
+ get_media_file,
+ upload_file_to_s3,
+ update_global_shortcuts,
+ spawn_screenpipe,
+ stop_screenpipe,
+ // Commands from commands.rs
+ commands::get_disk_usage,
+ commands::open_pipe_window,
+ commands::update_show_screenpipe_shortcut,
+ commands::show_window,
+ commands::close_window,
+ commands::set_window_size,
+ // Onboarding commands
+ commands::get_onboarding_status,
+ commands::complete_onboarding,
+ commands::reset_onboarding,
+ commands::show_onboarding_window,
+ // Commands from tray.rs
+ set_tray_unhealth_icon,
+ set_tray_health_icon,
+ ])
+ .typ::<SettingsStore>()
+ .typ::<OnboardingStore>();
+
+ builder
+ .export(
+ Typescript::default().bigint(specta_typescript::BigIntExportBehavior::BigInt),
+ "../lib/utils/tauri.ts",
+ )
+ .expect("Failed to export TypeScript bindings");
+ }
+
let sidecar_state = SidecarState(Arc::new(tokio::sync::Mutex::new(None)));
#[allow(clippy::single_match)]
let app = tauri::Builder::default()
@@ -659,11 +690,19 @@ async fn main() {
commands::update_show_screenpipe_shortcut,
commands::get_disk_usage,
commands::open_pipe_window,
+ commands::show_window,
+ commands::close_window,
+ commands::set_window_size,
+ // Onboarding commands
+ commands::get_onboarding_status,
+ commands::complete_onboarding,
+ commands::reset_onboarding,
+ commands::show_onboarding_window,
get_log_files,
get_media_file,
upload_file_to_s3,
update_global_shortcuts,
- get_env,
+ get_env
])
.setup(|app| {
//deep link register_all
@@ -672,9 +711,9 @@ async fn main() {
use tauri_plugin_deep_link::DeepLinkExt;
app.deep_link().register_all()?;
}
+ let app_handle = app.handle();
// Logging setup
- let app_handle = app.handle();
let base_dir =
get_base_dir(app_handle, None).expect("Failed to ensure local data directory");
@@ -732,18 +771,19 @@ async fn main() {
}
// Store setup and initialization - must be done first
- let store = StoreBuilder::new(app.handle(), path.clone())
- .build()
- .unwrap();
+ let store = store::init_store(&app.handle()).unwrap();
+ app.manage(store.clone());
- // Initialize default store values if empty
- if store.is_empty() {
- store.set("analyticsEnabled".to_string(), Value::Bool(true));
- }
+ // Initialize onboarding store
+ let onboarding_store = store::init_onboarding_store(&app.handle()).unwrap();
+ app.manage(onboarding_store.clone());
- // Ensure store is saved and managed
- store.save()?;
- app.manage(store.clone());
+ // Show onboarding window if not completed
+ if !onboarding_store.is_completed {
+ let _ = ShowRewindWindow::Onboarding.show(&app.handle());
+ } else {
+ let _ = ShowRewindWindow::Main.show(&app.handle());
+ }
// Get app handle once for all initializations
let app_handle = app.handle().clone();
@@ -758,9 +798,7 @@ async fn main() {
// Dev mode check and sidecar initialization
let use_dev_mode = store
- .get("devMode")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .dev_mode;
info!("use_dev_mode: {}", use_dev_mode);
@@ -791,16 +829,10 @@ async fn main() {
// Check analytics settings from store
let is_analytics_enabled = store
- .get("analyticsEnabled")
- .unwrap_or(Value::Bool(true))
- .as_bool()
- .unwrap_or(true);
+ .analytics_enabled;
let is_autostart_enabled = store
- .get("autoStartEnabled")
- .unwrap_or(Value::Bool(true))
- .as_bool()
- .unwrap_or(true);
+ .auto_start_enabled;
if is_autostart_enabled {
let _ = autostart_manager.enable();
@@ -813,15 +845,8 @@ async fn main() {
autostart_manager.is_enabled().unwrap()
);
- let unique_id = store
- .get("user.id")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or_default();
-
- let email = store
- .get("user.email")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or_default();
+ let unique_id = store.user.id.unwrap_or_default();
+ let email = store.user.email.unwrap_or_default();
if is_analytics_enabled {
match start_analytics(
@@ -844,7 +869,7 @@ async fn main() {
// Start health check service (macos only)
let app_handle_clone = app_handle.clone();
- tauri::async_runtime::spawn(async move {
+ tauri::async_runtime::spawn(async move {
if let Err(e) = start_health_check(app_handle_clone).await {
error!("Failed to start health check service: {}", e);
}
@@ -918,11 +943,49 @@ async fn main() {
window.set_focus().unwrap();
}
}
+ tauri::RunEvent::WindowEvent {
+ label,
+ event: tauri::WindowEvent::Destroyed,
+ ..
+ } => {
+ if label == "main" {
+ let window = app_handle.get_webview_window("main").unwrap();
+ window.show().unwrap();
+ window.set_focus().unwrap();
+ }
+
+ if let Ok(window_id) = RewindWindowId::from_str(label.as_str()) {
+ match window_id {
+ RewindWindowId::Settings => {
+ if let Some(window) = RewindWindowId::Main.get(&app_handle) {
+ let _ = window.show();
+ }
+
+ return;
+ }
+
+ _ => {}
+ }
+ }
+ }
+
#[cfg(target_os = "macos")]
tauri::RunEvent::Reopen {
has_visible_windows,
..
} => {
+ let has_window = app_handle
+ .webview_windows()
+ .iter()
+ .any(|(label, _)| label.as_str() == "settings");
+
+ if has_window {
+ if let Some(window) = app_handle.get_webview_window("settings") {
+ let _ = window.show();
+ }
+ return;
+ }
+
if !has_visible_windows {
show_main_window(app_handle, false);
}
diff --git a/openrewind/src-tauri/src/permissions.rs b/openrewind/src-tauri/src/permissions.rs
index 3aec29091..b7bbfaa22 100644
--- a/openrewind/src-tauri/src/permissions.rs
+++ b/openrewind/src-tauri/src/permissions.rs
@@ -1,4 +1,5 @@
use serde::{Deserialize, Serialize};
+use specta::Type;
#[cfg(target_os = "macos")]
#[link(name = "ApplicationServices", kind = "framework")]
@@ -8,7 +9,7 @@ extern "C" {
-> bool;
}
-#[derive(Serialize, Deserialize)]
+#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum OSPermission {
ScreenRecording,
@@ -17,6 +18,7 @@ pub enum OSPermission {
}
#[tauri::command(async)]
+#[specta::specta]
pub fn open_permission_settings(permission: OSPermission) {
#[cfg(target_os = "macos")]
{
@@ -44,6 +46,7 @@ pub fn open_permission_settings(permission: OSPermission) {
}
#[tauri::command]
+#[specta::specta]
pub async fn request_permission(permission: OSPermission) {
#[cfg(target_os = "macos")]
{
@@ -73,7 +76,7 @@ fn request_av_permission(media_type: nokhwa_bindings_macos::AVMediaType) {
};
}
-#[derive(Serialize, Deserialize, Debug, PartialEq)]
+#[derive(Serialize, Deserialize, Debug, PartialEq, Type)]
#[serde(rename_all = "camelCase")]
pub enum OSPermissionStatus {
// This platform does not require this permission
@@ -92,7 +95,7 @@ impl OSPermissionStatus {
}
}
-#[derive(Serialize, Deserialize, Debug)]
+#[derive(Serialize, Deserialize, Debug, Type)]
#[serde(rename_all = "camelCase")]
pub struct OSPermissionsCheck {
pub screen_recording: OSPermissionStatus,
@@ -107,6 +110,7 @@ impl OSPermissionsCheck {
}
#[tauri::command(async)]
+#[specta::specta]
pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {
#[cfg(target_os = "macos")]
{
diff --git a/openrewind/src-tauri/src/sidecar.rs b/openrewind/src-tauri/src/sidecar.rs
index 4a21db3a4..641977643 100644
--- a/openrewind/src-tauri/src/sidecar.rs
+++ b/openrewind/src-tauri/src/sidecar.rs
@@ -1,4 +1,5 @@
use crate::get_store;
+use crate::store::{Credits, SettingsStore};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
@@ -41,41 +42,25 @@ pub struct User {
}
impl User {
- pub fn from_store<R: tauri::Runtime>(store: &Store<R>) -> Self {
+ pub fn from_store(store: &SettingsStore) -> Self {
Self {
- id: store
- .get("user.id")
- .and_then(|v| v.as_str().map(String::from)),
- email: store
- .get("user.email")
- .and_then(|v| v.as_str().map(String::from)),
- name: store
- .get("user.name")
- .and_then(|v| v.as_str().map(String::from)),
- image: store
- .get("user.image")
- .and_then(|v| v.as_str().map(String::from)),
- token: store
- .get("user.token")
- .and_then(|v| v.as_str().map(String::from)),
- clerk_id: store
- .get("user.clerk_id")
- .and_then(|v| v.as_str().map(String::from)),
- credits: Some(UserCredits {
- amount: store
- .get("user.credits.amount")
- .and_then(|v| v.as_i64())
- .unwrap_or(0),
- created_at: store
- .get("user.credits.created_at")
- .and_then(|v| v.as_str().map(String::from)),
+ id: store.user.id.clone(),
+ email: store.user.email.clone(),
+ name: store.user.name.clone(),
+ image: store.user.image.clone(),
+ token: store.user.token.clone(),
+ clerk_id: store.user.clerk_id.clone(),
+ credits: store.user.credits.clone().map(|c| UserCredits {
+ amount: c.amount as i64,
+ created_at: None,
}),
- cloud_subscribed: store.get("user.cloud_subscribed").and_then(|v| v.as_bool()),
+ cloud_subscribed: store.user.cloud_subscribed.clone(),
}
}
}
#[tauri::command]
+#[specta::specta]
pub async fn stop_screenpipe(
state: State<'_, SidecarState>,
_app: tauri::AppHandle,
@@ -161,6 +146,7 @@ pub async fn stop_screenpipe(
}
#[tauri::command]
+#[specta::specta]
pub async fn spawn_screenpipe(
state: tauri::State<'_, SidecarState>,
app: tauri::AppHandle,
@@ -179,121 +165,64 @@ pub async fn spawn_screenpipe(
}
fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>>) -> Result<CommandChild, String> {
- let store = get_store(app, None).unwrap();
+ let store = app.state::<SettingsStore>();
- let audio_transcription_engine = store
- .get("audioTranscriptionEngine")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or(String::from("default"));
+ let audio_transcription_engine = store.audio_transcription_engine.clone();
- let ocr_engine = store
- .get("ocrEngine")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or(String::from("default"));
+ let ocr_engine = store.ocr_engine.clone();
- let monitor_ids = store
- .get("monitorIds")
- .and_then(|v| v.as_array().cloned())
- .unwrap_or_default();
+ let monitor_ids = store.monitor_ids.clone();
- let audio_devices = store
- .get("audioDevices")
- .and_then(|v| v.as_array().cloned())
- .unwrap_or_default();
+ let audio_devices = store.audio_devices.clone();
- let use_pii_removal = store
- .get("usePiiRemoval")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ let use_pii_removal = store.use_pii_removal;
- let port = store.get("port").and_then(|v| v.as_u64()).unwrap_or(3030);
+ let port = store.port;
- let disable_audio = store
- .get("disableAudio")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ let disable_audio = store.disable_audio;
- let ignored_windows = store
- .get("ignoredWindows")
- .and_then(|v| v.as_array().cloned())
- .unwrap_or_default();
+ let ignored_windows = store.ignored_windows.clone();
- let included_windows = store
- .get("includedWindows")
- .and_then(|v| v.as_array().cloned())
- .unwrap_or_default();
+ let included_windows = store.included_windows.clone();
- let deepgram_api_key = store
- .get("deepgramApiKey")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or(String::from("default"));
+ let deepgram_api_key = store.deepgram_api_key.clone();
- let fps = store.get("fps").and_then(|v| v.as_f64()).unwrap_or(0.2);
+ let fps = store.fps;
let dev_mode = store
- .get("devMode")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .dev_mode;
- let vad_sensitivity = store
- .get("vadSensitivity")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or(String::from("high"));
+ let vad_sensitivity = store.vad_sensitivity.clone();
- let audio_chunk_duration = store
- .get("audioChunkDuration")
- .and_then(|v| v.as_u64())
- .unwrap_or(30);
+ let audio_chunk_duration = store.audio_chunk_duration;
let telemetry_enabled = store
- .get("analyticsEnabled")
- .and_then(|v| v.as_bool())
- .unwrap_or(true);
+ .analytics_enabled;
let use_chinese_mirror = store
- .get("useChineseMirror")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .use_chinese_mirror;
- let languages = store
- .get("languages")
- .and_then(|v| v.as_array().cloned())
- .unwrap_or_default();
+ let languages = store.languages.clone();
let enable_beta = store
- .get("enableBeta")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .enable_beta;
let enable_frame_cache = store
- .get("enableFrameCache")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .enable_frame_cache;
let enable_ui_monitoring = store
- .get("enableUiMonitoring")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .enable_ui_monitoring;
- let data_dir = store
- .get("dataDir")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or(String::from("default"));
+ let data_dir = store.data_dir.clone();
let enable_realtime_audio_transcription = store
- .get("enableRealtimeAudioTranscription")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .enable_realtime_audio_transcription;
let enable_realtime_vision = store
- .get("enableRealtimeVision")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .enable_realtime_vision;
let _use_all_monitors = store
- .get("useAllMonitors")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .use_all_monitors;
let user = User::from_store(&store);
@@ -327,14 +256,14 @@ fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>>) ->
if !monitor_ids.is_empty() && monitor_ids[0] != Value::String("default".to_string()) {
for monitor in &monitor_ids {
args.push("--monitor-id");
- args.push(monitor.as_str().unwrap());
+ args.push(monitor.as_str());
}
}
if !languages.is_empty() && languages[0] != Value::String("default".to_string()) {
for language in &languages {
args.push("--language");
- args.push(language.as_str().unwrap());
+ args.push(language.as_str());
}
}
@@ -347,7 +276,7 @@ fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>>) ->
if !audio_devices.is_empty() && audio_devices[0] != Value::String("default".to_string()) {
for device in &audio_devices {
args.push("--audio-device");
- args.push(device.as_str().unwrap());
+ args.push(device.as_str());
}
}
@@ -362,14 +291,14 @@ fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>>) ->
if !ignored_windows.is_empty() {
for window in &ignored_windows {
args.push("--ignored-windows");
- args.push(window.as_str().unwrap());
+ args.push(window.as_str());
}
}
if !included_windows.is_empty() {
for window in &included_windows {
args.push("--included-windows");
- args.push(window.as_str().unwrap());
+ args.push(window.as_str());
}
}
let current_pid = std::process::id();
@@ -425,9 +354,7 @@ fn spawn_sidecar(app: &tauri::AppHandle, override_args: Option<Vec<String>>) ->
// }
let disable_vision = store
- .get("disableVision")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+ .disable_vision;
if disable_vision {
args.push("--disable-vision");
diff --git a/openrewind/src-tauri/src/store.rs b/openrewind/src-tauri/src/store.rs
index 928600e82..7d78c8cd3 100644
--- a/openrewind/src-tauri/src/store.rs
+++ b/openrewind/src-tauri/src/store.rs
@@ -1,64 +1,462 @@
use super::get_base_dir;
-use std::sync::Arc;
+use std::{collections::HashMap, sync::Arc};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use specta::Type;
use tauri::AppHandle;
use tauri_plugin_store::StoreBuilder;
-use tracing::debug;
+use tracing::error;
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct ProfilesConfig {
- active_profile: String,
- profiles: Vec<String>,
+pub fn get_store(
+ app: &AppHandle,
+ _profile_name: Option<String>, // Keep parameter for API compatibility but ignore it
+) -> anyhow::Result<Arc<tauri_plugin_store::Store<tauri::Wry>>> {
+ let base_dir = get_base_dir(app, None)?;
+ let store_path = base_dir.join("store.bin");
+
+ // Build and return the store wrapped in Arc
+ StoreBuilder::new(app, store_path)
+ .build()
+ .map_err(|e| anyhow::anyhow!(e))
+}
+
+#[derive(Serialize, Deserialize, Type, Clone)]
+pub struct OnboardingStore {
+ #[serde(rename = "isCompleted")]
+ pub is_completed: bool,
+ #[serde(rename = "completedAt")]
+ pub completed_at: Option<String>,
}
-impl Default for ProfilesConfig {
+impl Default for OnboardingStore {
fn default() -> Self {
Self {
- active_profile: "default".to_string(),
- profiles: vec!["default".to_string()],
+ is_completed: false,
+ completed_at: None,
}
}
}
-pub fn get_profiles_store(
- app: &AppHandle,
-) -> anyhow::Result<Arc<tauri_plugin_store::Store<tauri::Wry>>> {
- let base_dir = get_base_dir(app, None)?;
- let profiles_path = base_dir.join("profiles.bin");
- Ok(StoreBuilder::new(app, profiles_path).build()?)
+impl OnboardingStore {
+ pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
+ let store = get_store(app, None).map_err(|e| e.to_string())?;
+
+ match store.is_empty() {
+ true => Ok(None),
+ false => {
+ let onboarding = serde_json::from_value(store.get("onboarding").unwrap_or(Value::Null));
+ match onboarding {
+ Ok(onboarding) => Ok(onboarding),
+ Err(e) => {
+ error!("Failed to deserialize onboarding: {}", e);
+ Err(e.to_string())
+ }
+ }
+ }
+ }
+ }
+
+ pub fn update(app: &AppHandle, update: impl FnOnce(&mut OnboardingStore)) -> Result<(), String> {
+ let Ok(store) = get_store(app, None) else {
+ return Err("Failed to get onboarding store".to_string());
+ };
+
+ let mut onboarding = Self::get(app)?.unwrap_or_default();
+ update(&mut onboarding);
+ store.set("onboarding", json!(onboarding));
+ store.save().map_err(|e| e.to_string())?;
+ Ok(())
+ }
+
+ pub fn save(&self, app: &AppHandle) -> Result<(), String> {
+ let Ok(store) = get_store(app, None) else {
+ return Err("Failed to get onboarding store".to_string());
+ };
+
+ store.set("onboarding", json!(self));
+ store.save().map_err(|e| e.to_string())
+ }
+
+ pub fn complete(&mut self) {
+ self.is_completed = true;
+ self.completed_at = Some(chrono::Utc::now().to_rfc3339());
+ }
+
+ pub fn reset(&mut self) {
+ self.is_completed = false;
+ self.completed_at = None;
+ }
}
-pub fn get_store(
- app: &AppHandle,
- profile_name: Option<String>,
-) -> anyhow::Result<Arc<tauri_plugin_store::Store<tauri::Wry>>> {
- let base_dir = get_base_dir(app, None)?;
- let profiles_path = base_dir.join("profiles.bin");
-
- // Try to load profiles configuration, fallback to default if file doesn't exist
- let profile = if profiles_path.exists() {
- let profiles_store = StoreBuilder::new(app, profiles_path.clone()).build()?;
- match profile_name {
- Some(name) => name,
- None => profiles_store
- .get("activeProfile")
- .and_then(|v| v.as_str().map(String::from))
- .unwrap_or_else(|| "default".to_string()),
+#[derive(Serialize, Deserialize,Type,Clone)]
+pub struct SettingsStore {
+ #[serde(rename = "aiPresets")]
+ pub ai_presets: Vec<AIPreset>,
+
+ #[serde(rename = "deepgramApiKey")]
+ pub deepgram_api_key: String,
+ #[serde(rename = "isLoading")]
+ pub is_loading: bool,
+
+ #[serde(rename = "installedPipes")]
+ pub installed_pipes: Vec<Pipe>,
+ #[serde(rename = "userId")]
+ pub user_id: String,
+
+ #[serde(rename = "devMode")]
+ pub dev_mode: bool,
+ #[serde(rename = "audioTranscriptionEngine")]
+ pub audio_transcription_engine: String,
+ #[serde(rename = "ocrEngine")]
+ pub ocr_engine: String,
+ #[serde(rename = "monitorIds")]
+ pub monitor_ids: Vec<String>,
+ #[serde(rename = "audioDevices")]
+ pub audio_devices: Vec<String>,
+ #[serde(rename = "usePiiRemoval")]
+ pub use_pii_removal: bool,
+ #[serde(rename = "restartInterval")]
+ pub restart_interval: u32,
+ #[serde(rename = "port")]
+ pub port: u16,
+ #[serde(rename = "dataDir")]
+ pub data_dir: String,
+ #[serde(rename = "disableAudio")]
+ pub disable_audio: bool,
+ #[serde(rename = "ignoredWindows")]
+ pub ignored_windows: Vec<String>,
+ #[serde(rename = "includedWindows")]
+ pub included_windows: Vec<String>,
+
+ #[serde(rename = "fps")]
+ pub fps: f32,
+ #[serde(rename = "vadSensitivity")]
+ pub vad_sensitivity: String,
+ #[serde(rename = "analyticsEnabled")]
+ pub analytics_enabled: bool,
+ #[serde(rename = "audioChunkDuration")]
+ pub audio_chunk_duration: u32,
+ #[serde(rename = "useChineseMirror")]
+ pub use_chinese_mirror: bool,
+ #[serde(rename = "languages")]
+ pub languages: Vec<String>,
+ #[serde(rename = "embeddedLLM")]
+ pub embedded_llm: EmbeddedLLM,
+ #[serde(rename = "enableBeta")]
+ pub enable_beta: bool,
+ #[serde(rename = "isFirstTimeUser")]
+ pub is_first_time_user: bool,
+ #[serde(rename = "autoStartEnabled")]
+ pub auto_start_enabled: bool,
+ #[serde(rename = "enableFrameCache")]
+ pub enable_frame_cache: bool,
+ #[serde(rename = "enableUiMonitoring")]
+ pub enable_ui_monitoring: bool,
+ #[serde(rename = "platform")]
+ pub platform: String,
+ #[serde(rename = "disabledShortcuts")]
+ pub disabled_shortcuts: Vec<String>,
+ #[serde(rename = "user")]
+ pub user: User,
+ #[serde(rename = "showScreenpipeShortcut")]
+ pub show_screenpipe_shortcut: String,
+ #[serde(rename = "startRecordingShortcut")]
+ pub start_recording_shortcut: String,
+ #[serde(rename = "stopRecordingShortcut")]
+ pub stop_recording_shortcut: String,
+ #[serde(rename = "startAudioShortcut")]
+ pub start_audio_shortcut: String,
+ #[serde(rename = "stopAudioShortcut")]
+ pub stop_audio_shortcut: String,
+ #[serde(rename = "pipeShortcuts")]
+ pub pipe_shortcuts: HashMap<String, String>,
+ #[serde(rename = "enableRealtimeAudioTranscription")]
+ pub enable_realtime_audio_transcription: bool,
+ #[serde(rename = "realtimeAudioTranscriptionEngine")]
+ pub realtime_audio_transcription_engine: String,
+ #[serde(rename = "disableVision")]
+ pub disable_vision: bool,
+ #[serde(rename = "useAllMonitors")]
+ pub use_all_monitors: bool,
+ #[serde(rename = "enableRealtimeVision")]
+ pub enable_realtime_vision: bool,
+}
+
+#[derive(Serialize, Deserialize, Type,Clone)]
+pub enum AIProviderType {
+ #[serde(rename = "openai")]
+ OpenAI,
+ #[serde(rename = "native-ollama")]
+ NativeOllama,
+ #[serde(rename = "custom")]
+ Custom,
+ #[serde(rename = "screenpipe-cloud")]
+ ScreenpipeCloud,
+}
+
+#[derive(Serialize, Deserialize,Type,Clone)]
+pub struct AIPreset {
+ pub id: String,
+ pub prompt: String,
+ pub provider: AIProviderType,
+ pub url: String,
+ pub model: String,
+ #[serde(rename = "defaultPreset")]
+ pub default_preset: bool,
+ #[serde(rename = "apiKey")]
+ pub api_key: Option<String>,
+ #[serde(rename = "maxContextChars")]
+ pub max_context_chars: u32,
+}
+
+#[derive(Serialize, Deserialize,Type,Clone)]
+pub struct User {
+ pub id: Option<String>,
+ pub name: Option<String>,
+ pub email: Option<String>,
+ pub image: Option<String>,
+ pub token: Option<String>,
+ pub clerk_id: Option<String>,
+ pub api_key: Option<String>,
+ pub credits: Option<Credits>,
+ pub stripe_connected: Option<bool>,
+ pub stripe_account_status: Option<String>,
+ pub github_username: Option<String>,
+ pub bio: Option<String>,
+ pub website: Option<String>,
+ pub contact: Option<String>,
+ pub cloud_subscribed: Option<bool>,
+}
+
+#[derive(Serialize, Deserialize,Type,Clone)]
+pub struct Credits {
+ pub amount: u32,
+}
+
+#[derive(Serialize, Deserialize,Type,Clone)]
+pub struct Pipe {
+ pub id: String,
+ pub name: String,
+ pub description: String,
+ pub version: String,
+ pub author: String,
+ #[serde(rename = "authorLink")]
+ pub author_link: String,
+ #[serde(rename = "repository")]
+ pub repository: String,
+ #[serde(rename = "lastUpdate")]
+ pub last_update: String,
+ #[serde(rename = "fullDescription")]
+ pub full_description: String,
+ #[serde(rename = "downloads")]
+ pub downloads: u32,
+ #[serde(rename = "mainFile")]
+ pub main_file: String,
+ pub config: HashMap<String, String>,
+}
+
+#[derive(Serialize, Deserialize,Type,Clone)]
+pub struct EmbeddedLLM {
+ pub enabled: bool,
+ pub model: String,
+ pub port: u16,
+}
+
+impl Default for SettingsStore {
+ fn default() -> Self {
+ // Default ignored windows for all OS
+ let mut ignored_windows = vec![
+ "bit".to_string(),
+ "VPN".to_string(),
+ "Trash".to_string(),
+ "Private".to_string(),
+ "Incognito".to_string(),
+ "Wallpaper".to_string(),
+ "Settings".to_string(),
+ "Keepass".to_string(),
+ "Recorder".to_string(),
+ "Vaults".to_string(),
+ "OBS Studio".to_string(),
+ "screenpipe".to_string(),
+ ];
+
+ // Add platform-specific ignored windows
+ // Note: In a real implementation, you'd detect the actual platform
+ // For now, we'll include common ones or you can detect platform here
+ #[cfg(target_os = "macos")]
+ ignored_windows.extend([
+ ".env".to_string(),
+ "Item-0".to_string(),
+ "App Icon Window".to_string(),
+ "Battery".to_string(),
+ "Shortcuts".to_string(),
+ "WiFi".to_string(),
+ "BentoBox".to_string(),
+ "Clock".to_string(),
+ "Dock".to_string(),
+ "DeepL".to_string(),
+ "Control Center".to_string(),
+ ]);
+
+ #[cfg(target_os = "windows")]
+ ignored_windows.extend([
+ "Nvidia".to_string(),
+ "Control Panel".to_string(),
+ "System Properties".to_string(),
+ ]);
+
+ #[cfg(target_os = "linux")]
+ ignored_windows.extend([
+ "Info center".to_string(),
+ "Discover".to_string(),
+ "Parted".to_string(),
+ ]);
+
+ Self {
+ ai_presets: vec![],
+ deepgram_api_key: "".to_string(),
+ is_loading: false,
+ installed_pipes: vec![],
+ user_id: "".to_string(),
+
+ dev_mode: false,
+ audio_transcription_engine: "whisper-large-v3-turbo".to_string(),
+ #[cfg(target_os = "macos")]
+ ocr_engine: "apple-native".to_string(),
+ #[cfg(target_os = "windows")]
+ ocr_engine: "windows-native".to_string(),
+ #[cfg(target_os = "linux")]
+ ocr_engine: "tesseract".to_string(),
+ monitor_ids: vec!["default".to_string()],
+ audio_devices: vec!["default".to_string()],
+ use_pii_removal: false,
+ restart_interval: 0,
+ port: 3030,
+ data_dir: "default".to_string(),
+ disable_audio: false,
+ ignored_windows,
+ included_windows: vec![],
+
+ fps: 0.5,
+ vad_sensitivity: "high".to_string(),
+ analytics_enabled: true,
+ audio_chunk_duration: 30,
+ use_chinese_mirror: false,
+ languages: vec![],
+ embedded_llm: EmbeddedLLM {
+ enabled: false,
+ model: "llama3.2:1b-instruct-q4_K_M".to_string(),
+ port: 11434
+ },
+ enable_beta: false,
+ is_first_time_user: true,
+ auto_start_enabled: true,
+ enable_frame_cache: true,
+ enable_ui_monitoring: false,
+ platform: "unknown".to_string(),
+ disabled_shortcuts: vec![],
+ user: User {
+ id: None,
+ name: None,
+ email: None,
+ image: None,
+ token: None,
+ clerk_id: None,
+ api_key: None,
+ credits: None,
+ stripe_connected: None,
+ stripe_account_status: None,
+ github_username: None,
+ bio: None,
+ website: None,
+ contact: None,
+ cloud_subscribed: None,
+ },
+ show_screenpipe_shortcut: "Super+Alt+S".to_string(),
+ start_recording_shortcut: "Super+Alt+U".to_string(),
+ stop_recording_shortcut: "Super+Alt+X".to_string(),
+ start_audio_shortcut: "".to_string(),
+ stop_audio_shortcut: "".to_string(),
+ pipe_shortcuts: HashMap::new(),
+ enable_realtime_audio_transcription: false,
+ realtime_audio_transcription_engine: "deepgram".to_string(),
+ disable_vision: false,
+ use_all_monitors: false,
+ enable_realtime_vision: true,
}
- } else {
- "default".to_string()
- };
+ }
+}
+
+impl SettingsStore {
+ pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
+ let store = get_store(app, None).unwrap();
+
+ match store.is_empty() {
+ true => Ok(None),
+ false => {
+ let settings = serde_json::from_value(store.get("settings").unwrap_or(Value::Null));
+ match settings {
+ Ok(settings) => Ok(settings),
+ Err(e) => {
+ error!("Failed to deserialize settings: {}", e);
+ Err(e.to_string())
+ }
+ }
+ }
+ }
+ }
- debug!("Using settings profile: {}", profile);
+ pub fn update(app: &AppHandle, update: impl FnOnce(&mut SettingsStore)) -> Result<(), String> {
+ let Ok(store) = get_store(app, None) else {
+ return Err("Failed to get store".to_string());
+ };
- // Determine store file path based on profile
- let store_path = if profile == "default" {
- base_dir.join("store.bin")
- } else {
- base_dir.join(format!("store-{}.bin", profile))
+ let mut settings = Self::get(app)?.unwrap();
+ update(&mut settings);
+ store.set("settings", json!(settings));
+ Ok(())
+ }
+
+ pub fn save(&self,app: &AppHandle) -> Result<(), String> {
+ let Ok(store) = get_store(app, None) else {
+ return Err("Failed to get store".to_string());
+ };
+
+ store.set("settings", json!(self));
+ store.save().map_err(|e| e.to_string())
+ }
+}
+
+pub fn init_store(app: &AppHandle) -> Result<SettingsStore, String> {
+ println!("Initializing settings store");
+
+ let store = match SettingsStore::get(app) {
+ Ok(Some(store)) => store,
+ Ok(None) => SettingsStore::default(),
+
+ Err(e) => {
+ error!("Failed to get settings store: {}", e);
+ return Err(e);
+ }
};
- // Build and return the store wrapped in Arc
- StoreBuilder::new(app, store_path)
- .build()
- .map_err(|e| anyhow::anyhow!(e))
+ store.save(app).unwrap();
+ Ok(store)
}
+
+pub fn init_onboarding_store(app: &AppHandle) -> Result<OnboardingStore, String> {
+ println!("Initializing onboarding store");
+
+ let onboarding = match OnboardingStore::get(app) {
+ Ok(Some(onboarding)) => onboarding,
+ Ok(None) => OnboardingStore::default(),
+
+ Err(e) => {
+ error!("Failed to get onboarding store: {}", e);
+ return Err(e);
+ }
+ };
+
+ onboarding.save(app).unwrap();
+ Ok(onboarding)
+}
\ No newline at end of file
diff --git a/openrewind/src-tauri/src/window_api.rs b/openrewind/src-tauri/src/window_api.rs
index 9d1682561..3b707b9cc 100644
--- a/openrewind/src-tauri/src/window_api.rs
+++ b/openrewind/src-tauri/src/window_api.rs
@@ -1,6 +1,8 @@
+use std::{path::PathBuf, str::FromStr};
+
use axum::{extract::State, http::StatusCode, Json};
use serde::{Deserialize, Serialize};
-use tauri::Manager;
+use tauri::{AppHandle, LogicalSize, Manager, Size, WebviewUrl, WebviewWindow, WebviewWindowBuilder, Wry};
use tracing::{error, info};
use crate::ServerState;
@@ -129,3 +131,189 @@ pub async fn close_window(
))
}
}
+
+pub enum RewindWindowId {
+ Main,
+ Settings,
+ Search,
+ Onboarding,
+}
+
+impl FromStr for RewindWindowId {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "main" => Ok(RewindWindowId::Main),
+ "settings" => Ok(RewindWindowId::Settings),
+ "search" => Ok(RewindWindowId::Search),
+ "onboarding" => Ok(RewindWindowId::Onboarding),
+ _ => Ok(RewindWindowId::Main),
+ }
+ }
+}
+
+impl std::fmt::Display for RewindWindowId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ RewindWindowId::Main => write!(f, "main"),
+ RewindWindowId::Settings => write!(f, "settings"),
+ RewindWindowId::Search => write!(f, "search"),
+ RewindWindowId::Onboarding => write!(f, "onboarding"),
+ }
+ }
+}
+
+impl RewindWindowId {
+ pub fn label(&self) -> &str {
+ match self {
+ RewindWindowId::Main => "main",
+ RewindWindowId::Settings => "settings",
+ RewindWindowId::Search => "search",
+ RewindWindowId::Onboarding => "onboarding",
+ }
+ }
+
+ pub fn title(&self) -> &str {
+ match self {
+ RewindWindowId::Main => "openrewind",
+ RewindWindowId::Settings => "settings",
+ RewindWindowId::Search => "search",
+ RewindWindowId::Onboarding => "onboarding",
+ }
+ }
+
+ pub fn url(&self) -> &str {
+ match self {
+ RewindWindowId::Main => "/",
+ RewindWindowId::Settings => "/settings",
+ RewindWindowId::Search => "/search",
+ RewindWindowId::Onboarding => "/onboarding",
+ }
+ }
+
+ pub fn min_size(&self) -> Option<(f64, f64)> {
+ Some(match self {
+ RewindWindowId::Main => (1200.0, 850.0),
+ RewindWindowId::Settings => (1200.0, 850.0),
+ RewindWindowId::Search => (1200.0, 850.0),
+ RewindWindowId::Onboarding => (1000.0, 640.0),
+ })
+ }
+
+ pub fn get(&self, app: &AppHandle<Wry>) -> Option<WebviewWindow> {
+ let label = self.label();
+ app.get_webview_window(&label)
+ }
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone,specta::Type)]
+pub enum ShowRewindWindow {
+ Main,
+ Settings { page: Option<String> },
+ Search,
+ Onboarding,
+}
+
+impl ShowRewindWindow {
+ fn window_builder<'a>(
+ &'a self,
+ app: &'a AppHandle<Wry>,
+ url: impl Into<PathBuf>,
+ ) -> WebviewWindowBuilder<'a, Wry, AppHandle<Wry>> {
+ let id = self.id();
+
+ let mut builder = WebviewWindow::builder(app, id.label(), WebviewUrl::App(url.into()))
+ .title(id.title())
+ .visible(true)
+ .accept_first_mouse(true)
+ .shadow(true);
+
+ // This is for windows to have minimum size
+ // if let Some(min) = id.min_size() {
+ // builder = builder
+ // .inner_size(min.0, min.1)
+ // .min_inner_size(min.0, min.1);
+ // }
+
+ #[cfg(target_os = "macos")]
+ {
+ builder = builder
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay);
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ // builder = builder.decorations(false);
+ builder = builder
+ }
+
+ builder
+ }
+
+ pub fn id(&self) -> RewindWindowId {
+ match self {
+ ShowRewindWindow::Main => RewindWindowId::Main,
+ ShowRewindWindow::Settings { page: _ } => RewindWindowId::Settings,
+ ShowRewindWindow::Search => RewindWindowId::Search,
+ ShowRewindWindow::Onboarding => RewindWindowId::Onboarding,
+ }
+ }
+
+ pub fn show(&self, app: &AppHandle) -> tauri::Result<WebviewWindow> {
+ let id = self.id();
+
+ if let Some(window) = id.get(app) {
+ info!("showing window: {:?}", id.label());
+ window.show().ok();
+ return Ok(window);
+ }
+
+ info!("showing window: {:?} (not found)", id.label());
+
+
+ let window = match self {
+ ShowRewindWindow::Main => {
+ let builder = self.window_builder(app, "/").hidden_title(true).focused(true);
+ let window = builder.build()?;
+
+ window
+ }
+ ShowRewindWindow::Settings { page: _ } => {
+ let builder = self.window_builder(app, "/settings").hidden_title(true).focused(true);
+ let window = builder.build()?;
+ window
+ }
+ ShowRewindWindow::Search => {
+ let builder = self.window_builder(app, "/search");
+ let window = builder.build()?;
+ window
+ }
+ ShowRewindWindow::Onboarding => {
+ let builder = self.window_builder(app, "/onboarding").visible_on_all_workspaces(true).always_on_top(true).inner_size(1000.0, 750.0);
+ let window = builder.build()?;
+ window
+ }
+ };
+
+ Ok(window)
+ }
+
+ pub fn close(&self, app: &AppHandle) -> tauri::Result<()> {
+ let id = self.id();
+ if let Some(window) = id.get(app) {
+ window.close().ok();
+ }
+ Ok(())
+ }
+
+ pub fn set_size(&self, app: &AppHandle, width: f64, height: f64) -> tauri::Result<()> {
+ let size = Size::Logical(LogicalSize::new(width, height));
+ let id = self.id();
+ if let Some(window) = id.get(app) {
+ window.set_size(size).ok();
+ }
+ Ok(())
+ }
+}
diff --git a/openrewind/src-tauri/tauri.conf.json b/openrewind/src-tauri/tauri.conf.json
index a83472141..7d2ee97e7 100644
--- a/openrewind/src-tauri/tauri.conf.json
+++ b/openrewind/src-tauri/tauri.conf.json
@@ -105,14 +105,6 @@
"iconPath": "assets/screenpipe-logo-tray-white.png",
"iconAsTemplate": true
},
- "windows": [
- {
- "title": "openrewind",
- "width": 1200,
- "height": 850,
- "resizable": true
- }
- ],
"security": {
"assetProtocol": {
"enable": true,