Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix: Pi agent auto-restart on crash + better error messages

Louis Beaumontce65ecde3d30
diff --git a/Cargo.lock b/Cargo.lock
index 0e09af120..515fd1107 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3676,7 +3676,7 @@ source = "git+https://github.com/Neptune650/knf-rs.git#b782e6bb02db495ce767f0094
dependencies = [
"eyre",
"knf-rs-sys",
- "ndarray 0.16.1",
+ "ndarray",
]
[[package]]
@@ -4246,19 +4246,6 @@ dependencies = [
"tempfile",
]
-[[package]]
-name = "ndarray"
-version = "0.15.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "adb12d4e967ec485a5f71c6311fe28158e9d6f4bc4a447b474184d0f91a8fa32"
-dependencies = [
- "matrixmultiply",
- "num-complex",
- "num-integer",
- "num-traits",
- "rawpointer",
-]
-
[[package]]
name = "ndarray"
version = "0.16.1"
@@ -5122,7 +5109,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5f95fe501e1cb81dec2f66ee3129025759b602817aa2c77ff421390c418cc34"
dependencies = [
"half",
- "ndarray 0.16.1",
+ "ndarray",
"ort-sys",
"tracing",
]
@@ -6062,16 +6049,6 @@ dependencies = [
"realfft",
]
-[[package]]
-name = "rust-stemmers"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54"
-dependencies = [
- "serde",
- "serde_derive",
-]
-
[[package]]
name = "rustc-demangle"
version = "0.1.24"
@@ -6380,7 +6357,7 @@ dependencies = [
"libpulse-simple-binding",
"libsamplerate-sys",
"log",
- "ndarray 0.16.1",
+ "ndarray",
"oasgen",
"objc",
"once_cell",
@@ -6549,14 +6526,12 @@ dependencies = [
"lru",
"md5",
"moka",
- "ndarray 0.15.6",
"nix 0.29.0",
"oasgen",
"once_cell",
"port_check",
"regex",
"reqwest 0.12.12",
- "rust-stemmers",
"screenpipe-accessibility",
"screenpipe-apple-intelligence",
"screenpipe-audio",
@@ -8594,7 +8569,7 @@ version = "0.2.0"
source = "git+https://github.com/screenpipe/vad-rs-1.git#3af3b1829ab4d8f018f271fe53c6f382f15ca3a6"
dependencies = [
"eyre",
- "ndarray 0.16.1",
+ "ndarray",
"ort",
"ort-sys",
"ringbuffer",
diff --git a/apps/screenpipe-app-tauri/components/onboarding/api-setup.tsx b/apps/screenpipe-app-tauri/components/onboarding/api-setup.tsx
deleted file mode 100644
index 33e0ccd46..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/api-setup.tsx
+++ /dev/null
@@ -1,194 +0,0 @@
-import React, { useEffect, useRef } from "react";
-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 { open } from "@tauri-apps/plugin-shell";
-
-import OnboardingNavigation from "@/components/onboarding/navigation";
-import { AIPresets } from "../settings/ai-presets";
-
-interface OnboardingAPISetupProps {
- className?: string;
- handleNextSlide: () => void;
- handlePrevSlide: () => void;
-}
-
-const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({
- className,
- handleNextSlide,
- handlePrevSlide,
-}) => {
- const { toast } = useToast();
- const { settings } = useSettings();
- const [isValidating, setIsValidating] = React.useState(false);
- const containerRef = useRef<HTMLDivElement>(null);
-
- // Add effect to scroll to top when component mounts
- useEffect(() => {
- if (containerRef.current) {
- containerRef.current.scrollTo({
- top: 0,
- behavior: "auto"
- });
- }
- }, []);
-
- // Check if at least one preset exists and has required fields
- const hasValidPreset = React.useMemo(() => {
- 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];
-
- if (!defaultPreset) return false;
-
- // Check if the preset has the required fields
- const { url, model, provider } = defaultPreset;
- const isApiKeyRequired =
- url !== "https://api.screenpi.pe/v1" &&
- url !== "http://localhost:11434/v1";
-
- // Check if API key is required and present
- const hasRequiredApiKey = !isApiKeyRequired ||
- provider === "pi" ||
- ((provider === "openai" || provider === "custom") &&
- "apiKey" in defaultPreset &&
- defaultPreset.apiKey?.trim() !== "");
-
- return url?.trim() !== "" &&
- model?.trim() !== "" &&
- hasRequiredApiKey;
- }, [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];
-
- if (!defaultPreset) {
- toast({
- title: "No AI preset found",
- description: "Please create at least one AI preset",
- variant: "destructive",
- });
- setIsValidating(false);
- return false;
- }
-
- const { url, model, provider } = defaultPreset;
-
- // Get API key if available based on provider
- const apiKey = (provider === "openai" || provider === "custom") && "apiKey" in defaultPreset
- ? defaultPreset.apiKey
- : "";
-
- const t = toast({
- title: "Validating AI provider",
- description: "Please wait...",
- duration: 10000,
- });
-
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- Authorization: `Bearer ${apiKey}`,
- };
-
- const response = await fetch(`${url}/chat/completions`, {
- method: "POST",
- headers,
- body: JSON.stringify({
- model: model,
- messages: [
- {
- role: "user",
- content: "You are a helpful assistant that tells short jokes.",
- },
- ],
- max_tokens: 5,
- }),
- });
-
- t.dismiss();
-
- if (!response.ok) {
- const errorData = await response.json();
- toast({
- title: "Error validating AI provider",
- description: errorData.error?.message || "Unknown error",
- variant: "destructive",
- });
- setIsValidating(false);
- return false;
- }
-
- toast({
- title: "AI provider validated successfully",
- description: "You're all set!",
- });
-
- setIsValidating(false);
- handleNextSlide();
- return true;
- } catch (error) {
- toast({
- title: "Error validating AI provider",
- description: error instanceof Error ? error.message : "Unknown error",
- variant: "destructive",
- });
- setIsValidating(false);
- return false;
- }
- };
-
- return (
- <div
- ref={containerRef}
- className={`${className} w-full flex flex-col items-center relative max-h-full overflow-y-auto`}>
- <div className="flex flex-col items-center justify-start w-full overflow-visible pt-4">
- <div className="flex flex-col px-2 justify-center items-center">
- <img
- className="w-24 h-24 justify-center"
- src="/128x128.png"
- alt="screenpipe-logo"
- />
- <h1 className="text-center text-2xl text-text-primary">
- setup your ai settings
- </h1>
- </div>
- <div className="mt-4 h-full w-full">
- <CardContent className="flex flex-col items-center space-y-4 h-full">
- <AIPresets />
- <a
- onClick={() =>
- open("https://github.com/ollama/ollama?tab=readme-ov-file#ollama")
- }
- href="#"
- className="text-text-secondary text-sm !text-center hover:underline hover:text-text-primary transition-colors"
- >
- don&apos;t have api key ? set up ollama locally
- <ArrowUpRight className="inline w-4 h-4 ml-1" />
- </a>
- </CardContent>
- </div>
-
- </div>
- <OnboardingNavigation
- className="pt-8"
- isLoading={isValidating}
- handlePrevSlide={handlePrevSlide}
- handleNextSlide={
- hasValidPreset
- ? handleValidationMoveNextSlide
- : handleNextSlide
- }
- prevBtnText="previous"
- nextBtnText={hasValidPreset ? "setup" : "i'll setup later"}
- />
- </div>
- );
-};
-
-export default OnboardingAPISetup;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/dev-configuration.tsx b/apps/screenpipe-app-tauri/components/onboarding/dev-configuration.tsx
deleted file mode 100644
index 8d97c9ad1..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/dev-configuration.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import React, { useEffect, useState } from "react";
-import { ArrowUpRight } from "lucide-react";
-import { open } from "@tauri-apps/plugin-shell";
-import { platform } from "@tauri-apps/plugin-os";
-import { CodeBlock } from "@/components/onboarding/single-codeblock";
-import { DialogHeader, DialogTitle } from "@/components/ui/dialog";
-import OnboardingNavigation from "@/components/onboarding/navigation";
-
-interface OnboardingDevConfigProps {
- className?: string;
- handlePrevSlide: () => void;
- handleNextSlide: () => void;
-}
-
-interface devInstructionsItemsTypes {
- label: string;
- description: string;
- command: string;
-}
-
-type devInstructionItems = Record<string, devInstructionsItemsTypes[]>;
-
-const OnboardingDevConfig: React.FC<OnboardingDevConfigProps> = ({
- className = "",
- handlePrevSlide,
- handleNextSlide,
-}) => {
- const [instructions, setInstructions] = useState<devInstructionsItemsTypes[]>(
- []
- );
-
- const devInstructionsData: devInstructionItems = {
- windows: [
- {
- label: "to start using the screenpipe cli,",
- description:
- "to use the screenpipe cli, open your cmd with admin privileges and navigate to '%LOCALAPPDATA%\\screenpipe' or run this command to view all setup arguments",
- command:
- "cd %LOCALAPPDATA%\\screenpipe && ./screenpipe.exe -h # shows list of arguments",
- },
- {
- label: "starting screenpipe with custom arguments,",
- description:
- "after reviewing the cli arguments, choose your setup options and start screenpipe with your preference. replace arguments as needed. for example:",
- command:
- "screenpipe --ignored-windows settings # ignore the windows named settings",
- },
- ],
- macos: [
- {
- label: "to start using the screenpipe cli,",
- description:
- "to use the screenpipe cli, open your terminal and navigate to '/Applications/screenpipe.app/Contents/MacOS/' or run this command to view all setup arguments",
- command:
- "cd /Applications/screenpipe.app/Contents/MacOS/ && screenpipe -h # shows help",
- },
- {
- label: "starting screenpipe with custom arguments",
- description:
- "after reviewing the cli arguments, choose your setup options and start screenpipe with your preference. replace arguments as needed. for example:",
- command: "screenpipe --list-monitors # list monitors",
- },
- ],
- linux: [
- {
- label: "to start using the screenpipe cli,",
- description:
- "open your terminal and navigate to the installation directory (usually /usr/local/bin) or run this command, this will show all arguments to setup screenpipe as you prefer.",
- command:
- "cd /usr/local/bin/ && screenpipe -h # shows list of arguments",
- },
- {
- label: "starting screenpipe with custom arguments",
- description:
- "after reviewing the cli arguments, choose your setup options and start screenpipe with your preference. replace arguments as needed. for example:",
- command:
- "screenpipe --ignored-windows kitty # ignore the windows named kitty",
- },
- ],
- };
-
- useEffect(() => {
- const getOsType = () => {
- const os = platform();
- setInstructions(devInstructionsData[os] || []);
- };
- getOsType();
- }, []);
-
- return (
- <div className={`${className} w-full flex justify-center flex-col`}>
- <DialogHeader className="flex flex-col px-2 justify-center items-center">
- <img
- className="w-24 h-24 justify-center"
- src="/128x128.png"
- alt="screenpipe-logo"
- />
- <DialogTitle className="text-center text-2xl text-text-primary">
- screenpipe in dev mode
- </DialogTitle>
- </DialogHeader>
- <div className="mt-8 w-full flex justify-around flex-col">
- <div className="mx-3">
- <p className="text-text-secondary text-[14px]">
- <span className="font-medium prose text-[14px] mr-1 text-text-primary">
- by using the cli,
- </span>
- you can manually configure and manage backend processes for advanced
- customization and debugging.
- </p>
- </div>
- {instructions.length > 0 && (
- <div className="mx-3 mt-1">
- <h1 className="font-medium text-md text-text-primary">
- run the screenpipe backend via cli:
- </h1>
- <ul className="mt-0">
- {instructions.map((instructions, index) => (
- <li key={index} className="list-disc mt-1">
- <p className="text-text-secondary text-sm ml-4">
- <span className="font-medium text-nowrap text-[14px] mr-1 prose text-text-primary">
- {instructions.label}
- </span>
- {instructions.description}
- </p>
- <CodeBlock
- className="rounded-md mt-2"
- language="bash"
- value={instructions.command}
- />
- </li>
- ))}
- </ul>
- </div>
- )}
- <a
- onClick={() => open("https://docs.screenpi.pe/")}
- href="#"
- className="mt-4 text-text-secondary text-sm mr-auto ml-auto !text-center hover:underline"
- >
- learn more about screenpipe args &amp; api
- <ArrowUpRight className="inline w-4 h-4 ml-1 " />
- </a>
- </div>
- <p className="text-xs text-text-secondary text-center mt-2">
- note: if you use dev mode, you will have to start and maintain the
- recording process yourself in the terminal
- </p>
- <OnboardingNavigation
- className="mt-6"
- handlePrevSlide={handlePrevSlide}
- handleNextSlide={handleNextSlide}
- prevBtnText="previous"
- nextBtnText="next"
- />
- </div>
- );
-};
-
-export default OnboardingDevConfig;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/dev-or-non-dev.tsx b/apps/screenpipe-app-tauri/components/onboarding/dev-or-non-dev.tsx
deleted file mode 100644
index 141cf627d..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/dev-or-non-dev.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import React, { useState } from "react";
-import { Info } from "lucide-react";
-import { Wrench, UserRound } from "lucide-react";
-import { useToast } from "@/components/ui/use-toast";
-import { useSettings } from "@/lib/hooks/use-settings";
-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;
- handleNextSlide: () => void;
- handlePrevSlide: () => void;
- handleOptionClick: (option: string) => void;
- selectedPreference?: string | null;
-}
-
-const DEV_OPTIONS = [
- {
- key: "nonDevMode",
- icon: UserRound,
- title: "standard mode",
- description:
- "screenpipe takes care of everything for you, making it easy and stress-free.",
- },
- {
- key: "devMode",
- icon: Wrench,
- title: "dev mode",
- description:
- "run the CLI on top of the UI, and customize screenpipe to fit your needs.",
- },
-];
-
-const CardItem: React.FC<{
- isSelected: boolean;
- onClick: () => void;
- option: (typeof DEV_OPTIONS)[number];
-}> = ({ option, isSelected, onClick }) => {
- const { icon: Icon, title, description } = option;
-
- return (
- <div className="relative group h-64">
- <div
- className={`absolute inset-0 rounded-lg transition-transform duration-300 ease-out group-hover:scale-105`}
- />
- <Card
- className={`p-4 h-64 mt-[-5px] cursor-pointer bg-card transition-transform duration-300 ease-out group-hover:scale-105
- ${isSelected ? "bg-accent" : ""}`}
- onClick={onClick}
- >
- <CardContent className="flex flex-col w-60 justify-start">
- <Icon className="w-12 h-12 mx-auto text-text-primary" />
- <h2 className="font-semibold text-xl text-center mt-1 text-text-primary">{title}</h2>
- <span className="text-sm mt-0 text-text-secondary">{description}</span>
- </CardContent>
- </Card>
- </div>
- );
-};
-
-const OnboardingDevOrNonDev: React.FC<OnboardingDevOrNonDevProps> = ({
- className = "",
- selectedPreference = "",
- handleOptionClick,
- handleNextSlide,
- handlePrevSlide,
-}) => {
- const { toast } = useToast();
- const { settings, updateSettings } = useSettings();
- const [localSettings, setLocalSettings] = useState(settings);
-
- const handleNextWithPreference = async (option: string) => {
- try {
- if (option === "devMode") {
- await updateSettings({ devMode: true });
- setLocalSettings({ ...localSettings, devMode: true } as SettingsStore);
- toast({
- title: "success",
- description: "dev mode enabled successfully",
- variant: "default",
- });
- } else if (option === "nonDevMode") {
- await updateSettings({ devMode: false });
- setLocalSettings({ ...localSettings, devMode: false } as SettingsStore);
- toast({
- title: "success",
- description: "screenpipe backend is in standard mode",
- variant: "default",
- });
- // TODO: should give better user feedback
- await invoke("spawn_screenpipe");
- }
- } catch (error: any) {
- toast({
- title: "error",
- description: error,
- variant: "destructive",
- });
- }
- };
-
- return (
- <div
- className={`${className} w-full flex justify-around flex-col relative`}
- >
- <DialogHeader className="flex flex-col px-2 justify-center items-center">
- <img
- className="w-24 h-24 justify-center"
- src="/128x128.png"
- alt="screenpipe-logo"
- />
- <DialogTitle className="text-center text-2xl text-text-primary">
- how do you prefer to use screenpipe?
- </DialogTitle>
- </DialogHeader>
- <div className="flex w-full justify-around mt-12">
- {DEV_OPTIONS.map((option) => (
- <CardItem
- key={option.key}
- option={option}
- isSelected={selectedPreference === option.key}
- onClick={() => handleOptionClick(option.key)}
- />
- ))}
- </div>
-
- <OnboardingNavigation
- className="mt-9"
- nextBtnText="next"
- prevBtnText="previous"
- handlePrevSlide={handlePrevSlide}
- handleNextSlide={async () => {
- if (selectedPreference) {
- await handleNextWithPreference(selectedPreference);
- }
- handleNextSlide();
- }}
- />
- </div>
- );
-};
-
-export default OnboardingDevOrNonDev;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/explain-instructions.tsx b/apps/screenpipe-app-tauri/components/onboarding/explain-instructions.tsx
deleted file mode 100644
index cbfc6c339..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/explain-instructions.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-import React from "react";
-import { Button } from "@/components/ui/button";
-import { RainbowButton } from "../ui/rainbow-button";
-import {
- ArrowLeft,
- ArrowRight,
- Video,
- Mic,
- Search,
- Clock,
- Settings,
- Bot,
- MonitorSpeaker
-} from "lucide-react";
-import { motion } from "framer-motion";
-import { Card, CardContent } from "@/components/ui/card";
-
-interface OnboardingInstructionsProps {
- className?: string;
- handleNextSlide: () => void;
- handlePrevSlide: () => void;
-}
-
-const OnboardingInstructions: React.FC<OnboardingInstructionsProps> = ({
- className = "",
- handleNextSlide,
- handlePrevSlide,
-}) => {
- const steps = [
- {
- icon: MonitorSpeaker,
- title: "Background Recording",
- description: "screenpipe 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: "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: Settings,
- title: "Customize Settings",
- description: "Adjust recording preferences, privacy settings, and AI configurations to match your workflow.",
- color: "text-orange-500"
- }
- ];
-
- const shortcuts = [
- { key: "⌘ + ⌥ + S", description: "Show/Hide screenpipe" },
- { key: "⌘ + ⌥ + U", description: "Start Recording" },
- { key: "⌘ + ⌥ + X", description: "Stop Recording" },
- ];
-
- return (
- <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 }}
- >
- <Bot className="w-8 h-8 text-white" />
- </motion.div>
- <h1 className="text-center text-2xl font-bold mb-2 text-text-primary">
- You&apos;re All Set! 🎉
- </h1>
- <p className="text-center text-text-secondary max-w-md">
- screenpipe is now configured and ready to help you remember everything. Here&apos;s how to get the most out of it.
- </p>
- </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">
- {steps.map((step, index) => (
- <motion.div
- key={index}
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: index * 0.1 }}
- className="bg-card border border-border rounded-xl p-4 text-center"
- >
- <div className="flex items-center justify-center mb-3">
- <step.icon className={`w-8 h-8 ${step.color}`} />
- </div>
- <h3 className="font-semibold text-sm mb-1 text-text-primary">{step.title}</h3>
- <p className="text-xs text-text-secondary">{step.description}</p>
- </motion.div>
- ))}
- </div>
-
- {/* Quick Tips */}
- <motion.div
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: 0.4 }}
- 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 border border-border"
- >
- <div className="flex items-center justify-center mb-4">
- <Settings className="w-5 h-5 text-orange-500 mr-2" />
- <h3 className="text-lg font-semibold text-text-primary">Quick Tips</h3>
- </div>
- <ul className="space-y-2 text-sm">
- {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-text-secondary">{shortcut.key} - {shortcut.description}</span>
- </li>
- ))}
- </ul>
- </motion.div>
-
- {/* Next Steps */}
- <motion.div
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: 0.6 }}
- className="text-center"
- >
- <p className="text-sm text-text-secondary mb-4">
- Start using your computer normally. screenpipe will build your timeline in the background.
- </p>
- <div className="bg-warning-muted border border-warning rounded-lg p-3">
- <p className="text-xs text-text-primary">
- 💡 <strong>Pro tip:</strong> Come back in a few minutes to see your first recorded activities!
- </p>
- </div>
- </motion.div>
- </div>
-
- <div className="flex justify-center gap-4 mt-6">
- <Button
- variant="ghost"
- onClick={handlePrevSlide}
- className="text-text-secondary hover:text-text-primary"
- >
- Back
- </Button>
- <RainbowButton onClick={handleNextSlide}>
- Start Using screenpipe
- <ArrowRight className="w-4 h-4 ml-2" />
- </RainbowButton>
- </div>
- </div>
- );
-};
-
-export default OnboardingInstructions;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/introduction.tsx b/apps/screenpipe-app-tauri/components/onboarding/introduction.tsx
deleted file mode 100644
index 50565225c..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/introduction.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import React from "react";
-import { Button } from "@/components/ui/button";
-import { ArrowRight, Video, Mic, Brain, Clock } from "lucide-react";
-import { motion } from "framer-motion";
-
-interface OnboardingIntroProps {
- className?: string;
- handleNextSlide: () => void;
-}
-
-const OnboardingIntro: React.FC<OnboardingIntroProps> = ({
- className = "",
- handleNextSlide,
-}) => {
- const features = [
- {
- icon: Video,
- title: "records your screen",
- description: "captures everything you see and do on your computer",
- },
- {
- icon: Mic,
- title: "captures audio",
- description: "records conversations, meetings, and all audio interactions",
- },
- {
- icon: Clock,
- title: "creates a timeline",
- description: "organizes everything into an easy-to-navigate visual timeline",
- },
- {
- icon: Brain,
- title: "ai-powered search",
- description: "ask questions about your recorded data using AI",
- }
- ];
-
- return (
- <div className={`flex justify-center items-center flex-col space-y-8 ${className}`}>
- <div className="flex flex-col px-2 justify-center items-center">
- <motion.img
- className="w-24 h-24 justify-center"
- src="/128x128.png"
- alt="screenpipe-logo"
- initial={{ scale: 0.8, opacity: 0 }}
- animate={{ scale: 1, opacity: 1 }}
- transition={{ duration: 0.5 }}
- />
- <h1 className="text-center text-3xl font-mono font-bold text-foreground mt-4">
- screenpipe
- </h1>
- <p className="text-center text-sm font-mono text-muted-foreground mt-2">
- memory infrastructure for your computer
- </p>
- <div className="mt-3 px-3 py-1.5 border border-border bg-card">
- <span className="text-xs font-mono text-muted-foreground tracking-wide">
- 100% local • open source
- </span>
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-4 max-w-2xl">
- {features.map((feature, index) => (
- <motion.div
- key={index}
- className="bg-card border border-border p-5 hover:bg-foreground hover:text-background transition-all duration-150 group"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: index * 0.1 }}
- >
- <feature.icon className="w-6 h-6 text-foreground group-hover:text-background mb-3" strokeWidth={1.5} />
- <h3 className="font-mono text-sm mb-1 text-foreground group-hover:text-background">{feature.title}</h3>
- <p className="font-mono text-xs text-muted-foreground group-hover:text-background/70">{feature.description}</p>
- </motion.div>
- ))}
- </div>
-
- <div className="border border-border p-6 max-w-md">
- <h3 className="font-mono text-sm text-center mb-4 text-foreground">how it works</h3>
- <div className="flex items-center justify-center space-x-4 font-mono text-xs">
- <div className="flex items-center space-x-2">
- <Video className="w-4 h-4 text-foreground" strokeWidth={1.5} />
- <span className="text-foreground">record</span>
- </div>
- <span className="text-muted-foreground">→</span>
- <div className="flex items-center space-x-2">
- <Clock className="w-4 h-4 text-foreground" strokeWidth={1.5} />
- <span className="text-foreground">timeline</span>
- </div>
- <span className="text-muted-foreground">→</span>
- <div className="flex items-center space-x-2">
- <Brain className="w-4 h-4 text-foreground" strokeWidth={1.5} />
- <span className="text-foreground">search</span>
- </div>
- </div>
- </div>
-
- <Button
- onClick={handleNextSlide}
- size="lg"
- >
- get started
- <ArrowRight className="w-4 h-4 ml-2" strokeWidth={1.5} />
- </Button>
- </div>
- );
-};
-
-export default OnboardingIntro;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/login.tsx b/apps/screenpipe-app-tauri/components/onboarding/login.tsx
deleted file mode 100644
index 02544fe8c..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/login.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import React from "react";
-import { ExternalLinkIcon, UserCog, CheckCircle2 } from "lucide-react";
-import { open } from "@tauri-apps/plugin-shell";
-import { Button } from "@/components/ui/button";
-import { useSettings } from "@/lib/hooks/use-settings";
-import { toast } from "@/components/ui/use-toast";
-import posthog from "posthog-js";
-
-interface OnboardingLoginProps {
- className?: string;
- handlePrevSlide: () => void;
- handleNextSlide: () => void;
-}
-
-const OnboardingLogin: React.FC<OnboardingLoginProps> = ({
- className = "",
- handlePrevSlide,
- handleNextSlide,
-}) => {
- const { settings, updateSettings } = useSettings();
- const isLoggedIn = !!settings?.user?.token;
-
- const handleSkip = () => {
- posthog.capture("onboarding_login_skipped");
- handleNextSlide();
- };
-
- const handleContinue = () => {
- posthog.capture("onboarding_login_completed", {
- email: settings?.user?.email,
- });
- handleNextSlide();
- };
-
- return (
- <div className={`w-full h-full flex flex-col items-center justify-center space-y-6 py-4 ${className}`}>
- <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 tracking-tight">welcome to screenpipe</h1>
- <p className="text-sm text-muted-foreground">
- 100% local. your data never leaves your device.
- </p>
- </div>
-
- <div className="p-6 border border-border rounded-lg bg-card space-y-4">
- {isLoggedIn ? (
- <>
- <div className="flex items-center justify-center gap-2 text-sm text-foreground">
- <CheckCircle2 className="w-4 h-4" />
- signed in as {settings?.user?.email}
- </div>
- <div className="flex flex-col gap-2">
- <Button
- variant="default"
- onClick={handleContinue}
- className="w-full"
- >
- continue
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => open("https://accounts.screenpi.pe/user")}
- className="w-full text-muted-foreground"
- >
- manage account <UserCog className="w-4 h-4 ml-2" />
- </Button>
- </div>
- </>
- ) : (
- <>
- <div className="space-y-3 text-sm text-muted-foreground">
- <p className="font-medium text-foreground">no account needed to use screenpipe</p>
- <p className="text-xs">
- optional sign in unlocks: cloud AI, settings sync, priority support
- </p>
- </div>
-
- <div className="flex flex-col gap-2 pt-2">
- <Button
- variant="default"
- onClick={handleSkip}
- className="w-full"
- >
- continue without account
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => open("https://screenpi.pe/login")}
- className="w-full text-muted-foreground"
- >
- sign in (optional) <ExternalLinkIcon className="w-4 h-4 ml-2" />
- </Button>
- </div>
- </>
- )}
- </div>
-
- <p className="text-xs text-center text-muted-foreground">
- your data stays on your device.
- </p>
- </div>
- </div>
- );
-};
-
-export default OnboardingLogin;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/navigation.tsx b/apps/screenpipe-app-tauri/components/onboarding/navigation.tsx
deleted file mode 100644
index 173a27dec..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/navigation.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import React from 'react';
-import { Button } from '@/components/ui/button';
-import { ArrowLeft, ArrowRight } from 'lucide-react'; // Importing icons
-
-interface OnboardingNavigationProps {
- prevBtnText?: string,
- nextBtnText?: string,
- className?: string,
- isLoading?: boolean;
- nextDisabled?: boolean;
- handlePrevSlide: () => void;
- handleNextSlide: () => void;
-}
-
-const OnboardingNavigation: React.FC<OnboardingNavigationProps> = ({
- nextBtnText = "",
- prevBtnText = "",
- className = "",
- isLoading,
- nextDisabled,
- handlePrevSlide,
- handleNextSlide,
-}) => {
- return (
- <div className={`flex justify-between items-center mx-auto ${className} w-full p-4 bg-transparent max-w-screen-lg`}>
- <Button
- className="flex items-center w-fit min-w-32 disabled:!cursor-not-allowed disabled:!pointer-events-auto"
- variant={"outline"}
- onClick={handlePrevSlide}
- disabled={isLoading}
- >
- <ArrowLeft className="mr-2" /> {/* Icon with margin */}
- {prevBtnText}
- </Button>
- <Button
- className="flex items-center w-fit min-w-32 disabled:!cursor-not-allowed disabled:!pointer-events-auto"
- onClick={handleNextSlide}
- disabled={isLoading || nextDisabled}
- >
- {nextBtnText}
- <ArrowRight className="ml-2" /> {/* Icon with margin */}
- </Button>
- </div>
- );
-}
-export default OnboardingNavigation;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/particle-stream.tsx b/apps/screenpipe-app-tauri/components/onboarding/particle-stream.tsx
deleted file mode 100644
index b2e961a04..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/particle-stream.tsx
+++ /dev/null
@@ -1,630 +0,0 @@
-"use client";
-
-import React, { useEffect, useRef } from "react";
-import { motion } from "framer-motion";
-
-interface Props {
- progress: number;
- width?: number;
- height?: number;
- className?: string;
-}
-
-// ─── constants ───────────────────────────────────────────
-const GLITCH_CHARS =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%&*<>[]{}|/=+~";
-const TEXT_L1 = "upgrading your";
-const TEXT_L2 = "memory";
-const MEMORY_FRAGMENTS = [
- "13:42:07", "chrome", "screenshot", "meeting", "2026-02-02",
- "email_draft", "slack", "terminal", "vscode", "figma",
- "notion", "14:08:33", "recording_", "memory_03", "frame_2847",
- "audio_in", "ocr_batch", "context_q", "index_07", "recall",
-];
-
-// ─── types ───────────────────────────────────────────────
-interface Node {
- x: number; y: number;
- ring: number; // 0=outer, 1=mid, 2=inner
- activation: number; // progress threshold to activate
- brightness: number;
-}
-interface Connection {
- from: number; to: number;
- activation: number; // progress threshold
- drawProg: number; // 0→1 animated draw
- heat: number; // brightens when pulse passes
-}
-interface Pulse {
- connIdx: number;
- t: number; // 0→1 along connection
- speed: number;
- brightness: number;
-}
-interface RainCol {
- x: number;
- chars: { y: number; ch: string; speed: number; opacity: number }[];
-}
-interface TextGlyph {
- target: string;
- current: string;
- decodeFrame: number; // frame at which it decodes
- decoded: boolean;
- sourceChars: string[]; // chars from memory fragments to cycle through
- sourceIdx: number; // current position in sourceChars
-}
-interface Fragment {
- x: number; y: number;
- text: string;
- life: number; maxLife: number;
- opacity: number;
-}
-interface State {
- nodes: Node[];
- conns: Connection[];
- pulses: Pulse[];
- rain: RainCol[];
- line1: TextGlyph[];
- line2: TextGlyph[];
- frags: Fragment[];
- scanY: number;
- centerGlow: number;
- decodeFlash: number; // 0→1→0 flash when text fully decoded
-}
-
-// ─── helpers ─────────────────────────────────────────────
-const rng = () => Math.random();
-const pick = <T,>(a: T[]) => a[Math.floor(rng() * a.length)];
-const randChar = () => GLITCH_CHARS[Math.floor(rng() * GLITCH_CHARS.length)];
-const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
-const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
-
-function initState(w: number, h: number): State {
- const cx = w / 2, cy = h * 0.42;
-
- // ── nodes in 3 rings ──
- const nodes: Node[] = [];
- const rings = [
- { count: 10, radius: Math.min(w, h) * 0.44, act: 0.10 },
- { count: 8, radius: Math.min(w, h) * 0.28, act: 0.25 },
- { count: 5, radius: Math.min(w, h) * 0.13, act: 0.40 },
- ];
- rings.forEach((ring, ri) => {
- for (let i = 0; i < ring.count; i++) {
- const angle = (i / ring.count) * Math.PI * 2 + ri * 0.3;
- const jitter = ring.radius * 0.15;
- nodes.push({
- x: cx + Math.cos(angle) * ring.radius + (rng() - 0.5) * jitter,
- y: cy + Math.sin(angle) * ring.radius * 0.6 + (rng() - 0.5) * jitter * 0.6,
- ring: ri,
- activation: ring.act + rng() * 0.1,
- brightness: 0,
- });
- }
- });
-
- // ── connections: outer→mid, mid→inner, inner→center ──
- const conns: Connection[] = [];
- const byRing = (r: number) => nodes.map((n, i) => ({ n, i })).filter(x => x.n.ring === r);
- const outer = byRing(0), mid = byRing(1), inner = byRing(2);
-
- // Connect each mid node to 1-2 nearest outer nodes
- mid.forEach(m => {
- const sorted = [...outer].sort((a, b) =>
- Math.hypot(a.n.x - m.n.x, a.n.y - m.n.y) - Math.hypot(b.n.x - m.n.x, b.n.y - m.n.y)
- );
- const count = 1 + Math.floor(rng() * 2);
- for (let i = 0; i < count && i < sorted.length; i++) {
- conns.push({ from: sorted[i].i, to: m.i, activation: 0.15 + rng() * 0.15, drawProg: 0, heat: 0 });
- }
- });
- // Connect each inner node to 1-2 nearest mid nodes
- inner.forEach(n => {
- const sorted = [...mid].sort((a, b) =>
- Math.hypot(a.n.x - n.n.x, a.n.y - n.n.y) - Math.hypot(b.n.x - n.n.x, b.n.y - n.n.y)
- );
- const count = 1 + Math.floor(rng() * 2);
- for (let i = 0; i < count && i < sorted.length; i++) {
- conns.push({ from: sorted[i].i, to: n.i, activation: 0.30 + rng() * 0.15, drawProg: 0, heat: 0 });
- }
- });
- // Connect inner nodes to center point (virtual — we draw toward cx,cy)
- inner.forEach(n => {
- conns.push({ from: n.i, to: -1, activation: 0.45 + rng() * 0.1, drawProg: 0, heat: 0 });
- });
-
- // ── rain columns ──
- const rain: RainCol[] = [];
- const colCount = Math.floor(w / 28);
- for (let c = 0; c < colCount; c++) {
- const x = 8 + c * (w / colCount) + (rng() - 0.5) * 8;
- const chars: RainCol["chars"] = [];
- const count = 3 + Math.floor(rng() * 4);
- for (let i = 0; i < count; i++) {
- chars.push({
- y: rng() * h,
- ch: randChar(),
- speed: 0.3 + rng() * 0.5,
- opacity: 0.03 + rng() * 0.05,
- });
- }
- rain.push({ x, chars });
- }
-
- // ── text glyphs ──
- // Build a cycle sequence from memory fragments for each character.
- // Prefer fragments starting with the same letter, then fill from others.
- const buildSourceChars = (ch: string): string[] => {
- const upper = ch.toUpperCase();
- const chars: string[] = [];
- // chars from fragments that start with the same letter
- for (const frag of MEMORY_FRAGMENTS) {
- if (frag[0].toUpperCase() === upper) {
- for (const c of frag.toUpperCase()) {
- if (c !== "_" && !chars.includes(c)) chars.push(c);
- }
- }
- }
- // pad from other fragments so the cycle is 10+ chars long
- while (chars.length < 12) {
- const frag = pick(MEMORY_FRAGMENTS);
- const c = frag[Math.floor(rng() * frag.length)].toUpperCase();
- if (c !== "_" && !chars.includes(c)) chars.push(c);
- if (chars.length < 12 && GLITCH_CHARS.length > 0) {
- chars.push(randChar());
- }
- }
- return chars;
- };
-
- const makeGlyphs = (text: string, baseFrame: number): TextGlyph[] =>
- text.split("").map((ch, i) => {
- const src = ch === " " ? [] : buildSourceChars(ch);
- return {
- target: ch,
- current: ch === " " ? " " : src[0] || randChar(),
- decodeFrame: baseFrame + i * 4 + Math.floor(rng() * 8),
- decoded: ch === " ",
- sourceChars: src,
- sourceIdx: 0,
- };
- });
- const line1 = makeGlyphs(TEXT_L1, 30); // starts decoding ~0.5s in
- const line2 = makeGlyphs(TEXT_L2, 60); // starts ~1s in
-
- return {
- nodes, conns, pulses: [], rain,
- line1, line2,
- frags: [],
- scanY: 0,
- centerGlow: 0,
- decodeFlash: 0,
- };
-}
-
-// ─── component ───────────────────────────────────────────
-export function ParticleStream({
- progress,
- width = 420,
- height = 180,
- className = "",
-}: Props) {
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const animRef = useRef(0);
- const progressRef = useRef(progress);
- const stateRef = useRef<State | null>(null);
- const frameRef = useRef(0);
-
- useEffect(() => { progressRef.current = progress; }, [progress]);
-
- useEffect(() => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- const ctx = canvas.getContext("2d")!;
- if (!ctx) return;
-
- const dpr = window.devicePixelRatio || 1;
- canvas.width = width * dpr;
- canvas.height = height * dpr;
- ctx.scale(dpr, dpr);
-
- const state = initState(width, height);
- stateRef.current = state;
-
- const cx = width / 2, cy = height * 0.42;
-
- function draw() {
- const p = progressRef.current;
- const f = ++frameRef.current;
- const s = state;
-
- ctx.clearRect(0, 0, width, height);
-
- // ════════════════════════════════════════════════════
- // LAYER 1: Rain — faint falling characters
- // ════════════════════════════════════════════════════
- ctx.font = "9px monospace";
- ctx.textAlign = "center";
- for (const col of s.rain) {
- for (const ch of col.chars) {
- ch.y += ch.speed * (0.8 + p * 1.2);
- if (ch.y > height + 10) { ch.y = -10; ch.ch = randChar(); }
- // cycle char occasionally
- if (rng() < 0.02) ch.ch = randChar();
- const alpha = ch.opacity * (0.5 + p * 0.8);
- const gray = 120 + Math.floor(rng() * 40);
- ctx.fillStyle = `rgba(${gray},${gray},${gray},${alpha})`;
- ctx.fillText(ch.ch, col.x, ch.y);
- }
- }
-
- // ════════════════════════════════════════════════════
- // LAYER 2: Network connections
- // ════════════════════════════════════════════════════
- for (const conn of s.conns) {
- // animate draw progress
- if (p > conn.activation) {
- conn.drawProg = Math.min(1, conn.drawProg + 0.012);
- }
- conn.heat *= 0.96; // decay heat
-
- if (conn.drawProg < 0.01) continue;
-
- const fromN = s.nodes[conn.from];
- const toX = conn.to === -1 ? cx : s.nodes[conn.to].x;
- const toY = conn.to === -1 ? cy : s.nodes[conn.to].y;
-
- const dx = toX - fromN.x, dy = toY - fromN.y;
- const endX = fromN.x + dx * conn.drawProg;
- const endY = fromN.y + dy * conn.drawProg;
-
- const baseAlpha = 0.06 + conn.heat * 0.5;
- const gray = 130 + Math.floor(conn.heat * 125);
- ctx.strokeStyle = `rgba(${gray},${gray},${gray},${baseAlpha + conn.drawProg * 0.08})`;
- ctx.lineWidth = 0.5 + conn.heat * 1.5;
- ctx.beginPath();
- ctx.moveTo(fromN.x, fromN.y);
- ctx.lineTo(endX, endY);
- ctx.stroke();
- }
-
- // ════════════════════════════════════════════════════
- // LAYER 3: Data pulses
- // ════════════════════════════════════════════════════
- // spawn pulses on active connections
- if (f % Math.max(2, Math.floor(12 - p * 10)) === 0) {
- const active = s.conns.filter(c => c.drawProg > 0.8);
- if (active.length > 0) {
- const conn = pick(active);
- const ci = s.conns.indexOf(conn);
- s.pulses.push({
- connIdx: ci,
- t: 0,
- speed: 0.015 + p * 0.02 + rng() * 0.01,
- brightness: 0.6 + rng() * 0.4,
- });
- }
- }
-
- for (let i = s.pulses.length - 1; i >= 0; i--) {
- const pulse = s.pulses[i];
- pulse.t += pulse.speed;
-
- if (pulse.t > 1) {
- // heat up the connection
- s.conns[pulse.connIdx].heat = Math.min(1, s.conns[pulse.connIdx].heat + 0.5);
- s.pulses.splice(i, 1);
- continue;
- }
-
- const conn = s.conns[pulse.connIdx];
- const fromN = s.nodes[conn.from];
- const toX = conn.to === -1 ? cx : s.nodes[conn.to].x;
- const toY = conn.to === -1 ? cy : s.nodes[conn.to].y;
-
- const px = lerp(fromN.x, toX, pulse.t);
- const py = lerp(fromN.y, toY, pulse.t);
- const sz = 1.5 + pulse.brightness;
-
- // glow
- const gray = Math.floor(180 + pulse.brightness * 75);
- ctx.shadowColor = `rgba(${gray},${gray},${gray},0.8)`;
- ctx.shadowBlur = 6;
- ctx.fillStyle = `rgba(${gray},${gray},${gray},${pulse.brightness * 0.9})`;
- ctx.fillRect(px - sz / 2, py - sz / 2, sz, sz);
- ctx.shadowBlur = 0;
- }
-
- // ════════════════════════════════════════════════════
- // LAYER 4: Central singularity
- // ════════════════════════════════════════════════════
- s.centerGlow = lerp(s.centerGlow, p, 0.02);
- const g = s.centerGlow;
-
- if (g > 0.05) {
- // Radial glow
- const grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, 50 + g * 40);
- grad.addColorStop(0, `rgba(200,200,200,${g * 0.15})`);
- grad.addColorStop(0.5, `rgba(150,150,150,${g * 0.06})`);
- grad.addColorStop(1, "rgba(0,0,0,0)");
- ctx.fillStyle = grad;
- ctx.fillRect(cx - 100, cy - 80, 200, 160);
-
- // Nested rotating sharp squares
- ctx.save();
- ctx.translate(cx, cy);
- for (let sq = 0; sq < 3; sq++) {
- const size = 4 + sq * 6 + g * 8;
- const rotation = f * (0.003 + sq * 0.002) * (sq % 2 === 0 ? 1 : -1);
- const alpha = g * (0.15 - sq * 0.03);
- ctx.save();
- ctx.rotate(rotation);
- ctx.strokeStyle = `rgba(200,200,200,${alpha})`;
- ctx.lineWidth = 0.7;
- ctx.strokeRect(-size / 2, -size / 2, size, size);
- ctx.restore();
- }
- ctx.restore();
-
- // Bright core dot
- const coreAlpha = g * (0.4 + Math.sin(f * 0.05) * 0.15);
- ctx.shadowColor = `rgba(220,220,220,${coreAlpha})`;
- ctx.shadowBlur = 12 + g * 8;
- ctx.fillStyle = `rgba(230,230,230,${coreAlpha})`;
- ctx.fillRect(cx - 1.5, cy - 1.5, 3, 3);
- ctx.shadowBlur = 0;
- }
-
- // ════════════════════════════════════════════════════
- // LAYER 5: Scan line
- // ════════════════════════════════════════════════════
- s.scanY += 0.4 + p * 0.3;
- if (s.scanY > height + 2) s.scanY = -2;
-
- ctx.fillStyle = `rgba(180,180,180,${0.03 + p * 0.04})`;
- ctx.fillRect(0, s.scanY, width, 1);
- ctx.fillStyle = `rgba(150,150,150,${0.015 + p * 0.02})`;
- ctx.fillRect(0, s.scanY - 1, width, 3);
-
- // ════════════════════════════════════════════════════
- // LAYER 6: Nodes
- // ════════════════════════════════════════════════════
- for (const node of s.nodes) {
- if (p > node.activation) {
- node.brightness = Math.min(1, node.brightness + 0.02);
- }
- if (node.brightness < 0.01) continue;
-
- const nb = node.brightness;
- const pulse = 0.6 + Math.sin(f * 0.025 + node.x * 0.01) * 0.4;
- const sz = 2 + nb * 1.5;
- const gray = Math.floor(120 + nb * 100 * pulse);
- const alpha = nb * 0.5 * pulse;
-
- ctx.shadowColor = `rgba(${gray},${gray},${gray},${alpha})`;
- ctx.shadowBlur = 3;
- ctx.fillStyle = `rgba(${gray},${gray},${gray},${alpha})`;
- ctx.fillRect(node.x - sz / 2, node.y - sz / 2, sz, sz);
- ctx.shadowBlur = 0;
- }
-
- // ════════════════════════════════════════════════════
- // LAYER 7: Memory fragments (edge flashes)
- // ════════════════════════════════════════════════════
- if (p > 0.1 && f % 35 === 0 && s.frags.length < 4) {
- const edge = Math.floor(rng() * 4); // 0=top, 1=right, 2=bottom, 3=left
- let fx: number, fy: number;
- switch (edge) {
- case 0: fx = rng() * width; fy = 6; break;
- case 1: fx = width - 8; fy = rng() * height; break;
- case 2: fx = rng() * width; fy = height - 8; break;
- default: fx = 8; fy = rng() * height; break;
- }
- s.frags.push({
- x: fx, y: fy,
- text: pick(MEMORY_FRAGMENTS),
- life: 0, maxLife: 50 + Math.floor(rng() * 30),
- opacity: 0.06 + rng() * 0.08,
- });
- }
-
- ctx.font = "7px monospace";
- ctx.textAlign = "left";
- for (let i = s.frags.length - 1; i >= 0; i--) {
- const frag = s.frags[i];
- frag.life++;
- if (frag.life > frag.maxLife) { s.frags.splice(i, 1); continue; }
- const fadeIn = Math.min(1, frag.life / 8);
- const fadeOut = Math.max(0, 1 - (frag.life - frag.maxLife + 12) / 12);
- const a = frag.opacity * fadeIn * fadeOut;
- ctx.fillStyle = `rgba(150,150,150,${a})`;
- ctx.fillText(frag.text, frag.x, frag.y);
- }
-
- // ════════════════════════════════════════════════════
- // LAYER 8: Text — decode effect
- // ════════════════════════════════════════════════════
- const allDecoded1 = updateTextGlyphs(s.line1, f);
- const allDecoded2 = updateTextGlyphs(s.line2, f);
-
- // Flash when fully decoded
- if (allDecoded1 && allDecoded2 && s.decodeFlash === 0) {
- s.decodeFlash = 1;
- }
- if (s.decodeFlash > 0) {
- s.decodeFlash *= 0.96;
- if (s.decodeFlash < 0.01) s.decodeFlash = 0;
- const flashGrad = ctx.createRadialGradient(cx, cy + 10, 0, cx, cy + 10, 120);
- flashGrad.addColorStop(0, `rgba(220,220,220,${s.decodeFlash * 0.25})`);
- flashGrad.addColorStop(1, "rgba(0,0,0,0)");
- ctx.fillStyle = flashGrad;
- ctx.fillRect(0, 0, width, height);
- }
-
- // Draw line 1: "upgrading your"
- const charW1 = 8.2;
- const totalW1 = s.line1.length * charW1;
- const startX1 = cx - totalW1 / 2;
- const textY = height * 0.78;
-
- ctx.font = "600 11px monospace";
- ctx.textAlign = "left";
- for (let i = 0; i < s.line1.length; i++) {
- const gl = s.line1[i];
- const isDecoding = !gl.decoded && f > gl.decodeFrame - 10;
- const gray = gl.decoded ? 200 : (isDecoding ? 140 : 80);
- const alpha = gl.decoded ? 0.85 : (isDecoding ? 0.6 : 0.3);
-
- if (gl.decoded) {
- ctx.shadowColor = `rgba(200,200,200,0.3)`;
- ctx.shadowBlur = 4;
- }
- ctx.fillStyle = `rgba(${gray},${gray},${gray},${alpha})`;
- ctx.fillText(gl.current, startX1 + i * charW1, textY);
- ctx.shadowBlur = 0;
- }
-
- // Draw line 2: "memory"
- const charW2 = 10.5;
- const totalW2 = s.line2.length * charW2;
- const startX2 = cx - totalW2 / 2;
- const textY2 = textY + 20;
-
- ctx.font = "700 15px monospace";
- for (let i = 0; i < s.line2.length; i++) {
- const gl = s.line2[i];
- const isDecoding = !gl.decoded && f > gl.decodeFrame - 10;
- const gray = gl.decoded ? 220 : (isDecoding ? 150 : 70);
- const alpha = gl.decoded ? 0.95 : (isDecoding ? 0.6 : 0.25);
-
- if (gl.decoded) {
- ctx.shadowColor = `rgba(220,220,220,0.4)`;
- ctx.shadowBlur = 6;
- }
- ctx.fillStyle = `rgba(${gray},${gray},${gray},${alpha})`;
- ctx.fillText(gl.current, startX2 + i * charW2, textY2);
- ctx.shadowBlur = 0;
-
- // Brief flash when this char just decoded
- if (gl.decoded && f - gl.decodeFrame < 8) {
- const flashA = (1 - (f - gl.decodeFrame) / 8) * 0.4;
- ctx.shadowColor = `rgba(220,220,220,${flashA})`;
- ctx.shadowBlur = 10;
- ctx.fillStyle = `rgba(220,220,220,${flashA})`;
- ctx.fillText(gl.current, startX2 + i * charW2, textY2);
- ctx.shadowBlur = 0;
- }
- }
-
- // ════════════════════════════════════════════════════
- // LAYER 9: Vignette
- // ════════════════════════════════════════════════════
- const vig = ctx.createRadialGradient(cx, cy, Math.min(w, h) * 0.15, cx, cy, Math.max(w, h) * 0.65);
- vig.addColorStop(0, "rgba(0,0,0,0)");
- vig.addColorStop(1, `rgba(0,0,0,${0.03 + (1 - p) * 0.05})`);
- ctx.fillStyle = vig;
- ctx.fillRect(0, 0, width, height);
-
- // Thin progress bar at absolute bottom
- const barW = width * 0.6;
- const barX = (width - barW) / 2;
- const barY = height - 3;
- ctx.fillStyle = "rgba(100,100,100,0.15)";
- ctx.fillRect(barX, barY, barW, 1);
- ctx.fillStyle = `rgba(200,200,200,${0.3 + p * 0.5})`;
- ctx.fillRect(barX, barY, barW * clamp(p, 0, 1), 1);
-
- animRef.current = requestAnimationFrame(draw);
- }
-
- const w = width, h = height; // closure
- draw();
- return () => cancelAnimationFrame(animRef.current);
- }, [width, height]);
-
- return (
- <canvas
- ref={canvasRef}
- style={{ width, height }}
- className={className}
- />
- );
-}
-
-// ─── text glyph updater ─────────────────────────────────
-function updateTextGlyphs(glyphs: TextGlyph[], frame: number): boolean {
- let allDone = true;
- for (const gl of glyphs) {
- if (gl.target === " ") continue;
- if (!gl.decoded) {
- // Cycle through memory-sourced chars instead of random noise
- if (frame % 3 === 0 && gl.sourceChars.length > 0) {
- gl.sourceIdx = (gl.sourceIdx + 1) % gl.sourceChars.length;
- gl.current = gl.sourceChars[gl.sourceIdx];
- }
- // Decode when frame reaches threshold
- if (frame >= gl.decodeFrame) {
- gl.decoded = true;
- gl.current = gl.target;
- gl.decodeFrame = frame; // record actual decode frame
- } else {
- allDone = false;
- }
- } else {
- // Occasional re-glitch shows a memory fragment char briefly
- if (rng() < 0.002 && gl.sourceChars.length > 0) {
- gl.current = pick(gl.sourceChars);
- setTimeout(() => { gl.current = gl.target; }, 80);
- }
- }
- }
- return allDone;
-}
-
-// ─── progress steps ──────────────────────────────────────
-export function ProgressSteps({
- steps,
- className = "",
-}: {
- steps: Array<{ label: string; done: boolean; active: boolean }>;
- className?: string;
-}) {
- return (
- <div className={`flex items-center justify-center gap-5 ${className}`}>
- {steps.map((step, i) => (
- <div key={i} className="flex items-center gap-1.5">
- <motion.div
- className={`w-1 h-1 ${
- step.done
- ? "bg-foreground"
- : step.active
- ? "bg-foreground/50"
- : "bg-foreground/15"
- }`}
- animate={
- step.active
- ? { opacity: [0.4, 1, 0.4] }
- : {}
- }
- transition={
- step.active
- ? { duration: 1.8, repeat: Infinity, ease: "easeInOut" }
- : {}
- }
- />
- <span
- className={`font-mono text-[9px] tracking-wider uppercase ${
- step.done
- ? "text-foreground"
- : step.active
- ? "text-foreground/60"
- : "text-foreground/20"
- }`}
- >
- {step.label}
- </span>
- </div>
- ))}
- </div>
- );
-}
diff --git a/apps/screenpipe-app-tauri/components/onboarding/personalize.tsx b/apps/screenpipe-app-tauri/components/onboarding/personalize.tsx
deleted file mode 100644
index a40c53519..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/personalize.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import React from "react";
-import {
- Brain,
- CircleCheck,
- Zap,
- Shield,
- Settings,
-} from "lucide-react";
-import OnboardingNavigation from "@/components/onboarding/navigation";
-import { motion } from "framer-motion";
-
-interface OnboardingPersonalizeProps {
- className?: string;
- selectedPersonalization: string | null;
- handleOptionClick: (option: string) => void;
- handleNextSlide: () => void;
- handlePrevSlide: () => void;
-}
-
-const OPTIONS = [
- {
- key: "maxAI",
- icon: Brain,
- label: "Maximum AI assistance",
- description: "Full AI analysis with cloud processing for best results",
- features: ["Best search accuracy", "Real-time analysis", "Advanced summaries"],
- recommended: true
- },
- {
- key: "balancedAI",
- icon: Zap,
- label: "Balanced AI assistance",
- description: "Good AI analysis with some local processing",
- features: ["Good search accuracy", "Periodic analysis", "Basic summaries"],
- recommended: false
- },
- {
- key: "minimalAI",
- icon: Shield,
- label: "Minimal AI assistance",
- description: "Basic analysis with local processing only",
- features: ["Basic search", "Manual triggers", "Data stays local"],
- recommended: false
- }
-];
-
-const SelectionItem: React.FC<{
- option: (typeof OPTIONS)[number];
- isSelected: boolean | undefined;
- onClick: () => void;
- index: number;
-}> = ({ option, isSelected, onClick, index }) => {
- const { icon: Icon, label, description, features, recommended } = option;
- return (
- <motion.div
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: index * 0.1 }}
- className={`relative w-full max-w-sm flex flex-col border rounded-xl p-6 m-2 hover:shadow-lg cursor-pointer transition-all duration-300
- ${
- isSelected
- ? "bg-primary text-primary-foreground border-primary shadow-lg transform scale-105"
- : "bg-card hover:bg-accent"
- }`}
- onClick={onClick}
- >
- {recommended && (
- <div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
- <span className="bg-orange-500 text-white text-xs px-3 py-1 rounded-full font-medium">
- Recommended
- </span>
- </div>
- )}
-
- <div className="flex items-center justify-between mb-4">
- <Icon className={`h-8 w-8 ${isSelected ? 'text-primary-foreground' : 'text-primary'}`} />
- {isSelected && <CircleCheck className="h-6 w-6 flex-shrink-0" />}
- </div>
-
- <h3 className="font-semibold text-lg mb-2">{label}</h3>
-
- <p className={`text-sm mb-4 ${isSelected ? 'text-primary-foreground/90' : 'text-muted-foreground'}`}>
- {description}
- </p>
-
- <div className="space-y-2">
- {features.map((feature, featureIndex) => (
- <div key={featureIndex} className="flex items-center text-sm">
- <div className={`w-2 h-2 rounded-full mr-2 ${isSelected ? 'bg-primary-foreground/60' : 'bg-primary/60'}`} />
- <span className={isSelected ? 'text-primary-foreground/90' : 'text-muted-foreground'}>
- {feature}
- </span>
- </div>
- ))}
- </div>
- </motion.div>
- );
-};
-
-const OnboardingPersonalize: React.FC<OnboardingPersonalizeProps> = ({
- className,
- selectedPersonalization,
- handleOptionClick,
- handleNextSlide,
- handlePrevSlide,
-}) => {
- return (
- <div className={`${className} flex flex-col h-full`}>
- <div className="flex flex-col px-2 justify-center items-center mb-6">
- <motion.img
- className="w-20 h-20 justify-center mb-4"
- src="/128x128.png"
- alt="screenpipe-logo"
- initial={{ scale: 0.8, opacity: 0 }}
- animate={{ scale: 1, opacity: 1 }}
- transition={{ duration: 0.5 }}
- />
- <h2 className="text-center text-2xl font-bold">
- Choose your AI assistance level
- </h2>
- <p className="text-center text-muted-foreground mt-2 max-w-md">
- screenpipe uses AI to help you find and understand your recorded data. Choose how much AI assistance you&apos;d like.
- </p>
- </div>
-
- <div className="flex-1 flex flex-col items-center justify-center">
- <div className="flex flex-wrap justify-center gap-4 max-w-6xl">
- {OPTIONS.map((option, index) => (
- <SelectionItem
- key={option.key}
- option={option}
- isSelected={selectedPersonalization === option.key}
- onClick={() => handleOptionClick(option.key)}
- index={index}
- />
- ))}
- </div>
-
- {selectedPersonalization && (
- <motion.div
- initial={{ opacity: 0, y: 10 }}
- animate={{ opacity: 1, y: 0 }}
- className="mt-6 text-center text-sm text-muted-foreground max-w-md"
- >
- <Settings className="h-4 w-4 inline mr-1" />
- You can always change this setting later in preferences.
- </motion.div>
- )}
- </div>
-
- <OnboardingNavigation
- handlePrevSlide={handlePrevSlide}
- handleNextSlide={handleNextSlide}
- prevBtnText="Back"
- nextBtnText="Continue"
- />
- </div>
- );
-};
-
-export default OnboardingPersonalize;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/shortcuts.tsx b/apps/screenpipe-app-tauri/components/onboarding/shortcuts.tsx
deleted file mode 100644
index 67da0aede..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/shortcuts.tsx
+++ /dev/null
@@ -1,280 +0,0 @@
-import React, { useState, useEffect } from "react";
-import { cn, parseKeyboardShortcut } from "@/lib/utils";
-import { CommandShortcut } from "@/components/ui/command";
-import { useSettings } from "@/lib/hooks/use-settings";
-import { usePlatform } from "@/lib/hooks/use-platform";
-import { commands } from "@/lib/utils/tauri";
-import { Switch } from "@/components/ui/switch";
-import { Pencil } from "lucide-react";
-import hotkeys from "hotkeys-js";
-import { toast } from "@/components/ui/use-toast";
-
-interface OnboardingShortcutsProps {
- className?: string;
- handleNextSlide: () => void;
- handlePrevSlide: () => void;
-}
-
-export default function OnboardingShortcuts({
- className,
- handleNextSlide,
- handlePrevSlide,
-}: OnboardingShortcutsProps) {
- const { settings, updateSettings } = useSettings();
- const { isMac, isWindows } = usePlatform();
- const [recordingShortcut, setRecordingShortcut] = useState<string | null>(null);
-
- // Function to convert internal key names to platform-specific display names
- const getDisplayKey = (key: string): string => {
- if (key === "Super" || key === "SUPER") {
- if (isMac) return "Cmd";
- if (isWindows) return "Win";
- return "Super"; // fallback for Linux or unknown platforms
- }
- return key;
- };
-
- const shortcuts = [
- {
- id: "showScreenpipeShortcut",
- title: "Show/Hide screenpipe",
- defaultShortcut: isWindows ? "Alt+S" : "Control+Super+S",
- description: "Quickly toggle the screenpipe interface",
- value: settings.showScreenpipeShortcut,
- },
- {
- id: "startRecordingShortcut",
- title: "Start Recording",
- defaultShortcut: isWindows ? "Alt+Shift+U" : "Super+Ctrl+U",
- description: "Begin screen recording",
- value: settings.startRecordingShortcut,
- },
- {
- id: "stopRecordingShortcut",
- title: "Stop Recording",
- defaultShortcut: isWindows ? "Alt+Shift+X" : "Super+Ctrl+X",
- description: "End screen recording",
- value: settings.stopRecordingShortcut,
- },
- ];
-
- useEffect(() => {
- if (!recordingShortcut) return;
-
- const handleKeyDown = (event: KeyboardEvent) => {
- event.preventDefault();
-
- const MODIFIER_KEYS = ["SUPER", "CTRL", "ALT", "SHIFT"] as const;
- const KEY_CODE_MAP: Record<number, string> = {
- 224: "SUPER", // Meta key on macOS
- 91: "SUPER", // Left Windows key
- 92: "SUPER", // Right Windows key
- 93: "SUPER", // Context menu key
- 16: "SHIFT",
- 17: "CTRL",
- 18: "ALT",
- };
-
- const pressedKeys = hotkeys
- .getPressedKeyCodes()
- .map((code) => {
- // Special handling for Shift key
- if (code === 16) {
- return "SHIFT";
- }
- return KEY_CODE_MAP[code] || String.fromCharCode(code).toUpperCase();
- })
- .filter((value, index, self) => self.indexOf(value) === index);
-
- const modifiers = pressedKeys.filter((k) =>
- MODIFIER_KEYS.includes(k as any)
- );
- const normalKeys = pressedKeys.filter(
- (k) => !MODIFIER_KEYS.includes(k as any)
- );
- const finalKeys = [...modifiers, ...normalKeys];
-
- if (normalKeys.length > 0) {
- handleEnableShortcut(recordingShortcut, finalKeys.join("+"));
- setRecordingShortcut(null);
- }
- };
-
- hotkeys.filter = () => true;
- hotkeys("*", handleKeyDown);
-
- return () => {
- setRecordingShortcut(null);
- hotkeys.unbind("*");
- hotkeys.filter = (event) => {
- const target = (event.target || event.srcElement) as any;
- return !(
- target.isContentEditable ||
- target.tagName === "INPUT" ||
- target.tagName === "TEXTAREA"
- );
- };
- };
- }, [recordingShortcut]);
-
- const handleEnableShortcut = async (shortcutId: string, keys: string) => {
- try {
- // Convert keys to display format for toast
- const displayKeys = keys.split("+").map(getDisplayKey).join("+");
- toast({
- title: "Shortcut updated",
- description: `${shortcutId.replace(/_/g, " ")} set to ${displayKeys}`,
- });
-
- // Update settings
- updateSettings({ [shortcutId]: keys });
-
- // Sync with backend
- await commands.updateGlobalShortcuts(
- settings.showScreenpipeShortcut,
- settings.startRecordingShortcut,
- settings.stopRecordingShortcut,
- settings.startAudioShortcut,
- settings.stopAudioShortcut,
- {}
- );
- } catch (error) {
- console.error("Error updating shortcut:", error);
- toast({
- title: "Error updating shortcut",
- description: "Failed to register shortcut. Please try a different combination.",
- variant: "destructive",
- });
- }
- };
-
- const handleDisableShortcut = async (shortcutId: string) => {
- try {
- toast({
- title: "Shortcut disabled",
- description: `${shortcutId.replace(/_/g, " ")} disabled`,
- });
-
- updateSettings({
- disabledShortcuts: Array.from(
- new Set([...settings.disabledShortcuts, shortcutId])
- ),
- });
-
- await commands.updateGlobalShortcuts(
- settings.showScreenpipeShortcut,
- settings.startRecordingShortcut,
- settings.stopRecordingShortcut,
- settings.startAudioShortcut,
- settings.stopAudioShortcut,
- {}
- );
- } catch (error) {
- console.error("Error disabling shortcut:", error);
- toast({
- title: "Error disabling shortcut",
- description: "Failed to disable shortcut. Please try again.",
- variant: "destructive",
- });
- }
- };
-
- const isValueEmpty = (v: string | undefined): boolean =>
- !v || v.trim() === "";
-
- const getShortcutState = (shortcutId: string): "enabled" | "disabled" | "unassigned" => {
- if (isValueEmpty(settings[shortcutId as keyof typeof settings] as string)) {
- return "unassigned";
- }
- return settings.disabledShortcuts.includes(shortcutId)
- ? "disabled"
- : "enabled";
- };
-
- return (
- <div className={cn("space-y-8", className)}>
- <div className="space-y-3">
- <h1 className="text-3xl font-bold tracking-tight text-foreground">
- Keyboard Shortcuts
- </h1>
- <p className="text-muted-foreground text-lg">
- Customize your keyboard shortcuts to boost your productivity
- </p>
- </div>
-
- <div className="space-y-6">
- {shortcuts.map((shortcut) => {
- const currentKeys = isValueEmpty(shortcut.value)
- ? ["Unassigned"]
- : shortcut.value.split("+");
-
- return (
- <div key={shortcut.id} className="flex items-center justify-between">
- <div className="space-y-1">
- <h4 className="font-medium">{shortcut.title}</h4>
- <p className="text-sm text-muted-foreground">
- {shortcut.description}
- </p>
- </div>
- <div className="flex items-center gap-4">
- <button
- onClick={() => setRecordingShortcut(shortcut.id)}
- className={cn(
- "relative min-w-[140px] rounded-md border px-3 py-2 text-sm",
- "bg-muted/50 hover:bg-muted/70 transition-colors",
- "focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-ring",
- recordingShortcut === shortcut.id && "border-primary",
- !shortcut.value && "text-muted-foreground"
- )}
- >
- {recordingShortcut === shortcut.id ? (
- <span className="animate-pulse">recording...</span>
- ) : (
- <span className="flex items-center justify-between gap-2">
- <kbd
- className={cn(
- "px-1 rounded",
- shortcut.value ? "bg-background/50" : "bg-transparent"
- )}
- >
- {parseKeyboardShortcut(shortcut.value || "")}
- </kbd>
- <Pencil className="h-3 w-3 opacity-50" />
- </span>
- )}
- </button>
-
- <Switch
- checked={getShortcutState(shortcut.id) === "enabled"}
- disabled={getShortcutState(shortcut.id) === "unassigned"}
- onCheckedChange={async (checked) => {
- if (checked && shortcut.value) {
- await handleEnableShortcut(shortcut.id, shortcut.value);
- } else {
- await handleDisableShortcut(shortcut.id);
- }
- }}
- />
- </div>
- </div>
- );
- })}
- </div>
-
- <div className="flex justify-between pt-6">
- <button
- onClick={handlePrevSlide}
- className="px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
- >
- Back
- </button>
- <button
- onClick={handleNextSlide}
- className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
- >
- Continue
- </button>
- </div>
- </div>
- );
-}
\ No newline at end of file
diff --git a/apps/screenpipe-app-tauri/components/onboarding/single-codeblock.tsx b/apps/screenpipe-app-tauri/components/onboarding/single-codeblock.tsx
deleted file mode 100644
index 8daf9c312..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/single-codeblock.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-"use client";
-
-import { FC, memo } from "react";
-import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
-import { coldarkDark } from "react-syntax-highlighter/dist/cjs/styles/prism";
-import { useCopyToClipboard } from "@/lib/hooks/use-copy-to-clipboard";
-import { IconCheck, IconCopy} from "@/components/ui/icons";
-import { Button } from "@/components/ui/button";
-
-interface Props {
- className?: string;
- language: string;
- value: string;
-}
-
-interface languageMap {
- [key: string]: string | undefined;
-}
-
-export const programmingLanguages: languageMap = {
- javascript: ".js",
- python: ".py",
- java: ".java",
- c: ".c",
- cpp: ".cpp",
- "c++": ".cpp",
- "c#": ".cs",
- ruby: ".rb",
- php: ".php",
- swift: ".swift",
- "objective-c": ".m",
- kotlin: ".kt",
- typescript: ".ts",
- go: ".go",
- perl: ".pl",
- rust: ".rs",
- scala: ".scala",
- haskell: ".hs",
- lua: ".lua",
- shell: ".sh",
- sql: ".sql",
- html: ".html",
- css: ".css",
-};
-
-export const generateRandomString = (length: number, lowercase = false) => {
- const chars = "ABCDEFGHJKLMNPQRSTUVWXY3456789";
- let result = "";
- for (let i = 0; i < length; i++) {
- result += chars.charAt(Math.floor(Math.random() * chars.length));
- }
- return lowercase ? result.toLowerCase() : result;
-};
-
-const CodeBlock: FC<Props> = memo(({ className, language, value }) => {
- const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 });
-
- const onCopy = () => {
- if (isCopied) return;
- copyToClipboard(value);
- };
-
- return (
- <div className={` relative w-full font-sans codeblock bg-card ${className}`}>
- <SyntaxHighlighter
- language={language}
- style={coldarkDark}
- PreTag="div"
- customStyle={{
- margin: 0,
- width: "100%",
- background: "transparent",
- padding: "10px 8px",
- }}
- codeTagProps={{
- style: {
- fontSize: "0.85rem",
- fontFamily: "var(--font-mono)",
- },
- }}
- >
- {value}
- </SyntaxHighlighter>
- <div className="absolute rounded-md z-[100] items-center right-0 top-[2px] text-zinc-100 bg-zinc-950">
- <Button
- title="Copy"
- variant="ghost"
- size="icon"
- className="text-xs hover:text-zinc-200/80 hover:bg-zinc-950"
- onClick={onCopy}
- >
- {isCopied ? <IconCheck /> : <IconCopy />}
- <span className="sr-only">Copy code</span>
- </Button>
- </div>
- </div>
- );
-});
-CodeBlock.displayName = "CodeBlock";
-
-export { CodeBlock };
diff --git a/apps/screenpipe-app-tauri/components/onboarding/timeline-ai-demo.tsx b/apps/screenpipe-app-tauri/components/onboarding/timeline-ai-demo.tsx
deleted file mode 100644
index 60bc231b7..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/timeline-ai-demo.tsx
+++ /dev/null
@@ -1,247 +0,0 @@
-import React from "react";
-import { motion } from "framer-motion";
-import { MessageSquare, Sparkles } from "lucide-react";
-import { useSettings } from "@/lib/hooks/use-settings";
-import { usePlatform } from "@/lib/hooks/use-platform";
-
-/**
- * Format a shortcut string for display with consistent modifier ordering.
- * On macOS: Command (⌘) → Control (⌃) → Option (⌥) → Shift (⇧) → Key
- */
-function formatShortcut(shortcut: string, isMac: boolean): string {
- if (!shortcut) return "";
-
- const parts = shortcut.split("+").map(p => p.trim().toLowerCase());
- const modifierPriority: Record<string, number> = {
- "super": 0, "command": 0, "cmd": 0,
- "ctrl": 1, "control": 1,
- "alt": 2, "option": 2,
- "shift": 3,
- };
-
- const modifiers: string[] = [];
- let key = "";
-
- for (const part of parts) {
- if (modifierPriority[part] !== undefined) {
- modifiers.push(part);
- } else {
- key = part;
- }
- }
-
- modifiers.sort((a, b) => (modifierPriority[a] ?? 99) - (modifierPriority[b] ?? 99));
-
- if (isMac) {
- const macSymbols: Record<string, string> = {
- "super": "⌘", "command": "⌘", "cmd": "⌘",
- "ctrl": "⌃", "control": "⌃",
- "alt": "⌥", "option": "⌥",
- "shift": "⇧",
- };
- return modifiers.map(m => macSymbols[m] || m).join("") + key.toUpperCase();
- } else {
- const winNames: Record<string, string> = {
- "super": "Win", "command": "Ctrl", "cmd": "Ctrl",
- "ctrl": "Ctrl", "control": "Ctrl",
- "alt": "Alt", "option": "Alt",
- "shift": "Shift",
- };
- return [...modifiers.map(m => winNames[m] || m), key.toUpperCase()].join("+");
- }
-}
-
-/**
- * Animated demo showing:
- * 1. Timeline with activity bars
- * 2. Selection being made (drag effect)
- * 3. AI chat appearing
- * 4. Response typing in
- *
- * Loops every 6 seconds
- */
-export const TimelineAIDemo: React.FC = () => {
- const { settings } = useSettings();
- const { isMac } = usePlatform();
- const chatShortcut = formatShortcut(settings.showChatShortcut, isMac);
- return (
- <div className="bg-muted/30 border border-border rounded-lg p-4 max-w-sm overflow-hidden">
- <div className="flex items-center space-x-2 mb-3">
- <MessageSquare className="w-4 h-4 text-primary" />
- <span className="font-mono text-xs font-medium text-foreground">
- then chat with your history
- </span>
- </div>
-
- <div className="bg-background rounded border border-border p-3 space-y-3">
- {/* Timeline visualization */}
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <span className="font-mono text-[9px] text-muted-foreground">timeline</span>
- <span className="font-mono text-[9px] text-muted-foreground">2:00pm</span>
- </div>
-
- {/* Activity bars */}
- <div className="relative h-6 bg-muted/50 rounded overflow-hidden">
- {/* Static activity indicators */}
- <div className="absolute inset-y-1 left-[5%] w-[15%] bg-blue-500/30 rounded-sm" />
- <div className="absolute inset-y-1 left-[25%] w-[20%] bg-green-500/30 rounded-sm" />
- <div className="absolute inset-y-1 left-[50%] w-[10%] bg-purple-500/30 rounded-sm" />
- <div className="absolute inset-y-1 left-[65%] w-[25%] bg-orange-500/30 rounded-sm" />
-
- {/* Animated selection highlight */}
- <motion.div
- className="absolute inset-y-0 bg-primary/20 border-x-2 border-primary"
- initial={{ left: "20%", width: "0%" }}
- animate={{
- left: ["20%", "20%", "20%", "20%"],
- width: ["0%", "35%", "35%", "35%"],
- opacity: [0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.2, 0.7, 1],
- ease: "easeInOut",
- }}
- />
-
- {/* Selection handles */}
- <motion.div
- className="absolute top-1/2 -translate-y-1/2 w-1 h-4 bg-primary rounded-full"
- initial={{ left: "20%", opacity: 0 }}
- animate={{
- left: ["20%", "20%", "20%", "20%"],
- opacity: [0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.2, 0.7, 1],
- }}
- />
- <motion.div
- className="absolute top-1/2 -translate-y-1/2 w-1 h-4 bg-primary rounded-full"
- initial={{ left: "20%", opacity: 0 }}
- animate={{
- left: ["20%", "55%", "55%", "55%"],
- opacity: [0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.2, 0.7, 1],
- }}
- />
- </div>
- </div>
-
- {/* Keyboard shortcut hint */}
- <motion.div
- className="flex items-center justify-center space-x-1"
- initial={{ opacity: 0 }}
- animate={{
- opacity: [0, 0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.15, 0.25, 0.35, 0.45],
- }}
- >
- <span className="font-mono text-[10px] text-muted-foreground">press</span>
- <kbd className="px-1.5 py-0.5 bg-muted border border-border rounded text-[10px] font-mono font-semibold">
- {chatShortcut}
- </kbd>
- </motion.div>
-
- {/* AI Chat bubble */}
- <motion.div
- className="bg-muted/50 rounded-lg p-2 space-y-2"
- initial={{ opacity: 0, y: 10, height: 0 }}
- animate={{
- opacity: [0, 0, 0, 1, 1, 0],
- y: [10, 10, 10, 0, 0, 0],
- height: ["0px", "0px", "0px", "auto", "auto", "auto"],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.3, 0.35, 0.45, 0.9, 1],
- }}
- >
- {/* User question */}
- <motion.div
- className="flex items-start space-x-2"
- initial={{ opacity: 0 }}
- animate={{
- opacity: [0, 0, 0, 0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.35, 0.4, 0.45, 0.5, 0.9, 1],
- }}
- >
- <div className="w-4 h-4 rounded-full bg-primary/20 flex items-center justify-center flex-shrink-0">
- <span className="text-[8px]">👤</span>
- </div>
- <p className="font-mono text-[10px] text-foreground">
- what was discussed here?
- </p>
- </motion.div>
-
- {/* AI response */}
- <motion.div
- className="flex items-start space-x-2"
- initial={{ opacity: 0 }}
- animate={{
- opacity: [0, 0, 0, 0, 0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.45, 0.5, 0.55, 0.6, 0.65, 0.9, 1],
- }}
- >
- <div className="w-4 h-4 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
- <Sparkles className="w-2.5 h-2.5 text-primary-foreground" />
- </div>
- <div className="space-y-1">
- <motion.p
- className="font-mono text-[10px] text-muted-foreground"
- initial={{ opacity: 0 }}
- animate={{
- opacity: [0, 0, 0, 0, 0, 0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.5, 0.55, 0.6, 0.65, 0.68, 0.72, 0.9, 1],
- }}
- >
- In this meeting you discussed
- </motion.p>
- <motion.p
- className="font-mono text-[10px] text-foreground"
- initial={{ opacity: 0 }}
- animate={{
- opacity: [0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
- }}
- transition={{
- duration: 6,
- repeat: Infinity,
- times: [0, 0.55, 0.6, 0.65, 0.7, 0.73, 0.76, 0.8, 0.9, 1],
- }}
- >
- Q1 roadmap priorities...
- </motion.p>
- </div>
- </motion.div>
- </motion.div>
- </div>
- </div>
- );
-};
-
-export default TimelineAIDemo;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/usecases-selection.tsx b/apps/screenpipe-app-tauri/components/onboarding/usecases-selection.tsx
deleted file mode 100644
index e411ba9d0..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/usecases-selection.tsx
+++ /dev/null
@@ -1,248 +0,0 @@
-import React, { useState, useEffect } from "react";
-import {
- Brain,
- CircleCheck,
- Search,
- Calendar,
- Code,
- Shield,
- Sparkles,
- MessageSquare,
-} from "lucide-react";
-import OnboardingNavigation from "@/components/onboarding/navigation";
-import posthog from "posthog-js";
-import { motion, AnimatePresence } from "framer-motion";
-import { Input } from "@/components/ui/input";
-
-interface OnboardingSelectionProps {
- className?: string;
- selectedOption: string | null;
- handleOptionClick: (option: string) => void;
- handleNextSlide: () => void;
- handlePrevSlide: () => void;
-}
-
-const OPTIONS = [
- {
- key: "memory",
- icon: Brain,
- label: "find something i saw",
- description: "i saw something on my screen but can't remember where or when",
- },
- {
- key: "meetings",
- icon: Calendar,
- label: "remember conversations",
- description: "i want to recall what was said in meetings or calls",
- },
- {
- key: "productivity",
- icon: Search,
- label: "track my time",
- description: "i want to see how i actually spend time on my computer",
- },
- {
- key: "developer",
- icon: Code,
- label: "build with my data",
- description: "i'm a developer and want to build automations on my screen data",
- },
- {
- key: "privacy",
- icon: Shield,
- label: "local ai alternative",
- description: "i want a private, local alternative to cloud ai tools",
- },
- {
- key: "curious",
- icon: Sparkles,
- label: "just exploring",
- description: "i heard about screenpipe and want to see what it does",
- },
- {
- key: "other",
- icon: MessageSquare,
- label: "something else",
- description: "tell us in your own words",
- },
-];
-
-const SelectionItem: React.FC<{
- option: (typeof OPTIONS)[number];
- isSelected: boolean;
- onClick: () => void;
- index: number;
- children?: React.ReactNode;
-}> = ({ option, isSelected, onClick, index, children }) => {
- const { icon: Icon, label, description } = option;
- return (
- <motion.div
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ delay: index * 0.08 }}
- className={`w-full flex flex-col border rounded-xl p-4 hover:shadow-lg cursor-pointer transition-all duration-300
- ${
- isSelected
- ? "bg-primary text-primary-foreground border-primary shadow-lg"
- : "bg-card hover:bg-accent"
- }`}
- onClick={onClick}
- >
- <div className="flex items-start justify-between mb-2">
- <div className="flex items-center">
- <Icon className={`h-5 w-5 mr-3 ${isSelected ? 'text-primary-foreground' : 'text-primary'}`} />
- <span className="font-medium">{label}</span>
- </div>
- {isSelected && <CircleCheck className="h-5 w-5 flex-shrink-0" />}
- </div>
-
- <p className={`text-sm ${isSelected ? 'text-primary-foreground/90' : 'text-muted-foreground'}`}>
- {description}
- </p>
-
- {children}
- </motion.div>
- );
-};
-
-const OnboardingSelection: React.FC<OnboardingSelectionProps> = ({
- className,
- selectedOption,
- handleOptionClick,
- handleNextSlide,
- handlePrevSlide,
-}) => {
- const [otherText, setOtherText] = useState("");
- const [hasSubmitted, setHasSubmitted] = useState(false);
-
- // Load saved selection and submission status on mount
- useEffect(() => {
- let savedOption: string | null = null, savedOtherText: string | null = null, submitted: string | null = null;
- try {
- savedOption = localStorage?.getItem("onboarding_usecase");
- savedOtherText = localStorage?.getItem("onboarding_usecase_other");
- submitted = localStorage?.getItem("onboarding_usecase_submitted");
- } catch {}
-
- if (savedOption && !selectedOption) {
- handleOptionClick(savedOption);
- }
- if (savedOtherText) {
- setOtherText(savedOtherText);
- }
- if (submitted === "true") {
- setHasSubmitted(true);
- }
- }, []);
-
- // Save selection when it changes
- useEffect(() => {
- if (selectedOption) {
- try { localStorage?.setItem("onboarding_usecase", selectedOption); } catch {}
- }
- }, [selectedOption]);
-
- // Save other text when it changes
- useEffect(() => {
- if (otherText) {
- try { localStorage?.setItem("onboarding_usecase_other", otherText); } catch {}
- }
- }, [otherText]);
-
- const isOtherSelected = selectedOption === "other";
- const canContinue = selectedOption !== null && (selectedOption !== "other" || otherText.trim().length > 0);
-
- const handleNext = () => {
- // Only track to PostHog once to avoid spam
- if (!hasSubmitted) {
- posthog.capture("onboarding_usecases_selected", {
- selected_option: selectedOption,
- other_text: isOtherSelected ? otherText.trim() : null,
- });
- try { localStorage?.setItem("onboarding_usecase_submitted", "true"); } catch {}
- setHasSubmitted(true);
- }
-
- handleNextSlide();
- };
-
- return (
- <div className={`${className} flex flex-col h-full`}>
- <div className="flex flex-col px-2 justify-center items-center mb-6">
- <motion.img
- className="w-20 h-20 justify-center mb-4"
- src="/128x128.png"
- alt="screenpipe-logo"
- initial={{ scale: 0.8, opacity: 0 }}
- animate={{ scale: 1, opacity: 1 }}
- transition={{ duration: 0.5 }}
- />
- <h2 className="text-center text-2xl font-bold">
- what&apos;s your #1 goal with screenpipe?
- </h2>
- <p className="text-center text-muted-foreground mt-2">
- pick the one that matters most to you
- </p>
- </div>
-
- <div className="flex-1 flex flex-col items-center justify-center overflow-y-auto">
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-w-3xl w-full px-4">
- {OPTIONS.map((option, index) => (
- <SelectionItem
- key={option.key}
- option={option}
- isSelected={selectedOption === option.key}
- onClick={() => handleOptionClick(option.key)}
- index={index}
- >
- {option.key === "other" && selectedOption === "other" && (
- <AnimatePresence>
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: "auto" }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- className="mt-3"
- onClick={(e) => e.stopPropagation()}
- >
- <Input
- type="text"
- placeholder="what are you trying to do?"
- value={otherText}
- onChange={(e) => setOtherText(e.target.value)}
- className="bg-background text-foreground border-primary-foreground/30 placeholder:text-primary-foreground/50"
- autoFocus
- />
- </motion.div>
- </AnimatePresence>
- )}
- </SelectionItem>
- ))}
- </div>
-
- <AnimatePresence>
- {!selectedOption && (
- <motion.p
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- className="mt-4 text-center text-sm text-muted-foreground"
- >
- this helps us build the right features for you
- </motion.p>
- )}
- </AnimatePresence>
- </div>
-
- <OnboardingNavigation
- handlePrevSlide={handlePrevSlide}
- handleNextSlide={handleNext}
- prevBtnText="Back"
- nextBtnText="Continue"
- nextDisabled={!canContinue}
- />
- </div>
- );
-};
-
-export default OnboardingSelection;
diff --git a/apps/screenpipe-app-tauri/components/onboarding/welcome.tsx b/apps/screenpipe-app-tauri/components/onboarding/welcome.tsx
deleted file mode 100644
index dd9288481..000000000
--- a/apps/screenpipe-app-tauri/components/onboarding/welcome.tsx
+++ /dev/null
@@ -1,541 +0,0 @@
-"use client";
-
-import React, { useEffect, useState, useRef } from "react";
-import { motion, AnimatePresence, useMotionValue, useTransform, animate } from "framer-motion";
-import { ExternalLinkIcon, CheckCircle2, Monitor, Mic, Brain, Sparkles, Clock, Search, Zap } from "lucide-react";
-import { open } from "@tauri-apps/plugin-shell";
-import { Button } from "@/components/ui/button";
-import { useSettings } from "@/lib/hooks/use-settings";
-import posthog from "posthog-js";
-
-interface OnboardingWelcomeProps {
- className?: string;
- handleNextSlide: () => void;
-}
-
-// Timeline frame component
-function TimelineFrame({ index, isActive, delay }: { index: number; isActive: boolean; delay: number }) {
- return (
- <motion.div
- className="relative flex-shrink-0 w-16 h-10 rounded border overflow-hidden"
- initial={{ opacity: 0, scale: 0.8 }}
- animate={{
- opacity: isActive ? 1 : 0.4,
- scale: isActive ? 1.1 : 1,
- borderColor: isActive ? "rgb(var(--foreground))" : "rgb(var(--foreground) / 0.2)",
- }}
- transition={{ duration: 0.3, delay }}
- >
- {/* Frame content - simulated screenshot */}
- <div className="absolute inset-0 bg-gradient-to-br from-foreground/10 to-foreground/5">
- <div className="absolute top-1 left-1 right-1 h-1.5 bg-foreground/20 rounded-sm" />
- <div className="absolute top-3.5 left-1 w-8 h-1 bg-foreground/15 rounded-sm" />
- <div className="absolute top-5 left-1 w-6 h-1 bg-foreground/10 rounded-sm" />
- </div>
- {isActive && (
- <motion.div
- className="absolute inset-0 border-2 border-primary rounded"
- layoutId="activeFrame"
- transition={{ type: "spring", stiffness: 300, damping: 30 }}
- />
- )}
- </motion.div>
- );
-}
-
-// Animated waveform for audio
-function AudioWaveform({ isActive }: { isActive: boolean }) {
- return (
- <div className="flex items-center gap-0.5 h-8">
- {[...Array(12)].map((_, i) => (
- <motion.div
- key={i}
- className="w-0.5 bg-foreground/40 rounded-full"
- animate={{
- height: isActive
- ? [8, 16 + Math.random() * 16, 8]
- : 8,
- }}
- transition={{
- duration: 0.5,
- repeat: isActive ? Infinity : 0,
- delay: i * 0.05,
- ease: "easeInOut",
- }}
- />
- ))}
- </div>
- );
-}
-
-// Main animated demo component
-function AnimatedDemo() {
- const [phase, setPhase] = useState(0);
- const [activeFrame, setActiveFrame] = useState(0);
- const timelineProgress = useMotionValue(0);
- const scrubberX = useTransform(timelineProgress, [0, 100], [0, 280]);
-
- useEffect(() => {
- // Phase cycle: record → capture → timeline → search
- const phaseInterval = setInterval(() => {
- setPhase((p) => (p + 1) % 4);
- }, 3500);
- return () => clearInterval(phaseInterval);
- }, []);
-
- useEffect(() => {
- // Timeline scrubbing animation
- if (phase === 2) {
- const controls = animate(timelineProgress, 100, {
- duration: 3,
- ease: "easeInOut",
- onUpdate: (v) => {
- setActiveFrame(Math.floor((v / 100) * 7));
- },
- });
- return () => controls.stop();
- } else {
- timelineProgress.set(0);
- setActiveFrame(0);
- }
- }, [phase, timelineProgress]);
-
- const phaseLabels = [
- { icon: Monitor, label: "recording screen", sublabel: "OCR + context" },
- { icon: Mic, label: "capturing audio", sublabel: "transcription" },
- { icon: Clock, label: "building timeline", sublabel: "searchable history" },
- { icon: Brain, label: "AI ready", sublabel: "ask anything" },
- ];
-
- return (
- <div className="relative w-full h-full flex flex-col items-center justify-center overflow-hidden bg-gradient-to-br from-background via-muted/20 to-background">
- {/* Animated background particles */}
- <div className="absolute inset-0 overflow-hidden pointer-events-none">
- {[...Array(30)].map((_, i) => (
- <motion.div
- key={i}
- className="absolute w-1 h-1 bg-foreground/10 rounded-full"
- style={{
- left: `${Math.random() * 100}%`,
- top: `${Math.random() * 100}%`,
- }}
- animate={{
- y: [0, -30, 0],
- opacity: [0.1, 0.3, 0.1],
- scale: [1, 1.5, 1],
- }}
- transition={{
- duration: 4 + Math.random() * 4,
- repeat: Infinity,
- delay: Math.random() * 4,
- ease: "easeInOut",
- }}
- />
- ))}
- </div>
-
- {/* Glowing orb in background */}
- <motion.div
- className="absolute w-64 h-64 rounded-full bg-primary/5 blur-3xl"
- animate={{
- scale: [1, 1.2, 1],
- opacity: [0.3, 0.5, 0.3],
- }}
- transition={{ duration: 4, repeat: Infinity, ease: "easeInOut" }}
- />
-
- {/* Main visualization area */}
- <div className="relative z-10 flex flex-col items-center gap-6">
-
- {/* Screen/Monitor visualization */}
- <motion.div
- className="relative"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.6 }}
- >
- {/* Monitor frame */}
- <div className="relative w-80 h-48 bg-background border-2 border-foreground/20 rounded-xl overflow-hidden shadow-2xl">
- {/* Screen bezel */}
- <div className="absolute inset-2 bg-gradient-to-br from-muted/80 to-muted/40 rounded-lg overflow-hidden">
-
- {/* Simulated screen content */}
- <div className="absolute inset-0 p-3">
- {/* Window chrome */}
- <div className="flex items-center gap-1.5 mb-2">
- <div className="w-2 h-2 rounded-full bg-red-400/60" />
- <div className="w-2 h-2 rounded-full bg-yellow-400/60" />
- <div className="w-2 h-2 rounded-full bg-green-400/60" />
- <div className="flex-1 h-4 bg-foreground/5 rounded ml-2" />
- </div>
-
- {/* Content lines with OCR highlighting */}
- <div className="space-y-2 mt-3">
- {[...Array(5)].map((_, i) => (
- <motion.div
- key={i}
- className="flex items-center gap-2"
- initial={{ opacity: 0, x: -10 }}
- animate={{ opacity: 1, x: 0 }}
- transition={{ delay: 0.5 + i * 0.1 }}
- >
- <motion.div
- className="h-2.5 bg-foreground/20 rounded"
- style={{ width: `${40 + Math.random() * 50}%` }}
- animate={phase === 0 ? {
- backgroundColor: ["rgba(var(--foreground), 0.2)", "rgba(var(--primary), 0.4)", "rgba(var(--foreground), 0.2)"],
- } : {}}
- transition={{
- duration: 1,
- delay: i * 0.15,
- repeat: phase === 0 ? Infinity : 0,
- }}
- />
- </motion.div>
- ))}
- </div>
-
- {/* OCR scanning line */}
- <AnimatePresence>
- {phase === 0 && (
- <motion.div
- className="absolute left-0 right-0 h-8 bg-gradient-to-b from-primary/30 via-primary/10 to-transparent"
- initial={{ top: 0 }}
- animate={{ top: "100%" }}
- exit={{ opacity: 0 }}
- transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
- />
- )}
- </AnimatePresence>
- </div>
-
- {/* Audio visualization overlay */}
- <AnimatePresence>
- {phase === 1 && (
- <motion.div
- className="absolute bottom-3 left-3 right-3 h-12 bg-background/80 backdrop-blur rounded-lg flex items-center justify-center gap-3 px-4"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: 20 }}
- >
- <Mic className="w-4 h-4 text-primary" />
- <AudioWaveform isActive={phase === 1} />
- <motion.span
- className="text-[10px] font-mono text-muted-foreground"
- animate={{ opacity: [0.5, 1, 0.5] }}
- transition={{ duration: 1.5, repeat: Infinity }}
- >
- transcribing...
- </motion.span>
- </motion.div>
- )}
- </AnimatePresence>
- </div>
-
- {/* Recording indicator */}
- <motion.div
- className="absolute top-3 right-3 flex items-center gap-1.5 px-2 py-1 bg-red-500/90 rounded-full"
- animate={{ opacity: phase < 2 ? [1, 0.5, 1] : 0.3 }}
- transition={{ duration: 1, repeat: Infinity }}
- >
- <motion.div
- className="w-2 h-2 bg-white rounded-full"
- animate={{ scale: [1, 0.8, 1] }}
- transition={{ duration: 1, repeat: Infinity }}
- />
- <span className="text-[9px] font-mono text-white font-medium">REC</span>
- </motion.div>
- </div>
-
- {/* Monitor stand */}
- <div className="mx-auto w-20 h-4 bg-foreground/10 rounded-b-lg" />
- <div className="mx-auto w-28 h-2 bg-foreground/10 rounded-full" />
- </motion.div>
-
- {/* Timeline visualization */}
- <motion.div
- className="w-full max-w-sm"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: phase >= 2 ? 1 : 0.3, y: 0 }}
- transition={{ duration: 0.5, delay: 0.3 }}
- >
- <div className="relative bg-background/80 backdrop-blur border border-foreground/10 rounded-xl p-4">
- {/* Timeline header */}
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Clock className="w-3.5 h-3.5 text-muted-foreground" />
- <span className="text-[10px] font-mono text-muted-foreground">timeline</span>
- </div>
- <span className="text-[10px] font-mono text-muted-foreground">today</span>
- </div>
-
- {/* Timeline frames */}
- <div className="flex gap-2 overflow-hidden">
- {[...Array(8)].map((_, i) => (
- <TimelineFrame
- key={i}
- index={i}
- isActive={phase >= 2 && activeFrame === i}
- delay={i * 0.05}
- />
- ))}
- </div>
-
- {/* Scrubber */}
- <div className="relative h-1 bg-foreground/10 rounded-full mt-3">
- <motion.div
- className="absolute top-1/2 -translate-y-1/2 w-3 h-3 bg-primary rounded-full shadow-lg"
- style={{ x: scrubberX }}
- />
- <motion.div
- className="absolute left-0 top-0 bottom-0 bg-primary/50 rounded-full"
- style={{ width: useTransform(timelineProgress, [0, 100], ["0%", "100%"]) }}
- />
- </div>
- </div>
- </motion.div>
-
- {/* AI Search result */}
- <AnimatePresence>
- {phase === 3 && (
- <motion.div
- className="w-full max-w-sm"
- initial={{ opacity: 0, y: 20, scale: 0.95 }}
- animate={{ opacity: 1, y: 0, scale: 1 }}
- exit={{ opacity: 0, y: -10 }}
- transition={{ duration: 0.4 }}
- >
- <div className="relative bg-background border border-foreground/20 rounded-xl p-4 shadow-xl">
- {/* Glow effect */}
- <div className="absolute -inset-px bg-gradient-to-r from-primary/20 via-transparent to-primary/20 rounded-xl blur-sm" />
-
- <div className="relative">
- {/* Search query */}
- <div className="flex items-center gap-2 mb-3 pb-3 border-b border-foreground/10">
- <Search className="w-4 h-4 text-primary" />
- <motion.span
- className="text-xs font-mono text-foreground"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- >
- &quot;what did john say about the deadline?&quot;
- </motion.span>
- </div>
-
- {/* AI Response */}
- <div className="flex items-start gap-2">
- <div className="w-6 h-6 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
- <Sparkles className="w-3.5 h-3.5 text-primary" />
- </div>
- <div className="space-y-1.5">
- <motion.p
- className="text-xs text-foreground leading-relaxed"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- transition={{ delay: 0.2 }}
- >
- John mentioned the <span className="text-primary font-medium">Q3 deadline is August 15th</span>
- </motion.p>
- <motion.p
- className="text-[10px] text-muted-foreground font-mono"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- transition={{ delay: 0.4 }}
- >
- from: team standup · yesterday 9:34 AM
- </motion.p>
- </div>
- </div>
- </div>
- </div>
- </motion.div>
- )}
- </AnimatePresence>
-
- {/* Phase indicator */}
- <div className="flex items-center gap-6 mt-4">
- {phaseLabels.map((item, i) => (
- <motion.div
- key={i}
- className="flex flex-col items-center gap-1.5"
- animate={{
- opacity: phase === i ? 1 : 0.3,
- scale: phase === i ? 1 : 0.9,
- }}
- transition={{ duration: 0.3 }}
- >
- <motion.div
- className="w-10 h-10 rounded-xl flex items-center justify-center border"
- animate={{
- backgroundColor: phase === i ? "rgb(var(--primary) / 0.1)" : "transparent",
- borderColor: phase === i ? "rgb(var(--primary))" : "rgb(var(--foreground) / 0.2)",
- }}
- >
- <item.icon className={`w-4 h-4 ${phase === i ? "text-primary" : "text-muted-foreground"}`} />
- </motion.div>
- <span className="text-[9px] font-mono text-muted-foreground text-center leading-tight">
- {item.label}
- </span>
- </motion.div>
- ))}
- </div>
- </div>
- </div>
- );
-}
-
-const OnboardingWelcome: React.FC<OnboardingWelcomeProps> = ({
- className = "",
- handleNextSlide,
-}) => {
- const { settings } = useSettings();
- const isLoggedIn = !!settings?.user?.token;
-
- const handleSkip = () => {
- posthog.capture("onboarding_login_skipped");
- handleNextSlide();
- };
-
- const handleContinue = () => {
- posthog.capture("onboarding_login_completed", {
- email: settings?.user?.email,
- });
- handleNextSlide();
- };
-
- return (
- <div className={`w-full h-full flex ${className}`}>
- {/* Left panel - Auth & value prop */}
- <div className="w-[35%] flex flex-col justify-center px-8 py-6 border-r border-border/50 bg-background">
- <div className="max-w-xs mx-auto space-y-8">
- {/* Logo and title */}
- <motion.div
- className="space-y-4"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.5 }}
- >
- <motion.div
- className="relative"
- initial={{ scale: 0.8, opacity: 0 }}
- animate={{ scale: 1, opacity: 1 }}
- transition={{ duration: 0.5, delay: 0.1 }}
- >
- <img
- className="w-14 h-14"
- src="/128x128.png"
- alt="screenpipe"
- />
- {/* Subtle glow */}
- <motion.div
- className="absolute inset-0 bg-primary/20 rounded-xl blur-xl"
- animate={{ opacity: [0.3, 0.6, 0.3] }}
- transition={{ duration: 2, repeat: Infinity }}
- />
- </motion.div>
- <div>
- <h1 className="text-2xl font-bold tracking-tight">screenpipe</h1>
- <p className="text-sm text-muted-foreground mt-1">
- AI memory for your screen
- </p>
- </div>
- </motion.div>
-
- {/* Feature highlights */}
- <motion.div
- className="space-y-2"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.5, delay: 0.15 }}
- >
- {[
- { icon: Zap, text: "records everything locally" },
- { icon: Search, text: "AI-powered search" },
- { icon: Clock, text: "visual timeline" },
- ].map((item, i) => (
- <motion.div
- key={i}
- className="flex items-center gap-2.5 text-xs text-muted-foreground"
- initial={{ opacity: 0, x: -10 }}
- animate={{ opacity: 1, x: 0 }}
- transition={{ delay: 0.3 + i * 0.1 }}
- >
- <item.icon className="w-3.5 h-3.5" />
- <span>{item.text}</span>
- </motion.div>
- ))}
- </motion.div>
-
- {/* Auth section */}
- <motion.div
- className="space-y-3"
- initial={{ opacity: 0, y: 20 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.5, delay: 0.25 }}
- >
- {isLoggedIn ? (
- <div className="space-y-3">
- <div className="flex items-center gap-2 text-sm text-foreground">
- <CheckCircle2 className="w-4 h-4" />
- signed in as {settings?.user?.email}
- </div>
- <Button
- variant="default"
- onClick={handleContinue}
- className="w-full"
- size="lg"
- >
- continue
- </Button>
- </div>
- ) : (
- <div className="space-y-2">
- <Button
- variant="default"
- onClick={handleSkip}
- className="w-full group"
- size="lg"
- >
- get started
- <motion.span
- className="ml-2"
- animate={{ x: [0, 4, 0] }}
- transition={{ duration: 1.5, repeat: Infinity }}
- >
- →
- </motion.span>
- </Button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => open("https://screenpi.pe/login")}
- className="w-full text-muted-foreground text-xs"
- >
- sign in for cloud features
- <ExternalLinkIcon className="w-3 h-3 ml-1.5" />
- </Button>
- </div>
- )}
- </motion.div>
-
- {/* Trust badges */}
- <motion.p
- className="text-[10px] font-mono text-muted-foreground"
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- transition={{ duration: 0.5, delay: 0.4 }}
- >
- 100% local · open source · your data stays yours
- </motion.p>
- </div>
- </div>
-
- {/* Right panel - Animated demo */}
- <div className="w-[65%] relative overflow-hidden">
- <AnimatedDemo />
- </div>
- </div>
- );
-};
-
-export default OnboardingWelcome;
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 4dbd74fe4..1966009a8 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -1139,6 +1139,7 @@ export function StandaloneChat() {
useEffect(() => {
let unlistenEvent: UnlistenFn | null = null;
let unlistenTerminated: UnlistenFn | null = null;
+ let unlistenLog: UnlistenFn | null = null;
let mounted = true;
const setup = async () => {
@@ -1351,7 +1352,12 @@ export function StandaloneChat() {
if (!content && hasNonTextBlocks) {
content = ""; // empty — tool/thinking blocks will render
} else if (!content) {
- content = "no response from model — try a different prompt or model";
+ const provider = activePreset?.provider;
+ if (provider === "native-ollama") {
+ content = "No response — is Ollama running? Start it with `ollama serve` and make sure the model is pulled.";
+ } else {
+ content = "No response from model — try again or check your AI preset in settings.";
+ }
}
// Add text as a content block if no text block exists yet
const hasTextBlock = contentBlocks.some((b) => b.type === "text");
@@ -1407,23 +1413,59 @@ export function StandaloneChat() {
return;
}
const terminatedPid = event.payload;
- console.log("[Pi] Process terminated unexpectedly, pid:", terminatedPid, "restart count:", piRestartCountRef.current);
+ console.log("[Pi] Process terminated, pid:", terminatedPid, "restart count:", piRestartCountRef.current);
piRestartCountRef.current += 1;
+ const delay = Math.min(1000 * piRestartCountRef.current, 5000);
setTimeout(async () => {
if (!mounted) return;
- // Check if a newer Pi process is already running — don't null out piInfo
- // if Rust already started a replacement (race between stop → start → terminated event)
+ // Check if a newer Pi process is already running (race: stop → start → terminated)
try {
const result = await commands.piInfo();
if (result.status === "ok" && result.data.running && result.data.pid !== terminatedPid) {
- console.log("[Pi] Stale termination for pid", terminatedPid, "— newer pid", result.data.pid, "is running, ignoring");
+ console.log("[Pi] Stale termination for pid", terminatedPid, "— newer pid", result.data.pid, "is running");
setPiInfo(result.data);
piRestartCountRef.current = 0;
return;
}
} catch {}
- setPiInfo(null);
- }, Math.min(1000 * piRestartCountRef.current, 5000));
+
+ // Pi is actually dead — auto-restart (up to 5 attempts)
+ if (piRestartCountRef.current <= 5 && !piStartInFlightRef.current) {
+ console.log("[Pi] Auto-restarting (attempt", piRestartCountRef.current, "/ 5)");
+ try {
+ const providerConfig = buildProviderConfig();
+ const home = await homeDir();
+ const dir = await join(home, ".screenpipe", "pi-chat");
+ const result = await commands.piStart(dir, settings.user?.token ?? null, providerConfig);
+ if (result.status === "ok") {
+ setPiInfo(result.data);
+ if (result.data.running) piRestartCountRef.current = 0;
+ } else {
+ console.error("[Pi] Auto-restart failed:", result.error);
+ setPiInfo(null);
+ }
+ } catch (e) {
+ console.error("[Pi] Auto-restart exception:", e);
+ setPiInfo(null);
+ }
+ } else {
+ setPiInfo(null);
+ }
+ }, delay);
+ });
+ // Listen for Pi stderr — surface critical errors to user
+ unlistenLog = await listen<string>("pi_log", (event) => {
+ if (!mounted) return;
+ const line = event.payload;
+ if (line.includes("not found") || line.includes("ECONNREFUSED") || line.includes("connection refused")) {
+ let hint = line;
+ if (line.includes("not found")) {
+ hint = `Model not found: ${line}. Check your AI preset in settings.`;
+ } else if (line.includes("ECONNREFUSED") || line.includes("connection refused")) {
+ hint = "Cannot connect to Ollama — is it running? Start with: ollama serve";
+ }
+ toast({ title: "Pi agent error", description: hint, variant: "destructive" });
+ }
});
};
@@ -1433,6 +1475,7 @@ export function StandaloneChat() {
mounted = false;
unlistenEvent?.();
unlistenTerminated?.();
+ unlistenLog?.();
};
}, []);
@@ -1536,10 +1579,22 @@ export function StandaloneChat() {
if (result.status === "error") {
clearTimeout(timeoutId);
piMessageIdRef.current = null;
+ // Provide helpful error messages for common failures
+ let errorMsg = result.error;
+ if (errorMsg.includes("Broken pipe") || errorMsg.includes("not running")) {
+ const provider = activePreset?.provider;
+ if (provider === "native-ollama") {
+ errorMsg = "Ollama is not running. Start it with: `ollama serve`";
+ } else {
+ errorMsg = "AI agent crashed — restarting automatically...";
+ }
+ } else if (errorMsg.includes("not found")) {
+ errorMsg = `Model "${activePreset?.model}" not found. Check your AI preset in settings.`;
+ }
setMessages((prev) =>
prev.map((m) =>
m.id === assistantMessageId
- ? { ...m, content: `Error: ${result.error}` }
+ ? { ...m, content: `Error: ${errorMsg}` }
: m
)
);
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index ff3528d46..f0fd15060 100755
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -5078,7 +5078,7 @@ source = "git+https://github.com/Neptune650/knf-rs.git#b782e6bb02db495ce767f0094
dependencies = [
"eyre",
"knf-rs-sys",
- "ndarray 0.16.1",
+ "ndarray",
]
[[package]]
@@ -5872,19 +5872,6 @@ dependencies = [
"tempfile",
]
-[[package]]
-name = "ndarray"
-version = "0.15.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "adb12d4e967ec485a5f71c6311fe28158e9d6f4bc4a447b474184d0f91a8fa32"
-dependencies = [
- "matrixmultiply",
- "num-complex",
- "num-integer",
- "num-traits",
- "rawpointer",
-]
-
[[package]]
name = "ndarray"
version = "0.16.1"
@@ -6965,7 +6952,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5f95fe501e1cb81dec2f66ee3129025759b602817aa2c77ff421390c418cc34"
dependencies = [
"half",
- "ndarray 0.16.1",
+ "ndarray",
"ort-sys",
"tracing",
]
@@ -8369,16 +8356,6 @@ dependencies = [
"ordered-multimap",
]
-[[package]]
-name = "rust-stemmers"
-version = "1.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54"
-dependencies = [
- "serde",
- "serde_derive",
-]
-
[[package]]
name = "rustc-demangle"
version = "0.1.27"
@@ -8836,7 +8813,7 @@ dependencies = [
"libpulse-simple-binding",
"libsamplerate-sys",
"log",
- "ndarray 0.16.1",
+ "ndarray",
"oasgen",
"objc",
"once_cell",
@@ -8997,14 +8974,12 @@ dependencies = [
"lru",
"md5",
"moka",
- "ndarray 0.15.6",
"nix 0.29.0",
"oasgen",
"once_cell",
"port_check",
"regex",
"reqwest 0.12.12",
- "rust-stemmers",
"screenpipe-accessibility",
"screenpipe-apple-intelligence",
"screenpipe-audio",
@@ -12374,7 +12349,7 @@ version = "0.2.0"
source = "git+https://github.com/screenpipe/vad-rs-1.git#3af3b1829ab4d8f018f271fe53c6f382f15ca3a6"
dependencies = [
"eyre",
- "ndarray 0.16.1",
+ "ndarray",
"ort",
"ort-sys",
"ringbuffer",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 6dbbf311d..d38ce1d2c 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -173,7 +173,6 @@ metal = ["screenpipe-audio/metal"]
pulseaudio = ["screenpipe-audio/pulseaudio"]
vulkan = ["screenpipe-audio/vulkan"]
mkl = []
-llm = []
cargo-clippy = []
default = ["custom-protocol"]
diff --git a/crates/screenpipe-core/Cargo.toml b/crates/screenpipe-core/Cargo.toml
index 6492c8e81..44fccb8e0 100644
--- a/crates/screenpipe-core/Cargo.toml
+++ b/crates/screenpipe-core/Cargo.toml
@@ -65,7 +65,6 @@ security = ["dep:regex", "dep:lazy_static"]
metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]
-llm = []
cloud-sync = [
"dep:argon2",
"dep:chacha20poly1305",
diff --git a/crates/screenpipe-core/examples/google.rs b/crates/screenpipe-core/examples/google.rs
deleted file mode 100644
index 5fdccfd93..000000000
--- a/crates/screenpipe-core/examples/google.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-use anyhow::Result;
-#[cfg(feature = "llm")]
-use screenpipe_core::google::GoogleConfig;
-#[cfg(feature = "llm")]
-use screenpipe_core::google_stream_text;
-
-fn main() -> Result<()> {
- #[cfg(feature = "llm")]
- google_stream_text(GoogleConfig::default(), |text| {
- println!("{}", text);
- Ok(())
- })?;
- Ok(())
-}
diff --git a/crates/screenpipe-core/examples/llama.rs b/crates/screenpipe-core/examples/llama.rs
deleted file mode 100644
index c54a15660..000000000
--- a/crates/screenpipe-core/examples/llama.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-use anyhow::Result;
-
-#[cfg(feature = "llm")]
-fn main() -> Result<()> {
- use screenpipe_core::LLM;
-
- let llm = LLM::new(screenpipe_core::ModelName::Llama)?;
-
- let res = llm.chat(screenpipe_core::ChatRequest {
- messages: vec![screenpipe_core::ChatMessage {
- role: "user".to_string(),
- content: "What is the meaning of life?".to_string(),
- }],
- temperature: None,
- top_k: None,
- top_p: None,
- max_completion_tokens: None,
- seed: None,
- stream: false,
- })?;
-
- println!("{:?}", res.choices[0].message.content);
-
- println!("{:?}", res.usage.tokens_per_second);
- Ok(())
-}
-
-#[cfg(not(feature = "llm"))]
-fn main() -> Result<()> {
- println!("LLM feature is not enabled");
- Ok(())
-}
diff --git a/crates/screenpipe-core/examples/mistral.rs b/crates/screenpipe-core/examples/mistral.rs
deleted file mode 100644
index fb0b3127a..000000000
--- a/crates/screenpipe-core/examples/mistral.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-use anyhow::Result;
-#[cfg(feature = "llm")]
-use screenpipe_core::mistral::MistralConfig;
-#[cfg(feature = "llm")]
-use screenpipe_core::stream_text;
-
-fn main() -> Result<()> {
- #[cfg(feature = "llm")]
- stream_text(MistralConfig::default(), |text| {
- println!("{}", text);
- Ok(())
- })?;
- Ok(())
-}
diff --git a/crates/screenpipe-core/examples/phi.rs b/crates/screenpipe-core/examples/phi.rs
deleted file mode 100644
index 1a4814b26..000000000
--- a/crates/screenpipe-core/examples/phi.rs
+++ /dev/null
@@ -1,50 +0,0 @@
-#[cfg(feature = "llm")]
-use anyhow::Result;
-#[cfg(feature = "llm")]
-fn main() -> Result<()> {
- use candle::Device;
- use screenpipe_core::{generate_text_streaming, load_llama_model};
- use std::env;
-
- let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
-
- let (mut model, tokenizer) = load_llama_model(&device)?;
-
- // use input from stdin if available
- let prompt = env::args()
- .nth(1)
- .unwrap_or_else(|| "explain quantum computing in simple terms:".to_string());
- let max_tokens = 50;
- let temperature = 0.7;
- let top_p = 0.9;
- let seed = 42;
- let repeat_penalty = 1.;
- let repeat_last_n = 64;
-
- let callback = |text: String| {
- print!("{}", text);
- Ok(())
- };
-
- generate_text_streaming(
- &mut model,
- &tokenizer,
- &prompt,
- max_tokens,
- temperature,
- repeat_penalty,
- repeat_last_n,
- seed,
- top_p,
- &device,
- callback,
- )?;
-
- println!("\n");
- Ok(())
-}
-
-#[cfg(not(feature = "llm"))]
-fn main() {
- println!("LLM is not enabled");
-}
diff --git a/crates/screenpipe-core/src/google.rs b/crates/screenpipe-core/src/google.rs
deleted file mode 100644
index 5c75dff4d..000000000
--- a/crates/screenpipe-core/src/google.rs
+++ /dev/null
@@ -1,330 +0,0 @@
-#![allow(clippy::all, dead_code, unused_variables, unused_mut)]
-mod google_module {
-
- use anyhow::{Error as E, Result};
- use candle::{DType, Device, Tensor};
- use candle_nn::VarBuilder;
- use candle_transformers::generation::{LogitsProcessor, Sampling};
- use candle_transformers::models::gemma::Model as Model1;
- use candle_transformers::models::gemma2::Model as Model2;
- use hf_hub::api::sync::ApiBuilder;
- use hf_hub::{Repo, RepoType};
- use tokenizers::Tokenizer;
-
- use crate::{hub_load_safetensors, TokenOutputStream};
-
- enum Model {
- V1(Model1),
- V2(Model2),
- }
-
- struct TextGeneration {
- model: Model,
- device: Device,
- tokenizer: TokenOutputStream,
- logits_processor: LogitsProcessor,
- repeat_penalty: f32,
- repeat_last_n: usize,
- }
-
- impl TextGeneration {
- #[allow(clippy::too_many_arguments)]
- fn new(
- model: Model,
- tokenizer: Tokenizer,
- seed: u64,
- temp: Option<f64>,
- top_p: Option<f64>,
- top_k: Option<usize>,
- repeat_penalty: f32,
- repeat_last_n: usize,
- device: &Device,
- ) -> Self {
- let logits_processor = {
- let temperature = temp.unwrap_or(0.);
- let sampling = if temperature <= 0. {
- Sampling::ArgMax
- } else {
- match (top_k, top_p) {
- (None, None) => Sampling::All { temperature },
- (Some(k), None) => Sampling::TopK { k, temperature },
- (None, Some(p)) => Sampling::TopP { p, temperature },
- (Some(k), Some(p)) => Sampling::TopKThenTopP { k, p, temperature },
- }
- };
- LogitsProcessor::from_sampling(seed, sampling)
- };
-
- Self {
- model,
- tokenizer: TokenOutputStream::new(tokenizer),
- logits_processor,
- repeat_penalty,
- repeat_last_n,
- device: device.clone(),
- }
- }
-
- fn run(&mut self, prompt: &str, sample_len: usize) -> Result<()> {
- use std::io::Write;
- self.tokenizer.clear();
- let mut tokens = self
- .tokenizer
- .tokenizer()
- .encode(prompt, true)
- .map_err(E::msg)?
- .get_ids()
- .to_vec();
- for &t in tokens.iter() {
- if let Some(t) = self.tokenizer.next_token(t)? {
- print!("{t}")
- }
- }
- std::io::stdout().flush()?;
-
- let mut generated_tokens = 0usize;
- let eos_token = match self.tokenizer.get_token("</s>") {
- Some(token) => token,
- None => anyhow::bail!("cannot find the </s> token"),
- };
- let start_gen = std::time::Instant::now();
- for index in 0..sample_len {
- let context_size = if index > 0 { 1 } else { tokens.len() };
- let start_pos = tokens.len().saturating_sub(context_size);
- let ctxt = &tokens[start_pos..];
- let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?;
- let logits = match &mut self.model {
- Model::V1(m) => m.forward(&input, start_pos)?,
- Model::V2(m) => m.forward(&input, start_pos)?,
- };
- let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?;
- let logits = if self.repeat_penalty == 1. {
- logits
- } else {
- let start_at = tokens.len().saturating_sub(self.repeat_last_n);
- candle_transformers::utils::apply_repeat_penalty(
- &logits,
- self.repeat_penalty,
- &tokens[start_at..],
- )?
- };
-
- let next_token = self.logits_processor.sample(&logits)?;
- tokens.push(next_token);
- generated_tokens += 1;
- if next_token == eos_token {
- break;
- }
- if let Some(t) = self.tokenizer.next_token(next_token)? {
- print!("{t}");
- std::io::stdout().flush()?;
- }
- }
- let dt = start_gen.elapsed();
- if let Some(rest) = self.tokenizer.decode_rest().map_err(E::msg)? {
- print!("{rest}");
- }
- std::io::stdout().flush()?;
- println!(
- "\n{generated_tokens} tokens generated ({:.2} token/s)",
- generated_tokens as f64 / dt.as_secs_f64(),
- );
- Ok(())
- }
- }
-
- #[derive(Clone, Debug, Copy, PartialEq, Eq)]
- enum Which {
- Base2B,
- Base7B,
- Instruct2B,
- Instruct7B,
- InstructV1_1_2B,
- InstructV1_1_7B,
- CodeBase2B,
- CodeBase7B,
- CodeInstruct2B,
- CodeInstruct7B,
- BaseV2_2B,
- InstructV2_2B,
- BaseV2_9B,
- InstructV2_9B,
- }
-
- impl Which {
- fn as_str(&self) -> &'static str {
- match self {
- Which::Base2B => "2b",
- Which::Base7B => "7b",
- Which::Instruct2B => "2b-it",
- Which::Instruct7B => "7b-it",
- Which::InstructV1_1_2B => "1.1-2b-it",
- Which::InstructV1_1_7B => "1.1-7b-it",
- Which::CodeBase2B => "code-2b",
- Which::CodeBase7B => "code-7b",
- Which::CodeInstruct2B => "code-2b-it",
- Which::CodeInstruct7B => "code-7b-it",
- Which::BaseV2_2B => "2-2b",
- Which::InstructV2_2B => "2-2b-it",
- Which::BaseV2_9B => "2-9b",
- Which::InstructV2_9B => "2-9b-it",
- }
- }
- }
-
- impl ToString for Which {
- fn to_string(&self) -> String {
- self.as_str().to_string()
- }
- }
-
- #[derive(Debug)]
- pub struct GoogleConfig {
- cpu: bool,
- tracing: bool,
- use_flash_attn: bool,
- prompt: String,
- temperature: Option<f64>,
- top_p: Option<f64>,
- top_k: Option<usize>,
- seed: u64,
- sample_len: usize,
- which: Which,
- model_id: Option<String>,
- revision: String,
- tokenizer_file: Option<String>,
- config_file: Option<String>,
- weight_files: Option<String>,
- repeat_penalty: f32,
- repeat_last_n: usize,
- force_dmmv: bool,
- }
-
- impl Default for GoogleConfig {
- fn default() -> Self {
- Self {
- cpu: false,
- tracing: false,
- use_flash_attn: false,
- prompt: String::new(),
- temperature: Some(0.8),
- top_p: Some(0.95),
- top_k: None,
- seed: 299792458,
- sample_len: 100,
- which: Which::InstructV2_2B,
- model_id: None,
- revision: "main".to_string(),
- tokenizer_file: None,
- config_file: None,
- weight_files: None,
- repeat_penalty: 1.1,
- repeat_last_n: 64,
- force_dmmv: false,
- }
- }
- }
-
- pub fn google_stream_text<F>(args: GoogleConfig, mut callback: F) -> Result<()>
- where
- F: FnMut(String) -> Result<()>,
- {
- #[cfg(feature = "cuda")]
- candle::quantized::cuda::set_force_dmmv(args.force_dmmv);
-
- println!(
- "avx: {}, neon: {}, simd128: {}, f16c: {}",
- candle::utils::with_avx(),
- candle::utils::with_neon(),
- candle::utils::with_simd128(),
- candle::utils::with_f16c()
- );
- println!(
- "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}",
- args.temperature.unwrap_or(0.),
- args.repeat_penalty,
- args.repeat_last_n
- );
-
- let start = std::time::Instant::now();
- let api = ApiBuilder::new()
- .with_token(Some("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".to_string()))
- .build()?;
- let model_id = match args.model_id {
- Some(model_id) => model_id,
- None => {
- let name = match args.which {
- Which::Base2B => "google/gemma-2b",
- Which::Base7B => "google/gemma-7b",
- Which::Instruct2B => "google/gemma-2b-it",
- Which::Instruct7B => "google/gemma-7b-it",
- Which::InstructV1_1_2B => "google/gemma-1.1-2b-it",
- Which::InstructV1_1_7B => "google/gemma-1.1-7b-it",
- Which::CodeBase2B => "google/codegemma-2b",
- Which::CodeBase7B => "google/codegemma-7b",
- Which::CodeInstruct2B => "google/codegemma-2b-it",
- Which::CodeInstruct7B => "google/codegemma-7b-it",
- Which::BaseV2_2B => "google/gemma-2-2b",
- Which::InstructV2_2B => "google/gemma-2-2b-it",
- Which::BaseV2_9B => "google/gemma-2-9b",
- Which::InstructV2_9B => "google/gemma-2-9b-it",
- };
- name.to_string()
- }
- };
- let repo = api.repo(Repo::with_revision(
- model_id,
- RepoType::Model,
- args.revision,
- ));
- let tokenizer_filename = match args.tokenizer_file {
- Some(file) => std::path::PathBuf::from(file),
- None => repo.get("tokenizer.json")?,
- };
- let filenames = match args.weight_files {
- Some(files) => files
- .split(',')
- .map(std::path::PathBuf::from)
- .collect::<Vec<_>>(),
- None => hub_load_safetensors(&repo, "model.safetensors.index.json")?,
- };
- println!("retrieved the files in {:?}", start.elapsed());
- let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?;
-
- let start = std::time::Instant::now();
- let config = match args.config_file {
- Some(config_file) => serde_json::from_slice(&std::fs::read(config_file)?)?,
- None => {
- let config_file = repo.get("config.json")?;
- serde_json::from_slice(&std::fs::read(config_file)?)?
- }
- };
- let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
-
- let (model, device) = {
- let vb =
- unsafe { VarBuilder::from_mmaped_safetensors(&filenames, DType::F32, &device)? };
- let model = Model2::new(args.use_flash_attn, &config, vb)?;
- (Model::V2(model), device)
- };
-
- println!("loaded the model in {:?}", start.elapsed());
-
- let mut pipeline = TextGeneration::new(
- model,
- tokenizer,
- args.seed,
- args.temperature,
- args.top_p,
- args.top_k,
- args.repeat_penalty,
- args.repeat_last_n,
- &device,
- );
- pipeline.run(&args.prompt, args.sample_len)?;
- Ok(())
- }
-}
-
-#[cfg(feature = "llm")]
-pub use google_module::*;
diff --git a/crates/screenpipe-core/src/lib.rs b/crates/screenpipe-core/src/lib.rs
index 776f1e7d5..438c4d152 100644
--- a/crates/screenpipe-core/src/lib.rs
+++ b/crates/screenpipe-core/src/lib.rs
@@ -5,26 +5,6 @@ pub mod agents;
pub mod ffmpeg;
pub mod pipes;
pub use ffmpeg::find_ffmpeg_path;
-#[cfg(feature = "llm")]
-pub mod llm;
-#[cfg(feature = "llm")]
-pub use llm::*;
-#[cfg(feature = "llm")]
-pub mod phi;
-#[cfg(feature = "llm")]
-pub use phi::*;
-#[cfg(feature = "llm")]
-pub mod google;
-#[cfg(feature = "llm")]
-pub use google::*;
-#[cfg(feature = "llm")]
-pub mod mistral;
-#[cfg(feature = "llm")]
-pub use mistral::*;
-#[cfg(feature = "llm")]
-pub mod llama;
-#[cfg(feature = "llm")]
-pub use llama::*;
mod language;
#[cfg(feature = "security")]
diff --git a/crates/screenpipe-core/src/llama.rs b/crates/screenpipe-core/src/llama.rs
deleted file mode 100644
index 8f61e9e83..000000000
--- a/crates/screenpipe-core/src/llama.rs
+++ /dev/null
@@ -1,298 +0,0 @@
-#[cfg(feature = "llm")]
-mod llm_module {
- use anyhow::{Error as E, Result};
- use std::path::PathBuf;
-
- use candle::{DType, Device, Tensor};
- use candle_nn::VarBuilder;
- use candle_transformers::generation::{LogitsProcessor, Sampling};
- use hf_hub::{Repo, RepoType};
-
- use candle_transformers::models::llama as model;
- use log::debug;
- use model::LlamaConfig;
- use tokenizers::Tokenizer;
-
- use crate::{
- ChatMessage, ChatRequest, ChatResponse, ChatResponseChoice, ChatResponseUsage, Model,
- TokenOutputStream,
- };
-
- const EOS_TOKEN: &str = "</s>";
-
- #[derive(Clone, Debug, Copy, PartialEq, Eq)]
- enum Which {
- V32_1bInstruct,
- }
-
- impl Which {
- fn model_id(&self) -> String {
- match self {
- // Which::V1 => "Narsil/amall-7b".to_string(),
- // Which::V2 => "meta-llama/Llama-2-7b-hf".to_string(),
- // Which::V3 => "meta-llama/Meta-Llama-3-8B".to_string(),
- // Which::V3Instruct => "meta-llama/Meta-Llama-3-8B-Instruct".to_string(),
- // Which::V31 => "meta-llama/Meta-Llama-3.1-8B".to_string(),
- // Which::V31Instruct => "meta-llama/Meta-Llama-3.1-8B-Instruct".to_string(),
- // Which::V32_1b => "meta-llama/Llama-3.2-1B".to_string(),
- Which::V32_1bInstruct => "meta-llama/Llama-3.2-1B-Instruct".to_string(),
- // Which::V32_3b => "meta-llama/Llama-3.2-3B".to_string(),
- // Which::V32_3bInstruct => "meta-llama/Llama-3.2-3B-Instruct".to_string(),
- // Which::Solar10_7B => "upstage/SOLAR-10.7B-v1.0".to_string(),
- // Which::TinyLlama1_1BChat => "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(),
- }
- }
- }
-
- #[derive(Debug, Clone)]
- pub struct LlamaInitConfig {
- /// The temperature used to generate samples.
- temperature: f64,
-
- /// Nucleus sampling probability cutoff.
- top_p: Option<f64>,
-
- /// Only sample among the top K samples.
- top_k: Option<usize>,
-
- /// The seed to use when generating random samples.
- seed: u64,
-
- /// The length of the sample to generate (in tokens).
- sample_len: usize,
-
- /// Use different dtype than f16
- dtype: DType,
-
- /// The model size to use.
- which: Which,
-
- use_flash_attn: bool,
-
- /// Penalty to be applied for repeating tokens, 1. means no penalty.
- repeat_penalty: f32,
-
- /// The context size to consider for the repeat penalty.
- repeat_last_n: usize,
- }
-
- impl Default for LlamaInitConfig {
- fn default() -> Self {
- Self {
- use_flash_attn: false,
- temperature: 0.8,
- top_p: None,
- top_k: None,
- seed: 299792458,
- sample_len: 1000,
- which: Which::V32_1bInstruct,
- repeat_penalty: 1.1,
- repeat_last_n: 64,
- dtype: DType::F16,
- }
- }
- }
-
- pub struct Llama {
- llama_config: candle_transformers::models::llama::Config,
- // device: Device,
- filenames: Vec<PathBuf>,
- tokenizer: Tokenizer,
- // llama: model::Llama,
- eos_token_id: Option<model::LlamaEosToks>,
- config: LlamaInitConfig,
- }
-
- impl Llama {
- pub fn new() -> Result<Self> {
- // let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
- let init_config = LlamaInitConfig::default();
- let api = hf_hub::api::sync::Api::new()?;
-
- let hf_api = api.repo(Repo::with_revision(
- init_config.which.model_id(),
- RepoType::Model,
- "main".to_string(),
- ));
-
- let tokenizer_filename = hf_api.get("tokenizer.json")?;
- let config_filename = hf_api.get("config.json")?;
- let config: LlamaConfig = serde_json::from_slice(&std::fs::read(config_filename)?)?;
- let llama_config = config.into_config(init_config.use_flash_attn);
-
- let filenames = vec![hf_api.get("model.safetensors")?];
- // let vb = unsafe {
- // VarBuilder::from_mmaped_safetensors(&filenames, init_config.dtype, &device)?
- // };
-
- let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?;
-
- // let llama = model::Llama::load(vb, &llama_config)?;
-
- let eos_token_id = tokenizer
- .token_to_id(EOS_TOKEN)
- .map(model::LlamaEosToks::Single);
- Ok(Self {
- llama_config,
- // device,
- filenames,
- eos_token_id,
- tokenizer,
- // llama,
- config: init_config,
- })
- }
-
- // TODO Implement
- pub fn llama_stream_text(&self) -> Result<()> {
- Ok(())
- }
- }
-
- impl Model for Llama {
- fn chat(&self, request: ChatRequest) -> Result<ChatResponse> {
- let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
-
- let vb = unsafe {
- VarBuilder::from_mmaped_safetensors(
- &self.filenames.clone(),
- self.config.dtype,
- &device,
- )?
- };
-
- let llama = model::Llama::load(vb, &self.llama_config)?;
-
- let sample_len = request
- .max_completion_tokens
- .unwrap_or(self.config.sample_len);
- let prompt = request
- .messages
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<&str>>()
- .join("\n\n");
- let mut cache =
- model::Cache::new(true, self.config.dtype, &self.llama_config, &device)?;
-
- let temperature = request.temperature.unwrap_or(self.config.temperature);
- let top_k = request.top_k.or(self.config.top_k);
- let top_p = request.top_p.or(self.config.top_p);
- let seed = request.seed.unwrap_or(self.config.seed);
- let sampling = if temperature <= 0. {
- Sampling::ArgMax
- } else {
- match (top_k, top_p) {
- (None, None) => Sampling::All { temperature },
- (Some(k), None) => Sampling::TopK { k, temperature },
- (None, Some(p)) => Sampling::TopP { p, temperature },
- (Some(k), Some(p)) => Sampling::TopKThenTopP { k, p, temperature },
- }
- };
- let mut logits_processor = LogitsProcessor::from_sampling(seed, sampling);
-
- let prompt = prompt.as_str();
- let mut tokens = self
- .tokenizer
- .encode(prompt, true)
- .map_err(E::msg)?
- .get_ids()
- .to_vec();
-
- let prompt_tokens = tokens.len();
-
- let mut tokenizer = TokenOutputStream::new(self.tokenizer.clone());
-
- let mut output = String::new();
- let mut start_gen = std::time::Instant::now();
-
- let mut index_pos = 0;
- let mut token_generated = 0;
-
- for index in 0..sample_len {
- let (context_size, context_index) = if cache.use_kv_cache && index > 0 {
- (1, index_pos)
- } else {
- (tokens.len(), 0)
- };
- if index == 1 {
- start_gen = std::time::Instant::now()
- }
- let ctxt = &tokens[tokens.len().saturating_sub(context_size)..];
- let input = Tensor::new(ctxt, &device)?.unsqueeze(0)?;
- let logits = llama.forward(&input, context_index, &mut cache)?;
- let logits = logits.squeeze(0)?;
- let logits = if self.config.repeat_penalty == 1. {
- logits
- } else {
- let start_at = tokens.len().saturating_sub(self.config.repeat_last_n);
- candle_transformers::utils::apply_repeat_penalty(
- &logits,
- self.config.repeat_penalty,
- &tokens[start_at..],
- )?
- };
- index_pos += ctxt.len();
-
- let next_token = logits_processor.sample(&logits)?;
- token_generated += 1;
- tokens.push(next_token);
-
- // match eos_token_id {
- match self.eos_token_id {
- Some(model::LlamaEosToks::Single(eos_tok_id)) if next_token == eos_tok_id => {
- break;
- }
- Some(model::LlamaEosToks::Multiple(ref eos_ids))
- if eos_ids.contains(&next_token) =>
- {
- break;
- }
- _ => (),
- }
- if let Some(t) = tokenizer.next_token(next_token)? {
- output.push_str(&t);
- }
- }
- if let Some(rest) = tokenizer.decode_rest().map_err(E::msg)? {
- output.push_str(&rest);
- }
- let dt = start_gen.elapsed();
- tokenizer.clear();
-
- let tokens_per_second = (token_generated - 1) as f64 / dt.as_secs_f64();
-
- debug!(
- "Llama: {} tokens generated ({} token/s)",
- token_generated, tokens_per_second
- );
-
- Ok(ChatResponse {
- id: "123".to_string(),
- object: "chat.completion".to_string(),
- created: 1,
- model: "ministral-3".to_string(),
- system_fingerprint: "".to_string(),
- choices: vec![ChatResponseChoice {
- index: 0,
- message: ChatMessage {
- role: "assistant".to_string(),
- content: output,
- },
- logprobs: None,
- finish_reason: "stop".to_string(),
- }],
- usage: ChatResponseUsage {
- prompt_tokens: prompt_tokens as i64,
- completion_tokens: token_generated,
- total_tokens: token_generated,
- completion_tokens_details: serde_json::Value::Null,
- tokens_per_second,
- },
- })
- }
- }
-}
-// Optionally, you can re-export the module contents if needed
-#[cfg(feature = "llm")]
-pub use llm_module::*;
diff --git a/crates/screenpipe-core/src/llm.rs b/crates/screenpipe-core/src/llm.rs
deleted file mode 100644
index 54df0fa98..000000000
--- a/crates/screenpipe-core/src/llm.rs
+++ /dev/null
@@ -1,166 +0,0 @@
-#[cfg(feature = "llm")]
-mod llm_module {
-
- use serde::{Deserialize, Serialize};
-
- use crate::Llama;
- #[derive(Deserialize, Serialize, Clone, Debug)]
- pub struct ChatMessage {
- pub role: String,
- pub content: String,
- }
-
- #[derive(Deserialize, Serialize)]
- pub struct ChatResponseChoice {
- pub index: i64,
- pub message: ChatMessage,
- pub logprobs: Option<serde_json::Value>,
- pub finish_reason: String,
- }
-
- #[derive(Deserialize, Serialize)]
- pub struct ChatResponseUsage {
- pub prompt_tokens: i64,
- pub completion_tokens: i64,
- pub total_tokens: i64,
- pub completion_tokens_details: serde_json::Value,
- pub tokens_per_second: f64,
- }
-
- #[derive(Serialize, Deserialize)]
- pub struct ChatResponse {
- pub id: String,
- pub object: String,
- pub created: i64,
- pub model: String,
- pub system_fingerprint: String,
- pub choices: Vec<ChatResponseChoice>,
- pub usage: ChatResponseUsage,
- }
-
- #[derive(Deserialize, Clone, Debug)]
- pub struct ChatRequest {
- pub messages: Vec<ChatMessage>,
- #[serde(default)]
- pub stream: bool,
- pub max_completion_tokens: Option<usize>,
- pub temperature: Option<f64>,
- pub top_p: Option<f64>,
- pub top_k: Option<usize>,
- pub seed: Option<u64>,
- }
-
- pub trait Model {
- fn chat(&self, request: ChatRequest) -> anyhow::Result<ChatResponse>;
- }
-
- pub struct LLM {
- model: Llama,
- }
-
- pub enum ModelName {
- Llama,
- }
-
- impl LLM {
- pub fn new(model_name: ModelName) -> anyhow::Result<Self> {
- let model = match model_name {
- ModelName::Llama => Llama::new()?,
- };
-
- Ok(Self { model })
- }
-
- pub fn chat(&self, request: ChatRequest) -> anyhow::Result<ChatResponse> {
- self.model.chat(request)
- }
- }
- /// This is a wrapper around a tokenizer to ensure that tokens can be returned to the user in a
- /// streaming way rather than having to wait for the full decoding.
- pub struct TokenOutputStream {
- tokenizer: tokenizers::Tokenizer,
- tokens: Vec<u32>,
- prev_index: usize,
- current_index: usize,
- }
-
- impl TokenOutputStream {
- pub fn new(tokenizer: tokenizers::Tokenizer) -> Self {
- Self {
- tokenizer,
- tokens: Vec::new(),
- prev_index: 0,
- current_index: 0,
- }
- }
-
- pub fn into_inner(self) -> tokenizers::Tokenizer {
- self.tokenizer
- }
-
- fn decode(&self, tokens: &[u32]) -> anyhow::Result<String> {
- match self.tokenizer.decode(tokens, true) {
- Ok(str) => Ok(str),
- Err(err) => anyhow::bail!("cannot decode: {err}"),
- }
- }
-
- // https://github.com/huggingface/text-generation-inference/blob/5ba53d44a18983a4de32d122f4cb46f4a17d9ef6/server/text_generation_server/models/model.py#L68
- pub fn next_token(&mut self, token: u32) -> anyhow::Result<Option<String>> {
- let prev_text = if self.tokens.is_empty() {
- String::new()
- } else {
- let tokens = &self.tokens[self.prev_index..self.current_index];
- self.decode(tokens)?
- };
- self.tokens.push(token);
- let text = self.decode(&self.tokens[self.prev_index..])?;
- if text.len() > prev_text.len() && text.chars().last().unwrap().is_alphanumeric() {
- let text = text.split_at(prev_text.len());
- self.prev_index = self.current_index;
- self.current_index = self.tokens.len();
- Ok(Some(text.1.to_string()))
- } else {
- Ok(None)
- }
- }
-
- pub fn decode_rest(&self) -> anyhow::Result<Option<String>> {
- let prev_text = if self.tokens.is_empty() {
- String::new()
- } else {
- let tokens = &self.tokens[self.prev_index..self.current_index];
- self.decode(tokens)?
- };
- let text = self.decode(&self.tokens[self.prev_index..])?;
- if text.len() > prev_text.len() {
- let text = text.split_at(prev_text.len());
- Ok(Some(text.1.to_string()))
- } else {
- Ok(None)
- }
- }
-
- pub fn decode_all(&self) -> anyhow::Result<String> {
- self.decode(&self.tokens)
- }
-
- pub fn get_token(&self, token_s: &str) -> Option<u32> {
- self.tokenizer.get_vocab(true).get(token_s).copied()
- }
-
- pub fn tokenizer(&self) -> &tokenizers::Tokenizer {
- &self.tokenizer
- }
-
- pub fn clear(&mut self) {
- self.tokens.clear();
- self.prev_index = 0;
- self.current_index = 0;
- }
- }
-}
-
-// Optionally, you can re-export the module contents if needed
-#[cfg(feature = "llm")]
-pub use llm_module::*;
diff --git a/crates/screenpipe-core/src/mistral.rs b/crates/screenpipe-core/src/mistral.rs
deleted file mode 100644
index 683e1d222..000000000
--- a/crates/screenpipe-core/src/mistral.rs
+++ /dev/null
@@ -1,369 +0,0 @@
-#![allow(clippy::all, dead_code, unused_variables, unused_mut)]
-#[cfg(feature = "llm")]
-mod llm_module {
-
- use anyhow::{Error as E, Result};
-
- use candle_transformers::models::mistral::{Config, Model as Mistral};
- use candle_transformers::models::quantized_mistral::Model as QMistral;
-
- use candle::{DType, Device, Tensor};
- use candle_nn::VarBuilder;
- use candle_transformers::generation::{LogitsProcessor, Sampling};
- use hf_hub::api::sync::ApiBuilder;
- use hf_hub::{Repo, RepoType};
- use tokenizers::Tokenizer;
-
- use crate::{hub_load_safetensors, TokenOutputStream};
-
- enum Model {
- Mistral(Mistral),
- Quantized(QMistral),
- }
-
- struct TextGeneration {
- model: Model,
- device: Device,
- tokenizer: TokenOutputStream,
- logits_processor: LogitsProcessor,
- repeat_penalty: f32,
- repeat_last_n: usize,
- }
-
- impl TextGeneration {
- #[allow(clippy::too_many_arguments)]
- fn new(
- model: Model,
- tokenizer: Tokenizer,
- seed: u64,
- temp: Option<f64>,
- top_p: Option<f64>,
- top_k: Option<usize>,
- repeat_penalty: f32,
- repeat_last_n: usize,
- device: &Device,
- ) -> Self {
- let logits_processor = {
- let temperature = temp.unwrap_or(0.);
- let sampling = if temperature <= 0. {
- Sampling::ArgMax
- } else {
- match (top_k, top_p) {
- (None, None) => Sampling::All { temperature },
- (Some(k), None) => Sampling::TopK { k, temperature },
- (None, Some(p)) => Sampling::TopP { p, temperature },
- (Some(k), Some(p)) => Sampling::TopKThenTopP { k, p, temperature },
- }
- };
- LogitsProcessor::from_sampling(seed, sampling)
- };
-
- Self {
- model,
- tokenizer: TokenOutputStream::new(tokenizer),
- logits_processor,
- repeat_penalty,
- repeat_last_n,
- device: device.clone(),
- }
- }
-
- fn run(&mut self, prompt: &str, sample_len: usize) -> Result<()> {
- use std::io::Write;
- self.tokenizer.clear();
- let mut tokens = self
- .tokenizer
- .tokenizer()
- .encode(prompt, true)
- .map_err(E::msg)?
- .get_ids()
- .to_vec();
- for &t in tokens.iter() {
- if let Some(t) = self.tokenizer.next_token(t)? {
- print!("{t}")
- }
- }
- std::io::stdout().flush()?;
-
- let mut generated_tokens = 0usize;
- let eos_token = match self.tokenizer.get_token("</s>") {
- Some(token) => token,
- None => anyhow::bail!("cannot find the </s> token"),
- };
- let start_gen = std::time::Instant::now();
- for index in 0..sample_len {
- let context_size = if index > 0 { 1 } else { tokens.len() };
- let start_pos = tokens.len().saturating_sub(context_size);
- let ctxt = &tokens[start_pos..];
- let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?;
- let logits = match &mut self.model {
- Model::Mistral(m) => m.forward(&input, start_pos)?,
- Model::Quantized(m) => m.forward(&input, start_pos)?,
- };
- let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?;
- let logits = if self.repeat_penalty == 1. {
- logits
- } else {
- let start_at = tokens.len().saturating_sub(self.repeat_last_n);
- candle_transformers::utils::apply_repeat_penalty(
- &logits,
- self.repeat_penalty,
- &tokens[start_at..],
- )?
- };
-
- let next_token = self.logits_processor.sample(&logits)?;
- tokens.push(next_token);
- generated_tokens += 1;
- if next_token == eos_token {
- break;
- }
- if let Some(t) = self.tokenizer.next_token(next_token)? {
- print!("{t}");
- std::io::stdout().flush()?;
- }
- }
- let dt = start_gen.elapsed();
- if let Some(rest) = self.tokenizer.decode_rest().map_err(E::msg)? {
- print!("{rest}");
- }
- std::io::stdout().flush()?;
- println!(
- "\n{generated_tokens} tokens generated ({:.2} token/s)",
- generated_tokens as f64 / dt.as_secs_f64(),
- );
- Ok(())
- }
- }
-
- #[derive(Clone, Debug, Copy, PartialEq, Eq)]
- enum Which {
- Mistral7bV01,
- Mistral7bV02,
- Mistral7bInstructV01,
- Mistral7bInstructV02,
- Mistral7bInstructV03,
- Mathstral7bV01,
- MistralNemo2407,
- MistralNemoInstruct2407,
- }
-
- impl Which {
- fn as_str(&self) -> &'static str {
- match self {
- Which::Mistral7bV01 => "7b-v0.1",
- Which::Mistral7bV02 => "7b-v0.2",
- Which::Mistral7bInstructV01 => "7b-instruct-v0.1",
- Which::Mistral7bInstructV02 => "7b-instruct-v0.2",
- Which::Mistral7bInstructV03 => "7b-instruct-v0.3",
- Which::Mathstral7bV01 => "7b-maths-v0.1",
- Which::MistralNemo2407 => "nemo-2407",
- Which::MistralNemoInstruct2407 => "nemo-instruct-2407",
- }
- }
- }
-
- impl ToString for Which {
- fn to_string(&self) -> String {
- self.as_str().to_string()
- }
- }
-
- #[derive(Debug)]
- pub struct MistralConfig {
- use_flash_attn: bool,
-
- prompt: String,
-
- /// The temperature used to generate samples.
- temperature: Option<f64>,
-
- /// Nucleus sampling probability cutoff.
- top_p: Option<f64>,
-
- /// Only sample among the top K samples.
- top_k: Option<usize>,
-
- /// The seed to use when generating random samples.
- seed: u64,
-
- /// The length of the sample to generate (in tokens).
- sample_len: usize,
-
- /// The model size to use.
- which: Which,
-
- model_id: Option<String>,
-
- revision: String,
-
- tokenizer_file: Option<String>,
-
- config_file: Option<String>,
-
- weight_files: Option<String>,
-
- quantized: bool,
-
- /// Penalty to be applied for repeating tokens, 1. means no penalty.
- repeat_penalty: f32,
-
- /// The context size to consider for the repeat penalty.
- repeat_last_n: usize,
-
- /// Use the slower dmmv cuda kernel.
- force_dmmv: bool,
- }
-
- impl Default for MistralConfig {
- fn default() -> Self {
- Self {
- use_flash_attn: false,
- prompt: String::new(),
- temperature: Some(0.8),
- top_p: Some(0.95),
- top_k: None,
- seed: 299792458,
- sample_len: 100,
- which: Which::Mistral7bInstructV03,
- model_id: None,
- revision: "main".to_string(),
- tokenizer_file: None,
- config_file: None,
- weight_files: None,
- quantized: false,
- repeat_penalty: 1.1,
- repeat_last_n: 64,
- force_dmmv: false,
- }
- }
- }
-
- pub fn stream_text<F>(args: MistralConfig, mut callback: F) -> Result<()>
- where
- F: FnMut(String) -> Result<()>,
- {
- #[cfg(feature = "cuda")]
- candle::quantized::cuda::set_force_dmmv(args.force_dmmv);
-
- println!(
- "avx: {}, neon: {}, simd128: {}, f16c: {}",
- candle::utils::with_avx(),
- candle::utils::with_neon(),
- candle::utils::with_simd128(),
- candle::utils::with_f16c()
- );
- println!(
- "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}",
- args.temperature.unwrap_or(0.),
- args.repeat_penalty,
- args.repeat_last_n
- );
-
- let start = std::time::Instant::now();
- let api = ApiBuilder::new()
- // ! hardcoded louis token dont CARE
- .with_token(Some("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".to_string()))
- .build()?;
- let model_id = match args.model_id {
- Some(model_id) => model_id,
- None => {
- if args.quantized {
- if args.which != Which::Mistral7bV01 {
- anyhow::bail!("only 7b-v0.1 is available as a quantized model for now")
- }
- "lmz/candle-mistral".to_string()
- } else {
- let name = match args.which {
- // https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3
- Which::Mistral7bV01 => "mistralai/Mistral-7B-v0.1",
- Which::Mistral7bV02 => "mistralai/Mistral-7B-v0.2",
- Which::Mistral7bInstructV01 => "mistralai/Mistral-7B-Instruct-v0.1",
- Which::Mistral7bInstructV02 => "mistralai/Mistral-7B-Instruct-v0.2",
- Which::Mistral7bInstructV03 => "mistralai/Mistral-7B-Instruct-v0.3",
- Which::Mathstral7bV01 => "mistralai/mathstral-7B-v0.1",
- Which::MistralNemo2407 => "mistralai/Mistral-Nemo-Base-2407",
- Which::MistralNemoInstruct2407 => "mistralai/Mistral-Nemo-Instruct-2407",
- };
- name.to_string()
- }
- }
- };
- let repo = api.repo(Repo::with_revision(
- model_id,
- RepoType::Model,
- args.revision,
- ));
- let tokenizer_filename = match args.tokenizer_file {
- Some(file) => std::path::PathBuf::from(file),
- None => repo.get("tokenizer.json")?,
- };
- let filenames = match args.weight_files {
- Some(files) => files
- .split(',')
- .map(std::path::PathBuf::from)
- .collect::<Vec<_>>(),
- None => {
- if args.quantized {
- vec![repo.get("model-q4k.gguf")?]
- } else {
- hub_load_safetensors(&repo, "model.safetensors.index.json")?
- }
- }
- };
- println!("retrieved the files in {:?}", start.elapsed());
- let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?;
-
- let start = std::time::Instant::now();
- let config = match args.config_file {
- Some(config_file) => serde_json::from_slice(&std::fs::read(config_file)?)?,
- None => {
- if args.quantized {
- Config::config_7b_v0_1(args.use_flash_attn)
- } else {
- let config_file = repo.get("config.json")?;
- serde_json::from_slice(&std::fs::read(config_file)?)?
- }
- }
- };
- let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));
-
- let (model, device) = if args.quantized {
- let filename = &filenames[0];
- let vb = candle_transformers::quantized_var_builder::VarBuilder::from_gguf(
- filename, &device,
- )?;
- let model = QMistral::new(&config, vb)?;
- (Model::Quantized(model), device)
- } else {
- let dtype = if device.is_cuda() {
- DType::BF16
- } else {
- DType::F32
- };
- let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? };
- let model = Mistral::new(&config, vb)?;
- (Model::Mistral(model), device)
- };
-
- println!("loaded the model in {:?}", start.elapsed());
-
- let mut pipeline = TextGeneration::new(
- model,
- tokenizer,
- args.seed,
- args.temperature,
- args.top_p,
- args.top_k,
- args.repeat_penalty,
- args.repeat_last_n,
- &device,
- );
- pipeline.run(&args.prompt, args.sample_len)?;
- Ok(())
- }
-}
-
-// Optionally, you can re-export the module contents if needed
-#[cfg(feature = "llm")]
-pub use llm_module::*;
diff --git a/crates/screenpipe-core/src/phi.rs b/crates/screenpipe-core/src/phi.rs
deleted file mode 100755
index 463296801..000000000
--- a/crates/screenpipe-core/src/phi.rs
+++ /dev/null
@@ -1,138 +0,0 @@
-#[cfg(feature = "llm")]
-mod llm_module {
- use anyhow::Result;
- use candle::{DType, Device, Tensor};
- use candle_nn::VarBuilder;
- use candle_transformers::{
- generation::LogitsProcessor,
- models::phi3::{Config as Phi3Config, Model as Phi3},
- };
-
- use hf_hub::{api::sync::Api, Repo, RepoType};
- use tokenizers::Tokenizer;
-
- /// Loads the safetensors files for a model from the hub based on a json index file.
- pub fn hub_load_safetensors(
- repo: &hf_hub::api::sync::ApiRepo,
- json_file: &str,
- ) -> Result<Vec<std::path::PathBuf>> {
- let json_file = repo.get(json_file).map_err(candle::Error::wrap)?;
- let json_file = std::fs::File::open(json_file)?;
- let json: serde_json::Value =
- serde_json::from_reader(&json_file).map_err(candle::Error::wrap)?;
- let weight_map = match json.get("weight_map") {
- None => anyhow::bail!("no weight map in {json_file:?}"),
- Some(serde_json::Value::Object(map)) => map,
- Some(_) => anyhow::bail!("weight map in {json_file:?} is not a map"),
- };
- let mut safetensors_files = std::collections::HashSet::new();
- for value in weight_map.values() {
- if let Some(file) = value.as_str() {
- safetensors_files.insert(file.to_string());
- }
- }
- let safetensors_files = safetensors_files
- .iter()
- .map(|v| repo.get(v).map_err(anyhow::Error::from))
- .collect::<Result<Vec<_>, anyhow::Error>>()?;
- Ok(safetensors_files)
- }
-
- pub fn load_llama_model(device: &Device) -> Result<(Phi3, Tokenizer)> {
- let api = Api::new()?;
- let model_id = "microsoft/Phi-3-mini-4k-instruct";
- let revision = "main";
-
- let api = api.repo(Repo::with_revision(
- model_id.to_string(),
- RepoType::Model,
- revision.to_string(),
- ));
- let tokenizer_filename = api.get("tokenizer.json")?;
- let config_filename = api.get("config.json")?;
-
- let config: Phi3Config = serde_json::from_slice(&std::fs::read(config_filename)?)?;
-
- // https://github.com/huggingface/candle/blob/ddafc61055601002622778b7762c15bd60057c1f/candle-examples/examples/phi/main.rs#L364
- // let dtype = DType::BF16;
- let dtype = DType::F32;
-
- let filenames = hub_load_safetensors(&api, "model.safetensors.index.json")?;
- let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, device)? };
-
- let model = Phi3::new(&config, vb)?;
- let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(anyhow::Error::msg)?;
-
- Ok((model, tokenizer))
- }
-
- #[allow(clippy::too_many_arguments)]
- pub fn generate_text_streaming<F>(
- model: &mut Phi3,
- tokenizer: &Tokenizer,
- prompt: &str,
- max_tokens: usize,
- temperature: f64,
- repeat_penalty: f32,
- repeat_last_n: usize,
- seed: u64,
- top_p: f64,
- device: &Device,
- mut callback: F,
- ) -> Result<()>
- where
- F: FnMut(String) -> Result<()>,
- {
- let mut logits_processor = LogitsProcessor::new(seed, Some(temperature), Some(top_p));
- let tokens = tokenizer.encode(prompt, true).unwrap();
- if tokens.is_empty() {
- anyhow::bail!("empty prompt")
- }
- let mut tokens = tokens.get_ids().to_vec();
- let eos_token = match tokenizer.token_to_id("<|endoftext|>") {
- Some(token) => token,
- None => anyhow::bail!("cannot find the endoftext token"),
- };
-
- for pos in 0..max_tokens {
- let context_size = if pos > 0 { 1 } else { tokens.len() };
- let ctxt = &tokens[tokens.len().saturating_sub(context_size)..];
- let input = Tensor::new(ctxt, device)?.unsqueeze(0)?;
- let logits = model.forward(&input, pos)?;
- let logits = logits.squeeze(0)?.to_dtype(DType::F32)?;
-
- let logits = if repeat_penalty == 1. {
- logits
- } else {
- let start_at = tokens.len().saturating_sub(repeat_last_n);
- candle_transformers::utils::apply_repeat_penalty(
- &logits,
- repeat_penalty,
- &tokens[start_at..],
- )?
- };
-
- // Remove the batch dimension if it exists
- let logits = if logits.dims().len() > 1 {
- logits.squeeze(0)?
- } else {
- logits
- };
-
- let next_token = logits_processor.sample(&logits)?;
- tokens.push(next_token);
- if next_token == eos_token {
- break;
- }
- if let Ok(t) = tokenizer.decode(&[next_token], false) {
- callback(t)?;
- }
- }
-
- Ok(())
- }
-}
-
-// Optionally, you can re-export the module contents if needed
-#[cfg(feature = "llm")]
-pub use llm_module::*;
diff --git a/crates/screenpipe-server/Cargo.toml b/crates/screenpipe-server/Cargo.toml
index d214843e3..42cbfe79c 100644
--- a/crates/screenpipe-server/Cargo.toml
+++ b/crates/screenpipe-server/Cargo.toml
@@ -88,10 +88,6 @@ reqwest = { workspace = true }
# Concurrency
crossbeam = { workspace = true }
-# filtering
-ndarray = "0.15.6"
-rust-stemmers = "1.2.0"
-
# base64
base64 = "0.22.1"
@@ -140,7 +136,6 @@ metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]
cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]
mkl = ["candle/mkl", "candle-nn/mkl", "candle-transformers/mkl"]
vulkan = ["screenpipe-audio/vulkan"]
-llm = []
experimental = []
debug-console = ["console-subscriber"]
adaptive-fps = ["screenpipe-vision/adaptive-fps"]
diff --git a/crates/screenpipe-server/src/bin/screenpipe-server.rs b/crates/screenpipe-server/src/bin/screenpipe-server.rs
index d5a613c05..11b1ff39c 100644
--- a/crates/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/crates/screenpipe-server/src/bin/screenpipe-server.rs
@@ -341,7 +341,6 @@ async fn main() -> anyhow::Result<()> {
"video_chunk_duration".into(),
json!(cli.video_chunk_duration),
);
- map.insert("enable_llm".into(), json!(cli.enable_llm));
map.insert("enable_frame_cache".into(), json!(cli.enable_frame_cache));
map.insert(
"capture_unfocused_windows".into(),
@@ -519,7 +518,6 @@ async fn main() -> anyhow::Result<()> {
cli.auto_destruct_pid = record_args.auto_destruct_pid;
cli.vad_sensitivity = record_args.vad_sensitivity.clone();
cli.disable_telemetry = record_args.disable_telemetry;
- cli.enable_llm = record_args.enable_llm;
cli.enable_frame_cache = record_args.enable_frame_cache;
cli.capture_unfocused_windows = record_args.capture_unfocused_windows;
cli.video_quality = record_args.video_quality.clone();
@@ -862,21 +860,6 @@ async fn main() -> anyhow::Result<()> {
};
let local_data_dir_clone_2 = local_data_dir_clone.clone();
- #[cfg(feature = "llm")]
- debug!("LLM initializing");
-
- #[cfg(feature = "llm")]
- let _llm = {
- match cli.enable_llm {
- true => Some(screenpipe_core::LLM::new(
- screenpipe_core::ModelName::Llama,
- )?),
- false => None,
- }
- };
-
- #[cfg(feature = "llm")]
- debug!("LLM initialized");
let mut server = SCServer::new(
db_server,
@@ -993,8 +976,6 @@ async fn main() -> anyhow::Result<()> {
"│ telemetry │ {:<34} │",
!cli.disable_telemetry
);
- println!("│ local llm │ {:<34} │", cli.enable_llm);
-
println!("│ use pii removal │ {:<34} │", cli.use_pii_removal);
println!("│ use all monitors │ {:<34} │", cli.use_all_monitors);
println!(
diff --git a/crates/screenpipe-server/src/chunking.rs b/crates/screenpipe-server/src/chunking.rs
deleted file mode 100644
index a98012afc..000000000
--- a/crates/screenpipe-server/src/chunking.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-use anyhow::Result;
-use candle::{DType, Device, Tensor};
-use candle_nn::{Module, VarBuilder};
-use candle_transformers::models::jina_bert::{BertModel, Config};
-use hf_hub::{api::sync::Api, Repo, RepoType};
-use tokenizers::Tokenizer;
-
-pub async fn text_chunking_by_similarity(text: &str) -> Result<Vec<String>> {
- let device =
- Device::new_metal(0).unwrap_or_else(|_| Device::new_cuda(0).unwrap_or(Device::Cpu));
- let repo = Repo::with_revision(
- "jinaai/jina-embeddings-v2-base-en".to_string(),
- RepoType::Model,
- "main".to_string(),
- );
- let api = Api::new()?;
- let model_file = api.repo(repo.clone()).get("model.safetensors")?;
- let tokenizer_file = api.repo(repo).get("tokenizer.json")?;
-
- let tokenizer = Tokenizer::from_file(tokenizer_file).map_err(anyhow::Error::msg)?;
- let config = Config::v2_base();
- let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[model_file], DType::F32, &device)? };
- let model = BertModel::new(vb, &config)?;
-
- let sentences: Vec<&str> = text
- .split(&['.', '!', '?', '\n'][..])
- .filter(|s| !s.trim().is_empty())
- .map(|s| s.trim())
- .collect();
-
- let mut chunks = Vec::new();
- let mut current_chunk = String::new();
- let mut previous_embedding: Option<Tensor> = None;
- let similarity_threshold = 0.8;
- let max_chunk_length = 300;
-
- for sentence in sentences {
- let tokens = tokenizer
- .encode(sentence, true)
- .map_err(anyhow::Error::msg)?;
- let token_ids = Tensor::new(tokens.get_ids(), &device)?;
- let embeddings = model.forward(&token_ids.unsqueeze(0)?)?;
- let sentence_embedding = embeddings.mean(1)?;
-
- let should_split = if let Some(prev_emb) = &previous_embedding {
- let similarity = cosine_similarity(&sentence_embedding, prev_emb)?;
- similarity < similarity_threshold
- || current_chunk.len() + sentence.len() > max_chunk_length
- } else {
- false
- };
-
- if should_split && !current_chunk.is_empty() {
- chunks.push(current_chunk);
- current_chunk = String::new();
- }
-
- if !current_chunk.is_empty() {
- current_chunk.push(' ');
- }
- current_chunk.push_str(sentence);
- previous_embedding = Some(sentence_embedding);
- }
-
- if !current_chunk.is_empty() {
- chunks.push(current_chunk);
- }
-
- Ok(chunks)
-}
-
-pub fn text_chunking_simple(text: &str) -> Result<Vec<String>> {
- let mut chunks = Vec::new();
- let lines: Vec<&str> = text.split('\n').collect();
-
- if lines.len() > 1 {
- // Chunk by newlines
- chunks = lines.into_iter().map(String::from).collect();
- } else {
- // Chunk by fixed character count with overlap
- let chunk_size = 200;
- let overlap = 30;
- let chars: Vec<char> = text.chars().collect();
- let mut start = 0;
-
- while start < chars.len() {
- let end = (start + chunk_size).min(chars.len());
- chunks.push(chars[start..end].iter().collect());
- start = if end == chars.len() {
- end
- } else {
- end - overlap
- };
- }
- }
-
- Ok(chunks)
-}
-
-fn cosine_similarity(a: &Tensor, b: &Tensor) -> Result<f32> {
- let a = a.flatten_all()?;
- let b = b.flatten_all()?;
- let dot_product = (&a * &b)?.sum_all()?;
- let norm_a = a.sqr()?.sum_all()?.sqrt()?;
- let norm_b = b.sqr()?.sum_all()?.sqrt()?;
- let similarity = dot_product.to_scalar::<f32>()?
- / (norm_a.to_scalar::<f32>()? * norm_b.to_scalar::<f32>()?);
- Ok(similarity)
-}
diff --git a/crates/screenpipe-server/src/cli.rs b/crates/screenpipe-server/src/cli.rs
index f81fea33d..2a21a2c03 100644
--- a/crates/screenpipe-server/src/cli.rs
+++ b/crates/screenpipe-server/src/cli.rs
@@ -263,9 +263,6 @@ pub struct Cli {
#[arg(long, default_value_t = false)]
pub disable_telemetry: bool,
- #[arg(long, default_value_t = false)]
- pub enable_llm: bool,
-
#[arg(long, default_value_t = true)]
pub enable_frame_cache: bool,
@@ -505,10 +502,6 @@ pub struct RecordArgs {
#[arg(long, default_value_t = false)]
pub disable_telemetry: bool,
- /// Enable Local LLM API
- #[arg(long, default_value_t = false)]
- pub enable_llm: bool,
-
/// Enable frame cache (makes timeline UI available)
#[arg(long, default_value_t = true)]
pub enable_frame_cache: bool,
@@ -578,7 +571,6 @@ impl RecordArgs {
auto_destruct_pid: cli.auto_destruct_pid,
vad_sensitivity: cli.vad_sensitivity.clone(),
disable_telemetry: cli.disable_telemetry,
- enable_llm: cli.enable_llm,
enable_frame_cache: cli.enable_frame_cache,
capture_unfocused_windows: cli.capture_unfocused_windows,
video_quality: cli.video_quality.clone(),
diff --git a/crates/screenpipe-server/src/filtering.rs b/crates/screenpipe-server/src/filtering.rs
deleted file mode 100644
index 66ccd0796..000000000
--- a/crates/screenpipe-server/src/filtering.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-use ndarray::{Array2, Axis};
-use rust_stemmers::{Algorithm, Stemmer};
-use sqlx::{query_as, sqlite::SqlitePool};
-use std::collections::{HashMap, HashSet};
-use std::error::Error;
-use tracing::debug;
-
-fn keep_least_similar(chunks: &[String], percentage: f64) -> Vec<usize> {
- if chunks.is_empty() {
- return vec![];
- }
-
- let en_stemmer = Stemmer::create(Algorithm::English);
- let mut term_freq = HashMap::new();
- let mut doc_freq = HashMap::new();
-
- // Calculate TF-IDF
- for (doc_id, chunk) in chunks.iter().enumerate() {
- let words: Vec<_> = chunk
- .split_whitespace()
- .map(|word| en_stemmer.stem(word).to_string())
- .collect();
-
- for word in words.iter() {
- *term_freq.entry((doc_id, word.clone())).or_insert(0) += 1;
- doc_freq
- .entry(word.clone())
- .or_insert_with(HashSet::new)
- .insert(doc_id);
- }
- }
-
- let n_docs = chunks.len();
- let mut tfidf_matrix = Array2::zeros((n_docs, n_docs));
-
- for ((doc_id, term), count) in term_freq.iter() {
- let df = doc_freq[term].len() as f64;
- let idf = (n_docs as f64 / df).ln();
- let tfidf = (*count as f64) * idf;
- tfidf_matrix[[*doc_id, *doc_id]] += tfidf * tfidf;
- }
-
- // Calculate cosine similarity
- let norms = tfidf_matrix.diag().mapv(f64::sqrt);
- for i in 0..n_docs {
- for j in 0..n_docs {
- if norms[i] != 0.0 && norms[j] != 0.0 {
- tfidf_matrix[[i, j]] /= norms[i] * norms[j];
- }
- }
- }
-
- let avg_similarities: Vec<_> = match tfidf_matrix.mean_axis(Axis(1)) {
- Some(mean) => mean.into_iter().enumerate().collect(),
- None => return vec![],
- };
-
- let mut sorted_similarities = avg_similarities.clone();
- sorted_similarities.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
-
- let keep_count = (percentage * n_docs as f64) as usize;
- sorted_similarities
- .into_iter()
- .take(keep_count)
- .map(|(i, _)| i)
- .collect()
-}
-
-fn word_count(text: &str) -> usize {
- text.split_whitespace().count()
-}
-
-pub async fn filter_texts(
- timestamp: &str,
- memory_source: &str,
- pool: &SqlitePool,
-) -> Result<String, Box<dyn Error + Send + Sync>> {
- let texts: Vec<String> = query_as(
- "
- SELECT cti.text
- FROM chunked_text_index cti
- JOIN chunked_text_entries cte ON cti.text_id = cte.text_id
- WHERE cte.timestamp > ? AND cte.source = ?
- GROUP BY cti.text_id
- ORDER BY MAX(cte.timestamp) DESC
- ",
- )
- .bind(timestamp)
- .bind(memory_source)
- .fetch_all(pool)
- .await?
- .into_iter()
- .map(|row: (String,)| row.0)
- .collect();
-
- let initial_text_count = texts.len();
- let initial_word_count: usize = texts.iter().map(|text| word_count(text)).sum();
- debug!(
- "Initial: {} texts, {} words",
- initial_text_count, initial_word_count
- );
-
- if texts.is_empty() {
- return Ok("".to_string());
- }
-
- let kept_indices = keep_least_similar(&texts, 0.1);
- let kept_texts: Vec<_> = kept_indices.iter().map(|&i| &texts[i]).collect();
-
- let final_text_count = kept_texts.len();
- let final_word_count: usize = kept_texts.iter().map(|&text| word_count(text)).sum();
- debug!(
- "Kept: {} texts, {} words",
- final_text_count, final_word_count
- );
-
- let output = kept_texts
- .iter()
- .map(|s| s.as_str())
- .collect::<Vec<&str>>()
- .join("\n");
-
- Ok(output)
-}
diff --git a/crates/screenpipe-server/src/lib.rs b/crates/screenpipe-server/src/lib.rs
index 871343886..3f2a79a17 100644
--- a/crates/screenpipe-server/src/lib.rs
+++ b/crates/screenpipe-server/src/lib.rs
@@ -6,13 +6,11 @@ pub mod analytics;
#[cfg(feature = "apple-intelligence")]
mod apple_intelligence_api;
mod auto_destruct;
-pub mod chunking;
pub mod cli;
pub mod cli_pipe;
pub mod cli_status;
pub mod cloud_search;
pub mod core;
-pub mod filtering;
pub mod pipes_api;
mod resource_monitor;
diff --git a/crates/screenpipe-server/tests/chunking_test.rs b/crates/screenpipe-server/tests/chunking_test.rs
deleted file mode 100644
index 81e8f6a0d..000000000
--- a/crates/screenpipe-server/tests/chunking_test.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use screenpipe_server::chunking::text_chunking_simple;
-
-#[test]
-fn test_text_chunking_with_chinese_characters() {
- let chinese_text = "謝謝大家".repeat(100); // Repeat 100 times to ensure we exceed chunk size
- let result = text_chunking_simple(&chinese_text);
-
- assert!(
- result.is_ok(),
- "Function should not panic with Chinese characters"
- );
-
- let chunks = result.unwrap();
- assert!(!chunks.is_empty(), "Should produce at least one chunk");
-
- for chunk in chunks {
- assert!(!chunk.is_empty(), "Each chunk should contain text");
- assert!(
- chunk.chars().all(|c| c == '謝' || c == '大' || c == '家'),
- "Chunks should only contain expected characters"
- );
- }
-}